Viewer.cpp 28 KB

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