Skip to content

Commit

Permalink
Merge pull request #238 from SiliconKiwi/patch-1
Browse files Browse the repository at this point in the history
Closest point algorithm can be easily extended to support 2d points #238
  • Loading branch information
Groovounet committed Oct 5, 2014
2 parents 0684a5e + b5409fb commit 3839987
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions glm/gtx/closest_point.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ namespace glm
detail::tvec3<T, P> const & point,
detail::tvec3<T, P> const & a,
detail::tvec3<T, P> const & b);

/// 2d lines work as well
template <typename T, precision P>
GLM_FUNC_DECL detail::tvec2<T, P> closestPointOnLine(
detail::tvec2<T, P> const & point,
detail::tvec2<T, P> const & a,
detail::tvec2<T, P> const & b);

/// @}
}// namespace glm
Expand Down
21 changes: 21 additions & 0 deletions glm/gtx/closest_point.inl
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,25 @@ namespace glm
if(Distance >= LineLength) return b;
return a + LineDirection * Distance;
}

template <typename T, precision P>
GLM_FUNC_QUALIFIER detail::tvec2<T, P> closestPointOnLine
(
detail::tvec2<T, P> const & point,
detail::tvec2<T, P> const & a,
detail::tvec2<T, P> const & b
)
{
T LineLength = distance(a, b);
detail::tvec2<T, P> Vector = point - a;
detail::tvec2<T, P> LineDirection = (b - a) / LineLength;

// Project Vector to LineDirection to get the distance of point from a
T Distance = dot(Vector, LineDirection);

if(Distance <= T(0)) return a;
if(Distance >= LineLength) return b;
return a + LineDirection * Distance;
}

}//namespace glm

0 comments on commit 3839987

Please sign in to comment.