Viewer.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  1. #include "Viewer.h"
  2. #ifdef _WIN32
  3. # include <windows.h>
  4. # undef max
  5. # undef min
  6. #endif
  7. #ifndef __APPLE__
  8. # define GLEW_STATIC
  9. # include <GL/glew.h>
  10. #endif
  11. #ifdef __APPLE__
  12. # include <OpenGL/gl3.h>
  13. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  14. #else
  15. # ifdef _WIN32
  16. # include <windows.h>
  17. # endif
  18. # include <GL/gl.h>
  19. #endif
  20. #include <Eigen/LU>
  21. #define GLFW_INCLUDE_GLU
  22. #include <GLFW/glfw3.h>
  23. #include <cmath>
  24. #include <cstdio>
  25. #include <sstream>
  26. #include <iomanip>
  27. #include <iostream>
  28. #include <fstream>
  29. #include <algorithm>
  30. //OK NV
  31. Eigen::Vector3f project(const Eigen::Vector3f& obj,
  32. const Eigen::Matrix4f& model,
  33. const Eigen::Matrix4f& proj,
  34. const Eigen::Vector4f& viewport)
  35. {
  36. Eigen::Vector4f tmp;
  37. tmp << obj,1;
  38. tmp = model * tmp;
  39. tmp = proj * tmp;
  40. tmp = tmp.array() / tmp(3);
  41. tmp = tmp.array() * 0.5f + 0.5f;
  42. tmp(0) = tmp(0) * viewport(2) + viewport(0);
  43. tmp(1) = tmp(1) * viewport(3) + viewport(1);
  44. return tmp.head(3);
  45. }
  46. Eigen::Matrix4f lookAt (
  47. const Eigen::Vector3f& eye,
  48. const Eigen::Vector3f& center,
  49. const Eigen::Vector3f& up)
  50. {
  51. Eigen::Vector3f f = (center - eye).normalized();
  52. Eigen::Vector3f s = f.cross(up).normalized();
  53. Eigen::Vector3f u = s.cross(f);
  54. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  55. Result(0,0) = s(0);
  56. Result(0,1) = s(1);
  57. Result(0,2) = s(2);
  58. Result(1,0) = u(0);
  59. Result(1,1) = u(1);
  60. Result(1,2) = u(2);
  61. Result(2,0) =-f(0);
  62. Result(2,1) =-f(1);
  63. Result(2,2) =-f(2);
  64. Result(0,3) =-s.transpose() * eye;
  65. Result(1,3) =-u.transpose() * eye;
  66. Result(2,3) = f.transpose() * eye;
  67. return Result;
  68. }
  69. Eigen::Matrix4f ortho (
  70. const float left,
  71. const float right,
  72. const float bottom,
  73. const float top,
  74. const float zNear,
  75. const float zFar
  76. )
  77. {
  78. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  79. Result(0,0) = 2.0f / (right - left);
  80. Result(1,1) = 2.0f / (top - bottom);
  81. Result(2,2) = - 2.0f / (zFar - zNear);
  82. Result(0,3) = - (right + left) / (right - left);
  83. Result(1,3) = - (top + bottom) / (top - bottom);
  84. Result(2,3) = - (zFar + zNear) / (zFar - zNear);
  85. return Result;
  86. }
  87. Eigen::Matrix4f frustum (
  88. const float left,
  89. const float right,
  90. const float bottom,
  91. const float top,
  92. const float nearVal,
  93. const float farVal)
  94. {
  95. Eigen::Matrix4f Result = Eigen::Matrix4f::Zero();
  96. Result(0,0) = (2.0f * nearVal) / (right - left);
  97. Result(1,1) = (2.0f * nearVal) / (top - bottom);
  98. Result(0,2) = (right + left) / (right - left);
  99. Result(1,2) = (top + bottom) / (top - bottom);
  100. Result(2,2) = -(farVal + nearVal) / (farVal - nearVal);
  101. Result(3,2) = -1.0f;
  102. Result(2,3) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
  103. return Result;
  104. }
  105. Eigen::Matrix4f scale (const Eigen::Matrix4f& m,
  106. const Eigen::Vector3f& v)
  107. {
  108. Eigen::Matrix4f Result;
  109. Result.col(0) = m.col(0).array() * v(0);
  110. Result.col(1) = m.col(1).array() * v(1);
  111. Result.col(2) = m.col(2).array() * v(2);
  112. Result.col(3) = m.col(3);
  113. return Result;
  114. }
  115. Eigen::Matrix4f translate(
  116. const Eigen::Matrix4f& m,
  117. const Eigen::Vector3f& v)
  118. {
  119. Eigen::Matrix4f Result = m;
  120. 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();
  121. return Result;
  122. }
  123. #include <limits>
  124. #include <cassert>
  125. #ifdef ENABLE_XML_SERIALIZATION
  126. #include "igl/xml/XMLSerializer.h"
  127. #endif
  128. #include <igl/readOBJ.h>
  129. #include <igl/readOFF.h>
  130. #include <igl/per_face_normals.h>
  131. #include <igl/per_vertex_normals.h>
  132. #include <igl/per_corner_normals.h>
  133. #include <igl/adjacency_list.h>
  134. #include <igl/writeOBJ.h>
  135. #include <igl/writeOFF.h>
  136. #include <igl/massmatrix.h>
  137. #include <igl/file_dialog_open.h>
  138. #include <igl/file_dialog_save.h>
  139. #include <igl/quat_to_mat.h>
  140. #include <igl/quat_mult.h>
  141. #include <igl/axis_angle_to_quat.h>
  142. #include <igl/trackball.h>
  143. #include <igl/snap_to_canonical_view_quat.h>
  144. #include <igl/unproject.h>
  145. #include <TwOpenGLCore.h>
  146. // Plugin manager (exported to other compilation units)
  147. igl::Plugin_manager igl_viewer_plugin_manager;
  148. // Internal global variables used for glfw event handling
  149. static igl::Viewer * __viewer;
  150. static double highdpi = 1;
  151. static double scroll_x = 0;
  152. static double scroll_y = 0;
  153. /* This class extends the font rendering code in AntTweakBar
  154. so that it can be used to render text at arbitrary 3D positions */
  155. class TextRenderer : public CTwGraphOpenGLCore {
  156. public:
  157. TextRenderer() : m_shaderHandleBackup(0) { }
  158. virtual int Init()
  159. {
  160. int retval = CTwGraphOpenGLCore::Init();
  161. if (retval == 1)
  162. {
  163. std::string vertexShader =
  164. "#version 150\n"
  165. "uniform vec2 offset;"
  166. "uniform vec2 wndSize;"
  167. "uniform vec4 color;"
  168. "uniform float depth;"
  169. "in vec2 vertex;"
  170. "in vec2 uv;"
  171. "out vec4 fcolor;"
  172. "out vec2 fuv;"
  173. "void main() {"
  174. " gl_Position = vec4(2.0*(vertex.x+offset.x-0.5)/wndSize.x - 1.0,"
  175. " 1.0 - 2.0*(vertex.y+offset.y-0.5)/wndSize.y,"
  176. " depth, 1);"
  177. " fuv = uv;"
  178. " fcolor = color;"
  179. "}";
  180. std::string fragmentShader =
  181. "#version 150\n"
  182. "uniform sampler2D tex;"
  183. "in vec2 fuv;"
  184. "in vec4 fcolor;"
  185. "out vec4 outColor;"
  186. "void main() { outColor.rgb = fcolor.bgr; outColor.a = fcolor.a * texture(tex, fuv).r; }";
  187. if (!m_shader.init(vertexShader, fragmentShader, "outColor"))
  188. return 0;
  189. /* Adjust location bindings */
  190. glBindAttribLocation(m_shader.program_shader, 0, "vertex");
  191. glBindAttribLocation(m_shader.program_shader, 1, "uv");
  192. glBindAttribLocation(m_shader.program_shader, 2, "color");
  193. glLinkProgram(m_shader.program_shader);
  194. m_shaderHandleBackup = m_TriTexUniProgram;
  195. m_TriTexUniProgram = m_shader.program_shader;
  196. m_TriTexUniLocationOffset = m_shader.uniform("offset");
  197. m_TriTexUniLocationWndSize = m_shader.uniform("wndSize");
  198. m_TriTexUniLocationColor = m_shader.uniform("color");
  199. m_TriTexUniLocationTexture = m_shader.uniform("tex");
  200. m_TriTexUniLocationDepth = m_shader.uniform("depth");
  201. }
  202. return retval;
  203. }
  204. virtual int Shut()
  205. {
  206. for (auto kv : m_textObjects)
  207. DeleteTextObj(kv.second);
  208. m_shader.free();
  209. m_TriTexUniProgram = m_shaderHandleBackup;
  210. return CTwGraphOpenGLCore::Shut();
  211. }
  212. void BeginDraw(const Eigen::Matrix4f &view, const Eigen::Matrix4f &proj,
  213. const Eigen::Vector4f &_viewport, float _object_scale)
  214. {
  215. viewport = _viewport;
  216. proj_matrix = proj;
  217. view_matrix = view;
  218. CTwGraphOpenGLCore::BeginDraw(viewport[2], viewport[3]);
  219. glEnable(GL_DEPTH_TEST);
  220. glDepthMask(GL_FALSE);
  221. object_scale = _object_scale;
  222. }
  223. void EndDraw()
  224. {
  225. /* Limit the number of cached text objects */
  226. for (auto it = m_textObjects.cbegin(); it != m_textObjects.cend(); )
  227. {
  228. if (m_textObjects.size() < 1000000)
  229. break;
  230. DeleteTextObj(it->second);
  231. m_textObjects.erase(it++);
  232. }
  233. glDepthMask(GL_TRUE);
  234. CTwGraphOpenGLCore::EndDraw();
  235. }
  236. void DrawText(Eigen::Vector3d pos, Eigen::Vector3d normal, const std::string &text)
  237. {
  238. pos += normal * 0.005f * object_scale;
  239. Eigen::Vector3f coord = project(Eigen::Vector3f(pos(0), pos(1), pos(2)),
  240. view_matrix, proj_matrix, viewport);
  241. auto it = m_textObjects.find(text);
  242. void *text_obj = nullptr;
  243. if (it == m_textObjects.end())
  244. {
  245. text_obj = NewTextObj();
  246. BuildText(text_obj, &text, NULL, NULL, 1, g_DefaultNormalFont, 0, 0);
  247. m_textObjects[text] = text_obj;
  248. } else {
  249. text_obj = it->second;
  250. }
  251. m_shader.bind();
  252. glUniform1f(m_TriTexUniLocationDepth, 2*(coord(2)-0.5f));
  253. CTwGraphOpenGLCore::DrawText(text_obj, coord[0], viewport[3] - coord[1], COLOR32_BLUE, 0);
  254. }
  255. protected:
  256. igl::Viewer::OpenGL_shader m_shader;
  257. std::map<std::string, void *> m_textObjects;
  258. GLuint m_shaderHandleBackup;
  259. GLuint m_TriTexUniLocationDepth;
  260. Eigen::Matrix4f view_matrix, proj_matrix;
  261. Eigen::Vector4f viewport;
  262. float object_scale;
  263. };
  264. static TextRenderer __font_renderer;
  265. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  266. {
  267. bool tw_used = TwEventMouseButtonGLFW(button, action);
  268. igl::Viewer::MouseButton mb;
  269. if (button == GLFW_MOUSE_BUTTON_1)
  270. mb = igl::Viewer::IGL_LEFT;
  271. else if (button == GLFW_MOUSE_BUTTON_2)
  272. mb = igl::Viewer::IGL_RIGHT;
  273. else //if (button == GLFW_MOUSE_BUTTON_3)
  274. mb = igl::Viewer::IGL_MIDDLE;
  275. if (action == GLFW_PRESS)
  276. {
  277. if(!tw_used)
  278. {
  279. __viewer->mouse_down(mb,modifier);
  280. }
  281. } else
  282. {
  283. // Always call mouse_up on up
  284. __viewer->mouse_up(mb,modifier);
  285. }
  286. }
  287. static void glfw_error_callback(int error, const char* description)
  288. {
  289. fputs(description, stderr);
  290. }
  291. int global_KMod = 0;
  292. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  293. {
  294. int handled = 0;
  295. // Register of modifiers state
  296. if (glfwAction==GLFW_PRESS)
  297. {
  298. switch (glfwKey)
  299. {
  300. case GLFW_KEY_LEFT_SHIFT:
  301. case GLFW_KEY_RIGHT_SHIFT:
  302. global_KMod |= TW_KMOD_SHIFT;
  303. break;
  304. case GLFW_KEY_LEFT_CONTROL:
  305. case GLFW_KEY_RIGHT_CONTROL:
  306. global_KMod |= TW_KMOD_CTRL;
  307. break;
  308. case GLFW_KEY_LEFT_ALT:
  309. case GLFW_KEY_RIGHT_ALT:
  310. global_KMod |= TW_KMOD_ALT;
  311. break;
  312. }
  313. }
  314. else
  315. {
  316. switch (glfwKey)
  317. {
  318. case GLFW_KEY_LEFT_SHIFT:
  319. case GLFW_KEY_RIGHT_SHIFT:
  320. global_KMod &= ~TW_KMOD_SHIFT;
  321. break;
  322. case GLFW_KEY_LEFT_CONTROL:
  323. case GLFW_KEY_RIGHT_CONTROL:
  324. global_KMod &= ~TW_KMOD_CTRL;
  325. break;
  326. case GLFW_KEY_LEFT_ALT:
  327. case GLFW_KEY_RIGHT_ALT:
  328. global_KMod &= ~TW_KMOD_ALT;
  329. break;
  330. }
  331. }
  332. // Process key pressed
  333. if (glfwAction==GLFW_PRESS)
  334. {
  335. int mod = global_KMod;
  336. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  337. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  338. handled = TwKeyPressed(glfwKey, mod);
  339. else if (glfwKey>=GLFW_KEY_ESCAPE )
  340. {
  341. int k = 0;
  342. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  343. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  344. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  345. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  346. else
  347. {
  348. switch (glfwKey)
  349. {
  350. case GLFW_KEY_ESCAPE :
  351. k = TW_KEY_ESCAPE;
  352. break;
  353. case GLFW_KEY_UP:
  354. k = TW_KEY_UP;
  355. break;
  356. case GLFW_KEY_DOWN:
  357. k = TW_KEY_DOWN;
  358. break;
  359. case GLFW_KEY_LEFT:
  360. k = TW_KEY_LEFT;
  361. break;
  362. case GLFW_KEY_RIGHT:
  363. k = TW_KEY_RIGHT;
  364. break;
  365. case GLFW_KEY_TAB:
  366. k = TW_KEY_TAB;
  367. break;
  368. case GLFW_KEY_ENTER:
  369. k = TW_KEY_RETURN;
  370. break;
  371. case GLFW_KEY_BACKSPACE:
  372. k = TW_KEY_BACKSPACE;
  373. break;
  374. case GLFW_KEY_INSERT:
  375. k = TW_KEY_INSERT;
  376. break;
  377. case GLFW_KEY_DELETE:
  378. k = TW_KEY_DELETE;
  379. break;
  380. case GLFW_KEY_PAGE_UP:
  381. k = TW_KEY_PAGE_UP;
  382. break;
  383. case GLFW_KEY_PAGE_DOWN:
  384. k = TW_KEY_PAGE_DOWN;
  385. break;
  386. case GLFW_KEY_HOME:
  387. k = TW_KEY_HOME;
  388. break;
  389. case GLFW_KEY_END:
  390. k = TW_KEY_END;
  391. break;
  392. case GLFW_KEY_KP_ENTER:
  393. k = TW_KEY_RETURN;
  394. break;
  395. case GLFW_KEY_KP_DIVIDE:
  396. if (testkp)
  397. k = '/';
  398. break;
  399. case GLFW_KEY_KP_MULTIPLY:
  400. if (testkp)
  401. k = '*';
  402. break;
  403. case GLFW_KEY_KP_SUBTRACT:
  404. if (testkp)
  405. k = '-';
  406. break;
  407. case GLFW_KEY_KP_ADD:
  408. if (testkp)
  409. k = '+';
  410. break;
  411. case GLFW_KEY_KP_DECIMAL:
  412. if (testkp)
  413. k = '.';
  414. break;
  415. case GLFW_KEY_KP_EQUAL:
  416. if (testkp)
  417. k = '=';
  418. break;
  419. }
  420. }
  421. if (k>0)
  422. handled = TwKeyPressed(k, mod);
  423. }
  424. }
  425. return handled;
  426. }
  427. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  428. {
  429. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  430. glfwSetWindowShouldClose(window, GL_TRUE);
  431. if (!TwEventKeyGLFW3(key,action))
  432. {
  433. if (action == GLFW_PRESS)
  434. __viewer->key_down(key, modifier);
  435. else
  436. __viewer->key_up(key, modifier);
  437. }
  438. }
  439. static void glfw_window_size(GLFWwindow* window, int width, int height)
  440. {
  441. int w = width*highdpi;
  442. int h = height*highdpi;
  443. __viewer->resize(w, h);
  444. TwWindowSize(w, h);
  445. const auto & bar = __viewer->bar;
  446. // Keep AntTweakBar on right side of screen and height == opengl height
  447. // get the current position of a bar
  448. int size[2];
  449. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  450. int pos[2];
  451. // Place bar on left side of opengl rect (padded by 10 pixels)
  452. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  453. // place bar at top (padded by 10 pixels)
  454. pos[1] = 10;
  455. // Set height to new height of window (padded by 10 pixels on bottom)
  456. size[1] = height-pos[1]-10;
  457. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  458. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  459. }
  460. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  461. {
  462. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  463. {
  464. // Call if TwBar hasn't used or if down
  465. __viewer->mouse_move(x*highdpi, y*highdpi);
  466. }
  467. }
  468. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  469. {
  470. using namespace std;
  471. scroll_x += x;
  472. scroll_y += y;
  473. if (!TwEventMouseWheelGLFW(scroll_y))
  474. __viewer->mouse_scroll(y);
  475. }
  476. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  477. {
  478. if ((c & 0xff00)==0)
  479. TwKeyPressed(c, global_KMod);
  480. }
  481. namespace igl
  482. {
  483. void Viewer::init(Plugin_manager* pm)
  484. {
  485. plugin_manager = pm;
  486. // Create a tweak bar
  487. bar = TwNewBar("libIGL-Viewer");
  488. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  489. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  490. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  491. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  492. // ---------------------- LOADING ----------------------
  493. #ifdef ENABLE_XML_SERIALIZATION
  494. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  495. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  496. #endif
  497. #ifdef ENABLE_IO
  498. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  499. #endif
  500. // ---------------------- SCENE ----------------------
  501. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  502. " group='Viewing Options'"
  503. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  504. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(options.camera_zoom),
  505. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  506. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  507. " group='Scene'"
  508. " label='Snap to canonical view' key=Z "
  509. " help='Snaps view to nearest canonical view.'");
  510. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, options.light_position.data(),
  511. " group='Scene'"
  512. " label='Light direction' open help='Change the light direction.' ");
  513. // ---------------------- DRAW OPTIONS ----------------------
  514. TwAddVarRW(bar, "Toggle Orthographic/Perspective", TW_TYPE_BOOLCPP, &(options.orthographic),
  515. " group='Viewing Options'"
  516. " label='Orthographic view' "
  517. " help='Toggles orthographic / perspective view. Default: perspective.'");
  518. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  519. " group='Draw options'"
  520. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  521. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(options.show_texture),
  522. " group='Draw options'");
  523. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  524. " group='Draw options'"
  525. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  526. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(options.show_overlay),
  527. " group='Draw options'"
  528. " label='Show overlay' key=o help='Show the overlay layers.' ");
  529. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(options.show_overlay_depth),
  530. " group='Draw options'"
  531. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  532. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  533. options.background_color.data(),
  534. " help='Select a background color' colormode=hls group='Draw options'");
  535. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  536. options.line_color.data(),
  537. " label='Line color' help='Select a outline color' group='Draw options'");
  538. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&options.shininess," group='Draw options'"
  539. " min=1 max=128");
  540. // ---------------------- Overlays ----------------------
  541. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(options.show_lines),
  542. " group='Overlays'"
  543. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  544. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(options.show_faces),
  545. " group='Overlays'"
  546. " label='Fill' key=t help='Display filled polygons of mesh'");
  547. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(options.show_vertid),
  548. " group='Overlays'"
  549. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  550. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(options.show_faceid),
  551. " group='Overlays'"
  552. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  553. " indices'");
  554. __font_renderer.Init();
  555. init_plugins();
  556. }
  557. Viewer::Viewer()
  558. {
  559. plugin_manager = 0;
  560. // Default shininess
  561. options.shininess = 35.0f;
  562. // Default colors
  563. options.background_color << 0.3f, 0.3f, 0.5f;
  564. options.line_color << 0.0f, 0.0f, 0.0f;
  565. // Default lights settings
  566. options.light_position << 0.0f, -0.30f, -5.0f;
  567. options.lighting_factor = 1.0f; //on
  568. // Default trackball
  569. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  570. // Defalut model viewing parameters
  571. options.model_zoom = 1.0f;
  572. options.model_translation << 0,0,0;
  573. // Camera parameters
  574. options.camera_zoom = 1.0f;
  575. options.orthographic = false;
  576. options.camera_view_angle = 45.0;
  577. options.camera_dnear = 1.0;
  578. options.camera_dfar = 100.0;
  579. options.camera_eye << 0, 0, 5;
  580. options.camera_center << 0, 0, 0;
  581. options.camera_up << 0, 1, 0;
  582. // Default visualization options
  583. options.show_faces = true;
  584. options.show_lines = true;
  585. options.invert_normals = false;
  586. options.show_overlay = true;
  587. options.show_overlay_depth = true;
  588. options.show_vertid = false;
  589. options.show_faceid = false;
  590. options.show_texture = false;
  591. // Default point size / line width
  592. options.point_size = 15;
  593. options.line_width = 0.5f;
  594. // Temporary variables initialization
  595. down = false;
  596. scroll_position = 0.0f;
  597. // Per face
  598. set_face_based(false);
  599. // C-style callbacks
  600. callback_pre_draw = 0;
  601. callback_post_draw = 0;
  602. callback_mouse_down = 0;
  603. callback_mouse_up = 0;
  604. callback_mouse_move = 0;
  605. callback_mouse_scroll = 0;
  606. callback_key_down = 0;
  607. callback_key_up = 0;
  608. callback_pre_draw_data = 0;
  609. callback_post_draw = 0;
  610. callback_mouse_down = 0;
  611. callback_mouse_up = 0;
  612. callback_mouse_move = 0;
  613. callback_mouse_scroll = 0;
  614. callback_key_down = 0;
  615. callback_key_up = 0;
  616. }
  617. void Viewer::init_plugins()
  618. {
  619. // Init all plugins
  620. if (plugin_manager)
  621. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  622. plugin_manager->plugin_list[i]->init(this);
  623. }
  624. Viewer::~Viewer()
  625. {
  626. }
  627. void Viewer::shutdown_plugins()
  628. {
  629. if (plugin_manager)
  630. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  631. plugin_manager->plugin_list[i]->shutdown();
  632. }
  633. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  634. {
  635. std::string mesh_file_name_string = std::string(mesh_file_name);
  636. // first try to load it with a plugin
  637. if (plugin_manager)
  638. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  639. if (plugin_manager->plugin_list[i]->load(mesh_file_name_string))
  640. return true;
  641. clear_mesh();
  642. size_t last_dot = mesh_file_name_string.rfind('.');
  643. if (last_dot == std::string::npos)
  644. {
  645. printf("Error: No file extension found in %s\n",mesh_file_name);
  646. return false;
  647. }
  648. std::string extension = mesh_file_name_string.substr(last_dot+1);
  649. if (extension == "off" || extension =="OFF")
  650. {
  651. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  652. return false;
  653. }
  654. else if (extension == "obj" || extension =="OBJ")
  655. {
  656. Eigen::MatrixXd corner_normals;
  657. Eigen::MatrixXi fNormIndices;
  658. Eigen::MatrixXd UV_V;
  659. Eigen::MatrixXi UV_F;
  660. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  661. return false;
  662. }
  663. else
  664. {
  665. // unrecognized file type
  666. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  667. return false;
  668. }
  669. compute_normals();
  670. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  671. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  672. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  673. if (data.V_uv.rows() == 0)
  674. grid_texture();
  675. align_camera_center();
  676. if (plugin_manager)
  677. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  678. if (plugin_manager->plugin_list[i]->post_load())
  679. return true;
  680. return true;
  681. }
  682. void Viewer::compute_normals()
  683. {
  684. igl::per_face_normals(data.V, data.F, data.F_normals);
  685. igl::per_vertex_normals(data.V, data.F, data.F_normals, data.V_normals);
  686. data.dirty |= DIRTY_NORMAL;
  687. }
  688. void Viewer::uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular)
  689. {
  690. data.V_material_ambient.resize(data.V.rows(),3);
  691. data.V_material_diffuse.resize(data.V.rows(),3);
  692. data.V_material_specular.resize(data.V.rows(),3);
  693. for (unsigned i=0; i<data.V.rows();++i)
  694. {
  695. data.V_material_ambient.row(i) = ambient;
  696. data.V_material_diffuse.row(i) = diffuse;
  697. data.V_material_specular.row(i) = specular;
  698. }
  699. data.F_material_ambient.resize(data.F.rows(),3);
  700. data.F_material_diffuse.resize(data.F.rows(),3);
  701. data.F_material_specular.resize(data.F.rows(),3);
  702. for (unsigned i=0; i<data.F.rows();++i)
  703. {
  704. data.F_material_ambient.row(i) = ambient;
  705. data.F_material_diffuse.row(i) = diffuse;
  706. data.F_material_specular.row(i) = specular;
  707. }
  708. data.dirty |= DIRTY_SPECULAR | DIRTY_DIFFUSE | DIRTY_AMBIENT;
  709. }
  710. void Viewer::grid_texture()
  711. {
  712. if (data.V_uv.rows() == 0)
  713. {
  714. data.V_uv = data.V.block(0, 0, data.V.rows(), 2);
  715. data.V_uv.col(0) = data.V_uv.col(0).array() - data.V_uv.col(0).minCoeff();
  716. data.V_uv.col(0) = data.V_uv.col(0).array() / data.V_uv.col(0).maxCoeff();
  717. data.V_uv.col(1) = data.V_uv.col(1).array() - data.V_uv.col(1).minCoeff();
  718. data.V_uv.col(1) = data.V_uv.col(1).array() / data.V_uv.col(1).maxCoeff();
  719. data.V_uv = data.V_uv.array() * 10;
  720. data.dirty |= DIRTY_TEXTURE;
  721. }
  722. unsigned size = 128;
  723. unsigned size2 = size/2;
  724. data.texture_R.resize(size, size);
  725. for (unsigned i=0; i<size; ++i)
  726. {
  727. for (unsigned j=0; j<size; ++j)
  728. {
  729. data.texture_R(i,j) = 0;
  730. if ((i<size2 && j<size2) || (i>=size2 && j>=size2))
  731. data.texture_R(i,j) = 255;
  732. }
  733. }
  734. data.texture_G = data.texture_R;
  735. data.texture_B = data.texture_R;
  736. data.dirty |= DIRTY_TEXTURE;
  737. }
  738. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  739. {
  740. std::string mesh_file_name_string(mesh_file_name);
  741. // first try to load it with a plugin
  742. if (plugin_manager)
  743. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  744. if (plugin_manager->plugin_list[i]->save(mesh_file_name_string))
  745. return true;
  746. size_t last_dot = mesh_file_name_string.rfind('.');
  747. if (last_dot == std::string::npos)
  748. {
  749. // No file type determined
  750. printf("Error: No file extension found in %s\n",mesh_file_name);
  751. return false;
  752. }
  753. std::string extension = mesh_file_name_string.substr(last_dot+1);
  754. if (extension == "off" || extension =="OFF")
  755. {
  756. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  757. }
  758. else if (extension == "obj" || extension =="OBJ")
  759. {
  760. Eigen::MatrixXd corner_normals;
  761. Eigen::MatrixXi fNormIndices;
  762. Eigen::MatrixXd UV_V;
  763. Eigen::MatrixXi UV_F;
  764. return igl::writeOBJ(mesh_file_name_string, data.V,
  765. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  766. }
  767. else
  768. {
  769. // unrecognized file type
  770. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  771. return false;
  772. }
  773. return true;
  774. }
  775. void Viewer::clear_mesh()
  776. {
  777. data.V = Eigen::MatrixXd (0,3);
  778. data.F = Eigen::MatrixXi (0,3);
  779. data.F_material_ambient = Eigen::MatrixXd (0,3);
  780. data.F_material_diffuse = Eigen::MatrixXd (0,3);
  781. data.F_material_specular = Eigen::MatrixXd (0,3);
  782. data.V_material_ambient = Eigen::MatrixXd (0,3);
  783. data.V_material_diffuse = Eigen::MatrixXd (0,3);
  784. data.V_material_specular = Eigen::MatrixXd (0,3);
  785. data.F_normals = Eigen::MatrixXd (0,3);
  786. data.V_normals = Eigen::MatrixXd (0,3);
  787. data.V_uv = Eigen::MatrixXd (0,2);
  788. data.F_uv = Eigen::MatrixXi (0,3);
  789. data.lines = Eigen::MatrixXd (0,9);
  790. data.points = Eigen::MatrixXd (0,6);
  791. data.labels_positions = Eigen::MatrixXd (0,3);
  792. data.labels_strings.clear();
  793. }
  794. bool Viewer::key_down(unsigned char key, int modifiers)
  795. {
  796. if (callback_key_down)
  797. if (callback_key_down(*this,key,modifiers))
  798. return true;
  799. if (plugin_manager)
  800. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  801. if (plugin_manager->plugin_list[i]->key_down(key, modifiers))
  802. return true;
  803. if (key == 'S')
  804. mouse_scroll(1);
  805. if (key == 'A')
  806. mouse_scroll(-1);
  807. // Why aren't these handled view AntTweakBar?
  808. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  809. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  810. if (key == 'y')
  811. options.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  812. if (key == 'x')
  813. options.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  814. return false;
  815. }
  816. bool Viewer::key_up(unsigned char key, int modifiers)
  817. {
  818. if (callback_key_up)
  819. if (callback_key_up(*this,key,modifiers))
  820. return true;
  821. if (plugin_manager)
  822. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  823. if (plugin_manager->plugin_list[i]->key_up(key, modifiers))
  824. return true;
  825. return false;
  826. }
  827. bool Viewer::mouse_down(MouseButton button, int modifier)
  828. {
  829. if (callback_mouse_down)
  830. if (callback_mouse_down(*this,button,modifier))
  831. return true;
  832. if (plugin_manager)
  833. for (unsigned int i = 0; i < plugin_manager->plugin_list.size(); ++i)
  834. if (plugin_manager->plugin_list[i]->mouse_down(button,modifier))
  835. return true;
  836. down = true;
  837. down_mouse_x = current_mouse_x;
  838. down_mouse_y = current_mouse_y;
  839. down_translation = options.model_translation;
  840. // Initialization code for the trackball
  841. Eigen::RowVector3d center;
  842. if (data.V.rows() == 0)
  843. center << 0,0,0;
  844. else
  845. center = data.V.colwise().sum()/data.V.rows();
  846. Eigen::Vector3f coord = project(Eigen::Vector3f(center(0),center(1),center(2)), view * model, proj, viewport);
  847. down_mouse_z = coord[2];
  848. down_rotation = options.trackball_angle;
  849. mouse_mode = ROTATION;
  850. switch (button)
  851. {
  852. case IGL_LEFT:
  853. mouse_mode = ROTATION;
  854. break;
  855. case IGL_RIGHT:
  856. mouse_mode = TRANSLATE;
  857. break;
  858. default:
  859. mouse_mode = NOTHING;
  860. break;
  861. }
  862. return true;
  863. }
  864. bool Viewer::mouse_up(MouseButton button, int modifier)
  865. {
  866. down = false;
  867. if (callback_mouse_up)
  868. if (callback_mouse_up(*this,button,modifier))
  869. return true;
  870. if (plugin_manager)
  871. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  872. if (plugin_manager->plugin_list[i]->mouse_up(button,modifier))
  873. return true;
  874. mouse_mode = NOTHING;
  875. return true;
  876. }
  877. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  878. {
  879. current_mouse_x = mouse_x;
  880. current_mouse_y = mouse_y;
  881. if (callback_mouse_move)
  882. if (callback_mouse_move(*this,mouse_x,mouse_y))
  883. return true;
  884. if (plugin_manager)
  885. for (unsigned int i = 0; i < plugin_manager->plugin_list.size(); ++i)
  886. if (plugin_manager->plugin_list[i]->mouse_move(mouse_x, mouse_y))
  887. return true;
  888. if (down)
  889. {
  890. switch (mouse_mode)
  891. {
  892. case ROTATION :
  893. {
  894. igl::trackball(width,
  895. height,
  896. 2.0f,
  897. down_rotation.data(),
  898. down_mouse_x,
  899. down_mouse_y,
  900. mouse_x,
  901. mouse_y,
  902. options.trackball_angle.data());
  903. //Eigen::Vector4f snapq = options.trackball_angle;
  904. break;
  905. }
  906. case TRANSLATE:
  907. {
  908. //translation
  909. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, viewport[3] - mouse_y, down_mouse_z), view * model, proj, viewport);
  910. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, viewport[3] - down_mouse_y, down_mouse_z), view * model, proj, viewport);
  911. Eigen::Vector3f diff = pos1 - pos0;
  912. options.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  913. break;
  914. }
  915. case ZOOM:
  916. {
  917. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  918. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  919. options.camera_zoom *= 1 + delta;
  920. down_mouse_x = mouse_x;
  921. down_mouse_y = mouse_y;
  922. break;
  923. }
  924. default:
  925. break;
  926. }
  927. }
  928. return true;
  929. }
  930. bool Viewer::mouse_scroll(float delta_y)
  931. {
  932. scroll_position += delta_y;
  933. if (callback_mouse_scroll)
  934. if (callback_mouse_scroll(*this,delta_y))
  935. return true;
  936. if (plugin_manager)
  937. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  938. if (plugin_manager->plugin_list[i]->mouse_scroll(delta_y))
  939. return true;
  940. // Only zoom if there's actually a change
  941. if(delta_y != 0)
  942. {
  943. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  944. const float min_zoom = 0.1f;
  945. options.camera_zoom = (options.camera_zoom * mult > min_zoom ? options.camera_zoom * mult : min_zoom);
  946. }
  947. return true;
  948. }
  949. static GLuint create_shader_helper(GLint type, const std::string &shader_string)
  950. {
  951. using namespace std;
  952. if (shader_string.empty())
  953. return (GLuint) 0;
  954. GLuint id = glCreateShader(type);
  955. const char *shader_string_const = shader_string.c_str();
  956. glShaderSource(id, 1, &shader_string_const, NULL);
  957. glCompileShader(id);
  958. GLint status;
  959. glGetShaderiv(id, GL_COMPILE_STATUS, &status);
  960. if (status != GL_TRUE)
  961. {
  962. char buffer[512];
  963. if (type == GL_VERTEX_SHADER)
  964. cerr << "Vertex shader:" << endl;
  965. else if (type == GL_FRAGMENT_SHADER)
  966. cerr << "Fragment shader:" << endl;
  967. else if (type == GL_GEOMETRY_SHADER)
  968. cerr << "Geometry shader:" << endl;
  969. cerr << shader_string << endl << endl;
  970. glGetShaderInfoLog(id, 512, NULL, buffer);
  971. cerr << "Error: " << endl << buffer << endl;
  972. return (GLuint) 0;
  973. }
  974. return id;
  975. }
  976. bool Viewer::OpenGL_shader::init_from_files(
  977. const std::string &vertex_shader_filename,
  978. const std::string &fragment_shader_filename,
  979. const std::string &fragment_data_name,
  980. const std::string &geometry_shader_filename,
  981. int geometry_shader_max_vertices)
  982. {
  983. auto file_to_string = [](const std::string &filename)
  984. {
  985. std::ifstream t(filename);
  986. return std::string((std::istreambuf_iterator<char>(t)),
  987. std::istreambuf_iterator<char>());
  988. };
  989. return init(
  990. file_to_string(vertex_shader_filename),
  991. file_to_string(fragment_shader_filename),
  992. fragment_data_name,
  993. file_to_string(geometry_shader_filename),
  994. geometry_shader_max_vertices
  995. );
  996. }
  997. bool Viewer::OpenGL_shader::init(
  998. const std::string &vertex_shader_string,
  999. const std::string &fragment_shader_string,
  1000. const std::string &fragment_data_name,
  1001. const std::string &geometry_shader_string,
  1002. int geometry_shader_max_vertices)
  1003. {
  1004. using namespace std;
  1005. vertex_shader = create_shader_helper(GL_VERTEX_SHADER, vertex_shader_string);
  1006. geometry_shader = create_shader_helper(GL_GEOMETRY_SHADER, geometry_shader_string);
  1007. fragment_shader = create_shader_helper(GL_FRAGMENT_SHADER, fragment_shader_string);
  1008. if (!vertex_shader || !fragment_shader)
  1009. return false;
  1010. program_shader = glCreateProgram();
  1011. glAttachShader(program_shader, vertex_shader);
  1012. glAttachShader(program_shader, fragment_shader);
  1013. if (geometry_shader)
  1014. {
  1015. glAttachShader(program_shader, geometry_shader);
  1016. /* This covers only basic cases and may need to be modified */
  1017. glProgramParameteri(program_shader, GL_GEOMETRY_INPUT_TYPE, GL_TRIANGLES);
  1018. glProgramParameteri(program_shader, GL_GEOMETRY_OUTPUT_TYPE, GL_TRIANGLES);
  1019. glProgramParameteri(program_shader, GL_GEOMETRY_VERTICES_OUT, geometry_shader_max_vertices);
  1020. }
  1021. glBindFragDataLocation(program_shader, 0, fragment_data_name.c_str());
  1022. glLinkProgram(program_shader);
  1023. GLint status;
  1024. glGetProgramiv(program_shader, GL_LINK_STATUS, &status);
  1025. if (status != GL_TRUE)
  1026. {
  1027. char buffer[512];
  1028. glGetProgramInfoLog(program_shader, 512, NULL, buffer);
  1029. cerr << "Linker error: " << endl << buffer << endl;
  1030. program_shader = 0;
  1031. return false;
  1032. }
  1033. return true;
  1034. }
  1035. void Viewer::OpenGL_shader::bind()
  1036. {
  1037. glUseProgram(program_shader);
  1038. }
  1039. GLint Viewer::OpenGL_shader::attrib(const std::string &name) const
  1040. {
  1041. return glGetAttribLocation(program_shader, name.c_str());
  1042. }
  1043. GLint Viewer::OpenGL_shader::uniform(const std::string &name) const
  1044. {
  1045. return glGetUniformLocation(program_shader, name.c_str());
  1046. }
  1047. GLint Viewer::OpenGL_shader::bindVertexAttribArray(
  1048. const std::string &name, GLuint bufferID, const Eigen::MatrixXf &M, bool refresh) const
  1049. {
  1050. GLint id = attrib(name);
  1051. if (id < 0)
  1052. return id;
  1053. if (M.size() == 0)
  1054. {
  1055. glDisableVertexAttribArray(id);
  1056. return id;
  1057. }
  1058. glBindBuffer(GL_ARRAY_BUFFER, bufferID);
  1059. if (refresh)
  1060. glBufferData(GL_ARRAY_BUFFER, sizeof(float)*M.size(), M.data(), GL_DYNAMIC_DRAW);
  1061. glVertexAttribPointer(id, M.rows(), GL_FLOAT, GL_FALSE, 0, 0);
  1062. glEnableVertexAttribArray(id);
  1063. return id;
  1064. }
  1065. void Viewer::OpenGL_shader::free()
  1066. {
  1067. if (program_shader)
  1068. {
  1069. glDeleteProgram(program_shader);
  1070. program_shader = 0;
  1071. }
  1072. if (vertex_shader)
  1073. {
  1074. glDeleteShader(vertex_shader);
  1075. vertex_shader = 0;
  1076. }
  1077. if (fragment_shader)
  1078. {
  1079. glDeleteShader(fragment_shader);
  1080. fragment_shader = 0;
  1081. }
  1082. if (geometry_shader)
  1083. {
  1084. glDeleteShader(geometry_shader);
  1085. geometry_shader = 0;
  1086. }
  1087. }
  1088. void Viewer::OpenGL_state::init()
  1089. {
  1090. // Mesh: Vertex Array Object & Buffer objects
  1091. glGenVertexArrays(1, &vao_mesh);
  1092. glBindVertexArray(vao_mesh);
  1093. glGenBuffers(1, &vbo_V);
  1094. glGenBuffers(1, &vbo_V_normals);
  1095. glGenBuffers(1, &vbo_V_ambient);
  1096. glGenBuffers(1, &vbo_V_diffuse);
  1097. glGenBuffers(1, &vbo_V_specular);
  1098. glGenBuffers(1, &vbo_V_uv);
  1099. glGenBuffers(1, &vbo_F);
  1100. glGenTextures(1, &vbo_tex);
  1101. // Line overlay
  1102. glGenVertexArrays(1, &vao_overlay_lines);
  1103. glBindVertexArray(vao_overlay_lines);
  1104. glGenBuffers(1, &vbo_lines_F);
  1105. glGenBuffers(1, &vbo_lines_V);
  1106. glGenBuffers(1, &vbo_lines_V_colors);
  1107. // Point overlay
  1108. glGenVertexArrays(1, &vao_overlay_points);
  1109. glBindVertexArray(vao_overlay_points);
  1110. glGenBuffers(1, &vbo_points_F);
  1111. glGenBuffers(1, &vbo_points_V);
  1112. glGenBuffers(1, &vbo_points_V_colors);
  1113. dirty = DIRTY_ALL;
  1114. }
  1115. void Viewer::OpenGL_state::free()
  1116. {
  1117. glDeleteVertexArrays(1, &vao_mesh);
  1118. glDeleteVertexArrays(1, &vao_overlay_lines);
  1119. glDeleteVertexArrays(1, &vao_overlay_points);
  1120. glDeleteBuffers(1, &vbo_V);
  1121. glDeleteBuffers(1, &vbo_V_normals);
  1122. glDeleteBuffers(1, &vbo_V_ambient);
  1123. glDeleteBuffers(1, &vbo_V_diffuse);
  1124. glDeleteBuffers(1, &vbo_V_specular);
  1125. glDeleteBuffers(1, &vbo_V_uv);
  1126. glDeleteBuffers(1, &vbo_F);
  1127. glDeleteBuffers(1, &vbo_lines_F);
  1128. glDeleteBuffers(1, &vbo_lines_V);
  1129. glDeleteBuffers(1, &vbo_lines_V_colors);
  1130. glDeleteBuffers(1, &vbo_points_F);
  1131. glDeleteBuffers(1, &vbo_points_V);
  1132. glDeleteBuffers(1, &vbo_points_V_colors);
  1133. glDeleteTextures(1, &vbo_tex);
  1134. }
  1135. void Viewer::OpenGL_state::set_data(const Data &data, bool face_based, bool invert_normals)
  1136. {
  1137. bool per_corner_uv = (data.F_uv.rows() == data.F.rows());
  1138. bool per_corner_normals = (data.F_normals.rows() == 3 * data.F.rows());
  1139. dirty |= data.dirty;
  1140. if (!face_based)
  1141. {
  1142. if (!per_corner_uv)
  1143. {
  1144. // Vertex positions
  1145. if (dirty & DIRTY_POSITION)
  1146. V_vbo = (data.V.transpose()).cast<float>();
  1147. // Vertex normals
  1148. if (dirty & DIRTY_NORMAL)
  1149. {
  1150. V_normals_vbo = (data.V_normals.transpose()).cast<float>();
  1151. if (invert_normals)
  1152. V_normals_vbo = -V_normals_vbo;
  1153. }
  1154. // Per-vertex material settings
  1155. if (dirty & DIRTY_AMBIENT)
  1156. V_ambient_vbo = (data.V_material_ambient.transpose()).cast<float>();
  1157. if (dirty & DIRTY_DIFFUSE)
  1158. V_diffuse_vbo = (data.V_material_diffuse.transpose()).cast<float>();
  1159. if (dirty & DIRTY_SPECULAR)
  1160. V_specular_vbo = (data.V_material_specular.transpose()).cast<float>();
  1161. // Face indices
  1162. if (dirty & DIRTY_FACE)
  1163. F_vbo = (data.F.transpose()).cast<unsigned>();
  1164. // Texture coordinates
  1165. if (dirty & DIRTY_UV)
  1166. V_uv_vbo = (data.V_uv.transpose()).cast<float>();
  1167. }
  1168. else
  1169. {
  1170. // Per vertex properties with per corner UVs
  1171. if (dirty & DIRTY_POSITION)
  1172. {
  1173. V_vbo.resize(3,data.F.rows()*3);
  1174. for (unsigned i=0; i<data.F.rows();++i)
  1175. for (unsigned j=0;j<3;++j)
  1176. V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
  1177. }
  1178. if (dirty & DIRTY_AMBIENT)
  1179. {
  1180. V_ambient_vbo.resize(3,data.F.rows()*3);
  1181. for (unsigned i=0; i<data.F.rows();++i)
  1182. for (unsigned j=0;j<3;++j)
  1183. V_ambient_vbo.col (i*3+j) = data.V_material_ambient.row(data.F(i,j)).transpose().cast<float>();
  1184. }
  1185. if (dirty & DIRTY_DIFFUSE)
  1186. {
  1187. V_diffuse_vbo.resize(3,data.F.rows()*3);
  1188. for (unsigned i=0; i<data.F.rows();++i)
  1189. for (unsigned j=0;j<3;++j)
  1190. V_diffuse_vbo.col (i*3+j) = data.V_material_diffuse.row(data.F(i,j)).transpose().cast<float>();
  1191. }
  1192. if (dirty & DIRTY_SPECULAR)
  1193. {
  1194. V_specular_vbo.resize(3,data.F.rows()*3);
  1195. for (unsigned i=0; i<data.F.rows();++i)
  1196. for (unsigned j=0;j<3;++j)
  1197. V_specular_vbo.col(i*3+j) = data.V_material_specular.row(data.F(i,j)).transpose().cast<float>();
  1198. }
  1199. if (dirty & DIRTY_NORMAL)
  1200. {
  1201. V_normals_vbo.resize(3,data.F.rows()*3);
  1202. for (unsigned i=0; i<data.F.rows();++i)
  1203. for (unsigned j=0;j<3;++j)
  1204. V_normals_vbo.col (i*3+j) = data.V_normals.row(data.F(i,j)).transpose().cast<float>();
  1205. if (invert_normals)
  1206. V_normals_vbo = -V_normals_vbo;
  1207. }
  1208. if (dirty & DIRTY_FACE)
  1209. {
  1210. F_vbo.resize(3,data.F.rows());
  1211. for (unsigned i=0; i<data.F.rows();++i)
  1212. F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
  1213. }
  1214. if (dirty & DIRTY_UV)
  1215. {
  1216. V_uv_vbo.resize(2,data.F.rows()*3);
  1217. for (unsigned i=0; i<data.F.rows();++i)
  1218. for (unsigned j=0;j<3;++j)
  1219. V_uv_vbo.col(i*3+j) = data.V_uv.row(data.F(i,j)).transpose().cast<float>();
  1220. }
  1221. }
  1222. }
  1223. else
  1224. {
  1225. if (dirty & DIRTY_POSITION)
  1226. {
  1227. V_vbo.resize(3,data.F.rows()*3);
  1228. for (unsigned i=0; i<data.F.rows();++i)
  1229. for (unsigned j=0;j<3;++j)
  1230. V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
  1231. }
  1232. if (dirty & DIRTY_AMBIENT)
  1233. {
  1234. V_ambient_vbo.resize(3,data.F.rows()*3);
  1235. for (unsigned i=0; i<data.F.rows();++i)
  1236. for (unsigned j=0;j<3;++j)
  1237. V_ambient_vbo.col (i*3+j) = data.F_material_ambient.row(i).transpose().cast<float>();
  1238. }
  1239. if (dirty & DIRTY_DIFFUSE)
  1240. {
  1241. V_diffuse_vbo.resize(3,data.F.rows()*3);
  1242. for (unsigned i=0; i<data.F.rows();++i)
  1243. for (unsigned j=0;j<3;++j)
  1244. V_diffuse_vbo.col (i*3+j) = data.F_material_diffuse.row(i).transpose().cast<float>();
  1245. }
  1246. if (dirty & DIRTY_SPECULAR)
  1247. {
  1248. V_specular_vbo.resize(3,data.F.rows()*3);
  1249. for (unsigned i=0; i<data.F.rows();++i)
  1250. for (unsigned j=0;j<3;++j)
  1251. V_specular_vbo.col(i*3+j) = data.F_material_specular.row(i).transpose().cast<float>();
  1252. }
  1253. if (dirty & DIRTY_NORMAL)
  1254. {
  1255. V_normals_vbo.resize(3,data.F.rows()*3);
  1256. for (unsigned i=0; i<data.F.rows();++i)
  1257. for (unsigned j=0;j<3;++j)
  1258. V_normals_vbo.col (i*3+j) =
  1259. per_corner_normals ?
  1260. data.F_normals.row(i*3+j).transpose().cast<float>() :
  1261. data.F_normals.row(i).transpose().cast<float>();
  1262. if (invert_normals)
  1263. V_normals_vbo = -V_normals_vbo;
  1264. }
  1265. if (dirty & DIRTY_FACE)
  1266. {
  1267. F_vbo.resize(3,data.F.rows());
  1268. for (unsigned i=0; i<data.F.rows();++i)
  1269. F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
  1270. }
  1271. if (dirty & DIRTY_UV)
  1272. {
  1273. V_uv_vbo.resize(2,data.F.rows()*3);
  1274. for (unsigned i=0; i<data.F.rows();++i)
  1275. for (unsigned j=0;j<3;++j)
  1276. 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>();
  1277. }
  1278. }
  1279. if (dirty & DIRTY_TEXTURE)
  1280. {
  1281. tex_u = data.texture_R.rows();
  1282. tex_v = data.texture_R.cols();
  1283. tex.resize(data.texture_R.size()*3);
  1284. for (unsigned i=0;i<data.texture_R.size();++i)
  1285. {
  1286. tex(i*3+0) = data.texture_R(i);
  1287. tex(i*3+1) = data.texture_G(i);
  1288. tex(i*3+2) = data.texture_B(i);
  1289. }
  1290. }
  1291. if (dirty & DIRTY_OVERLAY_LINES)
  1292. {
  1293. lines_V_vbo.resize(3, data.lines.rows()*2);
  1294. lines_V_colors_vbo.resize(3, data.lines.rows()*2);
  1295. lines_F_vbo.resize(1, data.lines.rows()*2);
  1296. for (unsigned i=0; i<data.lines.rows();++i)
  1297. {
  1298. lines_V_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 0).transpose().cast<float>();
  1299. lines_V_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 3).transpose().cast<float>();
  1300. lines_V_colors_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
  1301. lines_V_colors_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
  1302. lines_F_vbo(2*i+0) = 2*i+0;
  1303. lines_F_vbo(2*i+1) = 2*i+1;
  1304. }
  1305. }
  1306. if (dirty & DIRTY_OVERLAY_POINTS)
  1307. {
  1308. points_V_vbo.resize(3, data.points.rows());
  1309. points_V_colors_vbo.resize(3, data.points.rows());
  1310. points_F_vbo.resize(1, data.points.rows());
  1311. for (unsigned i=0; i<data.points.rows();++i)
  1312. {
  1313. points_V_vbo.col(i) = data.points.block<1, 3>(i, 0).transpose().cast<float>();
  1314. points_V_colors_vbo.col(i) = data.points.block<1, 3>(i, 3).transpose().cast<float>();
  1315. points_F_vbo(i) = i;
  1316. }
  1317. }
  1318. }
  1319. void Viewer::OpenGL_state::bind_mesh()
  1320. {
  1321. glBindVertexArray(vao_mesh);
  1322. shader_mesh.bind();
  1323. shader_mesh.bindVertexAttribArray("position", vbo_V, V_vbo, dirty & DIRTY_POSITION);
  1324. shader_mesh.bindVertexAttribArray("normal", vbo_V_normals, V_normals_vbo, dirty & DIRTY_NORMAL);
  1325. shader_mesh.bindVertexAttribArray("Ka", vbo_V_ambient, V_ambient_vbo, dirty & DIRTY_AMBIENT);
  1326. shader_mesh.bindVertexAttribArray("Kd", vbo_V_diffuse, V_diffuse_vbo, dirty & DIRTY_DIFFUSE);
  1327. shader_mesh.bindVertexAttribArray("Ks", vbo_V_specular, V_specular_vbo, dirty & DIRTY_SPECULAR);
  1328. shader_mesh.bindVertexAttribArray("texcoord", vbo_V_uv, V_uv_vbo, dirty & DIRTY_UV);
  1329. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_F);
  1330. if (dirty & DIRTY_FACE)
  1331. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*F_vbo.size(), F_vbo.data(), GL_DYNAMIC_DRAW);
  1332. glActiveTexture(GL_TEXTURE0);
  1333. glBindTexture(GL_TEXTURE_2D, vbo_tex);
  1334. if (dirty & DIRTY_TEXTURE)
  1335. {
  1336. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  1337. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  1338. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1339. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1340. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_u, tex_v, 0, GL_RGB, GL_UNSIGNED_BYTE, tex.data());
  1341. }
  1342. glUniform1i(shader_mesh.uniform("tex"), 0);
  1343. dirty &= ~DIRTY_MESH;
  1344. }
  1345. void Viewer::OpenGL_state::bind_overlay_lines()
  1346. {
  1347. bool is_dirty = dirty & DIRTY_OVERLAY_LINES;
  1348. glBindVertexArray(vao_overlay_lines);
  1349. shader_overlay_lines.bind();
  1350. shader_overlay_lines.bindVertexAttribArray("position", vbo_lines_V, lines_V_vbo, is_dirty);
  1351. shader_overlay_lines.bindVertexAttribArray("color", vbo_lines_V_colors, lines_V_colors_vbo, is_dirty);
  1352. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_lines_F);
  1353. if (is_dirty)
  1354. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*lines_F_vbo.size(), lines_F_vbo.data(), GL_DYNAMIC_DRAW);
  1355. dirty &= ~DIRTY_OVERLAY_LINES;
  1356. }
  1357. void Viewer::OpenGL_state::bind_overlay_points()
  1358. {
  1359. bool is_dirty = dirty & DIRTY_OVERLAY_POINTS;
  1360. glBindVertexArray(vao_overlay_points);
  1361. shader_overlay_points.bind();
  1362. shader_overlay_points.bindVertexAttribArray("position", vbo_points_V, points_V_vbo, is_dirty);
  1363. shader_overlay_points.bindVertexAttribArray("color", vbo_points_V_colors, points_V_colors_vbo, is_dirty);
  1364. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_points_F);
  1365. if (is_dirty)
  1366. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*points_F_vbo.size(), points_F_vbo.data(), GL_DYNAMIC_DRAW);
  1367. dirty &= ~DIRTY_OVERLAY_POINTS;
  1368. }
  1369. void Viewer::OpenGL_state::draw_mesh(bool solid)
  1370. {
  1371. glPolygonMode(GL_FRONT_AND_BACK, solid ? GL_FILL : GL_LINE);
  1372. /* Avoid Z-buffer fighting between filled triangles & wireframe lines */
  1373. if (solid)
  1374. {
  1375. glEnable(GL_POLYGON_OFFSET_FILL);
  1376. glPolygonOffset(1.0, 1.0);
  1377. }
  1378. glDrawElements(GL_TRIANGLES, 3*F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1379. glDisable(GL_POLYGON_OFFSET_FILL);
  1380. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1381. }
  1382. void Viewer::OpenGL_state::draw_overlay_lines()
  1383. {
  1384. glDrawElements(GL_LINES, lines_F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1385. }
  1386. void Viewer::OpenGL_state::draw_overlay_points()
  1387. {
  1388. glDrawElements(GL_POINTS, points_F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1389. }
  1390. void Viewer::init_opengl()
  1391. {
  1392. std::string mesh_vertex_shader_string =
  1393. "#version 150\n"
  1394. "uniform mat4 model;"
  1395. "uniform mat4 view;"
  1396. "uniform mat4 proj;"
  1397. "in vec3 position;"
  1398. "in vec3 normal;"
  1399. "out vec3 position_eye;"
  1400. "out vec3 normal_eye;"
  1401. "in vec3 Ka;"
  1402. "in vec3 Kd;"
  1403. "in vec3 Ks;"
  1404. "in vec2 texcoord;"
  1405. "out vec2 texcoordi;"
  1406. "out vec3 Kai;"
  1407. "out vec3 Kdi;"
  1408. "out vec3 Ksi;"
  1409. "void main()"
  1410. "{"
  1411. " position_eye = vec3 (view * model * vec4 (position, 1.0));"
  1412. " normal_eye = vec3 (view * model * vec4 (normal, 0.0));"
  1413. " normal_eye = normalize(normal_eye);"
  1414. " gl_Position = proj * vec4 (position_eye, 1.0);" //proj * view * model * vec4(position, 1.0);"
  1415. " Kai = Ka;"
  1416. " Kdi = Kd;"
  1417. " Ksi = Ks;"
  1418. " texcoordi = texcoord;"
  1419. "}";
  1420. std::string mesh_fragment_shader_string =
  1421. "#version 150\n"
  1422. "uniform mat4 model;"
  1423. "uniform mat4 view;"
  1424. "uniform mat4 proj;"
  1425. "uniform vec4 fixed_color;"
  1426. "in vec3 position_eye;"
  1427. "in vec3 normal_eye;"
  1428. "uniform vec3 light_position_world;"
  1429. "vec3 Ls = vec3 (1, 1, 1);"
  1430. "vec3 Ld = vec3 (1, 1, 1);"
  1431. "vec3 La = vec3 (1, 1, 1);"
  1432. "in vec3 Ksi;"
  1433. "in vec3 Kdi;"
  1434. "in vec3 Kai;"
  1435. "in vec2 texcoordi;"
  1436. "uniform sampler2D tex;"
  1437. "uniform float specular_exponent;"
  1438. "uniform float lighting_factor;"
  1439. "uniform float texture_factor;"
  1440. "out vec4 outColor;"
  1441. "void main()"
  1442. "{"
  1443. "vec3 Ia = La * Kai;" // ambient intensity
  1444. "vec3 light_position_eye = vec3 (view * vec4 (light_position_world, 1.0));"
  1445. "vec3 distance_to_light_eye = light_position_eye - position_eye;"
  1446. "vec3 direction_to_light_eye = normalize (distance_to_light_eye);"
  1447. "float dot_prod = dot (direction_to_light_eye, normal_eye);"
  1448. "dot_prod = max (dot_prod, 0.0);"
  1449. "vec3 Id = Ld * Kdi * dot_prod;" // Diffuse intensity
  1450. "vec3 reflection_eye = reflect (-direction_to_light_eye, normal_eye);"
  1451. "vec3 surface_to_viewer_eye = normalize (-position_eye);"
  1452. "float dot_prod_specular = dot (reflection_eye, surface_to_viewer_eye);"
  1453. "dot_prod_specular = max (dot_prod_specular, 0.0);"
  1454. "float specular_factor = pow (dot_prod_specular, specular_exponent);"
  1455. "vec3 Is = Ls * Ksi * specular_factor;" // specular intensity
  1456. "vec4 color = vec4(lighting_factor * (Is + Id) + Ia, 1.0) + vec4((1.0-lighting_factor) * Kdi,1.0);"
  1457. "outColor = mix(vec4(1,1,1,1), texture(tex, texcoordi), texture_factor) * color;"
  1458. "if (fixed_color != vec4(0.0)) outColor = fixed_color;"
  1459. "}";
  1460. std::string overlay_vertex_shader_string =
  1461. "#version 150\n"
  1462. "uniform mat4 model;"
  1463. "uniform mat4 view;"
  1464. "uniform mat4 proj;"
  1465. "in vec3 position;"
  1466. "in vec3 color;"
  1467. "out vec3 color_frag;"
  1468. "void main()"
  1469. "{"
  1470. " gl_Position = proj * view * model * vec4 (position, 1.0);"
  1471. " color_frag = color;"
  1472. "}";
  1473. std::string overlay_fragment_shader_string =
  1474. "#version 150\n"
  1475. "in vec3 color_frag;"
  1476. "out vec4 outColor;"
  1477. "void main()"
  1478. "{"
  1479. " outColor = vec4(color_frag, 1.0);"
  1480. "}";
  1481. std::string overlay_point_fragment_shader_string =
  1482. "#version 150\n"
  1483. "in vec3 color_frag;"
  1484. "out vec4 outColor;"
  1485. "void main()"
  1486. "{"
  1487. " if (length(gl_PointCoord - vec2(0.5)) > 0.5)"
  1488. " discard;"
  1489. " outColor = vec4(color_frag, 1.0);"
  1490. "}";
  1491. opengl.init();
  1492. opengl.shader_mesh.init(mesh_vertex_shader_string,
  1493. mesh_fragment_shader_string, "outColor");
  1494. opengl.shader_overlay_lines.init(overlay_vertex_shader_string,
  1495. overlay_fragment_shader_string, "outColor");
  1496. opengl.shader_overlay_points.init(overlay_vertex_shader_string,
  1497. overlay_point_fragment_shader_string, "outColor");
  1498. }
  1499. void Viewer::free_opengl()
  1500. {
  1501. opengl.shader_mesh.free();
  1502. opengl.shader_overlay_lines.free();
  1503. opengl.shader_overlay_points.free();
  1504. opengl.free();
  1505. __font_renderer.Shut();
  1506. }
  1507. void Viewer::draw()
  1508. {
  1509. using namespace std;
  1510. using namespace Eigen;
  1511. glClearColor(options.background_color[0],
  1512. options.background_color[1],
  1513. options.background_color[2],
  1514. 1.0f);
  1515. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1516. glEnable(GL_DEPTH_TEST);
  1517. if (callback_pre_draw)
  1518. if (callback_pre_draw(*this))
  1519. return;
  1520. if (plugin_manager)
  1521. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1522. if (plugin_manager->plugin_list[i]->pre_draw())
  1523. return;
  1524. /* Bind and potentially refresh mesh/line/point data */
  1525. if (data.dirty)
  1526. {
  1527. opengl.set_data(data, options.face_based, options.invert_normals);
  1528. data.dirty = DIRTY_NONE;
  1529. }
  1530. opengl.bind_mesh();
  1531. // Initialize uniform
  1532. glViewport(0, 0, width, height);
  1533. model = Eigen::Matrix4f::Identity();
  1534. view = Eigen::Matrix4f::Identity();
  1535. proj = Eigen::Matrix4f::Identity();
  1536. // Set view
  1537. view = lookAt(Eigen::Vector3f(options.camera_eye[0], options.camera_eye[1], options.camera_eye[2]),
  1538. Eigen::Vector3f(options.camera_center[0], options.camera_center[1], options.camera_center[2]),
  1539. Eigen::Vector3f(options.camera_up[0], options.camera_up[1], options.camera_up[2]));
  1540. // Set projection
  1541. if (options.orthographic)
  1542. {
  1543. float length = (options.camera_eye - options.camera_center).norm();
  1544. float h = tan(options.camera_view_angle/360.0 * M_PI) * (length);
  1545. proj = ortho(-h*width/height, h*width/height, -h, h, options.camera_dnear, options.camera_dfar);
  1546. }
  1547. else
  1548. {
  1549. float fH = tan(options.camera_view_angle / 360.0 * M_PI) * options.camera_dnear;
  1550. float fW = fH * (double)width/(double)height;
  1551. proj = frustum(-fW, fW, -fH, fH, options.camera_dnear, options.camera_dfar);
  1552. }
  1553. // end projection
  1554. // Set model transformation
  1555. float mat[16];
  1556. igl::quat_to_mat(options.trackball_angle.data(), mat);
  1557. for (unsigned i=0;i<4;++i)
  1558. for (unsigned j=0;j<4;++j)
  1559. model(i,j) = mat[i+4*j];
  1560. model = scale(model, Eigen::Vector3f(options.camera_zoom,options.camera_zoom,options.camera_zoom));
  1561. model = scale(model, Eigen::Vector3f(options.model_zoom,options.model_zoom,options.model_zoom));
  1562. model = translate(model, Eigen::Vector3f(options.model_translation[0],options.model_translation[1],options.model_translation[2]));
  1563. // Send transformations to the GPU
  1564. GLint modeli = opengl.shader_mesh.uniform("model");
  1565. GLint viewi = opengl.shader_mesh.uniform("view");
  1566. GLint proji = opengl.shader_mesh.uniform("proj");
  1567. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1568. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1569. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1570. // Light parameters
  1571. GLint specular_exponenti = opengl.shader_mesh.uniform("specular_exponent");
  1572. GLint light_position_worldi = opengl.shader_mesh.uniform("light_position_world");
  1573. GLint lighting_factori = opengl.shader_mesh.uniform("lighting_factor");
  1574. GLint fixed_colori = opengl.shader_mesh.uniform("fixed_color");
  1575. GLint texture_factori = opengl.shader_mesh.uniform("texture_factor");
  1576. glUniform1f(specular_exponenti, options.shininess);
  1577. Vector3f rev_light = -1.*options.light_position;
  1578. glUniform3fv(light_position_worldi, 1, rev_light.data());
  1579. glUniform1f(lighting_factori, options.lighting_factor); // enables lighting
  1580. glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);
  1581. if (data.V.rows()>0)
  1582. {
  1583. // Render fill
  1584. if (options.show_faces)
  1585. {
  1586. // Texture
  1587. glUniform1f(texture_factori, options.show_texture ? 1.0f : 0.0f);
  1588. opengl.draw_mesh(true);
  1589. glUniform1f(texture_factori, 0.0f);
  1590. }
  1591. // Render wireframe
  1592. if (options.show_lines)
  1593. {
  1594. glLineWidth(options.line_width);
  1595. glUniform4f(fixed_colori, options.line_color[0], options.line_color[1],
  1596. options.line_color[2], 1.0f);
  1597. opengl.draw_mesh(false);
  1598. glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);
  1599. }
  1600. if (options.show_vertid)
  1601. {
  1602. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1603. for (int i=0; i<data.V.rows(); ++i)
  1604. __font_renderer.DrawText(data.V.row(i), data.V_normals.row(i), to_string(i));
  1605. __font_renderer.EndDraw();
  1606. }
  1607. if (options.show_faceid)
  1608. {
  1609. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1610. for (int i=0; i<data.F.rows(); ++i)
  1611. {
  1612. Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
  1613. for (int j=0;j<data.F.cols();++j)
  1614. p += data.V.row(data.F(i,j));
  1615. p /= data.F.cols();
  1616. __font_renderer.DrawText(p, data.F_normals.row(i), to_string(i));
  1617. }
  1618. __font_renderer.EndDraw();
  1619. }
  1620. }
  1621. if (options.show_overlay)
  1622. {
  1623. if (options.show_overlay_depth)
  1624. glEnable(GL_DEPTH_TEST);
  1625. else
  1626. glDisable(GL_DEPTH_TEST);
  1627. if (data.lines.rows() > 0)
  1628. {
  1629. opengl.bind_overlay_lines();
  1630. modeli = opengl.shader_overlay_lines.uniform("model");
  1631. viewi = opengl.shader_overlay_lines.uniform("view");
  1632. proji = opengl.shader_overlay_lines.uniform("proj");
  1633. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1634. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1635. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1636. glLineWidth(options.line_width);
  1637. opengl.draw_overlay_lines();
  1638. }
  1639. if (data.points.rows() > 0)
  1640. {
  1641. opengl.bind_overlay_points();
  1642. modeli = opengl.shader_overlay_points.uniform("model");
  1643. viewi = opengl.shader_overlay_points.uniform("view");
  1644. proji = opengl.shader_overlay_points.uniform("proj");
  1645. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1646. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1647. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1648. glPointSize(options.point_size);
  1649. opengl.draw_overlay_points();
  1650. }
  1651. if (data.labels_positions.rows() > 0)
  1652. {
  1653. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1654. for (int i=0; i<data.labels_positions.rows(); ++i)
  1655. __font_renderer.DrawText(data.labels_positions.row(i), Eigen::Vector3d(0.0,0.0,0.0),
  1656. data.labels_strings[i]);
  1657. __font_renderer.EndDraw();
  1658. }
  1659. glEnable(GL_DEPTH_TEST);
  1660. }
  1661. if (callback_post_draw)
  1662. if (callback_post_draw(*this))
  1663. return;
  1664. if (plugin_manager)
  1665. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1666. if (plugin_manager->plugin_list[i]->post_draw())
  1667. break;
  1668. TwDraw();
  1669. }
  1670. bool Viewer::save_scene()
  1671. {
  1672. #ifdef ENABLE_XML_SERIALIZATION
  1673. string fname = igl::file_dialog_save();
  1674. if (fname.length() == 0)
  1675. return false;
  1676. ::igl::XMLSerializer serializer("Viewer");
  1677. serializer.Add(data,"Data");
  1678. serializer.Add(options,"Options");
  1679. if (plugin_manager)
  1680. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1681. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1682. serializer.Save(fname.c_str(),true);
  1683. #endif
  1684. return true;
  1685. }
  1686. bool Viewer::load_scene()
  1687. {
  1688. #ifdef ENABLE_XML_SERIALIZATION
  1689. string fname = igl::file_dialog_open();
  1690. if (fname.length() == 0)
  1691. return false;
  1692. ::igl::XMLSerializer serializer("Viewer");
  1693. serializer.Add(data,"Data");
  1694. serializer.Add(options,"Options");
  1695. if (plugin_manager)
  1696. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1697. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1698. serializer.Load(fname.c_str());
  1699. #endif
  1700. return true;
  1701. }
  1702. void Viewer::align_camera_center()
  1703. {
  1704. get_scale_and_shift_to_fit_mesh(data.V,data.F,options.model_zoom,options.model_translation);
  1705. data.object_scale = (data.V.colwise().maxCoeff() - data.V.colwise().minCoeff()).norm();
  1706. }
  1707. void Viewer::resize(int w, int h)
  1708. {
  1709. width = w;
  1710. height = h;
  1711. viewport = Eigen::Vector4f(0,0,width,height);
  1712. }
  1713. void Viewer::get_scale_and_shift_to_fit_mesh(
  1714. const Eigen::MatrixXd& V,
  1715. const Eigen::MatrixXi& F,
  1716. float& zoom,
  1717. Eigen::Vector3f& shift)
  1718. {
  1719. if (V.rows() == 0)
  1720. return;
  1721. //Compute mesh centroid
  1722. Eigen::SparseMatrix<double> M;
  1723. igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);
  1724. const auto & MV = M*V;
  1725. Eigen::RowVector3d centroid = MV.colwise().sum()/M.diagonal().sum();
  1726. Eigen::RowVector3d min_point = V.colwise().minCoeff();
  1727. Eigen::RowVector3d max_point = V.colwise().maxCoeff();
  1728. shift = -centroid.cast<float>();
  1729. double x_scale = fabs(max_point[0] - min_point[0]);
  1730. double y_scale = fabs(max_point[1] - min_point[1]);
  1731. double z_scale = fabs(max_point[2] - min_point[2]);
  1732. zoom = 2.0/ std::max(z_scale,std::max(x_scale,y_scale));
  1733. }
  1734. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  1735. {
  1736. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->options.trackball_angle;
  1737. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->options.trackball_angle.data());
  1738. }
  1739. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  1740. {
  1741. static_cast<Viewer *>(clientData)->align_camera_center();
  1742. }
  1743. void TW_CALL Viewer::save_scene_cb(void *clientData)
  1744. {
  1745. static_cast<Viewer *>(clientData)->save_scene();
  1746. }
  1747. void TW_CALL Viewer::load_scene_cb(void *clientData)
  1748. {
  1749. static_cast<Viewer *>(clientData)->load_scene();
  1750. }
  1751. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  1752. {
  1753. Viewer *viewer = static_cast<Viewer *>(clientData);
  1754. viewer->data.dirty |= Viewer::DIRTY_NORMAL;
  1755. viewer->options.invert_normals = *((bool *) param);
  1756. }
  1757. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  1758. {
  1759. *((bool *) param) = static_cast<Viewer *>(clientData)->options.invert_normals;
  1760. }
  1761. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  1762. {
  1763. Viewer *viewer = static_cast<Viewer *>(clientData);
  1764. viewer->set_face_based(*((bool *) param));
  1765. }
  1766. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  1767. {
  1768. *((bool *) param) = static_cast<Viewer *>(clientData)->options.face_based;
  1769. }
  1770. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  1771. {
  1772. std::string fname = igl::file_dialog_open();
  1773. if (fname.length() == 0)
  1774. return;
  1775. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  1776. }
  1777. // Serialization
  1778. void Viewer::Options::InitSerialization()
  1779. {
  1780. #ifdef ENABLE_XML_SERIALIZATION
  1781. xmlSerializer->Add(shininess, "shininess");
  1782. xmlSerializer->Add(background_color, "background_color");
  1783. xmlSerializer->Add(line_color, "line_color");
  1784. xmlSerializer->Add(light_position, "light_position");
  1785. xmlSerializer->Add(lighting_factor, "lighting_factor");
  1786. xmlSerializer->Add(trackball_angle, "trackball_angle");
  1787. xmlSerializer->Add(model_zoom, "model_zoom");
  1788. xmlSerializer->Add(model_translation, "model_translation");
  1789. xmlSerializer->Add(model_zoom_uv, "model_zoom_uv");
  1790. xmlSerializer->Add(model_translation_uv, "model_translation_uv");
  1791. xmlSerializer->Add(camera_zoom, "camera_zoom");
  1792. xmlSerializer->Add(orthographic, "orthographic");
  1793. xmlSerializer->Add(camera_eye, "camera_eye");
  1794. xmlSerializer->Add(camera_up, "camera_up");
  1795. xmlSerializer->Add(camera_center, "camera_center");
  1796. xmlSerializer->Add(camera_view_angle, "camera_view_angle");
  1797. xmlSerializer->Add(camera_dnear, "camera_dnear");
  1798. xmlSerializer->Add(camera_dfar, "camera_dfar");
  1799. xmlSerializer->Add(show_overlay, "show_overlay");
  1800. xmlSerializer->Add(show_overlay_depth, "show_overlay_depth");
  1801. xmlSerializer->Add(show_texture, "show_texture");
  1802. xmlSerializer->Add(show_faces, "show_faces");
  1803. xmlSerializer->Add(show_lines, "show_lines");
  1804. xmlSerializer->Add(show_vertid, "show_vertid");
  1805. xmlSerializer->Add(show_faceid, "show_faceid");
  1806. xmlSerializer->Add(point_size, "point_size");
  1807. xmlSerializer->Add(line_width, "line_width");
  1808. xmlSerializer->Add(invert_normals, "invert_normals");
  1809. xmlSerializer->Add(face_based, "face_based");
  1810. #endif
  1811. }
  1812. void Viewer::Data::InitSerialization()
  1813. {
  1814. #ifdef ENABLE_XML_SERIALIZATION
  1815. xmlSerializer->Add(V,"V");
  1816. xmlSerializer->Add(F,"F");
  1817. xmlSerializer->Add(F_normals,"F_normals");
  1818. xmlSerializer->Add(F_material_ambient,"F_material_ambient");
  1819. xmlSerializer->Add(F_material_diffuse,"F_material_diffuse");
  1820. xmlSerializer->Add(F_material_specular,"F_material_specular");
  1821. xmlSerializer->Add(V_normals,"V_normals");
  1822. xmlSerializer->Add(V_material_ambient,"V_material_ambient");
  1823. xmlSerializer->Add(V_material_diffuse,"V_material_diffuse");
  1824. xmlSerializer->Add(V_material_specular,"V_material_specular");
  1825. xmlSerializer->Add(V_uv,"V_uv");
  1826. xmlSerializer->Add(F_uv,"F_uv");
  1827. xmlSerializer->Add(texture_R,"texture_R");
  1828. xmlSerializer->Add(texture_G,"texture_G");
  1829. xmlSerializer->Add(texture_B,"texture_B");
  1830. xmlSerializer->Add(lines,"lines");
  1831. xmlSerializer->Add(points,"points");
  1832. xmlSerializer->Add(labels_positions,"labels_positions");
  1833. xmlSerializer->Add(labels_strings,"labels_strings");
  1834. #endif
  1835. }
  1836. void Viewer::set_face_based(bool newvalue)
  1837. {
  1838. if (options.face_based != newvalue)
  1839. {
  1840. options.face_based = newvalue;
  1841. data.dirty = DIRTY_ALL;
  1842. }
  1843. }
  1844. // Helpers that draws the most common meshes
  1845. void Viewer::set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)
  1846. {
  1847. using namespace std;
  1848. Eigen::MatrixXd V_temp;
  1849. // If V only has two columns, pad with a column of zeros
  1850. if (V.cols() == 2)
  1851. {
  1852. V_temp = Eigen::MatrixXd::Zero(V.rows(),3);
  1853. V_temp.block(0,0,V.rows(),2) = V;
  1854. }
  1855. else
  1856. V_temp = V;
  1857. if (data.V.rows() == 0 && data.F.rows() == 0)
  1858. {
  1859. clear_mesh();
  1860. data.V = V_temp;
  1861. data.F = F;
  1862. compute_normals();
  1863. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  1864. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  1865. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  1866. grid_texture();
  1867. align_camera_center();
  1868. }
  1869. else
  1870. {
  1871. if (data.V.rows() == V.rows() && data.F.rows() == F.rows())
  1872. {
  1873. data.V = V_temp;
  1874. data.F = F;
  1875. align_camera_center();
  1876. }
  1877. else
  1878. cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
  1879. }
  1880. data.dirty |= DIRTY_FACE | DIRTY_POSITION;
  1881. }
  1882. void Viewer::set_vertices(const Eigen::MatrixXd& V)
  1883. {
  1884. data.V = V;
  1885. assert(data.F.size() == 0 || data.F.maxCoeff() < data.V.rows());
  1886. data.dirty |= DIRTY_POSITION;
  1887. }
  1888. void Viewer::set_normals(const Eigen::MatrixXd& N)
  1889. {
  1890. using namespace std;
  1891. if (N.rows() == data.V.rows())
  1892. {
  1893. set_face_based(false);
  1894. data.V_normals = N;
  1895. }
  1896. else if (N.rows() == data.F.rows() || N.rows() == data.F.rows()*3)
  1897. {
  1898. set_face_based(true);
  1899. data.F_normals = N;
  1900. }
  1901. else
  1902. cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex.";
  1903. data.dirty |= DIRTY_NORMAL;
  1904. }
  1905. void Viewer::set_colors(const Eigen::MatrixXd &C)
  1906. {
  1907. using namespace std;
  1908. using namespace Eigen;
  1909. // Ambient color should be darker color
  1910. const auto ambient = [](const MatrixXd & C)->MatrixXd
  1911. {
  1912. return 0.1*C;
  1913. };
  1914. // Specular color should be a less saturated and darker color: dampened
  1915. // highlights
  1916. const auto specular = [](const MatrixXd & C)->MatrixXd
  1917. {
  1918. const double grey = 0.3;
  1919. return grey+0.1*(C.array()-grey);
  1920. };
  1921. if (C.rows() == 1)
  1922. {
  1923. for (unsigned i=0;i<data.V_material_diffuse.rows();++i)
  1924. {
  1925. data.V_material_diffuse.row(i) = C.row(0);
  1926. }
  1927. data.V_material_ambient = ambient(data.V_material_diffuse);
  1928. data.V_material_specular = specular(data.V_material_diffuse);
  1929. for (unsigned i=0;i<data.F_material_diffuse.rows();++i)
  1930. {
  1931. data.F_material_diffuse.row(i) = C.row(0);
  1932. }
  1933. data.F_material_ambient = ambient(data.F_material_diffuse);
  1934. data.F_material_specular = specular(data.F_material_diffuse);
  1935. }
  1936. else if (C.rows() == data.V.rows())
  1937. {
  1938. set_face_based(false);
  1939. data.V_material_diffuse = C;
  1940. data.V_material_ambient = ambient(data.V_material_diffuse);
  1941. data.V_material_specular = specular(data.V_material_diffuse);
  1942. }
  1943. else if (C.rows() == data.F.rows())
  1944. {
  1945. set_face_based(true);
  1946. data.F_material_diffuse = C;
  1947. data.F_material_ambient = ambient(data.F_material_diffuse);
  1948. data.F_material_specular = specular(data.F_material_diffuse);
  1949. }
  1950. else
  1951. cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex.";
  1952. data.dirty |= DIRTY_DIFFUSE;
  1953. }
  1954. void Viewer::set_uv(const Eigen::MatrixXd& UV)
  1955. {
  1956. using namespace std;
  1957. if (UV.rows() == data.V.rows())
  1958. {
  1959. set_face_based(false);
  1960. data.V_uv = UV;
  1961. }
  1962. else
  1963. cerr << "ERROR (set_UV): Please provide uv per vertex.";
  1964. data.dirty |= DIRTY_UV;
  1965. }
  1966. void Viewer::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
  1967. {
  1968. set_face_based(true);
  1969. data.V_uv = UV_V;
  1970. data.F_uv = UV_F;
  1971. data.dirty |= DIRTY_UV;
  1972. }
  1973. void Viewer::set_texture(
  1974. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  1975. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  1976. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
  1977. {
  1978. data.texture_R = R;
  1979. data.texture_G = G;
  1980. data.texture_B = B;
  1981. data.dirty |= DIRTY_TEXTURE;
  1982. }
  1983. void Viewer::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C)
  1984. {
  1985. Eigen::MatrixXd P_temp;
  1986. // If P only has two columns, pad with a column of zeros
  1987. if (P.cols() == 2)
  1988. {
  1989. P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
  1990. P_temp.block(0,0,P.rows(),2) = P;
  1991. }
  1992. else
  1993. P_temp = P;
  1994. int lastid = data.points.rows();
  1995. data.points.conservativeResize(data.points.rows() + P_temp.rows(),6);
  1996. for (unsigned i=0; i<P_temp.rows(); ++i)
  1997. data.points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1998. data.dirty |= DIRTY_OVERLAY_POINTS;
  1999. }
  2000. void Viewer::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
  2001. {
  2002. Eigen::MatrixXd P1_temp,P2_temp;
  2003. // If P1 only has two columns, pad with a column of zeros
  2004. if (P1.cols() == 2)
  2005. {
  2006. P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);
  2007. P1_temp.block(0,0,P1.rows(),2) = P1;
  2008. P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);
  2009. P2_temp.block(0,0,P2.rows(),2) = P2;
  2010. }
  2011. else
  2012. {
  2013. P1_temp = P1;
  2014. P2_temp = P2;
  2015. }
  2016. int lastid = data.lines.rows();
  2017. data.lines.conservativeResize(data.lines.rows() + P1_temp.rows(),9);
  2018. for (unsigned i=0; i<P1_temp.rows(); ++i)
  2019. data.lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  2020. data.dirty |= DIRTY_OVERLAY_LINES;
  2021. }
  2022. void Viewer::add_label(const Eigen::VectorXd& P, const std::string& str)
  2023. {
  2024. Eigen::MatrixXd P_temp;
  2025. // If P only has two columns, pad with a column of zeros
  2026. if (P.cols() == 2)
  2027. {
  2028. P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
  2029. P_temp.block(0,0,P.rows(),2) = P;
  2030. }
  2031. else
  2032. P_temp = P;
  2033. int lastid = data.labels_positions.rows();
  2034. data.labels_positions.conservativeResize(lastid+1, 3);
  2035. data.labels_positions.row(lastid) = P_temp;
  2036. data.labels_strings.push_back(str);
  2037. }
  2038. int Viewer::launch(std::string filename)
  2039. {
  2040. GLFWwindow* window;
  2041. glfwSetErrorCallback(glfw_error_callback);
  2042. if (!glfwInit())
  2043. return EXIT_FAILURE;
  2044. glfwWindowHint(GLFW_SAMPLES, 16);
  2045. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  2046. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  2047. #ifdef __APPLE__
  2048. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  2049. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  2050. #endif
  2051. window = glfwCreateWindow(1280, 800, "IGL Viewer", NULL, NULL);
  2052. if (!window)
  2053. {
  2054. glfwTerminate();
  2055. return EXIT_FAILURE;
  2056. }
  2057. glfwMakeContextCurrent(window);
  2058. #ifndef __APPLE__
  2059. glewExperimental = true;
  2060. GLenum err = glewInit();
  2061. if (GLEW_OK != err)
  2062. {
  2063. /* Problem: glewInit failed, something is seriously wrong. */
  2064. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  2065. }
  2066. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  2067. #endif
  2068. #ifdef DEBUG
  2069. int major, minor, rev;
  2070. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  2071. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  2072. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  2073. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  2074. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  2075. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  2076. #endif
  2077. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  2078. // Initialize AntTweakBar
  2079. TwInit(TW_OPENGL_CORE, NULL);
  2080. // Initialize IGL viewer
  2081. init(&igl_viewer_plugin_manager);
  2082. __viewer = this;
  2083. // Register callbacks
  2084. glfwSetKeyCallback(window, glfw_key_callback);
  2085. glfwSetCursorPosCallback(window,glfw_mouse_move);
  2086. glfwSetWindowSizeCallback(window,glfw_window_size);
  2087. glfwSetMouseButtonCallback(window,glfw_mouse_press);
  2088. glfwSetScrollCallback(window,glfw_mouse_scroll);
  2089. glfwSetCharCallback(window, glfw_char_callback);
  2090. // Handle retina displays (windows and mac)
  2091. int width, height;
  2092. glfwGetFramebufferSize(window, &width, &height);
  2093. int width_window, height_window;
  2094. glfwGetWindowSize(window, &width_window, &height_window);
  2095. highdpi = width/width_window;
  2096. glfw_window_size(window,width_window,height_window);
  2097. init_opengl();
  2098. // Load the mesh passed as input
  2099. if (filename.size() > 0)
  2100. load_mesh_from_file(filename.c_str());
  2101. // Rendering loop
  2102. while (!glfwWindowShouldClose(window))
  2103. {
  2104. draw();
  2105. glfwSwapBuffers(window);
  2106. //glfwPollEvents();
  2107. glfwWaitEvents();
  2108. }
  2109. free_opengl();
  2110. shutdown_plugins();
  2111. glfwDestroyWindow(window);
  2112. glfwTerminate();
  2113. return EXIT_SUCCESS;
  2114. }
  2115. } // end namespace