Viewer.cpp 28 KB

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