Viewer.cpp 71 KB

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