render_to_buffer.cpp 12 KB

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