example.cpp 16 KB

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