DGtalTools 2.0.0
Loading...
Searching...
No Matches
3dImplicitSurfaceExtractorByThickening.cpp
1
32#include <iostream>
33#include <map>
34#include "CLI11.hpp"
35
36#include "DGtal/base/Common.h"
37#include "DGtal/base/CountedPtr.h"
38#include "DGtal/helpers/StdDefs.h"
39#include "DGtal/math/MPolynomial.h"
40#include "DGtal/io/readers/MPolynomialReader.h"
41#include "DGtal/io/viewers/PolyscopeViewer.h"
42#include "DGtal/topology/KhalimskySpaceND.h"
43#include "DGtal/topology/CubicalComplex.h"
44#include "DGtal/topology/CubicalComplexFunctions.h"
45#include "DGtal/topology/SetOfSurfels.h"
46#include "DGtal/topology/DigitalSurface.h"
47#include "DGtal/topology/helpers/Surfaces.h"
48#include "DGtal/shapes/GaussDigitizer.h"
49#include "DGtal/shapes/Mesh.h"
50#include "DGtal/shapes/implicit/ImplicitPolynomial3Shape.h"
52
53using namespace std;
54using namespace DGtal;
55
56
57
118template <typename CellOutputIterator, typename DigitalSurface>
119void
120analyzeSurface( CellOutputIterator itSure, CellOutputIterator itUnsure, DigitalSurface surface )
121{
122 typedef typename DigitalSurface::KSpace KSpace;
123 typedef typename DigitalSurface::Surfel Surfel;
124 typedef typename DigitalSurface::ConstIterator ConstIterator;
125 typedef typename DigitalSurface::DigitalSurfaceContainer Container;
126 typedef typename DigitalSurface::DigitalSurfaceTracker Tracker;
127 typedef typename KSpace::Integer Integer;
128 typedef typename KSpace::Cell Cell;
129 const Dimension t = KSpace::dimension - 1;
130 const Container& C = surface.container();
131 const KSpace& K = surface.container().space();
132 Surfel s2;
133 for ( ConstIterator it = surface.begin(), itE = surface.end(); it != itE; ++it )
134 {
135 Surfel s = *it;
136 Cell is = K.unsigns( s );
137 Integer s_xt = K.sKCoord( s, t );
138 if ( s_xt == 0 ) *itUnsure++ = is;
139 else if ( s_xt == -1 )
140 {
141 CountedPtr<Tracker> tracker( C.newTracker( s ) );
142 if ( tracker->adjacent( s2, t, true ) != 0 )
143 {
144 Integer s2_xt = K.sKCoord( s2, t );
145 Cell ic = K.uIncident( is, t, true );
146 if ( s2_xt > 0 ) *itSure++ = ic;
147 else *itUnsure++ = ic;
148 }
149 }
150 else if ( s_xt == 1 )
151 {
152 CountedPtr<Tracker> tracker( C.newTracker( s ) );
153 if ( tracker->adjacent( s2, t, false ) != 0 )
154 {
155 Integer s2_xt = K.sKCoord( s2, t );
156 Cell ic = K.uIncident( is, t, false );
157 if ( s2_xt < 0 ) *itSure++ = ic;
158 else *itUnsure++ = ic;
159 }
160 }
161 else cout << " " << s_xt;
162 }
163}
164
173template <typename ImplicitSurface, typename RealPoint>
174RealPoint projectNewton( const ImplicitSurface & is,
175 RealPoint x,
176 typename RealPoint::Coordinate epsilon,
177 unsigned int max_iter )
178{
179 typedef typename RealPoint::Coordinate Scalar;
180 RealPoint gx;
181 Scalar f, g2;
182 Scalar eps2 = epsilon * epsilon;
183 while ( max_iter-- != 0 )
184 {
185 f = is( x );
186 if ( abs( f ) < epsilon ) return x;
187 gx = is.gradient( x );
188 g2 = gx.dot( gx );
189 if ( g2 < eps2 ) return x;
190 x -= (f/g2) * gx;
191 }
192 return x;
193}
194
195
196template <typename CubicalComplex3, typename ImplicitShape3,
197 typename ImplicitDigitalShape3>
198void projectComplex( std::vector< typename ImplicitShape3::RealPoint >& points,
199 const CubicalComplex3& complex3,
200 const ImplicitShape3& shape,
201 const ImplicitDigitalShape3& dshape,
202 double epsilon,
203 unsigned int max_iter,
204 double max_distance )
205{
206 typedef typename CubicalComplex3::Cell Cell3;
207 typedef typename CubicalComplex3::Point Point3;
208 typedef typename CubicalComplex3::CellMapConstIterator CellMapConstIterator;
209 typedef typename ImplicitShape3::RealPoint RealPoint3;
210 typedef typename ImplicitShape3::Ring Ring;
211 points.clear();
212 for ( CellMapConstIterator it = complex3.begin( 0 ), itE = complex3.end( 0 ); it != itE; ++it )
213 {
214 Cell3 cell = it->first;
215 Point3 dp = complex3.space().uKCoords( cell ) - Point3::diagonal( 1 );
216 RealPoint3 p = dshape->embed( dp ) / 2.0;
217 RealPoint3 q = projectNewton( shape, p, epsilon, max_iter );
218 double d = (p-q).norm();
219 if ( d > max_distance ) q = p + (q-p)*( max_distance / d );
220 points.push_back( q );
221 }
222}
223
224template <typename CubicalComplex3, typename ImplicitShape3,
225 typename ImplicitDigitalShape3>
226typename ImplicitShape3::Ring
227getValue( const CubicalComplex3& complex3,
228 const typename CubicalComplex3::Cell& cell,
229 const ImplicitShape3& shape,
230 const ImplicitDigitalShape3& dshape )
231{
232 typedef typename CubicalComplex3::Cell Cell3;
233 typedef typename CubicalComplex3::Cells Cells3;
234 typedef typename CubicalComplex3::Point Point3;
235 typedef typename ImplicitShape3::RealPoint RealPoint3;
236 typedef typename ImplicitShape3::Ring Ring;
237
238 Point3 dp = complex3.space().uKCoords( cell ) - Point3::diagonal( 1 );
239 RealPoint3 p = dshape->embed( dp ) / 2.0;
240 Ring v = shape( p );
241 return v;
242}
243
244
245template <typename CubicalComplex3, typename ImplicitShape3,
246 typename ImplicitDigitalShape3>
247void doNotProjectComplex( std::vector< typename ImplicitShape3::RealPoint >& points,
248 const CubicalComplex3& complex3,
249 const ImplicitShape3& shape,
250 const ImplicitDigitalShape3& dshape )
251{
252 typedef typename CubicalComplex3::Cell Cell3;
253 typedef typename CubicalComplex3::Point Point3;
254 typedef typename CubicalComplex3::CellMapConstIterator CellMapConstIterator;
255 typedef typename ImplicitShape3::RealPoint RealPoint3;
256 typedef typename ImplicitShape3::Ring Ring;
257 points.clear();
258 for ( CellMapConstIterator it = complex3.begin( 0 ), itE = complex3.end( 0 ); it != itE; ++it )
259 {
260 Cell3 cell = it->first;
261 Point3 dp = complex3.space().uKCoords( cell );
262 RealPoint3 p = dshape->embed( dp ) / 2.0;
263 points.push_back( p );
264 }
265}
266
267
268
269int main( int argc, char** argv )
270{
271 typedef int Integer;
272 typedef SpaceND<3,Integer> Space3;
273 typedef KhalimskySpaceND<3,Integer> KSpace3;
274 typedef KSpace3::Cell Cell3;
275 typedef std::map<Cell3, CubicalCellData> Map3;
276 // typedef boost::unordered_map<Cell3, CubicalCellData> Map3;
277 typedef CubicalComplex< KSpace3, Map3 > CC3;
278 typedef Space3::Point Point3;
279 typedef Space3::RealPoint RealPoint3;
280 typedef Space3::RealVector RealVector3;
281 typedef RealPoint3::Coordinate Ring;
282 typedef Ring Scalar;
283 typedef MPolynomial<3, Ring> Polynomial3;
284 typedef MPolynomialReader<3, Ring> Polynomial3Reader;
285 typedef ImplicitPolynomial3Shape<Space3> ImplicitShape3;
286 typedef GaussDigitizer< Space3, ImplicitShape3 >
287 ImplicitDigitalShape3;
288 typedef ImplicitDigitalShape3::Domain Domain3;
289 typedef CC3::CellMapIterator CellMapIterator;
290 typedef CC3::CellMapConstIterator CellMapConstIterator;
291 typedef CC3::Cells Cells3;
292
293 // parse command line using CLI ----------------------------------------------
294 CLI::App app;
295 string poly_str;
296 std::string outputFileName {"result.raw"};
297 DGtal::int64_t rescaleInputMin {0};
298 DGtal::int64_t rescaleInputMax {255};
299 Ring min_x {-10.0};
300 Ring max_x {10.0};
301 Ring h {1.0};
302 Ring t {1e-2};
303 std::string project {"Newton"};
304 double epsilon {1e-6};
305 unsigned int max_iter {500};
306 std::string view {"Normal"};
307
308 app.description( "Computes the zero level set of the given polynomial. Usage: 3dImplicitSurfaceExtractorByThickening -p <polynomial> [options]\n Example:\n 3dImplicitSurfaceExtractorByThickening -p \"x^2-y*z^2\" -g 0.1 -a -2 -A 2 -v Singular\n - whitney : x^2-y*z^2 \n - 4lines : x*y*(y-x)*(y-z*x) \n - cone : z^2-x^2-y^2 \n - simonU : x^2-z*y^2+x^4+y^4 \n - cayley3 : 4*(x^2 + y^2 + z^2) + 16*x*y*z - 1 \n - crixxi : -0.9*(y^2+z^2-1)^2-(x^2+y^2-1)^3 \n Some other examples (more difficult): \n 3dImplicitSurfaceExtractorByThickening -a -2 -A 2 -p \"((y^2+z^2-1)^2-(x^2+y^2-1)^3)*(y*(x-1)^2-z*(x+1))^2\" -g 0.025 -e 1e-6 -n 50000 -v Singular -t 0.5 -P Newton \n 3dImplicitSurfaceExtractorByThickening -a -2 -A 2 -p \"(x^5-4*z^3*y^2)*((x+y)^2-(z-x)^3)\" -g 0.025 -e 1e-6 -n 50000 -v Singular -t 0.05 -P Newton ");
309 app.add_option("-p,--polynomial,1", poly_str, "the implicit polynomial whose zero-level defines the shape of interest." )
310 ->required();
311 app.add_option("--minAABB,-a",min_x, "the min value of the AABB bounding box (domain)");
312 app.add_option("--maxAABB,-A",max_x, "the max value of the AABB bounding box (domain)" );
313 app.add_option("--gridstep,-g", h, "the gridstep that defines the digitization (often called h).");
314 app.add_option("--thickness,-t",t, "the thickening parameter for the implicit surface." );
315 app.add_option("--project,-P", project, "defines the projection: either No or Newton.")
316 -> check(CLI::IsMember({"No", "Newton"}));
317 app.add_option("--epsilon,-e", epsilon, "the maximum precision relative to the implicit surface in the Newton approximation of F=0.");
318 app.add_option("--max_iter,-n", max_iter, "the maximum number of iteration in the Newton approximation of F=0." );
319 app.add_option("--view,-v", view, "specifies if the surface is viewed as is (Normal) or if places close to singularities are highlighted (Singular), or if unsure places should not be displayed (Hide).")
320 -> check(CLI::IsMember({"Singular", "Normal", "Hide"}));
321
322 app.get_formatter()->column_width(40);
323 CLI11_PARSE(app, argc, argv);
324 // END parse command line using CLI ----------------------------------------------
325
326
327 //-------------- read polynomial and creating 3d implicit fct -----------------
328 trace.beginBlock( "Reading polynomial and creating 3D implicit function" );
329 Polynomial3 poly;
330 Polynomial3Reader reader;
331 string::const_iterator iter = reader.read( poly, poly_str.begin(), poly_str.end() );
332 if ( iter != poly_str.end() )
333 {
334 trace.error() << "ERROR reading polynomial: I read only <" << poly_str.substr( 0, iter - poly_str.begin() )
335 << ">, and I built P=" << poly << std::endl;
336 return 2;
337 }
338 // Creating implicit shape and storing it with smart pointer for automatic deallocation.
339 CountedPtr<ImplicitShape3> shape( new ImplicitShape3( poly ) );
340
341 RealPoint3 p1( min_x, min_x, min_x );
342 RealPoint3 p2( max_x, max_x, max_x );
343 // Creating digitized shape and storing it with smart pointer for automatic deallocation.
344 CountedPtr<ImplicitDigitalShape3> dshape( new ImplicitDigitalShape3() );
345 dshape->attach( *shape );
346 dshape->init( p1, p2, RealVector3( h, h, h ) );
347 Domain3 domain3 = dshape->getDomain();
348 KSpace3 K3;
349 K3.init( domain3.lowerBound(), domain3.upperBound(), true );
350 trace.info() << "- domain is " << domain3 << std::endl;
351 trace.endBlock();
352
353 //-------------- read polynomial and creating 3d implicit fct -----------------
354 trace.beginBlock( "Extracting thickened isosurface [-t,+t] of 3D polynomial. " );
355 CubicalCellData unsure_data( 0 );
356 CubicalCellData sure_data( CC3::FIXED );
357 CC3 complex3( K3 );
358 for ( Domain3::ConstIterator it = domain3.begin(), itE = domain3.end(); it != itE; ++it )
359 {
360 Cell3 spel = K3.uSpel( *it );
361 // RealPoint3 px = dshape->embed( *it );
362 RealPoint3 px = dshape->embed( K3.uKCoords( spel ) - Point3::diagonal( 1 ) ) / 2.0;
363 Ring s = (*shape)( px );
364 if ( (-t <= s ) && ( s <= t ) ) complex3.insertCell( spel, unsure_data );
365 }
366 trace.info() << "- K[-t,+t] = " << complex3 << endl;
367 complex3.close();
368 trace.info() << "- Cl K[-t,+t] = " << complex3 << endl;
369 std::vector<Cell3> separating_cells;
370 std::back_insert_iterator< std::vector<Cell3> > outItSurface( separating_cells );
371 Surfaces<KSpace3>::uWriteBoundary( outItSurface,
372 K3, *dshape, domain3.lowerBound(), domain3.upperBound() );
373 trace.info() << "- separating S = " << separating_cells.size() << " 2-cells." << endl;
374 complex3.insertCells( separating_cells.begin(), separating_cells.end(), sure_data );
375 for ( std::vector<Cell3>::const_iterator it = separating_cells.begin(), itE = separating_cells.end(); it != itE; ++it )
376 {
377 Cells3 bdry = K3.uFaces( *it );
378 for ( Cells3::const_iterator itBdry = bdry.begin(), itBdryE = bdry.end(); itBdry != itBdryE; ++itBdry )
379 complex3.insertCell( *itBdry, sure_data );
380 }
381 separating_cells.clear();
382 trace.info() << "- Cl K[-t,+t] + Cl S = " << complex3 << endl;
383 trace.endBlock();
384
385 //-------------- Get boundary and inner cells --------------------------------
386 trace.beginBlock( "Get boundary and inner cells. " );
387 std::vector<Cell3> inner;
388 std::vector<Cell3> bdry;
389 functions::filterCellsWithinBounds
390 ( complex3, K3.uKCoords( K3.lowerCell() ), K3.uKCoords( K3.upperCell() ),
391 std::back_inserter( bdry ), std::back_inserter( inner ) );
392 trace.info() << "- there are " << inner.size() << " inner cells." << endl;
393 trace.info() << "- there are " << bdry.size() << " boundary cells." << endl;
394 trace.endBlock();
395
396 //-------------- Compute priority function -----------------------------------
397 trace.beginBlock( "Compute priority function. " );
398 Dimension d = complex3.dim();
399 for ( Dimension i = 0; i <= d; ++i )
400 {
401 for ( CellMapIterator it = complex3.begin( i ), itE = complex3.end( i ); it != itE; ++it )
402 {
403 Cell3 cell = it->first;
404 Ring v = getValue( complex3, cell, *shape, dshape );
405 v = abs( 10000.0*v );
406 if ( v > 10000000.0 ) v = 10000000.0;
407 it->second.data &= ~CC3::VALUE;
408 it->second.data |= (DGtal::uint32_t) floor( v );
409 // std::cout << " " << it->second.data;
410 }
411 }
412 trace.endBlock();
413
414 //-------------- Collapse boundary -------------------------------------------
415 trace.beginBlock( "Collapse boundary. " );
416 typename CC3::DefaultCellMapIteratorPriority priority;
417 CC3 bdry_complex3( K3 );
418 for ( std::vector<Cell3>::const_iterator it = bdry.begin(), itE = bdry.end(); it != itE; ++it )
419 {
420 Cell3 cell = *it;
421 Dimension d = K3.uDim( cell );
422 CellMapConstIterator cmIt = complex3.findCell( d, cell );
423 bdry_complex3.insertCell( d, cell, cmIt->second );
424 }
425 trace.info() << "- [before collapse] K_bdry =" << bdry_complex3 << endl;
426 functions::collapse( bdry_complex3, bdry.begin(), bdry.end(), priority, true, true, false );
427 trace.info() << "- [after collapse] K_bdry =" << bdry_complex3 << endl;
428 for ( std::vector<Cell3>::const_iterator it = bdry.begin(), itE = bdry.end(); it != itE; ++it )
429 {
430 Cell3 cell = *it;
431 Dimension d = K3.uDim( cell );
432 CellMapConstIterator cmIt = bdry_complex3.findCell( d, cell );
433 if ( cmIt != bdry_complex3.end( d ) ) {
434 CellMapIterator cmIt2 = complex3.findCell( d, cell );
435 cmIt2->second = sure_data;
436 }
437 }
438 trace.endBlock();
439
440 //-------------- Collapse all -------------------------------------------
441 trace.beginBlock( "Collapse all. " );
442 std::copy( bdry.begin(), bdry.end(), std::back_inserter( inner ) );
443 functions::collapse( complex3, inner.begin(), inner.end(), priority, true, true, true );
444 trace.info() << "- K = " << complex3 << endl;
445 trace.endBlock();
446
447 //-------------- Project complex onto surface --------------------------------
448 trace.beginBlock( "Project complex onto surface. " );
449 std::vector<RealPoint3> points;
450 if ( project == "Newton" )
451 projectComplex( points, complex3, *shape, dshape, epsilon, max_iter, h * sqrt(3.0));
452 else
453 doNotProjectComplex( points, complex3, *shape, dshape );
454 trace.endBlock();
455
456 //-------------- Create Mesh -------------------------------------------
457 trace.beginBlock( "Create Mesh. " );
458 bool highlight = ( view == "Singular" );
459 bool hide = ( view == "Hide" );
460 Mesh<RealPoint3> mesh( true );
461 std::map<Cell3,unsigned int> indices;
462 int idx = 0;
463 for ( CellMapConstIterator it = complex3.begin( 0 ), itE = complex3.end( 0 ); it != itE; ++it, ++idx )
464 {
465 Cell3 cell = it->first;
466 indices[ cell ] = idx;
467 mesh.addVertex( points[ idx ] );
468 }
469 for ( CellMapConstIterator it = complex3.begin( 2 ), itE = complex3.end( 2 ); it != itE; ++it )
470 {
471 Cell3 cell = it->first;
472 bool fixed = it->second.data & CC3::FIXED;
473 Cells3 bdry = complex3.cellBoundary( cell, true );
474 std::vector<unsigned int> face_idx;
475 for ( Cells3::const_iterator itC = bdry.begin(), itCE = bdry.end(); itC != itCE; ++itC )
476 {
477 if ( complex3.dim( *itC ) == 0 )
478 face_idx.push_back( indices[ *itC ] );
479 }
480 if ( ( ! fixed ) && hide ) continue;
481 Color color = highlight
482 ? ( fixed ? Color::White : Color(128,255,128) )
483 : Color::White;
484 RealVector3 diag03 = points[ face_idx[ 0 ] ] - points[ face_idx[ 3 ] ];
485 RealVector3 diag12 = points[ face_idx[ 1 ] ] - points[ face_idx[ 2 ] ];
486 if ( diag03.dot( diag03 ) <= diag12.dot( diag12 ) )
487 {
488 mesh.addTriangularFace( face_idx[ 0 ], face_idx[ 1 ], face_idx[ 3 ], color );
489 mesh.addTriangularFace( face_idx[ 0 ], face_idx[ 3 ], face_idx[ 2 ], color );
490 }
491 else
492 {
493 mesh.addTriangularFace( face_idx[ 0 ], face_idx[ 1 ], face_idx[ 2 ], color );
494 mesh.addTriangularFace( face_idx[ 1 ], face_idx[ 3 ], face_idx[ 2 ], color );
495 }
496 //mesh.addQuadFace( face_idx[ 0 ], face_idx[ 1 ], face_idx[ 3 ], face_idx[ 2 ], color );
497 }
498 trace.endBlock();
499
500 //-------------- View surface -------------------------------------------
501 PolyscopeViewer<Space3,KSpace3> viewer( K3 );
502 viewer << mesh;
503 // Display lines that are not in the mesh.
504 for ( CellMapConstIterator it = complex3.begin( 1 ), itE = complex3.end( 1 ); it != itE; ++it )
505 {
506 Cell3 cell = it->first;
507 bool fixed = it->second.data & CC3::FIXED;
508 std::vector<Cell3> dummy;
509 std::back_insert_iterator< std::vector<Cell3> > outIt( dummy );
510 complex3.directCoFaces( outIt, cell );
511 if ( ! dummy.empty() ) continue;
512
513 Cells3 bdry = complex3.cellBoundary( cell, true );
514 Cell3 v0 = *(bdry.begin() );
515 Cell3 v1 = *(bdry.begin() + 1);
516 if ( ( ! fixed ) && hide ) continue;
517 Color color = highlight
518 ? ( fixed ? Color::White : Color(128,255,128) )
519 : Color::White;
520 viewer.drawColor( color );
521 viewer.drawLine( points[ indices[ v0 ] ], points[ indices[ v1 ] ]);
522 }
523 viewer.show();
524 return 0;
525}
Definition ATu0v1.h:57