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