diff --git a/engine/math/CMakeLists.txt b/engine/math/CMakeLists.txt index dbd9363..1c71d5c 100755 --- a/engine/math/CMakeLists.txt +++ b/engine/math/CMakeLists.txt @@ -7,7 +7,7 @@ set(SRC include/plane.hpp src/transform.cpp - src/math.cpp) + src/math.cpp include/ray.hpp) add_library(Math STATIC ${SRC}) target_include_directories(Math PUBLIC include) diff --git a/engine/math/include/math.hpp b/engine/math/include/math.hpp index 3b50805..2b600fa 100755 --- a/engine/math/include/math.hpp +++ b/engine/math/include/math.hpp @@ -3,6 +3,7 @@ #include "matrix.hpp" #include "transform.hpp" #include "vector.hpp" +#include "ray.hpp" constexpr double PI = 3.141592653589793; diff --git a/engine/math/include/ray.hpp b/engine/math/include/ray.hpp new file mode 100644 index 0000000..099d6af --- /dev/null +++ b/engine/math/include/ray.hpp @@ -0,0 +1,8 @@ +#pragma once + +struct ray { + Vector3 origin, direction; + float t = 0.0f; +}; + +float closest_distance_between_lines(ray& l1, ray& l2); \ No newline at end of file diff --git a/engine/math/src/math.cpp b/engine/math/src/math.cpp index 1743d0f..0dfa24e 100755 --- a/engine/math/src/math.cpp +++ b/engine/math/src/math.cpp @@ -167,3 +167,23 @@ Quaternion angle_axis(const float angle, const Vector3 axis) { return result; } + +// from https://nelari.us/post/gizmos/ +float closest_distance_between_lines(ray& l1, ray& l2) { + const Vector3 dp = l2.origin - l1.origin; + const float v12 = dot(l1.direction, l1.direction); + const float v22 = dot(l2.direction, l2.direction); + const float v1v2 = dot(l1.direction, l2.direction); + + const float det = v1v2 * v1v2 - v12 * v22; + + const float inv_det = 10.f / det; + + const float dpv1 = dot(dp, l1.direction); + const float dpv2 = dot(dp, l2.direction); + + l1.t = inv_det * (v22 * dpv1 - v1v2 * dpv2); + l2.t = inv_det * (v1v2 * dpv1 - v12 * dpv2); + + return length(dp + l2.direction * l2.t - l1.direction * l1.t); +} \ No newline at end of file