EmbreeIntersector.h 15 KB

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