DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
gjk.h
1// Copyright (C) 2020-2026 Chris Richardson and Jørgen S. Dokken
2// Copyright (C) 2026 Garth N. Wells
3//
4// This file is part of DOLFINx (https://www.fenicsproject.org)
5//
6// SPDX-License-Identifier: LGPL-3.0-or-later
7
8#pragma once
9
10#include <algorithm>
11#include <array>
12#include <boost/multiprecision/cpp_bin_float.hpp>
13#include <cassert>
14#include <cmath>
15#include <concepts>
16#include <cstddef>
17#include <dolfinx/common/local_range.h>
18#include <functional>
19#include <iterator>
20#include <limits>
21#include <span>
22#include <spdlog/spdlog.h>
23#include <stdexcept>
24#include <thread>
25#include <vector>
26
27namespace dolfinx::geometry
28{
29
30namespace impl_gjk
31{
32
39template <typename T>
40inline std::array<T, 4> det4(const std::array<T, 12>& s)
41{
42 std::span<const T, 3> s0(s.begin(), 3);
43 std::span<const T, 3> s1(s.begin() + 3, 3);
44 std::span<const T, 3> s2(s.begin() + 6, 3);
45 std::span<const T, 3> s3(s.begin() + 9, 3);
46
47 std::array<T, 4> w;
48 T c0 = s2[1] * s3[2] - s2[2] * s3[1];
49 T c1 = s2[0] * s3[2] - s2[2] * s3[0];
50 T c2 = s2[0] * s3[1] - s2[1] * s3[0];
51 w[2] = -s0[0] * c0 + s0[1] * c1 - s0[2] * c2;
52 w[3] = s1[0] * c0 - s1[1] * c1 + s1[2] * c2;
53
54 c0 = s0[1] * s1[2] - s0[2] * s1[1];
55 c1 = s0[0] * s1[2] - s0[2] * s1[0];
56 c2 = s0[0] * s1[1] - s0[1] * s1[0];
57 w[0] = -s2[0] * c0 + s2[1] * c1 - s2[2] * c2;
58 w[1] = s3[0] * c0 - s3[1] * c1 + s3[2] * c2;
59
60 return w;
61}
62
67template <typename Vec>
68inline Vec::value_type dot3(const Vec& a, const Vec& b)
69{
70 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
71}
72
81template <typename T, std::size_t simplex_size>
82void nearest_simplex(const std::array<T, 12>& s, std::array<T, 4>& coordinates)
83{
84
85 SPDLOG_DEBUG("GJK: nearest_simplex({})", simplex_size);
86
87 if constexpr (simplex_size == 2)
88 {
89 // Simplex is an interval. Point may lie on the interval, or on either end.
90 // Compute lm = dot(s0, ds / |ds|)
91 std::span<const T, 3> s0(s.data(), 3);
92 std::span<const T, 3> s1(s.data() + 3, 3);
93
94 T lm = dot3(s0, s0) - dot3(s0, s1);
95 if (lm < 0.0)
96 {
97 SPDLOG_DEBUG("GJK: line point A");
98
99 coordinates[0] = 1.0;
100 coordinates[1] = 0.0;
101 return;
102 }
103 T mu = dot3(s1, s1) - dot3(s1, s0);
104 if (mu < 0.0)
105 {
106 SPDLOG_DEBUG("GJK: line point B");
107 coordinates[0] = 0.0;
108 coordinates[1] = 1.0;
109 return;
110 }
111
112 SPDLOG_DEBUG("GJK line: AB");
113 T f1 = 1.0 / (lm + mu);
114 coordinates[0] = mu * f1;
115 coordinates[1] = lm * f1;
116 return;
117 }
118 else if constexpr (simplex_size == 3)
119 {
120 // Simplex is a triangle. Point may lie in one of 7 regions (outside near a
121 // vertex, outside near an edge, or on the interior)
122 std::span<const T, 3> a(s.data(), 3);
123 std::span<const T, 3> b(s.data() + 3, 3);
124 std::span<const T, 3> c(s.data() + 6, 3);
125
126 T aa = dot3(a, a);
127 T ab = dot3(a, b);
128 T ac = dot3(a, c);
129 T d1 = aa - ab;
130 T d2 = aa - ac;
131 if (d1 < 0.0 and d2 < 0.0)
132 {
133 SPDLOG_DEBUG("GJK: Point A");
134 coordinates[0] = 1.0;
135 coordinates[1] = 0.0;
136 coordinates[2] = 0.0;
137 return;
138 }
139
140 T bb = dot3(b, b);
141 T bc = dot3(b, c);
142 T d3 = bb - ab;
143 T d4 = bb - bc;
144 if (d3 < 0.0 and d4 < 0.0)
145 {
146 SPDLOG_DEBUG("GJK: Point B");
147 coordinates[0] = 0.0;
148 coordinates[1] = 1.0;
149 coordinates[2] = 0.0;
150 return;
151 }
152
153 T cc = dot3(c, c);
154 T d5 = cc - ac;
155 T d6 = cc - bc;
156 if (d5 < 0.0 and d6 < 0.0)
157 {
158 SPDLOG_DEBUG("GJK: Point C");
159 coordinates[0] = 0.0;
160 coordinates[1] = 0.0;
161 coordinates[2] = 1.0;
162 return;
163 }
164
165 T vc = d4 * d1 - d1 * d3 + d3 * d2;
166 if (vc < 0.0 and d1 > 0.0 and d3 > 0.0)
167 {
168 SPDLOG_DEBUG("GJK: edge AB");
169 T f1 = 1.0 / (d1 + d3);
170 T lm = d1 * f1;
171 T mu = d3 * f1;
172 coordinates[0] = mu;
173 coordinates[1] = lm;
174 coordinates[2] = 0.0;
175 return;
176 }
177 T vb = d1 * d5 - d5 * d2 + d2 * d6;
178 if (vb < 0.0 and d2 > 0.0 and d5 > 0.0)
179 {
180 SPDLOG_DEBUG("GJK: edge AC");
181 T f1 = 1.0 / (d2 + d5);
182 T lm = d2 * f1;
183 T mu = d5 * f1;
184 coordinates[0] = mu;
185 coordinates[1] = 0.0;
186 coordinates[2] = lm;
187 return;
188 }
189 T va = d3 * d6 - d6 * d4 + d4 * d5;
190 if (va < 0.0 and d4 > 0.0 and d6 > 0.0)
191 {
192 SPDLOG_DEBUG("GJK: edge BC");
193 T f1 = 1.0 / (d4 + d6);
194 T lm = d4 * f1;
195 T mu = d6 * f1;
196 coordinates[0] = 0.0;
197 coordinates[1] = mu;
198 coordinates[2] = lm;
199 return;
200 }
201
202 SPDLOG_DEBUG("GJK: triangle ABC");
203 T f1 = 1.0 / (va + vb + vc);
204 coordinates[0] = va * f1;
205 coordinates[1] = vb * f1;
206 coordinates[2] = vc * f1;
207 return;
208 }
209 else if constexpr (simplex_size == 4)
210 {
211 // Most complex case, where simplex is a tetrahedron, with 15 possible
212 // outcomes (4 vertices, 6 edges, 4 facets and the interior).
213 std::ranges::fill(coordinates, 0.0);
214
215 T d[4][4];
216 for (int i = 0; i < 4; ++i)
217 // Compute dot products at each vertex
218 {
219 std::span<const T, 3> si(s.begin() + i * 3, 3);
220 T sii = dot3(si, si);
221 bool out = true;
222 for (int j = 0; j < 4; ++j)
223 {
224 std::span<const T, 3> sj(s.begin() + j * 3, 3);
225 if (i != j)
226 {
227 d[i][j] = (sii - dot3(si, sj));
228 SPDLOG_DEBUG("d[{}][{}] = {}", i, j, static_cast<double>(d[i][j]));
229 if (d[i][j] > 0.0)
230 out = false;
231 }
232 }
233 if (out)
234 {
235 // Return if a vertex is closest
236 coordinates[i] = 1.0;
237 return;
238 }
239 }
240
241 SPDLOG_DEBUG("Check for edges");
242
243 // Check if an edge is closest
244 T v[6][2] = {{0.0}};
245 int edges[6][2] = {{2, 3}, {1, 3}, {1, 2}, {0, 3}, {0, 2}, {0, 1}};
246 for (int i = 0; i < 6; ++i)
247 {
248 // Four vertices of the tetrahedron, j0 and j1 at the ends of the current
249 // edge and j2 and j3 on the opposing edge.
250 int j0 = edges[i][0];
251 int j1 = edges[i][1];
252 int j2 = edges[5 - i][0];
253 int j3 = edges[5 - i][1];
254 v[i][0] = d[j1][j2] * d[j0][j1] - d[j0][j1] * d[j1][j0]
255 + d[j1][j0] * d[j0][j2];
256 v[i][1] = d[j1][j3] * d[j0][j1] - d[j0][j1] * d[j1][j0]
257 + d[j1][j0] * d[j0][j3];
258
259 SPDLOG_DEBUG("v[{}] = {},{}", i, (double)v[i][0], (double)v[i][1]);
260 if (v[i][0] <= 0.0 and v[i][1] <= 0.0 and d[j0][j1] >= 0.0
261 and d[j1][j0] >= 0.0)
262 {
263 // On an edge
264 T f1 = 1.0 / (d[j0][j1] + d[j1][j0]);
265 coordinates[j0] = f1 * d[j1][j0];
266 coordinates[j1] = f1 * d[j0][j1];
267 return;
268 }
269 }
270
271 // Now check the facets of a tetrahedron
272 std::array<T, 4> w = det4(s);
273 T wsum = w[0] + w[1] + w[2] + w[3];
274 if (wsum < 0.0)
275 {
276 w[0] = -w[0];
277 w[1] = -w[1];
278 w[2] = -w[2];
279 w[3] = -w[3];
280 wsum = -wsum;
281 }
282
283 if (w[0] < 0.0 and v[2][0] > 0.0 and v[4][0] > 0.0 and v[5][0] > 0.0)
284 {
285 T f1 = 1.0 / (v[2][0] + v[4][0] + v[5][0]);
286 coordinates[0] = v[2][0] * f1;
287 coordinates[1] = v[4][0] * f1;
288 coordinates[2] = v[5][0] * f1;
289 coordinates[3] = 0.0;
290 return;
291 }
292
293 if (w[1] < 0.0 and v[1][0] > 0.0 and v[3][0] > 0.0 and v[5][1] > 0.0)
294 {
295 T f1 = 1.0 / (v[1][0] + v[3][0] + v[5][1]);
296 coordinates[0] = v[1][0] * f1;
297 coordinates[1] = v[3][0] * f1;
298 coordinates[2] = 0.0;
299 coordinates[3] = v[5][1] * f1;
300 return;
301 }
302
303 if (w[2] < 0.0 and v[0][0] > 0.0 and v[3][1] > 0 and v[4][1] > 0.0)
304 {
305 T f1 = 1.0 / (v[0][0] + v[3][1] + v[4][1]);
306 coordinates[0] = v[0][0] * f1;
307 coordinates[1] = 0.0;
308 coordinates[2] = v[3][1] * f1;
309 coordinates[3] = v[4][1] * f1;
310 return;
311 }
312
313 if (w[3] < 0.0 and v[0][1] > 0.0 and v[1][1] > 0.0 and v[2][1] > 0.0)
314 {
315 T f1 = 1.0 / (v[0][1] + v[1][1] + v[2][1]);
316 coordinates[0] = 0.0;
317 coordinates[1] = v[0][1] * f1;
318 coordinates[2] = v[1][1] * f1;
319 coordinates[3] = v[2][1] * f1;
320 return;
321 }
322
323 // Point lies in interior of tetrahedron with these barycentric coordinates
324 coordinates[0] = w[3] / wsum;
325 coordinates[1] = w[2] / wsum;
326 coordinates[2] = w[1] / wsum;
327 coordinates[3] = w[0] / wsum;
328 return;
329 }
330 else
331 {
332 // Evaluated at compile-time instead of runtime!
333 static_assert(simplex_size >= 2 && simplex_size <= 4,
334 "Number of rows defining simplex not supported.");
335 }
336}
337
342template <typename T>
343inline int support(std::span<const T> bd, const std::array<T, 3>& v)
344{
345 int i = 0;
346 T qmax = bd[0] * v[0] + bd[1] * v[1] + bd[2] * v[2];
347 for (std::size_t m = 1; m < bd.size() / 3; ++m)
348 {
349 T q = bd[3 * m] * v[0] + bd[3 * m + 1] * v[1] + bd[3 * m + 2] * v[2];
350 if (q > qmax)
351 {
352 qmax = q;
353 i = m;
354 }
355 }
356
357 return i;
358}
359} // namespace impl_gjk
360
374template <std::floating_point T,
375 typename U = boost::multiprecision::cpp_bin_float_double_extended>
376std::array<T, 3> compute_distance_gjk(std::span<const T> p0,
377 std::span<const T> q0)
378{
379 assert(p0.size() % 3 == 0);
380 assert(q0.size() % 3 == 0);
381
382 constexpr int maxk = 15; // Maximum number of iterations of the GJK algorithm
383 const U eps = 1000 * std::numeric_limits<U>::epsilon();
384
385 // Initialize distance vector x_k
386 std::array<U, 3> x_k = {static_cast<U>(p0[0]) - static_cast<U>(q0[0]),
387 static_cast<U>(p0[1]) - static_cast<U>(q0[1]),
388 static_cast<U>(p0[2]) - static_cast<U>(q0[2])};
389 // Initialize simplex
390 std::array<U, 12> s = {0}; // Max simplex is a tetrahedron
391 s[0] = x_k[0];
392 s[1] = x_k[1];
393 s[2] = x_k[2];
394 std::array<U, 4> lmn = {0}; // Scratch memory for barycentric
395 // coordinates of closest point in simplex
396 std::size_t simplex_size = 1;
397 // Begin GJK iteration
398 int k;
399 for (k = 0; k < maxk; ++k)
400 {
401
402 // Compute the squared norm of current iterate to normalize support search
403 // in original precision
404 const U x_norm2 = impl_gjk::dot3(x_k, x_k);
405 std::array<U, 3> x_k_normalized = x_k;
406 if (x_norm2 > eps * eps)
407 {
408 // ADL lookup:
409 // If U is double/float use std::sqrt
410 // If U is a boost::multiprecision member use boost::multiprecision::sqrt
411 using std::sqrt;
412 U inv_norm = U(1.0) / sqrt(x_norm2);
413 x_k_normalized[0] *= inv_norm;
414 x_k_normalized[1] *= inv_norm;
415 x_k_normalized[2] *= inv_norm;
416 }
417 // Compute support point in original precision
418 std::array<T, 3> dir_p = {static_cast<T>(-x_k_normalized[0]),
419 static_cast<T>(-x_k_normalized[1]),
420 static_cast<T>(-x_k_normalized[2])};
421 std::array<T, 3> dir_q
422 = {static_cast<T>(x_k_normalized[0]), static_cast<T>(x_k_normalized[1]),
423 static_cast<T>(x_k_normalized[2])};
424 int ip = impl_gjk::support(p0, dir_p);
425 int iq = impl_gjk::support(q0, dir_q);
426
427 // Only cast the winning support points to U
428 std::array<U, 3> s_k
429 = {static_cast<U>(p0[ip * 3]) - static_cast<U>(q0[iq * 3]),
430 static_cast<U>(p0[ip * 3 + 1]) - static_cast<U>(q0[iq * 3 + 1]),
431 static_cast<U>(p0[ip * 3 + 2]) - static_cast<U>(q0[iq * 3 + 2])};
432
433 // Break if the newly found support point s_k is already in the simplex
434 std::size_t m;
435 for (m = 0; m < simplex_size; ++m)
436 {
437 auto it = std::next(s.begin(), 3 * m);
438 if (std::equal(it, std::next(it, 3), s_k.begin(), s_k.end()))
439 break;
440 }
441
442 if (m != simplex_size)
443 break;
444
445 // 1st exit condition: (x_k - s_k).x_k = 0
446 const U xs_diff = x_norm2 - impl_gjk::dot3(x_k, s_k);
447 if (xs_diff < (eps * x_norm2) or xs_diff < eps)
448 break;
449
450 SPDLOG_DEBUG("GJK: xs_diff={}/{}", static_cast<double>(xs_diff),
451 static_cast<double>(eps));
452
453 // Add new vertex to simplex
454 assert(simplex_size < 4);
455 std::ranges::copy(s_k, s.begin() + 3 * simplex_size);
456 ++simplex_size;
457
458 // Find nearest subset of simplex
459 switch (simplex_size)
460 {
461 case 2:
462 impl_gjk::nearest_simplex<U, 2>(s, lmn);
463 break;
464 case 3:
465 impl_gjk::nearest_simplex<U, 3>(s, lmn);
466 break;
467 case 4:
468 impl_gjk::nearest_simplex<U, 4>(s, lmn);
469 break;
470 default:
471 throw std::runtime_error("Invalid simplex size");
472 }
473
474 // Recompute x_k and keep points with non-zero values in lmn
475 std::size_t j = 0;
476 x_k = {0.0, 0.0, 0.0};
477 for (std::size_t i = 0; i < simplex_size; ++i)
478 {
479 std::span<const U> sc(std::next(s.begin(), 3 * i), 3);
480 if (lmn[i] > 0.0)
481 {
482 x_k[0] += lmn[i] * sc[0];
483 x_k[1] += lmn[i] * sc[1];
484 x_k[2] += lmn[i] * sc[2];
485 if (i > j)
486 std::ranges::copy(sc, std::next(s.begin(), 3 * j));
487 ++j;
488 }
489 }
490 simplex_size = j;
491
492 // Origin is in the interior of a tetrahedron: bodies intersect. Exit
493 // here, since rounding can leave |x_k| above the tolerance of the 3rd
494 // exit condition and the simplex cannot grow further.
495 if (simplex_size == 4)
496 break;
497
498 // 2nd exit condition - strict monotonicity
499 const U x_next_norm2 = impl_gjk::dot3(x_k, x_k);
500 if (x_norm2 <= x_next_norm2)
501 break;
502
503 // 3rd exit condition - intersecting or touching
504 if (x_next_norm2 < eps * eps)
505 break;
506 }
507
508 if (k == maxk)
509 throw std::runtime_error("GJK error - max iteration limit reached");
510 return {static_cast<T>(x_k[0]), static_cast<T>(x_k[1]),
511 static_cast<T>(x_k[2])};
512}
513
531template <std::floating_point T,
532 typename U = boost::multiprecision::cpp_bin_float_double_extended>
533std::vector<T>
534compute_distances_gjk(const std::vector<std::span<const T>>& bodies,
535 std::span<const T> q, int num_threads)
536{
537 if (num_threads <= 0)
538 throw std::invalid_argument("num_threads must be >= 1.");
539
540 std::size_t total_size = bodies.size();
541 num_threads
542 = std::max<std::size_t>(1, std::min(num_threads, (int)total_size));
543
544 std::vector<T> results(total_size * 3);
545 auto compute_chunk
546 = [](std::vector<T>& chunk_results,
547 const std::vector<std::span<const T>>& chunk_bodies, std::size_t c0,
548 std::size_t c1, std::span<const T> q_ref)
549 {
550 for (std::size_t i = c0; i < c1; ++i)
551 {
552 // Using U explicitly as the internal precision type
553 std::array<T, 3> dist
554 = compute_distance_gjk<T, U>(chunk_bodies[i], q_ref);
555 chunk_results[3 * i + 0] = dist[0];
556 chunk_results[3 * i + 1] = dist[1];
557 chunk_results[3 * i + 2] = dist[2];
558 }
559 };
560
561 std::vector<std::jthread> threads;
562 for (int i = 1; i < num_threads; ++i)
563 {
564 auto [c0, c1] = common::local_range(i, total_size, num_threads);
565 threads.emplace_back(compute_chunk, std::ref(results), std::ref(bodies), c0,
566 c1, std::ref(q));
567 }
568 auto [c0, c1] = common::local_range(0, total_size, num_threads);
569 compute_chunk(std::ref(results), std::cref(bodies), c0, c1, q);
570
571 return results;
572}
573
574} // namespace dolfinx::geometry
constexpr std::array< std::int64_t, 2 > local_range(int index, std::int64_t N, int size)
Partition a global range [0, N - 1] across callers into non-overlapping sub-partitions of almost equa...
Definition local_range.h:26
Geometry data structures and algorithms.
Definition BoundingBoxTree.h:26
std::vector< T > compute_distances_gjk(const std::vector< std::span< const T > > &bodies, std::span< const T > q, int num_threads)
Compute the distance between a sequence of convex bodies p0, ..., pN and q, each defined by a set of ...
Definition gjk.h:534
std::array< T, 3 > compute_distance_gjk(std::span< const T > p0, std::span< const T > q0)
Compute the distance between two convex bodies p0 and q0, each defined by a set of points.
Definition gjk.h:376