Viewer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. // TODO: save_scene()/load_scene()
  9. #include "Viewer.h"
  10. #ifdef _WIN32
  11. # include <windows.h>
  12. # undef max
  13. # undef min
  14. #endif
  15. #include <chrono>
  16. #include <thread>
  17. #ifndef __APPLE__
  18. # define GLEW_STATIC
  19. # include <GL/glew.h>
  20. #endif
  21. #ifdef __APPLE__
  22. # include <OpenGL/gl3.h>
  23. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  24. #else
  25. # include <GL/gl.h>
  26. #endif
  27. #include <Eigen/LU>
  28. #define GLFW_INCLUDE_GLU
  29. #include <GLFW/glfw3.h>
  30. #include <cmath>
  31. #include <cstdio>
  32. #include <sstream>
  33. #include <iomanip>
  34. #include <iostream>
  35. #include <fstream>
  36. #include <algorithm>
  37. #include <limits>
  38. #include <cassert>
  39. #include <igl/project.h>
  40. #include <igl/get_seconds.h>
  41. #include <igl/readOBJ.h>
  42. #include <igl/readOFF.h>
  43. #include <igl/adjacency_list.h>
  44. #include <igl/writeOBJ.h>
  45. #include <igl/writeOFF.h>
  46. #include <igl/massmatrix.h>
  47. #include <igl/file_dialog_open.h>
  48. #include <igl/file_dialog_save.h>
  49. #include <igl/quat_mult.h>
  50. #include <igl/axis_angle_to_quat.h>
  51. #include <igl/trackball.h>
  52. #include <igl/snap_to_canonical_view_quat.h>
  53. #include <igl/unproject.h>
  54. #include <igl/viewer/TextRenderer.h>
  55. #ifdef ENABLE_SERIALIZATION
  56. #include <igl/serialize.h>
  57. #endif
  58. // Internal global variables used for glfw event handling
  59. static igl::Viewer * __viewer;
  60. static double highdpi = 1;
  61. static double scroll_x = 0;
  62. static double scroll_y = 0;
  63. static int global_KMod = 0;
  64. namespace {
  65. void TW_CALL copy_str(std::string& dst, const std::string& src)
  66. {
  67. dst = src;
  68. }
  69. }
  70. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  71. {
  72. bool tw_used = TwEventMouseButtonGLFW(button, action);
  73. igl::Viewer::MouseButton mb;
  74. if (button == GLFW_MOUSE_BUTTON_1)
  75. mb = igl::Viewer::IGL_LEFT;
  76. else if (button == GLFW_MOUSE_BUTTON_2)
  77. mb = igl::Viewer::IGL_RIGHT;
  78. else //if (button == GLFW_MOUSE_BUTTON_3)
  79. mb = igl::Viewer::IGL_MIDDLE;
  80. if (action == GLFW_PRESS)
  81. {
  82. if(!tw_used)
  83. {
  84. __viewer->mouse_down(mb,modifier);
  85. }
  86. } else
  87. {
  88. // Always call mouse_up on up
  89. __viewer->mouse_up(mb,modifier);
  90. }
  91. }
  92. static void glfw_error_callback(int error, const char* description)
  93. {
  94. fputs(description, stderr);
  95. }
  96. IGL_INLINE int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  97. {
  98. int handled = 0;
  99. // Register of modifiers state
  100. if (glfwAction==GLFW_PRESS)
  101. {
  102. switch (glfwKey)
  103. {
  104. case GLFW_KEY_LEFT_SHIFT:
  105. case GLFW_KEY_RIGHT_SHIFT:
  106. global_KMod |= TW_KMOD_SHIFT;
  107. break;
  108. case GLFW_KEY_LEFT_CONTROL:
  109. case GLFW_KEY_RIGHT_CONTROL:
  110. global_KMod |= TW_KMOD_CTRL;
  111. break;
  112. case GLFW_KEY_LEFT_ALT:
  113. case GLFW_KEY_RIGHT_ALT:
  114. global_KMod |= TW_KMOD_ALT;
  115. break;
  116. }
  117. }
  118. else
  119. {
  120. switch (glfwKey)
  121. {
  122. case GLFW_KEY_LEFT_SHIFT:
  123. case GLFW_KEY_RIGHT_SHIFT:
  124. global_KMod &= ~TW_KMOD_SHIFT;
  125. break;
  126. case GLFW_KEY_LEFT_CONTROL:
  127. case GLFW_KEY_RIGHT_CONTROL:
  128. global_KMod &= ~TW_KMOD_CTRL;
  129. break;
  130. case GLFW_KEY_LEFT_ALT:
  131. case GLFW_KEY_RIGHT_ALT:
  132. global_KMod &= ~TW_KMOD_ALT;
  133. break;
  134. }
  135. }
  136. // Process key pressed
  137. if (glfwAction==GLFW_PRESS)
  138. {
  139. int mod = global_KMod;
  140. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  141. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  142. handled = TwKeyPressed(glfwKey, mod);
  143. else if (glfwKey>=GLFW_KEY_ESCAPE )
  144. {
  145. int k = 0;
  146. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  147. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  148. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  149. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  150. else
  151. {
  152. switch (glfwKey)
  153. {
  154. case GLFW_KEY_ESCAPE :
  155. k = TW_KEY_ESCAPE;
  156. break;
  157. case GLFW_KEY_UP:
  158. k = TW_KEY_UP;
  159. break;
  160. case GLFW_KEY_DOWN:
  161. k = TW_KEY_DOWN;
  162. break;
  163. case GLFW_KEY_LEFT:
  164. k = TW_KEY_LEFT;
  165. break;
  166. case GLFW_KEY_RIGHT:
  167. k = TW_KEY_RIGHT;
  168. break;
  169. case GLFW_KEY_TAB:
  170. k = TW_KEY_TAB;
  171. break;
  172. case GLFW_KEY_ENTER:
  173. k = TW_KEY_RETURN;
  174. break;
  175. case GLFW_KEY_BACKSPACE:
  176. k = TW_KEY_BACKSPACE;
  177. break;
  178. case GLFW_KEY_INSERT:
  179. k = TW_KEY_INSERT;
  180. break;
  181. case GLFW_KEY_DELETE:
  182. k = TW_KEY_DELETE;
  183. break;
  184. case GLFW_KEY_PAGE_UP:
  185. k = TW_KEY_PAGE_UP;
  186. break;
  187. case GLFW_KEY_PAGE_DOWN:
  188. k = TW_KEY_PAGE_DOWN;
  189. break;
  190. case GLFW_KEY_HOME:
  191. k = TW_KEY_HOME;
  192. break;
  193. case GLFW_KEY_END:
  194. k = TW_KEY_END;
  195. break;
  196. case GLFW_KEY_KP_ENTER:
  197. k = TW_KEY_RETURN;
  198. break;
  199. case GLFW_KEY_KP_DIVIDE:
  200. if (testkp)
  201. k = '/';
  202. break;
  203. case GLFW_KEY_KP_MULTIPLY:
  204. if (testkp)
  205. k = '*';
  206. break;
  207. case GLFW_KEY_KP_SUBTRACT:
  208. if (testkp)
  209. k = '-';
  210. break;
  211. case GLFW_KEY_KP_ADD:
  212. if (testkp)
  213. k = '+';
  214. break;
  215. case GLFW_KEY_KP_DECIMAL:
  216. if (testkp)
  217. k = '.';
  218. break;
  219. case GLFW_KEY_KP_EQUAL:
  220. if (testkp)
  221. k = '=';
  222. break;
  223. }
  224. }
  225. if (k>0)
  226. handled = TwKeyPressed(k, mod);
  227. }
  228. }
  229. return handled;
  230. }
  231. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  232. {
  233. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  234. glfwSetWindowShouldClose(window, GL_TRUE);
  235. if (!TwEventKeyGLFW3(key,action))
  236. {
  237. if (action == GLFW_PRESS)
  238. __viewer->key_down(key, modifier);
  239. else
  240. __viewer->key_up(key, modifier);
  241. }
  242. }
  243. static void glfw_window_size(GLFWwindow* window, int width, int height)
  244. {
  245. int w = width*highdpi;
  246. int h = height*highdpi;
  247. __viewer->resize(w, h);
  248. TwWindowSize(w, h);
  249. const auto & bar = __viewer->bar;
  250. // Keep AntTweakBar on right side of screen and height == opengl height
  251. // get the current position of a bar
  252. int size[2];
  253. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  254. int pos[2];
  255. // Place bar on left side of opengl rect (padded by 10 pixels)
  256. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  257. // place bar at top (padded by 10 pixels)
  258. pos[1] = 10;
  259. // Set height to new height of window (padded by 10 pixels on bottom)
  260. size[1] = highdpi*(height-pos[1]-10);
  261. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  262. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  263. }
  264. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  265. {
  266. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  267. {
  268. // Call if TwBar hasn't used or if down
  269. __viewer->mouse_move(x*highdpi, y*highdpi);
  270. }
  271. }
  272. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  273. {
  274. using namespace std;
  275. scroll_x += x;
  276. scroll_y += y;
  277. if (!TwEventMouseWheelGLFW(scroll_y))
  278. __viewer->mouse_scroll(y);
  279. }
  280. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  281. {
  282. if ((c & 0xff00)==0)
  283. TwKeyPressed(c, global_KMod);
  284. }
  285. namespace igl
  286. {
  287. IGL_INLINE void Viewer::init()
  288. {
  289. // Create a tweak bar
  290. bar = TwNewBar("libIGL-Viewer");
  291. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  292. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  293. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  294. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  295. // ---------------------- LOADING ----------------------
  296. #ifdef ENABLE_SERIALIZATION
  297. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  298. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  299. #endif
  300. #ifdef ENABLE_IO
  301. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  302. #endif
  303. // ---------------------- SCENE ----------------------
  304. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  305. " group='Viewing Options'"
  306. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  307. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(core.camera_zoom),
  308. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  309. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  310. " group='Scene'"
  311. " label='Snap to canonical view' key=Z "
  312. " help='Snaps view to nearest canonical view.'");
  313. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, core.light_position.data(),
  314. " group='Scene'"
  315. " label='Light direction' open help='Change the light direction.' ");
  316. // ---------------------- DRAW OPTIONS ----------------------
  317. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(core.orthographic),
  318. " group='Viewing Options'"
  319. " label='Orthographic view' "
  320. " help='Toggles orthographic / perspective view. Default: perspective.'");
  321. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(core.trackball_angle),
  322. " group='Viewing Options'"
  323. " label='Rotation'"
  324. " help='Rotates view.'");
  325. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  326. " group='Draw options'"
  327. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  328. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(core.show_texture),
  329. " group='Draw options'");
  330. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  331. " group='Draw options'"
  332. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  333. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(core.show_overlay),
  334. " group='Draw options'"
  335. " label='Show overlay' key=o help='Show the overlay layers.' ");
  336. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(core.show_overlay_depth),
  337. " group='Draw options'"
  338. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  339. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  340. core.background_color.data(),
  341. " help='Select a background color' colormode=hls group='Draw options'");
  342. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  343. core.line_color.data(),
  344. " label='Line color' help='Select a outline color' group='Draw options'");
  345. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&core.shininess," group='Draw options'"
  346. " min=1 max=128");
  347. // ---------------------- Overlays ----------------------
  348. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(core.show_lines),
  349. " group='Overlays'"
  350. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  351. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(core.show_faces),
  352. " group='Overlays'"
  353. " label='Fill' key=t help='Display filled polygons of mesh'");
  354. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(core.show_vertid),
  355. " group='Overlays'"
  356. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  357. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(core.show_faceid),
  358. " group='Overlays'"
  359. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  360. " indices'");
  361. core.init();
  362. if (callback_init)
  363. if (callback_init(*this))
  364. return;
  365. init_plugins();
  366. }
  367. IGL_INLINE Viewer::Viewer()
  368. {
  369. // Temporary variables initialization
  370. down = false;
  371. hack_never_moved = true;
  372. scroll_position = 0.0f;
  373. // Per face
  374. data.set_face_based(false);
  375. callback_init_data = 0;
  376. callback_pre_draw_data = 0;
  377. callback_post_draw_data = 0;
  378. callback_mouse_down_data = 0;
  379. callback_mouse_up_data = 0;
  380. callback_mouse_move_data = 0;
  381. callback_mouse_scroll_data = 0;
  382. callback_key_down_data = 0;
  383. callback_key_up_data = 0;
  384. }
  385. IGL_INLINE void Viewer::init_plugins()
  386. {
  387. // Init all plugins
  388. for (unsigned int i = 0; i<plugins.size(); ++i)
  389. plugins[i]->init(this);
  390. }
  391. IGL_INLINE Viewer::~Viewer()
  392. {
  393. }
  394. IGL_INLINE void Viewer::shutdown_plugins()
  395. {
  396. for (unsigned int i = 0; i<plugins.size(); ++i)
  397. plugins[i]->shutdown();
  398. }
  399. IGL_INLINE bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  400. {
  401. std::string mesh_file_name_string = std::string(mesh_file_name);
  402. // first try to load it with a plugin
  403. for (unsigned int i = 0; i<plugins.size(); ++i)
  404. {
  405. if (plugins[i]->load(mesh_file_name_string))
  406. {
  407. return true;
  408. }
  409. }
  410. data.clear();
  411. size_t last_dot = mesh_file_name_string.rfind('.');
  412. if (last_dot == std::string::npos)
  413. {
  414. printf("Error: No file extension found in %s\n",mesh_file_name);
  415. return false;
  416. }
  417. std::string extension = mesh_file_name_string.substr(last_dot+1);
  418. if (extension == "off" || extension =="OFF")
  419. {
  420. Eigen::MatrixXd V;
  421. Eigen::MatrixXi F;
  422. if (!igl::readOFF(mesh_file_name_string, V, F))
  423. return false;
  424. data.set_mesh(V,F);
  425. }
  426. else if (extension == "obj" || extension =="OBJ")
  427. {
  428. Eigen::MatrixXd corner_normals;
  429. Eigen::MatrixXi fNormIndices;
  430. Eigen::MatrixXd UV_V;
  431. Eigen::MatrixXi UV_F;
  432. Eigen::MatrixXd V;
  433. Eigen::MatrixXi F;
  434. if (!(igl::readOBJ(mesh_file_name_string, V, F, corner_normals, fNormIndices, UV_V, UV_F)))
  435. return false;
  436. data.set_mesh(V,F);
  437. data.set_uv(UV_V,UV_F);
  438. }
  439. else
  440. {
  441. // unrecognized file type
  442. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  443. return false;
  444. }
  445. data.compute_normals();
  446. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  447. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  448. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  449. if (data.V_uv.rows() == 0)
  450. data.grid_texture();
  451. core.align_camera_center(data.V,data.F);
  452. for (unsigned int i = 0; i<plugins.size(); ++i)
  453. if (plugins[i]->post_load())
  454. return true;
  455. return true;
  456. }
  457. IGL_INLINE bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  458. {
  459. std::string mesh_file_name_string(mesh_file_name);
  460. // first try to load it with a plugin
  461. for (unsigned int i = 0; i<plugins.size(); ++i)
  462. if (plugins[i]->save(mesh_file_name_string))
  463. return true;
  464. size_t last_dot = mesh_file_name_string.rfind('.');
  465. if (last_dot == std::string::npos)
  466. {
  467. // No file type determined
  468. printf("Error: No file extension found in %s\n",mesh_file_name);
  469. return false;
  470. }
  471. std::string extension = mesh_file_name_string.substr(last_dot+1);
  472. if (extension == "off" || extension =="OFF")
  473. {
  474. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  475. }
  476. else if (extension == "obj" || extension =="OBJ")
  477. {
  478. Eigen::MatrixXd corner_normals;
  479. Eigen::MatrixXi fNormIndices;
  480. Eigen::MatrixXd UV_V;
  481. Eigen::MatrixXi UV_F;
  482. return igl::writeOBJ(mesh_file_name_string, data.V,
  483. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  484. }
  485. else
  486. {
  487. // unrecognized file type
  488. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  489. return false;
  490. }
  491. return true;
  492. }
  493. IGL_INLINE bool Viewer::key_down(int key,int modifiers)
  494. {
  495. if (callback_key_down)
  496. if (callback_key_down(*this,key,modifiers))
  497. return true;
  498. for (unsigned int i = 0; i<plugins.size(); ++i)
  499. if (plugins[i]->key_down(key, modifiers))
  500. return true;
  501. char k = key;
  502. if(key == GLFW_KEY_S && modifiers == GLFW_MOD_SHIFT)
  503. mouse_scroll(1);
  504. if(key == GLFW_KEY_A && modifiers == GLFW_MOD_SHIFT)
  505. mouse_scroll(-1);
  506. // Why aren't these handled via AntTweakBar?
  507. if(key == GLFW_KEY_Z) // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  508. core.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  509. if(key == GLFW_KEY_Y)
  510. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  511. if(key == GLFW_KEY_X)
  512. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  513. return false;
  514. }
  515. IGL_INLINE bool Viewer::key_up(int key,int modifiers)
  516. {
  517. if (callback_key_up)
  518. if (callback_key_up(*this,key,modifiers))
  519. return true;
  520. for (unsigned int i = 0; i<plugins.size(); ++i)
  521. if (plugins[i]->key_up(key, modifiers))
  522. return true;
  523. return false;
  524. }
  525. IGL_INLINE bool Viewer::mouse_down(MouseButton button,int modifier)
  526. {
  527. if (callback_mouse_down)
  528. if (callback_mouse_down(*this,button,modifier))
  529. return true;
  530. for (unsigned int i = 0; i<plugins.size(); ++i)
  531. if (plugins[i]->mouse_down(button,modifier))
  532. return true;
  533. down = true;
  534. down_mouse_x = current_mouse_x;
  535. down_mouse_y = current_mouse_y;
  536. down_translation = core.model_translation;
  537. // Initialization code for the trackball
  538. Eigen::RowVector3d center;
  539. if (data.V.rows() == 0)
  540. center << 0,0,0;
  541. else
  542. center = data.V.colwise().sum()/data.V.rows();
  543. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), (core.view * core.model).eval(), core.proj, core.viewport);
  544. down_mouse_z = coord[2];
  545. down_rotation = core.trackball_angle;
  546. mouse_mode = ROTATION;
  547. switch (button)
  548. {
  549. case IGL_LEFT:
  550. mouse_mode = ROTATION;
  551. break;
  552. case IGL_RIGHT:
  553. mouse_mode = TRANSLATE;
  554. break;
  555. default:
  556. mouse_mode = NOTHING;
  557. break;
  558. }
  559. return true;
  560. }
  561. IGL_INLINE bool Viewer::mouse_up(MouseButton button,int modifier)
  562. {
  563. down = false;
  564. if (callback_mouse_up)
  565. if (callback_mouse_up(*this,button,modifier))
  566. return true;
  567. for (unsigned int i = 0; i<plugins.size(); ++i)
  568. if (plugins[i]->mouse_up(button,modifier))
  569. return true;
  570. mouse_mode = NOTHING;
  571. return true;
  572. }
  573. IGL_INLINE bool Viewer::mouse_move(int mouse_x,int mouse_y)
  574. {
  575. if(hack_never_moved)
  576. {
  577. down_mouse_x = mouse_x;
  578. down_mouse_y = mouse_y;
  579. hack_never_moved = false;
  580. }
  581. current_mouse_x = mouse_x;
  582. current_mouse_y = mouse_y;
  583. if (callback_mouse_move)
  584. if (callback_mouse_move(*this,mouse_x,mouse_y))
  585. return true;
  586. for (unsigned int i = 0; i<plugins.size(); ++i)
  587. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  588. return true;
  589. if (down)
  590. {
  591. switch (mouse_mode)
  592. {
  593. case ROTATION :
  594. {
  595. igl::trackball(core.viewport(2),
  596. core.viewport(3),
  597. 2.0f,
  598. down_rotation.data(),
  599. down_mouse_x,
  600. down_mouse_y,
  601. mouse_x,
  602. mouse_y,
  603. core.trackball_angle.data());
  604. //Eigen::Vector4f snapq = core.trackball_angle;
  605. break;
  606. }
  607. case TRANSLATE:
  608. {
  609. //translation
  610. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, core.viewport[3] - mouse_y, down_mouse_z), (core.view * core.model).eval(), core.proj, core.viewport);
  611. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, core.viewport[3] - down_mouse_y, down_mouse_z), (core.view * core.model).eval(), core.proj, core.viewport);
  612. Eigen::Vector3f diff = pos1 - pos0;
  613. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  614. break;
  615. }
  616. case ZOOM:
  617. {
  618. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  619. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  620. core.camera_zoom *= 1 + delta;
  621. down_mouse_x = mouse_x;
  622. down_mouse_y = mouse_y;
  623. break;
  624. }
  625. default:
  626. break;
  627. }
  628. }
  629. return true;
  630. }
  631. IGL_INLINE bool Viewer::mouse_scroll(float delta_y)
  632. {
  633. scroll_position += delta_y;
  634. if (callback_mouse_scroll)
  635. if (callback_mouse_scroll(*this,delta_y))
  636. return true;
  637. for (unsigned int i = 0; i<plugins.size(); ++i)
  638. if (plugins[i]->mouse_scroll(delta_y))
  639. return true;
  640. // Only zoom if there's actually a change
  641. if(delta_y != 0)
  642. {
  643. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  644. const float min_zoom = 0.1f;
  645. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  646. }
  647. return true;
  648. }
  649. IGL_INLINE void Viewer::draw()
  650. {
  651. using namespace std;
  652. using namespace Eigen;
  653. core.clear_framebuffers();
  654. if (callback_pre_draw)
  655. if (callback_pre_draw(*this))
  656. return;
  657. for (unsigned int i = 0; i<plugins.size(); ++i)
  658. if (plugins[i]->pre_draw())
  659. return;
  660. core.draw(data,opengl);
  661. if (callback_post_draw)
  662. if (callback_post_draw(*this))
  663. return;
  664. for (unsigned int i = 0; i<plugins.size(); ++i)
  665. if (plugins[i]->post_draw())
  666. break;
  667. TwDraw();
  668. }
  669. IGL_INLINE bool Viewer::save_scene()
  670. {
  671. std::string fname = igl::file_dialog_save();
  672. if (fname.length() == 0)
  673. return false;
  674. #ifdef ENABLE_SERIALIZATION
  675. igl::serialize(core,"Core",fname.c_str(),true);
  676. igl::serialize(data,"Data",fname.c_str());
  677. for(unsigned int i = 0; i <plugins.size(); ++i)
  678. igl::serialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  679. #endif
  680. return true;
  681. }
  682. IGL_INLINE bool Viewer::load_scene()
  683. {
  684. std::string fname = igl::file_dialog_open();
  685. if (fname.length() == 0)
  686. return false;
  687. #ifdef ENABLE_SERIALIZATION
  688. igl::deserialize(core,"Core",fname.c_str());
  689. igl::deserialize(data,"Data",fname.c_str());
  690. for(unsigned int i = 0; i <plugins.size(); ++i)
  691. igl::deserialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  692. #endif
  693. return true;
  694. }
  695. IGL_INLINE void Viewer::resize(int w,int h)
  696. {
  697. core.viewport = Eigen::Vector4f(0,0,w,h);
  698. }
  699. IGL_INLINE void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  700. {
  701. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->core.trackball_angle;
  702. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->core.trackball_angle.data());
  703. }
  704. IGL_INLINE void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  705. {
  706. static_cast<Viewer *>(clientData)->core.align_camera_center(
  707. static_cast<Viewer *>(clientData)->data.V,
  708. static_cast<Viewer *>(clientData)->data.F);
  709. }
  710. IGL_INLINE void TW_CALL Viewer::save_scene_cb(void *clientData)
  711. {
  712. static_cast<Viewer *>(clientData)->save_scene();
  713. }
  714. IGL_INLINE void TW_CALL Viewer::load_scene_cb(void *clientData)
  715. {
  716. static_cast<Viewer *>(clientData)->load_scene();
  717. }
  718. IGL_INLINE void TW_CALL Viewer::set_invert_normals_cb(const void *param,void *clientData)
  719. {
  720. Viewer *viewer = static_cast<Viewer *>(clientData);
  721. viewer->data.dirty |= ViewerData::DIRTY_NORMAL;
  722. viewer->core.invert_normals = *((bool *) param);
  723. }
  724. IGL_INLINE void TW_CALL Viewer::get_invert_normals_cb(void *param,void *clientData)
  725. {
  726. *((bool *) param) = static_cast<Viewer *>(clientData)->core.invert_normals;
  727. }
  728. IGL_INLINE void TW_CALL Viewer::set_face_based_cb(const void *param,void *clientData)
  729. {
  730. Viewer *viewer = static_cast<Viewer *>(clientData);
  731. viewer->data.set_face_based(*((bool *) param));
  732. }
  733. IGL_INLINE void TW_CALL Viewer::get_face_based_cb(void *param,void *clientData)
  734. {
  735. *((bool *) param) = static_cast<Viewer *>(clientData)->data.face_based;
  736. }
  737. IGL_INLINE void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  738. {
  739. std::string fname = igl::file_dialog_open();
  740. if (fname.length() == 0)
  741. return;
  742. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  743. }
  744. IGL_INLINE int Viewer::launch(std::string filename)
  745. {
  746. GLFWwindow* window;
  747. glfwSetErrorCallback(glfw_error_callback);
  748. if (!glfwInit())
  749. return EXIT_FAILURE;
  750. glfwWindowHint(GLFW_SAMPLES, 4);
  751. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  752. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  753. #ifdef __APPLE__
  754. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  755. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  756. #endif
  757. window = glfwCreateWindow(1280, 800, "libigl viewer", NULL, NULL);
  758. if (!window)
  759. {
  760. glfwTerminate();
  761. return EXIT_FAILURE;
  762. }
  763. glfwMakeContextCurrent(window);
  764. #ifndef __APPLE__
  765. glewExperimental = true;
  766. GLenum err = glewInit();
  767. if (GLEW_OK != err)
  768. {
  769. /* Problem: glewInit failed, something is seriously wrong. */
  770. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  771. }
  772. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  773. #endif
  774. #ifdef DEBUG
  775. int major, minor, rev;
  776. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  777. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  778. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  779. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  780. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  781. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  782. #endif
  783. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  784. // Initialize AntTweakBar
  785. TwInit(TW_OPENGL_CORE, NULL);
  786. TwCopyStdStringToClientFunc(static_cast<TwCopyStdStringToClient>(::copy_str));
  787. // Initialize IGL viewer
  788. init();
  789. __viewer = this;
  790. // Register callbacks
  791. glfwSetKeyCallback(window, glfw_key_callback);
  792. glfwSetCursorPosCallback(window,glfw_mouse_move);
  793. glfwSetWindowSizeCallback(window,glfw_window_size);
  794. glfwSetMouseButtonCallback(window,glfw_mouse_press);
  795. glfwSetScrollCallback(window,glfw_mouse_scroll);
  796. glfwSetCharCallback(window, glfw_char_callback);
  797. // Handle retina displays (windows and mac)
  798. int width, height;
  799. glfwGetFramebufferSize(window, &width, &height);
  800. int width_window, height_window;
  801. glfwGetWindowSize(window, &width_window, &height_window);
  802. highdpi = width/width_window;
  803. glfw_window_size(window,width_window,height_window);
  804. opengl.init();
  805. // Alec: It seems silly to overload launch to take a filename as an
  806. // argument. load_mesh_from_file has many side effects so it makes
  807. // debugging launch difficult.
  808. // Load the mesh passed as input
  809. if (filename.size() > 0)
  810. {
  811. load_mesh_from_file(filename.c_str());
  812. }
  813. core.align_camera_center(data.V,data.F);
  814. // Rendering loop
  815. while (!glfwWindowShouldClose(window))
  816. {
  817. double tic = get_seconds();
  818. draw();
  819. glfwSwapBuffers(window);
  820. if(core.is_animating)
  821. {
  822. glfwPollEvents();
  823. // In microseconds
  824. double duration = 1000000.*(get_seconds()-tic);
  825. const double min_duration = 1000000./core.animation_max_fps;
  826. if(duration<min_duration)
  827. {
  828. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  829. }
  830. }
  831. else
  832. {
  833. glfwWaitEvents();
  834. }
  835. }
  836. opengl.free();
  837. core.shut();
  838. shutdown_plugins();
  839. glfwDestroyWindow(window);
  840. glfwTerminate();
  841. return EXIT_SUCCESS;
  842. }
  843. } // end namespace