DistPoint3Rectangle3.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/Rectangle.h>
  10. #include <Mathematics/Vector3.h>
  11. namespace WwiseGTE
  12. {
  13. template <typename Real>
  14. class DCPQuery<Real, Vector3<Real>, Rectangle3<Real>>
  15. {
  16. public:
  17. struct Result
  18. {
  19. Real distance, sqrDistance;
  20. Real rectangleParameter[2];
  21. Vector3<Real> rectangleClosestPoint;
  22. };
  23. Result operator()(Vector3<Real> const& point, Rectangle3<Real> const& rectangle)
  24. {
  25. Result result;
  26. Vector3<Real> diff = rectangle.center - point;
  27. Real b0 = Dot(diff, rectangle.axis[0]);
  28. Real b1 = Dot(diff, rectangle.axis[1]);
  29. Real s0 = -b0, s1 = -b1;
  30. result.sqrDistance = Dot(diff, diff);
  31. if (s0 < -rectangle.extent[0])
  32. {
  33. s0 = -rectangle.extent[0];
  34. }
  35. else if (s0 > rectangle.extent[0])
  36. {
  37. s0 = rectangle.extent[0];
  38. }
  39. result.sqrDistance += s0 * (s0 + (Real)2 * b0);
  40. if (s1 < -rectangle.extent[1])
  41. {
  42. s1 = -rectangle.extent[1];
  43. }
  44. else if (s1 > rectangle.extent[1])
  45. {
  46. s1 = rectangle.extent[1];
  47. }
  48. result.sqrDistance += s1 * (s1 + (Real)2 * b1);
  49. // Account for numerical round-off error.
  50. if (result.sqrDistance < (Real)0)
  51. {
  52. result.sqrDistance = (Real)0;
  53. }
  54. result.distance = std::sqrt(result.sqrDistance);
  55. result.rectangleParameter[0] = s0;
  56. result.rectangleParameter[1] = s1;
  57. result.rectangleClosestPoint = rectangle.center;
  58. for (int i = 0; i < 2; ++i)
  59. {
  60. result.rectangleClosestPoint += result.rectangleParameter[i] * rectangle.axis[i];
  61. }
  62. return result;
  63. }
  64. };
  65. }