Viewer.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189
  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 |= 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 |= DIRTY_SPECULAR | DIRTY_DIFFUSE | 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 |= 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 |= 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::OpenGL_state::init()
  842. {
  843. // Mesh: Vertex Array Object & Buffer objects
  844. glGenVertexArrays(1, &vao_mesh);
  845. glBindVertexArray(vao_mesh);
  846. glGenBuffers(1, &vbo_V);
  847. glGenBuffers(1, &vbo_V_normals);
  848. glGenBuffers(1, &vbo_V_ambient);
  849. glGenBuffers(1, &vbo_V_diffuse);
  850. glGenBuffers(1, &vbo_V_specular);
  851. glGenBuffers(1, &vbo_V_uv);
  852. glGenBuffers(1, &vbo_F);
  853. glGenTextures(1, &vbo_tex);
  854. // Line overlay
  855. glGenVertexArrays(1, &vao_overlay_lines);
  856. glBindVertexArray(vao_overlay_lines);
  857. glGenBuffers(1, &vbo_lines_F);
  858. glGenBuffers(1, &vbo_lines_V);
  859. glGenBuffers(1, &vbo_lines_V_colors);
  860. // Point overlay
  861. glGenVertexArrays(1, &vao_overlay_points);
  862. glBindVertexArray(vao_overlay_points);
  863. glGenBuffers(1, &vbo_points_F);
  864. glGenBuffers(1, &vbo_points_V);
  865. glGenBuffers(1, &vbo_points_V_colors);
  866. dirty = DIRTY_ALL;
  867. }
  868. void Viewer::OpenGL_state::free()
  869. {
  870. glDeleteVertexArrays(1, &vao_mesh);
  871. glDeleteVertexArrays(1, &vao_overlay_lines);
  872. glDeleteVertexArrays(1, &vao_overlay_points);
  873. glDeleteBuffers(1, &vbo_V);
  874. glDeleteBuffers(1, &vbo_V_normals);
  875. glDeleteBuffers(1, &vbo_V_ambient);
  876. glDeleteBuffers(1, &vbo_V_diffuse);
  877. glDeleteBuffers(1, &vbo_V_specular);
  878. glDeleteBuffers(1, &vbo_V_uv);
  879. glDeleteBuffers(1, &vbo_F);
  880. glDeleteBuffers(1, &vbo_lines_F);
  881. glDeleteBuffers(1, &vbo_lines_V);
  882. glDeleteBuffers(1, &vbo_lines_V_colors);
  883. glDeleteBuffers(1, &vbo_points_F);
  884. glDeleteBuffers(1, &vbo_points_V);
  885. glDeleteBuffers(1, &vbo_points_V_colors);
  886. glDeleteTextures(1, &vbo_tex);
  887. }
  888. void Viewer::OpenGL_state::set_data(const igl::ViewerData &data, bool face_based, bool invert_normals)
  889. {
  890. bool per_corner_uv = (data.F_uv.rows() == data.F.rows());
  891. bool per_corner_normals = (data.F_normals.rows() == 3 * data.F.rows());
  892. dirty |= data.dirty;
  893. if (!face_based)
  894. {
  895. if (!per_corner_uv)
  896. {
  897. // Vertex positions
  898. if (dirty & DIRTY_POSITION)
  899. V_vbo = (data.V.transpose()).cast<float>();
  900. // Vertex normals
  901. if (dirty & DIRTY_NORMAL)
  902. {
  903. V_normals_vbo = (data.V_normals.transpose()).cast<float>();
  904. if (invert_normals)
  905. V_normals_vbo = -V_normals_vbo;
  906. }
  907. // Per-vertex material settings
  908. if (dirty & DIRTY_AMBIENT)
  909. V_ambient_vbo = (data.V_material_ambient.transpose()).cast<float>();
  910. if (dirty & DIRTY_DIFFUSE)
  911. V_diffuse_vbo = (data.V_material_diffuse.transpose()).cast<float>();
  912. if (dirty & DIRTY_SPECULAR)
  913. V_specular_vbo = (data.V_material_specular.transpose()).cast<float>();
  914. // Face indices
  915. if (dirty & DIRTY_FACE)
  916. F_vbo = (data.F.transpose()).cast<unsigned>();
  917. // Texture coordinates
  918. if (dirty & DIRTY_UV)
  919. V_uv_vbo = (data.V_uv.transpose()).cast<float>();
  920. }
  921. else
  922. {
  923. // Per vertex properties with per corner UVs
  924. if (dirty & DIRTY_POSITION)
  925. {
  926. V_vbo.resize(3,data.F.rows()*3);
  927. for (unsigned i=0; i<data.F.rows();++i)
  928. for (unsigned j=0;j<3;++j)
  929. V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
  930. }
  931. if (dirty & DIRTY_AMBIENT)
  932. {
  933. V_ambient_vbo.resize(3,data.F.rows()*3);
  934. for (unsigned i=0; i<data.F.rows();++i)
  935. for (unsigned j=0;j<3;++j)
  936. V_ambient_vbo.col (i*3+j) = data.V_material_ambient.row(data.F(i,j)).transpose().cast<float>();
  937. }
  938. if (dirty & DIRTY_DIFFUSE)
  939. {
  940. V_diffuse_vbo.resize(3,data.F.rows()*3);
  941. for (unsigned i=0; i<data.F.rows();++i)
  942. for (unsigned j=0;j<3;++j)
  943. V_diffuse_vbo.col (i*3+j) = data.V_material_diffuse.row(data.F(i,j)).transpose().cast<float>();
  944. }
  945. if (dirty & DIRTY_SPECULAR)
  946. {
  947. V_specular_vbo.resize(3,data.F.rows()*3);
  948. for (unsigned i=0; i<data.F.rows();++i)
  949. for (unsigned j=0;j<3;++j)
  950. V_specular_vbo.col(i*3+j) = data.V_material_specular.row(data.F(i,j)).transpose().cast<float>();
  951. }
  952. if (dirty & DIRTY_NORMAL)
  953. {
  954. V_normals_vbo.resize(3,data.F.rows()*3);
  955. for (unsigned i=0; i<data.F.rows();++i)
  956. for (unsigned j=0;j<3;++j)
  957. V_normals_vbo.col (i*3+j) = data.V_normals.row(data.F(i,j)).transpose().cast<float>();
  958. if (invert_normals)
  959. V_normals_vbo = -V_normals_vbo;
  960. }
  961. if (dirty & DIRTY_FACE)
  962. {
  963. F_vbo.resize(3,data.F.rows());
  964. for (unsigned i=0; i<data.F.rows();++i)
  965. F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
  966. }
  967. if (dirty & DIRTY_UV)
  968. {
  969. V_uv_vbo.resize(2,data.F.rows()*3);
  970. for (unsigned i=0; i<data.F.rows();++i)
  971. for (unsigned j=0;j<3;++j)
  972. V_uv_vbo.col(i*3+j) = data.V_uv.row(data.F(i,j)).transpose().cast<float>();
  973. }
  974. }
  975. }
  976. else
  977. {
  978. if (dirty & DIRTY_POSITION)
  979. {
  980. V_vbo.resize(3,data.F.rows()*3);
  981. for (unsigned i=0; i<data.F.rows();++i)
  982. for (unsigned j=0;j<3;++j)
  983. V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
  984. }
  985. if (dirty & DIRTY_AMBIENT)
  986. {
  987. V_ambient_vbo.resize(3,data.F.rows()*3);
  988. for (unsigned i=0; i<data.F.rows();++i)
  989. for (unsigned j=0;j<3;++j)
  990. V_ambient_vbo.col (i*3+j) = data.F_material_ambient.row(i).transpose().cast<float>();
  991. }
  992. if (dirty & DIRTY_DIFFUSE)
  993. {
  994. V_diffuse_vbo.resize(3,data.F.rows()*3);
  995. for (unsigned i=0; i<data.F.rows();++i)
  996. for (unsigned j=0;j<3;++j)
  997. V_diffuse_vbo.col (i*3+j) = data.F_material_diffuse.row(i).transpose().cast<float>();
  998. }
  999. if (dirty & DIRTY_SPECULAR)
  1000. {
  1001. V_specular_vbo.resize(3,data.F.rows()*3);
  1002. for (unsigned i=0; i<data.F.rows();++i)
  1003. for (unsigned j=0;j<3;++j)
  1004. V_specular_vbo.col(i*3+j) = data.F_material_specular.row(i).transpose().cast<float>();
  1005. }
  1006. if (dirty & DIRTY_NORMAL)
  1007. {
  1008. V_normals_vbo.resize(3,data.F.rows()*3);
  1009. for (unsigned i=0; i<data.F.rows();++i)
  1010. for (unsigned j=0;j<3;++j)
  1011. V_normals_vbo.col (i*3+j) =
  1012. per_corner_normals ?
  1013. data.F_normals.row(i*3+j).transpose().cast<float>() :
  1014. data.F_normals.row(i).transpose().cast<float>();
  1015. if (invert_normals)
  1016. V_normals_vbo = -V_normals_vbo;
  1017. }
  1018. if (dirty & DIRTY_FACE)
  1019. {
  1020. F_vbo.resize(3,data.F.rows());
  1021. for (unsigned i=0; i<data.F.rows();++i)
  1022. F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
  1023. }
  1024. if (dirty & DIRTY_UV)
  1025. {
  1026. V_uv_vbo.resize(2,data.F.rows()*3);
  1027. for (unsigned i=0; i<data.F.rows();++i)
  1028. for (unsigned j=0;j<3;++j)
  1029. V_uv_vbo.col(i*3+j) = data.V_uv.row(per_corner_uv ? data.F_uv(i,j) : data.F(i,j)).transpose().cast<float>();
  1030. }
  1031. }
  1032. if (dirty & DIRTY_TEXTURE)
  1033. {
  1034. tex_u = data.texture_R.rows();
  1035. tex_v = data.texture_R.cols();
  1036. tex.resize(data.texture_R.size()*3);
  1037. for (unsigned i=0;i<data.texture_R.size();++i)
  1038. {
  1039. tex(i*3+0) = data.texture_R(i);
  1040. tex(i*3+1) = data.texture_G(i);
  1041. tex(i*3+2) = data.texture_B(i);
  1042. }
  1043. }
  1044. if (dirty & DIRTY_OVERLAY_LINES)
  1045. {
  1046. lines_V_vbo.resize(3, data.lines.rows()*2);
  1047. lines_V_colors_vbo.resize(3, data.lines.rows()*2);
  1048. lines_F_vbo.resize(1, data.lines.rows()*2);
  1049. for (unsigned i=0; i<data.lines.rows();++i)
  1050. {
  1051. lines_V_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 0).transpose().cast<float>();
  1052. lines_V_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 3).transpose().cast<float>();
  1053. lines_V_colors_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
  1054. lines_V_colors_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
  1055. lines_F_vbo(2*i+0) = 2*i+0;
  1056. lines_F_vbo(2*i+1) = 2*i+1;
  1057. }
  1058. }
  1059. if (dirty & DIRTY_OVERLAY_POINTS)
  1060. {
  1061. points_V_vbo.resize(3, data.points.rows());
  1062. points_V_colors_vbo.resize(3, data.points.rows());
  1063. points_F_vbo.resize(1, data.points.rows());
  1064. for (unsigned i=0; i<data.points.rows();++i)
  1065. {
  1066. points_V_vbo.col(i) = data.points.block<1, 3>(i, 0).transpose().cast<float>();
  1067. points_V_colors_vbo.col(i) = data.points.block<1, 3>(i, 3).transpose().cast<float>();
  1068. points_F_vbo(i) = i;
  1069. }
  1070. }
  1071. }
  1072. void Viewer::OpenGL_state::bind_mesh()
  1073. {
  1074. glBindVertexArray(vao_mesh);
  1075. shader_mesh.bind();
  1076. shader_mesh.bindVertexAttribArray("position", vbo_V, V_vbo, dirty & DIRTY_POSITION);
  1077. shader_mesh.bindVertexAttribArray("normal", vbo_V_normals, V_normals_vbo, dirty & DIRTY_NORMAL);
  1078. shader_mesh.bindVertexAttribArray("Ka", vbo_V_ambient, V_ambient_vbo, dirty & DIRTY_AMBIENT);
  1079. shader_mesh.bindVertexAttribArray("Kd", vbo_V_diffuse, V_diffuse_vbo, dirty & DIRTY_DIFFUSE);
  1080. shader_mesh.bindVertexAttribArray("Ks", vbo_V_specular, V_specular_vbo, dirty & DIRTY_SPECULAR);
  1081. shader_mesh.bindVertexAttribArray("texcoord", vbo_V_uv, V_uv_vbo, dirty & DIRTY_UV);
  1082. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_F);
  1083. if (dirty & DIRTY_FACE)
  1084. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*F_vbo.size(), F_vbo.data(), GL_DYNAMIC_DRAW);
  1085. glActiveTexture(GL_TEXTURE0);
  1086. glBindTexture(GL_TEXTURE_2D, vbo_tex);
  1087. if (dirty & DIRTY_TEXTURE)
  1088. {
  1089. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  1090. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  1091. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1092. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1093. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_u, tex_v, 0, GL_RGB, GL_UNSIGNED_BYTE, tex.data());
  1094. }
  1095. glUniform1i(shader_mesh.uniform("tex"), 0);
  1096. dirty &= ~DIRTY_MESH;
  1097. }
  1098. void Viewer::OpenGL_state::bind_overlay_lines()
  1099. {
  1100. bool is_dirty = dirty & DIRTY_OVERLAY_LINES;
  1101. glBindVertexArray(vao_overlay_lines);
  1102. shader_overlay_lines.bind();
  1103. shader_overlay_lines.bindVertexAttribArray("position", vbo_lines_V, lines_V_vbo, is_dirty);
  1104. shader_overlay_lines.bindVertexAttribArray("color", vbo_lines_V_colors, lines_V_colors_vbo, is_dirty);
  1105. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_lines_F);
  1106. if (is_dirty)
  1107. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*lines_F_vbo.size(), lines_F_vbo.data(), GL_DYNAMIC_DRAW);
  1108. dirty &= ~DIRTY_OVERLAY_LINES;
  1109. }
  1110. void Viewer::OpenGL_state::bind_overlay_points()
  1111. {
  1112. bool is_dirty = dirty & DIRTY_OVERLAY_POINTS;
  1113. glBindVertexArray(vao_overlay_points);
  1114. shader_overlay_points.bind();
  1115. shader_overlay_points.bindVertexAttribArray("position", vbo_points_V, points_V_vbo, is_dirty);
  1116. shader_overlay_points.bindVertexAttribArray("color", vbo_points_V_colors, points_V_colors_vbo, is_dirty);
  1117. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_points_F);
  1118. if (is_dirty)
  1119. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*points_F_vbo.size(), points_F_vbo.data(), GL_DYNAMIC_DRAW);
  1120. dirty &= ~DIRTY_OVERLAY_POINTS;
  1121. }
  1122. void Viewer::OpenGL_state::draw_mesh(bool solid)
  1123. {
  1124. glPolygonMode(GL_FRONT_AND_BACK, solid ? GL_FILL : GL_LINE);
  1125. /* Avoid Z-buffer fighting between filled triangles & wireframe lines */
  1126. if (solid)
  1127. {
  1128. glEnable(GL_POLYGON_OFFSET_FILL);
  1129. glPolygonOffset(1.0, 1.0);
  1130. }
  1131. glDrawElements(GL_TRIANGLES, 3*F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1132. glDisable(GL_POLYGON_OFFSET_FILL);
  1133. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1134. }
  1135. void Viewer::OpenGL_state::draw_overlay_lines()
  1136. {
  1137. glDrawElements(GL_LINES, lines_F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1138. }
  1139. void Viewer::OpenGL_state::draw_overlay_points()
  1140. {
  1141. glDrawElements(GL_POINTS, points_F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1142. }
  1143. void Viewer::init_opengl()
  1144. {
  1145. std::string mesh_vertex_shader_string =
  1146. "#version 150\n"
  1147. "uniform mat4 model;"
  1148. "uniform mat4 view;"
  1149. "uniform mat4 proj;"
  1150. "in vec3 position;"
  1151. "in vec3 normal;"
  1152. "out vec3 position_eye;"
  1153. "out vec3 normal_eye;"
  1154. "in vec3 Ka;"
  1155. "in vec3 Kd;"
  1156. "in vec3 Ks;"
  1157. "in vec2 texcoord;"
  1158. "out vec2 texcoordi;"
  1159. "out vec3 Kai;"
  1160. "out vec3 Kdi;"
  1161. "out vec3 Ksi;"
  1162. "void main()"
  1163. "{"
  1164. " position_eye = vec3 (view * model * vec4 (position, 1.0));"
  1165. " normal_eye = vec3 (view * model * vec4 (normal, 0.0));"
  1166. " normal_eye = normalize(normal_eye);"
  1167. " gl_Position = proj * vec4 (position_eye, 1.0);" //proj * view * model * vec4(position, 1.0);"
  1168. " Kai = Ka;"
  1169. " Kdi = Kd;"
  1170. " Ksi = Ks;"
  1171. " texcoordi = texcoord;"
  1172. "}";
  1173. std::string mesh_fragment_shader_string =
  1174. "#version 150\n"
  1175. "uniform mat4 model;"
  1176. "uniform mat4 view;"
  1177. "uniform mat4 proj;"
  1178. "uniform vec4 fixed_color;"
  1179. "in vec3 position_eye;"
  1180. "in vec3 normal_eye;"
  1181. "uniform vec3 light_position_world;"
  1182. "vec3 Ls = vec3 (1, 1, 1);"
  1183. "vec3 Ld = vec3 (1, 1, 1);"
  1184. "vec3 La = vec3 (1, 1, 1);"
  1185. "in vec3 Ksi;"
  1186. "in vec3 Kdi;"
  1187. "in vec3 Kai;"
  1188. "in vec2 texcoordi;"
  1189. "uniform sampler2D tex;"
  1190. "uniform float specular_exponent;"
  1191. "uniform float lighting_factor;"
  1192. "uniform float texture_factor;"
  1193. "out vec4 outColor;"
  1194. "void main()"
  1195. "{"
  1196. "vec3 Ia = La * Kai;" // ambient intensity
  1197. "vec3 light_position_eye = vec3 (view * vec4 (light_position_world, 1.0));"
  1198. "vec3 distance_to_light_eye = light_position_eye - position_eye;"
  1199. "vec3 direction_to_light_eye = normalize (distance_to_light_eye);"
  1200. "float dot_prod = dot (direction_to_light_eye, normal_eye);"
  1201. "dot_prod = max (dot_prod, 0.0);"
  1202. "vec3 Id = Ld * Kdi * dot_prod;" // Diffuse intensity
  1203. "vec3 reflection_eye = reflect (-direction_to_light_eye, normal_eye);"
  1204. "vec3 surface_to_viewer_eye = normalize (-position_eye);"
  1205. "float dot_prod_specular = dot (reflection_eye, surface_to_viewer_eye);"
  1206. "dot_prod_specular = max (dot_prod_specular, 0.0);"
  1207. "float specular_factor = pow (dot_prod_specular, specular_exponent);"
  1208. "vec3 Is = Ls * Ksi * specular_factor;" // specular intensity
  1209. "vec4 color = vec4(lighting_factor * (Is + Id) + Ia, 1.0) + vec4((1.0-lighting_factor) * Kdi,1.0);"
  1210. "outColor = mix(vec4(1,1,1,1), texture(tex, texcoordi), texture_factor) * color;"
  1211. "if (fixed_color != vec4(0.0)) outColor = fixed_color;"
  1212. "}";
  1213. std::string overlay_vertex_shader_string =
  1214. "#version 150\n"
  1215. "uniform mat4 model;"
  1216. "uniform mat4 view;"
  1217. "uniform mat4 proj;"
  1218. "in vec3 position;"
  1219. "in vec3 color;"
  1220. "out vec3 color_frag;"
  1221. "void main()"
  1222. "{"
  1223. " gl_Position = proj * view * model * vec4 (position, 1.0);"
  1224. " color_frag = color;"
  1225. "}";
  1226. std::string overlay_fragment_shader_string =
  1227. "#version 150\n"
  1228. "in vec3 color_frag;"
  1229. "out vec4 outColor;"
  1230. "void main()"
  1231. "{"
  1232. " outColor = vec4(color_frag, 1.0);"
  1233. "}";
  1234. std::string overlay_point_fragment_shader_string =
  1235. "#version 150\n"
  1236. "in vec3 color_frag;"
  1237. "out vec4 outColor;"
  1238. "void main()"
  1239. "{"
  1240. " if (length(gl_PointCoord - vec2(0.5)) > 0.5)"
  1241. " discard;"
  1242. " outColor = vec4(color_frag, 1.0);"
  1243. "}";
  1244. opengl.init();
  1245. opengl.shader_mesh.init(mesh_vertex_shader_string,
  1246. mesh_fragment_shader_string, "outColor");
  1247. opengl.shader_overlay_lines.init(overlay_vertex_shader_string,
  1248. overlay_fragment_shader_string, "outColor");
  1249. opengl.shader_overlay_points.init(overlay_vertex_shader_string,
  1250. overlay_point_fragment_shader_string, "outColor");
  1251. }
  1252. void Viewer::free_opengl()
  1253. {
  1254. opengl.shader_mesh.free();
  1255. opengl.shader_overlay_lines.free();
  1256. opengl.shader_overlay_points.free();
  1257. opengl.free();
  1258. __font_renderer.Shut();
  1259. }
  1260. void Viewer::draw()
  1261. {
  1262. using namespace std;
  1263. using namespace Eigen;
  1264. glClearColor(options.background_color[0],
  1265. options.background_color[1],
  1266. options.background_color[2],
  1267. 1.0f);
  1268. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1269. glEnable(GL_DEPTH_TEST);
  1270. if (callback_pre_draw)
  1271. if (callback_pre_draw(*this))
  1272. return;
  1273. for (unsigned int i = 0; i<plugins.size(); ++i)
  1274. if (plugins[i]->pre_draw())
  1275. return;
  1276. /* Bind and potentially refresh mesh/line/point data */
  1277. if (data.dirty)
  1278. {
  1279. opengl.set_data(data, options.face_based, options.invert_normals);
  1280. data.dirty = DIRTY_NONE;
  1281. }
  1282. opengl.bind_mesh();
  1283. // Initialize uniform
  1284. glViewport(0, 0, width, height);
  1285. model = Eigen::Matrix4f::Identity();
  1286. view = Eigen::Matrix4f::Identity();
  1287. proj = Eigen::Matrix4f::Identity();
  1288. // Set view
  1289. view = lookAt(Eigen::Vector3f(options.camera_eye[0], options.camera_eye[1], options.camera_eye[2]),
  1290. Eigen::Vector3f(options.camera_center[0], options.camera_center[1], options.camera_center[2]),
  1291. Eigen::Vector3f(options.camera_up[0], options.camera_up[1], options.camera_up[2]));
  1292. // Set projection
  1293. if (options.orthographic)
  1294. {
  1295. float length = (options.camera_eye - options.camera_center).norm();
  1296. float h = tan(options.camera_view_angle/360.0 * M_PI) * (length);
  1297. proj = ortho(-h*width/height, h*width/height, -h, h, options.camera_dnear, options.camera_dfar);
  1298. }
  1299. else
  1300. {
  1301. float fH = tan(options.camera_view_angle / 360.0 * M_PI) * options.camera_dnear;
  1302. float fW = fH * (double)width/(double)height;
  1303. proj = frustum(-fW, fW, -fH, fH, options.camera_dnear, options.camera_dfar);
  1304. }
  1305. // end projection
  1306. // Set model transformation
  1307. float mat[16];
  1308. igl::quat_to_mat(options.trackball_angle.data(), mat);
  1309. for (unsigned i=0;i<4;++i)
  1310. for (unsigned j=0;j<4;++j)
  1311. model(i,j) = mat[i+4*j];
  1312. model = scale(model, Eigen::Vector3f(options.camera_zoom,options.camera_zoom,options.camera_zoom));
  1313. model = scale(model, Eigen::Vector3f(options.model_zoom,options.model_zoom,options.model_zoom));
  1314. model = translate(model, Eigen::Vector3f(options.model_translation[0],options.model_translation[1],options.model_translation[2]));
  1315. // Send transformations to the GPU
  1316. GLint modeli = opengl.shader_mesh.uniform("model");
  1317. GLint viewi = opengl.shader_mesh.uniform("view");
  1318. GLint proji = opengl.shader_mesh.uniform("proj");
  1319. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1320. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1321. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1322. // Light parameters
  1323. GLint specular_exponenti = opengl.shader_mesh.uniform("specular_exponent");
  1324. GLint light_position_worldi = opengl.shader_mesh.uniform("light_position_world");
  1325. GLint lighting_factori = opengl.shader_mesh.uniform("lighting_factor");
  1326. GLint fixed_colori = opengl.shader_mesh.uniform("fixed_color");
  1327. GLint texture_factori = opengl.shader_mesh.uniform("texture_factor");
  1328. glUniform1f(specular_exponenti, options.shininess);
  1329. Vector3f rev_light = -1.*options.light_position;
  1330. glUniform3fv(light_position_worldi, 1, rev_light.data());
  1331. glUniform1f(lighting_factori, options.lighting_factor); // enables lighting
  1332. glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);
  1333. if (data.V.rows()>0)
  1334. {
  1335. // Render fill
  1336. if (options.show_faces)
  1337. {
  1338. // Texture
  1339. glUniform1f(texture_factori, options.show_texture ? 1.0f : 0.0f);
  1340. opengl.draw_mesh(true);
  1341. glUniform1f(texture_factori, 0.0f);
  1342. }
  1343. // Render wireframe
  1344. if (options.show_lines)
  1345. {
  1346. glLineWidth(options.line_width);
  1347. glUniform4f(fixed_colori, options.line_color[0], options.line_color[1],
  1348. options.line_color[2], 1.0f);
  1349. opengl.draw_mesh(false);
  1350. glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);
  1351. }
  1352. if (options.show_vertid)
  1353. {
  1354. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1355. for (int i=0; i<data.V.rows(); ++i)
  1356. __font_renderer.DrawText(data.V.row(i), data.V_normals.row(i), to_string(i));
  1357. __font_renderer.EndDraw();
  1358. }
  1359. if (options.show_faceid)
  1360. {
  1361. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1362. for (int i=0; i<data.F.rows(); ++i)
  1363. {
  1364. Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
  1365. for (int j=0;j<data.F.cols();++j)
  1366. p += data.V.row(data.F(i,j));
  1367. p /= data.F.cols();
  1368. __font_renderer.DrawText(p, data.F_normals.row(i), to_string(i));
  1369. }
  1370. __font_renderer.EndDraw();
  1371. }
  1372. }
  1373. if (options.show_overlay)
  1374. {
  1375. if (options.show_overlay_depth)
  1376. glEnable(GL_DEPTH_TEST);
  1377. else
  1378. glDisable(GL_DEPTH_TEST);
  1379. if (data.lines.rows() > 0)
  1380. {
  1381. opengl.bind_overlay_lines();
  1382. modeli = opengl.shader_overlay_lines.uniform("model");
  1383. viewi = opengl.shader_overlay_lines.uniform("view");
  1384. proji = opengl.shader_overlay_lines.uniform("proj");
  1385. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1386. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1387. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1388. // This must be enabled, otherwise glLineWidth has no effect
  1389. glEnable(GL_LINE_SMOOTH);
  1390. glLineWidth(options.line_width);
  1391. opengl.draw_overlay_lines();
  1392. }
  1393. if (data.points.rows() > 0)
  1394. {
  1395. opengl.bind_overlay_points();
  1396. modeli = opengl.shader_overlay_points.uniform("model");
  1397. viewi = opengl.shader_overlay_points.uniform("view");
  1398. proji = opengl.shader_overlay_points.uniform("proj");
  1399. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1400. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1401. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1402. glPointSize(options.point_size);
  1403. opengl.draw_overlay_points();
  1404. }
  1405. if (data.labels_positions.rows() > 0)
  1406. {
  1407. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1408. for (int i=0; i<data.labels_positions.rows(); ++i)
  1409. __font_renderer.DrawText(data.labels_positions.row(i), Eigen::Vector3d(0.0,0.0,0.0),
  1410. data.labels_strings[i]);
  1411. __font_renderer.EndDraw();
  1412. }
  1413. glEnable(GL_DEPTH_TEST);
  1414. }
  1415. if (callback_post_draw)
  1416. if (callback_post_draw(*this))
  1417. return;
  1418. for (unsigned int i = 0; i<plugins.size(); ++i)
  1419. if (plugins[i]->post_draw())
  1420. break;
  1421. TwDraw();
  1422. }
  1423. bool Viewer::save_scene()
  1424. {
  1425. #ifdef ENABLE_XML_SERIALIZATION
  1426. string fname = igl::file_dialog_save();
  1427. if (fname.length() == 0)
  1428. return false;
  1429. ::igl::XMLSerializer serializer("Viewer");
  1430. serializer.Add(data,"Data");
  1431. serializer.Add(options,"Options");
  1432. if (plugin_manager)
  1433. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1434. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1435. serializer.Save(fname.c_str(),true);
  1436. #endif
  1437. return true;
  1438. }
  1439. bool Viewer::load_scene()
  1440. {
  1441. #ifdef ENABLE_XML_SERIALIZATION
  1442. string fname = igl::file_dialog_open();
  1443. if (fname.length() == 0)
  1444. return false;
  1445. ::igl::XMLSerializer serializer("Viewer");
  1446. serializer.Add(data,"Data");
  1447. serializer.Add(options,"Options");
  1448. if (plugin_manager)
  1449. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1450. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1451. serializer.Load(fname.c_str());
  1452. #endif
  1453. return true;
  1454. }
  1455. void Viewer::align_camera_center()
  1456. {
  1457. get_scale_and_shift_to_fit_mesh(data.V,data.F,options.model_zoom,options.model_translation);
  1458. data.object_scale = (data.V.colwise().maxCoeff() - data.V.colwise().minCoeff()).norm();
  1459. }
  1460. void Viewer::resize(int w, int h)
  1461. {
  1462. width = w;
  1463. height = h;
  1464. viewport = Eigen::Vector4f(0,0,width,height);
  1465. }
  1466. void Viewer::get_scale_and_shift_to_fit_mesh(
  1467. const Eigen::MatrixXd& V,
  1468. const Eigen::MatrixXi& F,
  1469. float& zoom,
  1470. Eigen::Vector3f& shift)
  1471. {
  1472. if (V.rows() == 0)
  1473. return;
  1474. //Compute mesh centroid
  1475. Eigen::SparseMatrix<double> M;
  1476. igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);
  1477. const auto & MV = M*V;
  1478. Eigen::RowVector3d centroid = MV.colwise().sum()/M.diagonal().sum();
  1479. Eigen::RowVector3d min_point = V.colwise().minCoeff();
  1480. Eigen::RowVector3d max_point = V.colwise().maxCoeff();
  1481. shift = -centroid.cast<float>();
  1482. double x_scale = fabs(max_point[0] - min_point[0]);
  1483. double y_scale = fabs(max_point[1] - min_point[1]);
  1484. double z_scale = fabs(max_point[2] - min_point[2]);
  1485. zoom = 2.0/ std::max(z_scale,std::max(x_scale,y_scale));
  1486. }
  1487. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  1488. {
  1489. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->options.trackball_angle;
  1490. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->options.trackball_angle.data());
  1491. }
  1492. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  1493. {
  1494. static_cast<Viewer *>(clientData)->align_camera_center();
  1495. }
  1496. void TW_CALL Viewer::save_scene_cb(void *clientData)
  1497. {
  1498. static_cast<Viewer *>(clientData)->save_scene();
  1499. }
  1500. void TW_CALL Viewer::load_scene_cb(void *clientData)
  1501. {
  1502. static_cast<Viewer *>(clientData)->load_scene();
  1503. }
  1504. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  1505. {
  1506. Viewer *viewer = static_cast<Viewer *>(clientData);
  1507. viewer->data.dirty |= Viewer::DIRTY_NORMAL;
  1508. viewer->options.invert_normals = *((bool *) param);
  1509. }
  1510. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  1511. {
  1512. *((bool *) param) = static_cast<Viewer *>(clientData)->options.invert_normals;
  1513. }
  1514. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  1515. {
  1516. Viewer *viewer = static_cast<Viewer *>(clientData);
  1517. viewer->set_face_based(*((bool *) param));
  1518. }
  1519. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  1520. {
  1521. *((bool *) param) = static_cast<Viewer *>(clientData)->options.face_based;
  1522. }
  1523. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  1524. {
  1525. std::string fname = igl::file_dialog_open();
  1526. if (fname.length() == 0)
  1527. return;
  1528. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  1529. }
  1530. // Serialization
  1531. void Viewer::Options::InitSerialization()
  1532. {
  1533. #ifdef ENABLE_XML_SERIALIZATION
  1534. xmlSerializer->Add(shininess, "shininess");
  1535. xmlSerializer->Add(background_color, "background_color");
  1536. xmlSerializer->Add(line_color, "line_color");
  1537. xmlSerializer->Add(light_position, "light_position");
  1538. xmlSerializer->Add(lighting_factor, "lighting_factor");
  1539. xmlSerializer->Add(trackball_angle, "trackball_angle");
  1540. xmlSerializer->Add(model_zoom, "model_zoom");
  1541. xmlSerializer->Add(model_translation, "model_translation");
  1542. xmlSerializer->Add(model_zoom_uv, "model_zoom_uv");
  1543. xmlSerializer->Add(model_translation_uv, "model_translation_uv");
  1544. xmlSerializer->Add(camera_zoom, "camera_zoom");
  1545. xmlSerializer->Add(orthographic, "orthographic");
  1546. xmlSerializer->Add(camera_eye, "camera_eye");
  1547. xmlSerializer->Add(camera_up, "camera_up");
  1548. xmlSerializer->Add(camera_center, "camera_center");
  1549. xmlSerializer->Add(camera_view_angle, "camera_view_angle");
  1550. xmlSerializer->Add(camera_dnear, "camera_dnear");
  1551. xmlSerializer->Add(camera_dfar, "camera_dfar");
  1552. xmlSerializer->Add(show_overlay, "show_overlay");
  1553. xmlSerializer->Add(show_overlay_depth, "show_overlay_depth");
  1554. xmlSerializer->Add(show_texture, "show_texture");
  1555. xmlSerializer->Add(show_faces, "show_faces");
  1556. xmlSerializer->Add(show_lines, "show_lines");
  1557. xmlSerializer->Add(show_vertid, "show_vertid");
  1558. xmlSerializer->Add(show_faceid, "show_faceid");
  1559. xmlSerializer->Add(point_size, "point_size");
  1560. xmlSerializer->Add(line_width, "line_width");
  1561. xmlSerializer->Add(invert_normals, "invert_normals");
  1562. xmlSerializer->Add(face_based, "face_based");
  1563. #endif
  1564. }
  1565. void Viewer::set_face_based(bool newvalue)
  1566. {
  1567. if (options.face_based != newvalue)
  1568. {
  1569. options.face_based = newvalue;
  1570. data.dirty = DIRTY_ALL;
  1571. }
  1572. }
  1573. // Helpers that draws the most common meshes
  1574. void Viewer::set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)
  1575. {
  1576. using namespace std;
  1577. Eigen::MatrixXd V_temp;
  1578. // If V only has two columns, pad with a column of zeros
  1579. if (V.cols() == 2)
  1580. {
  1581. V_temp = Eigen::MatrixXd::Zero(V.rows(),3);
  1582. V_temp.block(0,0,V.rows(),2) = V;
  1583. }
  1584. else
  1585. V_temp = V;
  1586. if (data.V.rows() == 0 && data.F.rows() == 0)
  1587. {
  1588. clear_mesh();
  1589. data.V = V_temp;
  1590. data.F = F;
  1591. compute_normals();
  1592. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  1593. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  1594. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  1595. grid_texture();
  1596. align_camera_center();
  1597. }
  1598. else
  1599. {
  1600. if (data.V.rows() == V.rows() && data.F.rows() == F.rows())
  1601. {
  1602. data.V = V_temp;
  1603. data.F = F;
  1604. align_camera_center();
  1605. }
  1606. else
  1607. cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
  1608. }
  1609. data.dirty |= DIRTY_FACE | DIRTY_POSITION;
  1610. }
  1611. void Viewer::set_vertices(const Eigen::MatrixXd& V)
  1612. {
  1613. data.V = V;
  1614. assert(data.F.size() == 0 || data.F.maxCoeff() < data.V.rows());
  1615. data.dirty |= DIRTY_POSITION;
  1616. }
  1617. void Viewer::set_normals(const Eigen::MatrixXd& N)
  1618. {
  1619. using namespace std;
  1620. if (N.rows() == data.V.rows())
  1621. {
  1622. set_face_based(false);
  1623. data.V_normals = N;
  1624. }
  1625. else if (N.rows() == data.F.rows() || N.rows() == data.F.rows()*3)
  1626. {
  1627. set_face_based(true);
  1628. data.F_normals = N;
  1629. }
  1630. else
  1631. cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex.";
  1632. data.dirty |= DIRTY_NORMAL;
  1633. }
  1634. void Viewer::set_colors(const Eigen::MatrixXd &C)
  1635. {
  1636. using namespace std;
  1637. using namespace Eigen;
  1638. // Ambient color should be darker color
  1639. const auto ambient = [](const MatrixXd & C)->MatrixXd
  1640. {
  1641. return 0.1*C;
  1642. };
  1643. // Specular color should be a less saturated and darker color: dampened
  1644. // highlights
  1645. const auto specular = [](const MatrixXd & C)->MatrixXd
  1646. {
  1647. const double grey = 0.3;
  1648. return grey+0.1*(C.array()-grey);
  1649. };
  1650. if (C.rows() == 1)
  1651. {
  1652. for (unsigned i=0;i<data.V_material_diffuse.rows();++i)
  1653. {
  1654. data.V_material_diffuse.row(i) = C.row(0);
  1655. }
  1656. data.V_material_ambient = ambient(data.V_material_diffuse);
  1657. data.V_material_specular = specular(data.V_material_diffuse);
  1658. for (unsigned i=0;i<data.F_material_diffuse.rows();++i)
  1659. {
  1660. data.F_material_diffuse.row(i) = C.row(0);
  1661. }
  1662. data.F_material_ambient = ambient(data.F_material_diffuse);
  1663. data.F_material_specular = specular(data.F_material_diffuse);
  1664. }
  1665. else if (C.rows() == data.V.rows())
  1666. {
  1667. set_face_based(false);
  1668. data.V_material_diffuse = C;
  1669. data.V_material_ambient = ambient(data.V_material_diffuse);
  1670. data.V_material_specular = specular(data.V_material_diffuse);
  1671. }
  1672. else if (C.rows() == data.F.rows())
  1673. {
  1674. set_face_based(true);
  1675. data.F_material_diffuse = C;
  1676. data.F_material_ambient = ambient(data.F_material_diffuse);
  1677. data.F_material_specular = specular(data.F_material_diffuse);
  1678. }
  1679. else
  1680. cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex.";
  1681. data.dirty |= DIRTY_DIFFUSE;
  1682. }
  1683. void Viewer::set_uv(const Eigen::MatrixXd& UV)
  1684. {
  1685. using namespace std;
  1686. if (UV.rows() == data.V.rows())
  1687. {
  1688. set_face_based(false);
  1689. data.V_uv = UV;
  1690. }
  1691. else
  1692. cerr << "ERROR (set_UV): Please provide uv per vertex.";
  1693. data.dirty |= DIRTY_UV;
  1694. }
  1695. void Viewer::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
  1696. {
  1697. set_face_based(true);
  1698. data.V_uv = UV_V;
  1699. data.F_uv = UV_F;
  1700. data.dirty |= DIRTY_UV;
  1701. }
  1702. void Viewer::set_texture(
  1703. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  1704. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  1705. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
  1706. {
  1707. data.texture_R = R;
  1708. data.texture_G = G;
  1709. data.texture_B = B;
  1710. data.dirty |= DIRTY_TEXTURE;
  1711. }
  1712. void Viewer::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C)
  1713. {
  1714. Eigen::MatrixXd P_temp;
  1715. // If P only has two columns, pad with a column of zeros
  1716. if (P.cols() == 2)
  1717. {
  1718. P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
  1719. P_temp.block(0,0,P.rows(),2) = P;
  1720. }
  1721. else
  1722. P_temp = P;
  1723. int lastid = data.points.rows();
  1724. data.points.conservativeResize(data.points.rows() + P_temp.rows(),6);
  1725. for (unsigned i=0; i<P_temp.rows(); ++i)
  1726. data.points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1727. data.dirty |= DIRTY_OVERLAY_POINTS;
  1728. }
  1729. void Viewer::set_edges(
  1730. const Eigen::MatrixXd& P,
  1731. const Eigen::MatrixXi& E,
  1732. const Eigen::MatrixXd& C)
  1733. {
  1734. using namespace Eigen;
  1735. data.lines.resize(E.rows(),9);
  1736. assert(C.cols() == 3);
  1737. for(int e = 0;e<E.rows();e++)
  1738. {
  1739. RowVector3d color;
  1740. if(C.size() == 3)
  1741. {
  1742. color<<C;
  1743. }else if(C.rows() == E.rows())
  1744. {
  1745. color<<C.row(e);
  1746. }
  1747. data.lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;
  1748. }
  1749. data.dirty |= DIRTY_OVERLAY_LINES;
  1750. }
  1751. void Viewer::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
  1752. {
  1753. Eigen::MatrixXd P1_temp,P2_temp;
  1754. // If P1 only has two columns, pad with a column of zeros
  1755. if (P1.cols() == 2)
  1756. {
  1757. P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);
  1758. P1_temp.block(0,0,P1.rows(),2) = P1;
  1759. P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);
  1760. P2_temp.block(0,0,P2.rows(),2) = P2;
  1761. }
  1762. else
  1763. {
  1764. P1_temp = P1;
  1765. P2_temp = P2;
  1766. }
  1767. int lastid = data.lines.rows();
  1768. data.lines.conservativeResize(data.lines.rows() + P1_temp.rows(),9);
  1769. for (unsigned i=0; i<P1_temp.rows(); ++i)
  1770. data.lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1771. data.dirty |= DIRTY_OVERLAY_LINES;
  1772. }
  1773. void Viewer::add_label(const Eigen::VectorXd& P, const std::string& str)
  1774. {
  1775. Eigen::RowVectorXd P_temp;
  1776. // If P only has two columns, pad with a column of zeros
  1777. if (P.size() == 2)
  1778. {
  1779. P_temp = Eigen::RowVectorXd::Zero(3);
  1780. P_temp << P, 0;
  1781. }
  1782. else
  1783. P_temp = P;
  1784. int lastid = data.labels_positions.rows();
  1785. data.labels_positions.conservativeResize(lastid+1, 3);
  1786. data.labels_positions.row(lastid) = P_temp;
  1787. data.labels_strings.push_back(str);
  1788. }
  1789. int Viewer::launch(std::string filename)
  1790. {
  1791. GLFWwindow* window;
  1792. glfwSetErrorCallback(glfw_error_callback);
  1793. if (!glfwInit())
  1794. return EXIT_FAILURE;
  1795. glfwWindowHint(GLFW_SAMPLES, 16);
  1796. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  1797. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  1798. #ifdef __APPLE__
  1799. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  1800. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  1801. #endif
  1802. window = glfwCreateWindow(1280, 800, "IGL Viewer", NULL, NULL);
  1803. if (!window)
  1804. {
  1805. glfwTerminate();
  1806. return EXIT_FAILURE;
  1807. }
  1808. glfwMakeContextCurrent(window);
  1809. #ifndef __APPLE__
  1810. glewExperimental = true;
  1811. GLenum err = glewInit();
  1812. if (GLEW_OK != err)
  1813. {
  1814. /* Problem: glewInit failed, something is seriously wrong. */
  1815. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  1816. }
  1817. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  1818. #endif
  1819. #ifdef DEBUG
  1820. int major, minor, rev;
  1821. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  1822. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  1823. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  1824. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  1825. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  1826. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  1827. #endif
  1828. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  1829. // Initialize AntTweakBar
  1830. TwInit(TW_OPENGL_CORE, NULL);
  1831. // Initialize IGL viewer
  1832. init();
  1833. __viewer = this;
  1834. // Register callbacks
  1835. 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);
  1836. // Handle retina displays (windows and mac)
  1837. int width, height;
  1838. glfwGetFramebufferSize(window, &width, &height);
  1839. int width_window, height_window;
  1840. glfwGetWindowSize(window, &width_window, &height_window);
  1841. highdpi = width/width_window;
  1842. glfw_window_size(window,width_window,height_window);
  1843. init_opengl();
  1844. // Load the mesh passed as input
  1845. if (filename.size() > 0)
  1846. load_mesh_from_file(filename.c_str());
  1847. // Rendering loop
  1848. while (!glfwWindowShouldClose(window))
  1849. {
  1850. double tic = get_seconds();
  1851. draw();
  1852. glfwSwapBuffers(window);
  1853. if(options.is_animating)
  1854. {
  1855. glfwPollEvents();
  1856. // In microseconds
  1857. double duration = 1000000.*(get_seconds()-tic);
  1858. const double min_duration = 1000000./options.animation_max_fps;
  1859. if(duration<min_duration)
  1860. {
  1861. // TODO: windows equivalent
  1862. usleep(min_duration-duration);
  1863. }
  1864. }
  1865. else
  1866. {
  1867. glfwWaitEvents();
  1868. }
  1869. }
  1870. free_opengl();
  1871. shutdown_plugins();
  1872. glfwDestroyWindow(window);
  1873. glfwTerminate();
  1874. return EXIT_SUCCESS;
  1875. }
  1876. } // end namespace