File: qPoissonRecon.cpp

package info (click to toggle)
cloudcompare 2.10.3-4
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 57,516 kB
  • sloc: cpp: 219,980; ansic: 29,944; makefile: 78; sh: 21
file content (568 lines) | stat: -rw-r--r-- 16,212 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
//##########################################################################
//#                                                                        #
//#                CLOUDCOMPARE PLUGIN: qPoissonRecon                      #
//#                                                                        #
//#  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: Daniel Girardeau-Montaut                   #
//#                                                                        #
//##########################################################################

#include "qPoissonRecon.h"

//dialog
#include "ui_poissonReconParamDlg.h"

//Qt
#include <QtGui>
#include <QInputDialog>
#include <QtCore>
#include <QtConcurrentRun>
#include <QDialog>
#include <QMainWindow>

//PoissonRecon
#include <PoissonReconLib.h>

//qCC_db
#include <ccPointCloud.h>
#include <ccMesh.h>
#include <ccProgressDialog.h>
#include <ccScalarField.h>

//System
#if defined(CC_WINDOWS)
#include "windows.h"
#else
#include <time.h>
#include <unistd.h>
#endif

//Dedicated 'OrientedPointStream' for the ccPointCloud structure
template <class Real> class ccPointStream : public OrientedPointStream<Real>
{
public:
	explicit ccPointStream( ccPointCloud* cloud ) : m_cloud(cloud), m_index(0) {}
	virtual void reset( void ) { m_index = 0; }
	virtual bool nextPoint( OrientedPoint3D< Real >& out )
	{
		if (!m_cloud || m_index == m_cloud->size())
		{
			return false;
		}
		//point
		const CCVector3* P = m_cloud->getPoint(m_index);
		out.p[0] = static_cast<Real>(P->x);
		out.p[1] = static_cast<Real>(P->y);
		out.p[2] = static_cast<Real>(P->z);

		//normal
		assert(m_cloud->hasNormals());
		const CCVector3& N = m_cloud->getPointNormal(m_index);
		//DGM: strangely, this new version of PoissonRecon seems to require inverted normals
		out.n[0] = -static_cast<Real>(N.x);
		out.n[1] = -static_cast<Real>(N.y);
		out.n[2] = -static_cast<Real>(N.z);

		//auto-forward
		++m_index;

		return true;
	}

protected:
	ccPointCloud* m_cloud;
	unsigned m_index;
};

//Dedicated 'OrientedPointStream' for the ccPointCloud structure (with colors)
template <class Real> class ccColoredPointStream : public OrientedPointStreamWithData<Real , Point3D< Real > >
{
public:
	explicit ccColoredPointStream( ccPointCloud* cloud ) : m_cloud(cloud), m_index(0) { assert(cloud && cloud->hasColors()); }
	virtual void reset( void ) { m_index = 0; }
	virtual bool nextPoint( OrientedPoint3D< Real >& out, Point3D< Real >& d )
	{
		if (!m_cloud || m_index == m_cloud->size())
		{
			return false;
		}
		//point
		const CCVector3* P = m_cloud->getPoint(m_index);
		out.p[0] = static_cast<Real>(P->x);
		out.p[1] = static_cast<Real>(P->y);
		out.p[2] = static_cast<Real>(P->z);

		//normal
		assert(m_cloud->hasNormals());
		const CCVector3& N = m_cloud->getPointNormal(m_index);
		out.n[0] = -static_cast<Real>(N.x);
		out.n[1] = -static_cast<Real>(N.y);
		out.n[2] = -static_cast<Real>(N.z);

		//color
		assert(m_cloud->hasColors());
		const ccColor::Rgb& rgb = m_cloud->getPointColor(m_index);
		d[0] = static_cast<Real>(rgb.r);
		d[1] = static_cast<Real>(rgb.g);
		d[2] = static_cast<Real>(rgb.b);

		//auto-forward
		++m_index;

		return true;
	}

protected:
	ccPointCloud* m_cloud;
	unsigned m_index;
};

//dialog for qPoissonRecon plugin
class PoissonReconParamDlg : public QDialog, public Ui::PoissonReconParamDialog
{
public:
	explicit PoissonReconParamDlg(QWidget* parent = 0)
		: QDialog(parent, Qt::Tool)
		, Ui::PoissonReconParamDialog()
	{
		setupUi(this);
	}
};

qPoissonRecon::qPoissonRecon(QObject* parent/*=0*/)
	: QObject(parent)
	, ccStdPluginInterface(":/CC/plugin/qPoissonRecon/info.json")
	, m_action(0)
{
}

void qPoissonRecon::onNewSelection(const ccHObject::Container& selectedEntities)
{
	if (m_action)
		m_action->setEnabled(selectedEntities.size()==1 && selectedEntities[0]->isA(CC_TYPES::POINT_CLOUD));
}

QList<QAction *> qPoissonRecon::getActions()
{
	//default action
	if (!m_action)
	{
		m_action = new QAction(getName(),this);
		m_action->setToolTip(getDescription());
		m_action->setIcon(getIcon());
		//connect signal
		connect(m_action, &QAction::triggered, this, &qPoissonRecon::doAction);
	}

	return QList<QAction *>{ m_action };
}

typedef PlyValueVertex< PointCoordinateType > Vertex;
typedef CoredVectorMeshData< Vertex > PoissonMesh;

typedef PlyColorAndValueVertex< PointCoordinateType > ColoredVertex;
typedef CoredVectorMeshData< ColoredVertex > ColoredPoissonMesh;

static PoissonReconLib::Parameters s_params;
static ccPointCloud* s_cloud = 0;
static PoissonMesh* s_mesh = 0;
static ColoredPoissonMesh* s_coloredMesh = 0;
static XForm4x4< PointCoordinateType > s_iXForm;

bool doReconstruct()
{
	//invalid parameters
	if (!s_cloud || !s_mesh)
	{
		return false;
	}

	ccPointStream<PointCoordinateType> pointStream(s_cloud);
	return PoissonReconLib::Reconstruct(s_params, &pointStream, *s_mesh, s_iXForm);
}

bool doReconstructWithColors()
{
	//invalid parameters
	if (!s_cloud || !s_coloredMesh || !s_cloud->hasColors())
	{
		return false;
	}

	ccColoredPointStream<PointCoordinateType> pointStream(s_cloud);
	return PoissonReconLib::Reconstruct(s_params, &pointStream, *s_coloredMesh, s_iXForm);
}

void qPoissonRecon::doAction()
{
	assert(m_app);
	if (!m_app)
	{
		return;
	}

	//we need one point cloud
	if (!m_app->haveOneSelection())
	{
		m_app->dispToConsole("Select only one cloud!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	//a real point cloud
	const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();
	
	ccHObject* ent = selectedEntities[0];
	if (!ent->isA(CC_TYPES::POINT_CLOUD))
	{
		m_app->dispToConsole("Select a cloud!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	//with normals!
	ccPointCloud* pc = static_cast<ccPointCloud*>(ent);
	if (!pc->hasNormals())
	{
		m_app->dispToConsole("Cloud must have normals!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	bool cloudHasColors = pc->hasColors();
	PoissonReconParamDlg prpDlg(m_app->getMainWindow());
	prpDlg.importColorsCheckBox->setVisible(cloudHasColors);

	//init dialog with semi-persistent settings
	prpDlg.octreeLevelSpinBox->setValue(s_params.depth);
	prpDlg.weightDoubleSpinBox->setValue(s_params.pointWeight);
	prpDlg.fullDepthSpinBox->setValue(s_params.fullDepth);
	prpDlg.samplesPerNodeSpinBox->setValue(s_params.samplesPerNode);
	prpDlg.densityCheckBox->setChecked(s_params.density);
	prpDlg.importColorsCheckBox->setChecked(true);
	switch (s_params.boundary)
	{
	case PoissonReconLib::Parameters::FREE:
		prpDlg.boundaryComboBox->setCurrentIndex(0);
		break;
	case PoissonReconLib::Parameters::DIRICHLET:
		prpDlg.boundaryComboBox->setCurrentIndex(1);
		break;
	case PoissonReconLib::Parameters::NEUMANN:
		prpDlg.boundaryComboBox->setCurrentIndex(2);
		break;
	default:
		assert(false);
		break;
	}

	if (!prpDlg.exec())
		return;

	//set parameters with dialog settings
	s_params.depth = prpDlg.octreeLevelSpinBox->value();
	s_params.pointWeight = static_cast<float>(prpDlg.weightDoubleSpinBox->value());
	s_params.fullDepth = prpDlg.fullDepthSpinBox->value();
	s_params.samplesPerNode = static_cast<float>(prpDlg.samplesPerNodeSpinBox->value());
	s_params.density = prpDlg.densityCheckBox->isChecked();
	switch (prpDlg.boundaryComboBox->currentIndex())
	{
	case 0:
		s_params.boundary = PoissonReconLib::Parameters::FREE;
		break;
	case 1:
		s_params.boundary = PoissonReconLib::Parameters::DIRICHLET;
		break;
	case 2:
		s_params.boundary = PoissonReconLib::Parameters::NEUMANN;
		break;
	default:
		assert(false);
		break;
	}
	bool withColors = pc->hasColors() && prpDlg.importColorsCheckBox->isChecked();

	/*** RECONSTRUCTION PROCESS ***/

	PoissonMesh mesh;
	ColoredPoissonMesh coloredMesh;
	s_cloud = 0;
	s_mesh = 0;
	s_coloredMesh = 0;

	//run in a separate thread
	bool result = false;
	{
		//start message
		m_app->dispToConsole(QString("[PoissonRecon] Job started (level %1)").arg(s_params.depth),ccMainAppInterface::STD_CONSOLE_MESSAGE);

		//progress dialog (Qtconcurrent::run can't be canceled!)
		QProgressDialog pDlg("Initialization", QString(), 0, 0, m_app->getMainWindow());
		pDlg.setWindowTitle("Poisson Reconstruction");
		pDlg.show();
		//QApplication::processEvents();

		pDlg.setLabelText(QString("Reconstruction in progress\nlevel: %1 [%2 thread(s)]").arg(s_params.depth).arg(s_params.threads));
		QApplication::processEvents();

		QFuture<bool> future;
			
		//run in a separate thread
		s_cloud = pc;
		if (withColors)
		{
			s_coloredMesh = &coloredMesh;
			future = QtConcurrent::run(doReconstructWithColors);
		}
		else
		{
			s_mesh = &mesh;
			future = QtConcurrent::run(doReconstruct);
		}

		//wait until process is finished!
		while (!future.isFinished())
		{
#if defined(CC_WINDOWS)
			::Sleep(500);
#else
			usleep(500 * 1000);
#endif

			pDlg.setValue(pDlg.value() + 1);
			QApplication::processEvents();
		}

		result = future.result();

		pDlg.hide();
		QApplication::processEvents();
	}

	if (result
		&&	(!s_mesh || s_mesh->polygonCount() > 0)
		&&	(!s_coloredMesh || s_coloredMesh->polygonCount() > 0))
	{
		unsigned nic = 0, noc = 0, nr_faces = 0;
		if (s_coloredMesh)
		{
			s_coloredMesh->resetIterator();
			nic			= static_cast<unsigned>(s_coloredMesh->inCorePoints.size());
			noc			= static_cast<unsigned>(s_coloredMesh->outOfCorePointCount());
			nr_faces	= static_cast<unsigned>(s_coloredMesh->polygonCount());
		}
		else //if (s_mesh)
		{
			s_mesh->resetIterator();
			nic			= static_cast<unsigned>(s_mesh->inCorePoints.size());
			noc			= static_cast<unsigned>(s_mesh->outOfCorePointCount());
			nr_faces	= static_cast<unsigned>(s_mesh->polygonCount());
		}
		unsigned nr_vertices = nic+noc;

		//end message
		m_app->dispToConsole(QString("[PoissonRecon] Job finished (%1 triangles, %2 vertices)").arg(nr_faces).arg(nr_vertices),ccMainAppInterface::STD_CONSOLE_MESSAGE);

		ccPointCloud* newPC = new ccPointCloud("vertices");
		ccMesh* newMesh = new ccMesh(newPC);
		newMesh->addChild(newPC);

		if (newPC->reserve(nr_vertices) && newMesh->reserve(nr_faces))
		{
			ccScalarField* densitySF = 0;
			if (s_params.density)
			{
				densitySF = new ccScalarField("Density");
				if (!densitySF->reserveSafe(nr_vertices))
				{
					m_app->dispToConsole(QString("[PoissonRecon] Failed to allocate memory for storing density!"),ccMainAppInterface::WRN_CONSOLE_MESSAGE);
					densitySF->release();
					densitySF = 0;
				}
			}

			if (s_coloredMesh)
			{
				bool importColors = newPC->reserveTheRGBTable();
				if (!importColors)
				{
					if (m_app)
						m_app->dispToConsole("Not enough memory to import colors!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
				}
				//add 'in core' points
				{
					for (unsigned i = 0; i < nic; i++)
					{
						ColoredVertex p = s_iXForm * s_coloredMesh->inCorePoints[i];
						CCVector3 p2(	static_cast<PointCoordinateType>(p.point.coords[0]),
										static_cast<PointCoordinateType>(p.point.coords[1]),
										static_cast<PointCoordinateType>(p.point.coords[2]) );
						newPC->addPoint(p2);

						if (importColors)
						{
							ccColor::Rgb C(	static_cast<ColorCompType>(std::min(255.0f, std::max<float>(p.color[0], 0.0))),
											static_cast<ColorCompType>(std::min(255.0f, std::max<float>(p.color[1], 0.0))),
											static_cast<ColorCompType>(std::min(255.0f, std::max<float>(p.color[2], 0.0))) );
							newPC->addRGBColor(C);
						}

						if (densitySF)
						{
							ScalarType sf = static_cast<ScalarType>(p.value);
							densitySF->addElement(sf);
						}
					}
				}
				//add 'out of core' points
				{
					for (unsigned i = 0; i < noc; i++)
					{
						ColoredVertex p;
						s_coloredMesh->nextOutOfCorePoint(p);
						p = s_iXForm * p;
						CCVector3 p2(	static_cast<PointCoordinateType>(p.point.coords[0]),
										static_cast<PointCoordinateType>(p.point.coords[1]),
										static_cast<PointCoordinateType>(p.point.coords[2]) );
						newPC->addPoint(p2);

						if (importColors)
						{
							ccColor::Rgb C(	static_cast<ColorCompType>(std::min(255.0f, std::max<float>(p.color[0], 0.0))),
											static_cast<ColorCompType>(std::min(255.0f, std::max<float>(p.color[1], 0.0))),
											static_cast<ColorCompType>(std::min(255.0f, std::max<float>(p.color[2], 0.0))) );
							newPC->addRGBColor(C);
						}

						if (densitySF)
						{
							ScalarType sf = static_cast<ScalarType>(p.value);
							densitySF->addElement(sf);
						}
					}
				}

				newPC->showColors(importColors);
			}
			else
			{
				//add 'in core' points
				{
					for (unsigned i = 0; i < nic; i++)
					{
						Vertex p = s_iXForm * s_mesh->inCorePoints[i];
						CCVector3 p2(	static_cast<PointCoordinateType>(p.point.coords[0]),
										static_cast<PointCoordinateType>(p.point.coords[1]),
										static_cast<PointCoordinateType>(p.point.coords[2]) );
						newPC->addPoint(p2);

						if (densitySF)
						{
							ScalarType sf = static_cast<ScalarType>(p.value);
							densitySF->addElement(sf);
						}
					}
				}
				//add 'out of core' points
				{
					for (unsigned i = 0; i < noc; i++)
					{
						Vertex p;
						s_mesh->nextOutOfCorePoint(p);
						p = s_iXForm * p;
						CCVector3 p2(	static_cast<PointCoordinateType>(p.point.coords[0]),
										static_cast<PointCoordinateType>(p.point.coords[1]),
										static_cast<PointCoordinateType>(p.point.coords[2]) );
						newPC->addPoint(p2);

						if (densitySF)
						{
							ScalarType sf = static_cast<ScalarType>(p.value);
							densitySF->addElement(sf);
						}
					}
				}
				newPC->showColors(false);
			}

			// density SF
			if (densitySF)
			{
				densitySF->computeMinAndMax();
				densitySF->showNaNValuesInGrey(false);
				int sfIdx = newPC->addScalarField(densitySF);
				newPC->setCurrentDisplayedScalarField(sfIdx);
				newPC->showSF(true);
				newMesh->showColors(newPC->colorsShown());
				newMesh->showSF(true);
			}

			//add faces
			{
				for (unsigned i = 0; i < nr_faces; i++)
				{
					std::vector<CoredVertexIndex> triangleIndexes;
					if (s_mesh)
						s_mesh->nextPolygon(triangleIndexes);
					else
						s_coloredMesh->nextPolygon(triangleIndexes);

					if (triangleIndexes.size() == 3)
					{
						for (std::vector<CoredVertexIndex>::iterator it = triangleIndexes.begin(); it != triangleIndexes.end(); ++it)
							if (!it->inCore)
								it->idx += nic;

						newMesh->addTriangle(	triangleIndexes[0].idx,
												triangleIndexes[1].idx,
												triangleIndexes[2].idx );
					}
					else
					{
						//Can't handle anything else than triangles yet!
						assert(false);
					}
				}
			}

			newMesh->setName(QString("Mesh[%1] (level %2)").arg(pc->getName()).arg(s_params.depth));
			newPC->setEnabled(false);
			newMesh->setVisible(true);
			newMesh->computeNormals(true);
			newMesh->showColors(newMesh->hasColors());

			//copy Global Shift & Scale information
			newPC->setGlobalShift(pc->getGlobalShift());
			newPC->setGlobalScale(pc->getGlobalScale());

			//output mesh
			m_app->addToDB(newMesh);
			m_app->setSelectedInDB(ent, false);
			m_app->setSelectedInDB(newMesh, true);
		}
		else
		{
			delete newMesh;
			newMesh = 0;
			m_app->dispToConsole("Not enough memory!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		}

		//currently selected entities parameters may have changed!
		m_app->updateUI();
		//currently selected entities appearance may have changed!
		m_app->refreshAll();
	}
	else
	{
		m_app->dispToConsole("Reconstruction failed!", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
	}

	s_cloud = 0;
	s_mesh = 0;
	s_coloredMesh = 0;
}