Viewer.cpp 74 KB

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