segment_segment_intersect.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. auto t1 = igl::predicates::orient2d(a,b,c);
  19. auto t2 = igl::predicates::orient2d(b,c,d);
  20. auto t3 = igl::predicates::orient2d(a,b,d);
  21. auto t4 = igl::predicates::orient2d(a,c,d);
  22. // assume m,n,p are colinear, check whether p is in range [m,n]
  23. auto on_segment = [](
  24. const Eigen::MatrixBase<DerivedP>& m,
  25. const Eigen::MatrixBase<DerivedP>& n,
  26. const Eigen::MatrixBase<DerivedP>& p
  27. ){
  28. return ((p(0) >= std::min(m(0),n(0))) &&
  29. (p(0) <= std::max(m(0),n(0))) &&
  30. (p(1) >= std::min(m(1),n(1))) &&
  31. (p(1) <= std::max(m(1),n(1))));
  32. };
  33. // colinear case
  34. if((t1 == igl::predicates::Orientation::COLLINEAR && on_segment(a,b,c)) ||
  35. (t2 == igl::predicates::Orientation::COLLINEAR && on_segment(c,d,b)) ||
  36. (t3 == igl::predicates::Orientation::COLLINEAR && on_segment(a,b,d)) ||
  37. (t4 == igl::predicates::Orientation::COLLINEAR && on_segment(c,d,a)))
  38. return true;
  39. // ordinary case
  40. return (t1 != t3 && t2 != t4);
  41. }
  42. #ifdef IGL_STATIC_LIBRARY
  43. 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&);
  44. #endif