render_to_buffer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. // This required to get correct linking with Objective-C files
  2. extern "C" {
  3. #include "render_to_buffer.h"
  4. };
  5. // We're probably didn't build libigl.a with LLVM so just use the headers only
  6. // version.
  7. #define IGL_HEADER_ONLY
  8. #include <igl/per_face_normals.h>
  9. #include <igl/normalize_row_lengths.h>
  10. #include <igl/get_seconds.h>
  11. #include <igl/draw_mesh.h>
  12. #include <igl/draw_floor.h>
  13. #include <igl/material_colors.h>
  14. #include <igl/pathinfo.h>
  15. #include <igl/readOBJ.h>
  16. #include <igl/readWRL.h>
  17. #include <igl/triangulate.h>
  18. #include <igl/readOFF.h>
  19. #include <igl/readMESH.h>
  20. #include <igl/boundary_faces.h>
  21. #include <igl/barycenter.h>
  22. #include <igl/doublearea.h>
  23. #include <igl/EPS.h>
  24. #include <igl/Camera.h>
  25. #include <igl/canonical_quaternions.h>
  26. #include <igl/quat_to_mat.h>
  27. #include <igl/Viewport.h>
  28. #include <Eigen/Core>
  29. #include <GL/glu.h>
  30. #include <algorithm>
  31. static int width,height;
  32. static Eigen::MatrixXd V,N;
  33. static Eigen::MatrixXi F;
  34. static Eigen::Vector3d Vmean, Vmax,Vmin;
  35. //static bool invert = false;
  36. static float background_color[4] = {0,0,0,1};
  37. // Small viewports struct for keeping track of size and camera info
  38. #define NUM_VIEWPORTS 6
  39. class AugViewport : public igl::Viewport
  40. {
  41. public:
  42. igl::Camera camera;
  43. } viewports[NUM_VIEWPORTS];
  44. // Red screen for errors
  45. void red(const int width, const int height, GLubyte * buffer)
  46. {
  47. for(int h = 0;h<height;h++)
  48. {
  49. for(int w = 0;w<width;w++)
  50. {
  51. for(int c = 0;c<4;c++)
  52. {
  53. if(c == 0 || c==3)
  54. {
  55. buffer[c+4*w+4*width*h] = 255;
  56. }else
  57. {
  58. buffer[c+4*w+4*width*h] = 0;
  59. }
  60. }
  61. }
  62. }
  63. }
  64. // Initialize the viewport angles and camera rotations
  65. void init_viewports()
  66. {
  67. using namespace igl;
  68. using namespace std;
  69. for(auto & vp : viewports)
  70. {
  71. // Reset. I guess Mac is keeping global variables alive...
  72. vp.camera = Camera();
  73. vp.camera.push_away(3.);
  74. vp.camera.dolly_zoom(10.-vp.camera.m_angle);
  75. }
  76. // Above view
  77. double XZ_PLANE_QUAT_D_FLIP[4];
  78. copy(XZ_PLANE_QUAT_D,XZ_PLANE_QUAT_D+4,XZ_PLANE_QUAT_D_FLIP);
  79. XZ_PLANE_QUAT_D_FLIP[0] *= -1.0;
  80. // Straight on
  81. copy(
  82. XY_PLANE_QUAT_D,
  83. XY_PLANE_QUAT_D+4,
  84. viewports[0].camera.m_rotation_conj.coeffs().data());
  85. // Left side view
  86. copy(
  87. CANONICAL_VIEW_QUAT_D[9],
  88. CANONICAL_VIEW_QUAT_D[9]+4,
  89. viewports[1].camera.m_rotation_conj.coeffs().data());
  90. copy(
  91. CANONICAL_VIEW_QUAT_D[14],
  92. CANONICAL_VIEW_QUAT_D[14]+4,
  93. viewports[2].camera.m_rotation_conj.coeffs().data());
  94. // Straight on
  95. copy(
  96. CANONICAL_VIEW_QUAT_D[4],
  97. CANONICAL_VIEW_QUAT_D[4]+4,
  98. viewports[3].camera.m_rotation_conj.coeffs().data());
  99. copy(
  100. XZ_PLANE_QUAT_D,
  101. XZ_PLANE_QUAT_D+4,
  102. viewports[4].camera.m_rotation_conj.coeffs().data());
  103. copy(
  104. XZ_PLANE_QUAT_D_FLIP,
  105. XZ_PLANE_QUAT_D_FLIP+4,
  106. viewports[5].camera.m_rotation_conj.coeffs().data());
  107. }
  108. // Viewports are arranged to see all sides
  109. //
  110. // /-----.-----.-----\
  111. // | 3 | 2 | 1 |
  112. // -------------------
  113. // | 4 | |
  114. // ------- 0 |
  115. // | 5 | |
  116. // \-----.-----------/
  117. void reshape_viewports()
  118. {
  119. using namespace igl;
  120. using namespace std;
  121. viewports[0].reshape(1./3.*width, 0,2./3.*width,2./3.*height);
  122. viewports[1].reshape(2./3.*width, 2./3.*height,1./3.*width,1./3.*height);
  123. viewports[2].reshape(1./3.*width, 2./3.*height,1./3.*width,1./3.*height);
  124. viewports[3].reshape( 0, 2./3.*height,1./3.*width,1./3.*height);
  125. viewports[4].reshape( 0, 1./3.*height,1./3.*width,1./3.*height);
  126. viewports[5].reshape( 0, 0,1./3.*width,1./3.*height);
  127. for(auto & vp : viewports)
  128. {
  129. vp.camera.m_aspect = (double)vp.width/(double)vp.height;
  130. }
  131. }
  132. void reshape(int width, int height)
  133. {
  134. using namespace std;
  135. ::width = width;
  136. ::height = height;
  137. reshape_viewports();
  138. }
  139. // Simple two-sided, diffuse-only light
  140. void lights()
  141. {
  142. using namespace std;
  143. glEnable(GL_LIGHTING);
  144. glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  145. glEnable(GL_LIGHT0);
  146. glEnable(GL_LIGHT1);
  147. float WHITE[4] = {0.8,0.8,0.8,1.};
  148. float GREY[4] = {0.4,0.4,0.4,1.};
  149. float BLACK[4] = {0.,0.,0.,1.};
  150. float pos[4];
  151. float light_pos[4] = {0.1,0.1,1.0,0.0};
  152. copy(light_pos,light_pos+4,pos);
  153. glLightfv(GL_LIGHT0,GL_AMBIENT,GREY);
  154. glLightfv(GL_LIGHT0,GL_DIFFUSE,WHITE);
  155. glLightfv(GL_LIGHT0,GL_SPECULAR,BLACK);
  156. glLightfv(GL_LIGHT0,GL_POSITION,pos);
  157. pos[0] *= -1;
  158. pos[1] *= -1;
  159. pos[2] *= -1;
  160. glLightfv(GL_LIGHT1,GL_AMBIENT,GREY);
  161. glLightfv(GL_LIGHT1,GL_DIFFUSE,WHITE);
  162. glLightfv(GL_LIGHT1,GL_SPECULAR,BLACK);
  163. glLightfv(GL_LIGHT1,GL_POSITION,pos);
  164. }
  165. // Push scene based on viewport
  166. void push_scene(const AugViewport & vp)
  167. {
  168. using namespace igl;
  169. using namespace std;
  170. glMatrixMode(GL_PROJECTION);
  171. glPushMatrix();
  172. glLoadIdentity();
  173. auto & camera = vp.camera;
  174. glMultMatrixd(camera.projection().data());
  175. glMatrixMode(GL_MODELVIEW);
  176. glPushMatrix();
  177. glLoadIdentity();
  178. // -1 because buffer y-coordinates are flipped
  179. gluLookAt(
  180. camera.eye()(0), camera.eye()(1), camera.eye()(2),
  181. camera.at()(0), camera.at()(1), camera.at()(2),
  182. camera.up()(0), -1*camera.up()(1), camera.up()(2));
  183. }
  184. // Scale and shift for object so that it fits current view
  185. void push_object(const AugViewport & vp)
  186. {
  187. using namespace Eigen;
  188. glPushMatrix();
  189. Matrix3d m = vp.camera.m_rotation_conj.matrix();
  190. Vector3d eff_Vmax = m*Vmax;
  191. Vector3d eff_Vmin = m*Vmin;
  192. Vector3d eff_Vmean = m*Vmean;
  193. const double dy = fabs(eff_Vmax(1,0)-eff_Vmin(1,0));
  194. const double dx = fabs(eff_Vmax(0,0)-eff_Vmin(0,0));
  195. //const double dz = fabs(eff_Vmax(2,0)-eff_Vmin(2,0));
  196. // Assumes height < width
  197. const double sx = dx*(double)height/(double)width;
  198. const double sy = dy;
  199. const double s = 2./(sy > sx ? sy : sx);
  200. glScaled(s,s,s);
  201. glTranslated(-Vmean(0,0),-Vmean(1,0),-Vmean(2,0));
  202. // Hack. Should really just figure out max scale so that full model fits on
  203. // screen with given perspective.
  204. //const double dz_off = (dz > 2.*dy && dz > 2.*dx ? dz/2. : 0);
  205. //glTranslated(0,0,-dz_off);
  206. }
  207. void pop_object()
  208. {
  209. glPopMatrix();
  210. }
  211. void pop_scene()
  212. {
  213. glMatrixMode(GL_PROJECTION);
  214. glPopMatrix();
  215. glMatrixMode(GL_MODELVIEW);
  216. glPopMatrix();
  217. }
  218. void display()
  219. {
  220. using namespace std;
  221. using namespace igl;
  222. glClearColor(
  223. background_color[0],
  224. background_color[1],
  225. background_color[2],
  226. background_color[3]);
  227. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  228. glEnable(GL_DEPTH_TEST);
  229. glEnable(GL_NORMALIZE);
  230. glDisable(GL_CULL_FACE);
  231. glCullFace(GL_BACK);
  232. // "Flash light" attached to camera
  233. lights();
  234. // Draw for each viewport
  235. for(int vp = 0;vp<NUM_VIEWPORTS;vp++)
  236. {
  237. glViewport(
  238. viewports[vp].x,
  239. viewports[vp].y,
  240. viewports[vp].width,
  241. viewports[vp].height);
  242. push_scene(viewports[vp]);
  243. push_object(viewports[vp]);
  244. // Draw the mesh, inverted if need be.
  245. // Set material properties
  246. glDisable(GL_COLOR_MATERIAL);
  247. //if(invert)
  248. //{
  249. // glFrontFace(GL_CW);
  250. // glMaterialfv(GL_FRONT, GL_AMBIENT, CYAN_AMBIENT);
  251. // glMaterialfv(GL_FRONT, GL_DIFFUSE, CYAN_DIFFUSE );
  252. // glMaterialfv(GL_FRONT, GL_SPECULAR, CYAN_SPECULAR);
  253. // glMaterialf (GL_FRONT, GL_SHININESS, 128);
  254. // glMaterialfv(GL_BACK, GL_AMBIENT, SILVER_AMBIENT);
  255. // glMaterialfv(GL_BACK, GL_DIFFUSE, FAST_RED_DIFFUSE);
  256. // glMaterialfv(GL_BACK, GL_SPECULAR, SILVER_SPECULAR);
  257. // glMaterialf (GL_BACK, GL_SHININESS, 128);
  258. //}else
  259. //{
  260. glMaterialfv(GL_FRONT, GL_AMBIENT, GOLD_AMBIENT);
  261. glMaterialfv(GL_FRONT, GL_DIFFUSE, GOLD_DIFFUSE );
  262. glMaterialfv(GL_FRONT, GL_SPECULAR, GOLD_SPECULAR);
  263. glMaterialf (GL_FRONT, GL_SHININESS, 128);
  264. glMaterialfv(GL_BACK, GL_AMBIENT, SILVER_AMBIENT);
  265. glMaterialfv(GL_BACK, GL_DIFFUSE, FAST_GREEN_DIFFUSE );
  266. glMaterialfv(GL_BACK, GL_SPECULAR, SILVER_SPECULAR);
  267. glMaterialf (GL_BACK, GL_SHININESS, 128);
  268. //}
  269. draw_mesh(V,F,N);
  270. //if(invert)
  271. //{
  272. // glFrontFace(GL_CCW);
  273. //}
  274. pop_object();
  275. // Draw a nice floor unless we're looking from beneath it
  276. if(vp != 4)
  277. {
  278. glPushMatrix();
  279. glTranslated(0,-1,0);
  280. glScaled(4,4,4);
  281. draw_floor();
  282. glPopMatrix();
  283. }
  284. pop_scene();
  285. }
  286. // Screen space
  287. glDisable(GL_DEPTH_TEST);
  288. glDisable(GL_LIGHTING);
  289. glViewport(0,0,width,height);
  290. glMatrixMode(GL_PROJECTION);
  291. glLoadIdentity();
  292. gluOrtho2D(0,width,0,height);
  293. glMatrixMode(GL_MODELVIEW);
  294. glLoadIdentity();
  295. // Draw separation lines between (around) viewports
  296. const double BAR_THICKNESS = 3.0;
  297. glColor3f(0.5,0.5,0.5);
  298. for(int vp = 0;vp<NUM_VIEWPORTS;vp++)
  299. {
  300. glLineWidth(BAR_THICKNESS);
  301. glBegin(GL_LINE_STRIP);
  302. glVertex2f(viewports[vp].x,viewports[vp].y);
  303. glVertex2f(viewports[vp].x+viewports[vp].width,viewports[vp].y);
  304. glVertex2f(viewports[vp].x+viewports[vp].width,viewports[vp].y+viewports[vp].height);
  305. glVertex2f( viewports[vp].x,viewports[vp].y+viewports[vp].height);
  306. glEnd();
  307. }
  308. glFinish();
  309. }
  310. bool render_to_buffer(
  311. const char * filename,
  312. const float * background_color,
  313. const int width,
  314. const int height,
  315. GLubyte * buffer)
  316. {
  317. using namespace igl;
  318. using namespace std;
  319. using namespace Eigen;
  320. double ts = get_seconds();
  321. copy(background_color,background_color+4,::background_color);
  322. // Read and prepare mesh
  323. // dirname, basename, extension and filename
  324. string d,b,ext,f;
  325. pathinfo(filename,d,b,ext,f);
  326. // Convert extension to lower case
  327. transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  328. vector<vector<double > > vV,vN,vTC;
  329. vector<vector<int > > vF,vFTC,vFN;
  330. if(ext == "obj")
  331. {
  332. // Convert extension to lower case
  333. if(!igl::readOBJ(filename,vV,vTC,vN,vF,vFTC,vFN))
  334. {
  335. red(width,height,buffer);
  336. return false;
  337. }
  338. }else if(ext == "off")
  339. {
  340. // Convert extension to lower case
  341. if(!igl::readOFF(filename,vV,vF,vN))
  342. {
  343. red(width,height,buffer);
  344. return false;
  345. }
  346. }else if(ext == "wrl")
  347. {
  348. // Convert extension to lower case
  349. if(!igl::readWRL(filename,vV,vF))
  350. {
  351. red(width,height,buffer);
  352. return false;
  353. }
  354. }else
  355. {
  356. // Convert extension to lower case
  357. MatrixXi T;
  358. if(!igl::readMESH(filename,V,T,F))
  359. {
  360. red(width,height,buffer);
  361. return false;
  362. }
  363. //if(F.size() > T.size() || F.size() == 0)
  364. {
  365. boundary_faces(T,F);
  366. }
  367. }
  368. if(vV.size() > 0)
  369. {
  370. if(!list_to_matrix(vV,V))
  371. {
  372. red(width,height,buffer);
  373. return false;
  374. }
  375. triangulate(vF,F);
  376. }
  377. cout<<"IO: "<<(get_seconds()-ts)<<"s"<<endl;
  378. ts = get_seconds();
  379. // Computer already normalized per triangle normals
  380. per_face_normals(V,F,N);
  381. //Vmean = 0.5*(V.colwise().maxCoeff()+V.colwise().minCoeff());
  382. Vmax = V.colwise().maxCoeff();
  383. Vmin = V.colwise().minCoeff();
  384. Vmean = 0.5*(Vmax + Vmin);
  385. //// Figure out if normals should be flipped (hopefully this is never a
  386. //// bottleneck)
  387. //MatrixXd BC;
  388. //VectorXd dblA;
  389. //barycenter(V,F,BC);
  390. //BC.col(0).array() -= Vmean(0,0);
  391. //BC.col(1).array() -= Vmean(1,0);
  392. //BC.col(2).array() -= Vmean(2,0);
  393. //doublearea(V,F,dblA);
  394. //VectorXd BCDN = (BC.array() * N.array()).rowwise().sum();
  395. //const double tot_dp = dblA.transpose() * BCDN;
  396. //invert = tot_dp < 0;
  397. //cout<<"Normals: "<<(get_seconds()-ts)<<"s"<<endl;
  398. //ts = get_seconds();
  399. // Initialize MESA
  400. OSMesaContext ctx;
  401. /* Create an RGBA-mode context */
  402. # if OSMESA_MAJOR_VERSION * 100 + OSMESA_MINOR_VERSION >= 305
  403. /* specify Z, stencil, accum sizes */
  404. ctx = OSMesaCreateContextExt( OSMESA_RGBA, 32, 0, 0, NULL );
  405. # else
  406. ctx = OSMesaCreateContext( OSMESA_RGBA, NULL );
  407. # endif
  408. if (!ctx)
  409. {
  410. fprintf(stderr,"OSMesaCreateContext failed!\n");
  411. red(width,height,buffer);
  412. return false;
  413. }
  414. /* Bind the buffer to the context and make it current */
  415. if (!OSMesaMakeCurrent( ctx, buffer, GL_UNSIGNED_BYTE, width, height))
  416. {
  417. fprintf(stderr,"OSMesaMakeCurrent failed!\n");
  418. red(width,height,buffer);
  419. return false;
  420. }
  421. // Render
  422. init_viewports();
  423. reshape(width,height);
  424. display();
  425. cout<<"Display: "<<(get_seconds()-ts)<<"s"<<endl;
  426. ts = get_seconds();
  427. /* destroy the context */
  428. OSMesaDestroyContext( ctx );
  429. return true;
  430. }