Browse Source

Merge pull request #238 from SiliconKiwi/patch-1

Closest point algorithm can be easily extended to support 2d points #238
Christophe Riccio 11 years ago
parent
commit
38399875f4
2 changed files with 28 additions and 0 deletions
  1. 7 0
      glm/gtx/closest_point.hpp
  2. 21 0
      glm/gtx/closest_point.inl

+ 7 - 0
glm/gtx/closest_point.hpp

@@ -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

+ 21 - 0
glm/gtx/closest_point.inl

@@ -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