BsLineSegment3.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsLineSegment3.h"
  4. #include "BsRay.h"
  5. namespace BansheeEngine
  6. {
  7. LineSegment3::LineSegment3()
  8. :mStart(BsZero), mEnd(BsZero)
  9. { }
  10. LineSegment3::LineSegment3(const Vector3& start, const Vector3& end)
  11. :mStart(start), mEnd(end)
  12. {
  13. }
  14. std::pair<std::array<Vector3, 2>, float> LineSegment3::getNearestPoint(const Ray& ray) const
  15. {
  16. const Vector3& org = ray.getOrigin();
  17. const Vector3& dir = ray.getDirection();
  18. Vector3 segDir = mEnd - mStart;
  19. float segExtent = segDir.normalize() * 0.5f;
  20. Vector3 segCenter = mStart + segDir * segExtent;
  21. Vector3 diff = org - segCenter;
  22. float a01 = -dir.dot(segDir);
  23. float b0 = diff.dot(dir);
  24. float c = diff.dot(diff);
  25. float det = fabs(1.0f - a01*a01);
  26. float s0, s1;
  27. float sqrDistance;
  28. if (det > 0.0f) // Not parallel
  29. {
  30. float b1 = -diff.dot(segDir);
  31. s1 = a01 * b0 - b1;
  32. float extDet = segExtent * det;
  33. if (s1 >= -extDet)
  34. {
  35. if (s1 <= extDet) // Interior of the segment and interior of the ray are closest
  36. {
  37. float invDet = 1.0f / det;
  38. s0 = (a01*b1 - b0)*invDet;
  39. s1 *= invDet;
  40. sqrDistance = s0*(s0 + a01*s1 + 2.0f*b0) +
  41. s1*(a01*s0 + s1 + 2.0f*b1) + c;
  42. }
  43. else // Segment end and interior of the ray are closest
  44. {
  45. s1 = segExtent;
  46. s0 = -(a01*s1 + b0);
  47. sqrDistance = -s0*s0 + s1*(s1 + (2.0f)*b1) + c;
  48. }
  49. }
  50. else // Segment start and interior of the ray are closest
  51. {
  52. s1 = -segExtent;
  53. s0 = -(a01*s1 + b0);
  54. sqrDistance = -s0*s0 + s1*(s1 + (2.0f)*b1) + c;
  55. }
  56. }
  57. else // Parallel
  58. {
  59. s1 = 0;
  60. s0 = -b0;
  61. sqrDistance = b0*s0 + c;
  62. }
  63. if (sqrDistance < 0.0f)
  64. sqrDistance = 0.0f;
  65. float distance = std::sqrt(sqrDistance);
  66. std::array<Vector3, 2> nearestPoints;
  67. nearestPoints[0] = org + s0 * dir;
  68. nearestPoints[1] = segCenter + s1 * segDir;
  69. return std::make_pair(nearestPoints, distance);
  70. }
  71. }