Debian Codegraph @

src/thirdparty/PoissonRecon/Reconstruction.example.cpp

raw
1 /*
2 Copyright (c) 2023, Michael Kazhdan
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8 Redistributions of source code must retain the above copyright notice, this list of
9 conditions and the following disclaimer. Redistributions in binary form must reproduce
10 the above copyright notice, this list of conditions and the following disclaimer
11 in the documentation and/or other materials provided with the distribution.
12
13 Neither the name of the Johns Hopkins University nor the names of its contributors
14 may be used to endorse or promote products derived from this software without specific
15 prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
18 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
20 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
22 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 DAMAGE.
27 */
28
29 #include "PreProcessor.h"
30 #include "Reconstructors.h"
31 #include "Extrapolator.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <random>
37 #include <iostream>
38 #include <fstream>
39 #include "MyMiscellany.h"
40 #include "CmdLineParser.h"
41
42 using namespace PoissonRecon;
43
44 CmdLineParameter< char* > Out( "out" );
45 CmdLineReadable SSDReconstruction( "ssd" ) , EvaluateImplicit( "evaluate" ) , Verbose( "verbose" );
46 CmdLineParameter< int > Depth( "depth" , 8 ) , SampleNum( "samples" , 100000 ) , ColorMode( "color" , 0 );
47
48 CmdLineReadable* params[] = { &Out , &SSDReconstruction , &ColorMode , &Verbose , &Depth , &SampleNum , &EvaluateImplicit , nullptr };
49
50 void ShowUsage( char* ex )
51 {
52 printf( "Usage: %s\n" , ex );
53 printf( "\t --%s <number of samples>\n" , SampleNum.name );
54 printf( "\t[--%s <ouput mesh>]\n" , Out.name );
55 printf( "\t[--%s <reconstruction depth>=%d]\n" , Depth.name , Depth.value );
56 printf( "\t[--%s <color mode>=%d]\n" , ColorMode.name , ColorMode.value );
57 printf( "\t\t0] No color\n" );
58 printf( "\t\t1] Jointly extrapolated color\n" );
59 printf( "\t\t2] Independently extrapolated color\n" );
60 printf( "\t[--%s]\n" , SSDReconstruction.name );
61 printf( "\t[--%s]\n" , EvaluateImplicit.name );
62 printf( "\t[--%s]\n" , Verbose.name );
63 }
64
65 // A simple structure for representing colors.
66 // Assuming values are in the range [0,1].
67 template< typename Real >
68 struct RGBColor
69 {
70 // The channels
71 RGBColor( Real r=0 , Real g=0 , Real b=0 ) : r(r) , g(g) , b(b){}
72 Real r,g,b;
73
74 // Methods supporting affine re-combination
75 RGBColor &operator += ( const RGBColor &c ){ r += c.r , g += c.g , b += c.b ; return *this; }
76 RGBColor &operator *= ( Real s ){ r *= s , g *= s , b *= s ; return *this; }
77 RGBColor &operator /= ( Real s ){ return operator *= (1/s); }
78
79 RGBColor operator + ( const RGBColor &c ) const { return RGBColor( r+c.r , g+c.g , b+c.b ); }
80 RGBColor operator * ( Real s ) const { return RGBColor( r*s , g*s , b*s ); }
81 RGBColor operator / ( Real s ) const { return operator * (1/s); }
82 };
83
84 namespace PoissonRecon
85 {
86 template< typename Real >
87 struct Atomic< RGBColor< Real > >
88 {
89 static void Add( volatile RGBColor< Real > &a , const RGBColor< Real > & b )
90 {
91 Atomic< Real >::Add( a.r , b.r );
92 Atomic< Real >::Add( a.g , b.g );
93 Atomic< Real >::Add( a.b , b.b );
94 }
95 };
96 }
97
98 // A stream for generating random oriented samples on the sphere
99 template< typename Real , unsigned int Dim >
100 struct SphereOrientedSampleStream : public Reconstructor::InputOrientedSampleStream< Real , Dim >
101 {
102 // from https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
103 std::random_device randomDevice;
104 std::default_random_engine generator;
105 std::uniform_real_distribution< Real > distribution;
106
107 // Constructs a stream that contains the specified number of samples
108 SphereOrientedSampleStream( unsigned int sz ) : _size(sz) , _current(0) , generator(0) , distribution((Real)-1.0,(Real)1.0) {}
109
110 // Overrides the pure abstract method from InputOrientedSampleStream< Real , Dim >
111 void reset( void ){ generator.seed(0) ; _current = 0; }
112
113 // Overrides the pure abstract method from InputOrientedSampleStream< Real , Dim >
114 bool read( Point< Real , Dim > &p , Point< Real , Dim > &n )
115 {
116 if( _current<_size )
117 {
118 p = n = RandomSpherePoint( generator , distribution );
119 _current++;
120 return true;
121 }
122 else return false;
123 }
124
125 static Point< Real , Dim > RandomSpherePoint( std::default_random_engine &generator , std::uniform_real_distribution< Real > &distribution )
126 {
127 while( true )
128 {
129 Point< Real , Dim > p;
130 for( unsigned int d=0 ; d<Dim ; d++ ) p[d] = distribution( generator );
131 if( Point< Real , Dim >::SquareNorm( p )<1 ) return p / (Real)sqrt( Point< Real , Dim >::SquareNorm(p) );
132 }
133 }
134 protected:
135 unsigned int _size , _current;
136 };
137
138 // A stream for generating random oriented samples with color on the sphere
139 template< typename Real , unsigned int Dim >
140 struct SphereOrientedSampleWithColorStream : public Reconstructor::InputOrientedSampleStream< Real , Dim , RGBColor< Real > >
141 {
142 // from https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
143 std::random_device randomDevice;
144 std::default_random_engine generator;
145 std::uniform_real_distribution< Real > distribution;
146
147 // Constructs a stream that contains the specified number of samples
148 SphereOrientedSampleWithColorStream( unsigned int sz ) : _size(sz) , _current(0) , generator(0) , distribution((Real)-1.0,(Real)1.0) {}
149
150 // Overrides the pure abstract method from InputOrientedSampleStream< Real , Dim , RGBColor< Real > >
151 void reset( void ){ generator.seed(0) ; _current = 0; }
152
153 // Overrides the pure abstract method from InputOrientedSampleStream< Real , Dim , RGBColor< Real > >
154 bool read( Point< Real , Dim > &p , Point< Real , Dim > &n , RGBColor< Real > &c )
155 {
156 if( _current<_size )
157 {
158 p = n = RandomSpherePoint( generator , distribution );
159 _current++;
160 c.r = c.g = c.b = 0;
161 if ( p[0]<-1.f/3 ) c.r = 1.f;
162 else if( p[0]< 1.f/3 ) c.g = 1.f;
163 else c.b = 1.f;
164 return true;
165 }
166 else return false;
167 }
168
169 static Point< Real , Dim > RandomSpherePoint( std::default_random_engine &generator , std::uniform_real_distribution< Real > &distribution )
170 {
171 while( true )
172 {
173 Point< Real , Dim > p;
174 for( unsigned int d=0 ; d<Dim ; d++ ) p[d] = distribution( generator );
175 if( Point< Real , Dim >::SquareNorm( p )<1 ) return p / (Real)sqrt( Point< Real , Dim >::SquareNorm(p) );
176 }
177 }
178 protected:
179 unsigned int _size , _current;
180 };
181
182 // A stream for generating random samples with color on the sphere
183 template< typename Real , unsigned int Dim >
184 struct SphereSampleWithColorStream : public Reconstructor::InputSampleStream< Real , Dim , RGBColor< Real > >
185 {
186 // from https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
187 std::random_device randomDevice;
188 std::default_random_engine generator;
189 std::uniform_real_distribution< Real > distribution;
190
191 // Constructs a stream that contains the specified number of samples
192 SphereSampleWithColorStream( unsigned int sz ) : _size(sz) , _current(0) , generator(0) , distribution((Real)-1.0,(Real)1.0) {}
193
194 // Overrides the pure abstract method from InputSampleStream< Real , Dim , RGBColor< Real > >
195 void reset( void ){ generator.seed(0) ; _current = 0; }
196
197 // Overrides the pure abstract method from InputSampleStream< Real , Dim , RGBColor< Real > >
198 bool read( Point< Real , Dim > &p , RGBColor< Real > &c )
199 {
200 if( _current<_size )
201 {
202 p = RandomSpherePoint( generator , distribution );
203 _current++;
204 c.r = c.g = c.b = 0;
205 if ( p[0]<-1.f/3 ) c.r = 1.f;
206 else if( p[0]< 1.f/3 ) c.g = 1.f;
207 else c.b = 1.f;
208 return true;
209 }
210 else return false;
211 }
212
213 static Point< Real , Dim > RandomSpherePoint( std::default_random_engine &generator , std::uniform_real_distribution< Real > &distribution )
214 {
215 while( true )
216 {
217 Point< Real , Dim > p;
218 for( unsigned int d=0 ; d<Dim ; d++ ) p[d] = distribution( generator );
219 if( Point< Real , Dim >::SquareNorm( p )<1 ) return p / (Real)sqrt( Point< Real , Dim >::SquareNorm(p) );
220 }
221 }
222 protected:
223 unsigned int _size , _current;
224 };
225
226 // A stream into which we can write polygons of the form std::vector< node_index_type >
227 template< typename Index >
228 struct PolygonStream : public Reconstructor::OutputFaceStream< 2 >
229 {
230 // Construct a stream that adds polygons to the vector of polygons
231 PolygonStream( std::vector< std::vector< Index > > &polygonStream ) : _polygons( polygonStream ) {}
232
233 // Override the pure abstract method from OutputPolygonStream
234 size_t size( void ) const { return _polygons.size(); }
235 size_t write( const std::vector< node_index_type > &polygon )
236 {
237 std::vector< Index > poly( polygon.size() );
238 for( unsigned int i=0 ; i<polygon.size() ; i++ ) poly[i] = (Index)polygon[i];
239 _polygons.push_back( poly );
240 return _polygons.size()-1;
241 }
242 protected:
243 std::vector< std::vector< Index > > &_polygons;
244 };
245
246 // A stream into which we can write the output vertices of the extracted mesh
247 template< typename Real , unsigned int Dim >
248 struct VertexStream : public Reconstructor::OutputLevelSetVertexStream< Real , Dim >
249 {
250 // Construct a stream that adds vertices into the coordinates
251 VertexStream( std::vector< Real > &vCoordinates ) : _vCoordinates( vCoordinates ) {}
252
253 // Override the pure abstract methods from Reconstructor::OutputLevelSetVertexStream< Real , Dim >
254 size_t size( void ) const { return _vCoordinates.size()/3; }
255 size_t write( const Point< Real , Dim > &p , const Point< Real , Dim > & , const Real & ){ for( unsigned int d=0 ; d<Dim ; d++ ) _vCoordinates.push_back( p[d] ); return _vCoordinates.size()/3-1; }
256 protected:
257 std::vector< Real > &_vCoordinates;
258 };
259
260 // A stream into which we can write the output vertices and colors of the extracted mesh
261 template< typename Real , unsigned int Dim >
262 struct VertexWithColorStream : public Reconstructor::OutputLevelSetVertexStream< Real , Dim , RGBColor< Real > >
263 {
264 // Construct a stream that adds vertices into the coordinates
265 VertexWithColorStream( std::vector< Real > &vCoordinates , std::vector< Real > &rgbCoordinates ) :
266 _vCoordinates( vCoordinates ) , _rgbCoordinates( rgbCoordinates ) {}
267
268 // Override the pure abstract methods from Reconstructor::OutputLevelSetVertexStream< Real , Dim >
269 size_t size( void ) const { return _vCoordinates.size()/3; }
270 size_t write( const Point< Real , Dim > &p , const Point< Real , Dim > & , const Real & , const RGBColor< Real > &c )
271 {
272 for( unsigned int d=0 ; d<Dim ; d++ ) _vCoordinates.push_back( p[d] );
273 _rgbCoordinates.push_back( c.r );
274 _rgbCoordinates.push_back( c.g );
275 _rgbCoordinates.push_back( c.b );
276 return _rgbCoordinates.size()/3-1;
277 }
278 protected:
279 std::vector< Real > &_vCoordinates;
280 std::vector< Real > &_rgbCoordinates;
281 };
282
283 template< typename Real >
284 void WritePly( std::string fileName , size_t vNum , const Real *vCoordinates , const Real *rgbCoordinates , const std::vector< std::vector< int > > &polygons )
285 {
286 std::fstream file( fileName , std::ios::out );
287 file << "ply" << std::endl;
288 file << "format ascii 1.0" << std::endl;
289 file << "element vertex " << vNum << std::endl;
290 file << "property float x" << std::endl << "property float y" << std::endl << "property float z" << std::endl;
291 if( rgbCoordinates ) file << "property uchar red" << std::endl << "property uchar green" << std::endl << "property uchar blue" << std::endl;
292 file << "element face " << polygons.size() << std::endl;
293 file << "property list uchar int vertex_indices" << std::endl;
294 file << "end_header" << std::endl;
295
296 auto ColorChannel = []( Real v ){ return std::max<int>( 0 , std::min<int>( 255 , (int)floor(255*v+0.5) ) ); };
297
298 for( size_t i=0 ; i<vNum ; i++ )
299 {
300 file << vCoordinates[3*i+0] << " " << vCoordinates[3*i+1] << " " << vCoordinates[3*i+2];
301 if( rgbCoordinates ) file << " " << ColorChannel( rgbCoordinates[3*i+0] ) << " " << ColorChannel( rgbCoordinates[3*i+1] ) << " " << ColorChannel( rgbCoordinates[3*i+2] );
302 file << std::endl;
303 }
304 for( const auto &polygon : polygons )
305 {
306 file << polygon.size();
307 for( auto vIdx : polygon ) file << " " << vIdx;
308 file << std::endl;
309 }
310 }
311
312 template
313 <
314 typename Real , // Arithmetic type (float or double)
315 unsigned int Dim , // Dimensionality of the reconstruction (=3)
316 typename ReconType , // Reconstructor type (Reconstructor::Poisson or Reconstructor::SSD)
317 bool UseColor // Should color be reconstructed as well?
318 >
319 void Execute( void )
320 {
321 // The 1D finite-elements signature
322 static const unsigned int FEMSig = FEMDegreeAndBType< ReconType::DefaultFEMDegree , ReconType::DefaultFEMBoundary >::Signature;
323
324 // The tensor-product finite-elements signatures
325 using FEMSigs = IsotropicUIntPack< Dim , FEMSig >;
326
327 // Parameters for performing the reconstruction
328 typename ReconType::template SolutionParameters< Real > solverParams;
329
330 solverParams.verbose = Verbose.set;
331 solverParams.depth = (unsigned int)Depth.value;
332
333 // Parameters for exracting the level-set surface
334 Reconstructor::LevelSetExtractionParameters extractionParams;
335 extractionParams.linearFit = SSDReconstruction.set; // Since the SSD solution approximates a TSDF, linear fitting works well
336 extractionParams.verbose = Verbose.set;
337
338 // The type of the reconstructor
339 using Implicit = std::conditional_t< UseColor , typename Reconstructor::template Implicit< Real , Dim , FEMSigs , RGBColor< Real > > , typename Reconstructor::template Implicit< Real , Dim , FEMSigs > >;
340
341 // The solver type
342 using Solver = std::conditional_t< UseColor , typename ReconType::template Solver < Real , Dim , FEMSigs , RGBColor< Real > > , typename ReconType::template Solver < Real , Dim , FEMSigs > >;
343
344 // Functionality for evaluating at a single point
345 auto _Evaluate = []( typename Implicit::Evaluator &evaluator , Point< double , Dim > p )
346 {
347 try{ std::cout << "\tValue/Gradient @ " << p << ": " << evaluator(p) << " / " << evaluator.grad(p) << std::endl; }
348 catch( typename Implicit::Evaluator::OutOfUnitCubeException &e ){ std::cout << e.what() << std::endl; }
349 };
350
351 // Functionality for evaluating at interior/exterior/boundary points
352 auto Evaluate = [&_Evaluate]( const Implicit &implicit )
353 {
354 typename Implicit::Evaluator evaluator = implicit.evaluator();
355 std::cout << "Evaluating interior:" << std::endl;
356 _Evaluate( evaluator , Point< Real , Dim >( (Real)0.0 , (Real)0.0 , (Real)0.0 ) );
357 std::cout << "Evaluating exterior: " << std::endl;
358 _Evaluate( evaluator , Point< Real , Dim >( (Real)1.0 , (Real)1.0 , (Real)1.0 ) );
359 std::cout << "Evaluating boundary: " << std::endl;
360 _Evaluate( evaluator , Point< Real , Dim >( (Real)1.0 , (Real)1.0 , (Real)1.0 )/(Real)sqrt(3.) );
361 };
362
363 if constexpr( UseColor )
364 {
365 // A stream generating random oriented points on the sphere with color
366 SphereOrientedSampleWithColorStream< Real , Dim > sampleStream( SampleNum.value );
367
368 // Construct the implicit representation
369 Implicit *implicit = Solver::Solve( sampleStream , solverParams , RGBColor< Real >() );
370
371 // vectors for storing the polygons (specifically, triangles), the coordinates of the vertices, and the colors at the vertices
372 std::vector< std::vector< int > > polygons;
373 std::vector< Real > vCoordinates , rgbCoordinates;
374
375 // Streams backed by these vectors
376 VertexWithColorStream< Real , Dim > vStream( vCoordinates , rgbCoordinates );
377 PolygonStream< int > pStream( polygons );
378
379 // Extract the iso-surface
380 implicit->extractLevelSet( vStream , pStream , extractionParams );
381
382 // Write out the level-set
383 if( Out.set ) WritePly( Out.value , vStream.size() , vCoordinates.data() , rgbCoordinates.data() , polygons );
384
385 // Evaluate the implicit function
386 if( EvaluateImplicit.set ) Evaluate(*implicit);
387
388 delete implicit;
389 }
390 else
391 {
392 // A stream generating random oriented points on the sphere
393 SphereOrientedSampleStream< Real , Dim > sampleStream( SampleNum.value );
394
395 // Construct the implicit representation
396 Implicit *implicit = Solver::Solve( sampleStream , solverParams );
397
398 // vectors for storing the polygons (specifically, triangles) and the coordinates of the vertices
399 std::vector< std::vector< int > > polygons;
400 std::vector< Real > vCoordinates;
401
402 // Streams backed by these vectors
403 PolygonStream< int > pStream( polygons );
404 VertexStream< Real , Dim > vStream( vCoordinates );
405
406 // Extract the iso-surface
407 implicit->extractLevelSet( vStream , pStream , extractionParams );
408
409 if( ColorMode.value==0 )
410 {
411 // Write out the level-set
412 if( Out.set ) WritePly( Out.value , vStream.size() , vCoordinates.data() , (Real*)nullptr , polygons );
413 }
414 else
415 {
416 // A stream generating random points on the sphere with color
417 SphereSampleWithColorStream< Real , Dim > sampleStream( SampleNum.value );
418
419 // Parameters for performing the extrapolation
420 typename Extrapolator::Implicit< Real , Dim , RGBColor< Real > >::Parameters eParams;
421 eParams.verbose = Verbose.set;
422 eParams.depth = Depth.value+1;
423
424 // The extrapolated color field
425 Extrapolator::Implicit< Real , Dim , RGBColor< Real > > extrapolator( sampleStream , eParams , RGBColor< Real >() );
426
427 // The sampled colors
428 std::vector< Real > rgbCoordinates( vCoordinates.size()/Dim*3 );
429
430 // Iterate over the vertices and evaluate the extrapolate to get the color values
431 ThreadPool::ParallelFor( 0 , vCoordinates.size()/Dim , [&]( unsigned int thread , size_t i )
432 {
433 Point< Real , Dim > p;
434 for( unsigned int d=0 ; d<Dim ; d++ ) p[d] = vCoordinates[ i*Dim+d ];
435 RGBColor< Real > c = extrapolator( thread , p );
436 rgbCoordinates[i*3+0] = c.r , rgbCoordinates[i*3+1] = c.g , rgbCoordinates[i*3+2] = c.b;
437 } );
438
439 // Write out the level-set with sampled colors
440 if( Out.set ) WritePly( Out.value , vStream.size() , vCoordinates.data() , rgbCoordinates.data() , polygons );
441 }
442
443 // Evaluate the implicit function
444 if( EvaluateImplicit.set ) Evaluate(*implicit);
445
446 delete implicit;
447 }
448 }
449
450 int main( int argc , char* argv[] )
451 {
452 Timer timer;
453 CmdLineParse( argc-1 , &argv[1] , params );
454 ThreadPool::ParallelizationType= (ThreadPool::ParallelType)0;
455
456 if( !SampleNum.set )
457 {
458 ShowUsage( argv[0] );
459 return 0;
460 }
461
462 if( Verbose.set )
463 {
464 std::cout << "****************************************************" << std::endl;
465 std::cout << "****************************************************" << std::endl;
466 std::cout << "** Running Reconstruction Example (Version " << ADAPTIVE_SOLVERS_VERSION << ") **" << std::endl;
467 std::cout << "****************************************************" << std::endl;
468 std::cout << "****************************************************" << std::endl;
469 }
470
471 // Solve using single float precision, in dimension 3, w/ finite-elements of degree 2 for SSD and degree 1 for Poisson, and using Neumann boundaries
472 if( SSDReconstruction.set )
473 if( ColorMode.value==1 ) Execute< float , 3 , Reconstructor::SSD , true >();
474 else Execute< float , 3 , Reconstructor::SSD , false >();
475 else
476 if( ColorMode.value==1 ) Execute< float , 3 , Reconstructor::Poisson , true >();
477 else Execute< float , 3 , Reconstructor::Poisson , false >();
478
479 if( Verbose.set )
480 {
481 printf( "Time (Wall/CPU): %.2f / %.2f\n" , timer.wallTime() , timer.cpuTime() );
482 printf( "Peak Memory (MB): %d\n" , MemoryInfo::PeakMemoryUsageMB() );
483 }
484
485 return EXIT_SUCCESS;
486 }