MeshLib C++ Docs
Loading...
Searching...
No Matches
MRClosestPointInTriangle.h
Go to the documentation of this file.
1
16#pragma once
17
18#include "MRVector3.h"
19#include "MRTriPoint.h"
20
21namespace MR
22{
25
26
27template <typename T>
28static std::pair<Vector3<T>, TriPoint<T>> closestPointInTriangle( const Vector3<T>& p, const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c )
29{
31 const Vector3<T> ab = b - a;
32 const Vector3<T> ac = c - a;
33 const Vector3<T> ap = p - a;
34
35 const T d1 = dot( ab, ap );
36 const T d2 = dot( ac, ap );
37 if ( d1 <= 0 && d2 <= 0 )
38 return { a, { 0, 0 } };
39
40 const Vector3<T> bp = p - b;
41 const T d3 = dot( ab, bp );
42 const T d4 = dot( ac, bp );
43 if ( d3 >= 0 && d4 <= d3 )
44 return { b, { 1, 0 } };
45
46 const Vector3<T> cp = p - c;
47 const T d5 = dot( ab, cp );
48 const T d6 = dot( ac, cp );
49 if ( d6 >= 0 && d5 <= d6 )
50 return { c, { 0, 1 } };
51
52 const T vc = d1 * d4 - d3 * d2;
53 if ( vc <= 0 && d1 >= 0 && d3 <= 0 )
54 {
55 const T v = d1 / ( d1 - d3 );
56 return { a + v * ab, { v, 0 } };
57 }
58
59 const T vb = d5 * d2 - d1 * d6;
60 if ( vb <= 0 && d6 <= 0 )
61 {
62 assert( d2 >= 0 );
63 const T v = d2 / ( d2 - d6 );
64 return { a + v * ac, { 0, v } };
65 }
66
67 const T va = d3 * d6 - d5 * d4;
68 if ( va <= 0 )
69 {
71 if ( d4 < d3 )
72 return { b, { 1, 0 } };
73
75 if ( d5 < d6 )
76 return { c, { 0, 1 } };
77
79 const T v = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
80 return { b + v * ( c - b ), { 1 - v, v } };
81 }
82
83 assert( va > 0 && vb > 0 && vc > 0 );
84 const T denom = 1 / ( va + vb + vc );
85 const T v = vb * denom;
86 const T w = vc * denom;
87 return { a + v * ab + w * ac, { v, w } };
88}
89
90}
constexpr auto dot(A a, A b)
Definition MRImGuiVectorOperators.h:129
only for bindings generation
Definition MRCameraOrientationPlugin.h:8