example.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. // Small GLUT application to test different scene rotation paradigms
  2. //
  3. #include "trackball.h"
  4. #include <igl/readOBJ.h>
  5. #include <igl/writeOBJ.h>
  6. #include <igl/writeOFF.h>
  7. #include <igl/readWRL.h>
  8. #include <igl/report_gl_error.h>
  9. #include <igl/triangulate.h>
  10. #include <igl/readOFF.h>
  11. #include <igl/readMESH.h>
  12. #include <igl/draw_mesh.h>
  13. #include <igl/draw_floor.h>
  14. #include <igl/pathinfo.h>
  15. #include <igl/list_to_matrix.h>
  16. #include <igl/quat_to_mat.h>
  17. #include <igl/per_face_normals.h>
  18. #include <igl/material_colors.h>
  19. #include <igl/trackball.h>
  20. #include <igl/snap_to_canonical_view_quat.h>
  21. #include <igl/REDRUM.h>
  22. #include <igl/Camera.h>
  23. #include <igl/ReAntTweakBar.h>
  24. #include <Eigen/Core>
  25. #include <Eigen/Geometry>
  26. #include <GLUT/glut.h>
  27. #include <Carbon/Carbon.h>
  28. #include <string>
  29. #include <vector>
  30. #include <stack>
  31. #include <iostream>
  32. Eigen::MatrixXd V,N;
  33. Eigen::VectorXd Vmid,Vmin,Vmax;
  34. double bbd = 1.0;
  35. Eigen::MatrixXi F;
  36. struct State
  37. {
  38. igl::Camera camera;
  39. } s;
  40. // See README for descriptions
  41. enum ROTATION_TYPE
  42. {
  43. ROTATION_TYPE_IGL_TRACKBALL = 0,
  44. ROTATION_TYPE_BELL_TRACKBALL = 1,
  45. ROTATION_TYPE_TWO_AXIS_VALUATOR = 2,
  46. ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP = 3,
  47. NUM_ROTATION_TYPES = 4,
  48. } rotation_type;
  49. std::stack<State> undo_stack;
  50. std::stack<State> redo_stack;
  51. bool is_rotating = false;
  52. int down_x,down_y;
  53. igl::Camera down_camera;
  54. int width,height;
  55. Eigen::Vector4f light_pos(-0.1,-0.1,0.9,0);
  56. #define REBAR_NAME "temp.rbr"
  57. igl::ReTwBar rebar;
  58. // No-op setter, does nothing
  59. void TW_CALL no_op(const void * /*value*/, void * /*clientData*/)
  60. {
  61. }
  62. void TW_CALL get_camera_rotation(void * value, void *clientData)
  63. {
  64. using namespace std;
  65. // case current value to double
  66. double * quat = (double *)(value);
  67. std::copy(s.camera.rotation,s.camera.rotation+4,quat);
  68. }
  69. void push_undo()
  70. {
  71. undo_stack.push(s);
  72. // Clear
  73. redo_stack = std::stack<State>();
  74. }
  75. void reshape(int width, int height)
  76. {
  77. ::width = width;
  78. ::height = height;
  79. glViewport(0,0,width,height);
  80. // Send the new window size to AntTweakBar
  81. TwWindowSize(width, height);
  82. }
  83. void push_scene()
  84. {
  85. using namespace igl;
  86. using namespace std;
  87. const double angle = s.camera.angle;
  88. glMatrixMode(GL_PROJECTION);
  89. glPushMatrix();
  90. glLoadIdentity();
  91. double zNear = 1e-2;
  92. double zFar = 100;
  93. double aspect = ((double)width)/((double)height);
  94. // Amount of scaling needed to "fix" perspective z-shift
  95. double z_fix = 1.0;
  96. // 5 is far enough to see unit "things" well
  97. const double camera_z = 2;
  98. // Test if should be using true orthographic projection
  99. if(angle == 0)
  100. {
  101. glOrtho(
  102. -0.5*camera_z*aspect,
  103. 0.5*camera_z*aspect,
  104. -0.5*camera_z,
  105. 0.5*camera_z,
  106. zNear,
  107. zFar);
  108. }else
  109. {
  110. // Make sure aspect is sane
  111. aspect = aspect < 0.01 ? 0.01 : aspect;
  112. gluPerspective(angle,aspect,zNear,zFar);
  113. z_fix = 2.*tan(angle/2./360.*2.*M_PI);
  114. }
  115. glMatrixMode(GL_MODELVIEW);
  116. glPushMatrix();
  117. glLoadIdentity();
  118. gluLookAt(0,0,camera_z,0,0,0,0,1,0);
  119. // Adjust scale to correct perspective
  120. glScaled(z_fix,z_fix,z_fix);
  121. // scale, pan
  122. glScaled( s.camera.zoom, s.camera.zoom, s.camera.zoom);
  123. double mat[4*4];
  124. quat_to_mat(s.camera.rotation,mat);
  125. glMultMatrixd(mat);
  126. }
  127. void push_object()
  128. {
  129. using namespace igl;
  130. glPushMatrix();
  131. glScaled(2./bbd,2./bbd,2./bbd);
  132. glTranslated(-Vmid(0),-Vmid(1),-Vmid(2));
  133. }
  134. void pop_object()
  135. {
  136. glPopMatrix();
  137. }
  138. void pop_scene()
  139. {
  140. glMatrixMode(GL_PROJECTION);
  141. glPopMatrix();
  142. glMatrixMode(GL_MODELVIEW);
  143. glPopMatrix();
  144. }
  145. // Set up double-sided lights
  146. void lights()
  147. {
  148. using namespace std;
  149. using namespace Eigen;
  150. glEnable(GL_LIGHTING);
  151. glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  152. glEnable(GL_LIGHT0);
  153. glEnable(GL_LIGHT1);
  154. float WHITE[4] = {0.8,0.8,0.8,1.};
  155. float GREY[4] = {0.4,0.4,0.4,1.};
  156. float BLACK[4] = {0.,0.,0.,1.};
  157. Vector4f pos = light_pos;
  158. glLightfv(GL_LIGHT0,GL_AMBIENT,GREY);
  159. glLightfv(GL_LIGHT0,GL_DIFFUSE,WHITE);
  160. glLightfv(GL_LIGHT0,GL_SPECULAR,BLACK);
  161. glLightfv(GL_LIGHT0,GL_POSITION,pos.data());
  162. pos(0) *= -1;
  163. pos(1) *= -1;
  164. pos(2) *= -1;
  165. glLightfv(GL_LIGHT1,GL_AMBIENT,GREY);
  166. glLightfv(GL_LIGHT1,GL_DIFFUSE,WHITE);
  167. glLightfv(GL_LIGHT1,GL_SPECULAR,BLACK);
  168. glLightfv(GL_LIGHT1,GL_POSITION,pos.data());
  169. }
  170. void display()
  171. {
  172. using namespace igl;
  173. using namespace std;
  174. glClearColor(1,1,1,0);
  175. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  176. glEnable(GL_DEPTH_TEST);
  177. glEnable(GL_NORMALIZE);
  178. lights();
  179. push_scene();
  180. push_object();
  181. // Set material properties
  182. glDisable(GL_COLOR_MATERIAL);
  183. glMaterialfv(GL_FRONT, GL_AMBIENT, GOLD_AMBIENT);
  184. glMaterialfv(GL_FRONT, GL_DIFFUSE, GOLD_DIFFUSE );
  185. glMaterialfv(GL_FRONT, GL_SPECULAR, GOLD_SPECULAR);
  186. glMaterialf (GL_FRONT, GL_SHININESS, 128);
  187. glMaterialfv(GL_BACK, GL_AMBIENT, SILVER_AMBIENT);
  188. glMaterialfv(GL_BACK, GL_DIFFUSE, FAST_GREEN_DIFFUSE );
  189. glMaterialfv(GL_BACK, GL_SPECULAR, SILVER_SPECULAR);
  190. glMaterialf (GL_BACK, GL_SHININESS, 128);
  191. draw_mesh(V,F,N);
  192. pop_object();
  193. // Draw a nice floor
  194. glPushMatrix();
  195. const double floor_offset =
  196. -2./bbd*(V.col(1).maxCoeff()-Vmid(1));
  197. glTranslated(0,floor_offset,0);
  198. const float GREY[4] = {0.5,0.5,0.6,1.0};
  199. const float DARK_GREY[4] = {0.2,0.2,0.3,1.0};
  200. draw_floor(GREY,DARK_GREY);
  201. glPopMatrix();
  202. pop_scene();
  203. report_gl_error();
  204. TwDraw();
  205. glutSwapBuffers();
  206. glutPostRedisplay();
  207. }
  208. void mouse_wheel(int wheel, int direction, int mouse_x, int mouse_y)
  209. {
  210. using namespace std;
  211. push_undo();
  212. if(wheel == 0)
  213. {
  214. static double mouse_scroll_y = 0;
  215. const double delta_y = 0.125*direction;
  216. mouse_scroll_y += delta_y;
  217. // absolute scale difference when changing zooms (+1)
  218. const double z_diff = 0.01;
  219. GLint viewport[4];
  220. glGetIntegerv(GL_VIEWPORT,viewport);
  221. if(TwMouseMotion(mouse_x, viewport[3] - mouse_y))
  222. {
  223. TwMouseWheel(mouse_scroll_y);
  224. }else
  225. {
  226. s.camera.zoom *= (1.0+double(direction)*z_diff);
  227. const double min_zoom = 0.01;
  228. const double max_zoom = 10.0;
  229. s.camera.zoom = min(max_zoom,max(min_zoom,s.camera.zoom));
  230. }
  231. }else
  232. {
  233. if(!is_rotating)
  234. {
  235. // Change viewing angle (reshape will take care of adjust zoom)
  236. const double a_diff = 1.0;
  237. s.camera.angle += double(direction)*a_diff;
  238. const double min_angle = 15.0;
  239. s.camera.angle =
  240. min(90.0,max(min_angle,s.camera.angle));
  241. }
  242. }
  243. }
  244. void mouse(int glutButton, int glutState, int mouse_x, int mouse_y)
  245. {
  246. using namespace std;
  247. using namespace Eigen;
  248. using namespace igl;
  249. bool tw_using = TwEventMouseButtonGLUT(glutButton,glutState,mouse_x,mouse_y);
  250. switch(glutButton)
  251. {
  252. case GLUT_RIGHT_BUTTON:
  253. case GLUT_LEFT_BUTTON:
  254. {
  255. switch(glutState)
  256. {
  257. case 1:
  258. // up
  259. glutSetCursor(GLUT_CURSOR_INHERIT);
  260. is_rotating = false;
  261. break;
  262. case 0:
  263. if(!tw_using)
  264. {
  265. push_undo();
  266. glutSetCursor(GLUT_CURSOR_CYCLE);
  267. // collect information for trackball
  268. is_rotating = true;
  269. down_camera = s.camera;
  270. down_x = mouse_x;
  271. down_y = mouse_y;
  272. }
  273. break;
  274. }
  275. break;
  276. }
  277. // Scroll down
  278. case 3:
  279. {
  280. mouse_wheel(0,-1,mouse_x,mouse_y);
  281. break;
  282. }
  283. // Scroll up
  284. case 4:
  285. {
  286. mouse_wheel(0,1,mouse_x,mouse_y);
  287. break;
  288. }
  289. // Scroll left
  290. case 5:
  291. {
  292. mouse_wheel(1,-1,mouse_x,mouse_y);
  293. break;
  294. }
  295. // Scroll right
  296. case 6:
  297. {
  298. mouse_wheel(1,1,mouse_x,mouse_y);
  299. break;
  300. }
  301. }
  302. }
  303. void mouse_drag(int mouse_x, int mouse_y)
  304. {
  305. using namespace igl;
  306. using namespace std;
  307. using namespace Eigen;
  308. if(is_rotating)
  309. {
  310. glutSetCursor(GLUT_CURSOR_CYCLE);
  311. switch(rotation_type)
  312. {
  313. case ROTATION_TYPE_IGL_TRACKBALL:
  314. {
  315. // Rotate according to trackball
  316. igl::trackball<double>(
  317. width,
  318. height,
  319. 2.0,
  320. down_camera.rotation,
  321. down_x,
  322. down_y,
  323. mouse_x,
  324. mouse_y,
  325. s.camera.rotation);
  326. break;
  327. }
  328. case ROTATION_TYPE_BELL_TRACKBALL:
  329. {
  330. float down_quaternion[4];
  331. copy(down_camera.rotation,down_camera.rotation+4,down_quaternion);
  332. float new_quaternion[4];
  333. const float center_x = ((float)width)/2.0;
  334. const float center_y = ((float)height)/2.0;
  335. const double speed = 2.0f;
  336. const float half_width = ((float)width)/speed;
  337. const float half_height = ((float)height)/speed;
  338. ::trackball(new_quaternion,
  339. (float)(center_x-down_x)/half_width,
  340. (float)(down_y-center_y)/half_height,
  341. (float)(center_x-mouse_x)/half_width,
  342. (float)(mouse_y-center_y)/half_height);
  343. // I think we need to do this because we have z pointing out of the
  344. // screen rather than into the screen
  345. new_quaternion[2] = -new_quaternion[2];
  346. float float_quat[4];
  347. add_quats(down_quaternion,new_quaternion,float_quat);
  348. copy(float_quat,float_quat+4,s.camera.rotation);
  349. break;
  350. }
  351. case ROTATION_TYPE_TWO_AXIS_VALUATOR:
  352. {
  353. Quaterniond down_q;
  354. copy(down_camera.rotation,down_camera.rotation+4,down_q.coeffs().data());
  355. Vector3d axis(mouse_y-down_y,mouse_x-down_x,0);
  356. const double speed = 2.0;
  357. if(axis.norm() != 0)
  358. {
  359. Quaterniond q;
  360. q =
  361. Quaterniond(
  362. AngleAxisd(
  363. M_PI*axis.norm()/(double)width*speed/2.0,
  364. axis.normalized())) * down_q;
  365. q.normalize();
  366. copy(q.coeffs().data(),q.coeffs().data()+4,s.camera.rotation);
  367. }
  368. break;
  369. }
  370. case ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
  371. {
  372. Quaterniond down_q;
  373. copy(down_camera.rotation,down_camera.rotation+4,down_q.coeffs().data());
  374. Vector3d axis(0,1,0);
  375. const double speed = 2.0;
  376. Quaterniond q;
  377. q = down_q *
  378. Quaterniond(
  379. AngleAxisd(
  380. M_PI*((double)(mouse_x-down_x))/(double)width*speed/2.0,
  381. axis.normalized()));
  382. q.normalize();
  383. {
  384. Vector3d axis(1,0,0);
  385. const double speed = 2.0;
  386. if(axis.norm() != 0)
  387. {
  388. q =
  389. Quaterniond(
  390. AngleAxisd(
  391. M_PI*(mouse_y-down_y)/(double)width*speed/2.0,
  392. axis.normalized())) * q;
  393. q.normalize();
  394. }
  395. }
  396. copy(q.coeffs().data(),q.coeffs().data()+4,s.camera.rotation);
  397. break;
  398. }
  399. default:
  400. break;
  401. }
  402. }
  403. }
  404. void init_relative()
  405. {
  406. using namespace Eigen;
  407. using namespace igl;
  408. per_face_normals(V,F,N);
  409. Vmax = V.colwise().maxCoeff();
  410. Vmin = V.colwise().minCoeff();
  411. Vmid = 0.5*(Vmax + Vmin);
  412. bbd = (Vmax-Vmin).norm();
  413. }
  414. KeyMap keyStates ;
  415. bool IS_KEYDOWN( uint16_t vKey )
  416. {
  417. uint8_t index = vKey / 32 ;
  418. uint8_t shift = vKey % 32 ;
  419. return keyStates[index].bigEndianValue & (1 << shift) ;
  420. }
  421. void undo()
  422. {
  423. using namespace std;
  424. if(!undo_stack.empty())
  425. {
  426. redo_stack.push(s);
  427. s = undo_stack.top();
  428. undo_stack.pop();
  429. }
  430. }
  431. void redo()
  432. {
  433. using namespace std;
  434. if(!redo_stack.empty())
  435. {
  436. undo_stack.push(s);
  437. s = redo_stack.top();
  438. redo_stack.pop();
  439. }
  440. }
  441. void key(unsigned char key, int mouse_x, int mouse_y)
  442. {
  443. using namespace std;
  444. GetKeys(keyStates);
  445. const bool command_down = IS_KEYDOWN(kVK_Command);
  446. const bool shift_down = IS_KEYDOWN(kVK_Shift);
  447. switch(key)
  448. {
  449. // ESC
  450. case char(27):
  451. rebar.save(REBAR_NAME);
  452. // ^C
  453. case char(3):
  454. exit(0);
  455. case 'z':
  456. case 'Z':
  457. if(command_down)
  458. {
  459. if(shift_down)
  460. {
  461. redo();
  462. }else
  463. {
  464. undo();
  465. }
  466. break;
  467. }else
  468. {
  469. push_undo();
  470. igl::snap_to_canonical_view_quat<double>(
  471. s.camera.rotation,
  472. 1.0,
  473. s.camera.rotation);
  474. break;
  475. }
  476. default:
  477. if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
  478. {
  479. cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
  480. }
  481. }
  482. }
  483. int main(int argc, char * argv[])
  484. {
  485. using namespace std;
  486. using namespace Eigen;
  487. using namespace igl;
  488. string filename = "../shared/cheburashka.obj";
  489. if(argc < 2)
  490. {
  491. cerr<<"Usage:"<<endl<<" ./example input.obj"<<endl;
  492. cout<<endl<<"Opening default mesh..."<<endl;
  493. }else
  494. {
  495. // Read and prepare mesh
  496. filename = argv[1];
  497. }
  498. // print key commands
  499. cout<<"[Click] and [drag] Rotate model using trackball."<<endl;
  500. cout<<"[Z,z] Snap rotation to canonical view."<<endl;
  501. cout<<"[⌘ Z] Undo."<<endl;
  502. cout<<"[⇧ ⌘ Z] Redo."<<endl;
  503. cout<<"[^C,ESC] Exit."<<endl;
  504. // dirname, basename, extension and filename
  505. string d,b,ext,f;
  506. pathinfo(filename,d,b,ext,f);
  507. // Convert extension to lower case
  508. transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  509. vector<vector<double > > vV,vN,vTC;
  510. vector<vector<int > > vF,vFTC,vFN;
  511. if(ext == "obj")
  512. {
  513. // Convert extension to lower case
  514. if(!igl::readOBJ(filename,vV,vTC,vN,vF,vFTC,vFN))
  515. {
  516. return 1;
  517. }
  518. }else if(ext == "off")
  519. {
  520. // Convert extension to lower case
  521. if(!igl::readOFF(filename,vV,vF,vN))
  522. {
  523. return 1;
  524. }
  525. }else if(ext == "wrl")
  526. {
  527. // Convert extension to lower case
  528. if(!igl::readWRL(filename,vV,vF))
  529. {
  530. return 1;
  531. }
  532. //}else
  533. //{
  534. // // Convert extension to lower case
  535. // MatrixXi T;
  536. // if(!igl::readMESH(filename,V,T,F))
  537. // {
  538. // return 1;
  539. // }
  540. // //if(F.size() > T.size() || F.size() == 0)
  541. // {
  542. // boundary_faces(T,F);
  543. // }
  544. }
  545. if(vV.size() > 0)
  546. {
  547. if(!list_to_matrix(vV,V))
  548. {
  549. return 1;
  550. }
  551. triangulate(vF,F);
  552. }
  553. init_relative();
  554. // Init glut
  555. glutInit(&argc,argv);
  556. if( !TwInit(TW_OPENGL, NULL) )
  557. {
  558. // A fatal error occured
  559. fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
  560. return 1;
  561. }
  562. // Create a tweak bar
  563. rebar.TwNewBar("TweakBar");
  564. rebar.TwAddVarCB("camera_rotation", TW_TYPE_QUAT4D, no_op,get_camera_rotation, NULL, "open readonly=true");
  565. TwEnumVal RotationTypesEV[NUM_ROTATION_TYPES] =
  566. {
  567. {ROTATION_TYPE_IGL_TRACKBALL,"igl trackball"},
  568. {ROTATION_TYPE_BELL_TRACKBALL,"bell trackball"},
  569. {ROTATION_TYPE_TWO_AXIS_VALUATOR,"two axis valuator"},
  570. {ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP,"two a... fixed up"},
  571. };
  572. TwType RotationTypeTW =
  573. ReTwDefineEnum(
  574. "RotationType",
  575. RotationTypesEV,
  576. NUM_ROTATION_TYPES);
  577. rebar.TwAddVarRW( "rotation_type", RotationTypeTW, &rotation_type,"keyIncr=] keyDecr=[");
  578. rebar.load(REBAR_NAME);
  579. // Init antweakbar
  580. glutInitDisplayString( "rgba depth double samples>=8 ");
  581. glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT));
  582. glutCreateWindow("upright");
  583. glutDisplayFunc(display);
  584. glutReshapeFunc(reshape);
  585. glutKeyboardFunc(key);
  586. glutMouseFunc(mouse);
  587. glutMotionFunc(mouse_drag);
  588. glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
  589. glutMainLoop();
  590. return 0;
  591. }