EmbreeIntersector.h 15 KB

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