imgui_impl_glfw_gl3.cc (17494B)
1 // ImGui GLFW binding with OpenGL3 + shaders 2 // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. 3 4 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. 5 // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). 6 // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. 7 // https://github.com/ocornut/imgui 8 9 #include "imgui.h" 10 #include "imgui_impl_glfw_gl3.h" 11 12 // GL3W/GLFW 13 #include "glad.h" 14 #include "libs/glfw/include/GLFW/glfw3.h" 15 #ifdef _WIN32 16 #undef APIENTRY 17 #define GLFW_EXPOSE_NATIVE_WIN32 18 #define GLFW_EXPOSE_NATIVE_WGL 19 #include "libs/glfw/include/GLFW/glfw3native.h" 20 #endif 21 22 // Data 23 static GLFWwindow* g_Window = NULL; 24 static double g_Time = 0.0f; 25 static bool g_MousePressed[3] = { false, false, false }; 26 static float g_MouseWheel = 0.0f; 27 static GLuint g_FontTexture = 0; 28 static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; 29 static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; 30 static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; 31 static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; 32 33 // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) 34 // If text or lines are blurry when integrating ImGui in your engine: 35 // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) 36 void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data) 37 { 38 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) 39 ImGuiIO& io = ImGui::GetIO(); 40 int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); 41 int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); 42 if (fb_width == 0 || fb_height == 0) 43 return; 44 draw_data->ScaleClipRects(io.DisplayFramebufferScale); 45 46 // Backup GL state 47 GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); 48 glActiveTexture(GL_TEXTURE0); 49 GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); 50 GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 51 GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); 52 GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); 53 GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); 54 GLint last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, &last_blend_src_rgb); 55 GLint last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, &last_blend_dst_rgb); 56 GLint last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha); 57 GLint last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, &last_blend_dst_alpha); 58 GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); 59 GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); 60 GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); 61 GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); 62 GLboolean last_enable_blend = glIsEnabled(GL_BLEND); 63 GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); 64 GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); 65 GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); 66 67 // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled 68 glEnable(GL_BLEND); 69 glBlendEquation(GL_FUNC_ADD); 70 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 71 glDisable(GL_CULL_FACE); 72 glDisable(GL_DEPTH_TEST); 73 glEnable(GL_SCISSOR_TEST); 74 75 // Setup viewport, orthographic projection matrix 76 glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); 77 const float ortho_projection[4][4] = 78 { 79 { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, 80 { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, 81 { 0.0f, 0.0f, -1.0f, 0.0f }, 82 {-1.0f, 1.0f, 0.0f, 1.0f }, 83 }; 84 glUseProgram(g_ShaderHandle); 85 glUniform1i(g_AttribLocationTex, 0); 86 glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); 87 glBindVertexArray(g_VaoHandle); 88 89 for (int n = 0; n < draw_data->CmdListsCount; n++) 90 { 91 const ImDrawList* cmd_list = draw_data->CmdLists[n]; 92 const ImDrawIdx* idx_buffer_offset = 0; 93 94 glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); 95 glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); 96 97 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); 98 glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); 99 100 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 101 { 102 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 103 if (pcmd->UserCallback) 104 { 105 pcmd->UserCallback(cmd_list, pcmd); 106 } 107 else 108 { 109 glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); 110 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)); 111 glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); 112 } 113 idx_buffer_offset += pcmd->ElemCount; 114 } 115 } 116 117 // Restore modified GL state 118 glUseProgram(last_program); 119 glBindTexture(GL_TEXTURE_2D, last_texture); 120 glActiveTexture(last_active_texture); 121 glBindVertexArray(last_vertex_array); 122 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); 123 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); 124 glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); 125 glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); 126 if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); 127 if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); 128 if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); 129 if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); 130 glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); 131 glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); 132 } 133 134 static const char* ImGui_ImplGlfwGL3_GetClipboardText(void* user_data) 135 { 136 return glfwGetClipboardString((GLFWwindow*)user_data); 137 } 138 139 static void ImGui_ImplGlfwGL3_SetClipboardText(void* user_data, const char* text) 140 { 141 glfwSetClipboardString((GLFWwindow*)user_data, text); 142 } 143 144 void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/) 145 { 146 if (action == GLFW_PRESS && button >= 0 && button < 3) 147 g_MousePressed[button] = true; 148 } 149 150 void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset) 151 { 152 g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines. 153 } 154 155 void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods) 156 { 157 ImGuiIO& io = ImGui::GetIO(); 158 if (action == GLFW_PRESS) 159 io.KeysDown[key] = true; 160 if (action == GLFW_RELEASE) 161 io.KeysDown[key] = false; 162 163 (void)mods; // Modifiers are not reliable across systems 164 io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; 165 io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; 166 io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; 167 io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; 168 } 169 170 void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c) 171 { 172 ImGuiIO& io = ImGui::GetIO(); 173 if (c > 0 && c < 0x10000) 174 io.AddInputCharacter((unsigned short)c); 175 } 176 177 bool ImGui_ImplGlfwGL3_CreateFontsTexture() 178 { 179 // Build texture atlas 180 ImGuiIO& io = ImGui::GetIO(); 181 unsigned char* pixels; 182 int width, height; 183 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. 184 185 // Upload texture to graphics system 186 GLint last_texture; 187 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 188 glGenTextures(1, &g_FontTexture); 189 glBindTexture(GL_TEXTURE_2D, g_FontTexture); 190 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 191 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 192 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); 193 194 // Store our identifier 195 io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; 196 197 // Restore state 198 glBindTexture(GL_TEXTURE_2D, last_texture); 199 200 return true; 201 } 202 203 bool ImGui_ImplGlfwGL3_CreateDeviceObjects() 204 { 205 // Backup GL state 206 GLint last_texture, last_array_buffer, last_vertex_array; 207 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 208 glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); 209 glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); 210 211 const GLchar *vertex_shader = 212 "#version 330\n" 213 "uniform mat4 ProjMtx;\n" 214 "in vec2 Position;\n" 215 "in vec2 UV;\n" 216 "in vec4 Color;\n" 217 "out vec2 Frag_UV;\n" 218 "out vec4 Frag_Color;\n" 219 "void main()\n" 220 "{\n" 221 " Frag_UV = UV;\n" 222 " Frag_Color = Color;\n" 223 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" 224 "}\n"; 225 226 const GLchar* fragment_shader = 227 "#version 330\n" 228 "uniform sampler2D Texture;\n" 229 "in vec2 Frag_UV;\n" 230 "in vec4 Frag_Color;\n" 231 "out vec4 Out_Color;\n" 232 "void main()\n" 233 "{\n" 234 " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" 235 "}\n"; 236 237 g_ShaderHandle = glCreateProgram(); 238 g_VertHandle = glCreateShader(GL_VERTEX_SHADER); 239 g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); 240 glShaderSource(g_VertHandle, 1, &vertex_shader, 0); 241 glShaderSource(g_FragHandle, 1, &fragment_shader, 0); 242 glCompileShader(g_VertHandle); 243 glCompileShader(g_FragHandle); 244 glAttachShader(g_ShaderHandle, g_VertHandle); 245 glAttachShader(g_ShaderHandle, g_FragHandle); 246 glLinkProgram(g_ShaderHandle); 247 248 g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); 249 g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); 250 g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); 251 g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); 252 g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); 253 254 glGenBuffers(1, &g_VboHandle); 255 glGenBuffers(1, &g_ElementsHandle); 256 257 glGenVertexArrays(1, &g_VaoHandle); 258 glBindVertexArray(g_VaoHandle); 259 glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); 260 glEnableVertexAttribArray(g_AttribLocationPosition); 261 glEnableVertexAttribArray(g_AttribLocationUV); 262 glEnableVertexAttribArray(g_AttribLocationColor); 263 264 #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) 265 glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); 266 glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); 267 glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); 268 #undef OFFSETOF 269 270 ImGui_ImplGlfwGL3_CreateFontsTexture(); 271 272 // Restore modified GL state 273 glBindTexture(GL_TEXTURE_2D, last_texture); 274 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); 275 glBindVertexArray(last_vertex_array); 276 277 return true; 278 } 279 280 void ImGui_ImplGlfwGL3_InvalidateDeviceObjects() 281 { 282 if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); 283 if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); 284 if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); 285 g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; 286 287 if (g_ShaderHandle && g_VertHandle) glDetachShader(g_ShaderHandle, g_VertHandle); 288 if (g_VertHandle) glDeleteShader(g_VertHandle); 289 g_VertHandle = 0; 290 291 if (g_ShaderHandle && g_FragHandle) glDetachShader(g_ShaderHandle, g_FragHandle); 292 if (g_FragHandle) glDeleteShader(g_FragHandle); 293 g_FragHandle = 0; 294 295 if (g_ShaderHandle) glDeleteProgram(g_ShaderHandle); 296 g_ShaderHandle = 0; 297 298 if (g_FontTexture) 299 { 300 glDeleteTextures(1, &g_FontTexture); 301 ImGui::GetIO().Fonts->TexID = 0; 302 g_FontTexture = 0; 303 } 304 } 305 306 bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks) 307 { 308 g_Window = window; 309 310 ImGuiIO& io = ImGui::GetIO(); 311 io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. 312 io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; 313 io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; 314 io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; 315 io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; 316 io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; 317 io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; 318 io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; 319 io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; 320 io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; 321 io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; 322 io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; 323 io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; 324 io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; 325 io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; 326 io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; 327 io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; 328 io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; 329 io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; 330 331 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. 332 io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText; 333 io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText; 334 io.ClipboardUserData = g_Window; 335 #ifdef _WIN32 336 io.ImeWindowHandle = glfwGetWin32Window(g_Window); 337 #endif 338 339 if (install_callbacks) 340 { 341 glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback); 342 glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback); 343 glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback); 344 glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback); 345 } 346 347 return true; 348 } 349 350 void ImGui_ImplGlfwGL3_Shutdown() 351 { 352 ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); 353 ImGui::Shutdown(); 354 } 355 356 void ImGui_ImplGlfwGL3_NewFrame() 357 { 358 if (!g_FontTexture) 359 ImGui_ImplGlfwGL3_CreateDeviceObjects(); 360 361 ImGuiIO& io = ImGui::GetIO(); 362 363 // Setup display size (every frame to accommodate for window resizing) 364 int w, h; 365 int display_w, display_h; 366 glfwGetWindowSize(g_Window, &w, &h); 367 glfwGetFramebufferSize(g_Window, &display_w, &display_h); 368 io.DisplaySize = ImVec2((float)w, (float)h); 369 io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); 370 371 // Setup time step 372 double current_time = glfwGetTime(); 373 io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); 374 g_Time = current_time; 375 376 // Setup inputs 377 // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) 378 if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED)) 379 { 380 double mouse_x, mouse_y; 381 glfwGetCursorPos(g_Window, &mouse_x, &mouse_y); 382 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.) 383 } 384 else 385 { 386 io.MousePos = ImVec2(-1,-1); 387 } 388 389 for (int i = 0; i < 3; i++) 390 { 391 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. 392 g_MousePressed[i] = false; 393 } 394 395 io.MouseWheel = g_MouseWheel; 396 g_MouseWheel = 0.0f; 397 398 // Hide OS mouse cursor if ImGui is drawing it 399 glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL); 400 401 // Start the frame 402 ImGui::NewFrame(); 403 }