Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
intersection.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
10#include "momentum/math/mesh.h"
12
13#include <axel/Bvh.h>
14
15namespace momentum {
16
17namespace {
18
19// Signed area (twice) of the 2D triangle (p1, p2, p3) projected onto the z=0 plane.
20// Equivalent to the z-component of the cross product (p2-p1) x (p3-p1) using only
21// the x,y coordinates. The sign indicates the orientation (CCW positive, CW negative)
22// and is used to test whether p1 lies on a consistent side of the directed edge p2->p3.
23//
24// TODO: This always projects onto z=0, which is degenerate for triangles whose normal
25// is close to the world Z axis (i.e., nearly horizontal in the xy plane). A more robust
26// test should project onto the coordinate plane that drops the dominant component of
27// the triangle's normal, or use barycentric/edge-cross tests in 3D.
28template <typename T>
29T sign(const Eigen::Vector3<T>& p1, const Eigen::Vector3<T>& p2, const Eigen::Vector3<T>& p3) {
30 return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]);
31}
32
33} // namespace
34
35template <typename T>
37 const MeshT<T>& mesh,
38 const std::vector<Vector3<T>>& faceNormals,
39 const int32_t face0,
40 const int32_t face1) {
41 // Faces that share at least one vertex are treated as non-intersecting. This avoids
42 // false positives on adjacent triangles that meet along an edge or at a vertex but
43 // do not actually overlap in their interiors.
44 // TODO: This O(9) loop also rejects pairs that share only a single vertex, which can
45 // miss real interior intersections when two triangles fan out from a common vertex.
46 for (size_t iVertex1 : mesh.faces[face0]) {
47 for (size_t iVertex2 : mesh.faces[face1]) {
48 if (iVertex1 == iVertex2) {
49 return false;
50 }
51 }
52 }
53
54 // Two-pass edge-vs-plane test: for each ordering (A=face0,B=face1) and (A=face1,B=face0),
55 // intersect each of triangle A's three edges against triangle B's supporting plane and
56 // check whether the intersection point lies inside triangle B. If any edge-segment of
57 // either triangle pierces the other triangle's interior, the triangles intersect.
58 // Note: this is asymmetric and does not implement the full Möller separating-axis test;
59 // it can miss coplanar intersections and edge-on-edge contacts.
60 size_t iFaceA = 0, iFaceB = 0;
61 for (size_t i = 0; i < 2; i++) {
62 if (i == 0) {
63 iFaceA = face0;
64 iFaceB = face1;
65 } else {
66 iFaceA = face1;
67 iFaceB = face0;
68 }
69
70 // Plane of triangle B in the form n . x + d = 0, with n = faceNormals[iFaceB] and
71 // d = -n . v0. Any point x satisfies n . x + d = 0 iff x lies on the plane.
72 const auto& faceVertsB = mesh.faces[iFaceB];
73 T planeD = -(mesh.vertices[faceVertsB[0]].dot(faceNormals[iFaceB]));
74
75 const auto& faceVertsA = mesh.faces[iFaceA];
76
77 for (size_t iTriVertex = 0; iTriVertex < 3; iTriVertex++) {
78 // Treat edge (e0 -> e0+eRay) of triangle A as a parametric ray and intersect it
79 // with the plane of triangle B. Solve for t in: n . (e0 + t*eRay) + d = 0.
80 const Eigen::Vector3<T>& e0 = mesh.vertices[faceVertsA[iTriVertex]];
81 const Eigen::Vector3<T> eRay = mesh.vertices[faceVertsA[(iTriVertex + 1) % 3]] - e0;
82 // If eRay is (nearly) perpendicular to the plane normal, the edge is (nearly)
83 // parallel to the plane, so the denominator vanishes; skip to avoid division
84 // by zero. Tolerance is 1e-7 (float) / 1e-16 (double) on |eRay . n|, which is
85 // an absolute (not scale-invariant) threshold.
86 // TODO: Tolerance on |eRay . n| is not scale-invariant; it should be relative
87 // to ||eRay|| (and possibly ||n||, though n is unit-length here).
88 if (abs(eRay.dot(faceNormals[iFaceB])) - momentum::Eps<T>(1e-7, 1e-16) < 0) {
89 continue;
90 }
91 const T rayUnitLength =
92 -(e0.dot(faceNormals[iFaceB]) + planeD) / (eRay.dot(faceNormals[iFaceB]));
93 // Edge parametrization is t in [0,1]; values outside (0,1) mean the plane is
94 // hit beyond the edge endpoints. Endpoints (t=0 or t=1) are excluded, which
95 // matches the share-vertex early-out above and prevents double-counting.
96 if (rayUnitLength <= 0 || rayUnitLength >= 1) {
97 continue;
98 }
99
100 const Eigen::Vector3<T> pIntersect = e0 + rayUnitLength * eRay;
101
102 // Point-in-triangle test using same-side-of-edges via 2D signed areas in the
103 // xy plane (see sign() above). pIntersect is inside triangle B iff all three
104 // signed areas have the same sign (or zero), i.e., NOT (some negative AND some
105 // positive). This 2D projection is degenerate for triangles whose normal is
106 // close to the world Z axis; see TODO on sign().
107 const T s1 = sign(pIntersect, mesh.vertices[faceVertsB[0]], mesh.vertices[faceVertsB[1]]);
108 const T s2 = sign(pIntersect, mesh.vertices[faceVertsB[1]], mesh.vertices[faceVertsB[2]]);
109 const T s3 = sign(pIntersect, mesh.vertices[faceVertsB[2]], mesh.vertices[faceVertsB[0]]);
110
111 const bool has_neg = (s1 < 0) || (s2 < 0) || (s3 < 0);
112 const bool has_pos = (s1 > 0) || (s2 > 0) || (s3 > 0);
113
114 if (!(has_neg && has_pos)) {
115 return true;
116 }
117 }
118 }
119 return false;
120}
121
122template <typename T>
123std::vector<std::pair<int32_t, int32_t>> intersectMeshBruteForce(const MeshT<T>& mesh) {
124 std::vector<std::pair<int32_t, int32_t>> intersectingFaces;
125
126 // Per-face unit normals: n = (v1 - v0) x (v2 - v0) / ||...||. Degenerate (zero-area)
127 // triangles produce a zero cross product; .normalized() then returns NaN/zero, which
128 // can poison downstream tests in intersectFace.
129 // TODO: Skip or specially handle degenerate triangles where (v1-v0) x (v2-v0) ~= 0.
130 std::vector<Vector3<T>> faceNormals(mesh.faces.size());
131 for (size_t iFace = 0; iFace < mesh.faces.size(); iFace++) {
132 const auto& faceVerts = mesh.faces[iFace];
133 const Eigen::Vector3<T> v0 = mesh.vertices[faceVerts[0]];
134 const Eigen::Vector3<T> v1 = mesh.vertices[faceVerts[1]];
135 const Eigen::Vector3<T> v2 = mesh.vertices[faceVerts[2]];
136 faceNormals[iFace] = (v1 - v0).cross(v2 - v0).normalized();
137 }
138 // O(F^2) all-pairs check; iterate the upper-triangular pair set so each unordered
139 // pair is tested exactly once.
140 for (size_t iFace0 = 0; iFace0 < mesh.faces.size(); iFace0++) {
141 for (size_t iFace1 = iFace0 + 1; iFace1 < mesh.faces.size(); iFace1++) {
142 if (intersectFace(
143 mesh, faceNormals, static_cast<int32_t>(iFace0), static_cast<int32_t>(iFace1))) {
144 intersectingFaces.emplace_back(static_cast<int32_t>(iFace0), static_cast<int32_t>(iFace1));
145 }
146 }
147 }
148
149 return intersectingFaces;
150}
151
152template <typename T>
153std::vector<std::pair<int32_t, int32_t>> intersectMesh(const MeshT<T>& mesh) {
154 std::vector<std::pair<int32_t, int32_t>> intersectingFaces;
155
156 std::vector<axel::BoundingBox<T>> aabbs(mesh.faces.size());
157 axel::Bvh<T> bvh;
158
159 // Build per-face unit normals (see intersectMeshBruteForce for caveats on degenerate
160 // triangles) and per-face AABBs in a single pass. The AABB is seeded from v0 and then
161 // extended to include v1 and v2 so that min/max bound all three vertices.
162 std::vector<Vector3<T>> faceNormals(mesh.faces.size());
163 for (size_t iFace = 0; iFace < mesh.faces.size(); iFace++) {
164 const auto& faceVerts = mesh.faces[iFace];
165 const Eigen::Vector3<T> v0 = mesh.vertices[faceVerts[0]];
166 const Eigen::Vector3<T> v1 = mesh.vertices[faceVerts[1]];
167 const Eigen::Vector3<T> v2 = mesh.vertices[faceVerts[2]];
168 faceNormals[iFace] = (v1 - v0).cross(v2 - v0).normalized();
169
170 auto& aabb = aabbs[iFace];
171 aabb.aabb.min() = v0;
172 aabb.aabb.max() = v0;
173 aabb.id = static_cast<axel::Index>(iFace);
174 aabb.extend(v1);
175 aabb.extend(v2);
176 }
177 bvh.setBoundingBoxes(aabbs);
178
179 // Use the BVH to enumerate only AABB-overlapping face pairs (broad phase), then run
180 // the exact triangle-triangle test (narrow phase) on each candidate. Returning true
181 // from the callback tells axel to continue traversal.
182 bvh.traverseOverlappingPairs([&](size_t iFace0, size_t iFace1) {
183 if (intersectFace(
184 mesh, faceNormals, static_cast<int32_t>(iFace0), static_cast<int32_t>(iFace1))) {
185 intersectingFaces.emplace_back(static_cast<int32_t>(iFace0), static_cast<int32_t>(iFace1));
186 }
187 return true;
188 });
189
190 return intersectingFaces;
191}
192
193// explicit instantiations
195 const MeshT<float>& mesh,
196 const std::vector<Vector3<float>>& faceNormals,
197 const int32_t face0,
198 const int32_t face1);
200 const MeshT<double>& mesh,
201 const std::vector<Vector3<double>>& faceNormals,
202 const int32_t face0,
203 const int32_t face1);
204template std::vector<std::pair<int32_t, int32_t>> intersectMeshBruteForce<float>(
205 const MeshT<float>& mesh);
206template std::vector<std::pair<int32_t, int32_t>> intersectMeshBruteForce<double>(
207 const MeshT<double>& mesh);
208template std::vector<std::pair<int32_t, int32_t>> intersectMesh<float>(const MeshT<float>& mesh);
209template std::vector<std::pair<int32_t, int32_t>> intersectMesh<double>(const MeshT<double>& mesh);
210
211} // namespace momentum
constexpr T Eps(T FloatEps=T(1e-7), T DoubleEps=T(1e-16))
Returns a type-appropriate tolerance/epsilon value.
Definition constants.h:30
template std::vector< std::pair< int32_t, int32_t > > intersectMeshBruteForce< float >(const MeshT< float > &mesh)
bool intersectFace(const MeshT< T > &mesh, const std::vector< Vector3< T > > &faceNormals, const int32_t face0, const int32_t face1)
Tests whether two given triangle faces of a mesh intersect with each other.
template bool intersectFace< double >(const MeshT< double > &mesh, const std::vector< Vector3< double > > &faceNormals, const int32_t face0, const int32_t face1)
template std::vector< std::pair< int32_t, int32_t > > intersectMesh< float >(const MeshT< float > &mesh)
std::vector< std::pair< int32_t, int32_t > > intersectMeshBruteForce(const MeshT< T > &mesh)
Tests if the mesh self-intersects anywhere and returns all intersecting face pairs using a brute-forc...
std::vector< std::pair< int32_t, int32_t > > intersectMesh(const MeshT< T > &mesh)
Tests if the mesh self-intersects anywhere and returns all intersecting face pairs using a BVH (bound...
Vector3P< S > cross(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes cross product of Eigen::Vector3f and Vector3P.
Definition simd.h:309
template std::vector< std::pair< int32_t, int32_t > > intersectMeshBruteForce< double >(const MeshT< double > &mesh)
template bool intersectFace< float >(const MeshT< float > &mesh, const std::vector< Vector3< float > > &faceNormals, const int32_t face0, const int32_t face1)
template std::vector< std::pair< int32_t, int32_t > > intersectMesh< double >(const MeshT< double > &mesh)
Vector< T, 3 > Vector3
Definition types.h:236
A generic mesh representation with support for vertices, faces, lines, and texture coordinates.
Definition mesh.h:20
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
Definition mesh.h:28