Viewer.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. #include "Viewer.h"
  2. #include <igl/get_seconds.h>
  3. #ifdef _WIN32
  4. # include <windows.h>
  5. # undef max
  6. # undef min
  7. #endif
  8. // Todo: windows equivalent for `usleep`
  9. #include <unistd.h>
  10. #ifndef __APPLE__
  11. # define GLEW_STATIC
  12. # include <GL/glew.h>
  13. #endif
  14. #ifdef __APPLE__
  15. # include <OpenGL/gl3.h>
  16. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  17. #else
  18. # ifdef _WIN32
  19. # include <windows.h>
  20. # endif
  21. # include <GL/gl.h>
  22. #endif
  23. #include <Eigen/LU>
  24. #define GLFW_INCLUDE_GLU
  25. #include <GLFW/glfw3.h>
  26. #include <cmath>
  27. #include <cstdio>
  28. #include <sstream>
  29. #include <iomanip>
  30. #include <iostream>
  31. #include <fstream>
  32. #include <algorithm>
  33. //OK NV
  34. Eigen::Vector3f project(const Eigen::Vector3f& obj,
  35. const Eigen::Matrix4f& model,
  36. const Eigen::Matrix4f& proj,
  37. const Eigen::Vector4f& viewport)
  38. {
  39. Eigen::Vector4f tmp;
  40. tmp << obj,1;
  41. tmp = model * tmp;
  42. tmp = proj * tmp;
  43. tmp = tmp.array() / tmp(3);
  44. tmp = tmp.array() * 0.5f + 0.5f;
  45. tmp(0) = tmp(0) * viewport(2) + viewport(0);
  46. tmp(1) = tmp(1) * viewport(3) + viewport(1);
  47. return tmp.head(3);
  48. }
  49. Eigen::Matrix4f lookAt (
  50. const Eigen::Vector3f& eye,
  51. const Eigen::Vector3f& center,
  52. const Eigen::Vector3f& up)
  53. {
  54. Eigen::Vector3f f = (center - eye).normalized();
  55. Eigen::Vector3f s = f.cross(up).normalized();
  56. Eigen::Vector3f u = s.cross(f);
  57. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  58. Result(0,0) = s(0);
  59. Result(0,1) = s(1);
  60. Result(0,2) = s(2);
  61. Result(1,0) = u(0);
  62. Result(1,1) = u(1);
  63. Result(1,2) = u(2);
  64. Result(2,0) =-f(0);
  65. Result(2,1) =-f(1);
  66. Result(2,2) =-f(2);
  67. Result(0,3) =-s.transpose() * eye;
  68. Result(1,3) =-u.transpose() * eye;
  69. Result(2,3) = f.transpose() * eye;
  70. return Result;
  71. }
  72. Eigen::Matrix4f ortho (
  73. const float left,
  74. const float right,
  75. const float bottom,
  76. const float top,
  77. const float zNear,
  78. const float zFar
  79. )
  80. {
  81. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  82. Result(0,0) = 2.0f / (right - left);
  83. Result(1,1) = 2.0f / (top - bottom);
  84. Result(2,2) = - 2.0f / (zFar - zNear);
  85. Result(0,3) = - (right + left) / (right - left);
  86. Result(1,3) = - (top + bottom) / (top - bottom);
  87. Result(2,3) = - (zFar + zNear) / (zFar - zNear);
  88. return Result;
  89. }
  90. Eigen::Matrix4f frustum (
  91. const float left,
  92. const float right,
  93. const float bottom,
  94. const float top,
  95. const float nearVal,
  96. const float farVal)
  97. {
  98. Eigen::Matrix4f Result = Eigen::Matrix4f::Zero();
  99. Result(0,0) = (2.0f * nearVal) / (right - left);
  100. Result(1,1) = (2.0f * nearVal) / (top - bottom);
  101. Result(0,2) = (right + left) / (right - left);
  102. Result(1,2) = (top + bottom) / (top - bottom);
  103. Result(2,2) = -(farVal + nearVal) / (farVal - nearVal);
  104. Result(3,2) = -1.0f;
  105. Result(2,3) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
  106. return Result;
  107. }
  108. Eigen::Matrix4f scale (const Eigen::Matrix4f& m,
  109. const Eigen::Vector3f& v)
  110. {
  111. Eigen::Matrix4f Result;
  112. Result.col(0) = m.col(0).array() * v(0);
  113. Result.col(1) = m.col(1).array() * v(1);
  114. Result.col(2) = m.col(2).array() * v(2);
  115. Result.col(3) = m.col(3);
  116. return Result;
  117. }
  118. Eigen::Matrix4f translate(
  119. const Eigen::Matrix4f& m,
  120. const Eigen::Vector3f& v)
  121. {
  122. Eigen::Matrix4f Result = m;
  123. Result.col(3) = m.col(0).array() * v(0) + m.col(1).array() * v(1) + m.col(2).array() * v(2) + m.col(3).array();
  124. return Result;
  125. }
  126. #include <limits>
  127. #include <cassert>
  128. #ifdef ENABLE_XML_SERIALIZATION
  129. #include "igl/xml/XMLSerializer.h"
  130. #endif
  131. #include <igl/readOBJ.h>
  132. #include <igl/readOFF.h>
  133. #include <igl/per_face_normals.h>
  134. #include <igl/per_vertex_normals.h>
  135. #include <igl/per_corner_normals.h>
  136. #include <igl/adjacency_list.h>
  137. #include <igl/writeOBJ.h>
  138. #include <igl/writeOFF.h>
  139. #include <igl/massmatrix.h>
  140. #include <igl/file_dialog_open.h>
  141. #include <igl/file_dialog_save.h>
  142. #include <igl/quat_to_mat.h>
  143. #include <igl/quat_mult.h>
  144. #include <igl/axis_angle_to_quat.h>
  145. #include <igl/trackball.h>
  146. #include <igl/snap_to_canonical_view_quat.h>
  147. #include <igl/unproject.h>
  148. #include <TwOpenGLCore.h>
  149. #include <igl/viewer/TextRenderer.h>
  150. // Internal global variables used for glfw event handling
  151. static igl::Viewer * __viewer;
  152. static double highdpi = 1;
  153. static double scroll_x = 0;
  154. static double scroll_y = 0;
  155. static igl::TextRenderer __font_renderer;
  156. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  157. {
  158. bool tw_used = TwEventMouseButtonGLFW(button, action);
  159. igl::Viewer::MouseButton mb;
  160. if (button == GLFW_MOUSE_BUTTON_1)
  161. mb = igl::Viewer::IGL_LEFT;
  162. else if (button == GLFW_MOUSE_BUTTON_2)
  163. mb = igl::Viewer::IGL_RIGHT;
  164. else //if (button == GLFW_MOUSE_BUTTON_3)
  165. mb = igl::Viewer::IGL_MIDDLE;
  166. if (action == GLFW_PRESS)
  167. {
  168. if(!tw_used)
  169. {
  170. __viewer->mouse_down(mb,modifier);
  171. }
  172. } else
  173. {
  174. // Always call mouse_up on up
  175. __viewer->mouse_up(mb,modifier);
  176. }
  177. }
  178. static void glfw_error_callback(int error, const char* description)
  179. {
  180. fputs(description, stderr);
  181. }
  182. int global_KMod = 0;
  183. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  184. {
  185. int handled = 0;
  186. // Register of modifiers state
  187. if (glfwAction==GLFW_PRESS)
  188. {
  189. switch (glfwKey)
  190. {
  191. case GLFW_KEY_LEFT_SHIFT:
  192. case GLFW_KEY_RIGHT_SHIFT:
  193. global_KMod |= TW_KMOD_SHIFT;
  194. break;
  195. case GLFW_KEY_LEFT_CONTROL:
  196. case GLFW_KEY_RIGHT_CONTROL:
  197. global_KMod |= TW_KMOD_CTRL;
  198. break;
  199. case GLFW_KEY_LEFT_ALT:
  200. case GLFW_KEY_RIGHT_ALT:
  201. global_KMod |= TW_KMOD_ALT;
  202. break;
  203. }
  204. }
  205. else
  206. {
  207. switch (glfwKey)
  208. {
  209. case GLFW_KEY_LEFT_SHIFT:
  210. case GLFW_KEY_RIGHT_SHIFT:
  211. global_KMod &= ~TW_KMOD_SHIFT;
  212. break;
  213. case GLFW_KEY_LEFT_CONTROL:
  214. case GLFW_KEY_RIGHT_CONTROL:
  215. global_KMod &= ~TW_KMOD_CTRL;
  216. break;
  217. case GLFW_KEY_LEFT_ALT:
  218. case GLFW_KEY_RIGHT_ALT:
  219. global_KMod &= ~TW_KMOD_ALT;
  220. break;
  221. }
  222. }
  223. // Process key pressed
  224. if (glfwAction==GLFW_PRESS)
  225. {
  226. int mod = global_KMod;
  227. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  228. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  229. handled = TwKeyPressed(glfwKey, mod);
  230. else if (glfwKey>=GLFW_KEY_ESCAPE )
  231. {
  232. int k = 0;
  233. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  234. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  235. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  236. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  237. else
  238. {
  239. switch (glfwKey)
  240. {
  241. case GLFW_KEY_ESCAPE :
  242. k = TW_KEY_ESCAPE;
  243. break;
  244. case GLFW_KEY_UP:
  245. k = TW_KEY_UP;
  246. break;
  247. case GLFW_KEY_DOWN:
  248. k = TW_KEY_DOWN;
  249. break;
  250. case GLFW_KEY_LEFT:
  251. k = TW_KEY_LEFT;
  252. break;
  253. case GLFW_KEY_RIGHT:
  254. k = TW_KEY_RIGHT;
  255. break;
  256. case GLFW_KEY_TAB:
  257. k = TW_KEY_TAB;
  258. break;
  259. case GLFW_KEY_ENTER:
  260. k = TW_KEY_RETURN;
  261. break;
  262. case GLFW_KEY_BACKSPACE:
  263. k = TW_KEY_BACKSPACE;
  264. break;
  265. case GLFW_KEY_INSERT:
  266. k = TW_KEY_INSERT;
  267. break;
  268. case GLFW_KEY_DELETE:
  269. k = TW_KEY_DELETE;
  270. break;
  271. case GLFW_KEY_PAGE_UP:
  272. k = TW_KEY_PAGE_UP;
  273. break;
  274. case GLFW_KEY_PAGE_DOWN:
  275. k = TW_KEY_PAGE_DOWN;
  276. break;
  277. case GLFW_KEY_HOME:
  278. k = TW_KEY_HOME;
  279. break;
  280. case GLFW_KEY_END:
  281. k = TW_KEY_END;
  282. break;
  283. case GLFW_KEY_KP_ENTER:
  284. k = TW_KEY_RETURN;
  285. break;
  286. case GLFW_KEY_KP_DIVIDE:
  287. if (testkp)
  288. k = '/';
  289. break;
  290. case GLFW_KEY_KP_MULTIPLY:
  291. if (testkp)
  292. k = '*';
  293. break;
  294. case GLFW_KEY_KP_SUBTRACT:
  295. if (testkp)
  296. k = '-';
  297. break;
  298. case GLFW_KEY_KP_ADD:
  299. if (testkp)
  300. k = '+';
  301. break;
  302. case GLFW_KEY_KP_DECIMAL:
  303. if (testkp)
  304. k = '.';
  305. break;
  306. case GLFW_KEY_KP_EQUAL:
  307. if (testkp)
  308. k = '=';
  309. break;
  310. }
  311. }
  312. if (k>0)
  313. handled = TwKeyPressed(k, mod);
  314. }
  315. }
  316. return handled;
  317. }
  318. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  319. {
  320. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  321. glfwSetWindowShouldClose(window, GL_TRUE);
  322. if (!TwEventKeyGLFW3(key,action))
  323. {
  324. if (action == GLFW_PRESS)
  325. __viewer->key_down(key, modifier);
  326. else
  327. __viewer->key_up(key, modifier);
  328. }
  329. }
  330. static void glfw_window_size(GLFWwindow* window, int width, int height)
  331. {
  332. int w = width*highdpi;
  333. int h = height*highdpi;
  334. __viewer->resize(w, h);
  335. TwWindowSize(w, h);
  336. const auto & bar = __viewer->bar;
  337. // Keep AntTweakBar on right side of screen and height == opengl height
  338. // get the current position of a bar
  339. int size[2];
  340. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  341. int pos[2];
  342. // Place bar on left side of opengl rect (padded by 10 pixels)
  343. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  344. // place bar at top (padded by 10 pixels)
  345. pos[1] = 10;
  346. // Set height to new height of window (padded by 10 pixels on bottom)
  347. size[1] = highdpi*(height-pos[1]-10);
  348. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  349. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  350. }
  351. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  352. {
  353. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  354. {
  355. // Call if TwBar hasn't used or if down
  356. __viewer->mouse_move(x*highdpi, y*highdpi);
  357. }
  358. }
  359. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  360. {
  361. using namespace std;
  362. scroll_x += x;
  363. scroll_y += y;
  364. if (!TwEventMouseWheelGLFW(scroll_y))
  365. __viewer->mouse_scroll(y);
  366. }
  367. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  368. {
  369. if ((c & 0xff00)==0)
  370. TwKeyPressed(c, global_KMod);
  371. }
  372. namespace igl
  373. {
  374. void Viewer::init()
  375. {
  376. // Create a tweak bar
  377. bar = TwNewBar("libIGL-Viewer");
  378. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  379. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  380. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  381. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  382. // ---------------------- LOADING ----------------------
  383. #ifdef ENABLE_XML_SERIALIZATION
  384. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  385. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  386. #endif
  387. #ifdef ENABLE_IO
  388. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  389. #endif
  390. // ---------------------- SCENE ----------------------
  391. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  392. " group='Viewing Options'"
  393. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  394. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(options.camera_zoom),
  395. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  396. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  397. " group='Scene'"
  398. " label='Snap to canonical view' key=Z "
  399. " help='Snaps view to nearest canonical view.'");
  400. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, options.light_position.data(),
  401. " group='Scene'"
  402. " label='Light direction' open help='Change the light direction.' ");
  403. // ---------------------- DRAW OPTIONS ----------------------
  404. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(options.orthographic),
  405. " group='Viewing Options'"
  406. " label='Orthographic view' "
  407. " help='Toggles orthographic / perspective view. Default: perspective.'");
  408. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(options.trackball_angle),
  409. " group='Viewing Options'"
  410. " label='Rotation'"
  411. " help='Rotates view.'");
  412. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  413. " group='Draw options'"
  414. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  415. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(options.show_texture),
  416. " group='Draw options'");
  417. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  418. " group='Draw options'"
  419. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  420. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(options.show_overlay),
  421. " group='Draw options'"
  422. " label='Show overlay' key=o help='Show the overlay layers.' ");
  423. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(options.show_overlay_depth),
  424. " group='Draw options'"
  425. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  426. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  427. options.background_color.data(),
  428. " help='Select a background color' colormode=hls group='Draw options'");
  429. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  430. options.line_color.data(),
  431. " label='Line color' help='Select a outline color' group='Draw options'");
  432. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&options.shininess," group='Draw options'"
  433. " min=1 max=128");
  434. // ---------------------- Overlays ----------------------
  435. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(options.show_lines),
  436. " group='Overlays'"
  437. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  438. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(options.show_faces),
  439. " group='Overlays'"
  440. " label='Fill' key=t help='Display filled polygons of mesh'");
  441. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(options.show_vertid),
  442. " group='Overlays'"
  443. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  444. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(options.show_faceid),
  445. " group='Overlays'"
  446. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  447. " indices'");
  448. __font_renderer.Init();
  449. init_plugins();
  450. }
  451. Viewer::Viewer()
  452. {
  453. // Default shininess
  454. options.shininess = 35.0f;
  455. // Default colors
  456. options.background_color << 0.3f, 0.3f, 0.5f;
  457. options.line_color << 0.0f, 0.0f, 0.0f;
  458. // Default lights settings
  459. options.light_position << 0.0f, -0.30f, -5.0f;
  460. options.lighting_factor = 1.0f; //on
  461. // Default trackball
  462. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  463. // Defalut model viewing parameters
  464. options.model_zoom = 1.0f;
  465. options.model_translation << 0,0,0;
  466. // Camera parameters
  467. options.camera_zoom = 1.0f;
  468. options.orthographic = false;
  469. options.camera_view_angle = 45.0;
  470. options.camera_dnear = 1.0;
  471. options.camera_dfar = 100.0;
  472. options.camera_eye << 0, 0, 5;
  473. options.camera_center << 0, 0, 0;
  474. options.camera_up << 0, 1, 0;
  475. // Default visualization options
  476. options.show_faces = true;
  477. options.show_lines = true;
  478. options.invert_normals = false;
  479. options.show_overlay = true;
  480. options.show_overlay_depth = true;
  481. options.show_vertid = false;
  482. options.show_faceid = false;
  483. options.show_texture = false;
  484. // Default point size / line width
  485. options.point_size = 15;
  486. options.line_width = 0.5f;
  487. options.face_based = false;
  488. options.is_animating = false;
  489. options.animation_max_fps = 30.;
  490. // Temporary variables initialization
  491. down = false;
  492. hack_never_moved = true;
  493. scroll_position = 0.0f;
  494. // Per face
  495. set_face_based(false);
  496. // C-style callbacks
  497. callback_pre_draw = 0;
  498. callback_post_draw = 0;
  499. callback_mouse_down = 0;
  500. callback_mouse_up = 0;
  501. callback_mouse_move = 0;
  502. callback_mouse_scroll = 0;
  503. callback_key_down = 0;
  504. callback_key_up = 0;
  505. callback_pre_draw_data = 0;
  506. callback_post_draw = 0;
  507. callback_mouse_down = 0;
  508. callback_mouse_up = 0;
  509. callback_mouse_move = 0;
  510. callback_mouse_scroll = 0;
  511. callback_key_down = 0;
  512. callback_key_up = 0;
  513. }
  514. void Viewer::init_plugins()
  515. {
  516. // Init all plugins
  517. for (unsigned int i = 0; i<plugins.size(); ++i)
  518. plugins[i]->init(this);
  519. }
  520. Viewer::~Viewer()
  521. {
  522. }
  523. void Viewer::shutdown_plugins()
  524. {
  525. for (unsigned int i = 0; i<plugins.size(); ++i)
  526. plugins[i]->shutdown();
  527. }
  528. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  529. {
  530. std::string mesh_file_name_string = std::string(mesh_file_name);
  531. // first try to load it with a plugin
  532. for (unsigned int i = 0; i<plugins.size(); ++i)
  533. if (plugins[i]->load(mesh_file_name_string))
  534. return true;
  535. clear_mesh();
  536. size_t last_dot = mesh_file_name_string.rfind('.');
  537. if (last_dot == std::string::npos)
  538. {
  539. printf("Error: No file extension found in %s\n",mesh_file_name);
  540. return false;
  541. }
  542. std::string extension = mesh_file_name_string.substr(last_dot+1);
  543. if (extension == "off" || extension =="OFF")
  544. {
  545. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  546. return false;
  547. }
  548. else if (extension == "obj" || extension =="OBJ")
  549. {
  550. Eigen::MatrixXd corner_normals;
  551. Eigen::MatrixXi fNormIndices;
  552. Eigen::MatrixXd UV_V;
  553. Eigen::MatrixXi UV_F;
  554. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  555. return false;
  556. }
  557. else
  558. {
  559. // unrecognized file type
  560. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  561. return false;
  562. }
  563. compute_normals();
  564. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  565. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  566. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  567. if (data.V_uv.rows() == 0)
  568. grid_texture();
  569. align_camera_center();
  570. for (unsigned int i = 0; i<plugins.size(); ++i)
  571. if (plugins[i]->post_load())
  572. return true;
  573. return true;
  574. }
  575. void Viewer::compute_normals()
  576. {
  577. igl::per_face_normals(data.V, data.F, data.F_normals);
  578. igl::per_vertex_normals(data.V, data.F, data.F_normals, data.V_normals);
  579. data.dirty |= OpenGL_state::DIRTY_NORMAL;
  580. }
  581. void Viewer::uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular)
  582. {
  583. data.V_material_ambient.resize(data.V.rows(),3);
  584. data.V_material_diffuse.resize(data.V.rows(),3);
  585. data.V_material_specular.resize(data.V.rows(),3);
  586. for (unsigned i=0; i<data.V.rows();++i)
  587. {
  588. data.V_material_ambient.row(i) = ambient;
  589. data.V_material_diffuse.row(i) = diffuse;
  590. data.V_material_specular.row(i) = specular;
  591. }
  592. data.F_material_ambient.resize(data.F.rows(),3);
  593. data.F_material_diffuse.resize(data.F.rows(),3);
  594. data.F_material_specular.resize(data.F.rows(),3);
  595. for (unsigned i=0; i<data.F.rows();++i)
  596. {
  597. data.F_material_ambient.row(i) = ambient;
  598. data.F_material_diffuse.row(i) = diffuse;
  599. data.F_material_specular.row(i) = specular;
  600. }
  601. data.dirty |= OpenGL_state::DIRTY_SPECULAR | OpenGL_state::DIRTY_DIFFUSE | OpenGL_state::DIRTY_AMBIENT;
  602. }
  603. void Viewer::grid_texture()
  604. {
  605. if (data.V_uv.rows() == 0)
  606. {
  607. data.V_uv = data.V.block(0, 0, data.V.rows(), 2);
  608. data.V_uv.col(0) = data.V_uv.col(0).array() - data.V_uv.col(0).minCoeff();
  609. data.V_uv.col(0) = data.V_uv.col(0).array() / data.V_uv.col(0).maxCoeff();
  610. data.V_uv.col(1) = data.V_uv.col(1).array() - data.V_uv.col(1).minCoeff();
  611. data.V_uv.col(1) = data.V_uv.col(1).array() / data.V_uv.col(1).maxCoeff();
  612. data.V_uv = data.V_uv.array() * 10;
  613. data.dirty |= OpenGL_state::DIRTY_TEXTURE;
  614. }
  615. unsigned size = 128;
  616. unsigned size2 = size/2;
  617. data.texture_R.resize(size, size);
  618. for (unsigned i=0; i<size; ++i)
  619. {
  620. for (unsigned j=0; j<size; ++j)
  621. {
  622. data.texture_R(i,j) = 0;
  623. if ((i<size2 && j<size2) || (i>=size2 && j>=size2))
  624. data.texture_R(i,j) = 255;
  625. }
  626. }
  627. data.texture_G = data.texture_R;
  628. data.texture_B = data.texture_R;
  629. data.dirty |= OpenGL_state::DIRTY_TEXTURE;
  630. }
  631. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  632. {
  633. std::string mesh_file_name_string(mesh_file_name);
  634. // first try to load it with a plugin
  635. for (unsigned int i = 0; i<plugins.size(); ++i)
  636. if (plugins[i]->save(mesh_file_name_string))
  637. return true;
  638. size_t last_dot = mesh_file_name_string.rfind('.');
  639. if (last_dot == std::string::npos)
  640. {
  641. // No file type determined
  642. printf("Error: No file extension found in %s\n",mesh_file_name);
  643. return false;
  644. }
  645. std::string extension = mesh_file_name_string.substr(last_dot+1);
  646. if (extension == "off" || extension =="OFF")
  647. {
  648. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  649. }
  650. else if (extension == "obj" || extension =="OBJ")
  651. {
  652. Eigen::MatrixXd corner_normals;
  653. Eigen::MatrixXi fNormIndices;
  654. Eigen::MatrixXd UV_V;
  655. Eigen::MatrixXi UV_F;
  656. return igl::writeOBJ(mesh_file_name_string, data.V,
  657. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  658. }
  659. else
  660. {
  661. // unrecognized file type
  662. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  663. return false;
  664. }
  665. return true;
  666. }
  667. void Viewer::clear_mesh()
  668. {
  669. data.V = Eigen::MatrixXd (0,3);
  670. data.F = Eigen::MatrixXi (0,3);
  671. data.F_material_ambient = Eigen::MatrixXd (0,3);
  672. data.F_material_diffuse = Eigen::MatrixXd (0,3);
  673. data.F_material_specular = Eigen::MatrixXd (0,3);
  674. data.V_material_ambient = Eigen::MatrixXd (0,3);
  675. data.V_material_diffuse = Eigen::MatrixXd (0,3);
  676. data.V_material_specular = Eigen::MatrixXd (0,3);
  677. data.F_normals = Eigen::MatrixXd (0,3);
  678. data.V_normals = Eigen::MatrixXd (0,3);
  679. data.V_uv = Eigen::MatrixXd (0,2);
  680. data.F_uv = Eigen::MatrixXi (0,3);
  681. data.lines = Eigen::MatrixXd (0,9);
  682. data.points = Eigen::MatrixXd (0,6);
  683. data.labels_positions = Eigen::MatrixXd (0,3);
  684. data.labels_strings.clear();
  685. }
  686. bool Viewer::key_down(unsigned char key, int modifiers)
  687. {
  688. if (callback_key_down)
  689. if (callback_key_down(*this,key,modifiers))
  690. return true;
  691. for (unsigned int i = 0; i<plugins.size(); ++i)
  692. if (plugins[i]->key_down(key, modifiers))
  693. return true;
  694. if (key == 'S')
  695. mouse_scroll(1);
  696. if (key == 'A')
  697. mouse_scroll(-1);
  698. // Why aren't these handled view AntTweakBar?
  699. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  700. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  701. if (key == 'y')
  702. options.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  703. if (key == 'x')
  704. options.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  705. return false;
  706. }
  707. bool Viewer::key_up(unsigned char key, int modifiers)
  708. {
  709. if (callback_key_up)
  710. if (callback_key_up(*this,key,modifiers))
  711. return true;
  712. for (unsigned int i = 0; i<plugins.size(); ++i)
  713. if (plugins[i]->key_up(key, modifiers))
  714. return true;
  715. return false;
  716. }
  717. bool Viewer::mouse_down(MouseButton button, int modifier)
  718. {
  719. if (callback_mouse_down)
  720. if (callback_mouse_down(*this,button,modifier))
  721. return true;
  722. for (unsigned int i = 0; i<plugins.size(); ++i)
  723. if (plugins[i]->mouse_down(button,modifier))
  724. return true;
  725. down = true;
  726. down_mouse_x = current_mouse_x;
  727. down_mouse_y = current_mouse_y;
  728. down_translation = options.model_translation;
  729. // Initialization code for the trackball
  730. Eigen::RowVector3d center;
  731. if (data.V.rows() == 0)
  732. center << 0,0,0;
  733. else
  734. center = data.V.colwise().sum()/data.V.rows();
  735. Eigen::Vector3f coord = project(Eigen::Vector3f(center(0),center(1),center(2)), view * model, proj, viewport);
  736. down_mouse_z = coord[2];
  737. down_rotation = options.trackball_angle;
  738. mouse_mode = ROTATION;
  739. switch (button)
  740. {
  741. case IGL_LEFT:
  742. mouse_mode = ROTATION;
  743. break;
  744. case IGL_RIGHT:
  745. mouse_mode = TRANSLATE;
  746. break;
  747. default:
  748. mouse_mode = NOTHING;
  749. break;
  750. }
  751. return true;
  752. }
  753. bool Viewer::mouse_up(MouseButton button, int modifier)
  754. {
  755. down = false;
  756. if (callback_mouse_up)
  757. if (callback_mouse_up(*this,button,modifier))
  758. return true;
  759. for (unsigned int i = 0; i<plugins.size(); ++i)
  760. if (plugins[i]->mouse_up(button,modifier))
  761. return true;
  762. mouse_mode = NOTHING;
  763. return true;
  764. }
  765. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  766. {
  767. if(hack_never_moved)
  768. {
  769. down_mouse_x = mouse_x;
  770. down_mouse_y = mouse_y;
  771. hack_never_moved = false;
  772. }
  773. current_mouse_x = mouse_x;
  774. current_mouse_y = mouse_y;
  775. if (callback_mouse_move)
  776. if (callback_mouse_move(*this,mouse_x,mouse_y))
  777. return true;
  778. for (unsigned int i = 0; i<plugins.size(); ++i)
  779. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  780. return true;
  781. if (down)
  782. {
  783. switch (mouse_mode)
  784. {
  785. case ROTATION :
  786. {
  787. igl::trackball(width,
  788. height,
  789. 2.0f,
  790. down_rotation.data(),
  791. down_mouse_x,
  792. down_mouse_y,
  793. mouse_x,
  794. mouse_y,
  795. options.trackball_angle.data());
  796. //Eigen::Vector4f snapq = options.trackball_angle;
  797. break;
  798. }
  799. case TRANSLATE:
  800. {
  801. //translation
  802. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, viewport[3] - mouse_y, down_mouse_z), view * model, proj, viewport);
  803. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, viewport[3] - down_mouse_y, down_mouse_z), view * model, proj, viewport);
  804. Eigen::Vector3f diff = pos1 - pos0;
  805. options.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  806. break;
  807. }
  808. case ZOOM:
  809. {
  810. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  811. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  812. options.camera_zoom *= 1 + delta;
  813. down_mouse_x = mouse_x;
  814. down_mouse_y = mouse_y;
  815. break;
  816. }
  817. default:
  818. break;
  819. }
  820. }
  821. return true;
  822. }
  823. bool Viewer::mouse_scroll(float delta_y)
  824. {
  825. scroll_position += delta_y;
  826. if (callback_mouse_scroll)
  827. if (callback_mouse_scroll(*this,delta_y))
  828. return true;
  829. for (unsigned int i = 0; i<plugins.size(); ++i)
  830. if (plugins[i]->mouse_scroll(delta_y))
  831. return true;
  832. // Only zoom if there's actually a change
  833. if(delta_y != 0)
  834. {
  835. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  836. const float min_zoom = 0.1f;
  837. options.camera_zoom = (options.camera_zoom * mult > min_zoom ? options.camera_zoom * mult : min_zoom);
  838. }
  839. return true;
  840. }
  841. void Viewer::draw()
  842. {
  843. using namespace std;
  844. using namespace Eigen;
  845. glClearColor(options.background_color[0],
  846. options.background_color[1],
  847. options.background_color[2],
  848. 1.0f);
  849. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  850. glEnable(GL_DEPTH_TEST);
  851. if (callback_pre_draw)
  852. if (callback_pre_draw(*this))
  853. return;
  854. for (unsigned int i = 0; i<plugins.size(); ++i)
  855. if (plugins[i]->pre_draw())
  856. return;
  857. /* Bind and potentially refresh mesh/line/point data */
  858. if (data.dirty)
  859. {
  860. opengl.set_data(data, options.face_based, options.invert_normals);
  861. data.dirty = OpenGL_state::DIRTY_NONE;
  862. }
  863. opengl.bind_mesh();
  864. // Initialize uniform
  865. glViewport(0, 0, width, height);
  866. model = Eigen::Matrix4f::Identity();
  867. view = Eigen::Matrix4f::Identity();
  868. proj = Eigen::Matrix4f::Identity();
  869. // Set view
  870. view = lookAt(Eigen::Vector3f(options.camera_eye[0], options.camera_eye[1], options.camera_eye[2]),
  871. Eigen::Vector3f(options.camera_center[0], options.camera_center[1], options.camera_center[2]),
  872. Eigen::Vector3f(options.camera_up[0], options.camera_up[1], options.camera_up[2]));
  873. // Set projection
  874. if (options.orthographic)
  875. {
  876. float length = (options.camera_eye - options.camera_center).norm();
  877. float h = tan(options.camera_view_angle/360.0 * M_PI) * (length);
  878. proj = ortho(-h*width/height, h*width/height, -h, h, options.camera_dnear, options.camera_dfar);
  879. }
  880. else
  881. {
  882. float fH = tan(options.camera_view_angle / 360.0 * M_PI) * options.camera_dnear;
  883. float fW = fH * (double)width/(double)height;
  884. proj = frustum(-fW, fW, -fH, fH, options.camera_dnear, options.camera_dfar);
  885. }
  886. // end projection
  887. // Set model transformation
  888. float mat[16];
  889. igl::quat_to_mat(options.trackball_angle.data(), mat);
  890. for (unsigned i=0;i<4;++i)
  891. for (unsigned j=0;j<4;++j)
  892. model(i,j) = mat[i+4*j];
  893. model = scale(model, Eigen::Vector3f(options.camera_zoom,options.camera_zoom,options.camera_zoom));
  894. model = scale(model, Eigen::Vector3f(options.model_zoom,options.model_zoom,options.model_zoom));
  895. model = translate(model, Eigen::Vector3f(options.model_translation[0],options.model_translation[1],options.model_translation[2]));
  896. // Send transformations to the GPU
  897. GLint modeli = opengl.shader_mesh.uniform("model");
  898. GLint viewi = opengl.shader_mesh.uniform("view");
  899. GLint proji = opengl.shader_mesh.uniform("proj");
  900. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  901. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  902. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  903. // Light parameters
  904. GLint specular_exponenti = opengl.shader_mesh.uniform("specular_exponent");
  905. GLint light_position_worldi = opengl.shader_mesh.uniform("light_position_world");
  906. GLint lighting_factori = opengl.shader_mesh.uniform("lighting_factor");
  907. GLint fixed_colori = opengl.shader_mesh.uniform("fixed_color");
  908. GLint texture_factori = opengl.shader_mesh.uniform("texture_factor");
  909. glUniform1f(specular_exponenti, options.shininess);
  910. Vector3f rev_light = -1.*options.light_position;
  911. glUniform3fv(light_position_worldi, 1, rev_light.data());
  912. glUniform1f(lighting_factori, options.lighting_factor); // enables lighting
  913. glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);
  914. if (data.V.rows()>0)
  915. {
  916. // Render fill
  917. if (options.show_faces)
  918. {
  919. // Texture
  920. glUniform1f(texture_factori, options.show_texture ? 1.0f : 0.0f);
  921. opengl.draw_mesh(true);
  922. glUniform1f(texture_factori, 0.0f);
  923. }
  924. // Render wireframe
  925. if (options.show_lines)
  926. {
  927. glLineWidth(options.line_width);
  928. glUniform4f(fixed_colori, options.line_color[0], options.line_color[1],
  929. options.line_color[2], 1.0f);
  930. opengl.draw_mesh(false);
  931. glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);
  932. }
  933. if (options.show_vertid)
  934. {
  935. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  936. for (int i=0; i<data.V.rows(); ++i)
  937. __font_renderer.DrawText(data.V.row(i), data.V_normals.row(i), to_string(i));
  938. __font_renderer.EndDraw();
  939. }
  940. if (options.show_faceid)
  941. {
  942. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  943. for (int i=0; i<data.F.rows(); ++i)
  944. {
  945. Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
  946. for (int j=0;j<data.F.cols();++j)
  947. p += data.V.row(data.F(i,j));
  948. p /= data.F.cols();
  949. __font_renderer.DrawText(p, data.F_normals.row(i), to_string(i));
  950. }
  951. __font_renderer.EndDraw();
  952. }
  953. }
  954. if (options.show_overlay)
  955. {
  956. if (options.show_overlay_depth)
  957. glEnable(GL_DEPTH_TEST);
  958. else
  959. glDisable(GL_DEPTH_TEST);
  960. if (data.lines.rows() > 0)
  961. {
  962. opengl.bind_overlay_lines();
  963. modeli = opengl.shader_overlay_lines.uniform("model");
  964. viewi = opengl.shader_overlay_lines.uniform("view");
  965. proji = opengl.shader_overlay_lines.uniform("proj");
  966. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  967. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  968. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  969. // This must be enabled, otherwise glLineWidth has no effect
  970. glEnable(GL_LINE_SMOOTH);
  971. glLineWidth(options.line_width);
  972. opengl.draw_overlay_lines();
  973. }
  974. if (data.points.rows() > 0)
  975. {
  976. opengl.bind_overlay_points();
  977. modeli = opengl.shader_overlay_points.uniform("model");
  978. viewi = opengl.shader_overlay_points.uniform("view");
  979. proji = opengl.shader_overlay_points.uniform("proj");
  980. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  981. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  982. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  983. glPointSize(options.point_size);
  984. opengl.draw_overlay_points();
  985. }
  986. if (data.labels_positions.rows() > 0)
  987. {
  988. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  989. for (int i=0; i<data.labels_positions.rows(); ++i)
  990. __font_renderer.DrawText(data.labels_positions.row(i), Eigen::Vector3d(0.0,0.0,0.0),
  991. data.labels_strings[i]);
  992. __font_renderer.EndDraw();
  993. }
  994. glEnable(GL_DEPTH_TEST);
  995. }
  996. if (callback_post_draw)
  997. if (callback_post_draw(*this))
  998. return;
  999. for (unsigned int i = 0; i<plugins.size(); ++i)
  1000. if (plugins[i]->post_draw())
  1001. break;
  1002. TwDraw();
  1003. }
  1004. bool Viewer::save_scene()
  1005. {
  1006. #ifdef ENABLE_XML_SERIALIZATION
  1007. string fname = igl::file_dialog_save();
  1008. if (fname.length() == 0)
  1009. return false;
  1010. ::igl::XMLSerializer serializer("Viewer");
  1011. serializer.Add(data,"Data");
  1012. serializer.Add(options,"Options");
  1013. if (plugin_manager)
  1014. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1015. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1016. serializer.Save(fname.c_str(),true);
  1017. #endif
  1018. return true;
  1019. }
  1020. bool Viewer::load_scene()
  1021. {
  1022. #ifdef ENABLE_XML_SERIALIZATION
  1023. string fname = igl::file_dialog_open();
  1024. if (fname.length() == 0)
  1025. return false;
  1026. ::igl::XMLSerializer serializer("Viewer");
  1027. serializer.Add(data,"Data");
  1028. serializer.Add(options,"Options");
  1029. if (plugin_manager)
  1030. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1031. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1032. serializer.Load(fname.c_str());
  1033. #endif
  1034. return true;
  1035. }
  1036. void Viewer::align_camera_center()
  1037. {
  1038. get_scale_and_shift_to_fit_mesh(data.V,data.F,options.model_zoom,options.model_translation);
  1039. data.object_scale = (data.V.colwise().maxCoeff() - data.V.colwise().minCoeff()).norm();
  1040. }
  1041. void Viewer::resize(int w, int h)
  1042. {
  1043. width = w;
  1044. height = h;
  1045. viewport = Eigen::Vector4f(0,0,width,height);
  1046. }
  1047. void Viewer::get_scale_and_shift_to_fit_mesh(
  1048. const Eigen::MatrixXd& V,
  1049. const Eigen::MatrixXi& F,
  1050. float& zoom,
  1051. Eigen::Vector3f& shift)
  1052. {
  1053. if (V.rows() == 0)
  1054. return;
  1055. //Compute mesh centroid
  1056. Eigen::SparseMatrix<double> M;
  1057. igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);
  1058. const auto & MV = M*V;
  1059. Eigen::RowVector3d centroid = MV.colwise().sum()/M.diagonal().sum();
  1060. Eigen::RowVector3d min_point = V.colwise().minCoeff();
  1061. Eigen::RowVector3d max_point = V.colwise().maxCoeff();
  1062. shift = -centroid.cast<float>();
  1063. double x_scale = fabs(max_point[0] - min_point[0]);
  1064. double y_scale = fabs(max_point[1] - min_point[1]);
  1065. double z_scale = fabs(max_point[2] - min_point[2]);
  1066. zoom = 2.0/ std::max(z_scale,std::max(x_scale,y_scale));
  1067. }
  1068. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  1069. {
  1070. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->options.trackball_angle;
  1071. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->options.trackball_angle.data());
  1072. }
  1073. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  1074. {
  1075. static_cast<Viewer *>(clientData)->align_camera_center();
  1076. }
  1077. void TW_CALL Viewer::save_scene_cb(void *clientData)
  1078. {
  1079. static_cast<Viewer *>(clientData)->save_scene();
  1080. }
  1081. void TW_CALL Viewer::load_scene_cb(void *clientData)
  1082. {
  1083. static_cast<Viewer *>(clientData)->load_scene();
  1084. }
  1085. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  1086. {
  1087. Viewer *viewer = static_cast<Viewer *>(clientData);
  1088. viewer->data.dirty |= OpenGL_state::DIRTY_NORMAL;
  1089. viewer->options.invert_normals = *((bool *) param);
  1090. }
  1091. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  1092. {
  1093. *((bool *) param) = static_cast<Viewer *>(clientData)->options.invert_normals;
  1094. }
  1095. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  1096. {
  1097. Viewer *viewer = static_cast<Viewer *>(clientData);
  1098. viewer->set_face_based(*((bool *) param));
  1099. }
  1100. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  1101. {
  1102. *((bool *) param) = static_cast<Viewer *>(clientData)->options.face_based;
  1103. }
  1104. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  1105. {
  1106. std::string fname = igl::file_dialog_open();
  1107. if (fname.length() == 0)
  1108. return;
  1109. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  1110. }
  1111. // Serialization
  1112. void Viewer::Options::InitSerialization()
  1113. {
  1114. #ifdef ENABLE_XML_SERIALIZATION
  1115. xmlSerializer->Add(shininess, "shininess");
  1116. xmlSerializer->Add(background_color, "background_color");
  1117. xmlSerializer->Add(line_color, "line_color");
  1118. xmlSerializer->Add(light_position, "light_position");
  1119. xmlSerializer->Add(lighting_factor, "lighting_factor");
  1120. xmlSerializer->Add(trackball_angle, "trackball_angle");
  1121. xmlSerializer->Add(model_zoom, "model_zoom");
  1122. xmlSerializer->Add(model_translation, "model_translation");
  1123. xmlSerializer->Add(model_zoom_uv, "model_zoom_uv");
  1124. xmlSerializer->Add(model_translation_uv, "model_translation_uv");
  1125. xmlSerializer->Add(camera_zoom, "camera_zoom");
  1126. xmlSerializer->Add(orthographic, "orthographic");
  1127. xmlSerializer->Add(camera_eye, "camera_eye");
  1128. xmlSerializer->Add(camera_up, "camera_up");
  1129. xmlSerializer->Add(camera_center, "camera_center");
  1130. xmlSerializer->Add(camera_view_angle, "camera_view_angle");
  1131. xmlSerializer->Add(camera_dnear, "camera_dnear");
  1132. xmlSerializer->Add(camera_dfar, "camera_dfar");
  1133. xmlSerializer->Add(show_overlay, "show_overlay");
  1134. xmlSerializer->Add(show_overlay_depth, "show_overlay_depth");
  1135. xmlSerializer->Add(show_texture, "show_texture");
  1136. xmlSerializer->Add(show_faces, "show_faces");
  1137. xmlSerializer->Add(show_lines, "show_lines");
  1138. xmlSerializer->Add(show_vertid, "show_vertid");
  1139. xmlSerializer->Add(show_faceid, "show_faceid");
  1140. xmlSerializer->Add(point_size, "point_size");
  1141. xmlSerializer->Add(line_width, "line_width");
  1142. xmlSerializer->Add(invert_normals, "invert_normals");
  1143. xmlSerializer->Add(face_based, "face_based");
  1144. #endif
  1145. }
  1146. void Viewer::set_face_based(bool newvalue)
  1147. {
  1148. if (options.face_based != newvalue)
  1149. {
  1150. options.face_based = newvalue;
  1151. data.dirty = OpenGL_state::DIRTY_ALL;
  1152. }
  1153. }
  1154. // Helpers that draws the most common meshes
  1155. void Viewer::set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)
  1156. {
  1157. using namespace std;
  1158. Eigen::MatrixXd V_temp;
  1159. // If V only has two columns, pad with a column of zeros
  1160. if (V.cols() == 2)
  1161. {
  1162. V_temp = Eigen::MatrixXd::Zero(V.rows(),3);
  1163. V_temp.block(0,0,V.rows(),2) = V;
  1164. }
  1165. else
  1166. V_temp = V;
  1167. if (data.V.rows() == 0 && data.F.rows() == 0)
  1168. {
  1169. clear_mesh();
  1170. data.V = V_temp;
  1171. data.F = F;
  1172. compute_normals();
  1173. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  1174. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  1175. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  1176. grid_texture();
  1177. align_camera_center();
  1178. }
  1179. else
  1180. {
  1181. if (data.V.rows() == V.rows() && data.F.rows() == F.rows())
  1182. {
  1183. data.V = V_temp;
  1184. data.F = F;
  1185. align_camera_center();
  1186. }
  1187. else
  1188. cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
  1189. }
  1190. data.dirty |= OpenGL_state::DIRTY_FACE | OpenGL_state::DIRTY_POSITION;
  1191. }
  1192. void Viewer::set_vertices(const Eigen::MatrixXd& V)
  1193. {
  1194. data.V = V;
  1195. assert(data.F.size() == 0 || data.F.maxCoeff() < data.V.rows());
  1196. data.dirty |= OpenGL_state::DIRTY_POSITION;
  1197. }
  1198. void Viewer::set_normals(const Eigen::MatrixXd& N)
  1199. {
  1200. using namespace std;
  1201. if (N.rows() == data.V.rows())
  1202. {
  1203. set_face_based(false);
  1204. data.V_normals = N;
  1205. }
  1206. else if (N.rows() == data.F.rows() || N.rows() == data.F.rows()*3)
  1207. {
  1208. set_face_based(true);
  1209. data.F_normals = N;
  1210. }
  1211. else
  1212. cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex.";
  1213. data.dirty |= OpenGL_state::DIRTY_NORMAL;
  1214. }
  1215. void Viewer::set_colors(const Eigen::MatrixXd &C)
  1216. {
  1217. using namespace std;
  1218. using namespace Eigen;
  1219. // Ambient color should be darker color
  1220. const auto ambient = [](const MatrixXd & C)->MatrixXd
  1221. {
  1222. return 0.1*C;
  1223. };
  1224. // Specular color should be a less saturated and darker color: dampened
  1225. // highlights
  1226. const auto specular = [](const MatrixXd & C)->MatrixXd
  1227. {
  1228. const double grey = 0.3;
  1229. return grey+0.1*(C.array()-grey);
  1230. };
  1231. if (C.rows() == 1)
  1232. {
  1233. for (unsigned i=0;i<data.V_material_diffuse.rows();++i)
  1234. {
  1235. data.V_material_diffuse.row(i) = C.row(0);
  1236. }
  1237. data.V_material_ambient = ambient(data.V_material_diffuse);
  1238. data.V_material_specular = specular(data.V_material_diffuse);
  1239. for (unsigned i=0;i<data.F_material_diffuse.rows();++i)
  1240. {
  1241. data.F_material_diffuse.row(i) = C.row(0);
  1242. }
  1243. data.F_material_ambient = ambient(data.F_material_diffuse);
  1244. data.F_material_specular = specular(data.F_material_diffuse);
  1245. }
  1246. else if (C.rows() == data.V.rows())
  1247. {
  1248. set_face_based(false);
  1249. data.V_material_diffuse = C;
  1250. data.V_material_ambient = ambient(data.V_material_diffuse);
  1251. data.V_material_specular = specular(data.V_material_diffuse);
  1252. }
  1253. else if (C.rows() == data.F.rows())
  1254. {
  1255. set_face_based(true);
  1256. data.F_material_diffuse = C;
  1257. data.F_material_ambient = ambient(data.F_material_diffuse);
  1258. data.F_material_specular = specular(data.F_material_diffuse);
  1259. }
  1260. else
  1261. cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex.";
  1262. data.dirty |= OpenGL_state::DIRTY_DIFFUSE;
  1263. }
  1264. void Viewer::set_uv(const Eigen::MatrixXd& UV)
  1265. {
  1266. using namespace std;
  1267. if (UV.rows() == data.V.rows())
  1268. {
  1269. set_face_based(false);
  1270. data.V_uv = UV;
  1271. }
  1272. else
  1273. cerr << "ERROR (set_UV): Please provide uv per vertex.";
  1274. data.dirty |= OpenGL_state::DIRTY_UV;
  1275. }
  1276. void Viewer::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
  1277. {
  1278. set_face_based(true);
  1279. data.V_uv = UV_V;
  1280. data.F_uv = UV_F;
  1281. data.dirty |= OpenGL_state::DIRTY_UV;
  1282. }
  1283. void Viewer::set_texture(
  1284. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  1285. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  1286. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
  1287. {
  1288. data.texture_R = R;
  1289. data.texture_G = G;
  1290. data.texture_B = B;
  1291. data.dirty |= OpenGL_state::DIRTY_TEXTURE;
  1292. }
  1293. void Viewer::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C)
  1294. {
  1295. Eigen::MatrixXd P_temp;
  1296. // If P only has two columns, pad with a column of zeros
  1297. if (P.cols() == 2)
  1298. {
  1299. P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
  1300. P_temp.block(0,0,P.rows(),2) = P;
  1301. }
  1302. else
  1303. P_temp = P;
  1304. int lastid = data.points.rows();
  1305. data.points.conservativeResize(data.points.rows() + P_temp.rows(),6);
  1306. for (unsigned i=0; i<P_temp.rows(); ++i)
  1307. data.points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1308. data.dirty |= OpenGL_state::DIRTY_OVERLAY_POINTS;
  1309. }
  1310. void Viewer::set_edges(
  1311. const Eigen::MatrixXd& P,
  1312. const Eigen::MatrixXi& E,
  1313. const Eigen::MatrixXd& C)
  1314. {
  1315. using namespace Eigen;
  1316. data.lines.resize(E.rows(),9);
  1317. assert(C.cols() == 3);
  1318. for(int e = 0;e<E.rows();e++)
  1319. {
  1320. RowVector3d color;
  1321. if(C.size() == 3)
  1322. {
  1323. color<<C;
  1324. }else if(C.rows() == E.rows())
  1325. {
  1326. color<<C.row(e);
  1327. }
  1328. data.lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;
  1329. }
  1330. data.dirty |= OpenGL_state::DIRTY_OVERLAY_LINES;
  1331. }
  1332. void Viewer::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
  1333. {
  1334. Eigen::MatrixXd P1_temp,P2_temp;
  1335. // If P1 only has two columns, pad with a column of zeros
  1336. if (P1.cols() == 2)
  1337. {
  1338. P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);
  1339. P1_temp.block(0,0,P1.rows(),2) = P1;
  1340. P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);
  1341. P2_temp.block(0,0,P2.rows(),2) = P2;
  1342. }
  1343. else
  1344. {
  1345. P1_temp = P1;
  1346. P2_temp = P2;
  1347. }
  1348. int lastid = data.lines.rows();
  1349. data.lines.conservativeResize(data.lines.rows() + P1_temp.rows(),9);
  1350. for (unsigned i=0; i<P1_temp.rows(); ++i)
  1351. data.lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1352. data.dirty |= OpenGL_state::DIRTY_OVERLAY_LINES;
  1353. }
  1354. void Viewer::add_label(const Eigen::VectorXd& P, const std::string& str)
  1355. {
  1356. Eigen::RowVectorXd P_temp;
  1357. // If P only has two columns, pad with a column of zeros
  1358. if (P.size() == 2)
  1359. {
  1360. P_temp = Eigen::RowVectorXd::Zero(3);
  1361. P_temp << P, 0;
  1362. }
  1363. else
  1364. P_temp = P;
  1365. int lastid = data.labels_positions.rows();
  1366. data.labels_positions.conservativeResize(lastid+1, 3);
  1367. data.labels_positions.row(lastid) = P_temp;
  1368. data.labels_strings.push_back(str);
  1369. }
  1370. int Viewer::launch(std::string filename)
  1371. {
  1372. GLFWwindow* window;
  1373. glfwSetErrorCallback(glfw_error_callback);
  1374. if (!glfwInit())
  1375. return EXIT_FAILURE;
  1376. glfwWindowHint(GLFW_SAMPLES, 16);
  1377. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  1378. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  1379. #ifdef __APPLE__
  1380. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  1381. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  1382. #endif
  1383. window = glfwCreateWindow(1280, 800, "IGL Viewer", NULL, NULL);
  1384. if (!window)
  1385. {
  1386. glfwTerminate();
  1387. return EXIT_FAILURE;
  1388. }
  1389. glfwMakeContextCurrent(window);
  1390. #ifndef __APPLE__
  1391. glewExperimental = true;
  1392. GLenum err = glewInit();
  1393. if (GLEW_OK != err)
  1394. {
  1395. /* Problem: glewInit failed, something is seriously wrong. */
  1396. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  1397. }
  1398. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  1399. #endif
  1400. #ifdef DEBUG
  1401. int major, minor, rev;
  1402. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  1403. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  1404. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  1405. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  1406. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  1407. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  1408. #endif
  1409. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  1410. // Initialize AntTweakBar
  1411. TwInit(TW_OPENGL_CORE, NULL);
  1412. // Initialize IGL viewer
  1413. init();
  1414. __viewer = this;
  1415. // Register callbacks
  1416. 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);
  1417. // Handle retina displays (windows and mac)
  1418. int width, height;
  1419. glfwGetFramebufferSize(window, &width, &height);
  1420. int width_window, height_window;
  1421. glfwGetWindowSize(window, &width_window, &height_window);
  1422. highdpi = width/width_window;
  1423. glfw_window_size(window,width_window,height_window);
  1424. opengl.init();
  1425. // Load the mesh passed as input
  1426. if (filename.size() > 0)
  1427. load_mesh_from_file(filename.c_str());
  1428. // Rendering loop
  1429. while (!glfwWindowShouldClose(window))
  1430. {
  1431. double tic = get_seconds();
  1432. draw();
  1433. glfwSwapBuffers(window);
  1434. if(options.is_animating)
  1435. {
  1436. glfwPollEvents();
  1437. // In microseconds
  1438. double duration = 1000000.*(get_seconds()-tic);
  1439. const double min_duration = 1000000./options.animation_max_fps;
  1440. if(duration<min_duration)
  1441. {
  1442. // TODO: windows equivalent
  1443. usleep(min_duration-duration);
  1444. }
  1445. }
  1446. else
  1447. {
  1448. glfwWaitEvents();
  1449. }
  1450. }
  1451. opengl.free();
  1452. __font_renderer.Shut();
  1453. shutdown_plugins();
  1454. glfwDestroyWindow(window);
  1455. glfwTerminate();
  1456. return EXIT_SUCCESS;
  1457. }
  1458. } // end namespace