Debian Codegraph @

extern/imgui_patched/backends/imgui_impl_opengl3.cpp

raw
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 as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
8 // [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
9 // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
10 // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
11
12 // About WebGL/ES:
13 // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
14 // - This is done automatically on iOS, Android and Emscripten targets.
15 // - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
16
17 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19 // Learn about Dear ImGui:
20 // - FAQ https://dearimgui.com/faq
21 // - Getting Started https://dearimgui.com/getting-started
22 // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23 // - Introduction, links and more at the top of imgui.cpp
24
25 // CHANGELOG
26 // (minor and older changes stripped away, please see git history for details)
27 // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
28 // 2025-07-22: OpenGL: Add and call embedded loader shutdown during ImGui_ImplOpenGL3_Shutdown() to facilitate multiple init/shutdown cycles in same process. (#8792)
29 // 2025-07-15: OpenGL: Set GL_UNPACK_ALIGNMENT to 1 before updating textures (#8802) + restore non-WebGL/ES update path that doesn't require a CPU-side copy.
30 // 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture().
31 // 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664)
32 // 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406)
33 // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap.
34 // 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748)
35 // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562)
36 // 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447)
37 // 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink.
38 // 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983)
39 // 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445)
40 // 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333)
41 // 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375)
42 // 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333)
43 // 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224)
44 // 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530)
45 // 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224)
46 // 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes).
47 // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
48 // 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'.
49 // 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127).
50 // 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states.
51 // 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers.
52 // 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions.
53 // 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.
54 // 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).
55 // 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state.
56 // 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader.
57 // 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version.
58 // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
59 // 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater.
60 // 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer.
61 // 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state.
62 // 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state.
63 // 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)
64 // 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.
65 // 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
66 // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
67 // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
68 // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
69 // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
70 // 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
71 // 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.
72 // 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
73 // 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
74 // 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
75 // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
76 // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
77 // 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
78 // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
79 // 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.
80 // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
81 // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
82 // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
83 // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
84 // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
85 // 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
86 // 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
87 // 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
88 // 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
89 // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
90 // 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
91 // 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer.
92 // 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".
93 // 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
94 // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
95 // 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
96 // 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
97 // 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
98 // 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
99 // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
100 // 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
101
102 //----------------------------------------
103 // OpenGL GLSL GLSL
104 // version version string
105 //----------------------------------------
106 // 2.0 110 "#version 110"
107 // 2.1 120 "#version 120"
108 // 3.0 130 "#version 130"
109 // 3.1 140 "#version 140"
110 // 3.2 150 "#version 150"
111 // 3.3 330 "#version 330 core"
112 // 4.0 400 "#version 400 core"
113 // 4.1 410 "#version 410 core"
114 // 4.2 420 "#version 410 core"
115 // 4.3 430 "#version 430 core"
116 // ES 2.0 100 "#version 100" = WebGL 1.0
117 // ES 3.0 300 "#version 300 es" = WebGL 2.0
118 //----------------------------------------
119
120 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
121 #define _CRT_SECURE_NO_WARNINGS
122 #endif
123
124 #include "imgui.h"
125 #ifndef IMGUI_DISABLE
126 #include "imgui_impl_opengl3.h"
127 #include <stdio.h>
128 #include <stdint.h> // intptr_t
129 #if defined(__APPLE__)
130 #include <TargetConditionals.h>
131 #endif
132
133 // Clang/GCC warnings with -Weverything
134 #if defined(__clang__)
135 #pragma clang diagnostic push
136 #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: ignore unknown flags
137 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
138 #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
139 #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used
140 #pragma clang diagnostic ignored "-Wnonportable-system-include-path"
141 #pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
142 #endif
143 #if defined(__GNUC__)
144 #pragma GCC diagnostic push
145 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
146 #pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx'
147 #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
148 #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
149 #endif
150
151 // GL includes
152 #if defined(IMGUI_IMPL_OPENGL_ES2)
153 #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
154 #include <OpenGLES/ES2/gl.h> // Use GL ES 2
155 #else
156 #include <GLES2/gl2.h> // Use GL ES 2
157 #endif
158 #if defined(__EMSCRIPTEN__)
159 #ifndef GL_GLEXT_PROTOTYPES
160 #define GL_GLEXT_PROTOTYPES
161 #endif
162 #include <GLES2/gl2ext.h>
163 #endif
164 #elif defined(IMGUI_IMPL_OPENGL_ES3)
165 #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
166 #include <OpenGLES/ES3/gl.h> // Use GL ES 3
167 #else
168 #include <GLES3/gl3.h> // Use GL ES 3
169 #endif
170 #elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
171 // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
172 // Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w.
173 // In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.).
174 // If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp):
175 // - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped
176 // Typically you would run: python3 ./gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
177 // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases
178 // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version.
179 #define IMGL3W_IMPL
180 #define IMGUI_IMPL_OPENGL_LOADER_IMGL3W
181 #include "imgui_impl_opengl3_loader.h"
182 #endif
183
184 // Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension
185 #ifndef IMGUI_IMPL_OPENGL_ES2
186 #define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
187 #elif defined(__EMSCRIPTEN__)
188 #define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
189 #define glBindVertexArray glBindVertexArrayOES
190 #define glGenVertexArrays glGenVertexArraysOES
191 #define glDeleteVertexArrays glDeleteVertexArraysOES
192 #define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES
193 #endif
194
195 // Desktop GL 2.0+ has extension and glPolygonMode() which GL ES and WebGL don't have..
196 // A desktop ES context can technically compile fine with our loader, so we also perform a runtime checks
197 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
198 #define IMGUI_IMPL_OPENGL_HAS_EXTENSIONS // has glGetIntegerv(GL_NUM_EXTENSIONS)
199 #define IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE // may have glPolygonMode()
200 #endif
201
202 // Desktop GL 2.1+ and GL ES 3.0+ have glBindBuffer() with GL_PIXEL_UNPACK_BUFFER target.
203 #if !defined(IMGUI_IMPL_OPENGL_ES2)
204 #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
205 #endif
206
207 // Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
208 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
209 #define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
210 #endif
211
212 // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
213 #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2)
214 #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
215 #endif
216
217 // Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler()
218 #if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3))
219 #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
220 #endif
221
222 #include "../../../src/ta-log.h"
223
224 // [Debugging]
225 //#define IMGUI_IMPL_OPENGL_DEBUG
226 #ifdef IMGUI_IMPL_OPENGL_DEBUG
227 #define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) logE("GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check
228 #else
229 #define GL_CALL(_CALL) _CALL // Call without error check
230 #endif
231
232 #define GL_CALL_FALSE(_CALL) _CALL; { GLenum gl_err = glGetError(); if (gl_err != 0) { logW("GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); return false; } }
233
234 // OpenGL Data
235 struct ImGui_ImplOpenGL3_Data
236 {
237 GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
238 char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings.
239 bool GlProfileIsES2;
240 bool GlProfileIsES3;
241 bool GlProfileIsCompat;
242 GLint GlProfileMask;
243 GLint MaxTextureSize;
244 GLuint ShaderHandle;
245 GLint AttribLocationTex; // Uniforms location
246 GLint AttribLocationProjMtx;
247 GLuint AttribLocationVtxPos; // Vertex attributes location
248 GLuint AttribLocationVtxUV;
249 GLuint AttribLocationVtxColor;
250 unsigned int VboHandle, ElementsHandle;
251 GLsizeiptr VertexBufferSize;
252 GLsizeiptr IndexBufferSize;
253 bool HasPolygonMode;
254 bool HasClipOrigin;
255 bool UseBufferSubData;
256 ImVector<char> TempBuffer;
257
258 ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); }
259 };
260
261 // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
262 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
263 static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData()
264 {
265 return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
266 }
267
268 // Forward Declarations
269 static void ImGui_ImplOpenGL3_InitMultiViewportSupport();
270 static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport();
271
272 // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only)
273 #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
274 struct ImGui_ImplOpenGL3_VtxAttribState
275 {
276 GLint Enabled, Size, Type, Normalized, Stride;
277 GLvoid* Ptr;
278
279 void GetState(GLint index)
280 {
281 glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled);
282 glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size);
283 glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type);
284 glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized);
285 glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride);
286 glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr);
287 }
288 void SetState(GLint index)
289 {
290 glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr);
291 if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index);
292 }
293 };
294 #endif
295
296 // Not static to allow third-party code to use that if they want to (but undocumented)
297 bool ImGui_ImplOpenGL3_InitLoader();
298 bool ImGui_ImplOpenGL3_InitLoader()
299 {
300 // Initialize our loader
301 #ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W
302 if (glGetIntegerv == nullptr && imgl3wInit() != 0)
303 {
304 fprintf(stderr, "Failed to initialize OpenGL loader!\n");
305 return false;
306 }
307 #endif
308 return true;
309 }
310
311 // Functions
312 bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
313 {
314 ImGuiIO& io = ImGui::GetIO();
315 IMGUI_CHECKVERSION();
316 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
317
318 // Initialize loader
319 if (!ImGui_ImplOpenGL3_InitLoader())
320 return false;
321
322 // Setup backend capabilities flags
323 ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)();
324 io.BackendRendererUserData = (void*)bd;
325 io.BackendRendererName = "imgui_impl_opengl3";
326
327 // Query for GL version (e.g. 320 for GL 3.2)
328 const char* gl_version_str = (const char*)glGetString(GL_VERSION);
329 #if defined(IMGUI_IMPL_OPENGL_ES2)
330 // tildearrow: unused variable fix
331 if (strcmp(gl_version_str,"")==0) {
332
333 }
334 // GLES 2
335 bd->GlVersion = 200;
336 bd->GlProfileIsES2 = true;
337 IM_UNUSED(gl_version_str);
338 #else
339 // Desktop or GLES 3
340 GLint major = 0;
341 GLint minor = 0;
342 glGetIntegerv(GL_MAJOR_VERSION, &major);
343 glGetIntegerv(GL_MINOR_VERSION, &minor);
344 if (major == 0 && minor == 0)
345 sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
346 bd->GlVersion = (GLuint)(major * 100 + minor * 10);
347 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &bd->MaxTextureSize);
348
349 #if defined(IMGUI_IMPL_OPENGL_ES3)
350 bd->GlProfileIsES3 = true;
351 #else
352 if (strncmp(gl_version_str, "OpenGL ES 3", 11) == 0)
353 bd->GlProfileIsES3 = true;
354 #endif
355
356 #if defined(GL_CONTEXT_PROFILE_MASK)
357 if (!bd->GlProfileIsES3 && bd->GlVersion >= 320)
358 glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask);
359 bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0;
360 #endif
361
362 bd->UseBufferSubData = false;
363 /*
364 // Query vendor to enable glBufferSubData kludge
365 #ifdef _WIN32
366 if (const char* vendor = (const char*)glGetString(GL_VENDOR))
367 if (strncmp(vendor, "Intel", 5) == 0)
368 bd->UseBufferSubData = true;
369 #endif
370 */
371 #endif
372
373 #ifdef IMGUI_IMPL_OPENGL_DEBUG
374 printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2/IsEs3 = %d/%d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
375 #endif
376
377 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
378 if (bd->GlVersion >= 320)
379 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
380 #endif
381 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
382 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
383
384 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
385 platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = (int)bd->MaxTextureSize;
386
387 // Store GLSL version string so we can refer to it later in case we recreate shaders.
388 // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure.
389 if (glsl_version == nullptr)
390 {
391 #if defined(IMGUI_IMPL_OPENGL_ES2)
392 glsl_version = "#version 100";
393 #elif defined(IMGUI_IMPL_OPENGL_ES3)
394 glsl_version = "#version 300 es";
395 #elif defined(__APPLE__)
396 glsl_version = "#version 150";
397 #else
398 glsl_version = "#version 130";
399 #endif
400 }
401 IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString));
402 strcpy(bd->GlslVersionString, glsl_version);
403 strcat(bd->GlslVersionString, "\n");
404
405 // Make an arbitrary GL call (we don't actually need the result)
406 // IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know!
407 GLint current_texture;
408 glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
409
410 // Detect extensions we support
411 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
412 bd->HasPolygonMode = (!bd->GlProfileIsES2 && !bd->GlProfileIsES3);
413 #endif
414 bd->HasClipOrigin = (bd->GlVersion >= 450);
415 #ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS
416 GLint num_extensions = 0;
417 glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
418 for (GLint i = 0; i < num_extensions; i++)
419 {
420 const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
421 if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0)
422 bd->HasClipOrigin = true;
423 }
424 #endif
425
426 ImGui_ImplOpenGL3_InitMultiViewportSupport();
427
428 return true;
429 }
430
431 void ImGui_ImplOpenGL3_Shutdown()
432 {
433 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
434 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
435 ImGuiIO& io = ImGui::GetIO();
436
437 ImGui_ImplOpenGL3_ShutdownMultiViewportSupport();
438 ImGui_ImplOpenGL3_DestroyDeviceObjects();
439 io.BackendRendererName = nullptr;
440 io.BackendRendererUserData = nullptr;
441 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
442 IM_DELETE(bd);
443
444 #ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W
445 imgl3wShutdown();
446 #endif
447 }
448
449 void ImGui_ImplOpenGL3_NewFrame()
450 {
451 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
452 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?");
453
454 ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries.
455
456 if (!bd->ShaderHandle)
457 if (!ImGui_ImplOpenGL3_CreateDeviceObjects())
458 IM_ASSERT(0 && "ImGui_ImplOpenGL3_CreateDeviceObjects() failed!");
459 }
460
461 static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
462 {
463 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
464
465 // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
466 glEnable(GL_BLEND);
467 glBlendEquation(GL_FUNC_ADD);
468 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
469 glDisable(GL_CULL_FACE);
470 glDisable(GL_DEPTH_TEST);
471 glDisable(GL_STENCIL_TEST);
472 glEnable(GL_SCISSOR_TEST);
473 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
474 if (!bd->GlProfileIsES3 && bd->GlVersion >= 310)
475 glDisable(GL_PRIMITIVE_RESTART);
476 #endif
477 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
478 if (bd->HasPolygonMode)
479 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
480 #endif
481
482 // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
483 #if defined(GL_CLIP_ORIGIN)
484 bool clip_origin_lower_left = true;
485 if (bd->HasClipOrigin)
486 {
487 GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
488 if (current_clip_origin == GL_UPPER_LEFT)
489 clip_origin_lower_left = false;
490 }
491 #endif
492
493 // Setup viewport, orthographic projection matrix
494 // 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.
495 GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height));
496 float L = draw_data->DisplayPos.x;
497 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
498 float T = draw_data->DisplayPos.y;
499 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
500 #if defined(GL_CLIP_ORIGIN)
501 if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
502 #endif
503 const float ortho_projection[4][4] =
504 {
505 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
506 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
507 { 0.0f, 0.0f, -1.0f, 0.0f },
508 { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
509 };
510 glUseProgram(bd->ShaderHandle);
511 glUniform1i(bd->AttribLocationTex, 0);
512 glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
513
514 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
515 if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
516 glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise.
517 #endif
518
519 (void)vertex_array_object;
520 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
521 glBindVertexArray(vertex_array_object);
522 #endif
523
524 // Bind vertex/index buffers and setup attributes for ImDrawVert
525 GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle));
526 GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle));
527 GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos));
528 GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV));
529 GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor));
530 GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos)));
531 GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv)));
532 GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col)));
533 }
534
535 // OpenGL3 Render function.
536 // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
537 // This is in order to be able to run within an OpenGL engine that doesn't do so.
538 void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
539 {
540 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
541 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
542 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
543 if (fb_width <= 0 || fb_height <= 0)
544 return;
545
546 ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries.
547
548 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
549
550 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
551 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
552 if (draw_data->Textures != nullptr)
553 for (ImTextureData* tex : *draw_data->Textures)
554 if (tex->Status != ImTextureStatus_OK)
555 ImGui_ImplOpenGL3_UpdateTexture(tex);
556
557 // Backup GL state
558 GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
559 glActiveTexture(GL_TEXTURE0);
560 GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
561 GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
562 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
563 GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; }
564 #endif
565 GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
566 #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
567 // This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+.
568 GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
569 ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos);
570 ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV);
571 ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor);
572 #endif
573 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
574 GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
575 #endif
576 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
577 GLint last_polygon_mode[2]; if (bd->HasPolygonMode) { glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); }
578 #endif
579 GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
580 GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
581 GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
582 GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
583 GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
584 GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
585 GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
586 GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
587 GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
588 GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
589 GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
590 GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
591 GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
592 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
593 GLboolean last_enable_primitive_restart = (!bd->GlProfileIsES3 && bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE;
594 #endif
595
596 // Setup desired GL state
597 // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
598 // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
599 GLuint vertex_array_object = 0;
600 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
601 GL_CALL(glGenVertexArrays(1, &vertex_array_object));
602 #endif
603 ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
604
605 // Will project scissor/clipping rectangles into framebuffer space
606 ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
607 ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
608
609 // Render command lists
610 for (const ImDrawList* draw_list : draw_data->CmdLists)
611 {
612 // Upload vertex/index buffers
613 // - OpenGL drivers are in a very sorry state nowadays....
614 // During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports
615 // of leaks on Intel GPU when using multi-viewports on Windows.
616 // - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel.
617 // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code.
618 // We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path.
619 // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues.
620 const GLsizeiptr vtx_buffer_size = (GLsizeiptr)draw_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
621 const GLsizeiptr idx_buffer_size = (GLsizeiptr)draw_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
622 if (bd->UseBufferSubData)
623 {
624 if (bd->VertexBufferSize < vtx_buffer_size)
625 {
626 bd->VertexBufferSize = vtx_buffer_size;
627 GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW));
628 }
629 if (bd->IndexBufferSize < idx_buffer_size)
630 {
631 bd->IndexBufferSize = idx_buffer_size;
632 GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW));
633 }
634 GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data));
635 GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data));
636 }
637 else
638 {
639 GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data, GL_STREAM_DRAW));
640 GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data, GL_STREAM_DRAW));
641 }
642
643 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
644 {
645 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
646 if (pcmd->UserCallback != nullptr)
647 {
648 // User callback, registered via ImDrawList::AddCallback()
649 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
650 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
651 ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
652 else
653 pcmd->UserCallback(draw_list, pcmd);
654 }
655 else
656 {
657 // Project scissor/clipping rectangles into framebuffer space
658 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
659 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
660 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
661 continue;
662
663 // Apply scissor/clipping rectangle (Y is inverted in OpenGL)
664 GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)));
665
666 // Bind texture, Draw
667 GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()));
668 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
669 if (bd->GlVersion >= 320)
670 GL_CALL(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));
671 else
672 #endif
673 GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))));
674 }
675 }
676 }
677
678 // Destroy the temporary VAO
679 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
680 GL_CALL(glDeleteVertexArrays(1, &vertex_array_object));
681 #endif
682
683 // Restore modified GL state
684 // This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220.
685 if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program);
686 glBindTexture(GL_TEXTURE_2D, last_texture);
687 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
688 if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
689 glBindSampler(0, last_sampler);
690 #endif
691 glActiveTexture(last_active_texture);
692 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
693 glBindVertexArray(last_vertex_array_object);
694 #endif
695 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
696 #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
697 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
698 last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos);
699 last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV);
700 last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor);
701 #endif
702 glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
703 glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
704 if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
705 if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
706 if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
707 if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
708 if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
709 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
710 if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
711 #endif
712
713 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
714 // Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons
715 if (bd->HasPolygonMode) { if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) { glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); } else { glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); } }
716 #endif // IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
717
718 glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
719 glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
720 (void)bd; // Not all compilation paths use this
721 }
722
723 static void ImGui_ImplOpenGL3_DestroyTexture(ImTextureData* tex)
724 {
725 GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID;
726 glDeleteTextures(1, &gl_tex_id);
727
728 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
729 tex->SetTexID(ImTextureID_Invalid);
730 tex->SetStatus(ImTextureStatus_Destroyed);
731 }
732
733 void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex)
734 {
735 // FIXME: Consider backing up and restoring
736 if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
737 {
738 #ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
739 GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
740 #endif
741 #ifdef GL_UNPACK_ALIGNMENT
742 GL_CALL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
743 #endif
744 }
745
746 if (tex->Status == ImTextureStatus_WantCreate)
747 {
748 // Create and upload new texture to graphics system
749 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
750 IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr);
751 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
752 const void* pixels = tex->GetPixels();
753 GLuint gl_texture_id = 0;
754
755 // Upload texture to graphics system
756 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
757 GLint last_texture;
758 GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
759 GL_CALL(glGenTextures(1, &gl_texture_id));
760 GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id));
761 GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
762 GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
763 GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
764 GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
765 GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
766
767 // Store identifiers
768 tex->SetTexID((ImTextureID)(intptr_t)gl_texture_id);
769 tex->SetStatus(ImTextureStatus_OK);
770
771 // Restore state
772 GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture));
773 }
774 else if (tex->Status == ImTextureStatus_WantUpdates)
775 {
776 // Update selected blocks. We only ever write to textures regions which have never been used before!
777 // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
778 GLint last_texture;
779 GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
780
781 GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID;
782 GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id));
783 #if GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
784 GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width));
785 for (ImTextureRect& r : tex->Updates)
786 GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y)));
787 GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
788 #else
789 // GL ES doesn't have GL_UNPACK_ROW_LENGTH, so we need to (A) copy to a contiguous buffer or (B) upload line by line.
790 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
791 for (ImTextureRect& r : tex->Updates)
792 {
793 const int src_pitch = r.w * tex->BytesPerPixel;
794 bd->TempBuffer.resize(r.h * src_pitch);
795 char* out_p = bd->TempBuffer.Data;
796 for (int y = 0; y < r.h; y++, out_p += src_pitch)
797 memcpy(out_p, tex->GetPixelsAt(r.x, r.y + y), src_pitch);
798 IM_ASSERT(out_p == bd->TempBuffer.end());
799 GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, bd->TempBuffer.Data));
800 }
801 #endif
802 tex->SetStatus(ImTextureStatus_OK);
803 GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); // Restore state
804 }
805 else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
806 ImGui_ImplOpenGL3_DestroyTexture(tex);
807 }
808
809 // 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.
810 static bool CheckShader(GLuint handle, const char* desc)
811 {
812 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
813 GLint status = 0, log_length = 0;
814 glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
815 glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
816 if ((GLboolean)status == GL_FALSE)
817 fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString);
818 if (log_length > 1)
819 {
820 ImVector<char> buf;
821 buf.resize((int)(log_length + 1));
822 glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
823 fprintf(stderr, "%s\n", buf.begin());
824 }
825 return (GLboolean)status == GL_TRUE;
826 }
827
828 // If you get an error please report on GitHub. You may try different GL context version or GLSL version.
829 static bool CheckProgram(GLuint handle, const char* desc)
830 {
831 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
832 GLint status = 0, log_length = 0;
833 glGetProgramiv(handle, GL_LINK_STATUS, &status);
834 glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
835 if ((GLboolean)status == GL_FALSE)
836 fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString);
837 if (log_length > 1)
838 {
839 ImVector<char> buf;
840 buf.resize((int)(log_length + 1));
841 glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
842 fprintf(stderr, "%s\n", buf.begin());
843 }
844 return (GLboolean)status == GL_TRUE;
845 }
846
847 bool ImGui_ImplOpenGL3_CreateDeviceObjects()
848 {
849 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
850
851 // Backup GL state
852 GLint last_texture, last_array_buffer;
853 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
854 glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
855 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
856 GLint last_pixel_unpack_buffer = 0;
857 if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); }
858 #endif
859 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
860 GLint last_vertex_array;
861 glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
862 #endif
863
864 // Parse GLSL version string
865 int glsl_version = 130;
866 sscanf(bd->GlslVersionString, "#version %d", &glsl_version);
867
868 const GLchar* vertex_shader_glsl_120 =
869 "uniform mat4 ProjMtx;\n"
870 "attribute vec2 Position;\n"
871 "attribute vec2 UV;\n"
872 "attribute vec4 Color;\n"
873 "varying vec2 Frag_UV;\n"
874 "varying vec4 Frag_Color;\n"
875 "void main()\n"
876 "{\n"
877 " Frag_UV = UV;\n"
878 " Frag_Color = Color;\n"
879 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
880 "}\n";
881
882 const GLchar* vertex_shader_glsl_130 =
883 "uniform mat4 ProjMtx;\n"
884 "in vec2 Position;\n"
885 "in vec2 UV;\n"
886 "in vec4 Color;\n"
887 "out vec2 Frag_UV;\n"
888 "out vec4 Frag_Color;\n"
889 "void main()\n"
890 "{\n"
891 " Frag_UV = UV;\n"
892 " Frag_Color = Color;\n"
893 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
894 "}\n";
895
896 const GLchar* vertex_shader_glsl_300_es =
897 "precision highp float;\n"
898 "layout (location = 0) in vec2 Position;\n"
899 "layout (location = 1) in vec2 UV;\n"
900 "layout (location = 2) in vec4 Color;\n"
901 "uniform mat4 ProjMtx;\n"
902 "out vec2 Frag_UV;\n"
903 "out vec4 Frag_Color;\n"
904 "void main()\n"
905 "{\n"
906 " Frag_UV = UV;\n"
907 " Frag_Color = Color;\n"
908 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
909 "}\n";
910
911 const GLchar* vertex_shader_glsl_410_core =
912 "layout (location = 0) in vec2 Position;\n"
913 "layout (location = 1) in vec2 UV;\n"
914 "layout (location = 2) in vec4 Color;\n"
915 "uniform mat4 ProjMtx;\n"
916 "out vec2 Frag_UV;\n"
917 "out vec4 Frag_Color;\n"
918 "void main()\n"
919 "{\n"
920 " Frag_UV = UV;\n"
921 " Frag_Color = Color;\n"
922 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
923 "}\n";
924
925 const GLchar* fragment_shader_glsl_120 =
926 "#ifdef GL_ES\n"
927 " precision mediump float;\n"
928 "#endif\n"
929 "uniform sampler2D Texture;\n"
930 "varying vec2 Frag_UV;\n"
931 "varying vec4 Frag_Color;\n"
932 "void main()\n"
933 "{\n"
934 " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
935 "}\n";
936
937 const GLchar* fragment_shader_glsl_130 =
938 "uniform sampler2D Texture;\n"
939 "in vec2 Frag_UV;\n"
940 "in vec4 Frag_Color;\n"
941 "out vec4 Out_Color;\n"
942 "void main()\n"
943 "{\n"
944 " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
945 "}\n";
946
947 const GLchar* fragment_shader_glsl_300_es =
948 "precision mediump float;\n"
949 "uniform sampler2D Texture;\n"
950 "in vec2 Frag_UV;\n"
951 "in vec4 Frag_Color;\n"
952 "layout (location = 0) out vec4 Out_Color;\n"
953 "void main()\n"
954 "{\n"
955 " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
956 "}\n";
957
958 const GLchar* fragment_shader_glsl_410_core =
959 "in vec2 Frag_UV;\n"
960 "in vec4 Frag_Color;\n"
961 "uniform sampler2D Texture;\n"
962 "layout (location = 0) out vec4 Out_Color;\n"
963 "void main()\n"
964 "{\n"
965 " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
966 "}\n";
967
968 // Select shaders matching our GLSL versions
969 const GLchar* vertex_shader = nullptr;
970 const GLchar* fragment_shader = nullptr;
971 if (glsl_version < 130)
972 {
973 vertex_shader = vertex_shader_glsl_120;
974 fragment_shader = fragment_shader_glsl_120;
975 }
976 else if (glsl_version >= 410)
977 {
978 vertex_shader = vertex_shader_glsl_410_core;
979 fragment_shader = fragment_shader_glsl_410_core;
980 }
981 else if (glsl_version == 300)
982 {
983 vertex_shader = vertex_shader_glsl_300_es;
984 fragment_shader = fragment_shader_glsl_300_es;
985 }
986 else
987 {
988 vertex_shader = vertex_shader_glsl_130;
989 fragment_shader = fragment_shader_glsl_130;
990 }
991
992 // Create shaders
993 const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader };
994 GLuint vert_handle;
995 GL_CALL(vert_handle = glCreateShader(GL_VERTEX_SHADER));
996 glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr);
997 glCompileShader(vert_handle);
998 if (!CheckShader(vert_handle, "vertex shader"))
999 return false;
1000
1001 const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader };
1002 GLuint frag_handle;
1003 GL_CALL(frag_handle = glCreateShader(GL_FRAGMENT_SHADER));
1004 glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr);
1005 glCompileShader(frag_handle);
1006 if (!CheckShader(frag_handle, "fragment shader"))
1007 return false;
1008
1009 // Link
1010 bd->ShaderHandle = glCreateProgram();
1011 glAttachShader(bd->ShaderHandle, vert_handle);
1012 glAttachShader(bd->ShaderHandle, frag_handle);
1013 glLinkProgram(bd->ShaderHandle);
1014 if (!CheckProgram(bd->ShaderHandle, "shader program"))
1015 return false;
1016
1017 glDetachShader(bd->ShaderHandle, vert_handle);
1018 glDetachShader(bd->ShaderHandle, frag_handle);
1019 glDeleteShader(vert_handle);
1020 glDeleteShader(frag_handle);
1021
1022 bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture");
1023 bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx");
1024 bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position");
1025 bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV");
1026 bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color");
1027
1028 // Create buffers
1029 glGenBuffers(1, &bd->VboHandle);
1030 glGenBuffers(1, &bd->ElementsHandle);
1031
1032 // Restore modified GL state
1033 glBindTexture(GL_TEXTURE_2D, last_texture);
1034 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
1035 #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
1036 if (bd->GlVersion >= 210) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, last_pixel_unpack_buffer); }
1037 #endif
1038 #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
1039 glBindVertexArray(last_vertex_array);
1040 #endif
1041
1042 return true;
1043 }
1044
1045 void ImGui_ImplOpenGL3_DestroyDeviceObjects()
1046 {
1047 ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
1048 if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; }
1049 if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; }
1050 if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; }
1051
1052 // Destroy all textures
1053 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
1054 if (tex->RefCount == 1)
1055 ImGui_ImplOpenGL3_DestroyTexture(tex);
1056 }
1057
1058 //--------------------------------------------------------------------------------------------------------
1059 // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
1060 // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
1061 // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
1062 //--------------------------------------------------------------------------------------------------------
1063
1064 static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*)
1065 {
1066 if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
1067 {
1068 ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
1069 glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
1070 glClear(GL_COLOR_BUFFER_BIT);
1071 }
1072 ImGui_ImplOpenGL3_RenderDrawData(viewport->DrawData);
1073 }
1074
1075 static void ImGui_ImplOpenGL3_InitMultiViewportSupport()
1076 {
1077 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1078 platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL3_RenderWindow;
1079 }
1080
1081 static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport()
1082 {
1083 ImGui::DestroyPlatformWindows();
1084 }
1085
1086 //-----------------------------------------------------------------------------
1087
1088 #if defined(__GNUC__)
1089 #pragma GCC diagnostic pop
1090 #endif
1091 #if defined(__clang__)
1092 #pragma clang diagnostic pop
1093 #endif
1094
1095 #endif // #ifndef IMGUI_DISABLE