EmbreeIntersector.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 <embree3/rtcore.h>
  22. #include <embree3/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. RTCRayHit& 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 RTCDevice g_device = nullptr;
  187. }
  188. }
  189. inline void igl::embree::EmbreeIntersector::global_init()
  190. {
  191. if(!g_device)
  192. {
  193. g_device = rtcNewDevice (NULL);
  194. if(rtcGetDeviceError (g_device) != RTC_ERROR_NONE)
  195. std::cerr << "Embree: An error occurred while initializing embree core!" << std::endl;
  196. #ifdef IGL_VERBOSE
  197. else
  198. std::cerr << "Embree: core initialized." << std::endl;
  199. #endif
  200. }
  201. }
  202. inline void igl::embree::EmbreeIntersector::global_deinit()
  203. {
  204. rtcReleaseDevice (g_device);
  205. g_device = nullptr;
  206. }
  207. inline igl::embree::EmbreeIntersector::EmbreeIntersector()
  208. :
  209. //scene(NULL),
  210. geomID(0),
  211. vertices(NULL),
  212. triangles(NULL),
  213. initialized(false)
  214. {
  215. }
  216. inline igl::embree::EmbreeIntersector::EmbreeIntersector(
  217. const EmbreeIntersector &)
  218. :// To make -Weffc++ happy
  219. //scene(NULL),
  220. geomID(0),
  221. vertices(NULL),
  222. triangles(NULL),
  223. initialized(false)
  224. {
  225. assert(false && "Embree: Copying EmbreeIntersector is not allowed");
  226. }
  227. inline igl::embree::EmbreeIntersector & igl::embree::EmbreeIntersector::operator=(
  228. const EmbreeIntersector &)
  229. {
  230. assert(false && "Embree: Assigning an EmbreeIntersector is not allowed");
  231. return *this;
  232. }
  233. inline void igl::embree::EmbreeIntersector::init(
  234. const PointMatrixType& V,
  235. const FaceMatrixType& F,
  236. bool isStatic)
  237. {
  238. std::vector<const PointMatrixType*> Vtemp;
  239. std::vector<const FaceMatrixType*> Ftemp;
  240. std::vector<int> masks;
  241. Vtemp.push_back(&V);
  242. Ftemp.push_back(&F);
  243. masks.push_back(0xFFFFFFFF);
  244. init(Vtemp,Ftemp,masks,isStatic);
  245. }
  246. inline void igl::embree::EmbreeIntersector::init(
  247. const std::vector<const PointMatrixType*>& V,
  248. const std::vector<const FaceMatrixType*>& F,
  249. const std::vector<int>& masks,
  250. bool isStatic)
  251. {
  252. if(initialized)
  253. deinit();
  254. using namespace std;
  255. global_init();
  256. if(V.size() == 0 || F.size() == 0)
  257. {
  258. std::cerr << "Embree: No geometry specified!";
  259. return;
  260. }
  261. RTCBuildQuality buildQuality = isStatic ? RTC_BUILD_QUALITY_HIGH : RTC_BUILD_QUALITY_MEDIUM;
  262. // create a scene
  263. scene = rtcNewScene(g_device);
  264. rtcSetSceneFlags(scene, RTC_SCENE_FLAG_ROBUST);
  265. rtcSetSceneBuildQuality(scene, buildQuality);
  266. for(int g=0;g<(int)V.size();g++)
  267. {
  268. // create triangle mesh geometry in that scene
  269. RTCGeometry geom_0 = rtcNewGeometry (g_device, RTC_GEOMETRY_TYPE_TRIANGLE);
  270. rtcSetGeometryBuildQuality(geom_0,buildQuality);
  271. rtcSetGeometryTimeStepCount(geom_0,1);
  272. geomID = rtcAttachGeometry(scene,geom_0);
  273. rtcReleaseGeometry(geom_0);
  274. // fill vertex buffer
  275. vertices = (Vertex*)rtcSetNewGeometryBuffer(geom_0,RTC_BUFFER_TYPE_VERTEX,0,RTC_FORMAT_FLOAT3,4*sizeof(float),V[g]->rows());
  276. for(int i=0;i<(int)V[g]->rows();i++)
  277. {
  278. vertices[i].x = (float)V[g]->coeff(i,0);
  279. vertices[i].y = (float)V[g]->coeff(i,1);
  280. vertices[i].z = (float)V[g]->coeff(i,2);
  281. }
  282. // fill triangle buffer
  283. triangles = (Triangle*) rtcSetNewGeometryBuffer(geom_0,RTC_BUFFER_TYPE_INDEX,0,RTC_FORMAT_UINT3,3*sizeof(int),F[g]->rows());
  284. for(int i=0;i<(int)F[g]->rows();i++)
  285. {
  286. triangles[i].v0 = (int)F[g]->coeff(i,0);
  287. triangles[i].v1 = (int)F[g]->coeff(i,1);
  288. triangles[i].v2 = (int)F[g]->coeff(i,2);
  289. }
  290. rtcSetGeometryMask(geom_0,masks[g]);
  291. rtcCommitGeometry(geom_0);
  292. }
  293. rtcCommitScene(scene);
  294. if(rtcGetDeviceError (g_device) != RTC_ERROR_NONE)
  295. std::cerr << "Embree: An error occurred while initializing the provided geometry!" << endl;
  296. #ifdef IGL_VERBOSE
  297. else
  298. std::cerr << "Embree: geometry added." << endl;
  299. #endif
  300. initialized = true;
  301. }
  302. igl::embree::EmbreeIntersector
  303. ::~EmbreeIntersector()
  304. {
  305. if(initialized)
  306. deinit();
  307. }
  308. void igl::embree::EmbreeIntersector::deinit()
  309. {
  310. if(g_device && scene)
  311. {
  312. rtcReleaseScene(scene);
  313. if(rtcGetDeviceError (g_device) != RTC_ERROR_NONE)
  314. {
  315. std::cerr << "Embree: An error occurred while resetting!" << std::endl;
  316. }
  317. #ifdef IGL_VERBOSE
  318. else
  319. {
  320. std::cerr << "Embree: geometry removed." << std::endl;
  321. }
  322. #endif
  323. }
  324. }
  325. inline bool igl::embree::EmbreeIntersector::intersectRay(
  326. const Eigen::RowVector3f& origin,
  327. const Eigen::RowVector3f& direction,
  328. Hit& hit,
  329. float tnear,
  330. float tfar,
  331. int mask) const
  332. {
  333. RTCRayHit ray; // EMBREE_FIXME: use RTCRay for occlusion rays
  334. ray.ray.flags = 0;
  335. createRay(ray, origin,direction,tnear,tfar,mask);
  336. // shot ray
  337. {
  338. RTCIntersectContext context;
  339. rtcInitIntersectContext(&context);
  340. rtcIntersect1(scene,&context,&ray);
  341. ray.hit.Ng_x = -ray.hit.Ng_x; // EMBREE_FIXME: only correct for triangles,quads, and subdivision surfaces
  342. ray.hit.Ng_y = -ray.hit.Ng_y;
  343. ray.hit.Ng_z = -ray.hit.Ng_z;
  344. }
  345. #ifdef IGL_VERBOSE
  346. if(rtcGetDeviceError (g_device) != RTC_ERROR_NONE)
  347. std::cerr << "Embree: An error occurred while resetting!" << std::endl;
  348. #endif
  349. if((unsigned)ray.hit.geomID != RTC_INVALID_GEOMETRY_ID)
  350. {
  351. hit.id = ray.hit.primID;
  352. hit.gid = ray.hit.geomID;
  353. hit.u = ray.hit.u;
  354. hit.v = ray.hit.v;
  355. hit.t = ray.ray.tfar;
  356. return true;
  357. }
  358. return false;
  359. }
  360. inline bool igl::embree::EmbreeIntersector::intersectBeam(
  361. const Eigen::RowVector3f& origin,
  362. const Eigen::RowVector3f& direction,
  363. Hit& hit,
  364. float tnear,
  365. float tfar,
  366. int mask,
  367. int geoId,
  368. bool closestHit,
  369. unsigned int samples) const
  370. {
  371. bool hasHit = false;
  372. Hit bestHit;
  373. if(closestHit)
  374. bestHit.t = std::numeric_limits<float>::max();
  375. else
  376. bestHit.t = 0;
  377. if((intersectRay(origin,direction,hit,tnear,tfar,mask) && (hit.gid == geoId || geoId == -1)))
  378. {
  379. bestHit = hit;
  380. hasHit = true;
  381. }
  382. // sample points around actual ray (conservative hitcheck)
  383. const float eps= 1e-5;
  384. Eigen::RowVector3f up(0,1,0);
  385. if (direction.cross(up).norm() < eps) up = Eigen::RowVector3f(1,0,0);
  386. Eigen::RowVector3f offset = direction.cross(up).normalized();
  387. Eigen::Matrix3f rot = Eigen::AngleAxis<float>(2*3.14159265358979/samples,direction).toRotationMatrix();
  388. for(int r=0;r<(int)samples;r++)
  389. {
  390. if(intersectRay(origin+offset*eps,direction,hit,tnear,tfar,mask) &&
  391. ((closestHit && (hit.t < bestHit.t)) ||
  392. (!closestHit && (hit.t > bestHit.t))) &&
  393. (hit.gid == geoId || geoId == -1))
  394. {
  395. bestHit = hit;
  396. hasHit = true;
  397. }
  398. offset = rot*offset.transpose();
  399. }
  400. hit = bestHit;
  401. return hasHit;
  402. }
  403. inline bool
  404. igl::embree::EmbreeIntersector
  405. ::intersectRay(
  406. const Eigen::RowVector3f& origin,
  407. const Eigen::RowVector3f& direction,
  408. std::vector<Hit > &hits,
  409. int& num_rays,
  410. float tnear,
  411. float tfar,
  412. int mask) const
  413. {
  414. using namespace std;
  415. num_rays = 0;
  416. hits.clear();
  417. int last_id0 = -1;
  418. double self_hits = 0;
  419. // This epsilon is directly correleated to the number of missed hits, smaller
  420. // means more accurate and slower
  421. //const double eps = DOUBLE_EPS;
  422. const double eps = FLOAT_EPS;
  423. double min_t = tnear;
  424. bool large_hits_warned = false;
  425. RTCRayHit ray; // EMBREE_FIXME: use RTCRay for occlusion rays
  426. ray.ray.flags = 0;
  427. createRay(ray,origin,direction,tnear,tfar,mask);
  428. while(true)
  429. {
  430. ray.ray.tnear = min_t;
  431. ray.ray.tfar = tfar;
  432. ray.hit.geomID = RTC_INVALID_GEOMETRY_ID;
  433. ray.hit.primID = RTC_INVALID_GEOMETRY_ID;
  434. ray.hit.instID[0] = RTC_INVALID_GEOMETRY_ID;
  435. num_rays++;
  436. {
  437. RTCIntersectContext context;
  438. rtcInitIntersectContext(&context);
  439. rtcIntersect1(scene,&context,&ray);
  440. ray.hit.Ng_x = -ray.hit.Ng_x; // EMBREE_FIXME: only correct for triangles,quads, and subdivision surfaces
  441. ray.hit.Ng_y = -ray.hit.Ng_y;
  442. ray.hit.Ng_z = -ray.hit.Ng_z;
  443. }
  444. if((unsigned)ray.hit.geomID != RTC_INVALID_GEOMETRY_ID)
  445. {
  446. // Hit self again, progressively advance
  447. if(ray.hit.primID == last_id0 || ray.ray.tfar <= min_t)
  448. {
  449. // push min_t a bit more
  450. //double t_push = pow(2.0,self_hits-4)*(hit.t<eps?eps:hit.t);
  451. double t_push = pow(2.0,self_hits)*eps;
  452. #ifdef IGL_VERBOSE
  453. std::cerr<<" t_push: "<<t_push<<endl;
  454. #endif
  455. //o = o+t_push*d;
  456. min_t += t_push;
  457. self_hits++;
  458. }
  459. else
  460. {
  461. Hit hit;
  462. hit.id = ray.hit.primID;
  463. hit.gid = ray.hit.geomID;
  464. hit.u = ray.hit.u;
  465. hit.v = ray.hit.v;
  466. hit.t = ray.ray.tfar;
  467. hits.push_back(hit);
  468. #ifdef IGL_VERBOSE
  469. std::cerr<<" t: "<<hit.t<<endl;
  470. #endif
  471. // Instead of moving origin, just change min_t. That way calculations
  472. // all use exactly same origin values
  473. min_t = ray.ray.tfar;
  474. // reset t_scale
  475. self_hits = 0;
  476. }
  477. last_id0 = ray.hit.primID;
  478. }
  479. else
  480. break; // no more hits
  481. if(hits.size()>1000 && !large_hits_warned)
  482. {
  483. std::cout<<"Warning: Large number of hits..."<<endl;
  484. std::cout<<"[ ";
  485. for(vector<Hit>::iterator hit = hits.begin(); hit != hits.end();hit++)
  486. {
  487. std::cout<<(hit->id+1)<<" ";
  488. }
  489. std::cout.precision(std::numeric_limits< double >::digits10);
  490. std::cout<<"[ ";
  491. for(vector<Hit>::iterator hit = hits.begin(); hit != hits.end(); hit++)
  492. {
  493. std::cout<<(hit->t)<<endl;;
  494. }
  495. std::cout<<"]"<<endl;
  496. large_hits_warned = true;
  497. return hits.empty();
  498. }
  499. }
  500. return hits.empty();
  501. }
  502. inline bool
  503. igl::embree::EmbreeIntersector
  504. ::intersectSegment(const Eigen::RowVector3f& a, const Eigen::RowVector3f& ab, Hit &hit, int mask) const
  505. {
  506. RTCRayHit ray; // EMBREE_FIXME: use RTCRay for occlusion rays
  507. ray.ray.flags = 0;
  508. createRay(ray,a,ab,0,1.0,mask);
  509. {
  510. RTCIntersectContext context;
  511. rtcInitIntersectContext(&context);
  512. rtcIntersect1(scene,&context,&ray);
  513. ray.hit.Ng_x = -ray.hit.Ng_x; // EMBREE_FIXME: only correct for triangles,quads, and subdivision surfaces
  514. ray.hit.Ng_y = -ray.hit.Ng_y;
  515. ray.hit.Ng_z = -ray.hit.Ng_z;
  516. }
  517. if((unsigned)ray.hit.geomID != RTC_INVALID_GEOMETRY_ID)
  518. {
  519. hit.id = ray.hit.primID;
  520. hit.gid = ray.hit.geomID;
  521. hit.u = ray.hit.u;
  522. hit.v = ray.hit.v;
  523. hit.t = ray.ray.tfar;
  524. return true;
  525. }
  526. return false;
  527. }
  528. inline void
  529. igl::embree::EmbreeIntersector
  530. ::createRay(RTCRayHit& ray, const Eigen::RowVector3f& origin, const Eigen::RowVector3f& direction, float tnear, float tfar, int mask) const
  531. {
  532. ray.ray.org_x = origin[0];
  533. ray.ray.org_y = origin[1];
  534. ray.ray.org_z = origin[2];
  535. ray.ray.dir_x = direction[0];
  536. ray.ray.dir_y = direction[1];
  537. ray.ray.dir_z = direction[2];
  538. ray.ray.tnear = tnear;
  539. ray.ray.tfar = tfar;
  540. ray.ray.id = RTC_INVALID_GEOMETRY_ID;
  541. ray.ray.mask = mask;
  542. ray.ray.time = 0.0f;
  543. ray.hit.geomID = RTC_INVALID_GEOMETRY_ID;
  544. ray.hit.instID[0] = RTC_INVALID_GEOMETRY_ID;
  545. ray.hit.primID = RTC_INVALID_GEOMETRY_ID;
  546. }
  547. #endif //EMBREE_INTERSECTOR_H