imgui_impl_opengl3.cpp 51 KB

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