Debian Codegraph @

plugins/core/Standard/qFacets/src/qFacets.cpp

raw
1 //##########################################################################
2 //# #
3 //# CLOUDCOMPARE PLUGIN: qFacets #
4 //# #
5 //# This program is free software; you can redistribute it and/or modify #
6 //# it under the terms of the GNU General Public License as published by #
7 //# the Free Software Foundation; version 2 or later of the License. #
8 //# #
9 //# This program is distributed in the hope that it will be useful, #
10 //# but WITHOUT ANY WARRANTY; without even the implied warranty of #
11 //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
12 //# GNU General Public License for more details. #
13 //# #
14 //# COPYRIGHT: Thomas Dewez, BRGM #
15 //# #
16 //##########################################################################
17
18 #include "qFacets.h"
19
20 //Local
21 #include "facetsClassifier.h"
22 #include "classificationParamsDlg.h"
23 #include "facetsExportDlg.h"
24 #include "stereogramDlg.h"
25 #include "kdTreeForFacetExtraction.h"
26 #include "fastMarchingForFacetExtraction.h"
27 #include "disclaimerDialog.h"
28
29 //Qt
30 #include <QtGui>
31 #include <QInputDialog>
32 #include <QElapsedTimer>
33 #include <QSettings>
34 #include <QFileInfo>
35 #include <QMessageBox>
36
37 //CCCoreLib
38 #include <Neighbourhood.h>
39
40 //qCC_db
41 #include <ccFileUtils.h>
42 #include <ccHObjectCaster.h>
43 #include <ccMesh.h>
44 #include <ccProgressDialog.h>
45 #include <ccScalarField.h>
46 #include <ccOctree.h> //for ComputeAverageNorm
47 #include <ShpDBFFields.h>
48
49 //qCC_io
50 #include <ShpFilter.h>
51
52
53 //semi-persistent dialog values
54 static unsigned s_octreeLevel = 8;
55 static bool s_fmUseRetroProjectionError = false;
56
57 static unsigned s_minPointsPerFacet = 10;
58 static double s_errorMaxPerFacet = 0.2;
59 static int s_errorMeasureType = 3; //max dist @ 99 %
60 static double s_maxEdgeLength = 1.0;
61
62 static double s_kdTreeFusionMaxAngle_deg = 20.0;
63 static double s_kdTreeFusionMaxRelativeDistance = 1.0;
64
65 static double s_classifAngleStep = 30.0;
66 static double s_classifMaxDist = 1.0;
67
68 static double s_stereogramAngleStep = 30.0;
69 static double s_stereogramResolution_deg = 5.0;
70 static ccPointCloud* s_lastCloud = nullptr;
71
72
73 qFacets::qFacets(QObject* parent)
74 : QObject(parent)
75 , ccStdPluginInterface( ":/CC/plugin/qFacets/info.json" )
76 , m_doFuseKdTreeCells(nullptr)
77 , m_fastMarchingExtraction(nullptr)
78 , m_doExportFacets(nullptr)
79 , m_doExportFacetsInfo(nullptr)
80 , m_doClassifyFacetsByAngle(nullptr)
81 , m_doShowStereogram(nullptr)
82 , m_stereogramDialog(nullptr)
83 {
84 }
85
86 QList<QAction *> qFacets::getActions()
87 {
88 //actions
89 if (!m_doFuseKdTreeCells)
90 {
91 m_doFuseKdTreeCells = new QAction("Extract facets (Kd-tree)", this);
92 m_doFuseKdTreeCells->setToolTip("Detect planar facets by fusing Kd-tree cells");
93 m_doFuseKdTreeCells->setIcon(QIcon(QString::fromUtf8(":/CC/plugin/qFacets/images/extractKD.png")));
94 //connect signal
95 connect(m_doFuseKdTreeCells, &QAction::triggered, this, &qFacets::fuseKdTreeCells);
96 }
97
98 if (!m_fastMarchingExtraction)
99 {
100 m_fastMarchingExtraction = new QAction("Extract facets (Fast Marching)", this);
101 m_fastMarchingExtraction->setToolTip("Detect planar facets with Fast Marching");
102 m_fastMarchingExtraction->setIcon(QIcon(QString::fromUtf8(":/CC/plugin/qFacets/images/extractFM.png")));
103 //connect signal
104 connect(m_fastMarchingExtraction, &QAction::triggered, this, &qFacets::extractFacetsWithFM);
105 }
106
107 if (!m_doExportFacets)
108 {
109 m_doExportFacets = new QAction("Export facets (SHP)", this);
110 m_doExportFacets->setToolTip("Exports one or several facets to a shapefile");
111 m_doExportFacets->setIcon(QIcon(QString::fromUtf8(":/CC/plugin/qFacets/images/shpFile.png")));
112 //connect signal
113 connect(m_doExportFacets, &QAction::triggered, this, &qFacets::exportFacets);
114 }
115
116 if (!m_doExportFacetsInfo)
117 {
118 m_doExportFacetsInfo = new QAction("Export facets info (CSV)", this);
119 m_doExportFacetsInfo->setToolTip("Exports various information on a set of facets (ASCII CSV file)");
120 m_doExportFacetsInfo->setIcon(QIcon(QString::fromUtf8(":/CC/plugin/qFacets/images/csvFile.png")));
121 //connect signal
122 connect(m_doExportFacetsInfo, &QAction::triggered, this, &qFacets::exportFacetsInfo);
123 }
124
125 if (!m_doClassifyFacetsByAngle)
126 {
127 m_doClassifyFacetsByAngle = new QAction("Classify facets by orientation", this);
128 m_doClassifyFacetsByAngle->setToolTip("Classifies facets based on their orienation (dip & dip direction)");
129 m_doClassifyFacetsByAngle->setIcon(QIcon(QString::fromUtf8(":/CC/plugin/qFacets/images/classifIcon.png")));
130 //connect signal
131 connect(m_doClassifyFacetsByAngle, &QAction::triggered, this, [=] () {
132 classifyFacetsByAngle();
133 } );
134 }
135
136 if (!m_doShowStereogram)
137 {
138 m_doShowStereogram = new QAction("Show stereogram", this);
139 m_doShowStereogram->setToolTip("Computes and displays a stereogram (+ interactive filtering)");
140 m_doShowStereogram->setIcon(QIcon(QString::fromUtf8(":/CC/plugin/qFacets/images/stereogram.png")));
141 //connect signal
142 connect(m_doShowStereogram, &QAction::triggered, this, &qFacets::showStereogram);
143 }
144
145 return QList<QAction *>{
146 m_doFuseKdTreeCells,
147 m_fastMarchingExtraction,
148 m_doExportFacets,
149 m_doExportFacetsInfo,
150 m_doClassifyFacetsByAngle,
151 m_doShowStereogram,
152 };
153 }
154
155 void qFacets::onNewSelection(const ccHObject::Container& selectedEntities)
156 {
157 if (m_doFuseKdTreeCells)
158 m_doFuseKdTreeCells->setEnabled(selectedEntities.size() == 1 && selectedEntities.back()->isA(CC_TYPES::POINT_CLOUD));
159 if (m_fastMarchingExtraction)
160 m_fastMarchingExtraction->setEnabled(selectedEntities.size() == 1 && selectedEntities.back()->isA(CC_TYPES::POINT_CLOUD));
161 if (m_doExportFacets)
162 m_doExportFacets->setEnabled(selectedEntities.size() != 0);
163 if (m_doExportFacetsInfo)
164 m_doExportFacetsInfo->setEnabled(selectedEntities.size() != 0);
165 if (m_doClassifyFacetsByAngle)
166 m_doClassifyFacetsByAngle->setEnabled(selectedEntities.size() == 1 && selectedEntities.back()->isA(CC_TYPES::HIERARCHY_OBJECT));
167 if (m_doShowStereogram)
168 m_doShowStereogram->setEnabled(selectedEntities.size() == 1 && (selectedEntities.back()->isA(CC_TYPES::HIERARCHY_OBJECT) || selectedEntities.back()->isA(CC_TYPES::POINT_CLOUD)));
169 }
170
171 void qFacets::extractFacetsWithFM()
172 {
173 extractFacets(CellsFusionDlg::ALGO_FAST_MARCHING);
174 }
175
176 void qFacets::fuseKdTreeCells()
177 {
178 extractFacets(CellsFusionDlg::ALGO_KD_TREE);
179 }
180
181 void qFacets::extractFacets(CellsFusionDlg::Algorithm algo)
182 {
183 //disclaimer accepted?
184 if (!ShowDisclaimer(m_app))
185 return;
186
187 assert(m_app);
188 if (!m_app)
189 return;
190
191 //we expect a unique cloud as input
192 const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();
193 ccPointCloud* pc = (m_app->haveOneSelection() ? ccHObjectCaster::ToPointCloud(selectedEntities.back()) : nullptr);
194 if (!pc)
195 {
196 m_app->dispToConsole("Select one and only one point cloud!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
197 return;
198 }
199
200 if (algo != CellsFusionDlg::ALGO_FAST_MARCHING && algo != CellsFusionDlg::ALGO_KD_TREE)
201 {
202 m_app->dispToConsole("Internal error: invalid algorithm type!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
203 return;
204 }
205
206 //first time: we compute the max edge length automatically
207 if (s_lastCloud != pc)
208 {
209 s_maxEdgeLength = static_cast<double>(pc->getOwnBB().getMinBoxDim()) / 50;
210 s_minPointsPerFacet = std::max<unsigned>(pc->size() / 100000, 10);
211 s_lastCloud = pc;
212 }
213
214 CellsFusionDlg fusionDlg(algo, m_app->getMainWindow());
215 if (algo == CellsFusionDlg::ALGO_FAST_MARCHING)
216 fusionDlg.octreeLevelSpinBox->setCloud(pc);
217
218 fusionDlg.octreeLevelSpinBox->setValue(s_octreeLevel);
219 fusionDlg.useRetroProjectionCheckBox->setChecked(s_fmUseRetroProjectionError);
220 fusionDlg.minPointsPerFacetSpinBox->setValue(s_minPointsPerFacet);
221 fusionDlg.errorMeasureComboBox->setCurrentIndex(s_errorMeasureType);
222 fusionDlg.maxRMSDoubleSpinBox->setValue(s_errorMaxPerFacet);
223 fusionDlg.maxAngleDoubleSpinBox->setValue(s_kdTreeFusionMaxAngle_deg);
224 fusionDlg.maxRelativeDistDoubleSpinBox->setValue(s_kdTreeFusionMaxRelativeDistance);
225 fusionDlg.maxEdgeLengthDoubleSpinBox->setValue(s_maxEdgeLength);
226 //"no normal" warning
227 fusionDlg.noNormalWarningLabel->setVisible(!pc->hasNormals());
228
229 if (!fusionDlg.exec())
230 return;
231
232 s_octreeLevel = fusionDlg.octreeLevelSpinBox->value();
233 s_fmUseRetroProjectionError = fusionDlg.useRetroProjectionCheckBox->isChecked();
234 s_minPointsPerFacet = fusionDlg.minPointsPerFacetSpinBox->value();
235 s_errorMeasureType = fusionDlg.errorMeasureComboBox->currentIndex();
236 s_errorMaxPerFacet = fusionDlg.maxRMSDoubleSpinBox->value();
237 s_kdTreeFusionMaxAngle_deg = fusionDlg.maxAngleDoubleSpinBox->value();
238 s_kdTreeFusionMaxRelativeDistance = fusionDlg.maxRelativeDistDoubleSpinBox->value();
239 s_maxEdgeLength = fusionDlg.maxEdgeLengthDoubleSpinBox->value();
240
241 //convert 'errorMeasureComboBox' index to enum
242 CCCoreLib::DistanceComputationTools::ERROR_MEASURES errorMeasure = CCCoreLib::DistanceComputationTools::RMS;
243 switch (s_errorMeasureType)
244 {
245 case 0:
246 errorMeasure = CCCoreLib::DistanceComputationTools::RMS;
247 break;
248 case 1:
249 errorMeasure = CCCoreLib::DistanceComputationTools::MAX_DIST_68_PERCENT;
250 break;
251 case 2:
252 errorMeasure = CCCoreLib::DistanceComputationTools::MAX_DIST_95_PERCENT;
253 break;
254 case 3:
255 errorMeasure = CCCoreLib::DistanceComputationTools::MAX_DIST_99_PERCENT;
256 break;
257 case 4:
258 errorMeasure = CCCoreLib::DistanceComputationTools::MAX_DIST;
259 break;
260 default:
261 assert(false);
262 break;
263 }
264
265 //create scalar field to host the fusion result
266 const char c_defaultSFName[] = "facet indexes";
267 int sfIdx = pc->getScalarFieldIndexByName(c_defaultSFName);
268 if (sfIdx < 0)
269 sfIdx = pc->addScalarField(c_defaultSFName);
270 if (sfIdx < 0)
271 {
272 m_app->dispToConsole("Couldn't allocate a new scalar field for computing fusion labels! Try to free some memory ...", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
273 return;
274 }
275 pc->setCurrentScalarField(sfIdx);
276
277 //computation
278 QElapsedTimer eTimer;
279 eTimer.start();
280 ccProgressDialog pDlg(true, m_app->getMainWindow());
281
282 bool success = true;
283 if (algo == CellsFusionDlg::ALGO_KD_TREE)
284 {
285 //we need a kd-tree
286 QElapsedTimer eTimer;
287 eTimer.start();
288 ccKdTree kdtree(pc);
289
290 if (kdtree.build(s_errorMaxPerFacet / 2, errorMeasure, s_minPointsPerFacet, 1000, &pDlg))
291 {
292 qint64 elapsedTime_ms = eTimer.elapsed();
293 m_app->dispToConsole(QString("[qFacets] Kd-tree construction timing: %1 s").arg(static_cast<double>(elapsedTime_ms) / 1.0e3, 0, 'f', 3), ccMainAppInterface::STD_CONSOLE_MESSAGE);
294
295 success = ccKdTreeForFacetExtraction::FuseCells(
296 &kdtree,
297 s_errorMaxPerFacet,
298 errorMeasure,
299 s_kdTreeFusionMaxAngle_deg,
300 static_cast<PointCoordinateType>(s_kdTreeFusionMaxRelativeDistance),
301 true,
302 &pDlg);
303 }
304 else
305 {
306 m_app->dispToConsole("Failed to build Kd-tree! (not enough memory?)", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
307 success = false;
308 }
309 }
310 else if (algo == CellsFusionDlg::ALGO_FAST_MARCHING)
311 {
312 int result = FastMarchingForFacetExtraction::ExtractPlanarFacets(
313 pc,
314 static_cast<unsigned char>(s_octreeLevel),
315 static_cast<ScalarType>(s_errorMaxPerFacet),
316 errorMeasure,
317 s_fmUseRetroProjectionError,
318 &pDlg,
319 pc->getOctree().data());
320
321 success = (result >= 0);
322 }
323
324 if (success)
325 {
326 pc->setCurrentScalarField(sfIdx); //for AutoSegmentationTools::extractConnectedComponents
327
328 CCCoreLib::ReferenceCloudContainer components;
329 if (!CCCoreLib::AutoSegmentationTools::extractConnectedComponents(pc, components))
330 {
331 m_app->dispToConsole("Failed to extract fused components! (not enough memory?)", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
332 }
333 else
334 {
335 //we remove the temporary scalar field (otherwise it will be copied to the sub-clouds!)
336 ccScalarField* indexSF = static_cast<ccScalarField*>(pc->getScalarField(sfIdx));
337 if (!indexSF)
338 {
339 assert(false);
340 return;
341 }
342 indexSF->link(); //to prevent deletion when calling deleteScalarField below
343 pc->deleteScalarField(sfIdx);
344 sfIdx = -1;
345
346 bool error = false;
347 ccHObject* group = createFacets(pc, components, s_minPointsPerFacet, s_maxEdgeLength, false, error);
348
349 if (group)
350 {
351 switch (algo)
352 {
353 case CellsFusionDlg::ALGO_KD_TREE:
354 group->setName(group->getName() + QString(" [Kd-tree][error < %1][angle < %2 deg.]").arg(s_errorMaxPerFacet).arg(s_kdTreeFusionMaxAngle_deg));
355 break;
356 case CellsFusionDlg::ALGO_FAST_MARCHING:
357 group->setName(group->getName() + QString(" [FM][level %2][error < %1]").arg(s_octreeLevel).arg(s_errorMaxPerFacet));
358 break;
359 default:
360 break;
361 }
362
363 unsigned count = group->getChildrenNumber();
364 m_app->dispToConsole(QString("[qFacets] %1 facet(s) where created from cloud '%2'").arg(count).arg(pc->getName()));
365
366 if (error)
367 {
368 m_app->dispToConsole("Error(s) occurred during the generation of facets! Result may be incomplete", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
369 }
370 else
371 {
372 //we put the scalar field back
373 sfIdx = pc->addScalarField(indexSF);
374 }
375
376 //pc->setEnabled(false);
377 m_app->addToDB(group);
378 group->prepareDisplayForRefresh();
379 }
380 else if (error)
381 {
382 m_app->dispToConsole("An error occurred during the generation of facets!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
383 }
384 else
385 {
386 m_app->dispToConsole("No facet remains! Check the parameters (min size, etc.)", ccMainAppInterface::WRN_CONSOLE_MESSAGE);
387 }
388 }
389 }
390 else
391 {
392 m_app->dispToConsole("An error occurred during the fusion process!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
393 }
394
395 if (sfIdx >= 0)
396 {
397 pc->getScalarField(sfIdx)->computeMinAndMax();
398 #ifdef _DEBUG
399 pc->setCurrentDisplayedScalarField(sfIdx);
400 pc->showSF(true);
401 #endif
402 }
403
404 //currently selected entities appearance may have changed!
405 m_app->redrawAll();
406 }
407
408 ccHObject* qFacets::createFacets( ccPointCloud* cloud,
409 CCCoreLib::ReferenceCloudContainer& components,
410 unsigned minPointsPerComponent,
411 double maxEdgeLength,
412 bool randomColors,
413 bool& error )
414 {
415 if (!cloud)
416 {
417 return nullptr;
418 }
419
420 //we create a new group to store all input CCs as 'facets'
421 ccHObject* ccGroup = new ccHObject(cloud->getName() + QString(" [facets]"));
422 ccGroup->setDisplay(cloud->getDisplay());
423 ccGroup->setVisible(true);
424
425 bool cloudHasNormal = cloud->hasNormals();
426
427 //number of input components
428 size_t componentCount = components.size();
429
430 //progress notification
431 ccProgressDialog pDlg(true, m_app->getMainWindow());
432 pDlg.setMethodTitle(QObject::tr("Facets creation"));
433 pDlg.setInfo(QObject::tr("Components: %1").arg(componentCount));
434 pDlg.setMaximum(static_cast<int>(componentCount));
435 pDlg.show();
436 QApplication::processEvents();
437
438 //for each component
439 error = false;
440 while (!components.empty())
441 {
442 CCCoreLib::ReferenceCloud* compIndexes = components.back();
443 components.pop_back();
444
445 //if it has enough points
446 if (compIndexes && compIndexes->size() >= minPointsPerComponent)
447 {
448 ccPointCloud* facetCloud = cloud->partialClone(compIndexes);
449 if (!facetCloud)
450 {
451 //not enough memory!
452 error = true;
453 delete facetCloud;
454 facetCloud = nullptr;
455 }
456 else
457 {
458 ccFacet* facet = ccFacet::Create(facetCloud, static_cast<PointCoordinateType>(maxEdgeLength), true);
459 if (facet)
460 {
461 QString facetName = QString("facet %1 (RMS=%2)").arg(ccGroup->getChildrenNumber()).arg(facet->getRMS());
462 facet->setName(facetName);
463 if (facet->getPolygon())
464 {
465 facet->getPolygon()->enableStippling(false);
466 facet->getPolygon()->showNormals(false);
467 }
468 if (facet->getContour())
469 {
470 facet->getContour()->copyGlobalShiftAndScale(*facetCloud);
471 }
472
473 //check the facet normal sign
474 if (cloudHasNormal)
475 {
476 CCVector3 N = ccOctree::ComputeAverageNorm(compIndexes, cloud);
477
478 if (N.dot(facet->getNormal()) < 0)
479 facet->invertNormal();
480 }
481
482 #ifdef _DEBUG
483 facet->showNormalVector(true);
484 #endif
485
486 //shall we colorize it with a random color?
487 ccColor::Rgb col;
488 ccColor::Rgb darkCol;
489 if (randomColors)
490 {
491 col = ccColor::Generator::Random();
492 assert(c_darkColorRatio <= 1.0);
493 darkCol.r = static_cast<ColorCompType>(static_cast<double>(col.r) * c_darkColorRatio);
494 darkCol.g = static_cast<ColorCompType>(static_cast<double>(col.g) * c_darkColorRatio);
495 darkCol.b = static_cast<ColorCompType>(static_cast<double>(col.b) * c_darkColorRatio);
496 }
497 else
498 {
499 //use normal-based HSV coloring
500 CCVector3 N = facet->getNormal();
501 PointCoordinateType dip = 0;
502 PointCoordinateType dipDir = 0;
503 ccNormalVectors::ConvertNormalToDipAndDipDir(N, dip, dipDir);
504 FacetsClassifier::GenerateSubfamilyColor(col, dip, dipDir, 0, 1, &darkCol);
505 }
506 facet->setColor(col);
507 if (facet->getContour())
508 {
509 facet->getContour()->setColor(darkCol);
510 facet->getContour()->setWidth(2);
511 }
512 ccGroup->addChild(facet);
513 }
514 }
515
516 delete compIndexes;
517 compIndexes = nullptr;
518 }
519
520 pDlg.setValue(static_cast<int>(componentCount - components.size()));
521 //QApplication::processEvents();
522 }
523
524 if (ccGroup->getChildrenNumber() == 0)
525 {
526 delete ccGroup;
527 ccGroup = nullptr;
528 }
529
530 return ccGroup;
531 }
532
533 void qFacets::getFacetsInCurrentSelection(FacetSet& facets) const
534 {
535 facets.clear();
536
537 //look for potential facets
538 for ( ccHObject *entity : m_app->getSelectedEntities() )
539 {
540 if (entity->isA(CC_TYPES::FACET))
541 {
542 ccFacet* facet = static_cast<ccFacet*>(entity);
543 if (facet->getContour()) //if no contour, we won't be able to save it?!
544 facets.insert(facet);
545 }
546 else //if (entity->isA(CC_TYPES::HIERARCHY_OBJECT)) //recursively tests group's children
547 {
548 ccHObject::Container childFacets;
549 entity->filterChildren(childFacets, true, CC_TYPES::FACET);
550
551 for ( ccHObject *childFacet : childFacets )
552 {
553 ccFacet* facet = static_cast<ccFacet*>(childFacet);
554 if (facet->getContour()) //if no contour, we won't be able to save it?!
555 {
556 facets.insert(facet);
557 }
558 }
559 }
560 }
561 }
562
563 //standard meta-data for the qFacets plugin
564 struct FacetMetaData
565 {
566 int facetIndex;
567 CCVector3 center;
568 CCVector3d globalCenter;
569 CCVector3 normal;
570 double surface;
571 int dip_deg;
572 int dipDir_deg;
573 double rms;
574 int familyIndex;
575 int subfamilyIndex;
576
577 //! Default constructor
578 FacetMetaData()
579 : facetIndex(-1)
580 , center(0, 0, 0)
581 , globalCenter(0, 0, 0)
582 , normal(0, 0, 1)
583 , surface(0.0)
584 , dip_deg(0)
585 , dipDir_deg(0)
586 , rms(0.0)
587 , familyIndex(0)
588 , subfamilyIndex(0)
589 {}
590 };
591
592 //helper: extract all meta-data information form a facet
593 void GetFacetMetaData(ccFacet* facet, FacetMetaData& data)
594 {
595 //try to get the facet index from the facet name!
596 {
597 QStringList tokens = facet->getName().split(" ", QString::SkipEmptyParts);
598 if (tokens.size() > 1 && tokens[0] == QString("facet"))
599 {
600 bool ok = true;
601 data.facetIndex = tokens[1].toInt(&ok);
602 if (!ok)
603 data.facetIndex = -1;
604 }
605 }
606
607 data.center = facet->getCenter();
608
609 ccHObject::Container clouds;
610 if (facet->filterChildren(clouds, false, CC_TYPES::POINT_CLOUD, true) != 0)
611 {
612 // any cloud directly under the facet should have the right Global Shift information now (either the 'countour points' or the 'origin points')
613 data.globalCenter = static_cast<const ccGenericPointCloud*>(clouds.front())->toGlobal3d(data.center);
614 }
615 else
616 {
617 // we couldn't find the vertices?!
618 assert(false);
619 data.globalCenter = data.center.toDouble();
620 }
621
622 data.normal = facet->getNormal();
623 data.surface = facet->getSurface();
624 data.rms = facet->getRMS();
625
626 //family and subfamily indexes
627 QVariant fi = facet->getMetaData(s_OriFamilyKey);
628 if (fi.isValid())
629 data.familyIndex = fi.toInt();
630 QVariant sfi = facet->getMetaData(s_OriSubFamilyKey);
631 if (sfi.isValid())
632 data.subfamilyIndex = sfi.toInt();
633
634 //compute dip direction & dip
635 {
636 PointCoordinateType dipDir = 0;
637 PointCoordinateType dip = 0;
638 ccNormalVectors::ConvertNormalToDipAndDipDir(data.normal, dip, dipDir);
639 data.dipDir_deg = static_cast<int>(dipDir);
640 data.dip_deg = static_cast<int>(dip);
641 }
642 }
643
644 //helper: computes a facet horizontal and vertical extensions
645 void ComputeFacetExtensions(CCVector3& N, ccPolyline* facetContour, double& horizExt, double& vertExt)
646 {
647 //horizontal and vertical extensions
648 horizExt = vertExt = 0;
649
650 CCCoreLib::GenericIndexedCloudPersist* vertCloud = facetContour->getAssociatedCloud();
651 if (vertCloud)
652 {
653 //oriRotMat.applyRotation(N); //DGM: oriRotMat is only for display!
654 //we assume that at this point the "up" direction is always (0,0,1)
655 CCVector3 Xf(1, 0, 0);
656 CCVector3 Yf(0, 1, 0);
657 //we get the horizontal vector on the plane
658 CCVector3 D = CCVector3(0, 0, 1).cross(N);
659 if ( CCCoreLib::GreaterThanSquareEpsilon( D.norm2() ) ) //otherwise the facet is horizontal!
660 {
661 Yf = D;
662 Yf.normalize();
663 Xf = N.cross(Yf);
664 }
665
666 const CCVector3* G = CCCoreLib::Neighbourhood(vertCloud).getGravityCenter();
667
668 ccBBox box;
669 for (unsigned i = 0; i < vertCloud->size(); ++i)
670 {
671 const CCVector3 P = *(vertCloud->getPoint(i)) - *G;
672 CCVector3 p(P.dot(Xf), P.dot(Yf), 0);
673 box.add(p);
674 }
675
676 vertExt = box.getDiagVec().x;
677 horizExt = box.getDiagVec().y;
678 }
679 }
680
681 void qFacets::exportFacets()
682 {
683 assert(m_app);
684 if (!m_app)
685 return;
686
687 //disclaimer accepted?
688 if (!ShowDisclaimer(m_app))
689 return;
690
691 //Retrive selected facets
692 FacetSet facets;
693 getFacetsInCurrentSelection(facets);
694
695 if (facets.empty())
696 {
697 m_app->dispToConsole("Couldn't find any facet in the current selection!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
698 return;
699 }
700 assert(!facets.empty());
701
702 FacetsExportDlg fDlg(FacetsExportDlg::SHAPE_FILE_IO, m_app->getMainWindow());
703
704 //persistent settings (default export path)
705 QSettings settings;
706 settings.beginGroup("qFacets");
707 QString facetsSavePath = settings.value("exportPath", ccFileUtils::defaultDocPath()).toString();
708 fDlg.destinationPathLineEdit->setText(facetsSavePath + QString("/facets.shp"));
709
710 if (!fDlg.exec())
711 return;
712
713 QString filename = fDlg.destinationPathLineEdit->text();
714
715 //save current export path to persistent settings
716 settings.setValue("exportPath", QFileInfo(filename).absolutePath());
717
718 if (QFile(filename).exists())
719 {
720 //if the file already exists, ask for confirmation!
721 if (QMessageBox::warning(m_app->getMainWindow(), "File already exists!", "File already exists! Are you sure you want to overwrite it?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
722 return;
723 }
724
725 //fields (shapefile) - WARNING names must not have more than 10 chars!
726 IntegerDBFField facetIndex("index");
727 DoubleDBFField facetSurface("surface");
728 DoubleDBFField facetRMS("rms");
729 IntegerDBFField facetDipDir("dip_dir");
730 IntegerDBFField facetDip("dip");
731 IntegerDBFField familyIndex("family_ind");
732 IntegerDBFField subfamilyIndex("subfam_ind");
733 DoubleDBFField3D facetNormal("normal");
734 DoubleDBFField3D facetBarycenter("center");
735 DoubleDBFField3D facetGlobalBarycenter("globalCenter");
736 DoubleDBFField horizExtension("horiz_ext");
737 DoubleDBFField vertExtension("vert_ext");
738 DoubleDBFField surfaceExtension("surf_ext");
739
740 size_t facetCount = facets.size();
741 assert(facetCount != 0);
742 try
743 {
744 facetIndex.values.reserve(facetCount);
745 facetSurface.values.reserve(facetCount);
746 facetRMS.values.reserve(facetCount);
747 facetDipDir.values.reserve(facetCount);
748 facetDip.values.reserve(facetCount);
749 familyIndex.values.reserve(facetCount);
750 subfamilyIndex.values.reserve(facetCount);
751 facetNormal.values.reserve(facetCount);
752 facetBarycenter.values.reserve(facetCount);
753 facetGlobalBarycenter.values.reserve(facetCount);
754 horizExtension.values.reserve(facetCount);
755 vertExtension.values.reserve(facetCount);
756 surfaceExtension.values.reserve(facetCount);
757 }
758 catch (const std::bad_alloc&)
759 {
760 m_app->dispToConsole("Not enough memory!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
761 return;
762 }
763
764 ccHObject toSave("facets");
765
766 //depending on the 'main orientation', the job is more or less easy ;)
767 bool useNativeOrientation = fDlg.nativeOriRadioButton->isChecked();
768 bool useGlobalOrientation = fDlg.verticalOriRadioButton->isChecked();
769 bool useCustomOrientation = fDlg.customOriRadioButton->isChecked();
770
771 //Default base
772 CCVector3 X(1, 0, 0);
773 CCVector3 Y(0, 1, 0);
774 CCVector3 Z(0, 0, 1);
775
776 //'vertical' orientation (potentially specified by the user)
777 if (!useNativeOrientation)
778 {
779 if (useCustomOrientation)
780 {
781 Z = CCVector3( static_cast<PointCoordinateType>(fDlg.nXLineEdit->text().toDouble()),
782 static_cast<PointCoordinateType>(fDlg.nYLineEdit->text().toDouble()),
783 static_cast<PointCoordinateType>(fDlg.nZLineEdit->text().toDouble()));
784 Z.normalize();
785 }
786 else if (useGlobalOrientation)
787 {
788 //we compute the mean orientation (weighted by each facet's surface)
789 CCVector3d Nsum(0, 0, 0);
790 for (FacetSet::iterator it = facets.begin(); it != facets.end(); ++it)
791 {
792 double surf = (*it)->getSurface();
793 CCVector3 N = (*it)->getNormal();
794 Nsum.x += static_cast<double>(N.x) * surf;
795 Nsum.y += static_cast<double>(N.y) * surf;
796 Nsum.z += static_cast<double>(N.z) * surf;
797 }
798 Nsum.normalize();
799
800 Z = CCVector3(static_cast<PointCoordinateType>(Nsum.x),
801 static_cast<PointCoordinateType>(Nsum.y),
802 static_cast<PointCoordinateType>(Nsum.z));
803 }
804
805 //update X & Y
806 CCVector3 D = Z.cross(CCVector3(0, 0, 1));
807 if ( CCCoreLib::GreaterThanSquareEpsilon( D.norm2() ) ) //otherwise the vertical dir hasn't changed!
808 {
809 X = -D;
810 X.normalize();
811 Y = Z.cross(X);
812 }
813 }
814
815 //we compute the mean center (weighted by each facet's surface)
816 CCVector3 C(0, 0, 0);
817 {
818 double weightSum = 0;
819 for (FacetSet::iterator it = facets.begin(); it != facets.end(); ++it)
820 {
821 double surf = (*it)->getSurface();
822 CCVector3 Ci = (*it)->getCenter();
823 C += Ci * static_cast<PointCoordinateType>(surf);
824 weightSum += surf;
825 }
826 if (weightSum)
827 C /= static_cast<PointCoordinateType>(weightSum);
828 }
829
830 //determine the 'global' orientation matrix
831 ccGLMatrix oriRotMat;
832 oriRotMat.toIdentity();
833 if (!useNativeOrientation)
834 {
835 oriRotMat.getColumn(0)[0] = static_cast<float>(X.x);
836 oriRotMat.getColumn(0)[1] = static_cast<float>(X.y);
837 oriRotMat.getColumn(0)[2] = static_cast<float>(X.z);
838 oriRotMat.getColumn(1)[0] = static_cast<float>(Y.x);
839 oriRotMat.getColumn(1)[1] = static_cast<float>(Y.y);
840 oriRotMat.getColumn(1)[2] = static_cast<float>(Y.z);
841 oriRotMat.getColumn(2)[0] = static_cast<float>(Z.x);
842 oriRotMat.getColumn(2)[1] = static_cast<float>(Z.y);
843 oriRotMat.getColumn(2)[2] = static_cast<float>(Z.z);
844 oriRotMat.invert();
845
846 ccGLMatrix transMat;
847 transMat.setTranslation(-C);
848 oriRotMat = oriRotMat * transMat;
849 oriRotMat.setTranslation(oriRotMat.getTranslationAsVec3D() + C);
850 }
851
852 //for each facet
853 for (FacetSet::iterator it = facets.begin(); it != facets.end(); ++it)
854 {
855 ccFacet* facet = *it;
856 ccPolyline* poly = facet->getContour();
857
858 //if necessary, we create a (temporary) new facet
859 if (!useNativeOrientation)
860 {
861 CCCoreLib::GenericIndexedCloudPersist* vertices = poly->getAssociatedCloud();
862 if (!vertices || vertices->size() < 3)
863 continue;
864
865 //create (temporary) new polyline
866 ccPolyline* newPoly = new ccPolyline(*poly);
867 ccPointCloud* pc = (newPoly ? dynamic_cast<ccPointCloud*>(newPoly->getAssociatedCloud()) : nullptr);
868 if (pc)
869 {
870 pc->applyGLTransformation_recursive(&oriRotMat);
871 }
872 else
873 {
874 m_app->dispToConsole(QString("Failed to change the orientation of polyline '%1'! (not enough memory)").arg(poly->getName()), ccMainAppInterface::WRN_CONSOLE_MESSAGE);
875 continue;
876 }
877
878 newPoly->set2DMode(true);
879 poly = newPoly;
880 }
881
882 toSave.addChild(poly, useNativeOrientation ? ccHObject::DP_NONE : ccHObject::DP_PARENT_OF_OTHER);
883
884 //save associated meta-data as 'shapefile' fields
885 {
886 //main parameters
887 FacetMetaData data;
888 GetFacetMetaData(facet, data);
889
890 //horizontal and vertical extensions
891 double horizExt = 0;
892 double vertExt = 0;
893 ComputeFacetExtensions(data.normal, poly, horizExt, vertExt);
894
895 facetIndex.values.push_back(data.facetIndex);
896 facetSurface.values.push_back(data.surface);
897 facetRMS.values.push_back(data.rms);
898 facetDipDir.values.push_back(data.dipDir_deg);
899 facetDip.values.push_back(data.dip_deg);
900 familyIndex.values.push_back(data.familyIndex);
901 subfamilyIndex.values.push_back(data.subfamilyIndex);
902 facetNormal.values.push_back(data.normal.toDouble());
903 facetBarycenter.values.push_back(data.center.toDouble());
904 facetGlobalBarycenter.values.push_back(data.globalCenter);
905 vertExtension.values.push_back(vertExt);
906 horizExtension.values.push_back(horizExt);
907 surfaceExtension.values.push_back(horizExt*vertExt);
908 }
909 }
910
911 //save entities
912 if (toSave.getChildrenNumber())
913 {
914 std::vector<GenericDBFField*> fields;
915 fields.push_back(&facetIndex);
916 fields.push_back(&facetBarycenter);
917 fields.push_back(&facetNormal);
918 fields.push_back(&facetRMS);
919 fields.push_back(&horizExtension);
920 fields.push_back(&vertExtension);
921 fields.push_back(&surfaceExtension);
922 fields.push_back(&facetSurface);
923 fields.push_back(&facetDipDir);
924 fields.push_back(&facetDip);
925 fields.push_back(&familyIndex);
926 fields.push_back(&subfamilyIndex);
927 ShpFilter filter;
928 filter.treatClosedPolylinesAsPolygons(true);
929 ShpFilter::SaveParameters params;
930 params.alwaysDisplaySaveDialog = false;
931 if (filter.saveToFile(&toSave, fields, filename, params) == CC_FERR_NO_ERROR)
932 {
933 m_app->dispToConsole(QString("[qFacets] File '%1' successfully saved").arg(filename), ccMainAppInterface::STD_CONSOLE_MESSAGE);
934 }
935 else
936 {
937 m_app->dispToConsole(QString("[qFacets] Failed to save file '%1'!").arg(filename), ccMainAppInterface::WRN_CONSOLE_MESSAGE);
938 }
939 }
940 }
941
942 void qFacets::showStereogram()
943 {
944 assert(m_app);
945 if (!m_app)
946 return;
947
948 //disclaimer accepted?
949 if (!ShowDisclaimer(m_app))
950 return;
951
952 //we expect a facet group or a cloud
953 const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();
954 if (!m_app->haveOneSelection()
955 || (!selectedEntities.back()->isA(CC_TYPES::HIERARCHY_OBJECT)
956 && !selectedEntities.back()->isA(CC_TYPES::POINT_CLOUD))
957 )
958 {
959 m_app->dispToConsole("Select a group of facets or a point cloud!");
960 return;
961 }
962
963 StereogramParamsDlg stereogramParamsDlg(m_app->getMainWindow());
964 stereogramParamsDlg.angleStepDoubleSpinBox->setValue(s_stereogramAngleStep);
965 stereogramParamsDlg.resolutionDoubleSpinBox->setValue(s_stereogramResolution_deg);
966 if (!stereogramParamsDlg.exec())
967 return;
968
969 s_stereogramAngleStep = stereogramParamsDlg.angleStepDoubleSpinBox->value();
970 s_stereogramResolution_deg = stereogramParamsDlg.resolutionDoubleSpinBox->value();
971
972 if ( m_stereogramDialog == nullptr )
973 {
974 m_stereogramDialog = new StereogramDialog( m_app );
975 }
976
977 if (m_stereogramDialog->init(s_stereogramAngleStep, selectedEntities.back(), s_stereogramResolution_deg))
978 {
979 m_stereogramDialog->show();
980 m_stereogramDialog->raise();
981 }
982 }
983
984 void qFacets::classifyFacetsByAngle()
985 {
986 assert(m_app);
987 if (!m_app)
988 return;
989
990 //disclaimer accepted?
991 if (!ShowDisclaimer(m_app))
992 return;
993
994 //we expect a facet group
995 const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();
996 if (!m_app->haveOneSelection() || !selectedEntities.back()->isA(CC_TYPES::HIERARCHY_OBJECT))
997 {
998 m_app->dispToConsole("Select a group of facets!");
999 return;
1000 }
1001
1002 ClassificationParamsDlg classifParamsDlg(m_app->getMainWindow());
1003 classifParamsDlg.angleStepDoubleSpinBox->setValue(s_classifAngleStep);
1004 classifParamsDlg.maxDistDoubleSpinBox->setValue(s_classifMaxDist);
1005 if (!classifParamsDlg.exec())
1006 return;
1007
1008 s_classifAngleStep = classifParamsDlg.angleStepDoubleSpinBox->value();
1009 s_stereogramAngleStep = s_classifAngleStep; //we automatically copy it to the stereogram's equivalent parameter
1010 s_classifMaxDist = classifParamsDlg.maxDistDoubleSpinBox->value();
1011
1012 ccHObject* group = selectedEntities.back();
1013 classifyFacetsByAngle(group, s_classifAngleStep, s_classifMaxDist);
1014 }
1015
1016 void qFacets::classifyFacetsByAngle(ccHObject* group,
1017 double angleStep_deg,
1018 double maxDist)
1019 {
1020 assert(m_app);
1021 if (!m_app)
1022 return;
1023
1024 assert(group);
1025
1026 if (group->isA(CC_TYPES::HIERARCHY_OBJECT))
1027 {
1028 if (group->getParent())
1029 {
1030 m_app->removeFromDB(group, false);
1031 }
1032
1033 bool success = FacetsClassifier::ByOrientation(group, angleStep_deg, maxDist);
1034 m_app->addToDB(group);
1035
1036 if (!success)
1037 {
1038 m_app->dispToConsole("An error occurred while classifying the facets! (not enough memory?)",
1039 ccMainAppInterface::ERR_CONSOLE_MESSAGE);
1040 return;
1041 }
1042 }
1043
1044 m_app->redrawAll();
1045 }
1046
1047 void qFacets::exportFacetsInfo()
1048 {
1049 assert(m_app);
1050 if (!m_app)
1051 return;
1052
1053 //disclaimer accepted?
1054 if (!ShowDisclaimer(m_app))
1055 return;
1056
1057 //Retrive selected facets
1058 FacetSet facets;
1059 getFacetsInCurrentSelection(facets);
1060
1061 if (facets.empty())
1062 {
1063 m_app->dispToConsole("Couldn't find any facet in the current selection!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
1064 return;
1065 }
1066 assert(!facets.empty());
1067
1068 FacetsExportDlg fDlg(FacetsExportDlg::ASCII_FILE_IO, m_app->getMainWindow());
1069 fDlg.orientationGroupBox->setEnabled(false);
1070
1071 //persistent settings (default export path)
1072 QSettings settings;
1073 settings.beginGroup("qFacets");
1074 QString facetsSavePath = settings.value("exportPath", ccFileUtils::defaultDocPath()).toString();
1075 fDlg.destinationPathLineEdit->setText(facetsSavePath + QString("/facets.csv"));
1076
1077 if (!fDlg.exec())
1078 return;
1079
1080 QString filename = fDlg.destinationPathLineEdit->text();
1081
1082 //save current export path to persistent settings
1083 settings.setValue("exportPath", QFileInfo(filename).absolutePath());
1084
1085 QFile outFile(filename);
1086 if (outFile.exists())
1087 {
1088 //if the file already exists, ask for confirmation!
1089 if (QMessageBox::warning(m_app->getMainWindow(),
1090 "Overwrite",
1091 "File already exists! Are you sure you want to overwrite it?",
1092 QMessageBox::Yes,
1093 QMessageBox::No) == QMessageBox::No)
1094 return;
1095 }
1096
1097 //open CSV file
1098 if (!outFile.open(QFile::WriteOnly | QFile::Text))
1099 {
1100 m_app->dispToConsole(QString("Failed to open file for writing! Check available space and access rights"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
1101 return;
1102 }
1103
1104 //write header
1105 QTextStream outStream(&outFile);
1106 outStream << "Index;";
1107 outStream << " CenterX;";
1108 outStream << " CenterY;";
1109 outStream << " CenterZ;";
1110 outStream << " GlobalCenterX;";
1111 outStream << " GlobalCenterY;";
1112 outStream << " GlobalCenterZ;";
1113 outStream << " NormalX;";
1114 outStream << " NormalY;";
1115 outStream << " NormalZ;";
1116 outStream << " RMS;";
1117 outStream << " Horiz_ext;";
1118 outStream << " Vert_ext;";
1119 outStream << " Surf_ext;";
1120 outStream << " Surface;";
1121 outStream << " Dip dir.;";
1122 outStream << " Dip;";
1123 outStream << " Family ind.;";
1124 outStream << " Subfamily ind.;";
1125 outStream << " \n";
1126
1127 //write data (one line per facet)
1128 for (FacetSet::iterator it = facets.begin(); it != facets.end(); ++it)
1129 {
1130 ccFacet* facet = *it;
1131 FacetMetaData data;
1132 GetFacetMetaData(facet, data);
1133 //horizontal and vertical extensions
1134 double horizExt = 0;
1135 double vertExt = 0;
1136 ComputeFacetExtensions(data.normal, facet->getContour(), horizExt, vertExt);
1137
1138 outStream << data.facetIndex << ";";
1139 outStream << data.center.x << ";" << data.center.y << ";" << data.center.z << ";";
1140 outStream << data.globalCenter.x << ";" << data.globalCenter.y << ";" << data.globalCenter.z << ";";
1141 outStream << data.normal.x << ";" << data.normal.y << ";" << data.normal.z << ";";
1142 outStream << data.rms << ";";
1143 outStream << horizExt << ";";
1144 outStream << vertExt << ";";
1145 outStream << horizExt*vertExt << ";";
1146 outStream << data.surface << ";";
1147 outStream << data.dipDir_deg << ";";
1148 outStream << data.dip_deg << ";";
1149 outStream << data.familyIndex << ";";
1150 outStream << data.subfamilyIndex << ";";
1151 outStream << "\n";
1152 }
1153
1154 outFile.close();
1155
1156 m_app->dispToConsole(QString("[qFacets] File '%1' successfully saved").arg(filename), ccMainAppInterface::STD_CONSOLE_MESSAGE);
1157 }