closest_facet.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 Qingnan Zhou <qnzhou@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. //
  9. #include "closest_facet.h"
  10. #include <vector>
  11. #include <stdexcept>
  12. #include <unordered_map>
  13. #include <CGAL/AABB_tree.h>
  14. #include <CGAL/AABB_traits.h>
  15. #include <CGAL/AABB_triangle_primitive.h>
  16. #include <CGAL/intersections.h>
  17. #include <CGAL/Exact_predicates_exact_constructions_kernel.h>
  18. #include "order_facets_around_edge.h"
  19. #include "../../vertex_triangle_adjacency.h"
  20. template<
  21. typename DerivedV,
  22. typename DerivedF,
  23. typename DerivedI,
  24. typename DerivedP,
  25. typename uE2EType,
  26. typename DerivedEMAP,
  27. typename DerivedR,
  28. typename DerivedS >
  29. IGL_INLINE void igl::copyleft::cgal::closest_facet(
  30. const Eigen::PlainObjectBase<DerivedV>& V,
  31. const Eigen::PlainObjectBase<DerivedF>& F,
  32. const Eigen::PlainObjectBase<DerivedI>& I,
  33. const Eigen::PlainObjectBase<DerivedP>& P,
  34. const std::vector<std::vector<uE2EType> >& uE2E,
  35. const Eigen::PlainObjectBase<DerivedEMAP>& EMAP,
  36. Eigen::PlainObjectBase<DerivedR>& R,
  37. Eigen::PlainObjectBase<DerivedS>& S) {
  38. typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
  39. typedef Kernel::Point_3 Point_3;
  40. typedef Kernel::Plane_3 Plane_3;
  41. typedef Kernel::Segment_3 Segment_3;
  42. typedef Kernel::Triangle_3 Triangle;
  43. typedef std::vector<Triangle>::iterator Iterator;
  44. typedef CGAL::AABB_triangle_primitive<Kernel, Iterator> Primitive;
  45. typedef CGAL::AABB_traits<Kernel, Primitive> AABB_triangle_traits;
  46. typedef CGAL::AABB_tree<AABB_triangle_traits> Tree;
  47. if (F.rows() <= 0 || I.rows() <= 0) {
  48. throw std::runtime_error(
  49. "Closest facet cannot be computed on empty mesh.");
  50. }
  51. std::vector<std::vector<size_t> > VF;
  52. std::vector<std::vector<size_t> > VFi;
  53. igl::vertex_triangle_adjacency(V, F, VF, VFi);
  54. std::vector<bool> in_I(F.rows(), false);
  55. const size_t num_faces = I.rows();
  56. std::vector<Triangle> triangles;
  57. for (size_t i=0; i<num_faces; i++) {
  58. const Eigen::Vector3i f = F.row(I(i, 0));
  59. in_I[I(i,0)] = true;
  60. triangles.emplace_back(
  61. Point_3(V(f[0], 0), V(f[0], 1), V(f[0], 2)),
  62. Point_3(V(f[1], 0), V(f[1], 1), V(f[1], 2)),
  63. Point_3(V(f[2], 0), V(f[2], 1), V(f[2], 2)));
  64. if (triangles.back().is_degenerate()) {
  65. throw std::runtime_error(
  66. "Input facet components contains degenerated triangles");
  67. }
  68. }
  69. Tree tree(triangles.begin(), triangles.end());
  70. tree.accelerate_distance_queries();
  71. auto on_the_positive_side = [&](size_t fid, const Point_3& p) {
  72. const auto& f = F.row(fid).eval();
  73. Point_3 v0(V(f[0], 0), V(f[0], 1), V(f[0], 2));
  74. Point_3 v1(V(f[1], 0), V(f[1], 1), V(f[1], 2));
  75. Point_3 v2(V(f[2], 0), V(f[2], 1), V(f[2], 2));
  76. auto ori = CGAL::orientation(v0, v1, v2, p);
  77. switch (ori) {
  78. case CGAL::POSITIVE:
  79. return true;
  80. case CGAL::NEGATIVE:
  81. return false;
  82. case CGAL::COPLANAR:
  83. throw std::runtime_error(
  84. "It seems input mesh contains self intersection");
  85. default:
  86. throw std::runtime_error("Unknown CGAL state.");
  87. }
  88. return false;
  89. };
  90. auto get_orientation = [&](size_t fid, size_t s, size_t d) -> bool {
  91. const auto& f = F.row(fid);
  92. if ((size_t)f[0] == s && (size_t)f[1] == d) return false;
  93. else if ((size_t)f[1] == s && (size_t)f[2] == d) return false;
  94. else if ((size_t)f[2] == s && (size_t)f[0] == d) return false;
  95. else if ((size_t)f[0] == d && (size_t)f[1] == s) return true;
  96. else if ((size_t)f[1] == d && (size_t)f[2] == s) return true;
  97. else if ((size_t)f[2] == d && (size_t)f[0] == s) return true;
  98. else {
  99. throw std::runtime_error(
  100. "Cannot compute orientation due to incorrect connectivity");
  101. return false;
  102. }
  103. };
  104. auto index_to_signed_index = [&](size_t index, bool ori) -> int{
  105. return (index+1) * (ori? 1:-1);
  106. };
  107. //auto signed_index_to_index = [&](int signed_index) -> size_t {
  108. // return abs(signed_index) - 1;
  109. //};
  110. enum ElementType { VERTEX, EDGE, FACE };
  111. auto determine_element_type = [&](const Point_3& p, const size_t fid,
  112. size_t& element_index) {
  113. const auto& tri = triangles[fid];
  114. const Point_3 p0 = tri[0];
  115. const Point_3 p1 = tri[1];
  116. const Point_3 p2 = tri[2];
  117. if (p == p0) { element_index = 0; return VERTEX; }
  118. if (p == p1) { element_index = 1; return VERTEX; }
  119. if (p == p2) { element_index = 2; return VERTEX; }
  120. if (CGAL::collinear(p0, p1, p)) { element_index = 2; return EDGE; }
  121. if (CGAL::collinear(p1, p2, p)) { element_index = 0; return EDGE; }
  122. if (CGAL::collinear(p2, p0, p)) { element_index = 1; return EDGE; }
  123. element_index = 0;
  124. return FACE;
  125. };
  126. auto process_edge_case = [&](
  127. size_t query_idx,
  128. const size_t s, const size_t d,
  129. size_t preferred_facet,
  130. bool& orientation) {
  131. Point_3 query_point(
  132. P(query_idx, 0),
  133. P(query_idx, 1),
  134. P(query_idx, 2));
  135. size_t corner_idx = std::numeric_limits<size_t>::max();
  136. if ((s == F(preferred_facet, 0) && d == F(preferred_facet, 1)) ||
  137. (s == F(preferred_facet, 1) && d == F(preferred_facet, 0))) {
  138. corner_idx = 2;
  139. } else if ((s == F(preferred_facet, 0) && d == F(preferred_facet, 2)) ||
  140. (s == F(preferred_facet, 2) && d == F(preferred_facet, 0))) {
  141. corner_idx = 1;
  142. } else if ((s == F(preferred_facet, 1) && d == F(preferred_facet, 2)) ||
  143. (s == F(preferred_facet, 2) && d == F(preferred_facet, 1))) {
  144. corner_idx = 0;
  145. } else {
  146. std::cerr << "s: " << s << "\t d:" << d << std::endl;
  147. std::cout << F.row(preferred_facet) << std::endl;
  148. throw std::runtime_error(
  149. "Invalid connectivity, edge does not belong to facet");
  150. }
  151. auto ueid = EMAP(preferred_facet + corner_idx * F.rows());
  152. auto eids = uE2E[ueid];
  153. std::vector<size_t> intersected_face_indices;
  154. for (auto eid : eids) {
  155. const size_t fid = eid % F.rows();
  156. if (in_I[fid]) {
  157. intersected_face_indices.push_back(fid);
  158. }
  159. }
  160. const size_t num_intersected_faces = intersected_face_indices.size();
  161. std::vector<int> intersected_face_signed_indices(num_intersected_faces);
  162. std::transform(
  163. intersected_face_indices.begin(),
  164. intersected_face_indices.end(),
  165. intersected_face_signed_indices.begin(),
  166. [&](size_t index) {
  167. return index_to_signed_index(
  168. index, get_orientation(index, s,d));
  169. });
  170. assert(num_intersected_faces >= 1);
  171. if (num_intersected_faces == 1) {
  172. // The edge must be a boundary edge. Thus, the orientation can be
  173. // simply determined by checking if the query point is on the
  174. // positive side of the facet.
  175. const size_t fid = intersected_face_indices[0];
  176. orientation = on_the_positive_side(fid, query_point);
  177. return fid;
  178. }
  179. Eigen::VectorXi order;
  180. DerivedP pivot = P.row(query_idx).eval();
  181. igl::copyleft::cgal::order_facets_around_edge(V, F, s, d,
  182. intersected_face_signed_indices,
  183. pivot, order);
  184. // Although first and last are equivalent, make the choice based on
  185. // preferred_facet.
  186. const size_t first = order[0];
  187. const size_t last = order[num_intersected_faces-1];
  188. if (intersected_face_indices[first] == preferred_facet) {
  189. orientation = intersected_face_signed_indices[first] < 0;
  190. return intersected_face_indices[first];
  191. } else if (intersected_face_indices[last] == preferred_facet) {
  192. orientation = intersected_face_signed_indices[last] > 0;
  193. return intersected_face_indices[last];
  194. } else {
  195. orientation = intersected_face_signed_indices[order[0]] < 0;
  196. return intersected_face_indices[order[0]];
  197. }
  198. };
  199. auto process_face_case = [&](
  200. const size_t query_idx, const Point_3& closest_point,
  201. const size_t fid, bool& orientation) {
  202. const auto& f = F.row(I(fid, 0));
  203. return process_edge_case(query_idx, f[0], f[1], I(fid, 0), orientation);
  204. };
  205. auto process_vertex_case = [&](const size_t query_idx, size_t s,
  206. size_t preferred_facet, bool& orientation) {
  207. const Point_3 query_point(
  208. P(query_idx, 0), P(query_idx, 1), P(query_idx, 2));
  209. const Point_3 closest_point(V(s, 0), V(s, 1), V(s, 2));
  210. std::vector<size_t> adj_faces;
  211. std::vector<size_t> adj_face_corners;
  212. {
  213. // Gether adj faces to s within I.
  214. const auto& all_adj_faces = VF[s];
  215. const auto& all_adj_face_corners = VFi[s];
  216. const size_t num_all_adj_faces = all_adj_faces.size();
  217. for (size_t i=0; i<num_all_adj_faces; i++) {
  218. const size_t fid = all_adj_faces[i];
  219. if (in_I[fid]) {
  220. adj_faces.push_back(fid);
  221. adj_face_corners.push_back(all_adj_face_corners[i]);
  222. }
  223. }
  224. }
  225. const size_t num_adj_faces = adj_faces.size();
  226. assert(num_adj_faces > 0);
  227. std::set<size_t> adj_vertices_set;
  228. std::unordered_multimap<size_t, size_t> v2f;
  229. for (size_t i=0; i<num_adj_faces; i++) {
  230. const size_t fid = adj_faces[i];
  231. const size_t cid = adj_face_corners[i];
  232. const auto& f = F.row(adj_faces[i]);
  233. const size_t next = f[(cid+1)%3];
  234. const size_t prev = f[(cid+2)%3];
  235. adj_vertices_set.insert(next);
  236. adj_vertices_set.insert(prev);
  237. v2f.insert({{next, fid}, {prev, fid}});
  238. }
  239. const size_t num_adj_vertices = adj_vertices_set.size();
  240. std::vector<size_t> adj_vertices(num_adj_vertices);
  241. std::copy(adj_vertices_set.begin(), adj_vertices_set.end(),
  242. adj_vertices.begin());
  243. std::vector<Point_3> adj_points;
  244. for (size_t vid : adj_vertices) {
  245. adj_points.emplace_back(V(vid,0), V(vid,1), V(vid,2));
  246. }
  247. // A plane is on the exterior if all adj_points lies on or to
  248. // one side of the plane.
  249. auto is_on_exterior = [&](const Plane_3& separator) {
  250. size_t positive=0;
  251. size_t negative=0;
  252. size_t coplanar=0;
  253. for (const auto& point : adj_points) {
  254. switch(separator.oriented_side(point)) {
  255. case CGAL::ON_POSITIVE_SIDE:
  256. positive++;
  257. break;
  258. case CGAL::ON_NEGATIVE_SIDE:
  259. negative++;
  260. break;
  261. case CGAL::ON_ORIENTED_BOUNDARY:
  262. coplanar++;
  263. break;
  264. default:
  265. throw "Unknown plane-point orientation";
  266. }
  267. }
  268. auto query_orientation = separator.oriented_side(query_point);
  269. if (query_orientation == CGAL::ON_ORIENTED_BOUNDARY &&
  270. (positive == 0 || negative == 0)) {
  271. // All adj vertices and query point are coplanar.
  272. // In this case, all separators are equally valid.
  273. return true;
  274. } else {
  275. bool r = (positive == 0 && query_orientation == CGAL::POSITIVE)
  276. || (negative == 0 && query_orientation == CGAL::NEGATIVE);
  277. return r;
  278. }
  279. };
  280. size_t d = std::numeric_limits<size_t>::max();
  281. for (size_t i=0; i<num_adj_vertices; i++) {
  282. const size_t vi = adj_vertices[i];
  283. for (size_t j=i+1; j<num_adj_vertices; j++) {
  284. Plane_3 separator(closest_point, adj_points[i], adj_points[j]);
  285. if (separator.is_degenerate()) {
  286. throw std::runtime_error(
  287. "Input mesh contains degenerated faces");
  288. }
  289. if (is_on_exterior(separator)) {
  290. d = vi;
  291. assert(!CGAL::collinear(
  292. query_point, adj_points[i], closest_point));
  293. break;
  294. }
  295. }
  296. }
  297. if (d == std::numeric_limits<size_t>::max()) {
  298. Eigen::MatrixXd tmp_vertices(V.rows(), V.cols());
  299. for (size_t i=0; i<V.rows(); i++) {
  300. for (size_t j=0; j<V.cols(); j++) {
  301. tmp_vertices(i,j) = CGAL::to_double(V(i,j));
  302. }
  303. }
  304. Eigen::MatrixXi tmp_faces(adj_faces.size(), 3);
  305. for (size_t i=0; i<adj_faces.size(); i++) {
  306. tmp_faces.row(i) = F.row(adj_faces[i]);
  307. }
  308. igl::writePLY("debug.ply", tmp_vertices, tmp_faces, false);
  309. throw std::runtime_error("Invalid vertex neighborhood");
  310. }
  311. const auto itr = v2f.equal_range(d);
  312. assert(itr.first != itr.second);
  313. return process_edge_case(query_idx, s, d, itr.first->second, orientation);
  314. };
  315. const size_t num_queries = P.rows();
  316. R.resize(num_queries, 1);
  317. S.resize(num_queries, 1);
  318. for (size_t i=0; i<num_queries; i++) {
  319. const Point_3 query(P(i,0), P(i,1), P(i,2));
  320. auto projection = tree.closest_point_and_primitive(query);
  321. const Point_3 closest_point = projection.first;
  322. size_t fid = projection.second - triangles.begin();
  323. bool fid_ori = false;
  324. // Gether all facets sharing the closest point.
  325. std::vector<Tree::Primitive_id> intersected_faces;
  326. tree.all_intersected_primitives(Segment_3(closest_point, query),
  327. std::back_inserter(intersected_faces));
  328. const size_t num_intersected_faces = intersected_faces.size();
  329. std::vector<size_t> intersected_face_indices(num_intersected_faces);
  330. std::transform(intersected_faces.begin(),
  331. intersected_faces.end(),
  332. intersected_face_indices.begin(),
  333. [&](const Tree::Primitive_id& itr) -> size_t
  334. { return I(itr-triangles.begin(), 0); });
  335. size_t element_index;
  336. auto element_type = determine_element_type(closest_point, fid,
  337. element_index);
  338. switch(element_type) {
  339. case VERTEX:
  340. {
  341. const auto& f = F.row(I(fid, 0));
  342. const size_t s = f[element_index];
  343. fid = process_vertex_case(i, s, I(fid, 0), fid_ori);
  344. }
  345. break;
  346. case EDGE:
  347. {
  348. const auto& f = F.row(I(fid, 0));
  349. const size_t s = f[(element_index+1)%3];
  350. const size_t d = f[(element_index+2)%3];
  351. fid = process_edge_case(i, s, d, I(fid, 0), fid_ori);
  352. }
  353. break;
  354. case FACE:
  355. {
  356. fid = process_face_case(i, closest_point, fid, fid_ori);
  357. }
  358. break;
  359. default:
  360. throw std::runtime_error("Unknown element type.");
  361. }
  362. R(i,0) = fid;
  363. S(i,0) = fid_ori;
  364. }
  365. }
  366. template<
  367. typename DerivedV,
  368. typename DerivedF,
  369. typename DerivedP,
  370. typename uE2EType,
  371. typename DerivedEMAP,
  372. typename DerivedR,
  373. typename DerivedS >
  374. IGL_INLINE void igl::copyleft::cgal::closest_facet(
  375. const Eigen::PlainObjectBase<DerivedV>& V,
  376. const Eigen::PlainObjectBase<DerivedF>& F,
  377. const Eigen::PlainObjectBase<DerivedP>& P,
  378. const std::vector<std::vector<uE2EType> >& uE2E,
  379. const Eigen::PlainObjectBase<DerivedEMAP>& EMAP,
  380. Eigen::PlainObjectBase<DerivedR>& R,
  381. Eigen::PlainObjectBase<DerivedS>& S) {
  382. const size_t num_faces = F.rows();
  383. Eigen::VectorXi I(num_faces);
  384. I.setLinSpaced(num_faces, 0, num_faces-1);
  385. igl::copyleft::cgal::closest_facet(V, F, I, P, uE2E, EMAP, R, S);
  386. }
  387. #ifdef IGL_STATIC_LIBRARY
  388. template void igl::copyleft::cgal::closest_facet<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
  389. #endif