Optimization of the closest_point_on_line function

This commit is contained in:
c0d3d3v 2022-05-03 13:47:28 +02:00
parent 87893ceca7
commit 0a6902acae
No known key found for this signature in database
GPG key ID: 068AF680530DFF31

View file

@ -145,16 +145,16 @@ typedef vector2_base<bool> bvec2;
typedef vector2_base<int> ivec2;
template<typename T>
inline bool closest_point_on_line(vector2_base<T> line_point0, vector2_base<T> line_point1, vector2_base<T> target_point, vector2_base<T> &out_pos)
inline bool closest_point_on_line(vector2_base<T> line_pointA, vector2_base<T> line_pointB, vector2_base<T> target_point, vector2_base<T> &out_pos)
{
vector2_base<T> c = target_point - line_point0;
vector2_base<T> v = (line_point1 - line_point0);
T d = length(line_point0 - line_point1);
if(d > 0)
vector2_base<T> AP = target_point - line_pointA;
vector2_base<T> AB = line_pointB - line_pointA;
T SquaredMagnitudeAB = dot(AB, AB);
if(SquaredMagnitudeAB > 0)
{
v = normalize_pre_length<T>(v, d);
T t = dot(v, c) / d;
out_pos = mix(line_point0, line_point1, clamp(t, (T)0, (T)1));
T APdotAB = dot(AP, AB);
T t = APdotAB / SquaredMagnitudeAB;
out_pos = line_pointA + AB * clamp(t, (T)0, (T)1);
return true;
}
else