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