example.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #include <igl/opengl/OpenGL_convenience.h>
  2. #include <igl/per_face_normals.h>
  3. #include <igl/per_vertex_normals.h>
  4. #include <igl/two_axis_valuator_fixed_up.h>
  5. #include <igl/normalize_row_lengths.h>
  6. #include <igl/opengl2/draw_mesh.h>
  7. #include <igl/opengl2/draw_floor.h>
  8. #include <igl/quat_to_mat.h>
  9. #include <igl/opengl/report_gl_error.h>
  10. #include <igl/readOBJ.h>
  11. #include <igl/readDMAT.h>
  12. #include <igl/readOFF.h>
  13. #include <igl/readMESH.h>
  14. #include <igl/jet.h>
  15. #include <igl/readWRL.h>
  16. #include <igl/trackball.h>
  17. #include <igl/list_to_matrix.h>
  18. #include <igl/snap_to_canonical_view_quat.h>
  19. #include <igl/snap_to_fixed_up.h>
  20. #include <igl/polygon_mesh_to_triangle_mesh.h>
  21. #include <igl/material_colors.h>
  22. #include <igl/barycenter.h>
  23. #include <igl/matlab_format.h>
  24. #include <igl/anttweakbar/ReAntTweakBar.h>
  25. #include <igl/pathinfo.h>
  26. #include <igl/Camera.h>
  27. #include <igl/get_seconds.h>
  28. #ifdef __APPLE__
  29. # include <GLUT/glut.h>
  30. #else
  31. # include <GL/glut.h>
  32. #endif
  33. #include <Eigen/Core>
  34. #include <vector>
  35. #include <iostream>
  36. #include <algorithm>
  37. struct State
  38. {
  39. igl::Camera camera;
  40. } s;
  41. enum RotationType
  42. {
  43. ROTATION_TYPE_IGL_TRACKBALL = 0,
  44. ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP = 1,
  45. NUM_ROTATION_TYPES = 2,
  46. } rotation_type;
  47. bool is_rotating = false;
  48. int down_x,down_y;
  49. igl::Camera down_camera;
  50. bool is_animating = false;
  51. double animation_start_time = 0;
  52. double ANIMATION_DURATION = 0.5;
  53. Eigen::Quaterniond animation_from_quat;
  54. Eigen::Quaterniond animation_to_quat;
  55. // Use vector for range-based `for`
  56. std::vector<State> undo_stack;
  57. std::vector<State> redo_stack;
  58. void push_undo()
  59. {
  60. undo_stack.push_back(s);
  61. // Clear
  62. redo_stack = std::vector<State>();
  63. }
  64. void undo()
  65. {
  66. using namespace std;
  67. if(!undo_stack.empty())
  68. {
  69. redo_stack.push_back(s);
  70. s = undo_stack.front();
  71. undo_stack.pop_back();
  72. }
  73. }
  74. void redo()
  75. {
  76. using namespace std;
  77. if(!redo_stack.empty())
  78. {
  79. undo_stack.push_back(s);
  80. s = redo_stack.front();
  81. redo_stack.pop_back();
  82. }
  83. }
  84. void TW_CALL set_rotation_type(const void * value, void * clientData)
  85. {
  86. using namespace Eigen;
  87. using namespace std;
  88. using namespace igl;
  89. const RotationType old_rotation_type = rotation_type;
  90. rotation_type = *(const RotationType *)(value);
  91. if(rotation_type == ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP &&
  92. old_rotation_type != ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP)
  93. {
  94. push_undo();
  95. animation_from_quat = s.camera.m_rotation_conj;
  96. snap_to_fixed_up(animation_from_quat,animation_to_quat);
  97. // start animation
  98. animation_start_time = get_seconds();
  99. is_animating = true;
  100. }
  101. }
  102. void TW_CALL get_rotation_type(void * value, void *clientData)
  103. {
  104. RotationType * rt = (RotationType *)(value);
  105. *rt = rotation_type;
  106. }
  107. // Width and height of window
  108. int width,height;
  109. // Position of light
  110. float light_pos[4] = {0.1,0.1,-0.9,0};
  111. // Vertex positions, normals, colors and centroid
  112. Eigen::MatrixXd V,N,C,Z,mid;
  113. int selected_col = 0;
  114. // Faces
  115. Eigen::MatrixXi F;
  116. // Bounding box diagonal length
  117. double bbd;
  118. // Running ambient occlusion
  119. Eigen::VectorXd S;
  120. int tot_num_samples = 0;
  121. #define REBAR_NAME "temp.rbr"
  122. igl::anttweakbar::ReTwBar rebar; // Pointer to the tweak bar
  123. void reshape(int width,int height)
  124. {
  125. using namespace std;
  126. // Save width and height
  127. ::width = width;
  128. ::height = height;
  129. glMatrixMode(GL_PROJECTION);
  130. glLoadIdentity();
  131. glViewport(0,0,width,height);
  132. // Send the new window size to AntTweakBar
  133. TwWindowSize(width, height);
  134. // Set aspect for all cameras
  135. s.camera.m_aspect = (double)width/(double)height;
  136. for(auto & s : undo_stack)
  137. {
  138. s.camera.m_aspect = (double)width/(double)height;
  139. }
  140. for(auto & s : redo_stack)
  141. {
  142. s.camera.m_aspect = (double)width/(double)height;
  143. }
  144. }
  145. void push_scene()
  146. {
  147. using namespace igl;
  148. using namespace std;
  149. glMatrixMode(GL_PROJECTION);
  150. glPushMatrix();
  151. glLoadIdentity();
  152. auto & camera = s.camera;
  153. gluPerspective(camera.m_angle,camera.m_aspect,camera.m_near,camera.m_far);
  154. glMatrixMode(GL_MODELVIEW);
  155. glPushMatrix();
  156. glLoadIdentity();
  157. gluLookAt(
  158. camera.eye()(0), camera.eye()(1), camera.eye()(2),
  159. camera.at()(0), camera.at()(1), camera.at()(2),
  160. camera.up()(0), camera.up()(1), camera.up()(2));
  161. }
  162. void pop_scene()
  163. {
  164. glMatrixMode(GL_PROJECTION);
  165. glPopMatrix();
  166. glMatrixMode(GL_MODELVIEW);
  167. glPopMatrix();
  168. }
  169. void pop_object()
  170. {
  171. glPopMatrix();
  172. }
  173. // Scale and shift for object
  174. void push_object()
  175. {
  176. glPushMatrix();
  177. glScaled(2./bbd,2./bbd,2./bbd);
  178. glTranslated(-mid(0,0),-mid(0,1),-mid(0,2));
  179. }
  180. // Set up double-sided lights
  181. void lights()
  182. {
  183. using namespace std;
  184. glEnable(GL_LIGHTING);
  185. glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  186. glEnable(GL_LIGHT0);
  187. glEnable(GL_LIGHT1);
  188. float amb[4];
  189. amb[0] = amb[1] = amb[2] = 0;
  190. amb[3] = 1.0;
  191. float diff[4] = {0.0,0.0,0.0,0.0};
  192. diff[0] = diff[1] = diff[2] = (1.0 - 0/0.4);;
  193. diff[3] = 1.0;
  194. float zeros[4] = {0.0,0.0,0.0,0.0};
  195. float pos[4];
  196. copy(light_pos,light_pos+4,pos);
  197. glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
  198. glLightfv(GL_LIGHT0,GL_DIFFUSE,diff);
  199. glLightfv(GL_LIGHT0,GL_SPECULAR,zeros);
  200. glLightfv(GL_LIGHT0,GL_POSITION,pos);
  201. pos[0] *= -1;
  202. pos[1] *= -1;
  203. pos[2] *= -1;
  204. glLightfv(GL_LIGHT1,GL_AMBIENT,amb);
  205. glLightfv(GL_LIGHT1,GL_DIFFUSE,diff);
  206. glLightfv(GL_LIGHT1,GL_SPECULAR,zeros);
  207. glLightfv(GL_LIGHT1,GL_POSITION,pos);
  208. }
  209. const float back[4] = {30.0/255.0,30.0/255.0,50.0/255.0,0};
  210. void display()
  211. {
  212. using namespace Eigen;
  213. using namespace igl;
  214. using namespace std;
  215. glClearColor(back[0],back[1],back[2],0);
  216. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  217. if(is_animating)
  218. {
  219. double t = (get_seconds() - animation_start_time)/ANIMATION_DURATION;
  220. if(t > 1)
  221. {
  222. t = 1;
  223. is_animating = false;
  224. }
  225. const Quaterniond q = animation_from_quat.slerp(t,animation_to_quat).normalized();
  226. s.camera.orbit(q.conjugate());
  227. }
  228. glDisable(GL_LIGHTING);
  229. lights();
  230. push_scene();
  231. glEnable(GL_DEPTH_TEST);
  232. glDepthFunc(GL_LEQUAL);
  233. glEnable(GL_NORMALIZE);
  234. glEnable(GL_COLOR_MATERIAL);
  235. glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
  236. push_object();
  237. // Draw the model
  238. // Set material properties
  239. glEnable(GL_COLOR_MATERIAL);
  240. igl::opengl2::draw_mesh(V,F,N,C);
  241. pop_object();
  242. // Draw a nice floor
  243. glPushMatrix();
  244. const double floor_offset =
  245. -2./bbd*(V.col(1).maxCoeff()-mid(1));
  246. glTranslated(0,floor_offset,0);
  247. const float GREY[4] = {0.5,0.5,0.6,1.0};
  248. const float DARK_GREY[4] = {0.2,0.2,0.3,1.0};
  249. igl::opengl2::draw_floor(GREY,DARK_GREY);
  250. glPopMatrix();
  251. pop_scene();
  252. igl::opengl::report_gl_error();
  253. TwDraw();
  254. glutSwapBuffers();
  255. if(is_animating)
  256. {
  257. glutPostRedisplay();
  258. }
  259. }
  260. void mouse_wheel(int wheel, int direction, int mouse_x, int mouse_y)
  261. {
  262. using namespace std;
  263. using namespace igl;
  264. using namespace Eigen;
  265. GLint viewport[4];
  266. glGetIntegerv(GL_VIEWPORT,viewport);
  267. if(wheel == 0 && TwMouseMotion(mouse_x, viewport[3] - mouse_y))
  268. {
  269. static double mouse_scroll_y = 0;
  270. const double delta_y = 0.125*direction;
  271. mouse_scroll_y += delta_y;
  272. TwMouseWheel(mouse_scroll_y);
  273. return;
  274. }
  275. push_undo();
  276. auto & camera = s.camera;
  277. if(wheel==0)
  278. {
  279. // factor of zoom change
  280. double s = (1.-0.01*direction);
  281. //// FOV zoom: just widen angle. This is hardly ever appropriate.
  282. //camera.m_angle *= s;
  283. //camera.m_angle = min(max(camera.m_angle,1),89);
  284. camera.push_away(s);
  285. }else
  286. {
  287. // Dolly zoom:
  288. camera.dolly_zoom((double)direction*1.0);
  289. }
  290. }
  291. void mouse(int glutButton, int glutState, int mouse_x, int mouse_y)
  292. {
  293. using namespace std;
  294. using namespace Eigen;
  295. using namespace igl;
  296. bool tw_using = TwEventMouseButtonGLUT(glutButton,glutState,mouse_x,mouse_y);
  297. switch(glutButton)
  298. {
  299. case GLUT_RIGHT_BUTTON:
  300. case GLUT_LEFT_BUTTON:
  301. {
  302. switch(glutState)
  303. {
  304. case 1:
  305. // up
  306. glutSetCursor(GLUT_CURSOR_LEFT_ARROW);
  307. is_rotating = false;
  308. break;
  309. case 0:
  310. // down
  311. if(!tw_using)
  312. {
  313. glutSetCursor(GLUT_CURSOR_CYCLE);
  314. // collect information for trackball
  315. is_rotating = true;
  316. down_camera = s.camera;
  317. down_x = mouse_x;
  318. down_y = mouse_y;
  319. }
  320. break;
  321. }
  322. break;
  323. }
  324. // Scroll down
  325. case 3:
  326. {
  327. mouse_wheel(0,-1,mouse_x,mouse_y);
  328. break;
  329. }
  330. // Scroll up
  331. case 4:
  332. {
  333. mouse_wheel(0,1,mouse_x,mouse_y);
  334. break;
  335. }
  336. // Scroll left
  337. case 5:
  338. {
  339. mouse_wheel(1,-1,mouse_x,mouse_y);
  340. break;
  341. }
  342. // Scroll right
  343. case 6:
  344. {
  345. mouse_wheel(1,1,mouse_x,mouse_y);
  346. break;
  347. }
  348. }
  349. glutPostRedisplay();
  350. }
  351. void mouse_drag(int mouse_x, int mouse_y)
  352. {
  353. using namespace igl;
  354. using namespace Eigen;
  355. if(is_rotating)
  356. {
  357. glutSetCursor(GLUT_CURSOR_CYCLE);
  358. Quaterniond q;
  359. auto & camera = s.camera;
  360. switch(rotation_type)
  361. {
  362. case ROTATION_TYPE_IGL_TRACKBALL:
  363. {
  364. // Rotate according to trackball
  365. igl::trackball<double>(
  366. width,
  367. height,
  368. 2.0,
  369. down_camera.m_rotation_conj.coeffs().data(),
  370. down_x,
  371. down_y,
  372. mouse_x,
  373. mouse_y,
  374. q.coeffs().data());
  375. break;
  376. }
  377. case ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
  378. {
  379. // Rotate according to two axis valuator with fixed up vector
  380. two_axis_valuator_fixed_up(
  381. width, height,
  382. 2.0,
  383. down_camera.m_rotation_conj,
  384. down_x, down_y, mouse_x, mouse_y,
  385. q);
  386. break;
  387. }
  388. default:
  389. break;
  390. }
  391. camera.orbit(q.conjugate());
  392. }else
  393. {
  394. TwEventMouseMotionGLUT(mouse_x, mouse_y);
  395. }
  396. glutPostRedisplay();
  397. }
  398. void initC(
  399. const Eigen::MatrixXd & Z,
  400. const int selected_col,
  401. Eigen::MatrixXd & C)
  402. {
  403. using namespace igl;
  404. C.resize(Z.rows(),3);
  405. const double min_z = Z.minCoeff();
  406. const double max_z = Z.maxCoeff();
  407. for(int r = 0;r<Z.rows();r++)
  408. {
  409. jet((Z(r,selected_col)-min_z)/(max_z-min_z),C(r,0),C(r,1),C(r,2));
  410. }
  411. }
  412. void key(unsigned char key, int mouse_x, int mouse_y)
  413. {
  414. using namespace std;
  415. switch(key)
  416. {
  417. case '.':
  418. selected_col = (selected_col+1)%Z.cols();
  419. initC(Z,selected_col,C);
  420. break;
  421. case ',':
  422. selected_col = (selected_col+Z.cols()-1)%Z.cols();
  423. initC(Z,selected_col,C);
  424. break;
  425. // ESC
  426. case char(27):
  427. rebar.save(REBAR_NAME);
  428. // ^C
  429. case char(3):
  430. exit(0);
  431. default:
  432. if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
  433. {
  434. cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
  435. }
  436. }
  437. glutPostRedisplay();
  438. }
  439. int main(int argc, char * argv[])
  440. {
  441. using namespace Eigen;
  442. using namespace igl;
  443. using namespace std;
  444. // init mesh
  445. string filename = "../shared/beast.obj";
  446. string cfilename = "../shared/beast-xyz.dmat";
  447. if(argc < 3)
  448. {
  449. cerr<<"Usage:"<<endl<<" ./example input.obj color.dmat"<<endl;
  450. cout<<endl<<"Opening default mesh..."<<endl;
  451. }else
  452. {
  453. // Read and prepare mesh
  454. filename = argv[1];
  455. cfilename = argv[2];
  456. }
  457. // dirname, basename, extension and filename
  458. string d,b,ext,f;
  459. pathinfo(filename,d,b,ext,f);
  460. // Convert extension to lower case
  461. transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  462. vector<vector<double > > vV,vN,vTC;
  463. vector<vector<int > > vF,vFTC,vFN;
  464. if(ext == "obj")
  465. {
  466. // Convert extension to lower case
  467. if(!igl::readOBJ(filename,vV,vTC,vN,vF,vFTC,vFN))
  468. {
  469. return 1;
  470. }
  471. }else if(ext == "off")
  472. {
  473. // Convert extension to lower case
  474. if(!igl::readOFF(filename,vV,vF,vN))
  475. {
  476. return 1;
  477. }
  478. }else if(ext == "wrl")
  479. {
  480. // Convert extension to lower case
  481. if(!igl::readWRL(filename,vV,vF))
  482. {
  483. return 1;
  484. }
  485. //}else
  486. //{
  487. // // Convert extension to lower case
  488. // MatrixXi T;
  489. // if(!igl::readMESH(filename,V,T,F))
  490. // {
  491. // return 1;
  492. // }
  493. // //if(F.size() > T.size() || F.size() == 0)
  494. // {
  495. // boundary_facets(T,F);
  496. // }
  497. }
  498. if(vV.size() > 0)
  499. {
  500. if(!list_to_matrix(vV,V))
  501. {
  502. return 1;
  503. }
  504. polygon_mesh_to_triangle_mesh(vF,F);
  505. }
  506. if(!readDMAT(cfilename,Z))
  507. {
  508. return 1;
  509. }
  510. // Compute normals, centroid, colors, bounding box diagonal
  511. per_vertex_normals(V,F,N);
  512. mid = 0.5*(V.colwise().maxCoeff() + V.colwise().minCoeff());
  513. bbd = (V.colwise().maxCoeff() - V.colwise().minCoeff()).maxCoeff();
  514. initC(Z,selected_col,C);
  515. // Init glut
  516. glutInit(&argc,argv);
  517. if( !TwInit(TW_OPENGL, NULL) )
  518. {
  519. // A fatal error occured
  520. fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
  521. return 1;
  522. }
  523. // Create a tweak bar
  524. rebar.TwNewBar("TweakBar");
  525. rebar.TwAddVarRW("camera_rotation", TW_TYPE_QUAT4D,
  526. s.camera.m_rotation_conj.coeffs().data(), "open readonly=true");
  527. s.camera.push_away(3);
  528. s.camera.dolly_zoom(25-s.camera.m_angle);
  529. TwType RotationTypeTW = igl::anttweakbar::ReTwDefineEnumFromString("RotationType",
  530. "igl_trackball,two-a...-fixed-up");
  531. rebar.TwAddVarCB( "rotation_type", RotationTypeTW,
  532. set_rotation_type,get_rotation_type,NULL,"keyIncr=] keyDecr=[");
  533. rebar.load(REBAR_NAME);
  534. glutInitDisplayString("rgba depth double samples>=8 ");
  535. glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT));
  536. glutCreateWindow("colored-mesh");
  537. glutDisplayFunc(display);
  538. glutReshapeFunc(reshape);
  539. glutKeyboardFunc(key);
  540. glutMouseFunc(mouse);
  541. glutMotionFunc(mouse_drag);
  542. glutPassiveMotionFunc(
  543. [](int x, int y)
  544. {
  545. TwEventMouseMotionGLUT(x,y);
  546. glutPostRedisplay();
  547. });
  548. static std::function<void(int)> timer_bounce;
  549. auto timer = [] (int ms) {
  550. timer_bounce(ms);
  551. };
  552. timer_bounce = [&] (int ms) {
  553. glutTimerFunc(ms, timer, ms);
  554. glutPostRedisplay();
  555. };
  556. glutTimerFunc(500, timer, 500);
  557. glutMainLoop();
  558. return 0;
  559. }