Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closest point algorithm can be easily extended to support 2d points #238

Merged
merged 2 commits into from
Oct 5, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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