SelfIntersectMesh.h 26 KB

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