ray_mesh_intersect.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "ray_mesh_intersect.h"
  2. extern "C"
  3. {
  4. #include "raytri.c"
  5. }
  6. template <
  7. typename Derivedsource,
  8. typename Deriveddir,
  9. typename DerivedV,
  10. typename DerivedF>
  11. IGL_INLINE bool igl::ray_mesh_intersect(
  12. const Eigen::MatrixBase<Derivedsource> & s,
  13. const Eigen::MatrixBase<Deriveddir> & dir,
  14. const Eigen::MatrixBase<DerivedV> & V,
  15. const Eigen::MatrixBase<DerivedF> & F,
  16. std::vector<igl::Hit> & hits)
  17. {
  18. using namespace Eigen;
  19. using namespace std;
  20. // Should be but can't be const
  21. Vector3d s_d = s.template cast<double>();
  22. Vector3d dir_d = dir.template cast<double>();
  23. hits.clear();
  24. // loop over all triangles
  25. for(int f = 0;f<F.rows();f++)
  26. {
  27. // Should be but can't be const
  28. RowVector3d v0 = V.row(F(f,0)).template cast<double>();
  29. RowVector3d v1 = V.row(F(f,1)).template cast<double>();
  30. RowVector3d v2 = V.row(F(f,2)).template cast<double>();
  31. // shoot ray, record hit
  32. double t,u,v;
  33. if(intersect_triangle1(
  34. s_d.data(), dir_d.data(), v0.data(), v1.data(), v2.data(), &t, &u, &v) &&
  35. t>0)
  36. {
  37. hits.push_back({(int)f,(int)-1,(float)u,(float)v,(float)t});
  38. }
  39. }
  40. // Sort hits based on distance
  41. std::sort(
  42. hits.begin(),
  43. hits.end(),
  44. [](const Hit & a, const Hit & b)->bool{ return a.t < b.t;});
  45. return hits.size() > 0;
  46. }
  47. template <
  48. typename Derivedsource,
  49. typename Deriveddir,
  50. typename DerivedV,
  51. typename DerivedF>
  52. IGL_INLINE bool igl::ray_mesh_intersect(
  53. const Eigen::MatrixBase<Derivedsource> & source,
  54. const Eigen::MatrixBase<Deriveddir> & dir,
  55. const Eigen::MatrixBase<DerivedV> & V,
  56. const Eigen::MatrixBase<DerivedF> & F,
  57. igl::Hit & hit)
  58. {
  59. std::vector<igl::Hit> hits;
  60. ray_mesh_intersect(source,dir,V,F,hits);
  61. if(hits.size() > 0)
  62. {
  63. hit = hits.front();
  64. return true;
  65. }else
  66. {
  67. return false;
  68. }
  69. }
  70. #ifdef IGL_STATIC_LIBRARY
  71. // Explicit template instanciation
  72. template bool igl::ray_mesh_intersect<Eigen::Matrix<float, 3, 1, 0, 3, 1>, Eigen::Matrix<float, 3, 1, 0, 3, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, 3, 1, 0, 3, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<float, 3, 1, 0, 3, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, std::vector<igl::Hit, std::allocator<igl::Hit> >&);
  73. #endif