EmbreeIntersector.h 15 KB

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