Viewer.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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. if (plugins[i]->load(mesh_file_name_string))
  437. return true;
  438. data.clear();
  439. size_t last_dot = mesh_file_name_string.rfind('.');
  440. if (last_dot == std::string::npos)
  441. {
  442. printf("Error: No file extension found in %s\n",mesh_file_name);
  443. return false;
  444. }
  445. std::string extension = mesh_file_name_string.substr(last_dot+1);
  446. if (extension == "off" || extension =="OFF")
  447. {
  448. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  449. return false;
  450. }
  451. else if (extension == "obj" || extension =="OBJ")
  452. {
  453. Eigen::MatrixXd corner_normals;
  454. Eigen::MatrixXi fNormIndices;
  455. Eigen::MatrixXd UV_V;
  456. Eigen::MatrixXi UV_F;
  457. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  458. return false;
  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. 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. bool Viewer::key_down(unsigned char 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. if (key == 'S')
  523. mouse_scroll(1);
  524. if (key == 'A')
  525. mouse_scroll(-1);
  526. // Why aren't these handled via AntTweakBar?
  527. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  528. core.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  529. if (key == 'y')
  530. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  531. if (key == 'x')
  532. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  533. return false;
  534. }
  535. bool Viewer::key_up(unsigned char key, int modifiers)
  536. {
  537. if (callback_key_up)
  538. if (callback_key_up(*this,key,modifiers))
  539. return true;
  540. for (unsigned int i = 0; i<plugins.size(); ++i)
  541. if (plugins[i]->key_up(key, modifiers))
  542. return true;
  543. return false;
  544. }
  545. bool Viewer::mouse_down(MouseButton button, int modifier)
  546. {
  547. if (callback_mouse_down)
  548. if (callback_mouse_down(*this,button,modifier))
  549. return true;
  550. for (unsigned int i = 0; i<plugins.size(); ++i)
  551. if (plugins[i]->mouse_down(button,modifier))
  552. return true;
  553. down = true;
  554. down_mouse_x = current_mouse_x;
  555. down_mouse_y = current_mouse_y;
  556. down_translation = core.model_translation;
  557. // Initialization code for the trackball
  558. Eigen::RowVector3d center;
  559. if (data.V.rows() == 0)
  560. center << 0,0,0;
  561. else
  562. center = data.V.colwise().sum()/data.V.rows();
  563. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), core.view * core.model, core.proj, core.viewport);
  564. down_mouse_z = coord[2];
  565. down_rotation = core.trackball_angle;
  566. mouse_mode = ROTATION;
  567. switch (button)
  568. {
  569. case IGL_LEFT:
  570. mouse_mode = ROTATION;
  571. break;
  572. case IGL_RIGHT:
  573. mouse_mode = TRANSLATE;
  574. break;
  575. default:
  576. mouse_mode = NOTHING;
  577. break;
  578. }
  579. return true;
  580. }
  581. bool Viewer::mouse_up(MouseButton button, int modifier)
  582. {
  583. down = false;
  584. if (callback_mouse_up)
  585. if (callback_mouse_up(*this,button,modifier))
  586. return true;
  587. for (unsigned int i = 0; i<plugins.size(); ++i)
  588. if (plugins[i]->mouse_up(button,modifier))
  589. return true;
  590. mouse_mode = NOTHING;
  591. return true;
  592. }
  593. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  594. {
  595. if(hack_never_moved)
  596. {
  597. down_mouse_x = mouse_x;
  598. down_mouse_y = mouse_y;
  599. hack_never_moved = false;
  600. }
  601. current_mouse_x = mouse_x;
  602. current_mouse_y = mouse_y;
  603. if (callback_mouse_move)
  604. if (callback_mouse_move(*this,mouse_x,mouse_y))
  605. return true;
  606. for (unsigned int i = 0; i<plugins.size(); ++i)
  607. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  608. return true;
  609. if (down)
  610. {
  611. switch (mouse_mode)
  612. {
  613. case ROTATION :
  614. {
  615. igl::trackball(core.viewport(2),
  616. core.viewport(3),
  617. 2.0f,
  618. down_rotation.data(),
  619. down_mouse_x,
  620. down_mouse_y,
  621. mouse_x,
  622. mouse_y,
  623. core.trackball_angle.data());
  624. //Eigen::Vector4f snapq = core.trackball_angle;
  625. break;
  626. }
  627. case TRANSLATE:
  628. {
  629. //translation
  630. 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);
  631. 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);
  632. Eigen::Vector3f diff = pos1 - pos0;
  633. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  634. break;
  635. }
  636. case ZOOM:
  637. {
  638. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  639. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  640. core.camera_zoom *= 1 + delta;
  641. down_mouse_x = mouse_x;
  642. down_mouse_y = mouse_y;
  643. break;
  644. }
  645. default:
  646. break;
  647. }
  648. }
  649. return true;
  650. }
  651. bool Viewer::mouse_scroll(float delta_y)
  652. {
  653. scroll_position += delta_y;
  654. if (callback_mouse_scroll)
  655. if (callback_mouse_scroll(*this,delta_y))
  656. return true;
  657. for (unsigned int i = 0; i<plugins.size(); ++i)
  658. if (plugins[i]->mouse_scroll(delta_y))
  659. return true;
  660. // Only zoom if there's actually a change
  661. if(delta_y != 0)
  662. {
  663. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  664. const float min_zoom = 0.1f;
  665. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  666. }
  667. return true;
  668. }
  669. void Viewer::draw()
  670. {
  671. using namespace std;
  672. using namespace Eigen;
  673. core.clear_framebuffers();
  674. if (callback_pre_draw)
  675. if (callback_pre_draw(*this))
  676. return;
  677. for (unsigned int i = 0; i<plugins.size(); ++i)
  678. if (plugins[i]->pre_draw())
  679. return;
  680. core.draw(data,opengl);
  681. if (callback_post_draw)
  682. if (callback_post_draw(*this))
  683. return;
  684. for (unsigned int i = 0; i<plugins.size(); ++i)
  685. if (plugins[i]->post_draw())
  686. break;
  687. #ifndef NO_TBAR
  688. TwDraw();
  689. #endif
  690. }
  691. bool Viewer::save_scene()
  692. {
  693. #ifdef ENABLE_XML_SERIALIZATION
  694. string fname = igl::file_dialog_save();
  695. if (fname.length() == 0)
  696. return false;
  697. ::igl::XMLSerializer serializer("Viewer");
  698. serializer.Add(data,"Data");
  699. serializer.Add(options,"Options");
  700. if (plugin_manager)
  701. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  702. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  703. serializer.Save(fname.c_str(),true);
  704. #endif
  705. return true;
  706. }
  707. bool Viewer::load_scene()
  708. {
  709. #ifdef ENABLE_XML_SERIALIZATION
  710. string fname = igl::file_dialog_open();
  711. if (fname.length() == 0)
  712. return false;
  713. ::igl::XMLSerializer serializer("Viewer");
  714. serializer.Add(data,"Data");
  715. serializer.Add(options,"Options");
  716. if (plugin_manager)
  717. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  718. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  719. serializer.Load(fname.c_str());
  720. #endif
  721. return true;
  722. }
  723. void Viewer::resize(int w, int h)
  724. {
  725. core.viewport = Eigen::Vector4f(0,0,w,h);
  726. }
  727. #ifndef NO_TBAR
  728. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  729. {
  730. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->core.trackball_angle;
  731. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->core.trackball_angle.data());
  732. }
  733. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  734. {
  735. static_cast<Viewer *>(clientData)->core.align_camera_center(
  736. static_cast<Viewer *>(clientData)->data.V,
  737. static_cast<Viewer *>(clientData)->data.F);
  738. }
  739. void TW_CALL Viewer::save_scene_cb(void *clientData)
  740. {
  741. static_cast<Viewer *>(clientData)->save_scene();
  742. }
  743. void TW_CALL Viewer::load_scene_cb(void *clientData)
  744. {
  745. static_cast<Viewer *>(clientData)->load_scene();
  746. }
  747. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  748. {
  749. Viewer *viewer = static_cast<Viewer *>(clientData);
  750. viewer->data.dirty |= ViewerData::DIRTY_NORMAL;
  751. viewer->core.invert_normals = *((bool *) param);
  752. }
  753. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  754. {
  755. *((bool *) param) = static_cast<Viewer *>(clientData)->core.invert_normals;
  756. }
  757. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  758. {
  759. Viewer *viewer = static_cast<Viewer *>(clientData);
  760. viewer->data.set_face_based(*((bool *) param));
  761. }
  762. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  763. {
  764. *((bool *) param) = static_cast<Viewer *>(clientData)->data.face_based;
  765. }
  766. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  767. {
  768. std::string fname = igl::file_dialog_open();
  769. if (fname.length() == 0)
  770. return;
  771. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  772. }
  773. #endif
  774. int Viewer::launch(std::string filename)
  775. {
  776. GLFWwindow* window;
  777. glfwSetErrorCallback(glfw_error_callback);
  778. if (!glfwInit())
  779. return EXIT_FAILURE;
  780. glfwWindowHint(GLFW_SAMPLES, 16);
  781. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  782. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  783. #ifdef __APPLE__
  784. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  785. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  786. #endif
  787. window = glfwCreateWindow(1280, 800, "libigl viewer", NULL, NULL);
  788. if (!window)
  789. {
  790. glfwTerminate();
  791. return EXIT_FAILURE;
  792. }
  793. glfwMakeContextCurrent(window);
  794. #ifndef __APPLE__
  795. glewExperimental = true;
  796. GLenum err = glewInit();
  797. if (GLEW_OK != err)
  798. {
  799. /* Problem: glewInit failed, something is seriously wrong. */
  800. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  801. }
  802. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  803. #endif
  804. #ifdef DEBUG
  805. int major, minor, rev;
  806. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  807. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  808. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  809. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  810. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  811. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  812. #endif
  813. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  814. // Initialize AntTweakBar
  815. #ifndef NO_TBAR
  816. TwInit(TW_OPENGL_CORE, NULL);
  817. TwCopyStdStringToClientFunc(static_cast<TwCopyStdStringToClient>(::copy_str));
  818. #endif
  819. // Initialize IGL viewer
  820. init();
  821. __viewer = this;
  822. // Register callbacks
  823. 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);
  824. // Handle retina displays (windows and mac)
  825. int width, height;
  826. glfwGetFramebufferSize(window, &width, &height);
  827. int width_window, height_window;
  828. glfwGetWindowSize(window, &width_window, &height_window);
  829. highdpi = width/width_window;
  830. glfw_window_size(window,width_window,height_window);
  831. opengl.init();
  832. // Load the mesh passed as input
  833. if (filename.size() > 0)
  834. load_mesh_from_file(filename.c_str());
  835. core.align_camera_center(data.V,data.F);
  836. // Rendering loop
  837. while (!glfwWindowShouldClose(window))
  838. {
  839. double tic = get_seconds();
  840. draw();
  841. glfwSwapBuffers(window);
  842. if(core.is_animating)
  843. {
  844. glfwPollEvents();
  845. // In microseconds
  846. double duration = 1000000.*(get_seconds()-tic);
  847. const double min_duration = 1000000./core.animation_max_fps;
  848. if(duration<min_duration)
  849. {
  850. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  851. }
  852. }
  853. else
  854. {
  855. glfwWaitEvents();
  856. }
  857. }
  858. opengl.free();
  859. core.shut();
  860. shutdown_plugins();
  861. glfwDestroyWindow(window);
  862. glfwTerminate();
  863. return EXIT_SUCCESS;
  864. }
  865. } // end namespace