From 0a6902acaeb1233540bcabfbbb28a7055e0240ad Mon Sep 17 00:00:00 2001 From: c0d3d3v Date: Tue, 3 May 2022 13:47:28 +0200 Subject: [PATCH] Optimization of the closest_point_on_line function --- src/base/vmath.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/base/vmath.h b/src/base/vmath.h index e684e30b3..ec02c950a 100644 --- a/src/base/vmath.h +++ b/src/base/vmath.h @@ -145,16 +145,16 @@ typedef vector2_base bvec2; typedef vector2_base ivec2; template -inline bool closest_point_on_line(vector2_base line_point0, vector2_base line_point1, vector2_base target_point, vector2_base &out_pos) +inline bool closest_point_on_line(vector2_base line_pointA, vector2_base line_pointB, vector2_base target_point, vector2_base &out_pos) { - vector2_base c = target_point - line_point0; - vector2_base v = (line_point1 - line_point0); - T d = length(line_point0 - line_point1); - if(d > 0) + vector2_base AP = target_point - line_pointA; + vector2_base AB = line_pointB - line_pointA; + T SquaredMagnitudeAB = dot(AB, AB); + if(SquaredMagnitudeAB > 0) { - v = normalize_pre_length(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