EmbreeIntersector.h 16 KB

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