SelfIntersectMesh.h 28 KB

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