Viewer.cpp 28 KB

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