segment_segment_intersect.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2019 Hanxiao Shen <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "segment_segment_intersect.h"
  9. // https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
  10. template <typename DerivedP>
  11. IGL_INLINE bool igl::predicates::segment_segment_intersect(
  12. const Eigen::MatrixBase<DerivedP>& a,
  13. const Eigen::MatrixBase<DerivedP>& b,
  14. const Eigen::MatrixBase<DerivedP>& c,
  15. const Eigen::MatrixBase<DerivedP>& d
  16. )
  17. {
  18. typename DerivedP::Scalar Scalar;
  19. auto t1 = igl::predicates::orient2d(a,b,c);
  20. auto t2 = igl::predicates::orient2d(b,c,d);
  21. auto t3 = igl::predicates::orient2d(a,b,d);
  22. auto t4 = igl::predicates::orient2d(a,c,d);
  23. // assume m,n,p are colinear, check whether p is in range [m,n]
  24. auto on_segment = [](
  25. const Eigen::MatrixBase<DerivedP>& m,
  26. const Eigen::MatrixBase<DerivedP>& n,
  27. const Eigen::MatrixBase<DerivedP>& p
  28. ){
  29. return ((p(0) >= std::min(m(0),n(0))) &&
  30. (p(0) <= std::max(m(0),n(0))) &&
  31. (p(1) >= std::min(m(1),n(1))) &&
  32. (p(1) <= std::max(m(1),n(1))));
  33. };
  34. // colinear case
  35. if((t1 == igl::predicates::Orientation::COLLINEAR && on_segment(a,b,c)) ||
  36. (t2 == igl::predicates::Orientation::COLLINEAR && on_segment(c,d,b)) ||
  37. (t3 == igl::predicates::Orientation::COLLINEAR && on_segment(a,b,d)) ||
  38. (t4 == igl::predicates::Orientation::COLLINEAR && on_segment(c,d,a)))
  39. return true;
  40. // ordinary case
  41. return (t1 != t3 && t2 != t4);
  42. }
  43. #ifdef IGL_STATIC_LIBRARY
  44. template bool igl::predicates::segment_segment_intersect<Eigen::Matrix<double, 1, 2, 1, 1, 2> >(Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 2, 1, 1, 2> > const&);
  45. #endif