example.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. #include <igl/draw_skeleton_vector_graphics.h>
  2. #include <igl/two_axis_valuator_fixed_up.h>
  3. #include <igl/read_triangle_mesh.h>
  4. #include <igl/readTGF.h>
  5. #include <igl/writeOBJ.h>
  6. #include <igl/writeOFF.h>
  7. #include <igl/report_gl_error.h>
  8. #include <igl/draw_mesh.h>
  9. #include <igl/draw_floor.h>
  10. #include <igl/pathinfo.h>
  11. #include <igl/list_to_matrix.h>
  12. #include <igl/quat_to_mat.h>
  13. #include <igl/per_face_normals.h>
  14. #include <igl/material_colors.h>
  15. #include <igl/trackball.h>
  16. #include <igl/snap_to_canonical_view_quat.h>
  17. #include <igl/snap_to_fixed_up.h>
  18. #include <igl/REDRUM.h>
  19. #include <igl/Camera.h>
  20. #include <igl/ReAntTweakBar.h>
  21. #include <igl/get_seconds.h>
  22. #include <igl/forward_kinematics.h>
  23. #include <igl/boundary_conditions.h>
  24. #include <igl/normalize_row_sums.h>
  25. #include <igl/lbs_matrix.h>
  26. #include <igl/sort_triangles.h>
  27. #include <igl/slice.h>
  28. #include <igl/project.h>
  29. #include <igl/unproject.h>
  30. #include <igl/embree/EmbreeIntersector.h>
  31. #include <igl/embree/unproject_in_mesh.h>
  32. #include <igl/matlab_format.h>
  33. #include <igl/remove_unreferenced.h>
  34. #include <igl/adjacency_list.h>
  35. #include <igl/adjacency_matrix.h>
  36. #include <igl/right_axis.h>
  37. #include <igl/colon.h>
  38. #include <igl/unique.h>
  39. #include <igl/REDRUM.h>
  40. #include <igl/writeTGF.h>
  41. #include <igl/file_exists.h>
  42. #include <igl/centroid.h>
  43. #include <igl/draw_skeleton_3d.h>
  44. #include <Eigen/Core>
  45. #include <Eigen/Geometry>
  46. #ifdef __APPLE__
  47. #include <GLUT/glut.h>
  48. #else
  49. #include <GL/glut.h>
  50. #endif
  51. #include <string>
  52. #include <vector>
  53. #include <queue>
  54. #include <stack>
  55. #include <iostream>
  56. enum SkelStyleType
  57. {
  58. SKEL_STYLE_TYPE_3D = 0,
  59. SKEL_STYLE_TYPE_VECTOR_GRAPHICS = 1,
  60. NUM_SKEL_STYLE_TYPE = 2
  61. }skel_style;
  62. Eigen::MatrixXd V,N,sorted_N;
  63. Eigen::Vector3d Vmid,Vcen;
  64. double bbd = 1.0;
  65. Eigen::MatrixXi F,sorted_F;
  66. Eigen::VectorXi P;
  67. igl::Camera camera;
  68. struct State
  69. {
  70. Eigen::MatrixXd C;
  71. Eigen::MatrixXi BE;
  72. Eigen::VectorXi sel;
  73. } s;
  74. bool wireframe = false;
  75. bool skeleton_on_top = false;
  76. double alpha = 0.5;
  77. // See README for descriptions
  78. enum RotationType
  79. {
  80. ROTATION_TYPE_IGL_TRACKBALL = 0,
  81. ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP = 1,
  82. NUM_ROTATION_TYPES = 2,
  83. } rotation_type = ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP;
  84. std::stack<State> undo_stack;
  85. std::stack<State> redo_stack;
  86. bool is_rotating = false;
  87. bool is_dragging = false;
  88. bool new_leaf_on_drag = false;
  89. bool new_root_on_drag = false;
  90. int down_x,down_y;
  91. Eigen::MatrixXd down_C;
  92. igl::Camera down_camera;
  93. std::string output_filename;
  94. bool is_animating = false;
  95. double animation_start_time = 0;
  96. double ANIMATION_DURATION = 0.5;
  97. Eigen::Quaterniond animation_from_quat;
  98. Eigen::Quaterniond animation_to_quat;
  99. int width,height;
  100. Eigen::Vector4f light_pos(-0.1,-0.1,0.9,0);
  101. #define REBAR_NAME "temp.rbr"
  102. igl::ReTwBar rebar;
  103. igl::EmbreeIntersector ei;
  104. void push_undo()
  105. {
  106. undo_stack.push(s);
  107. // Clear
  108. redo_stack = std::stack<State>();
  109. }
  110. // No-op setter, does nothing
  111. void TW_CALL no_op(const void * /*value*/, void * /*clientData*/)
  112. {
  113. }
  114. void TW_CALL set_rotation_type(const void * value, void * clientData)
  115. {
  116. using namespace Eigen;
  117. using namespace std;
  118. using namespace igl;
  119. const RotationType old_rotation_type = rotation_type;
  120. rotation_type = *(const RotationType *)(value);
  121. if(rotation_type == ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP &&
  122. old_rotation_type != ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP)
  123. {
  124. push_undo();
  125. animation_from_quat = camera.m_rotation_conj;
  126. snap_to_fixed_up(animation_from_quat,animation_to_quat);
  127. // start animation
  128. animation_start_time = get_seconds();
  129. is_animating = true;
  130. }
  131. }
  132. void TW_CALL get_rotation_type(void * value, void *clientData)
  133. {
  134. RotationType * rt = (RotationType *)(value);
  135. *rt = rotation_type;
  136. }
  137. void reshape(int width, int height)
  138. {
  139. ::width = width;
  140. ::height = height;
  141. glViewport(0,0,width,height);
  142. // Send the new window size to AntTweakBar
  143. TwWindowSize(width, height);
  144. camera.m_aspect = (double)width/(double)height;
  145. }
  146. void push_scene()
  147. {
  148. using namespace igl;
  149. using namespace std;
  150. glMatrixMode(GL_PROJECTION);
  151. glPushMatrix();
  152. glLoadIdentity();
  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 push_object()
  163. {
  164. using namespace igl;
  165. glPushMatrix();
  166. glScaled(2./bbd,2./bbd,2./bbd);
  167. glTranslated(-Vmid(0),-Vmid(1),-Vmid(2));
  168. }
  169. void pop_object()
  170. {
  171. glPopMatrix();
  172. }
  173. void pop_scene()
  174. {
  175. glMatrixMode(GL_PROJECTION);
  176. glPopMatrix();
  177. glMatrixMode(GL_MODELVIEW);
  178. glPopMatrix();
  179. }
  180. // Set up double-sided lights
  181. void lights()
  182. {
  183. using namespace std;
  184. using namespace Eigen;
  185. glEnable(GL_LIGHTING);
  186. glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  187. glEnable(GL_LIGHT0);
  188. glEnable(GL_LIGHT1);
  189. float WHITE[4] = {0.8,0.8,0.8,1.};
  190. float GREY[4] = {0.4,0.4,0.4,1.};
  191. float BLACK[4] = {0.,0.,0.,1.};
  192. Vector4f pos = light_pos;
  193. glLightfv(GL_LIGHT0,GL_AMBIENT,GREY);
  194. glLightfv(GL_LIGHT0,GL_DIFFUSE,WHITE);
  195. glLightfv(GL_LIGHT0,GL_SPECULAR,BLACK);
  196. glLightfv(GL_LIGHT0,GL_POSITION,pos.data());
  197. pos(0) *= -1;
  198. pos(1) *= -1;
  199. pos(2) *= -1;
  200. glLightfv(GL_LIGHT1,GL_AMBIENT,GREY);
  201. glLightfv(GL_LIGHT1,GL_DIFFUSE,WHITE);
  202. glLightfv(GL_LIGHT1,GL_SPECULAR,BLACK);
  203. glLightfv(GL_LIGHT1,GL_POSITION,pos.data());
  204. }
  205. void sort()
  206. {
  207. using namespace std;
  208. using namespace Eigen;
  209. using namespace igl;
  210. push_scene();
  211. push_object();
  212. VectorXi I;
  213. sort_triangles(V,F,sorted_F,I);
  214. slice(N,I,1,sorted_N);
  215. pop_object();
  216. pop_scene();
  217. }
  218. void display()
  219. {
  220. using namespace igl;
  221. using namespace std;
  222. using namespace Eigen;
  223. const float back[4] = {0.75, 0.75, 0.75,0};
  224. glClearColor(back[0],back[1],back[2],0);
  225. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  226. static bool first = true;
  227. if(first)
  228. {
  229. sort();
  230. first = false;
  231. }
  232. if(is_animating)
  233. {
  234. double t = (get_seconds() - animation_start_time)/ANIMATION_DURATION;
  235. if(t > 1)
  236. {
  237. t = 1;
  238. is_animating = false;
  239. }
  240. Quaterniond q = animation_from_quat.slerp(t,animation_to_quat).normalized();
  241. camera.orbit(q.conjugate());
  242. }
  243. glEnable(GL_DEPTH_TEST);
  244. glDepthFunc(GL_LEQUAL);
  245. glEnable(GL_NORMALIZE);
  246. glEnable(GL_BLEND);
  247. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  248. lights();
  249. push_scene();
  250. // Draw a nice floor
  251. glEnable(GL_DEPTH_TEST);
  252. glPushMatrix();
  253. const double floor_offset =
  254. -2./bbd*(V.col(1).maxCoeff()-Vmid(1));
  255. glTranslated(0,floor_offset,0);
  256. const float GREY[4] = {0.5,0.5,0.6,1.0};
  257. const float DARK_GREY[4] = {0.2,0.2,0.3,1.0};
  258. glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  259. glEnable(GL_CULL_FACE);
  260. glCullFace(GL_BACK);
  261. draw_floor(GREY,DARK_GREY);
  262. glDisable(GL_CULL_FACE);
  263. glPopMatrix();
  264. push_object();
  265. const auto & draw_skeleton = []()
  266. {
  267. switch(skel_style)
  268. {
  269. default:
  270. case SKEL_STYLE_TYPE_3D:
  271. {
  272. MatrixXf colors = MAYA_VIOLET.transpose().replicate(s.BE.rows(),1);
  273. for(int si=0;si<s.sel.size();si++)
  274. {
  275. for(int b=0;b<s.BE.rows();b++)
  276. {
  277. if(s.BE(b,0) == s.sel(si) || s.BE(b,1) == s.sel(si))
  278. {
  279. colors.row(b) = MAYA_SEA_GREEN;
  280. }
  281. }
  282. }
  283. draw_skeleton_3d(s.C,s.BE,MatrixXd(),colors,bbd*0.5);
  284. break;
  285. }
  286. case SKEL_STYLE_TYPE_VECTOR_GRAPHICS:
  287. draw_skeleton_vector_graphics(s.C,s.BE);
  288. break;
  289. }
  290. };
  291. if(!skeleton_on_top)
  292. {
  293. draw_skeleton();
  294. }
  295. // Set material properties
  296. glDisable(GL_COLOR_MATERIAL);
  297. glMaterialfv(GL_FRONT, GL_AMBIENT,
  298. Vector4f(GOLD_AMBIENT[0],GOLD_AMBIENT[1],GOLD_AMBIENT[2],alpha).data());
  299. glMaterialfv(GL_FRONT, GL_DIFFUSE,
  300. Vector4f(GOLD_DIFFUSE[0],GOLD_DIFFUSE[1],GOLD_DIFFUSE[2],alpha).data());
  301. glMaterialfv(GL_FRONT, GL_SPECULAR,
  302. Vector4f(GOLD_SPECULAR[0],GOLD_SPECULAR[1],GOLD_SPECULAR[2],alpha).data());
  303. glMaterialf (GL_FRONT, GL_SHININESS, 128);
  304. glMaterialfv(GL_BACK, GL_AMBIENT,
  305. Vector4f(SILVER_AMBIENT[0],SILVER_AMBIENT[1],SILVER_AMBIENT[2],alpha).data());
  306. glMaterialfv(GL_BACK, GL_DIFFUSE,
  307. Vector4f(FAST_GREEN_DIFFUSE[0],FAST_GREEN_DIFFUSE[1],FAST_GREEN_DIFFUSE[2],alpha).data());
  308. glMaterialfv(GL_BACK, GL_SPECULAR,
  309. Vector4f(SILVER_SPECULAR[0],SILVER_SPECULAR[1],SILVER_SPECULAR[2],alpha).data());
  310. glMaterialf (GL_BACK, GL_SHININESS, 128);
  311. if(wireframe)
  312. {
  313. glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
  314. }
  315. glLineWidth(1.0);
  316. draw_mesh(V,sorted_F,sorted_N);
  317. glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  318. if(skeleton_on_top)
  319. {
  320. glDisable(GL_DEPTH_TEST);
  321. draw_skeleton();
  322. }
  323. pop_object();
  324. pop_scene();
  325. report_gl_error();
  326. TwDraw();
  327. glutSwapBuffers();
  328. if(is_animating)
  329. {
  330. glutPostRedisplay();
  331. }
  332. }
  333. void mouse_wheel(int wheel, int direction, int mouse_x, int mouse_y)
  334. {
  335. using namespace std;
  336. using namespace igl;
  337. using namespace Eigen;
  338. GLint viewport[4];
  339. glGetIntegerv(GL_VIEWPORT,viewport);
  340. if(wheel == 0 && TwMouseMotion(mouse_x, viewport[3] - mouse_y))
  341. {
  342. static double mouse_scroll_y = 0;
  343. const double delta_y = 0.125*direction;
  344. mouse_scroll_y += delta_y;
  345. TwMouseWheel(mouse_scroll_y);
  346. return;
  347. }
  348. push_undo();
  349. if(wheel==0)
  350. {
  351. // factor of zoom change
  352. double s = (1.-0.01*direction);
  353. //// FOV zoom: just widen angle. This is hardly ever appropriate.
  354. //camera.m_angle *= s;
  355. //camera.m_angle = min(max(camera.m_angle,1),89);
  356. camera.push_away(s);
  357. }else
  358. {
  359. // Dolly zoom:
  360. camera.dolly_zoom((double)direction*1.0);
  361. }
  362. glutPostRedisplay();
  363. }
  364. Eigen::VectorXi selection(const std::vector<bool> & mask)
  365. {
  366. const int count = std::count(mask.begin(),mask.end(),true);
  367. Eigen::VectorXi sel(count);
  368. int s = 0;
  369. for(int c = 0;c<(int)mask.size();c++)
  370. {
  371. if(mask[c])
  372. {
  373. sel(s) = c;
  374. s++;
  375. }
  376. }
  377. return sel;
  378. }
  379. std::vector<bool> selection_mask(const Eigen::VectorXi & sel, const int n)
  380. {
  381. std::vector<bool> mask(n,false);
  382. for(int si = 0;si<sel.size();si++)
  383. {
  384. const int i = sel(si);
  385. mask[i] = true;
  386. }
  387. return mask;
  388. }
  389. bool ss_select(
  390. const double mouse_x,
  391. const double mouse_y,
  392. const Eigen::MatrixXd & C,
  393. const bool accum,
  394. Eigen::VectorXi & sel)
  395. {
  396. using namespace igl;
  397. using namespace Eigen;
  398. using namespace std;
  399. //// zap old list
  400. //if(!accum)
  401. //{
  402. // sel.resize(0,1);
  403. //}
  404. vector<bool> old_mask = selection_mask(s.sel,s.C.rows());
  405. vector<bool> mask(old_mask.size(),false);
  406. double min_dist = 1e25;
  407. bool sel_changed = false;
  408. bool found = false;
  409. for(int c = 0;c<C.rows();c++)
  410. {
  411. const RowVector3d & Cc = C.row(c);
  412. const auto Pc = project(Cc);
  413. const double SELECTION_DIST = 18;//pixels
  414. const double dist = (Pc.head(2)-RowVector2d(mouse_x,height-mouse_y)).norm();
  415. if(dist < SELECTION_DIST && (accum || dist < min_dist))
  416. {
  417. mask[c] = true;
  418. min_dist = dist;
  419. found = true;
  420. sel_changed |= mask[c] != old_mask[c];
  421. }
  422. }
  423. for(int c = 0;c<C.rows();c++)
  424. {
  425. if(accum)
  426. {
  427. mask[c] = mask[c] ^ old_mask[c];
  428. }else
  429. {
  430. if(!sel_changed)
  431. {
  432. mask[c] = mask[c] || old_mask[c];
  433. }
  434. }
  435. }
  436. sel = selection(mask);
  437. return found;
  438. }
  439. void mouse(int glutButton, int glutState, int mouse_x, int mouse_y)
  440. {
  441. using namespace std;
  442. using namespace Eigen;
  443. using namespace igl;
  444. bool tw_using = TwEventMouseButtonGLUT(glutButton,glutState,mouse_x,mouse_y);
  445. const int mod = (glutButton <=2 ? glutGetModifiers() : 0);
  446. const bool option_down = mod & GLUT_ACTIVE_ALT;
  447. const bool shift_down = mod & GLUT_ACTIVE_SHIFT;
  448. const bool command_down = GLUT_ACTIVE_COMMAND & mod;
  449. switch(glutButton)
  450. {
  451. case GLUT_RIGHT_BUTTON:
  452. case GLUT_LEFT_BUTTON:
  453. {
  454. switch(glutState)
  455. {
  456. case 1:
  457. // up
  458. glutSetCursor(GLUT_CURSOR_INHERIT);
  459. if(is_rotating)
  460. {
  461. sort();
  462. }
  463. is_rotating = false;
  464. is_dragging = false;
  465. break;
  466. case 0:
  467. new_leaf_on_drag = false;
  468. new_root_on_drag = false;
  469. if(!tw_using)
  470. {
  471. down_x = mouse_x;
  472. down_y = mouse_y;
  473. if(option_down)
  474. {
  475. glutSetCursor(GLUT_CURSOR_CYCLE);
  476. // collect information for trackball
  477. is_rotating = true;
  478. down_camera = camera;
  479. }else
  480. {
  481. push_undo();
  482. push_scene();
  483. push_object();
  484. // Zap selection
  485. if(shift_down)
  486. {
  487. s.sel.resize(0,1);
  488. }
  489. if(ss_select(mouse_x,mouse_y,s.C,
  490. command_down && !shift_down,
  491. s.sel))
  492. {
  493. if(shift_down)
  494. {
  495. new_leaf_on_drag = true;
  496. }
  497. }else
  498. {
  499. new_root_on_drag = true;
  500. }
  501. is_dragging = !command_down;
  502. down_C = s.C;
  503. pop_object();
  504. pop_scene();
  505. }
  506. }
  507. break;
  508. }
  509. break;
  510. }
  511. // Scroll down
  512. case 3:
  513. {
  514. mouse_wheel(0,-1,mouse_x,mouse_y);
  515. break;
  516. }
  517. // Scroll up
  518. case 4:
  519. {
  520. mouse_wheel(0,1,mouse_x,mouse_y);
  521. break;
  522. }
  523. // Scroll left
  524. case 5:
  525. {
  526. mouse_wheel(1,-1,mouse_x,mouse_y);
  527. break;
  528. }
  529. // Scroll right
  530. case 6:
  531. {
  532. mouse_wheel(1,1,mouse_x,mouse_y);
  533. break;
  534. }
  535. }
  536. glutPostRedisplay();
  537. }
  538. void mouse_drag(int mouse_x, int mouse_y)
  539. {
  540. using namespace igl;
  541. using namespace std;
  542. using namespace Eigen;
  543. if(is_rotating)
  544. {
  545. glutSetCursor(GLUT_CURSOR_CYCLE);
  546. Quaterniond q;
  547. switch(rotation_type)
  548. {
  549. case ROTATION_TYPE_IGL_TRACKBALL:
  550. {
  551. // Rotate according to trackball
  552. igl::trackball<double>(
  553. width,
  554. height,
  555. 2.0,
  556. down_camera.m_rotation_conj.coeffs().data(),
  557. down_x,
  558. down_y,
  559. mouse_x,
  560. mouse_y,
  561. q.coeffs().data());
  562. break;
  563. }
  564. case ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
  565. {
  566. // Rotate according to two axis valuator with fixed up vector
  567. two_axis_valuator_fixed_up(
  568. width, height,
  569. 2.0,
  570. down_camera.m_rotation_conj,
  571. down_x, down_y, mouse_x, mouse_y,
  572. q);
  573. break;
  574. }
  575. default:
  576. break;
  577. }
  578. camera.orbit(q.conjugate());
  579. }
  580. if(is_dragging)
  581. {
  582. push_scene();
  583. push_object();
  584. if(new_leaf_on_drag)
  585. {
  586. assert(s.C.size() >= 1);
  587. // one new node
  588. s.C.conservativeResize(s.C.rows()+1,3);
  589. const int nc = s.C.rows();
  590. assert(s.sel.size() >= 1);
  591. s.C.row(nc-1) = s.C.row(s.sel(0));
  592. // one new bone
  593. s.BE.conservativeResize(s.BE.rows()+1,2);
  594. s.BE.row(s.BE.rows()-1) = RowVector2i(s.sel(0),nc-1);
  595. // select just last node
  596. s.sel.resize(1,1);
  597. s.sel(0) = nc-1;
  598. // reset down_C
  599. down_C = s.C;
  600. new_leaf_on_drag = false;
  601. }
  602. if(new_root_on_drag)
  603. {
  604. // two new nodes
  605. s.C.conservativeResize(s.C.rows()+2,3);
  606. const int nc = s.C.rows();
  607. Vector3d obj;
  608. int nhits = unproject_in_mesh(mouse_x,height-mouse_y,ei,obj);
  609. if(nhits == 0)
  610. {
  611. Vector3d pV_mid = project(Vcen);
  612. obj = unproject(Vector3d(mouse_x,height-mouse_y,pV_mid(2)));
  613. }
  614. s.C.row(nc-2) = obj;
  615. s.C.row(nc-1) = obj;
  616. // select last node
  617. s.sel.resize(1,1);
  618. s.sel(0) = nc-1;
  619. // one new bone
  620. s.BE.conservativeResize(s.BE.rows()+1,2);
  621. s.BE.row(s.BE.rows()-1) = RowVector2i(nc-2,nc-1);
  622. // reset down_C
  623. down_C = s.C;
  624. new_root_on_drag = false;
  625. }
  626. double z = 0;
  627. Vector3d obj,win;
  628. int nhits = unproject_in_mesh(mouse_x,height-mouse_y,ei,obj);
  629. project(obj,win);
  630. z = win(2);
  631. for(int si = 0;si<s.sel.size();si++)
  632. {
  633. const int c = s.sel(si);
  634. Vector3d pc = project((RowVector3d) down_C.row(c));
  635. pc(0) += mouse_x-down_x;
  636. pc(1) += (height-mouse_y)-(height-down_y);
  637. if(nhits > 0)
  638. {
  639. pc(2) = z;
  640. }
  641. s.C.row(c) = unproject(pc);
  642. }
  643. pop_object();
  644. pop_scene();
  645. }
  646. glutPostRedisplay();
  647. }
  648. void init_relative()
  649. {
  650. using namespace Eigen;
  651. using namespace igl;
  652. using namespace std;
  653. per_face_normals(V,F,N);
  654. const auto Vmax = V.colwise().maxCoeff();
  655. const auto Vmin = V.colwise().minCoeff();
  656. Vmid = 0.5*(Vmax + Vmin);
  657. centroid(V,F,Vcen);
  658. bbd = (Vmax-Vmin).norm();
  659. cout<<"bbd: "<<bbd<<endl;
  660. camera.push_away(2);
  661. }
  662. void undo()
  663. {
  664. using namespace std;
  665. if(!undo_stack.empty())
  666. {
  667. redo_stack.push(s);
  668. s = undo_stack.top();
  669. undo_stack.pop();
  670. }
  671. }
  672. void redo()
  673. {
  674. using namespace std;
  675. if(!redo_stack.empty())
  676. {
  677. undo_stack.push(s);
  678. s = redo_stack.top();
  679. redo_stack.pop();
  680. }
  681. }
  682. void symmetrize()
  683. {
  684. using namespace std;
  685. using namespace igl;
  686. using namespace Eigen;
  687. if(s.sel.size() == 0)
  688. {
  689. cout<<YELLOWGIN("Make a selection first.")<<endl;
  690. return;
  691. }
  692. push_undo();
  693. push_scene();
  694. push_object();
  695. Vector3d right;
  696. right_axis(right.data(),right.data()+1,right.data()+2);
  697. right.normalize();
  698. MatrixXd RC(s.C.rows(),s.C.cols());
  699. MatrixXd old_C = s.C;
  700. for(int c = 0;c<s.C.rows();c++)
  701. {
  702. const Vector3d Cc = s.C.row(c);
  703. const auto A = Cc-Vcen;
  704. const auto A1 = A.dot(right) * right;
  705. const auto A2 = A-A1;
  706. RC.row(c) = Vcen + A2 - A1;
  707. }
  708. vector<bool> mask = selection_mask(s.sel,s.C.rows());
  709. // stupid O(n²) matching
  710. for(int c = 0;c<s.C.rows();c++)
  711. {
  712. // not selected
  713. if(!mask[c])
  714. {
  715. continue;
  716. }
  717. const Vector3d Cc = s.C.row(c);
  718. int min_r = -1;
  719. double min_dist = 1e25;
  720. double max_dist = 0.1*bbd;
  721. for(int r= 0;r<RC.rows();r++)
  722. {
  723. const Vector3d RCr = RC.row(r);
  724. const double dist = (Cc-RCr).norm();
  725. if(
  726. dist<min_dist && // closest
  727. dist<max_dist && // not too far away
  728. (c==r || (Cc-Vcen).dot(right)*(RCr-Vcen).dot(right) > 0) // on same side
  729. )
  730. {
  731. min_dist = dist;
  732. min_r = r;
  733. }
  734. }
  735. if(min_r>=0)
  736. {
  737. if(mask[min_r])
  738. {
  739. s.C.row(c) = 0.5*(Cc.transpose()+RC.row(min_r));
  740. }else
  741. {
  742. s.C.row(c) = RC.row(min_r);
  743. }
  744. }
  745. }
  746. pop_object();
  747. pop_scene();
  748. }
  749. bool save()
  750. {
  751. using namespace std;
  752. using namespace igl;
  753. if(writeTGF(output_filename,s.C,s.BE))
  754. {
  755. cout<<GREENGIN("Current skeleton written to "+output_filename+".")<<endl;
  756. return true;
  757. }else
  758. {
  759. cout<<REDRUM("Writing to "+output_filename+" failed.")<<endl;
  760. return false;
  761. }
  762. }
  763. void key(unsigned char key, int mouse_x, int mouse_y)
  764. {
  765. using namespace std;
  766. using namespace igl;
  767. using namespace Eigen;
  768. int mod = glutGetModifiers();
  769. const bool command_down = GLUT_ACTIVE_COMMAND & mod;
  770. const bool shift_down = GLUT_ACTIVE_SHIFT & mod;
  771. switch(key)
  772. {
  773. // ESC
  774. case char(27):
  775. rebar.save(REBAR_NAME);
  776. // ^C
  777. case char(3):
  778. exit(0);
  779. case char(127):
  780. {
  781. push_undo();
  782. // delete
  783. MatrixXi new_BE(s.BE.rows(),s.BE.cols());
  784. int count = 0;
  785. for(int b=0;b<s.BE.rows();b++)
  786. {
  787. bool selected = false;
  788. for(int si=0;si<s.sel.size();si++)
  789. {
  790. if(s.BE(b,0) == s.sel(si) || s.BE(b,1) == s.sel(si))
  791. {
  792. selected = true;
  793. break;
  794. }
  795. }
  796. if(!selected)
  797. {
  798. new_BE.row(count) = s.BE.row(b);
  799. count++;
  800. }
  801. }
  802. new_BE.conservativeResize(count,new_BE.cols());
  803. const auto old_C = s.C;
  804. VectorXi I;
  805. remove_unreferenced(old_C,new_BE,s.C,s.BE,I);
  806. s.sel.resize(0,1);
  807. break;
  808. }
  809. case 'A':
  810. case 'a':
  811. {
  812. push_undo();
  813. s.sel = colon<int>(0,s.C.rows()-1);
  814. break;
  815. }
  816. case 'C':
  817. case 'c':
  818. {
  819. push_undo();
  820. // snap close vertices
  821. SparseMatrix<double> A;
  822. adjacency_matrix(s.BE,A);
  823. VectorXi J = colon<int>(0,s.C.rows()-1);
  824. // stupid O(n²) version
  825. for(int c = 0;c<s.C.rows();c++)
  826. {
  827. for(int d = c+1;d<s.C.rows();d++)
  828. {
  829. if(
  830. A.coeff(c,d) == 0 && // no edge
  831. (s.C.row(c)-s.C.row(d)).norm() < 0.02*bbd //close
  832. )
  833. {
  834. // c < d
  835. J(d) = c;
  836. }
  837. }
  838. }
  839. for(int e = 0;e<s.BE.rows();e++)
  840. {
  841. s.BE(e,0) = J(s.BE(e,0));
  842. s.BE(e,1) = J(s.BE(e,1));
  843. }
  844. const auto old_BE = s.BE;
  845. const auto old_C = s.C;
  846. VectorXi I;
  847. remove_unreferenced(old_C,old_BE,s.C,s.BE,I);
  848. for(int i = 0;i<s.sel.size();i++)
  849. {
  850. s.sel(i) = J(s.sel(i));
  851. }
  852. VectorXi _;
  853. igl::unique(s.sel,s.sel,_,_);
  854. break;
  855. }
  856. case 'D':
  857. case 'd':
  858. {
  859. push_undo();
  860. s.sel.resize(0,1);
  861. break;
  862. }
  863. case 'P':
  864. case 'p':
  865. {
  866. // add bone to parents (should really only be one)
  867. push_undo();
  868. vector<int> new_sel;
  869. const int old_nbe = s.BE.rows();
  870. for(int si=0;si<s.sel.size();si++)
  871. {
  872. for(int b=0;b<old_nbe;b++)
  873. {
  874. if(s.BE(b,1) == s.sel(si))
  875. {
  876. // one new node
  877. s.C.conservativeResize(s.C.rows()+1,3);
  878. const int nc = s.C.rows();
  879. s.C.row(nc-1) = 0.5*(s.C.row(s.BE(b,1)) + s.C.row(s.BE(b,0)));
  880. // one new bone
  881. s.BE.conservativeResize(s.BE.rows()+1,2);
  882. s.BE.row(s.BE.rows()-1) = RowVector2i(nc-1,s.BE(b,1));
  883. s.BE(b,1) = nc-1;
  884. // select last node
  885. new_sel.push_back(nc-1);
  886. }
  887. }
  888. }
  889. list_to_matrix(new_sel,s.sel);
  890. break;
  891. }
  892. case 'R':
  893. case 'r':
  894. {
  895. // re-root try at first selected
  896. if(s.sel.size() > 0)
  897. {
  898. push_undo();
  899. // only use first
  900. s.sel.conservativeResize(1,1);
  901. // Ideally this should only effect the connected component of s.sel(0)
  902. const auto & C = s.C;
  903. auto & BE = s.BE;
  904. vector<bool> seen(C.rows(),false);
  905. // adjacency list
  906. vector<vector< int> > A;
  907. adjacency_list(BE,A,false);
  908. int e = 0;
  909. queue<int> Q;
  910. Q.push(s.sel(0));
  911. seen[s.sel(0)] = true;
  912. while(!Q.empty())
  913. {
  914. const int c = Q.front();
  915. Q.pop();
  916. for(const auto & d : A[c])
  917. {
  918. if(!seen[d])
  919. {
  920. BE(e,0) = c;
  921. BE(e,1) = d;
  922. e++;
  923. Q.push(d);
  924. seen[d] = true;
  925. }
  926. }
  927. }
  928. // only keep tree
  929. BE.conservativeResize(e,BE.cols());
  930. }
  931. break;
  932. }
  933. case 'S':
  934. case 's':
  935. {
  936. save();
  937. break;
  938. }
  939. case 'U':
  940. case 'u':
  941. {
  942. push_scene();
  943. push_object();
  944. for(int c = 0;c<s.C.rows();c++)
  945. {
  946. Vector3d P = project((Vector3d)s.C.row(c));
  947. Vector3d obj;
  948. int nhits = unproject_in_mesh(P(0),P(1),ei,obj);
  949. if(nhits > 0)
  950. {
  951. s.C.row(c) = obj;
  952. }
  953. }
  954. pop_object();
  955. pop_scene();
  956. break;
  957. }
  958. case 'Y':
  959. case 'y':
  960. {
  961. symmetrize();
  962. break;
  963. }
  964. case 'z':
  965. case 'Z':
  966. is_rotating = false;
  967. is_dragging = false;
  968. if(command_down)
  969. {
  970. if(shift_down)
  971. {
  972. redo();
  973. }else
  974. {
  975. undo();
  976. }
  977. break;
  978. }else
  979. {
  980. push_undo();
  981. Quaterniond q;
  982. snap_to_canonical_view_quat(camera.m_rotation_conj,1.0,q);
  983. camera.orbit(q.conjugate());
  984. }
  985. break;
  986. default:
  987. if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
  988. {
  989. cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
  990. }
  991. }
  992. glutPostRedisplay();
  993. }
  994. int main(int argc, char * argv[])
  995. {
  996. using namespace std;
  997. using namespace Eigen;
  998. using namespace igl;
  999. string filename = "../shared/decimated-knight.obj";
  1000. string skel_filename = "";
  1001. output_filename = "";
  1002. switch(argc)
  1003. {
  1004. case 4:
  1005. output_filename = argv[3];
  1006. //fall through
  1007. case 3:
  1008. skel_filename = argv[2];
  1009. if(output_filename.size() == 0)
  1010. {
  1011. output_filename = skel_filename;
  1012. }
  1013. //fall through
  1014. case 2:
  1015. // Read and prepare mesh
  1016. filename = argv[1];
  1017. break;
  1018. default:
  1019. cerr<<"Usage:"<<endl<<" ./example input.obj [input/output.tgf]"<<endl;
  1020. cout<<endl<<"Opening default mesh..."<<endl;
  1021. }
  1022. // print key commands
  1023. cout<<"[Click] and [drag] Create bone (or select node) and reposition."<<endl;
  1024. cout<<"⇧ +[Click] and [drag] Select node (or create one) and _pull out_ new bone."<<endl;
  1025. cout<<"⌥ +[Click] and [drag] Rotate secene."<<endl;
  1026. cout<<"⌫ Delete selected node(s) and incident bones."<<endl;
  1027. cout<<"A,a Select all."<<endl;
  1028. cout<<"D,d Deselect all."<<endl;
  1029. cout<<"C,c Snap close nodes."<<endl;
  1030. cout<<"P,p Split \"parent\" bone(s) of selection by creating new node(s)."<<endl;
  1031. cout<<"R,r Breadth first search at selection to redirect skeleton into tree."<<endl;
  1032. cout<<"S,s Save current skeleton to output .tgf file."<<endl;
  1033. cout<<"U,u Project then unproject inside mesh (as if dragging each by ε)."<<endl;
  1034. cout<<"Y,Y Symmetrize selection over plane through object centroid and right vector."<<endl;
  1035. cout<<"Z,z Snap to canonical view."<<endl;
  1036. cout<<"⌘ Z Undo."<<endl;
  1037. cout<<"⇧ ⌘ Z Redo."<<endl;
  1038. cout<<"^C,ESC Exit (without saving)."<<endl;
  1039. string dir,_1,_2,name;
  1040. read_triangle_mesh(filename,V,F,dir,_1,_2,name);
  1041. if(output_filename.size() == 0)
  1042. {
  1043. output_filename = dir+"/"+name+".tgf";
  1044. }
  1045. if(file_exists(output_filename.c_str()))
  1046. {
  1047. cout<<YELLOWGIN("Output set to overwrite "<<output_filename)<<endl;
  1048. }else
  1049. {
  1050. cout<<BLUEGIN("Output set to "<<output_filename)<<endl;
  1051. }
  1052. if(skel_filename.length() > 0)
  1053. {
  1054. readTGF(skel_filename,s.C,s.BE);
  1055. }
  1056. init_relative();
  1057. ei.init(V.cast<float>(),F.cast<int>());
  1058. // Init glut
  1059. glutInit(&argc,argv);
  1060. if( !TwInit(TW_OPENGL, NULL) )
  1061. {
  1062. // A fatal error occured
  1063. fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
  1064. return 1;
  1065. }
  1066. // Create a tweak bar
  1067. rebar.TwNewBar("TweakBar");
  1068. rebar.TwAddVarRW("camera_rotation", TW_TYPE_QUAT4D,
  1069. camera.m_rotation_conj.coeffs().data(), "open readonly=true");
  1070. TwType RotationTypeTW = ReTwDefineEnumFromString("RotationType",
  1071. "igl_trackball,two-a...-fixed-up");
  1072. rebar.TwAddVarCB( "rotation_type", RotationTypeTW,
  1073. set_rotation_type,get_rotation_type,NULL,"keyIncr=] keyDecr=[");
  1074. rebar.TwAddVarRW("skeleton_on_top", TW_TYPE_BOOLCPP,&skeleton_on_top,"key=O");
  1075. rebar.TwAddVarRW("wireframe", TW_TYPE_BOOLCPP,&wireframe,"key=l");
  1076. TwType SkelStyleTypeTW = ReTwDefineEnumFromString("SkelStyleType",
  1077. "3d,vector-graphics");
  1078. rebar.TwAddVarRW("style",SkelStyleTypeTW,&skel_style,"");
  1079. rebar.TwAddVarRW("alpha",TW_TYPE_DOUBLE,&alpha,
  1080. "keyIncr=} keyDecr={ min=0 max=1 step=0.1");
  1081. rebar.load(REBAR_NAME);
  1082. // Init antweakbar
  1083. glutInitDisplayString( "rgba depth double samples>=8 ");
  1084. glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT)/2.0);
  1085. glutCreateWindow("skeleton-builder");
  1086. glutDisplayFunc(display);
  1087. glutReshapeFunc(reshape);
  1088. glutKeyboardFunc(key);
  1089. glutMouseFunc(mouse);
  1090. glutMotionFunc(mouse_drag);
  1091. glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
  1092. glutMainLoop();
  1093. return 0;
  1094. }