EmbreeIntersector.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. // 2014 Christian Schüller <schuellchr@gmail.com>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla Public License
  7. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  8. // obtain one at http://mozilla.org/MPL/2.0/.
  9. // igl function interface for Embree2.2
  10. //
  11. // Necessary changes to switch from previous Embree versions:
  12. // * Use igl:Hit instead of embree:Hit (where id0 -> id)
  13. // * For Embree2.2
  14. // * Uncomment #define __USE_RAY_MASK__ in platform.h to enable masking
  15. #ifndef IGL_EMBREE_INTERSECTOR_H
  16. #define IGL_EMBREE_INTERSECTOR_H
  17. #include "Hit.h"
  18. #include <Eigen/Geometry>
  19. #include <Eigen/Core>
  20. #include <Eigen/Geometry>
  21. #include <embree2/rtcore.h>
  22. #include <embree2/rtcore_ray.h>
  23. #include <iostream>
  24. #include <vector>
  25. namespace igl
  26. {
  27. class EmbreeIntersector
  28. {
  29. public:
  30. // Initialize embree engine. This will be called on instance `init()`
  31. // calls. If already inited then this function does nothing: it is harmless
  32. // to call more than once.
  33. static inline void global_init();
  34. private:
  35. // Deinitialize the embree engine.
  36. static inline void global_deinit();
  37. public:
  38. typedef Eigen::Matrix<float,Eigen::Dynamic,3> PointMatrixType;
  39. typedef Eigen::Matrix<int,Eigen::Dynamic,3> FaceMatrixType;
  40. public:
  41. inline EmbreeIntersector();
  42. private:
  43. // Copying and assignment are not allowed.
  44. inline EmbreeIntersector(const EmbreeIntersector & that);
  45. inline EmbreeIntersector & operator=(const EmbreeIntersector &);
  46. public:
  47. virtual inline ~EmbreeIntersector();
  48. // Initialize with a given mesh.
  49. //
  50. // Inputs:
  51. // V #V by 3 list of vertex positions
  52. // F #F by 3 list of Oriented triangles
  53. // Side effects:
  54. // The first time this is ever called the embree engine is initialized.
  55. inline void init(
  56. const PointMatrixType& V,
  57. const FaceMatrixType& F);
  58. // Initialize with a given mesh.
  59. //
  60. // Inputs:
  61. // V vector of #V by 3 list of vertex positions for each geometry
  62. // F vector of #F by 3 list of Oriented triangles for each geometry
  63. // masks a 32 bit mask to identify active geometries.
  64. // Side effects:
  65. // The first time this is ever called the embree engine is initialized.
  66. inline void init(
  67. const std::vector<const PointMatrixType*>& V,
  68. const std::vector<const FaceMatrixType*>& F,
  69. const std::vector<int>& masks);
  70. // Deinitialize embree datasctructures for current mesh. Also called on
  71. // destruction: no need to call if you just want to init() once and
  72. // destroy.
  73. inline void deinit();
  74. // Given a ray find the first hit
  75. //
  76. // Inputs:
  77. // origin 3d origin point of ray
  78. // direction 3d (not necessarily normalized) direction vector of ray
  79. // tnear start of ray segment
  80. // tfar end of ray segment
  81. // masks a 32 bit mask to identify active geometries.
  82. // Output:
  83. // hit information about hit
  84. // Returns true if and only if there was a hit
  85. inline bool intersectRay(
  86. const Eigen::RowVector3f& origin,
  87. const Eigen::RowVector3f& direction,
  88. Hit& hit,
  89. float tnear = 0,
  90. float tfar = std::numeric_limits<float>::infinity(),
  91. int mask = 0xFFFFFFFF) const;
  92. // Given a ray find the first hit
  93. // This is a conservative hit test where multiple rays within a small radius
  94. // will be tested and only the closesest hit is returned.
  95. //
  96. // Inputs:
  97. // origin 3d origin point of ray
  98. // direction 3d (not necessarily normalized) direction vector of ray
  99. // tnear start of ray segment
  100. // tfar end of ray segment
  101. // masks a 32 bit mask to identify active geometries.
  102. // geoId id of geometry mask (default -1 if no: no masking)
  103. // closestHit true for gets closest hit, false for furthest hit
  104. // Output:
  105. // hit information about hit
  106. // Returns true if and only if there was a hit
  107. inline bool intersectBeam(
  108. const Eigen::RowVector3f& origin,
  109. const Eigen::RowVector3f& direction,
  110. Hit& hit,
  111. float tnear = 0,
  112. float tfar = -1,
  113. int mask = 0xFFFFFFFF,
  114. int geoId = -1,
  115. bool closestHit = true) const;
  116. // Given a ray find all hits in order
  117. //
  118. // Inputs:
  119. // origin 3d origin point of ray
  120. // direction 3d (not necessarily normalized) direction vector of ray
  121. // tnear start of ray segment
  122. // tfar end of ray segment
  123. // masks a 32 bit mask to identify active geometries.
  124. // Output:
  125. // hit information about hit
  126. // num_rays number of rays shot (at least one)
  127. // Returns true if and only if there was a hit
  128. inline bool intersectRay(
  129. const Eigen::RowVector3f& origin,
  130. const Eigen::RowVector3f& direction,
  131. std::vector<Hit > &hits,
  132. int& num_rays,
  133. float tnear = 0,
  134. float tfar = std::numeric_limits<float>::infinity(),
  135. int mask = 0xFFFFFFFF) const;
  136. // Given a ray find the first hit
  137. //
  138. // Inputs:
  139. // a 3d first end point of segment
  140. // ab 3d vector from a to other endpoint b
  141. // Output:
  142. // hit information about hit
  143. // Returns true if and only if there was a hit
  144. inline bool intersectSegment(
  145. const Eigen::RowVector3f& a,
  146. const Eigen::RowVector3f& ab,
  147. Hit &hit,
  148. int mask = 0xFFFFFFFF) const;
  149. private:
  150. struct Vertex {float x,y,z,a;};
  151. struct Triangle {int v0, v1, v2;};
  152. RTCScene scene;
  153. unsigned geomID;
  154. Vertex* vertices;
  155. Triangle* triangles;
  156. bool initialized;
  157. inline void createRay(
  158. RTCRay& ray,
  159. const Eigen::RowVector3f& origin,
  160. const Eigen::RowVector3f& direction,
  161. float tnear,
  162. float tfar,
  163. int mask) const;
  164. };
  165. }
  166. // Implementation
  167. #include <igl/EPS.h>
  168. // This unfortunately cannot be a static field of EmbreeIntersector because it
  169. // would depend on the template and then we might end up with initializing
  170. // embree twice. If only there was a way to ask embree if it's already
  171. // initialized...
  172. namespace igl
  173. {
  174. // Keeps track of whether the **Global** Embree intersector has been
  175. // initialized. This should never been done at the global scope.
  176. static bool EmbreeIntersector_inited = false;
  177. }
  178. inline void igl::EmbreeIntersector::global_init()
  179. {
  180. if(!EmbreeIntersector_inited)
  181. {
  182. rtcInit();
  183. if(rtcGetError() != RTC_NO_ERROR)
  184. std::cerr << "Embree: An error occured while initialiting embree core!" << std::endl;
  185. #ifdef IGL_VERBOSE
  186. else
  187. std::cerr << "Embree: core initialized." << std::endl;
  188. #endif
  189. EmbreeIntersector_inited = true;
  190. }
  191. }
  192. inline void igl::EmbreeIntersector::global_deinit()
  193. {
  194. EmbreeIntersector_inited = false;
  195. rtcExit();
  196. }
  197. inline igl::EmbreeIntersector::EmbreeIntersector()
  198. :
  199. //scene(NULL),
  200. geomID(0),
  201. triangles(NULL),
  202. vertices(NULL),
  203. initialized(false)
  204. {
  205. }
  206. inline igl::EmbreeIntersector::EmbreeIntersector(
  207. const EmbreeIntersector &)
  208. :// To make -Weffc++ happy
  209. //scene(NULL),
  210. geomID(0),
  211. triangles(NULL),
  212. vertices(NULL),
  213. initialized(false)
  214. {
  215. assert(false && "Embree: Copying EmbreeIntersector is not allowed");
  216. }
  217. inline igl::EmbreeIntersector & igl::EmbreeIntersector::operator=(
  218. const EmbreeIntersector &)
  219. {
  220. assert(false && "Embree: Assigning an EmbreeIntersector is not allowed");
  221. return *this;
  222. }
  223. inline void igl::EmbreeIntersector::init(
  224. const PointMatrixType& V,
  225. const FaceMatrixType& F)
  226. {
  227. std::vector<const PointMatrixType*> Vtemp;
  228. std::vector<const FaceMatrixType*> Ftemp;
  229. std::vector<int> masks;
  230. Vtemp.push_back(&V);
  231. Ftemp.push_back(&F);
  232. masks.push_back(0xFFFFFFFF);
  233. init(Vtemp,Ftemp,masks);
  234. }
  235. inline void igl::EmbreeIntersector::init(
  236. const std::vector<const PointMatrixType*>& V,
  237. const std::vector<const FaceMatrixType*>& F,
  238. const std::vector<int>& masks)
  239. {
  240. if(initialized)
  241. deinit();
  242. using namespace std;
  243. global_init();
  244. if(V.size() == 0 || F.size() == 0)
  245. {
  246. std::cerr << "Embree: No geometry specified!";
  247. return;
  248. }
  249. // create a scene
  250. scene = rtcNewScene(RTC_SCENE_ROBUST | RTC_SCENE_HIGH_QUALITY,RTC_INTERSECT1);
  251. for(int g=0;g<(int)V.size();g++)
  252. {
  253. // create triangle mesh geometry in that scene
  254. geomID = rtcNewTriangleMesh(scene,RTC_GEOMETRY_STATIC,F[g]->rows(),V[g]->rows(),1);
  255. // fill vertex buffer
  256. vertices = (Vertex*)rtcMapBuffer(scene,geomID,RTC_VERTEX_BUFFER);
  257. for(int i=0;i<(int)V[g]->rows();i++)
  258. {
  259. vertices[i].x = (float)V[g]->coeff(i,0);
  260. vertices[i].y = (float)V[g]->coeff(i,1);
  261. vertices[i].z = (float)V[g]->coeff(i,2);
  262. }
  263. rtcUnmapBuffer(scene,geomID,RTC_VERTEX_BUFFER);
  264. // fill triangle buffer
  265. triangles = (Triangle*) rtcMapBuffer(scene,geomID,RTC_INDEX_BUFFER);
  266. for(int i=0;i<(int)F[g]->rows();i++)
  267. {
  268. triangles[i].v0 = (int)F[g]->coeff(i,0);
  269. triangles[i].v1 = (int)F[g]->coeff(i,1);
  270. triangles[i].v2 = (int)F[g]->coeff(i,2);
  271. }
  272. rtcUnmapBuffer(scene,geomID,RTC_INDEX_BUFFER);
  273. rtcSetMask(scene,geomID,masks[g]);
  274. }
  275. rtcCommit(scene);
  276. if(rtcGetError() != RTC_NO_ERROR)
  277. std::cerr << "Embree: An error occured while initializing the provided geometry!" << endl;
  278. #ifdef IGL_VERBOSE
  279. else
  280. std::cerr << "Embree: geometry added." << endl;
  281. #endif
  282. initialized = true;
  283. }
  284. igl::EmbreeIntersector
  285. ::~EmbreeIntersector()
  286. {
  287. if(initialized)
  288. deinit();
  289. }
  290. void igl::EmbreeIntersector::deinit()
  291. {
  292. if(scene)
  293. {
  294. rtcDeleteScene(scene);
  295. if(rtcGetError() != RTC_NO_ERROR)
  296. {
  297. std::cerr << "Embree: An error occured while resetting!" << std::endl;
  298. }
  299. #ifdef IGL_VERBOSE
  300. else
  301. {
  302. std::cerr << "Embree: geometry removed." << std::endl;
  303. }
  304. #endif
  305. }
  306. }
  307. inline bool igl::EmbreeIntersector::intersectRay(
  308. const Eigen::RowVector3f& origin,
  309. const Eigen::RowVector3f& direction,
  310. Hit& hit,
  311. float tnear,
  312. float tfar,
  313. int mask) const
  314. {
  315. RTCRay ray;
  316. createRay(ray, origin,direction,tnear,tfar,mask);
  317. // shot ray
  318. rtcIntersect(scene,ray);
  319. #ifdef IGL_VERBOSE
  320. if(rtcGetError() != RTC_NO_ERROR)
  321. std::cerr << "Embree: An error occured while resetting!" << std::endl;
  322. #endif
  323. if((unsigned)ray.geomID != RTC_INVALID_GEOMETRY_ID)
  324. {
  325. hit.id = ray.primID;
  326. hit.gid = ray.geomID;
  327. hit.u = ray.u;
  328. hit.v = ray.v;
  329. hit.t = ray.tfar;
  330. return true;
  331. }
  332. return false;
  333. }
  334. inline bool igl::EmbreeIntersector::intersectBeam(
  335. const Eigen::RowVector3f& origin,
  336. const Eigen::RowVector3f& direction,
  337. Hit& hit,
  338. float tnear,
  339. float tfar,
  340. int mask,
  341. int geoId,
  342. bool closestHit) const
  343. {
  344. bool hasHit = false;
  345. Hit bestHit;
  346. if(closestHit)
  347. bestHit.t = std::numeric_limits<float>::max();
  348. else
  349. bestHit.t = 0;
  350. if(hasHit = ((intersectRay(origin,direction,hit,tnear,tfar,mask)) && (hit.gid == geoId || geoId == -1)))
  351. bestHit = hit;
  352. // sample points around actual ray (conservative hitcheck)
  353. float eps= 1e-5;
  354. int density = 4;
  355. Eigen::RowVector3f up(0,1,0);
  356. Eigen::RowVector3f offset = direction.cross(up).normalized();
  357. Eigen::Matrix3f rot = Eigen::AngleAxis<float>(2*3.14159265358979/density,direction).toRotationMatrix();
  358. for(int r=0;r<density;r++)
  359. {
  360. if(intersectRay(origin+offset*eps,direction,hit,tnear,tfar,mask) && ((closestHit && (hit.t < bestHit.t)) || (!closestHit && (hit.t > bestHit.t))) && (hit.gid == geoId || geoId == -1))
  361. {
  362. bestHit = hit;
  363. hasHit = true;
  364. }
  365. offset = rot*offset.transpose();
  366. }
  367. hit = bestHit;
  368. return hasHit;
  369. }
  370. inline bool
  371. igl::EmbreeIntersector
  372. ::intersectRay(
  373. const Eigen::RowVector3f& origin,
  374. const Eigen::RowVector3f& direction,
  375. std::vector<Hit > &hits,
  376. int& num_rays,
  377. float tnear,
  378. float tfar,
  379. int mask) const
  380. {
  381. using namespace std;
  382. num_rays = 0;
  383. hits.clear();
  384. int last_id0 = -1;
  385. double self_hits = 0;
  386. // This epsilon is directly correleated to the number of missed hits, smaller
  387. // means more accurate and slower
  388. //const double eps = DOUBLE_EPS;
  389. const double eps = FLOAT_EPS;
  390. double min_t = tnear;
  391. bool large_hits_warned = false;
  392. RTCRay ray;
  393. createRay(ray,origin,direction,tnear,std::numeric_limits<float>::infinity(),mask);
  394. while(true)
  395. {
  396. ray.tnear = min_t;
  397. ray.tfar = tfar;
  398. ray.geomID = RTC_INVALID_GEOMETRY_ID;
  399. ray.primID = RTC_INVALID_GEOMETRY_ID;
  400. ray.instID = RTC_INVALID_GEOMETRY_ID;
  401. num_rays++;
  402. rtcIntersect(scene,ray);
  403. if((unsigned)ray.geomID != RTC_INVALID_GEOMETRY_ID)
  404. {
  405. // Hit self again, progressively advance
  406. if(ray.primID == last_id0 || ray.tfar <= min_t)
  407. {
  408. // push min_t a bit more
  409. //double t_push = pow(2.0,self_hits-4)*(hit.t<eps?eps:hit.t);
  410. double t_push = pow(2.0,self_hits)*eps;
  411. #ifdef IGL_VERBOSE
  412. std::cerr<<" t_push: "<<t_push<<endl;
  413. #endif
  414. //o = o+t_push*d;
  415. min_t += t_push;
  416. self_hits++;
  417. }
  418. else
  419. {
  420. Hit hit;
  421. hit.id = ray.primID;
  422. hit.gid = ray.geomID;
  423. hit.u = ray.u;
  424. hit.v = ray.v;
  425. hit.t = ray.tfar;
  426. hits.push_back(hit);
  427. #ifdef IGL_VERBOSE
  428. std::cerr<<" t: "<<hit.t<<endl;
  429. #endif
  430. // Instead of moving origin, just change min_t. That way calculations
  431. // all use exactly same origin values
  432. min_t = ray.tfar;
  433. // reset t_scale
  434. self_hits = 0;
  435. }
  436. last_id0 = ray.primID;
  437. }
  438. else
  439. break; // no more hits
  440. if(hits.size()>1000 && !large_hits_warned)
  441. {
  442. std::cout<<"Warning: Large number of hits..."<<endl;
  443. std::cout<<"[ ";
  444. for(vector<Hit>::iterator hit = hits.begin(); hit != hits.end();hit++)
  445. {
  446. std::cout<<(hit->id+1)<<" ";
  447. }
  448. std::cout.precision(std::numeric_limits< double >::digits10);
  449. std::cout<<"[ ";
  450. for(vector<Hit>::iterator hit = hits.begin(); hit != hits.end(); hit++)
  451. {
  452. std::cout<<(hit->t)<<endl;;
  453. }
  454. std::cout<<"]"<<endl;
  455. large_hits_warned = true;
  456. return hits.empty();
  457. }
  458. }
  459. return hits.empty();
  460. }
  461. inline bool
  462. igl::EmbreeIntersector
  463. ::intersectSegment(const Eigen::RowVector3f& a, const Eigen::RowVector3f& ab, Hit &hit, int mask) const
  464. {
  465. RTCRay ray;
  466. createRay(ray,a,ab,0,1.0,mask);
  467. rtcIntersect(scene,ray);
  468. if((unsigned)ray.geomID != RTC_INVALID_GEOMETRY_ID)
  469. {
  470. hit.id = ray.primID;
  471. hit.gid = ray.geomID;
  472. hit.u = ray.u;
  473. hit.v = ray.v;
  474. hit.t = ray.tfar;
  475. return true;
  476. }
  477. return false;
  478. }
  479. inline void
  480. igl::EmbreeIntersector
  481. ::createRay(RTCRay& ray, const Eigen::RowVector3f& origin, const Eigen::RowVector3f& direction, float tnear, float tfar, int mask) const
  482. {
  483. ray.org[0] = origin[0];
  484. ray.org[1] = origin[1];
  485. ray.org[2] = origin[2];
  486. ray.dir[0] = direction[0];
  487. ray.dir[1] = direction[1];
  488. ray.dir[2] = direction[2];
  489. ray.tnear = tnear;
  490. ray.tfar = tfar;
  491. ray.geomID = RTC_INVALID_GEOMETRY_ID;
  492. ray.primID = RTC_INVALID_GEOMETRY_ID;
  493. ray.instID = RTC_INVALID_GEOMETRY_ID;
  494. ray.mask = mask;
  495. ray.time = 0.0f;
  496. }
  497. #endif //EMBREE_INTERSECTOR_H