imgui_impl_opengl3.cpp (35308B)
1 // dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline 2 // - Desktop GL: 2.x 3.x 4.x 3 // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) 4 // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) 5 6 // Implemented features: 7 // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! 8 // [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices. 9 10 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 11 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 12 // Read online: https://github.com/ocornut/imgui/tree/master/docs 13 14 // CHANGELOG 15 // (minor and older changes stripped away, please see git history for details) 16 // 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version. 17 // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) 18 // 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater. 19 // 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer. 20 // 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state. 21 // 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state. 22 // 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x) 23 // 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader. 24 // 2020-07-10: OpenGL: Added support for glad2 OpenGL loader. 25 // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. 26 // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. 27 // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. 28 // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. 29 // 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader. 30 // 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders. 31 // 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility. 32 // 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call. 33 // 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. 34 // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. 35 // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. 36 // 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. 37 // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). 38 // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. 39 // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. 40 // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). 41 // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. 42 // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN. 43 // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used. 44 // 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES". 45 // 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation. 46 // 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link. 47 // 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples. 48 // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. 49 // 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state. 50 // 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer. 51 // 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150". 52 // 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context. 53 // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself. 54 // 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150. 55 // 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode. 56 // 2017-05-01: OpenGL: Fixed save and restore of current blend func state. 57 // 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE. 58 // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. 59 // 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752) 60 61 //---------------------------------------- 62 // OpenGL GLSL GLSL 63 // version version string 64 //---------------------------------------- 65 // 2.0 110 "#version 110" 66 // 2.1 120 "#version 120" 67 // 3.0 130 "#version 130" 68 // 3.1 140 "#version 140" 69 // 3.2 150 "#version 150" 70 // 3.3 330 "#version 330 core" 71 // 4.0 400 "#version 400 core" 72 // 4.1 410 "#version 410 core" 73 // 4.2 420 "#version 410 core" 74 // 4.3 430 "#version 430 core" 75 // ES 2.0 100 "#version 100" = WebGL 1.0 76 // ES 3.0 300 "#version 300 es" = WebGL 2.0 77 //---------------------------------------- 78 79 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) 80 #define _CRT_SECURE_NO_WARNINGS 81 #endif 82 83 #include "imgui.h" 84 #include "imgui_impl_opengl3.h" 85 #include <stdio.h> 86 #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier 87 #include <stddef.h> // intptr_t 88 #else 89 #include <stdint.h> // intptr_t 90 #endif 91 92 // GL includes 93 #if defined(IMGUI_IMPL_OPENGL_ES2) 94 #include <GLES2/gl2.h> 95 #elif defined(IMGUI_IMPL_OPENGL_ES3) 96 #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) 97 #include <OpenGLES/ES3/gl.h> // Use GL ES 3 98 #else 99 #include <GLES3/gl3.h> // Use GL ES 3 100 #endif 101 #else 102 // About Desktop OpenGL function loaders: 103 // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. 104 // Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). 105 // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. 106 #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 107 #include <GL/gl3w.h> // Needs to be initialized with gl3wInit() in user's code 108 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 109 #include <GL/glew.h> // Needs to be initialized with glewInit() in user's code. 110 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 111 #include <glad/glad.h> // Needs to be initialized with gladLoadGL() in user's code. 112 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) 113 #include <glad/gl.h> // Needs to be initialized with gladLoadGL(...) or gladLoaderLoadGL() in user's code. 114 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) 115 #ifndef GLFW_INCLUDE_NONE 116 #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. 117 #endif 118 #include <glbinding/Binding.h> // Needs to be initialized with glbinding::Binding::initialize() in user's code. 119 #include <glbinding/gl/gl.h> 120 using namespace gl; 121 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) 122 #ifndef GLFW_INCLUDE_NONE 123 #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. 124 #endif 125 #include <glbinding/glbinding.h>// Needs to be initialized with glbinding::initialize() in user's code. 126 #include <glbinding/gl/gl.h> 127 using namespace gl; 128 #else 129 #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM 130 #endif 131 #endif 132 133 // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. 134 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2) 135 #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 136 #endif 137 138 // Desktop GL 3.3+ has glBindSampler() 139 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_3) 140 #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER 141 #endif 142 143 // Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state 144 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1) 145 #define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART 146 #endif 147 148 // Desktop GL use extension detection 149 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) 150 #define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS 151 #endif 152 153 // OpenGL Data 154 static GLuint g_GlVersion = 0; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2) 155 static char g_GlslVersionString[32] = ""; // Specified by user or detected based on compile time GL settings. 156 static GLuint g_FontTexture = 0; 157 static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; 158 static GLint g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location 159 static GLuint g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location 160 static unsigned int g_VboHandle = 0, g_ElementsHandle = 0; 161 static bool g_HasClipOrigin = false; 162 163 // Functions 164 bool ImGui_ImplOpenGL3_Init(const char* glsl_version) 165 { 166 // Query for GL version (e.g. 320 for GL 3.2) 167 #if !defined(IMGUI_IMPL_OPENGL_ES2) 168 GLint major = 0; 169 GLint minor = 0; 170 glGetIntegerv(GL_MAJOR_VERSION, &major); 171 glGetIntegerv(GL_MINOR_VERSION, &minor); 172 if (major == 0 && minor == 0) 173 { 174 // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>" 175 const char* gl_version = (const char*)glGetString(GL_VERSION); 176 sscanf(gl_version, "%d.%d", &major, &minor); 177 } 178 g_GlVersion = (GLuint)(major * 100 + minor * 10); 179 #else 180 g_GlVersion = 200; // GLES 2 181 #endif 182 183 // Setup backend capabilities flags 184 ImGuiIO& io = ImGui::GetIO(); 185 io.BackendRendererName = "imgui_impl_opengl3"; 186 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 187 if (g_GlVersion >= 320) 188 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. 189 #endif 190 191 // Store GLSL version string so we can refer to it later in case we recreate shaders. 192 // Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. 193 #if defined(IMGUI_IMPL_OPENGL_ES2) 194 if (glsl_version == NULL) 195 glsl_version = "#version 100"; 196 #elif defined(IMGUI_IMPL_OPENGL_ES3) 197 if (glsl_version == NULL) 198 glsl_version = "#version 300 es"; 199 #elif defined(__APPLE__) 200 if (glsl_version == NULL) 201 glsl_version = "#version 150"; 202 #else 203 if (glsl_version == NULL) 204 glsl_version = "#version 130"; 205 #endif 206 IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString)); 207 strcpy(g_GlslVersionString, glsl_version); 208 strcat(g_GlslVersionString, "\n"); 209 210 // Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected. 211 // The code actually never uses the 'gl_loader' variable! It is only here so you can read it! 212 // If auto-detection fails or doesn't select the same GL loader file as used by your application, 213 // you are likely to get a crash below. 214 // You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. 215 const char* gl_loader = "Unknown"; 216 IM_UNUSED(gl_loader); 217 #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) 218 gl_loader = "GL3W"; 219 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) 220 gl_loader = "GLEW"; 221 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) 222 gl_loader = "GLAD"; 223 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) 224 gl_loader = "GLAD2"; 225 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) 226 gl_loader = "glbinding2"; 227 #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) 228 gl_loader = "glbinding3"; 229 #elif defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) 230 gl_loader = "custom"; 231 #else 232 gl_loader = "none"; 233 #endif 234 235 // Make an arbitrary GL call (we don't actually need the result) 236 // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code. 237 // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above. 238 GLint current_texture; 239 glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture); 240 241 // Detect extensions we support 242 g_HasClipOrigin = (g_GlVersion >= 450); 243 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS 244 GLint num_extensions = 0; 245 glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); 246 for (GLint i = 0; i < num_extensions; i++) 247 { 248 const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i); 249 if (strcmp(extension, "GL_ARB_clip_control") == 0) 250 g_HasClipOrigin = true; 251 } 252 #endif 253 254 return true; 255 } 256 257 void ImGui_ImplOpenGL3_Shutdown() 258 { 259 ImGui_ImplOpenGL3_DestroyDeviceObjects(); 260 } 261 262 void ImGui_ImplOpenGL3_NewFrame() 263 { 264 if (!g_ShaderHandle) 265 ImGui_ImplOpenGL3_CreateDeviceObjects(); 266 } 267 268 static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) 269 { 270 // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill 271 glEnable(GL_BLEND); 272 glBlendEquation(GL_FUNC_ADD); 273 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); 274 glDisable(GL_CULL_FACE); 275 glDisable(GL_DEPTH_TEST); 276 glDisable(GL_STENCIL_TEST); 277 glEnable(GL_SCISSOR_TEST); 278 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART 279 if (g_GlVersion >= 310) 280 glDisable(GL_PRIMITIVE_RESTART); 281 #endif 282 #ifdef GL_POLYGON_MODE 283 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); 284 #endif 285 286 // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) 287 #if defined(GL_CLIP_ORIGIN) 288 bool clip_origin_lower_left = true; 289 if (g_HasClipOrigin) 290 { 291 GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); 292 if (current_clip_origin == GL_UPPER_LEFT) 293 clip_origin_lower_left = false; 294 } 295 #endif 296 297 // Setup viewport, orthographic projection matrix 298 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. 299 glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); 300 float L = draw_data->DisplayPos.x; 301 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; 302 float T = draw_data->DisplayPos.y; 303 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; 304 #if defined(GL_CLIP_ORIGIN) 305 if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left 306 #endif 307 const float ortho_projection[4][4] = 308 { 309 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, 310 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, 311 { 0.0f, 0.0f, -1.0f, 0.0f }, 312 { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f }, 313 }; 314 glUseProgram(g_ShaderHandle); 315 glUniform1i(g_AttribLocationTex, 0); 316 glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); 317 318 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER 319 if (g_GlVersion >= 330) 320 glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. 321 #endif 322 323 (void)vertex_array_object; 324 #ifndef IMGUI_IMPL_OPENGL_ES2 325 glBindVertexArray(vertex_array_object); 326 #endif 327 328 // Bind vertex/index buffers and setup attributes for ImDrawVert 329 glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); 330 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); 331 glEnableVertexAttribArray(g_AttribLocationVtxPos); 332 glEnableVertexAttribArray(g_AttribLocationVtxUV); 333 glEnableVertexAttribArray(g_AttribLocationVtxColor); 334 glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); 335 glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); 336 glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); 337 } 338 339 // OpenGL3 Render function. 340 // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. 341 // This is in order to be able to run within an OpenGL engine that doesn't do so. 342 void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) 343 { 344 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) 345 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); 346 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); 347 if (fb_width <= 0 || fb_height <= 0) 348 return; 349 350 // Backup GL state 351 GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); 352 glActiveTexture(GL_TEXTURE0); 353 GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); 354 GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); 355 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER 356 GLuint last_sampler; if (g_GlVersion >= 330) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } 357 #endif 358 GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); 359 #ifndef IMGUI_IMPL_OPENGL_ES2 360 GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); 361 #endif 362 #ifdef GL_POLYGON_MODE 363 GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); 364 #endif 365 GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); 366 GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); 367 GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb); 368 GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb); 369 GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha); 370 GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha); 371 GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb); 372 GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha); 373 GLboolean last_enable_blend = glIsEnabled(GL_BLEND); 374 GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); 375 GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); 376 GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST); 377 GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); 378 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART 379 GLboolean last_enable_primitive_restart = (g_GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; 380 #endif 381 382 // Setup desired GL state 383 // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) 384 // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. 385 GLuint vertex_array_object = 0; 386 #ifndef IMGUI_IMPL_OPENGL_ES2 387 glGenVertexArrays(1, &vertex_array_object); 388 #endif 389 ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); 390 391 // Will project scissor/clipping rectangles into framebuffer space 392 ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports 393 ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) 394 395 // Render command lists 396 for (int n = 0; n < draw_data->CmdListsCount; n++) 397 { 398 const ImDrawList* cmd_list = draw_data->CmdLists[n]; 399 400 // Upload vertex/index buffers 401 glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); 402 glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); 403 404 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 405 { 406 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 407 if (pcmd->UserCallback != NULL) 408 { 409 // User callback, registered via ImDrawList::AddCallback() 410 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) 411 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) 412 ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); 413 else 414 pcmd->UserCallback(cmd_list, pcmd); 415 } 416 else 417 { 418 // Project scissor/clipping rectangles into framebuffer space 419 ImVec4 clip_rect; 420 clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x; 421 clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y; 422 clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x; 423 clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y; 424 425 if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) 426 { 427 // Apply scissor/clipping rectangle 428 glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y)); 429 430 // Bind texture, Draw 431 glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()); 432 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 433 if (g_GlVersion >= 320) 434 glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset); 435 else 436 #endif 437 glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))); 438 } 439 } 440 } 441 } 442 443 // Destroy the temporary VAO 444 #ifndef IMGUI_IMPL_OPENGL_ES2 445 glDeleteVertexArrays(1, &vertex_array_object); 446 #endif 447 448 // Restore modified GL state 449 glUseProgram(last_program); 450 glBindTexture(GL_TEXTURE_2D, last_texture); 451 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER 452 if (g_GlVersion >= 330) 453 glBindSampler(0, last_sampler); 454 #endif 455 glActiveTexture(last_active_texture); 456 #ifndef IMGUI_IMPL_OPENGL_ES2 457 glBindVertexArray(last_vertex_array_object); 458 #endif 459 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); 460 glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); 461 glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); 462 if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); 463 if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); 464 if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); 465 if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); 466 if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); 467 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART 468 if (g_GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } 469 #endif 470 471 #ifdef GL_POLYGON_MODE 472 glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); 473 #endif 474 glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); 475 glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); 476 } 477 478 bool ImGui_ImplOpenGL3_CreateFontsTexture() 479 { 480 // Build texture atlas 481 ImGuiIO& io = ImGui::GetIO(); 482 unsigned char* pixels; 483 int width, height; 484 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (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. 485 486 // Upload texture to graphics system 487 GLint last_texture; 488 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 489 glGenTextures(1, &g_FontTexture); 490 glBindTexture(GL_TEXTURE_2D, g_FontTexture); 491 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 492 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 493 #ifdef GL_UNPACK_ROW_LENGTH 494 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); 495 #endif 496 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); 497 498 // Store our identifier 499 io.Fonts->SetTexID((ImTextureID)(intptr_t)g_FontTexture); 500 501 // Restore state 502 glBindTexture(GL_TEXTURE_2D, last_texture); 503 504 return true; 505 } 506 507 void ImGui_ImplOpenGL3_DestroyFontsTexture() 508 { 509 if (g_FontTexture) 510 { 511 ImGuiIO& io = ImGui::GetIO(); 512 glDeleteTextures(1, &g_FontTexture); 513 io.Fonts->SetTexID(0); 514 g_FontTexture = 0; 515 } 516 } 517 518 // If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file. 519 static bool CheckShader(GLuint handle, const char* desc) 520 { 521 GLint status = 0, log_length = 0; 522 glGetShaderiv(handle, GL_COMPILE_STATUS, &status); 523 glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length); 524 if ((GLboolean)status == GL_FALSE) 525 fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc); 526 if (log_length > 1) 527 { 528 ImVector<char> buf; 529 buf.resize((int)(log_length + 1)); 530 glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin()); 531 fprintf(stderr, "%s\n", buf.begin()); 532 } 533 return (GLboolean)status == GL_TRUE; 534 } 535 536 // If you get an error please report on GitHub. You may try different GL context version or GLSL version. 537 static bool CheckProgram(GLuint handle, const char* desc) 538 { 539 GLint status = 0, log_length = 0; 540 glGetProgramiv(handle, GL_LINK_STATUS, &status); 541 glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length); 542 if ((GLboolean)status == GL_FALSE) 543 fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString); 544 if (log_length > 1) 545 { 546 ImVector<char> buf; 547 buf.resize((int)(log_length + 1)); 548 glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin()); 549 fprintf(stderr, "%s\n", buf.begin()); 550 } 551 return (GLboolean)status == GL_TRUE; 552 } 553 554 bool ImGui_ImplOpenGL3_CreateDeviceObjects() 555 { 556 // Backup GL state 557 GLint last_texture, last_array_buffer; 558 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 559 glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); 560 #ifndef IMGUI_IMPL_OPENGL_ES2 561 GLint last_vertex_array; 562 glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); 563 #endif 564 565 // Parse GLSL version string 566 int glsl_version = 130; 567 sscanf(g_GlslVersionString, "#version %d", &glsl_version); 568 569 const GLchar* vertex_shader_glsl_120 = 570 "uniform mat4 ProjMtx;\n" 571 "attribute vec2 Position;\n" 572 "attribute vec2 UV;\n" 573 "attribute vec4 Color;\n" 574 "varying vec2 Frag_UV;\n" 575 "varying vec4 Frag_Color;\n" 576 "void main()\n" 577 "{\n" 578 " Frag_UV = UV;\n" 579 " Frag_Color = Color;\n" 580 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" 581 "}\n"; 582 583 const GLchar* vertex_shader_glsl_130 = 584 "uniform mat4 ProjMtx;\n" 585 "in vec2 Position;\n" 586 "in vec2 UV;\n" 587 "in vec4 Color;\n" 588 "out vec2 Frag_UV;\n" 589 "out vec4 Frag_Color;\n" 590 "void main()\n" 591 "{\n" 592 " Frag_UV = UV;\n" 593 " Frag_Color = Color;\n" 594 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" 595 "}\n"; 596 597 const GLchar* vertex_shader_glsl_300_es = 598 "precision mediump float;\n" 599 "layout (location = 0) in vec2 Position;\n" 600 "layout (location = 1) in vec2 UV;\n" 601 "layout (location = 2) in vec4 Color;\n" 602 "uniform mat4 ProjMtx;\n" 603 "out vec2 Frag_UV;\n" 604 "out vec4 Frag_Color;\n" 605 "void main()\n" 606 "{\n" 607 " Frag_UV = UV;\n" 608 " Frag_Color = Color;\n" 609 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" 610 "}\n"; 611 612 const GLchar* vertex_shader_glsl_410_core = 613 "layout (location = 0) in vec2 Position;\n" 614 "layout (location = 1) in vec2 UV;\n" 615 "layout (location = 2) in vec4 Color;\n" 616 "uniform mat4 ProjMtx;\n" 617 "out vec2 Frag_UV;\n" 618 "out vec4 Frag_Color;\n" 619 "void main()\n" 620 "{\n" 621 " Frag_UV = UV;\n" 622 " Frag_Color = Color;\n" 623 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" 624 "}\n"; 625 626 const GLchar* fragment_shader_glsl_120 = 627 "#ifdef GL_ES\n" 628 " precision mediump float;\n" 629 "#endif\n" 630 "uniform sampler2D Texture;\n" 631 "varying vec2 Frag_UV;\n" 632 "varying vec4 Frag_Color;\n" 633 "void main()\n" 634 "{\n" 635 " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" 636 "}\n"; 637 638 const GLchar* fragment_shader_glsl_130 = 639 "uniform sampler2D Texture;\n" 640 "in vec2 Frag_UV;\n" 641 "in vec4 Frag_Color;\n" 642 "out vec4 Out_Color;\n" 643 "void main()\n" 644 "{\n" 645 " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" 646 "}\n"; 647 648 const GLchar* fragment_shader_glsl_300_es = 649 "precision mediump float;\n" 650 "uniform sampler2D Texture;\n" 651 "in vec2 Frag_UV;\n" 652 "in vec4 Frag_Color;\n" 653 "layout (location = 0) out vec4 Out_Color;\n" 654 "void main()\n" 655 "{\n" 656 " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" 657 "}\n"; 658 659 const GLchar* fragment_shader_glsl_410_core = 660 "in vec2 Frag_UV;\n" 661 "in vec4 Frag_Color;\n" 662 "uniform sampler2D Texture;\n" 663 "layout (location = 0) out vec4 Out_Color;\n" 664 "void main()\n" 665 "{\n" 666 " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" 667 "}\n"; 668 669 // Select shaders matching our GLSL versions 670 const GLchar* vertex_shader = NULL; 671 const GLchar* fragment_shader = NULL; 672 if (glsl_version < 130) 673 { 674 vertex_shader = vertex_shader_glsl_120; 675 fragment_shader = fragment_shader_glsl_120; 676 } 677 else if (glsl_version >= 410) 678 { 679 vertex_shader = vertex_shader_glsl_410_core; 680 fragment_shader = fragment_shader_glsl_410_core; 681 } 682 else if (glsl_version == 300) 683 { 684 vertex_shader = vertex_shader_glsl_300_es; 685 fragment_shader = fragment_shader_glsl_300_es; 686 } 687 else 688 { 689 vertex_shader = vertex_shader_glsl_130; 690 fragment_shader = fragment_shader_glsl_130; 691 } 692 693 // Create shaders 694 const GLchar* vertex_shader_with_version[2] = { g_GlslVersionString, vertex_shader }; 695 g_VertHandle = glCreateShader(GL_VERTEX_SHADER); 696 glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL); 697 glCompileShader(g_VertHandle); 698 CheckShader(g_VertHandle, "vertex shader"); 699 700 const GLchar* fragment_shader_with_version[2] = { g_GlslVersionString, fragment_shader }; 701 g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); 702 glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL); 703 glCompileShader(g_FragHandle); 704 CheckShader(g_FragHandle, "fragment shader"); 705 706 g_ShaderHandle = glCreateProgram(); 707 glAttachShader(g_ShaderHandle, g_VertHandle); 708 glAttachShader(g_ShaderHandle, g_FragHandle); 709 glLinkProgram(g_ShaderHandle); 710 CheckProgram(g_ShaderHandle, "shader program"); 711 712 g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); 713 g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); 714 g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position"); 715 g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV"); 716 g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color"); 717 718 // Create buffers 719 glGenBuffers(1, &g_VboHandle); 720 glGenBuffers(1, &g_ElementsHandle); 721 722 ImGui_ImplOpenGL3_CreateFontsTexture(); 723 724 // Restore modified GL state 725 glBindTexture(GL_TEXTURE_2D, last_texture); 726 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); 727 #ifndef IMGUI_IMPL_OPENGL_ES2 728 glBindVertexArray(last_vertex_array); 729 #endif 730 731 return true; 732 } 733 734 void ImGui_ImplOpenGL3_DestroyDeviceObjects() 735 { 736 if (g_VboHandle) { glDeleteBuffers(1, &g_VboHandle); g_VboHandle = 0; } 737 if (g_ElementsHandle) { glDeleteBuffers(1, &g_ElementsHandle); g_ElementsHandle = 0; } 738 if (g_ShaderHandle && g_VertHandle) { glDetachShader(g_ShaderHandle, g_VertHandle); } 739 if (g_ShaderHandle && g_FragHandle) { glDetachShader(g_ShaderHandle, g_FragHandle); } 740 if (g_VertHandle) { glDeleteShader(g_VertHandle); g_VertHandle = 0; } 741 if (g_FragHandle) { glDeleteShader(g_FragHandle); g_FragHandle = 0; } 742 if (g_ShaderHandle) { glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; } 743 744 ImGui_ImplOpenGL3_DestroyFontsTexture(); 745 }