2
0

imgui_impl_opengl3.cpp 52 KB

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