SelfIntersectMesh.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #ifndef IGL_COPYLEFT_CGAL_SELFINTERSECTMESH_H
  9. #define IGL_COPYLEFT_CGAL_SELFINTERSECTMESH_H
  10. #include "CGAL_includes.hpp"
  11. #include "RemeshSelfIntersectionsParam.h"
  12. #include "../../unique.h"
  13. #include <Eigen/Dense>
  14. #include <list>
  15. #include <map>
  16. #include <vector>
  17. #include <thread>
  18. #include <mutex>
  19. //#define IGL_SELFINTERSECTMESH_DEBUG
  20. #ifndef IGL_FIRST_HIT_EXCEPTION
  21. #define IGL_FIRST_HIT_EXCEPTION 10
  22. #endif
  23. // The easiest way to keep track of everything is to use a class
  24. namespace igl
  25. {
  26. namespace copyleft
  27. {
  28. namespace cgal
  29. {
  30. // Kernel is a CGAL kernel like:
  31. // CGAL::Exact_predicates_inexact_constructions_kernel
  32. // or
  33. // CGAL::Exact_predicates_exact_constructions_kernel
  34. template <
  35. typename Kernel,
  36. typename DerivedV,
  37. typename DerivedF,
  38. typename DerivedVV,
  39. typename DerivedFF,
  40. typename DerivedIF,
  41. typename DerivedJ,
  42. typename DerivedIM>
  43. class SelfIntersectMesh
  44. {
  45. typedef
  46. SelfIntersectMesh<
  47. Kernel,
  48. DerivedV,
  49. DerivedF,
  50. DerivedVV,
  51. DerivedFF,
  52. DerivedIF,
  53. DerivedJ,
  54. DerivedIM> Self;
  55. public:
  56. // 3D Primitives
  57. typedef CGAL::Point_3<Kernel> Point_3;
  58. typedef CGAL::Segment_3<Kernel> Segment_3;
  59. typedef CGAL::Triangle_3<Kernel> Triangle_3;
  60. typedef CGAL::Plane_3<Kernel> Plane_3;
  61. typedef CGAL::Tetrahedron_3<Kernel> Tetrahedron_3;
  62. //typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;
  63. //typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron_3;
  64. // 2D Primitives
  65. typedef CGAL::Point_2<Kernel> Point_2;
  66. typedef CGAL::Segment_2<Kernel> Segment_2;
  67. typedef CGAL::Triangle_2<Kernel> Triangle_2;
  68. // 2D Constrained Delaunay Triangulation types
  69. typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2;
  70. typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTFB_2;
  71. typedef CGAL::Triangulation_data_structure_2<TVB_2,CTFB_2> TDS_2;
  72. typedef CGAL::Exact_intersections_tag Itag;
  73. typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel,TDS_2,Itag>
  74. CDT_2;
  75. typedef CGAL::Constrained_triangulation_plus_2<CDT_2> CDT_plus_2;
  76. // Axis-align boxes for all-pairs self-intersection detection
  77. typedef std::vector<Triangle_3> Triangles;
  78. typedef typename Triangles::iterator TrianglesIterator;
  79. typedef typename Triangles::const_iterator TrianglesConstIterator;
  80. typedef
  81. CGAL::Box_intersection_d::Box_with_handle_d<double,3,TrianglesIterator>
  82. Box;
  83. // Input mesh
  84. const Eigen::PlainObjectBase<DerivedV> & V;
  85. const Eigen::PlainObjectBase<DerivedF> & F;
  86. // Number of self-intersecting triangle pairs
  87. typedef typename DerivedF::Index Index;
  88. Index count;
  89. typedef std::vector<std::pair<Index, CGAL::Object>> ObjectList;
  90. // Using a vector here makes this **not** output sensitive
  91. Triangles T;
  92. typedef std::vector<Index> IndexList;
  93. IndexList lIF;
  94. // #F-long list of faces with intersections mapping to the order in
  95. // which they were first found
  96. std::map<Index,ObjectList> offending;
  97. // Make a short name for the edge map's key
  98. typedef std::pair<Index,Index> EMK;
  99. // Make a short name for the type stored at each edge, the edge map's
  100. // value
  101. typedef std::vector<Index> EMV;
  102. // Make a short name for the edge map
  103. typedef std::map<EMK,EMV> EdgeMap;
  104. // Maps edges of offending faces to all incident offending faces
  105. //EdgeMap edge2faces;
  106. std::vector<std::pair<const Box, const Box> > candidate_box_pairs;
  107. public:
  108. RemeshSelfIntersectionsParam params;
  109. public:
  110. // Constructs (VV,FF) a new mesh with self-intersections of (V,F)
  111. // subdivided
  112. //
  113. // See also: remesh_self_intersections.h
  114. inline SelfIntersectMesh(
  115. const Eigen::PlainObjectBase<DerivedV> & V,
  116. const Eigen::PlainObjectBase<DerivedF> & F,
  117. const RemeshSelfIntersectionsParam & params,
  118. Eigen::PlainObjectBase<DerivedVV> & VV,
  119. Eigen::PlainObjectBase<DerivedFF> & FF,
  120. Eigen::PlainObjectBase<DerivedIF> & IF,
  121. Eigen::PlainObjectBase<DerivedJ> & J,
  122. Eigen::PlainObjectBase<DerivedIM> & IM);
  123. private:
  124. // Helper function to mark a face as offensive
  125. //
  126. // Inputs:
  127. // f index of face in F
  128. inline void mark_offensive(const Index f);
  129. // Helper function to count intersections between faces
  130. //
  131. // Input:
  132. // fa index of face A in F
  133. // fb index of face B in F
  134. inline void count_intersection( const Index fa, const Index fb);
  135. // Helper function for box_intersect. Intersect two triangles A and B,
  136. // append the intersection object (point,segment,triangle) to a running
  137. // list for A and B
  138. //
  139. // Inputs:
  140. // A triangle in 3D
  141. // B triangle in 3D
  142. // fa index of A in F (and key into offending)
  143. // fb index of B in F (and key into offending)
  144. // Returns true only if A intersects B
  145. //
  146. inline bool intersect(
  147. const Triangle_3 & A,
  148. const Triangle_3 & B,
  149. const Index fa,
  150. const Index fb);
  151. // Helper function for box_intersect. In the case where A and B have
  152. // already been identified to share a vertex, then we only want to add
  153. // possible segment intersections. Assumes truly duplicate triangles are
  154. // not given as input
  155. //
  156. // Inputs:
  157. // A triangle in 3D
  158. // B triangle in 3D
  159. // fa index of A in F (and key into offending)
  160. // fb index of B in F (and key into offending)
  161. // va index of shared vertex in A (and key into offending)
  162. // vb index of shared vertex in B (and key into offending)
  163. //// Returns object of intersection (should be Segment or point)
  164. // Returns true if intersection (besides shared point)
  165. //
  166. inline bool single_shared_vertex(
  167. const Triangle_3 & A,
  168. const Triangle_3 & B,
  169. const Index fa,
  170. const Index fb,
  171. const Index va,
  172. const Index vb);
  173. // Helper handling one direction
  174. inline bool single_shared_vertex(
  175. const Triangle_3 & A,
  176. const Triangle_3 & B,
  177. const Index fa,
  178. const Index fb,
  179. const Index va);
  180. // Helper function for box_intersect. In the case where A and B have
  181. // already been identified to share two vertices, then we only want to add
  182. // a possible coplanar (Triangle) intersection. Assumes truly degenerate
  183. // facets are not givin as input.
  184. inline bool double_shared_vertex(
  185. const Triangle_3 & A,
  186. const Triangle_3 & B,
  187. const Index fa,
  188. const Index fb,
  189. const std::vector<std::pair<Index,Index> > shared);
  190. public:
  191. // Callback function called during box self intersections test. Means
  192. // boxes a and b intersect. This method then checks if the triangles in
  193. // each box intersect and if so, then processes the intersections
  194. //
  195. // Inputs:
  196. // a box containing a triangle
  197. // b box containing a triangle
  198. inline void box_intersect(const Box& a, const Box& b);
  199. inline void process_intersecting_boxes();
  200. private:
  201. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  202. // intersection objects (points,segments,triangles). CGAL uses an affine
  203. // projection rather than an isometric projection, so we're not
  204. // guaranteed that the 2D delaunay triangulation here will be a delaunay
  205. // triangulation in 3D.
  206. //
  207. // Inputs:
  208. // A triangle in 3D
  209. // A_objects_3 updated list of intersection objects for A
  210. // Outputs:
  211. // cdt Contrained delaunay triangulation in projected 2D plane
  212. public:
  213. // Getters:
  214. //const IndexList& get_lIF() const{ return lIF;}
  215. static inline void box_intersect_static(
  216. SelfIntersectMesh * SIM,
  217. const Box &a,
  218. const Box &b);
  219. private:
  220. std::mutex m_offending_lock;
  221. };
  222. }
  223. }
  224. }
  225. // Implementation
  226. #include "mesh_to_cgal_triangle_list.h"
  227. #include "remesh_intersections.h"
  228. #include "../../REDRUM.h"
  229. #include "../../get_seconds.h"
  230. #include "../../C_STR.h"
  231. #include <functional>
  232. #include <algorithm>
  233. #include <exception>
  234. #include <cassert>
  235. #include <iostream>
  236. // References:
  237. // http://minregret.googlecode.com/svn/trunk/skyline/src/extern/CGAL-3.3.1/examples/Polyhedron/polyhedron_self_intersection.cpp
  238. // http://www.cgal.org/Manual/3.9/examples/Boolean_set_operations_2/do_intersect.cpp
  239. // Q: Should we be using CGAL::Polyhedron_3?
  240. // A: No! Input is just a list of unoriented triangles. Polyhedron_3 requires
  241. // a 2-manifold.
  242. // A: But! It seems we could use CGAL::Triangulation_3. Though it won't be easy
  243. // to take advantage of functions like insert_in_facet because we want to
  244. // constrain segments. Hmmm. Actualy Triangulation_3 doesn't look right...
  245. //static void box_intersect(SelfIntersectMesh * SIM,const Box & A, const Box & B)
  246. //{
  247. // return SIM->box_intersect(A,B);
  248. //}
  249. // CGAL's box_self_intersection_d uses C-style function callbacks without
  250. // userdata. This is a leapfrog method for calling a member function. It should
  251. // be bound as if the prototype was:
  252. // static void box_intersect(const Box &a, const Box &b)
  253. // using boost:
  254. // boost::function<void(const Box &a,const Box &b)> cb
  255. // = boost::bind(&::box_intersect, this, _1,_2);
  256. //
  257. template <
  258. typename Kernel,
  259. typename DerivedV,
  260. typename DerivedF,
  261. typename DerivedVV,
  262. typename DerivedFF,
  263. typename DerivedIF,
  264. typename DerivedJ,
  265. typename DerivedIM>
  266. inline void igl::copyleft::cgal::SelfIntersectMesh<
  267. Kernel,
  268. DerivedV,
  269. DerivedF,
  270. DerivedVV,
  271. DerivedFF,
  272. DerivedIF,
  273. DerivedJ,
  274. DerivedIM>::box_intersect_static(
  275. Self * SIM,
  276. const typename Self::Box &a,
  277. const typename Self::Box &b)
  278. {
  279. SIM->box_intersect(a,b);
  280. }
  281. template <
  282. typename Kernel,
  283. typename DerivedV,
  284. typename DerivedF,
  285. typename DerivedVV,
  286. typename DerivedFF,
  287. typename DerivedIF,
  288. typename DerivedJ,
  289. typename DerivedIM>
  290. inline igl::copyleft::cgal::SelfIntersectMesh<
  291. Kernel,
  292. DerivedV,
  293. DerivedF,
  294. DerivedVV,
  295. DerivedFF,
  296. DerivedIF,
  297. DerivedJ,
  298. DerivedIM>::SelfIntersectMesh(
  299. const Eigen::PlainObjectBase<DerivedV> & V,
  300. const Eigen::PlainObjectBase<DerivedF> & F,
  301. const RemeshSelfIntersectionsParam & params,
  302. Eigen::PlainObjectBase<DerivedVV> & VV,
  303. Eigen::PlainObjectBase<DerivedFF> & FF,
  304. Eigen::PlainObjectBase<DerivedIF> & IF,
  305. Eigen::PlainObjectBase<DerivedJ> & J,
  306. Eigen::PlainObjectBase<DerivedIM> & IM):
  307. V(V),
  308. F(F),
  309. count(0),
  310. T(),
  311. lIF(),
  312. offending(),
  313. //edge2faces(),
  314. params(params)
  315. {
  316. using namespace std;
  317. using namespace Eigen;
  318. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  319. const auto & tictoc = []() -> double
  320. {
  321. static double t_start = igl::get_seconds();
  322. double diff = igl::get_seconds()-t_start;
  323. t_start += diff;
  324. return diff;
  325. };
  326. const auto log_time = [&](const std::string& label) -> void{
  327. std::cout << "SelfIntersectMesh." << label << ": "
  328. << tictoc() << std::endl;
  329. };
  330. tictoc();
  331. #endif
  332. // Compute and process self intersections
  333. mesh_to_cgal_triangle_list(V,F,T);
  334. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  335. log_time("convert_to_triangle_list");
  336. #endif
  337. // http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Box_intersection_d/Chapter_main.html#Section_63.5
  338. // Create the corresponding vector of bounding boxes
  339. std::vector<Box> boxes;
  340. boxes.reserve(T.size());
  341. for (
  342. TrianglesIterator tit = T.begin();
  343. tit != T.end();
  344. ++tit)
  345. {
  346. if (!tit->is_degenerate())
  347. {
  348. boxes.push_back(Box(tit->bbox(), tit));
  349. }
  350. }
  351. // Leapfrog callback
  352. std::function<void(const Box &a,const Box &b)> cb =
  353. std::bind(&box_intersect_static, this,
  354. // Explicitly use std namespace to avoid confusion with boost (who puts
  355. // _1 etc. in global namespace)
  356. std::placeholders::_1,
  357. std::placeholders::_2);
  358. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  359. log_time("box_and_bind");
  360. #endif
  361. // Run the self intersection algorithm with all defaults
  362. try{
  363. CGAL::box_self_intersection_d(boxes.begin(), boxes.end(),cb);
  364. }catch(int e)
  365. {
  366. // Rethrow if not IGL_FIRST_HIT_EXCEPTION
  367. if(e != IGL_FIRST_HIT_EXCEPTION)
  368. {
  369. throw e;
  370. }
  371. // Otherwise just fall through
  372. }
  373. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  374. log_time("box_intersection_d");
  375. #endif
  376. process_intersecting_boxes();
  377. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  378. log_time("resolve_intersection");
  379. #endif
  380. // Convert lIF to Eigen matrix
  381. assert(lIF.size()%2 == 0);
  382. IF.resize(lIF.size()/2,2);
  383. {
  384. Index i=0;
  385. for(
  386. typename IndexList::const_iterator ifit = lIF.begin();
  387. ifit!=lIF.end();
  388. )
  389. {
  390. IF(i,0) = (*ifit);
  391. ifit++;
  392. IF(i,1) = (*ifit);
  393. ifit++;
  394. i++;
  395. }
  396. }
  397. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  398. log_time("store_intersecting_face_pairs");
  399. #endif
  400. if(params.detect_only)
  401. {
  402. return;
  403. }
  404. remesh_intersections(
  405. V,F,T,offending,params.stitch_all,VV,FF,J,IM);
  406. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  407. log_time("remesh_intersection");
  408. #endif
  409. // Q: Does this give the same result as TETGEN?
  410. // A: For the cow and beast, yes.
  411. // Q: Is tetgen faster than this CGAL implementation?
  412. // A: Well, yes. But Tetgen is only solving the detection (predicates)
  413. // problem. This is also appending the intersection objects (construction).
  414. // But maybe tetgen is still faster for the detection part. For example, this
  415. // CGAL implementation on the beast takes 98 seconds but tetgen detection
  416. // takes 14 seconds
  417. }
  418. template <
  419. typename Kernel,
  420. typename DerivedV,
  421. typename DerivedF,
  422. typename DerivedVV,
  423. typename DerivedFF,
  424. typename DerivedIF,
  425. typename DerivedJ,
  426. typename DerivedIM>
  427. inline void igl::copyleft::cgal::SelfIntersectMesh<
  428. Kernel,
  429. DerivedV,
  430. DerivedF,
  431. DerivedVV,
  432. DerivedFF,
  433. DerivedIF,
  434. DerivedJ,
  435. DerivedIM>::mark_offensive(const Index f)
  436. {
  437. using namespace std;
  438. lIF.push_back(f);
  439. if(offending.count(f) == 0)
  440. {
  441. // first time marking, initialize with new id and empty list
  442. offending[f] = {};
  443. for(Index e = 0; e<3;e++)
  444. {
  445. // append face to edge's list
  446. Index i = F(f,(e+1)%3) < F(f,(e+2)%3) ? F(f,(e+1)%3) : F(f,(e+2)%3);
  447. Index j = F(f,(e+1)%3) < F(f,(e+2)%3) ? F(f,(e+2)%3) : F(f,(e+1)%3);
  448. //edge2faces[EMK(i,j)].push_back(f);
  449. }
  450. }
  451. }
  452. template <
  453. typename Kernel,
  454. typename DerivedV,
  455. typename DerivedF,
  456. typename DerivedVV,
  457. typename DerivedFF,
  458. typename DerivedIF,
  459. typename DerivedJ,
  460. typename DerivedIM>
  461. inline void igl::copyleft::cgal::SelfIntersectMesh<
  462. Kernel,
  463. DerivedV,
  464. DerivedF,
  465. DerivedVV,
  466. DerivedFF,
  467. DerivedIF,
  468. DerivedJ,
  469. DerivedIM>::count_intersection(
  470. const Index fa,
  471. const Index fb)
  472. {
  473. std::lock_guard<std::mutex> guard(m_offending_lock);
  474. mark_offensive(fa);
  475. mark_offensive(fb);
  476. this->count++;
  477. // We found the first intersection
  478. if(params.first_only && this->count >= 1)
  479. {
  480. throw IGL_FIRST_HIT_EXCEPTION;
  481. }
  482. }
  483. template <
  484. typename Kernel,
  485. typename DerivedV,
  486. typename DerivedF,
  487. typename DerivedVV,
  488. typename DerivedFF,
  489. typename DerivedIF,
  490. typename DerivedJ,
  491. typename DerivedIM>
  492. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  493. Kernel,
  494. DerivedV,
  495. DerivedF,
  496. DerivedVV,
  497. DerivedFF,
  498. DerivedIF,
  499. DerivedJ,
  500. DerivedIM>::intersect(
  501. const Triangle_3 & A,
  502. const Triangle_3 & B,
  503. const Index fa,
  504. const Index fb)
  505. {
  506. // Determine whether there is an intersection
  507. if(!CGAL::do_intersect(A,B))
  508. {
  509. return false;
  510. }
  511. count_intersection(fa,fb);
  512. if(!params.detect_only)
  513. {
  514. // Construct intersection
  515. CGAL::Object result = CGAL::intersection(A,B);
  516. std::lock_guard<std::mutex> guard(m_offending_lock);
  517. offending[fa].push_back({fb, result});
  518. offending[fb].push_back({fa, result});
  519. }
  520. return true;
  521. }
  522. template <
  523. typename Kernel,
  524. typename DerivedV,
  525. typename DerivedF,
  526. typename DerivedVV,
  527. typename DerivedFF,
  528. typename DerivedIF,
  529. typename DerivedJ,
  530. typename DerivedIM>
  531. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  532. Kernel,
  533. DerivedV,
  534. DerivedF,
  535. DerivedVV,
  536. DerivedFF,
  537. DerivedIF,
  538. DerivedJ,
  539. DerivedIM>::single_shared_vertex(
  540. const Triangle_3 & A,
  541. const Triangle_3 & B,
  542. const Index fa,
  543. const Index fb,
  544. const Index va,
  545. const Index vb)
  546. {
  547. ////using namespace std;
  548. //CGAL::Object result = CGAL::intersection(A,B);
  549. //if(CGAL::object_cast<Segment_3 >(&result))
  550. //{
  551. // // Append to each triangle's running list
  552. // F_objects[fa].push_back(result);
  553. // F_objects[fb].push_back(result);
  554. // count_intersection(fa,fb);
  555. //}else
  556. //{
  557. // // Then intersection must be at point
  558. // // And point must be at shared vertex
  559. // assert(CGAL::object_cast<Point_3>(&result));
  560. //}
  561. if(single_shared_vertex(A,B,fa,fb,va))
  562. {
  563. return true;
  564. }
  565. return single_shared_vertex(B,A,fb,fa,vb);
  566. }
  567. template <
  568. typename Kernel,
  569. typename DerivedV,
  570. typename DerivedF,
  571. typename DerivedVV,
  572. typename DerivedFF,
  573. typename DerivedIF,
  574. typename DerivedJ,
  575. typename DerivedIM>
  576. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  577. Kernel,
  578. DerivedV,
  579. DerivedF,
  580. DerivedVV,
  581. DerivedFF,
  582. DerivedIF,
  583. DerivedJ,
  584. DerivedIM>::single_shared_vertex(
  585. const Triangle_3 & A,
  586. const Triangle_3 & B,
  587. const Index fa,
  588. const Index fb,
  589. const Index va)
  590. {
  591. // This was not a good idea. It will not handle coplanar triangles well.
  592. using namespace std;
  593. Segment_3 sa(
  594. A.vertex((va+1)%3),
  595. A.vertex((va+2)%3));
  596. if(CGAL::do_intersect(sa,B))
  597. {
  598. // can't put count_intersection(fa,fb) here since we use intersect below
  599. // and then it will be counted twice.
  600. if(params.detect_only)
  601. {
  602. count_intersection(fa,fb);
  603. return true;
  604. }
  605. CGAL::Object result = CGAL::intersection(sa,B);
  606. if(const Point_3 * p = CGAL::object_cast<Point_3 >(&result))
  607. {
  608. // Single intersection --> segment from shared point to intersection
  609. CGAL::Object seg = CGAL::make_object(Segment_3(
  610. A.vertex(va),
  611. *p));
  612. count_intersection(fa,fb);
  613. std::lock_guard<std::mutex> guard(m_offending_lock);
  614. offending[fa].push_back({fb, seg});
  615. offending[fb].push_back({fa, seg});
  616. return true;
  617. }else if(CGAL::object_cast<Segment_3 >(&result))
  618. {
  619. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (single shared).")<<endl;
  620. // Must be coplanar
  621. // WRONG:
  622. //// Segment intersection --> triangle from shared point to intersection
  623. //CGAL::Object tri = CGAL::make_object(Triangle_3(
  624. // A.vertex(va),
  625. // s->vertex(0),
  626. // s->vertex(1)));
  627. //F_objects[fa].push_back(tri);
  628. //F_objects[fb].push_back(tri);
  629. //count_intersection(fa,fb);
  630. // Need to do full test. Intersection could be a general poly.
  631. bool test = intersect(A,B,fa,fb);
  632. ((void)test);
  633. assert(test && "intersect should agree with do_intersect");
  634. return true;
  635. }else
  636. {
  637. cerr<<REDRUM("Segment ∩ triangle neither point nor segment?")<<endl;
  638. assert(false);
  639. }
  640. }
  641. return false;
  642. }
  643. template <
  644. typename Kernel,
  645. typename DerivedV,
  646. typename DerivedF,
  647. typename DerivedVV,
  648. typename DerivedFF,
  649. typename DerivedIF,
  650. typename DerivedJ,
  651. typename DerivedIM>
  652. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  653. Kernel,
  654. DerivedV,
  655. DerivedF,
  656. DerivedVV,
  657. DerivedFF,
  658. DerivedIF,
  659. DerivedJ,
  660. DerivedIM>::double_shared_vertex(
  661. const Triangle_3 & A,
  662. const Triangle_3 & B,
  663. const Index fa,
  664. const Index fb,
  665. const std::vector<std::pair<Index,Index> > shared)
  666. {
  667. using namespace std;
  668. // must be co-planar
  669. if(
  670. A.supporting_plane() != B.supporting_plane() &&
  671. A.supporting_plane() != B.supporting_plane().opposite())
  672. {
  673. return false;
  674. }
  675. // Since A and B are non-degenerate the intersection must be a polygon
  676. // (triangle). Either
  677. // - the vertex of A (B) opposite the shared edge of lies on B (A), or
  678. // - an edge of A intersects and edge of B without sharing a vertex
  679. // Determine if the vertex opposite edge (a0,a1) in triangle A lies in
  680. // (intersects) triangle B
  681. const auto & opposite_point_inside = [](
  682. const Triangle_3 & A, const Index a0, const Index a1, const Triangle_3 & B)
  683. -> bool
  684. {
  685. // get opposite index
  686. Index a2 = -1;
  687. for(int c = 0;c<3;c++)
  688. {
  689. if(c != a0 && c != a1)
  690. {
  691. a2 = c;
  692. break;
  693. }
  694. }
  695. assert(a2 != -1);
  696. bool ret = CGAL::do_intersect(A.vertex(a2),B);
  697. //cout<<"opposite_point_inside: "<<ret<<endl;
  698. return ret;
  699. };
  700. // Determine if edge opposite vertex va in triangle A intersects edge
  701. // opposite vertex vb in triangle B.
  702. const auto & opposite_edges_intersect = [](
  703. const Triangle_3 & A, const Index va,
  704. const Triangle_3 & B, const Index vb) -> bool
  705. {
  706. Segment_3 sa( A.vertex((va+1)%3), A.vertex((va+2)%3));
  707. Segment_3 sb( B.vertex((vb+1)%3), B.vertex((vb+2)%3));
  708. //cout<<sa<<endl;
  709. //cout<<sb<<endl;
  710. bool ret = CGAL::do_intersect(sa,sb);
  711. //cout<<"opposite_edges_intersect: "<<ret<<endl;
  712. return ret;
  713. };
  714. if(
  715. !opposite_point_inside(A,shared[0].first,shared[1].first,B) &&
  716. !opposite_point_inside(B,shared[0].second,shared[1].second,A) &&
  717. !opposite_edges_intersect(A,shared[0].first,B,shared[1].second) &&
  718. !opposite_edges_intersect(A,shared[1].first,B,shared[0].second))
  719. {
  720. return false;
  721. }
  722. // there is an intersection indeed
  723. count_intersection(fa,fb);
  724. if(params.detect_only)
  725. {
  726. return true;
  727. }
  728. // Construct intersection
  729. try
  730. {
  731. // This can fail for Epick but not Epeck
  732. CGAL::Object result = CGAL::intersection(A,B);
  733. if(!result.empty())
  734. {
  735. if(CGAL::object_cast<Segment_3 >(&result))
  736. {
  737. // not coplanar
  738. assert(false &&
  739. "Co-planar non-degenerate triangles should intersect over triangle");
  740. return false;
  741. } else if(CGAL::object_cast<Point_3 >(&result))
  742. {
  743. // this "shouldn't" happen but does for inexact
  744. assert(false &&
  745. "Co-planar non-degenerate triangles should intersect over triangle");
  746. return false;
  747. } else
  748. {
  749. // Triangle object
  750. std::lock_guard<std::mutex> guard(m_offending_lock);
  751. offending[fa].push_back({fb, result});
  752. offending[fb].push_back({fa, result});
  753. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (double shared).")<<endl;
  754. return true;
  755. }
  756. }else
  757. {
  758. // CGAL::intersection is disagreeing with do_intersect
  759. assert(false && "CGAL::intersection should agree with predicate tests");
  760. return false;
  761. }
  762. }catch(...)
  763. {
  764. // This catches some cgal assertion:
  765. // CGAL error: assertion violation!
  766. // Expression : is_finite(d)
  767. // File : /opt/local/include/CGAL/GMP/Gmpq_type.h
  768. // Line : 132
  769. // Explanation:
  770. // But only if NDEBUG is not defined, otherwise there's an uncaught
  771. // "Floating point exception: 8" SIGFPE
  772. return false;
  773. }
  774. // No intersection.
  775. return false;
  776. }
  777. template <
  778. typename Kernel,
  779. typename DerivedV,
  780. typename DerivedF,
  781. typename DerivedVV,
  782. typename DerivedFF,
  783. typename DerivedIF,
  784. typename DerivedJ,
  785. typename DerivedIM>
  786. inline void igl::copyleft::cgal::SelfIntersectMesh<
  787. Kernel,
  788. DerivedV,
  789. DerivedF,
  790. DerivedVV,
  791. DerivedFF,
  792. DerivedIF,
  793. DerivedJ,
  794. DerivedIM>::box_intersect(
  795. const Box& a,
  796. const Box& b)
  797. {
  798. candidate_box_pairs.push_back({a, b});
  799. }
  800. template <
  801. typename Kernel,
  802. typename DerivedV,
  803. typename DerivedF,
  804. typename DerivedVV,
  805. typename DerivedFF,
  806. typename DerivedIF,
  807. typename DerivedJ,
  808. typename DerivedIM>
  809. inline void igl::copyleft::cgal::SelfIntersectMesh<
  810. Kernel,
  811. DerivedV,
  812. DerivedF,
  813. DerivedVV,
  814. DerivedFF,
  815. DerivedIF,
  816. DerivedJ,
  817. DerivedIM>::process_intersecting_boxes()
  818. {
  819. std::vector<std::mutex> triangle_locks(T.size());
  820. std::vector<std::mutex> vertex_locks(V.rows());
  821. std::mutex index_lock;
  822. auto process_chunk = [&](const size_t first, const size_t last) -> void{
  823. assert(last >= first);
  824. for (size_t i=first; i<last; i++) {
  825. Index fa=T.size(), fb=T.size();
  826. {
  827. // Before knowing which triangles are involved, we need to lock
  828. // everything to prevent race condition in updating reference counters.
  829. std::lock_guard<std::mutex> guard(index_lock);
  830. const auto& box_pair = candidate_box_pairs[i];
  831. const auto& a = box_pair.first;
  832. const auto& b = box_pair.second;
  833. fa = a.handle()-T.begin();
  834. fb = b.handle()-T.begin();
  835. }
  836. assert(fa < T.size());
  837. assert(fb < T.size());
  838. // Lock triangles
  839. std::lock_guard<std::mutex> guard_A(triangle_locks[fa]);
  840. std::lock_guard<std::mutex> guard_B(triangle_locks[fb]);
  841. // Lock vertices
  842. std::list<std::lock_guard<std::mutex> > guard_vertices;
  843. {
  844. std::vector<typename DerivedF::Scalar> unique_vertices;
  845. std::vector<size_t> tmp1, tmp2;
  846. igl::unique({F(fa,0), F(fa,1), F(fa,2), F(fb,0), F(fb,1), F(fb,2)},
  847. unique_vertices, tmp1, tmp2);
  848. std::for_each(unique_vertices.begin(), unique_vertices.end(),
  849. [&](const typename DerivedF::Scalar& vi) {
  850. guard_vertices.emplace_back(vertex_locks[vi]);
  851. });
  852. }
  853. const Triangle_3& A = T[fa];
  854. const Triangle_3& B = T[fb];
  855. // Number of combinatorially shared vertices
  856. Index comb_shared_vertices = 0;
  857. // Number of geometrically shared vertices (*not* including combinatorially
  858. // shared)
  859. Index geo_shared_vertices = 0;
  860. // Keep track of shared vertex indices
  861. std::vector<std::pair<Index,Index> > shared;
  862. Index ea,eb;
  863. for(ea=0;ea<3;ea++)
  864. {
  865. for(eb=0;eb<3;eb++)
  866. {
  867. if(F(fa,ea) == F(fb,eb))
  868. {
  869. comb_shared_vertices++;
  870. shared.emplace_back(ea,eb);
  871. }else if(A.vertex(ea) == B.vertex(eb))
  872. {
  873. geo_shared_vertices++;
  874. shared.emplace_back(ea,eb);
  875. }
  876. }
  877. }
  878. const Index total_shared_vertices = comb_shared_vertices + geo_shared_vertices;
  879. if(comb_shared_vertices== 3)
  880. {
  881. assert(shared.size() == 3);
  882. //// Combinatorially duplicate face, these should be removed by preprocessing
  883. //cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are combinatorial duplicates")<<endl;
  884. continue;
  885. }
  886. if(total_shared_vertices== 3)
  887. {
  888. assert(shared.size() == 3);
  889. //// Geometrically duplicate face, these should be removed by preprocessing
  890. //cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are geometrical duplicates")<<endl;
  891. continue;
  892. }
  893. if(total_shared_vertices == 2)
  894. {
  895. assert(shared.size() == 2);
  896. // Q: What about coplanar?
  897. //
  898. // o o
  899. // |\ /|
  900. // | \/ |
  901. // | /\ |
  902. // |/ \|
  903. // o----o
  904. double_shared_vertex(A,B,fa,fb,shared);
  905. continue;
  906. }
  907. assert(total_shared_vertices<=1);
  908. if(total_shared_vertices==1)
  909. {
  910. single_shared_vertex(A,B,fa,fb,shared[0].first,shared[0].second);
  911. }else
  912. {
  913. intersect(A,B,fa,fb);
  914. }
  915. }
  916. };
  917. size_t num_threads=0;
  918. const size_t hardware_limit = std::thread::hardware_concurrency();
  919. if (const char* igl_num_threads = std::getenv("LIBIGL_NUM_THREADS")) {
  920. num_threads = atoi(igl_num_threads);
  921. }
  922. if (num_threads == 0 || num_threads > hardware_limit) {
  923. num_threads = hardware_limit;
  924. }
  925. assert(num_threads > 0);
  926. const size_t num_pairs = candidate_box_pairs.size();
  927. const size_t chunk_size = num_pairs / num_threads;
  928. std::vector<std::thread> threads;
  929. for (size_t i=0; i<num_threads-1; i++) {
  930. threads.emplace_back(process_chunk, i*chunk_size, (i+1)*chunk_size);
  931. }
  932. // Do some work in the master thread.
  933. process_chunk((num_threads-1)*chunk_size, num_pairs);
  934. for (auto& t : threads) {
  935. if (t.joinable()) t.join();
  936. }
  937. //process_chunk(0, candidate_box_pairs.size());
  938. }
  939. #endif