example.cpp 15 KB

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