ccLibAlgorithms.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. //##########################################################################
  2. //# #
  3. //# CLOUDCOMPARE #
  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: CloudCompare project #
  15. //# #
  16. //##########################################################################
  17. #include "ccLibAlgorithms.h"
  18. //CCCoreLib
  19. #include <ScalarFieldTools.h>
  20. //qCC_db
  21. #include <ccOctree.h>
  22. #include <ccPointCloud.h>
  23. #include <ccScalarField.h>
  24. //Local
  25. #include "ccCommon.h"
  26. #include "ccConsole.h"
  27. #include "ccProgressDialog.h"
  28. #include "ccRegistrationTools.h"
  29. #include "ccUtils.h"
  30. //Qt
  31. #include <QApplication>
  32. #include <QElapsedTimer>
  33. #include <QInputDialog>
  34. #include <QMessageBox>
  35. // This is included only for temporarily removing an object from the tree.
  36. // TODO figure out a cleaner way to do this without having to include all of mainwindow.h
  37. #include "mainwindow.h"
  38. namespace ccLibAlgorithms
  39. {
  40. static QString GetDensitySFName(CCCoreLib::GeometricalAnalysisTools::Density densityType, bool approx, double densityKernelSize = 0.0)
  41. {
  42. QString sfName;
  43. //update the name with the density type
  44. switch (densityType)
  45. {
  46. case CCCoreLib::GeometricalAnalysisTools::DENSITY_KNN:
  47. sfName = CC_LOCAL_KNN_DENSITY_FIELD_NAME;
  48. break;
  49. case CCCoreLib::GeometricalAnalysisTools::DENSITY_2D:
  50. sfName = CC_LOCAL_SURF_DENSITY_FIELD_NAME;
  51. break;
  52. case CCCoreLib::GeometricalAnalysisTools::DENSITY_3D:
  53. sfName = CC_LOCAL_VOL_DENSITY_FIELD_NAME;
  54. break;
  55. default:
  56. assert(false);
  57. break;
  58. }
  59. sfName += QString(" (r=%2)").arg(densityKernelSize);
  60. if (approx)
  61. sfName += " [approx]";
  62. return sfName;
  63. }
  64. double GetDefaultCloudKernelSize(ccGenericPointCloud* cloud, unsigned knn/*=12*/)
  65. {
  66. assert(cloud);
  67. if (cloud && cloud->size() != 0)
  68. {
  69. //we get 1% of the cloud bounding box
  70. //and we divide by the number of points / 10e6 (so that the kernel for a 20 M. points cloud is half the one of a 10 M. cloud)
  71. ccBBox box = cloud->getOwnBB();
  72. //old way
  73. //PointCoordinateType radius = box.getDiagNorm() * static_cast<PointCoordinateType>(0.01/std::max(1.0,1.0e-7*static_cast<double>(cloud->size())));
  74. //new way
  75. CCVector3 d = box.getDiagVec();
  76. double volume = (static_cast<double>(d[0]) * d[1]) * d[2];
  77. double surface = pow(volume, 2.0/3.0);
  78. double surfacePerPoint = surface / cloud->size();
  79. return sqrt(surfacePerPoint * knn);
  80. }
  81. return -CCCoreLib::PC_ONE;
  82. }
  83. double GetDefaultCloudKernelSize(const ccHObject::Container& entities, unsigned knn/*=12*/)
  84. {
  85. double sigma = std::numeric_limits<double>::max();
  86. for (ccHObject* entity : entities)
  87. {
  88. ccPointCloud* pc = ccHObjectCaster::ToPointCloud(entity);
  89. double sigmaCloud = GetDefaultCloudKernelSize(pc);
  90. //we keep the smallest value
  91. if (sigmaCloud < sigma)
  92. {
  93. sigma = sigmaCloud;
  94. }
  95. }
  96. return sigma;
  97. }
  98. bool ComputeGeomCharacteristics(const GeomCharacteristicSet& characteristics,
  99. PointCoordinateType radius,
  100. ccHObject::Container& entities,
  101. const CCVector3* roughnessUpDir/*=nullptr*/,
  102. QWidget* parent/*=nullptr*/)
  103. {
  104. //no feature case
  105. if (characteristics.empty())
  106. {
  107. //nothing to do
  108. assert(false);
  109. return true;
  110. }
  111. //single features case
  112. if (characteristics.size() == 1)
  113. {
  114. return ComputeGeomCharacteristic( characteristics.front().charac,
  115. characteristics.front().subOption,
  116. radius,
  117. entities,
  118. roughnessUpDir,
  119. parent);
  120. }
  121. //multiple features case
  122. QScopedPointer<ccProgressDialog> pDlg;
  123. if (parent)
  124. {
  125. pDlg.reset(new ccProgressDialog(true, parent));
  126. pDlg->setAutoClose(false);
  127. }
  128. for (const GeomCharacteristic& g : characteristics)
  129. {
  130. if (!ComputeGeomCharacteristic( g.charac,
  131. g.subOption,
  132. radius,
  133. entities,
  134. roughnessUpDir,
  135. parent,
  136. pDlg.data()))
  137. {
  138. return false;
  139. }
  140. }
  141. return true;
  142. }
  143. bool ComputeGeomCharacteristic( CCCoreLib::GeometricalAnalysisTools::GeomCharacteristic c,
  144. int subOption,
  145. PointCoordinateType radius,
  146. ccHObject::Container& entities,
  147. const CCVector3* roughnessUpDir/*=nullptr*/,
  148. QWidget* parent/*= nullptr*/,
  149. ccProgressDialog* progressDialog/*=nullptr*/)
  150. {
  151. size_t selNum = entities.size();
  152. if (selNum < 1)
  153. return false;
  154. //generate the right SF name
  155. QString sfName;
  156. switch (c)
  157. {
  158. case CCCoreLib::GeometricalAnalysisTools::Feature:
  159. {
  160. switch (subOption)
  161. {
  162. case CCCoreLib::Neighbourhood::EigenValuesSum:
  163. sfName = "Eigenvalues sum";
  164. break;
  165. case CCCoreLib::Neighbourhood::Omnivariance:
  166. sfName = "Omnivariance";
  167. break;
  168. case CCCoreLib::Neighbourhood::EigenEntropy:
  169. sfName = "Eigenentropy";
  170. break;
  171. case CCCoreLib::Neighbourhood::Anisotropy:
  172. sfName = "Anisotropy";
  173. break;
  174. case CCCoreLib::Neighbourhood::Planarity:
  175. sfName = "Planarity";
  176. break;
  177. case CCCoreLib::Neighbourhood::Linearity:
  178. sfName = "Linearity";
  179. break;
  180. case CCCoreLib::Neighbourhood::PCA1:
  181. sfName = "PCA1";
  182. break;
  183. case CCCoreLib::Neighbourhood::PCA2:
  184. sfName = "PCA2";
  185. break;
  186. case CCCoreLib::Neighbourhood::SurfaceVariation:
  187. sfName = "Surface variation";
  188. break;
  189. case CCCoreLib::Neighbourhood::Sphericity:
  190. sfName = "Sphericity";
  191. break;
  192. case CCCoreLib::Neighbourhood::Verticality:
  193. sfName = "Verticality";
  194. break;
  195. case CCCoreLib::Neighbourhood::EigenValue1:
  196. sfName = "1st eigenvalue";
  197. break;
  198. case CCCoreLib::Neighbourhood::EigenValue2:
  199. sfName = "2nd eigenvalue";
  200. break;
  201. case CCCoreLib::Neighbourhood::EigenValue3:
  202. sfName = "3rd eigenvalue";
  203. break;
  204. default:
  205. assert(false);
  206. ccLog::Error("Internal error: invalid sub option for Feature computation");
  207. return false;
  208. }
  209. sfName += QString(" (%1)").arg(radius);
  210. }
  211. break;
  212. case CCCoreLib::GeometricalAnalysisTools::Curvature:
  213. {
  214. switch (subOption)
  215. {
  216. case CCCoreLib::Neighbourhood::GAUSSIAN_CURV:
  217. sfName = CC_CURVATURE_GAUSSIAN_FIELD_NAME;
  218. break;
  219. case CCCoreLib::Neighbourhood::MEAN_CURV:
  220. sfName = CC_CURVATURE_MEAN_FIELD_NAME;
  221. break;
  222. case CCCoreLib::Neighbourhood::NORMAL_CHANGE_RATE:
  223. sfName = CC_CURVATURE_NORM_CHANGE_RATE_FIELD_NAME;
  224. break;
  225. default:
  226. assert(false);
  227. ccLog::Error("Internal error: invalid sub option for Curvature computation");
  228. return false;
  229. }
  230. sfName += QString(" (%1)").arg(radius);
  231. }
  232. break;
  233. case CCCoreLib::GeometricalAnalysisTools::LocalDensity:
  234. sfName = GetDensitySFName(static_cast<CCCoreLib::GeometricalAnalysisTools::Density>(subOption), false, radius);
  235. break;
  236. case CCCoreLib::GeometricalAnalysisTools::ApproxLocalDensity:
  237. sfName = GetDensitySFName(static_cast<CCCoreLib::GeometricalAnalysisTools::Density>(subOption), true);
  238. break;
  239. case CCCoreLib::GeometricalAnalysisTools::Roughness:
  240. sfName = CC_ROUGHNESS_FIELD_NAME + QString(" (%1)").arg(radius);
  241. break;
  242. case CCCoreLib::GeometricalAnalysisTools::MomentOrder1:
  243. sfName = CC_MOMENT_ORDER1_FIELD_NAME + QString(" (%1)").arg(radius);
  244. break;
  245. default:
  246. assert(false);
  247. return false;
  248. }
  249. ccProgressDialog* pDlg = progressDialog;
  250. if (!pDlg && parent)
  251. {
  252. pDlg = new ccProgressDialog(true, parent);
  253. pDlg->setAutoClose(false);
  254. }
  255. for (size_t i = 0; i < selNum; ++i)
  256. {
  257. //is the ith selected data is eligible for processing?
  258. if (entities[i]->isKindOf(CC_TYPES::POINT_CLOUD))
  259. {
  260. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entities[i]);
  261. ccPointCloud* pc = nullptr;
  262. int sfIdx = -1;
  263. if (cloud->isA(CC_TYPES::POINT_CLOUD))
  264. {
  265. pc = static_cast<ccPointCloud*>(cloud);
  266. sfIdx = pc->getScalarFieldIndexByName(sfName.toStdString());
  267. if (sfIdx < 0)
  268. sfIdx = pc->addScalarField(sfName.toStdString());
  269. if (sfIdx >= 0)
  270. pc->setCurrentScalarField(sfIdx);
  271. else
  272. {
  273. ccConsole::Error(QString("Failed to create scalar field on cloud '%1' (not enough memory?)").arg(pc->getName()));
  274. continue;
  275. }
  276. }
  277. ccOctree::Shared octree = cloud->getOctree();
  278. if (!octree)
  279. {
  280. if (pDlg)
  281. {
  282. pDlg->show();
  283. }
  284. octree = cloud->computeOctree(pDlg);
  285. if (!octree)
  286. {
  287. ccConsole::Error(QString("Couldn't compute octree for cloud '%1'!").arg(cloud->getName()));
  288. break;
  289. }
  290. }
  291. CCCoreLib::GeometricalAnalysisTools::ErrorCode result = CCCoreLib::GeometricalAnalysisTools::ComputeCharactersitic( c,
  292. subOption,
  293. cloud,
  294. radius,
  295. roughnessUpDir,
  296. pDlg,
  297. octree.data());
  298. if (result == CCCoreLib::GeometricalAnalysisTools::NoError)
  299. {
  300. if (pc && sfIdx >= 0)
  301. {
  302. pc->setCurrentDisplayedScalarField(sfIdx);
  303. pc->showSF(sfIdx >= 0);
  304. pc->getCurrentInScalarField()->computeMinAndMax();
  305. if (c == CCCoreLib::GeometricalAnalysisTools::Roughness && roughnessUpDir != nullptr)
  306. {
  307. // signed roughness should be displayed with a symmetrical color scale
  308. ccScalarField* sf = dynamic_cast<ccScalarField*>(pc->getCurrentInScalarField());
  309. if (sf)
  310. {
  311. sf->setSymmetricalScale(true);
  312. }
  313. else
  314. {
  315. assert(false);
  316. }
  317. }
  318. }
  319. cloud->prepareDisplayForRefresh();
  320. }
  321. else
  322. {
  323. QString errorMessage;
  324. switch (result)
  325. {
  326. case CCCoreLib::GeometricalAnalysisTools::InvalidInput:
  327. errorMessage = "Internal error (invalid input)";
  328. break;
  329. case CCCoreLib::GeometricalAnalysisTools::NotEnoughPoints:
  330. errorMessage = "Not enough points";
  331. break;
  332. case CCCoreLib::GeometricalAnalysisTools::OctreeComputationFailed:
  333. errorMessage = "Failed to compute octree (not enough memory?)";
  334. break;
  335. case CCCoreLib::GeometricalAnalysisTools::ProcessFailed:
  336. errorMessage = "Process failed";
  337. break;
  338. case CCCoreLib::GeometricalAnalysisTools::UnhandledCharacteristic:
  339. errorMessage = "Internal error (unhandled characteristic)";
  340. break;
  341. case CCCoreLib::GeometricalAnalysisTools::NotEnoughMemory:
  342. errorMessage = "Not enough memory";
  343. break;
  344. case CCCoreLib::GeometricalAnalysisTools::ProcessCancelledByUser:
  345. errorMessage = "Process cancelled by user";
  346. break;
  347. default:
  348. assert(false);
  349. errorMessage = "Unknown error";
  350. break;
  351. }
  352. ccConsole::Warning(QString("Failed to apply processing to cloud '%1'").arg(cloud->getName()));
  353. ccConsole::Warning(errorMessage);
  354. if (pc && sfIdx >= 0)
  355. {
  356. pc->deleteScalarField(sfIdx);
  357. sfIdx = -1;
  358. }
  359. if (pDlg != progressDialog)
  360. {
  361. delete pDlg;
  362. pDlg = nullptr;
  363. }
  364. return false;
  365. }
  366. }
  367. }
  368. if (pDlg != progressDialog)
  369. {
  370. delete pDlg;
  371. pDlg = nullptr;
  372. }
  373. return true;
  374. }
  375. bool ApplyCCLibAlgorithm(CC_LIB_ALGORITHM algo, ccHObject::Container& entities, QWidget* parent/*=nullptr*/, void** additionalParameters/*=nullptr*/)
  376. {
  377. size_t selNum = entities.size();
  378. if (selNum < 1)
  379. return false;
  380. //generic parameters
  381. QString sfName;
  382. //computeScalarFieldGradient parameters
  383. bool euclidean = false;
  384. switch (algo)
  385. {
  386. case CCLIB_ALGO_SF_GRADIENT:
  387. {
  388. sfName = CC_GRADIENT_NORMS_FIELD_NAME;
  389. //parameters already provided?
  390. if (additionalParameters)
  391. {
  392. euclidean = *static_cast<bool*>(additionalParameters[0]);
  393. }
  394. else //ask the user!
  395. {
  396. euclidean = ( QMessageBox::question(parent,
  397. "Gradient",
  398. "Is the scalar field composed of (euclidean) distances?",
  399. QMessageBox::Yes | QMessageBox::No,
  400. QMessageBox::No ) == QMessageBox::Yes );
  401. }
  402. }
  403. break;
  404. default:
  405. assert(false);
  406. return false;
  407. }
  408. for (size_t i = 0; i < selNum; ++i)
  409. {
  410. //is the ith selected data is eligible for processing?
  411. ccGenericPointCloud* cloud = nullptr;
  412. switch (algo)
  413. {
  414. case CCLIB_ALGO_SF_GRADIENT:
  415. //for scalar field gradient, we can apply it directly on meshes
  416. bool lockedVertices;
  417. cloud = ccHObjectCaster::ToGenericPointCloud(entities[i], &lockedVertices);
  418. if (lockedVertices)
  419. {
  420. ccUtils::DisplayLockedVerticesWarning(entities[i]->getName(), selNum == 1);
  421. cloud = nullptr;
  422. }
  423. if (cloud)
  424. {
  425. //but we need an already displayed SF!
  426. if (cloud->isA(CC_TYPES::POINT_CLOUD))
  427. {
  428. ccPointCloud* pc = static_cast<ccPointCloud*>(cloud);
  429. int outSfIdx = pc->getCurrentDisplayedScalarFieldIndex();
  430. if (outSfIdx < 0)
  431. {
  432. cloud = nullptr;
  433. }
  434. else
  435. {
  436. //we set as 'output' SF the currently displayed scalar field
  437. pc->setCurrentOutScalarField(outSfIdx);
  438. sfName = QString("%1(%2)").arg(CC_GRADIENT_NORMS_FIELD_NAME, QString::fromStdString(pc->getScalarFieldName(outSfIdx)));
  439. }
  440. }
  441. else //if (!cloud->hasDisplayedScalarField()) //TODO: displayed but not necessarily set as OUTPUT!
  442. {
  443. cloud = nullptr;
  444. }
  445. }
  446. break;
  447. //by default, we apply processings on clouds only
  448. default:
  449. if (entities[i]->isKindOf(CC_TYPES::POINT_CLOUD))
  450. cloud = ccHObjectCaster::ToGenericPointCloud(entities[i]);
  451. break;
  452. }
  453. if (cloud)
  454. {
  455. ccPointCloud* pc = nullptr;
  456. int sfIdx = -1;
  457. if (cloud->isA(CC_TYPES::POINT_CLOUD))
  458. {
  459. pc = static_cast<ccPointCloud*>(cloud);
  460. sfIdx = pc->getScalarFieldIndexByName(sfName.toStdString());
  461. if (sfIdx < 0)
  462. sfIdx = pc->addScalarField(sfName.toStdString());
  463. if (sfIdx >= 0)
  464. pc->setCurrentInScalarField(sfIdx);
  465. else
  466. {
  467. ccConsole::Error(QString("Failed to create scalar field on cloud '%1' (not enough memory?)").arg(pc->getName()));
  468. continue;
  469. }
  470. }
  471. QScopedPointer<ccProgressDialog> pDlg;
  472. if (parent)
  473. {
  474. pDlg.reset(new ccProgressDialog(true, parent));
  475. }
  476. ccOctree::Shared octree = cloud->getOctree();
  477. if (!octree)
  478. {
  479. if (pDlg)
  480. {
  481. pDlg->show();
  482. }
  483. octree = cloud->computeOctree(pDlg.data());
  484. if (!octree)
  485. {
  486. ccConsole::Error(QString("Couldn't compute octree for cloud '%1'!").arg(cloud->getName()));
  487. break;
  488. }
  489. }
  490. int result = 0;
  491. QElapsedTimer eTimer;
  492. eTimer.start();
  493. switch(algo)
  494. {
  495. case CCLIB_ALGO_SF_GRADIENT:
  496. result = CCCoreLib::ScalarFieldTools::computeScalarFieldGradient(cloud,
  497. 0, //auto --> FIXME: should be properly set by the user!
  498. euclidean,
  499. false,
  500. pDlg.data(),
  501. octree.data());
  502. break;
  503. default:
  504. //missed something?
  505. assert(false);
  506. }
  507. qint64 elapsedTime_ms = eTimer.elapsed();
  508. if (result == 0)
  509. {
  510. if (pc && sfIdx >= 0)
  511. {
  512. pc->setCurrentDisplayedScalarField(sfIdx);
  513. pc->showSF(sfIdx >= 0);
  514. pc->getCurrentInScalarField()->computeMinAndMax();
  515. }
  516. cloud->prepareDisplayForRefresh();
  517. ccConsole::Print("[Algorithm] Timing: %3.2f s.", static_cast<double>(elapsedTime_ms) / 1000.0);
  518. }
  519. else
  520. {
  521. ccConsole::Warning(QString("Failed to apply processing to cloud '%1'").arg(cloud->getName()));
  522. if (pc && sfIdx >= 0)
  523. {
  524. pc->deleteScalarField(sfIdx);
  525. sfIdx = -1;
  526. }
  527. }
  528. }
  529. }
  530. return true;
  531. }
  532. bool ApplyScaleMatchingAlgorithm( ScaleMatchingAlgorithm algo,
  533. ccHObject::Container& entities,
  534. double icpRmsDiff,
  535. int icpFinalOverlap,
  536. unsigned refEntityIndex/*=0*/,
  537. QWidget* parent/*=nullptr*/)
  538. {
  539. if ( entities.size() < 2
  540. || refEntityIndex >= entities.size())
  541. {
  542. ccLog::Error("[ApplyScaleMatchingAlgorithm] Invalid input parameter(s)");
  543. return false;
  544. }
  545. std::vector<double> scales;
  546. try
  547. {
  548. scales.resize(entities.size(), -1.0);
  549. }
  550. catch (const std::bad_alloc&)
  551. {
  552. ccLog::Error("Not enough memory!");
  553. return false;
  554. }
  555. //check the reference entity
  556. ccHObject* refEntity = entities[refEntityIndex];
  557. if ( !refEntity->isKindOf(CC_TYPES::POINT_CLOUD)
  558. && !refEntity->isKindOf(CC_TYPES::MESH))
  559. {
  560. ccLog::Warning("[Scale Matching] The reference entity must be a cloud or a mesh!");
  561. return false;
  562. }
  563. unsigned count = static_cast<unsigned>(entities.size());
  564. //now compute the scales
  565. ccProgressDialog pDlg(true,parent);
  566. pDlg.setMethodTitle(QObject::tr("Computing entities scales"));
  567. pDlg.setInfo(QObject::tr("Entities: %1").arg(count));
  568. CCCoreLib::NormalizedProgress nProgress(&pDlg, 2 * count - 1);
  569. pDlg.start();
  570. QApplication::processEvents();
  571. for (unsigned i = 0; i < count; ++i)
  572. {
  573. ccHObject* ent = entities[i];
  574. //try to get the underlying cloud (or the vertices set for a mesh)
  575. bool lockedVertices;
  576. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(ent,&lockedVertices);
  577. if (cloud && !lockedVertices)
  578. {
  579. switch (algo)
  580. {
  581. case BB_MAX_DIM:
  582. case BB_VOLUME:
  583. {
  584. ccBBox box = ent->getOwnBB();
  585. if (box.isValid())
  586. scales[i] = algo == BB_MAX_DIM ? box.getMaxBoxDim() : box.computeVolume();
  587. else
  588. ccLog::Warning(QString("[Scale Matching] Entity '%1' has an invalid bounding-box!").arg(ent->getName()));
  589. }
  590. break;
  591. case PCA_MAX_DIM:
  592. {
  593. CCCoreLib::Neighbourhood Yk(cloud);
  594. if (!Yk.getLSPlane())
  595. {
  596. ccLog::Warning(QString("[Scale Matching] Failed to perform PCA on entity '%1'!").arg(ent->getName()));
  597. break;
  598. }
  599. //deduce the scale
  600. {
  601. const CCVector3* X = Yk.getLSPlaneX();
  602. const CCVector3* O = Yk.getGravityCenter();
  603. double minX = 0;
  604. double maxX = 0;
  605. for (unsigned j = 0; j < cloud->size(); ++j)
  606. {
  607. double x = (*cloud->getPoint(j) - *O).dot(*X);
  608. if (j != 0)
  609. {
  610. minX = std::min(x,minX);
  611. maxX = std::max(x,maxX);
  612. }
  613. else
  614. {
  615. minX = maxX = x;
  616. }
  617. }
  618. scales[i] = maxX-minX;
  619. }
  620. }
  621. break;
  622. case ICP_SCALE:
  623. {
  624. ccGLMatrix transMat;
  625. double finalError = 0.0;
  626. double finalScale = 1.0;
  627. unsigned finalPointCount = 0;
  628. CCCoreLib::ICPRegistrationTools::Parameters parameters;
  629. {
  630. parameters.convType = CCCoreLib::ICPRegistrationTools::MAX_ERROR_CONVERGENCE;
  631. parameters.minRMSDecrease = icpRmsDiff;
  632. parameters.nbMaxIterations = 0;
  633. parameters.adjustScale = true;
  634. parameters.filterOutFarthestPoints = false;
  635. parameters.samplingLimit = 50000;
  636. parameters.finalOverlapRatio = icpFinalOverlap / 100.0;
  637. parameters.transformationFilters = CCCoreLib::RegistrationTools::SKIP_NONE;
  638. parameters.maxThreadCount = 0;
  639. parameters.useC2MSignedDistances = false;
  640. parameters.robustC2MSignedDistances = true;
  641. parameters.normalsMatching = CCCoreLib::ICPRegistrationTools::NO_NORMAL;
  642. }
  643. if (ccRegistrationTools::ICP(
  644. ent,
  645. refEntity,
  646. transMat,
  647. finalScale,
  648. finalError,
  649. finalPointCount,
  650. parameters,
  651. false,
  652. false,
  653. parent))
  654. {
  655. scales[i] = finalScale;
  656. }
  657. else
  658. {
  659. ccLog::Warning(QString("[Scale Matching] Failed to register entity '%1'!").arg(ent->getName()));
  660. }
  661. }
  662. break;
  663. default:
  664. assert(false);
  665. break;
  666. }
  667. }
  668. else if (cloud && lockedVertices)
  669. {
  670. //locked entities
  671. ccUtils::DisplayLockedVerticesWarning(ent->getName(),false);
  672. }
  673. else
  674. {
  675. //we need a cloud or a mesh
  676. ccLog::Warning(QString("[Scale Matching] Entity '%1' can't be rescaled this way!").arg(ent->getName()));
  677. }
  678. //if the reference entity is invalid!
  679. if (scales[i] <= 0 && i == refEntityIndex)
  680. {
  681. ccLog::Error("Reference entity has an invalid scale! Can't proceed.");
  682. return false;
  683. }
  684. if (!nProgress.oneStep())
  685. {
  686. //process cancelled by user
  687. return false;
  688. }
  689. }
  690. ccLog::Print(QString("[Scale Matching] Reference entity scale: %1").arg(scales[refEntityIndex]));
  691. //now we can rescale
  692. pDlg.setMethodTitle(QObject::tr("Rescaling entities"));
  693. {
  694. for (unsigned i=0; i<count; ++i)
  695. {
  696. if (i == refEntityIndex)
  697. continue;
  698. if (scales[i] < 0)
  699. continue;
  700. ccLog::Print(QString("[Scale Matching] Entity '%1' scale: %2").arg(entities[i]->getName()).arg(scales[i]));
  701. if (scales[i] <= CCCoreLib::ZERO_TOLERANCE_D)
  702. {
  703. ccLog::Warning("[Scale Matching] Entity scale is too small!");
  704. continue;
  705. }
  706. ccHObject* ent = entities[i];
  707. bool lockedVertices;
  708. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(ent,&lockedVertices);
  709. if (!cloud || lockedVertices)
  710. continue;
  711. double scaled = 1.0;
  712. if (algo == ICP_SCALE)
  713. scaled = scales[i];
  714. else
  715. scaled = scales[refEntityIndex] / scales[i];
  716. PointCoordinateType scale_pc = static_cast<PointCoordinateType>(scaled);
  717. //we temporarily detach entity, as it may undergo
  718. //"severe" modifications (octree deletion, etc.) --> see ccPointCloud::scale
  719. MainWindow* instance = dynamic_cast<MainWindow*>(parent);
  720. MainWindow::ccHObjectContext objContext;
  721. if (instance)
  722. {
  723. objContext = instance->removeObjectTemporarilyFromDBTree(cloud);
  724. }
  725. CCVector3 C = cloud->getOwnBB().getCenter();
  726. cloud->scale( scale_pc,
  727. scale_pc,
  728. scale_pc,
  729. C );
  730. if (instance)
  731. instance->putObjectBackIntoDBTree(cloud,objContext);
  732. cloud->prepareDisplayForRefresh_recursive();
  733. //don't forget the 'global shift'!
  734. const CCVector3d& shift = cloud->getGlobalShift();
  735. cloud->setGlobalShift(shift*scaled);
  736. //DGM: nope! Not the global scale!
  737. }
  738. if (!nProgress.oneStep())
  739. {
  740. //process cancelled by user
  741. return false;
  742. }
  743. }
  744. return true;
  745. }
  746. }