DistLineLine.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <Mathematics/DCPQuery.h>
  9. #include <Mathematics/Line.h>
  10. namespace WwiseGTE
  11. {
  12. template <int N, typename Real>
  13. class DCPQuery<Real, Line<N, Real>, Line<N, Real>>
  14. {
  15. public:
  16. struct Result
  17. {
  18. Real distance, sqrDistance;
  19. Real parameter[2];
  20. Vector<N, Real> closestPoint[2];
  21. };
  22. Result operator()(Line<N, Real> const& line0, Line<N, Real> const& line1)
  23. {
  24. Result result;
  25. Vector<N, Real> diff = line0.origin - line1.origin;
  26. Real a01 = -Dot(line0.direction, line1.direction);
  27. Real b0 = Dot(diff, line0.direction);
  28. Real s0, s1;
  29. if (std::fabs(a01) < (Real)1)
  30. {
  31. // Lines are not parallel.
  32. Real det = (Real)1 - a01 * a01;
  33. Real b1 = -Dot(diff, line1.direction);
  34. s0 = (a01 * b1 - b0) / det;
  35. s1 = (a01 * b0 - b1) / det;
  36. }
  37. else
  38. {
  39. // Lines are parallel, select any pair of closest points.
  40. s0 = -b0;
  41. s1 = (Real)0;
  42. }
  43. result.parameter[0] = s0;
  44. result.parameter[1] = s1;
  45. result.closestPoint[0] = line0.origin + s0 * line0.direction;
  46. result.closestPoint[1] = line1.origin + s1 * line1.direction;
  47. diff = result.closestPoint[0] - result.closestPoint[1];
  48. result.sqrDistance = Dot(diff, diff);
  49. result.distance = std::sqrt(result.sqrDistance);
  50. return result;
  51. }
  52. };
  53. // Template aliases for convenience.
  54. template <int N, typename Real>
  55. using DCPLineLine = DCPQuery<Real, Line<N, Real>, Line<N, Real>>;
  56. template <typename Real>
  57. using DCPLine2Line2 = DCPLineLine<2, Real>;
  58. template <typename Real>
  59. using DCPLine3Line3 = DCPLineLine<3, Real>;
  60. }