line_segment_in_rectangle.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "line_segment_in_rectangle.h"
  2. bool igl::line_segment_in_rectangle(
  3. const Eigen::Vector2d & s,
  4. const Eigen::Vector2d & d,
  5. const Eigen::Vector2d & A,
  6. const Eigen::Vector2d & B)
  7. {
  8. using namespace std;
  9. using namespace Eigen;
  10. using namespace igl;
  11. // http://stackoverflow.com/a/100165/148668
  12. const auto SegmentIntersectRectangle = [](double a_rectangleMinX,
  13. double a_rectangleMinY,
  14. double a_rectangleMaxX,
  15. double a_rectangleMaxY,
  16. double a_p1x,
  17. double a_p1y,
  18. double a_p2x,
  19. double a_p2y)->bool
  20. {
  21. // Find min and max X for the segment
  22. double minX = a_p1x;
  23. double maxX = a_p2x;
  24. if(a_p1x > a_p2x)
  25. {
  26. minX = a_p2x;
  27. maxX = a_p1x;
  28. }
  29. // Find the intersection of the segment's and rectangle's x-projections
  30. if(maxX > a_rectangleMaxX)
  31. {
  32. maxX = a_rectangleMaxX;
  33. }
  34. if(minX < a_rectangleMinX)
  35. {
  36. minX = a_rectangleMinX;
  37. }
  38. if(minX > maxX) // If their projections do not intersect return false
  39. {
  40. return false;
  41. }
  42. // Find corresponding min and max Y for min and max X we found before
  43. double minY = a_p1y;
  44. double maxY = a_p2y;
  45. double dx = a_p2x - a_p1x;
  46. if(fabs(dx) > 0.0000001)
  47. {
  48. double a = (a_p2y - a_p1y) / dx;
  49. double b = a_p1y - a * a_p1x;
  50. minY = a * minX + b;
  51. maxY = a * maxX + b;
  52. }
  53. if(minY > maxY)
  54. {
  55. double tmp = maxY;
  56. maxY = minY;
  57. minY = tmp;
  58. }
  59. // Find the intersection of the segment's and rectangle's y-projections
  60. if(maxY > a_rectangleMaxY)
  61. {
  62. maxY = a_rectangleMaxY;
  63. }
  64. if(minY < a_rectangleMinY)
  65. {
  66. minY = a_rectangleMinY;
  67. }
  68. if(minY > maxY) // If Y-projections do not intersect return false
  69. {
  70. return false;
  71. }
  72. return true;
  73. };
  74. const double minX = min(A(0),B(0));
  75. const double minY = min(A(1),B(1));
  76. const double maxX = max(A(0),B(0));
  77. const double maxY = max(A(1),B(1));
  78. bool ret = SegmentIntersectRectangle(minX,minY,maxX,maxY,s(0),s(1),d(0),d(1));
  79. return ret;
  80. }