Viewer.cpp 26 KB

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