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. #include <igl/get_seconds.h>
  11. #ifdef _WIN32
  12. # include <windows.h>
  13. # undef max
  14. # undef min
  15. #endif
  16. #include <chrono>
  17. #include <thread>
  18. #ifndef __APPLE__
  19. # define GLEW_STATIC
  20. # include <GL/glew.h>
  21. #endif
  22. #ifdef __APPLE__
  23. # include <OpenGL/gl3.h>
  24. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  25. #else
  26. # include <GL/gl.h>
  27. #endif
  28. #include <Eigen/LU>
  29. #define GLFW_INCLUDE_GLU
  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 <igl/project.h>
  39. #include <limits>
  40. #include <cassert>
  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. // Internal global variables used for glfw event handling
  56. static igl::Viewer * __viewer;
  57. static double highdpi = 1;
  58. static double scroll_x = 0;
  59. static double scroll_y = 0;
  60. namespace {
  61. void TW_CALL copy_str(std::string& dst, const std::string& src)
  62. {
  63. dst = src;
  64. }
  65. }
  66. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  67. {
  68. bool tw_used = TwEventMouseButtonGLFW(button, action);
  69. igl::Viewer::MouseButton mb;
  70. if (button == GLFW_MOUSE_BUTTON_1)
  71. mb = igl::Viewer::IGL_LEFT;
  72. else if (button == GLFW_MOUSE_BUTTON_2)
  73. mb = igl::Viewer::IGL_RIGHT;
  74. else //if (button == GLFW_MOUSE_BUTTON_3)
  75. mb = igl::Viewer::IGL_MIDDLE;
  76. if (action == GLFW_PRESS)
  77. {
  78. if(!tw_used)
  79. {
  80. __viewer->mouse_down(mb,modifier);
  81. }
  82. } else
  83. {
  84. // Always call mouse_up on up
  85. __viewer->mouse_up(mb,modifier);
  86. }
  87. }
  88. static void glfw_error_callback(int error, const char* description)
  89. {
  90. fputs(description, stderr);
  91. }
  92. int global_KMod = 0;
  93. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  94. {
  95. int handled = 0;
  96. // Register of modifiers state
  97. if (glfwAction==GLFW_PRESS)
  98. {
  99. switch (glfwKey)
  100. {
  101. case GLFW_KEY_LEFT_SHIFT:
  102. case GLFW_KEY_RIGHT_SHIFT:
  103. global_KMod |= TW_KMOD_SHIFT;
  104. break;
  105. case GLFW_KEY_LEFT_CONTROL:
  106. case GLFW_KEY_RIGHT_CONTROL:
  107. global_KMod |= TW_KMOD_CTRL;
  108. break;
  109. case GLFW_KEY_LEFT_ALT:
  110. case GLFW_KEY_RIGHT_ALT:
  111. global_KMod |= TW_KMOD_ALT;
  112. break;
  113. }
  114. }
  115. else
  116. {
  117. switch (glfwKey)
  118. {
  119. case GLFW_KEY_LEFT_SHIFT:
  120. case GLFW_KEY_RIGHT_SHIFT:
  121. global_KMod &= ~TW_KMOD_SHIFT;
  122. break;
  123. case GLFW_KEY_LEFT_CONTROL:
  124. case GLFW_KEY_RIGHT_CONTROL:
  125. global_KMod &= ~TW_KMOD_CTRL;
  126. break;
  127. case GLFW_KEY_LEFT_ALT:
  128. case GLFW_KEY_RIGHT_ALT:
  129. global_KMod &= ~TW_KMOD_ALT;
  130. break;
  131. }
  132. }
  133. // Process key pressed
  134. if (glfwAction==GLFW_PRESS)
  135. {
  136. int mod = global_KMod;
  137. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  138. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  139. handled = TwKeyPressed(glfwKey, mod);
  140. else if (glfwKey>=GLFW_KEY_ESCAPE )
  141. {
  142. int k = 0;
  143. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  144. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  145. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  146. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  147. else
  148. {
  149. switch (glfwKey)
  150. {
  151. case GLFW_KEY_ESCAPE :
  152. k = TW_KEY_ESCAPE;
  153. break;
  154. case GLFW_KEY_UP:
  155. k = TW_KEY_UP;
  156. break;
  157. case GLFW_KEY_DOWN:
  158. k = TW_KEY_DOWN;
  159. break;
  160. case GLFW_KEY_LEFT:
  161. k = TW_KEY_LEFT;
  162. break;
  163. case GLFW_KEY_RIGHT:
  164. k = TW_KEY_RIGHT;
  165. break;
  166. case GLFW_KEY_TAB:
  167. k = TW_KEY_TAB;
  168. break;
  169. case GLFW_KEY_ENTER:
  170. k = TW_KEY_RETURN;
  171. break;
  172. case GLFW_KEY_BACKSPACE:
  173. k = TW_KEY_BACKSPACE;
  174. break;
  175. case GLFW_KEY_INSERT:
  176. k = TW_KEY_INSERT;
  177. break;
  178. case GLFW_KEY_DELETE:
  179. k = TW_KEY_DELETE;
  180. break;
  181. case GLFW_KEY_PAGE_UP:
  182. k = TW_KEY_PAGE_UP;
  183. break;
  184. case GLFW_KEY_PAGE_DOWN:
  185. k = TW_KEY_PAGE_DOWN;
  186. break;
  187. case GLFW_KEY_HOME:
  188. k = TW_KEY_HOME;
  189. break;
  190. case GLFW_KEY_END:
  191. k = TW_KEY_END;
  192. break;
  193. case GLFW_KEY_KP_ENTER:
  194. k = TW_KEY_RETURN;
  195. break;
  196. case GLFW_KEY_KP_DIVIDE:
  197. if (testkp)
  198. k = '/';
  199. break;
  200. case GLFW_KEY_KP_MULTIPLY:
  201. if (testkp)
  202. k = '*';
  203. break;
  204. case GLFW_KEY_KP_SUBTRACT:
  205. if (testkp)
  206. k = '-';
  207. break;
  208. case GLFW_KEY_KP_ADD:
  209. if (testkp)
  210. k = '+';
  211. break;
  212. case GLFW_KEY_KP_DECIMAL:
  213. if (testkp)
  214. k = '.';
  215. break;
  216. case GLFW_KEY_KP_EQUAL:
  217. if (testkp)
  218. k = '=';
  219. break;
  220. }
  221. }
  222. if (k>0)
  223. handled = TwKeyPressed(k, mod);
  224. }
  225. }
  226. return handled;
  227. }
  228. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  229. {
  230. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  231. glfwSetWindowShouldClose(window, GL_TRUE);
  232. if (!TwEventKeyGLFW3(key,action))
  233. {
  234. if (action == GLFW_PRESS)
  235. __viewer->key_down(key, modifier);
  236. else
  237. __viewer->key_up(key, modifier);
  238. }
  239. }
  240. static void glfw_window_size(GLFWwindow* window, int width, int height)
  241. {
  242. int w = width*highdpi;
  243. int h = height*highdpi;
  244. __viewer->resize(w, h);
  245. TwWindowSize(w, h);
  246. const auto & bar = __viewer->bar;
  247. // Keep AntTweakBar on right side of screen and height == opengl height
  248. // get the current position of a bar
  249. int size[2];
  250. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  251. int pos[2];
  252. // Place bar on left side of opengl rect (padded by 10 pixels)
  253. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  254. // place bar at top (padded by 10 pixels)
  255. pos[1] = 10;
  256. // Set height to new height of window (padded by 10 pixels on bottom)
  257. size[1] = highdpi*(height-pos[1]-10);
  258. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  259. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  260. }
  261. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  262. {
  263. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  264. {
  265. // Call if TwBar hasn't used or if down
  266. __viewer->mouse_move(x*highdpi, y*highdpi);
  267. }
  268. }
  269. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  270. {
  271. using namespace std;
  272. scroll_x += x;
  273. scroll_y += y;
  274. if (!TwEventMouseWheelGLFW(scroll_y))
  275. __viewer->mouse_scroll(y);
  276. }
  277. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  278. {
  279. if ((c & 0xff00)==0)
  280. TwKeyPressed(c, global_KMod);
  281. }
  282. namespace igl
  283. {
  284. void Viewer::init()
  285. {
  286. // Create a tweak bar
  287. bar = TwNewBar("libIGL-Viewer");
  288. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  289. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  290. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  291. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  292. // ---------------------- LOADING ----------------------
  293. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  294. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  295. #ifdef ENABLE_IO
  296. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  297. #endif
  298. // ---------------------- SCENE ----------------------
  299. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  300. " group='Viewing Options'"
  301. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  302. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(core.camera_zoom),
  303. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  304. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  305. " group='Scene'"
  306. " label='Snap to canonical view' key=Z "
  307. " help='Snaps view to nearest canonical view.'");
  308. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, core.light_position.data(),
  309. " group='Scene'"
  310. " label='Light direction' open help='Change the light direction.' ");
  311. // ---------------------- DRAW OPTIONS ----------------------
  312. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(core.orthographic),
  313. " group='Viewing Options'"
  314. " label='Orthographic view' "
  315. " help='Toggles orthographic / perspective view. Default: perspective.'");
  316. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(core.trackball_angle),
  317. " group='Viewing Options'"
  318. " label='Rotation'"
  319. " help='Rotates view.'");
  320. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  321. " group='Draw options'"
  322. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  323. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(core.show_texture),
  324. " group='Draw options'");
  325. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  326. " group='Draw options'"
  327. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  328. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(core.show_overlay),
  329. " group='Draw options'"
  330. " label='Show overlay' key=o help='Show the overlay layers.' ");
  331. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(core.show_overlay_depth),
  332. " group='Draw options'"
  333. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  334. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  335. core.background_color.data(),
  336. " help='Select a background color' colormode=hls group='Draw options'");
  337. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  338. core.line_color.data(),
  339. " label='Line color' help='Select a outline color' group='Draw options'");
  340. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&core.shininess," group='Draw options'"
  341. " min=1 max=128");
  342. // ---------------------- Overlays ----------------------
  343. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(core.show_lines),
  344. " group='Overlays'"
  345. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  346. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(core.show_faces),
  347. " group='Overlays'"
  348. " label='Fill' key=t help='Display filled polygons of mesh'");
  349. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(core.show_vertid),
  350. " group='Overlays'"
  351. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  352. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(core.show_faceid),
  353. " group='Overlays'"
  354. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  355. " indices'");
  356. core.init();
  357. if (callback_init)
  358. if (callback_init(*this))
  359. return;
  360. init_plugins();
  361. }
  362. Viewer::Viewer()
  363. {
  364. // Temporary variables initialization
  365. down = false;
  366. hack_never_moved = true;
  367. scroll_position = 0.0f;
  368. // Per face
  369. data.set_face_based(false);
  370. // C-style callbacks
  371. callback_init = 0;
  372. callback_pre_draw = 0;
  373. callback_post_draw = 0;
  374. callback_mouse_down = 0;
  375. callback_mouse_up = 0;
  376. callback_mouse_move = 0;
  377. callback_mouse_scroll = 0;
  378. callback_key_down = 0;
  379. callback_key_up = 0;
  380. callback_init_data = 0;
  381. callback_pre_draw_data = 0;
  382. callback_post_draw_data = 0;
  383. callback_mouse_down_data = 0;
  384. callback_mouse_up_data = 0;
  385. callback_mouse_move_data = 0;
  386. callback_mouse_scroll_data = 0;
  387. callback_key_down_data = 0;
  388. callback_key_up_data = 0;
  389. }
  390. void Viewer::init_plugins()
  391. {
  392. // Init all plugins
  393. for (unsigned int i = 0; i<plugins.size(); ++i)
  394. plugins[i]->init(this);
  395. }
  396. Viewer::~Viewer()
  397. {
  398. }
  399. void Viewer::shutdown_plugins()
  400. {
  401. for (unsigned int i = 0; i<plugins.size(); ++i)
  402. plugins[i]->shutdown();
  403. }
  404. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  405. {
  406. std::string mesh_file_name_string = std::string(mesh_file_name);
  407. // first try to load it with a plugin
  408. for (unsigned int i = 0; i<plugins.size(); ++i)
  409. if (plugins[i]->load(mesh_file_name_string))
  410. return true;
  411. data.clear();
  412. size_t last_dot = mesh_file_name_string.rfind('.');
  413. if (last_dot == std::string::npos)
  414. {
  415. printf("Error: No file extension found in %s\n",mesh_file_name);
  416. return false;
  417. }
  418. std::string extension = mesh_file_name_string.substr(last_dot+1);
  419. if (extension == "off" || extension =="OFF")
  420. {
  421. Eigen::MatrixXd V;
  422. Eigen::MatrixXi F;
  423. if (!igl::readOFF(mesh_file_name_string, V, F))
  424. return false;
  425. data.set_mesh(V,F);
  426. }
  427. else if (extension == "obj" || extension =="OBJ")
  428. {
  429. Eigen::MatrixXd corner_normals;
  430. Eigen::MatrixXi fNormIndices;
  431. Eigen::MatrixXd UV_V;
  432. Eigen::MatrixXi UV_F;
  433. Eigen::MatrixXd V;
  434. Eigen::MatrixXi F;
  435. if (!(igl::readOBJ(mesh_file_name_string, V, F, corner_normals, fNormIndices, UV_V, UV_F)))
  436. return false;
  437. data.set_mesh(V,F);
  438. data.set_uv(UV_V,UV_F);
  439. }
  440. else
  441. {
  442. // unrecognized file type
  443. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  444. return false;
  445. }
  446. data.compute_normals();
  447. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  448. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  449. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  450. if (data.V_uv.rows() == 0)
  451. data.grid_texture();
  452. core.align_camera_center(data.V,data.F);
  453. for (unsigned int i = 0; i<plugins.size(); ++i)
  454. if (plugins[i]->post_load())
  455. return true;
  456. return true;
  457. }
  458. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  459. {
  460. std::string mesh_file_name_string(mesh_file_name);
  461. // first try to load it with a plugin
  462. for (unsigned int i = 0; i<plugins.size(); ++i)
  463. if (plugins[i]->save(mesh_file_name_string))
  464. return true;
  465. size_t last_dot = mesh_file_name_string.rfind('.');
  466. if (last_dot == std::string::npos)
  467. {
  468. // No file type determined
  469. printf("Error: No file extension found in %s\n",mesh_file_name);
  470. return false;
  471. }
  472. std::string extension = mesh_file_name_string.substr(last_dot+1);
  473. if (extension == "off" || extension =="OFF")
  474. {
  475. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  476. }
  477. else if (extension == "obj" || extension =="OBJ")
  478. {
  479. Eigen::MatrixXd corner_normals;
  480. Eigen::MatrixXi fNormIndices;
  481. Eigen::MatrixXd UV_V;
  482. Eigen::MatrixXi UV_F;
  483. return igl::writeOBJ(mesh_file_name_string, data.V,
  484. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  485. }
  486. else
  487. {
  488. // unrecognized file type
  489. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  490. return false;
  491. }
  492. return true;
  493. }
  494. bool Viewer::key_down(unsigned char key, int modifiers)
  495. {
  496. if (callback_key_down)
  497. if (callback_key_down(*this,key,modifiers))
  498. return true;
  499. for (unsigned int i = 0; i<plugins.size(); ++i)
  500. if (plugins[i]->key_down(key, modifiers))
  501. return true;
  502. if (key == 'S')
  503. mouse_scroll(1);
  504. if (key == 'A')
  505. mouse_scroll(-1);
  506. // Why aren't these handled via AntTweakBar?
  507. if (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 == 'y')
  510. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  511. if (key == 'x')
  512. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  513. return false;
  514. }
  515. bool Viewer::key_up(unsigned char 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. 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, 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. 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. 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, 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, 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. 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. 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. bool Viewer::save_scene()
  670. {
  671. std::string fname = igl::file_dialog_save();
  672. if (fname.length() == 0)
  673. return false;
  674. #ifdef ENABLE_XML_SERIALIZATION
  675. igl::serialize_xml(core,"Core",fname.c_str(),false,false);
  676. igl::serialize_xml(data,"Data",fname.c_str(),false,true);
  677. for(unsigned int i = 0; i <plugins.size(); ++i)
  678. igl::serialize_xml(*plugins[i],plugins[i]->plugin_name,fname.c_str(),false,true);
  679. #else
  680. igl::serialize(core,"Core",fname.c_str(),false);
  681. igl::serialize(data,"Data",fname.c_str(),true);
  682. for(unsigned int i = 0; i <plugins.size(); ++i)
  683. igl::serialize(*plugins[i],plugins[i]->plugin_name,fname.c_str(),true);
  684. #endif
  685. return true;
  686. }
  687. bool Viewer::load_scene()
  688. {
  689. std::string fname = igl::file_dialog_open();
  690. if (fname.length() == 0)
  691. return false;
  692. #ifdef ENABLE_XML_SERIALIZATION
  693. igl::deserialize_xml(core,"Core",fname.c_str());
  694. igl::deserialize_xml(data,"Data",fname.c_str());
  695. for(unsigned int i = 0; i <plugins.size(); ++i)
  696. igl::deserialize_xml(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  697. #else
  698. igl::deserialize(core,"Core",fname.c_str());
  699. igl::deserialize(data,"Data",fname.c_str());
  700. for(unsigned int i = 0; i <plugins.size(); ++i)
  701. igl::deserialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  702. #endif
  703. return true;
  704. }
  705. void Viewer::resize(int w, int h)
  706. {
  707. core.viewport = Eigen::Vector4f(0,0,w,h);
  708. }
  709. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  710. {
  711. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->core.trackball_angle;
  712. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->core.trackball_angle.data());
  713. }
  714. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  715. {
  716. static_cast<Viewer *>(clientData)->core.align_camera_center(
  717. static_cast<Viewer *>(clientData)->data.V,
  718. static_cast<Viewer *>(clientData)->data.F);
  719. }
  720. void TW_CALL Viewer::save_scene_cb(void *clientData)
  721. {
  722. static_cast<Viewer *>(clientData)->save_scene();
  723. }
  724. void TW_CALL Viewer::load_scene_cb(void *clientData)
  725. {
  726. static_cast<Viewer *>(clientData)->load_scene();
  727. }
  728. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  729. {
  730. Viewer *viewer = static_cast<Viewer *>(clientData);
  731. viewer->data.dirty |= ViewerData::DIRTY_NORMAL;
  732. viewer->core.invert_normals = *((bool *) param);
  733. }
  734. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  735. {
  736. *((bool *) param) = static_cast<Viewer *>(clientData)->core.invert_normals;
  737. }
  738. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  739. {
  740. Viewer *viewer = static_cast<Viewer *>(clientData);
  741. viewer->data.set_face_based(*((bool *) param));
  742. }
  743. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  744. {
  745. *((bool *) param) = static_cast<Viewer *>(clientData)->data.face_based;
  746. }
  747. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  748. {
  749. std::string fname = igl::file_dialog_open();
  750. if (fname.length() == 0)
  751. return;
  752. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  753. }
  754. int Viewer::launch(std::string filename)
  755. {
  756. GLFWwindow* window;
  757. glfwSetErrorCallback(glfw_error_callback);
  758. if (!glfwInit())
  759. return EXIT_FAILURE;
  760. glfwWindowHint(GLFW_SAMPLES, 4);
  761. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  762. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  763. #ifdef __APPLE__
  764. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  765. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  766. #endif
  767. window = glfwCreateWindow(1280, 800, "libigl viewer", NULL, NULL);
  768. if (!window)
  769. {
  770. glfwTerminate();
  771. return EXIT_FAILURE;
  772. }
  773. glfwMakeContextCurrent(window);
  774. #ifndef __APPLE__
  775. glewExperimental = true;
  776. GLenum err = glewInit();
  777. if (GLEW_OK != err)
  778. {
  779. /* Problem: glewInit failed, something is seriously wrong. */
  780. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  781. }
  782. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  783. #endif
  784. #ifdef DEBUG
  785. int major, minor, rev;
  786. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  787. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  788. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  789. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  790. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  791. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  792. #endif
  793. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  794. // Initialize AntTweakBar
  795. TwInit(TW_OPENGL_CORE, NULL);
  796. TwCopyStdStringToClientFunc(static_cast<TwCopyStdStringToClient>(::copy_str));
  797. // Initialize IGL viewer
  798. init();
  799. __viewer = this;
  800. // Register callbacks
  801. glfwSetKeyCallback(window, glfw_key_callback); glfwSetCursorPosCallback(window,glfw_mouse_move); glfwSetWindowSizeCallback(window,glfw_window_size); glfwSetMouseButtonCallback(window,glfw_mouse_press); glfwSetScrollCallback(window,glfw_mouse_scroll); glfwSetCharCallback(window, glfw_char_callback);
  802. // Handle retina displays (windows and mac)
  803. int width, height;
  804. glfwGetFramebufferSize(window, &width, &height);
  805. int width_window, height_window;
  806. glfwGetWindowSize(window, &width_window, &height_window);
  807. highdpi = width/width_window;
  808. glfw_window_size(window,width_window,height_window);
  809. opengl.init();
  810. // Load the mesh passed as input
  811. if (filename.size() > 0)
  812. load_mesh_from_file(filename.c_str());
  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