imgui_impl_glfw_gl3.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. // ImGui GLFW binding with OpenGL3 + shaders
  2. // https://github.com/ocornut/imgui
  3. #include <imgui.h>
  4. #include "imgui_impl_glfw_gl3.h"
  5. // GL3W/GLFW
  6. #include <GL/gl3w.h>
  7. #include <GLFW/glfw3.h>
  8. #ifdef _WIN32
  9. #undef APIENTRY
  10. #define GLFW_EXPOSE_NATIVE_WIN32
  11. #define GLFW_EXPOSE_NATIVE_WGL
  12. #include <GLFW/glfw3native.h>
  13. #endif
  14. // Data
  15. static GLFWwindow* g_Window = NULL;
  16. static double g_Time = 0.0f;
  17. static bool g_MousePressed[3] = { false, false, false };
  18. static float g_MouseWheel = 0.0f;
  19. static GLuint g_FontTexture = 0;
  20. static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
  21. static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
  22. static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
  23. static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
  24. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  25. // If text or lines are blurry when integrating ImGui in your engine:
  26. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  27. void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data)
  28. {
  29. // Backup GL state
  30. GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
  31. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  32. GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
  33. GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
  34. GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
  35. GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
  36. GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
  37. GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
  38. GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
  39. GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
  40. GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
  41. GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
  42. GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
  43. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  44. glEnable(GL_BLEND);
  45. glBlendEquation(GL_FUNC_ADD);
  46. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  47. glDisable(GL_CULL_FACE);
  48. glDisable(GL_DEPTH_TEST);
  49. glEnable(GL_SCISSOR_TEST);
  50. glActiveTexture(GL_TEXTURE0);
  51. // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
  52. ImGuiIO& io = ImGui::GetIO();
  53. float fb_height = io.DisplaySize.y * io.DisplayFramebufferScale.y;
  54. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  55. // Setup orthographic projection matrix
  56. const float ortho_projection[4][4] =
  57. {
  58. { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f },
  59. { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
  60. { 0.0f, 0.0f, -1.0f, 0.0f },
  61. {-1.0f, 1.0f, 0.0f, 1.0f },
  62. };
  63. glUseProgram(g_ShaderHandle);
  64. glUniform1i(g_AttribLocationTex, 0);
  65. glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
  66. glBindVertexArray(g_VaoHandle);
  67. for (int n = 0; n < draw_data->CmdListsCount; n++)
  68. {
  69. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  70. const ImDrawIdx* idx_buffer_offset = 0;
  71. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  72. glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);
  73. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
  74. glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);
  75. for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
  76. {
  77. if (pcmd->UserCallback)
  78. {
  79. pcmd->UserCallback(cmd_list, pcmd);
  80. }
  81. else
  82. {
  83. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  84. glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  85. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer_offset);
  86. }
  87. idx_buffer_offset += pcmd->ElemCount;
  88. }
  89. }
  90. // Restore modified GL state
  91. glUseProgram(last_program);
  92. glBindTexture(GL_TEXTURE_2D, last_texture);
  93. glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
  94. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
  95. glBindVertexArray(last_vertex_array);
  96. glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
  97. glBlendFunc(last_blend_src, last_blend_dst);
  98. if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
  99. if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
  100. if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
  101. if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
  102. }
  103. static const char* ImGui_ImplGlfwGL3_GetClipboardText()
  104. {
  105. return glfwGetClipboardString(g_Window);
  106. }
  107. static void ImGui_ImplGlfwGL3_SetClipboardText(const char* text)
  108. {
  109. glfwSetClipboardString(g_Window, text);
  110. }
  111. void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
  112. {
  113. if (action == GLFW_PRESS && button >= 0 && button < 3)
  114. g_MousePressed[button] = true;
  115. }
  116. void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
  117. {
  118. g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  119. }
  120. void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
  121. {
  122. ImGuiIO& io = ImGui::GetIO();
  123. if (action == GLFW_PRESS)
  124. io.KeysDown[key] = true;
  125. if (action == GLFW_RELEASE)
  126. io.KeysDown[key] = false;
  127. (void)mods; // Modifiers are not reliable across systems
  128. io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
  129. io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
  130. io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
  131. }
  132. void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c)
  133. {
  134. ImGuiIO& io = ImGui::GetIO();
  135. if (c > 0 && c < 0x10000)
  136. io.AddInputCharacter((unsigned short)c);
  137. }
  138. void ImGui_ImplGlfwGL3_CreateFontsTexture()
  139. {
  140. ImGuiIO& io = ImGui::GetIO();
  141. // Build texture atlas
  142. unsigned char* pixels;
  143. int width, height;
  144. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
  145. // Create OpenGL texture
  146. glGenTextures(1, &g_FontTexture);
  147. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  148. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  149. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  150. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  151. // Store our identifier
  152. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  153. // Cleanup (don't clear the input data if you want to append new fonts later)
  154. io.Fonts->ClearInputData();
  155. io.Fonts->ClearTexData();
  156. }
  157. bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
  158. {
  159. // Backup GL state
  160. GLint last_texture, last_array_buffer, last_vertex_array;
  161. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  162. glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
  163. glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
  164. const GLchar *vertex_shader =
  165. "#version 330\n"
  166. "uniform mat4 ProjMtx;\n"
  167. "in vec2 Position;\n"
  168. "in vec2 UV;\n"
  169. "in vec4 Color;\n"
  170. "out vec2 Frag_UV;\n"
  171. "out vec4 Frag_Color;\n"
  172. "void main()\n"
  173. "{\n"
  174. " Frag_UV = UV;\n"
  175. " Frag_Color = Color;\n"
  176. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  177. "}\n";
  178. const GLchar* fragment_shader =
  179. "#version 330\n"
  180. "uniform sampler2D Texture;\n"
  181. "in vec2 Frag_UV;\n"
  182. "in vec4 Frag_Color;\n"
  183. "out vec4 Out_Color;\n"
  184. "void main()\n"
  185. "{\n"
  186. " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
  187. "}\n";
  188. g_ShaderHandle = glCreateProgram();
  189. g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
  190. g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
  191. glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
  192. glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
  193. glCompileShader(g_VertHandle);
  194. glCompileShader(g_FragHandle);
  195. glAttachShader(g_ShaderHandle, g_VertHandle);
  196. glAttachShader(g_ShaderHandle, g_FragHandle);
  197. glLinkProgram(g_ShaderHandle);
  198. g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
  199. g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
  200. g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
  201. g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
  202. g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
  203. glGenBuffers(1, &g_VboHandle);
  204. glGenBuffers(1, &g_ElementsHandle);
  205. glGenVertexArrays(1, &g_VaoHandle);
  206. glBindVertexArray(g_VaoHandle);
  207. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  208. glEnableVertexAttribArray(g_AttribLocationPosition);
  209. glEnableVertexAttribArray(g_AttribLocationUV);
  210. glEnableVertexAttribArray(g_AttribLocationColor);
  211. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  212. glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  213. glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  214. glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  215. #undef OFFSETOF
  216. ImGui_ImplGlfwGL3_CreateFontsTexture();
  217. // Restore modified GL state
  218. glBindTexture(GL_TEXTURE_2D, last_texture);
  219. glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
  220. glBindVertexArray(last_vertex_array);
  221. return true;
  222. }
  223. bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks)
  224. {
  225. g_Window = window;
  226. ImGuiIO& io = ImGui::GetIO();
  227. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  228. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  229. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  230. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  231. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  232. io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
  233. io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
  234. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  235. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  236. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  237. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  238. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  239. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  240. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  241. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  242. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  243. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  244. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  245. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  246. io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  247. io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText;
  248. io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText;
  249. #ifdef _WIN32
  250. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  251. #endif
  252. if (install_callbacks)
  253. {
  254. glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback);
  255. glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback);
  256. glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback);
  257. glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback);
  258. }
  259. return true;
  260. }
  261. void ImGui_ImplGlfwGL3_Shutdown()
  262. {
  263. if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
  264. if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
  265. if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
  266. g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
  267. glDetachShader(g_ShaderHandle, g_VertHandle);
  268. glDeleteShader(g_VertHandle);
  269. g_VertHandle = 0;
  270. glDetachShader(g_ShaderHandle, g_FragHandle);
  271. glDeleteShader(g_FragHandle);
  272. g_FragHandle = 0;
  273. glDeleteProgram(g_ShaderHandle);
  274. g_ShaderHandle = 0;
  275. if (g_FontTexture)
  276. {
  277. glDeleteTextures(1, &g_FontTexture);
  278. ImGui::GetIO().Fonts->TexID = 0;
  279. g_FontTexture = 0;
  280. }
  281. ImGui::Shutdown();
  282. }
  283. void ImGui_ImplGlfwGL3_NewFrame()
  284. {
  285. if (!g_FontTexture)
  286. ImGui_ImplGlfwGL3_CreateDeviceObjects();
  287. ImGuiIO& io = ImGui::GetIO();
  288. // Setup display size (every frame to accommodate for window resizing)
  289. int w, h;
  290. int display_w, display_h;
  291. glfwGetWindowSize(g_Window, &w, &h);
  292. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  293. io.DisplaySize = ImVec2((float)w, (float)h);
  294. io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
  295. // Setup time step
  296. double current_time = glfwGetTime();
  297. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  298. g_Time = current_time;
  299. // Setup inputs
  300. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  301. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  302. {
  303. double mouse_x, mouse_y;
  304. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  305. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
  306. }
  307. else
  308. {
  309. io.MousePos = ImVec2(-1,-1);
  310. }
  311. for (int i = 0; i < 3; i++)
  312. {
  313. io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
  314. g_MousePressed[i] = false;
  315. }
  316. io.MouseWheel = g_MouseWheel;
  317. g_MouseWheel = 0.0f;
  318. // Hide OS mouse cursor if ImGui is drawing it
  319. glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
  320. // Start the frame
  321. ImGui::NewFrame();
  322. }