imgui_impl_opengl3.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline
  2. // - Desktop GL: 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 Binding (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 in imgui.cpp.
  7. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  8. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
  9. // https://github.com/ocornut/imgui
  10. // CHANGELOG
  11. // (minor and older changes stripped away, please see git history for details)
  12. // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
  13. // 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
  14. // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
  15. // 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.
  16. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
  17. // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
  18. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  19. // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
  20. // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
  21. // 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
  22. // 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
  23. // 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
  24. // 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
  25. // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  26. // 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
  27. // 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer.
  28. // 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".
  29. // 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
  30. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
  31. // 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
  32. // 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
  33. // 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
  34. // 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
  35. // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
  36. // 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
  37. //----------------------------------------
  38. // OpenGL GLSL GLSL
  39. // version version string
  40. //----------------------------------------
  41. // 2.0 110 "#version 110"
  42. // 2.1 120 "#version 120"
  43. // 3.0 130 "#version 130"
  44. // 3.1 140 "#version 140"
  45. // 3.2 150 "#version 150"
  46. // 3.3 330 "#version 330 core"
  47. // 4.0 400 "#version 400 core"
  48. // 4.1 410 "#version 410 core"
  49. // 4.2 420 "#version 410 core"
  50. // 4.3 430 "#version 430 core"
  51. // ES 2.0 100 "#version 100" = WebGL 1.0
  52. // ES 3.0 300 "#version 300 es" = WebGL 2.0
  53. //----------------------------------------
  54. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  55. #define _CRT_SECURE_NO_WARNINGS
  56. #endif
  57. #include "imgui.h"
  58. #include "imgui_impl_opengl3.h"
  59. #include <stdio.h>
  60. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  61. #include <stddef.h> // intptr_t
  62. #else
  63. #include <stdint.h> // intptr_t
  64. #endif
  65. #if defined(__APPLE__)
  66. #include "TargetConditionals.h"
  67. #endif
  68. // Auto-detect GL version
  69. #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
  70. #if (defined(__APPLE__) && TARGET_OS_IOS) || (defined(__ANDROID__))
  71. #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
  72. #elif defined(__EMSCRIPTEN__)
  73. #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
  74. #endif
  75. #endif
  76. #if defined(IMGUI_IMPL_OPENGL_ES2)
  77. #include <GLES2/gl2.h>
  78. #elif defined(IMGUI_IMPL_OPENGL_ES3)
  79. #include <GLES3/gl3.h> // Use GL ES 3
  80. #else
  81. // About Desktop OpenGL function loaders:
  82. // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
  83. // Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
  84. // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
  85. #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
  86. #include <GL/gl3w.h> // Needs to be initialized with gl3wInit() in user's code
  87. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
  88. #include <GL/glew.h> // Needs to be initialized with glewInit() in user's code
  89. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
  90. #include <glad/glad.h> // Needs to be initialized with gladLoadGL() in user's code
  91. #else
  92. #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
  93. #endif
  94. #endif
  95. // OpenGL Data
  96. static char g_GlslVersionString[32] = "";
  97. static GLuint g_FontTexture = 0;
  98. static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
  99. static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location
  100. static int g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location
  101. static unsigned int g_VboHandle = 0, g_ElementsHandle = 0;
  102. // Functions
  103. bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
  104. {
  105. ImGuiIO& io = ImGui::GetIO();
  106. io.BackendRendererName = "imgui_impl_opengl3";
  107. // Store GLSL version string so we can refer to it later in case we recreate shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure.
  108. #if defined(IMGUI_IMPL_OPENGL_ES2)
  109. if (glsl_version == NULL)
  110. glsl_version = "#version 100";
  111. #elif defined(IMGUI_IMPL_OPENGL_ES3)
  112. if (glsl_version == NULL)
  113. glsl_version = "#version 300 es";
  114. #else
  115. if (glsl_version == NULL)
  116. glsl_version = "#version 130";
  117. #endif
  118. IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
  119. strcpy(g_GlslVersionString, glsl_version);
  120. strcat(g_GlslVersionString, "\n");
  121. // Make a dummy GL call (we don't actually need the result)
  122. // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code.
  123. // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above.
  124. GLint current_texture;
  125. glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
  126. return true;
  127. }
  128. void ImGui_ImplOpenGL3_Shutdown()
  129. {
  130. ImGui_ImplOpenGL3_DestroyDeviceObjects();
  131. }
  132. void ImGui_ImplOpenGL3_NewFrame()
  133. {
  134. if (!g_FontTexture)
  135. ImGui_ImplOpenGL3_CreateDeviceObjects();
  136. }
  137. static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
  138. {
  139. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
  140. glEnable(GL_BLEND);
  141. glBlendEquation(GL_FUNC_ADD);
  142. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  143. glDisable(GL_CULL_FACE);
  144. glDisable(GL_DEPTH_TEST);
  145. glEnable(GL_SCISSOR_TEST);
  146. #ifdef GL_POLYGON_MODE
  147. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  148. #endif
  149. // Setup viewport, orthographic projection matrix
  150. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
  151. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  152. float L = draw_data->DisplayPos.x;
  153. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  154. float T = draw_data->DisplayPos.y;
  155. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  156. const float ortho_projection[4][4] =
  157. {
  158. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  159. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  160. { 0.0f, 0.0f, -1.0f, 0.0f },
  161. { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
  162. };
  163. glUseProgram(g_ShaderHandle);
  164. glUniform1i(g_AttribLocationTex, 0);
  165. glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
  166. #ifdef GL_SAMPLER_BINDING
  167. glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
  168. #endif
  169. (void)vertex_array_object;
  170. #ifndef IMGUI_IMPL_OPENGL_ES2
  171. glBindVertexArray(vertex_array_object);
  172. #endif
  173. // Bind vertex/index buffers and setup attributes for ImDrawVert
  174. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  175. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
  176. glEnableVertexAttribArray(g_AttribLocationVtxPos);
  177. glEnableVertexAttribArray(g_AttribLocationVtxUV);
  178. glEnableVertexAttribArray(g_AttribLocationVtxColor);
  179. glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
  180. glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
  181. glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
  182. }
  183. // OpenGL3 Render function.
  184. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  185. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
  186. void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
  187. {
  188. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  189. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  190. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  191. if (fb_width <= 0 || fb_height <= 0)
  192. return;
  193. // Backup GL state
  194. GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
  195. glActiveTexture(GL_TEXTURE0);
  196. GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
  197. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  198. #ifdef GL_SAMPLER_BINDING
  199. GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler);
  200. #endif
  201. GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
  202. #ifndef IMGUI_IMPL_OPENGL_ES2
  203. GLint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object);
  204. #endif
  205. #ifdef GL_POLYGON_MODE
  206. GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
  207. #endif
  208. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  209. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  210. GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
  211. GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
  212. GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
  213. GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
  214. GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
  215. GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
  216. GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
  217. GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
  218. GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
  219. GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
  220. bool clip_origin_lower_left = true;
  221. #if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__)
  222. GLenum last_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&last_clip_origin); // Support for GL 4.5's glClipControl(GL_UPPER_LEFT)
  223. if (last_clip_origin == GL_UPPER_LEFT)
  224. clip_origin_lower_left = false;
  225. #endif
  226. // Setup desired GL state
  227. // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
  228. // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
  229. GLuint vertex_array_object = 0;
  230. #ifndef IMGUI_IMPL_OPENGL_ES2
  231. glGenVertexArrays(1, &vertex_array_object);
  232. #endif
  233. ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
  234. // Will project scissor/clipping rectangles into framebuffer space
  235. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  236. ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  237. // Render command lists
  238. for (int n = 0; n < draw_data->CmdListsCount; n++)
  239. {
  240. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  241. size_t idx_buffer_offset = 0;
  242. // Upload vertex/index buffers
  243. glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
  244. glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
  245. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  246. {
  247. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  248. if (pcmd->UserCallback != NULL)
  249. {
  250. // User callback, registered via ImDrawList::AddCallback()
  251. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  252. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  253. ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
  254. else
  255. pcmd->UserCallback(cmd_list, pcmd);
  256. }
  257. else
  258. {
  259. // Project scissor/clipping rectangles into framebuffer space
  260. ImVec4 clip_rect;
  261. clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
  262. clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
  263. clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
  264. clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
  265. if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
  266. {
  267. // Apply scissor/clipping rectangle
  268. if (clip_origin_lower_left)
  269. glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y));
  270. else
  271. glScissor((int)clip_rect.x, (int)clip_rect.y, (int)clip_rect.z, (int)clip_rect.w); // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
  272. // Bind texture, Draw
  273. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  274. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)idx_buffer_offset);
  275. }
  276. }
  277. idx_buffer_offset += pcmd->ElemCount * sizeof(ImDrawIdx);
  278. }
  279. }
  280. // Destroy the temporary VAO
  281. #ifndef IMGUI_IMPL_OPENGL_ES2
  282. glDeleteVertexArrays(1, &vertex_array_object);
  283. #endif
  284. // Restore modified GL state
  285. glUseProgram(last_program);
  286. glBindTexture(GL_TEXTURE_2D, last_texture);
  287. #ifdef GL_SAMPLER_BINDING
  288. glBindSampler(0, last_sampler);
  289. #endif
  290. glActiveTexture(last_active_texture);
  291. #ifndef IMGUI_IMPL_OPENGL_ES2
  292. glBindVertexArray(last_vertex_array_object);
  293. #endif
  294. glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
  295. glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
  296. glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
  297. if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
  298. if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
  299. if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
  300. if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
  301. #ifdef GL_POLYGON_MODE
  302. glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
  303. #endif
  304. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  305. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  306. }
  307. bool ImGui_ImplOpenGL3_CreateFontsTexture()
  308. {
  309. // Build texture atlas
  310. ImGuiIO& io = ImGui::GetIO();
  311. unsigned char* pixels;
  312. int width, height;
  313. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (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.
  314. // Upload texture to graphics system
  315. GLint last_texture;
  316. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  317. glGenTextures(1, &g_FontTexture);
  318. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  319. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  320. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  321. #ifdef GL_UNPACK_ROW_LENGTH
  322. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  323. #endif
  324. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  325. // Store our identifier
  326. io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontTexture;
  327. // Restore state
  328. glBindTexture(GL_TEXTURE_2D, last_texture);
  329. return true;
  330. }
  331. void ImGui_ImplOpenGL3_DestroyFontsTexture()
  332. {
  333. if (g_FontTexture)
  334. {
  335. ImGuiIO& io = ImGui::GetIO();
  336. glDeleteTextures(1, &g_FontTexture);
  337. io.Fonts->TexID = 0;
  338. g_FontTexture = 0;
  339. }
  340. }
  341. // 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.
  342. static bool CheckShader(GLuint handle, const char* desc)
  343. {
  344. GLint status = 0, log_length = 0;
  345. glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
  346. glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
  347. if ((GLboolean)status == GL_FALSE)
  348. fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc);
  349. if (log_length > 0)
  350. {
  351. ImVector<char> buf;
  352. buf.resize((int)(log_length + 1));
  353. glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
  354. fprintf(stderr, "%s\n", buf.begin());
  355. }
  356. return (GLboolean)status == GL_TRUE;
  357. }
  358. // If you get an error please report on GitHub. You may try different GL context version or GLSL version.
  359. static bool CheckProgram(GLuint handle, const char* desc)
  360. {
  361. GLint status = 0, log_length = 0;
  362. glGetProgramiv(handle, GL_LINK_STATUS, &status);
  363. glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
  364. if ((GLboolean)status == GL_FALSE)
  365. fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString);
  366. if (log_length > 0)
  367. {
  368. ImVector<char> buf;
  369. buf.resize((int)(log_length + 1));
  370. glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
  371. fprintf(stderr, "%s\n", buf.begin());
  372. }
  373. return (GLboolean)status == GL_TRUE;
  374. }
  375. bool ImGui_ImplOpenGL3_CreateDeviceObjects()
  376. {
  377. // Backup GL state
  378. GLint last_texture, last_array_buffer;
  379. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  380. glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
  381. #ifndef IMGUI_IMPL_OPENGL_ES2
  382. GLint last_vertex_array;
  383. glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
  384. #endif
  385. // Parse GLSL version string
  386. int glsl_version = 130;
  387. sscanf(g_GlslVersionString, "#version %d", &glsl_version);
  388. const GLchar* vertex_shader_glsl_120 =
  389. "uniform mat4 ProjMtx;\n"
  390. "attribute vec2 Position;\n"
  391. "attribute vec2 UV;\n"
  392. "attribute vec4 Color;\n"
  393. "varying vec2 Frag_UV;\n"
  394. "varying vec4 Frag_Color;\n"
  395. "void main()\n"
  396. "{\n"
  397. " Frag_UV = UV;\n"
  398. " Frag_Color = Color;\n"
  399. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  400. "}\n";
  401. const GLchar* vertex_shader_glsl_130 =
  402. "uniform mat4 ProjMtx;\n"
  403. "in vec2 Position;\n"
  404. "in vec2 UV;\n"
  405. "in vec4 Color;\n"
  406. "out vec2 Frag_UV;\n"
  407. "out vec4 Frag_Color;\n"
  408. "void main()\n"
  409. "{\n"
  410. " Frag_UV = UV;\n"
  411. " Frag_Color = Color;\n"
  412. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  413. "}\n";
  414. const GLchar* vertex_shader_glsl_300_es =
  415. "precision mediump float;\n"
  416. "layout (location = 0) in vec2 Position;\n"
  417. "layout (location = 1) in vec2 UV;\n"
  418. "layout (location = 2) in vec4 Color;\n"
  419. "uniform mat4 ProjMtx;\n"
  420. "out vec2 Frag_UV;\n"
  421. "out vec4 Frag_Color;\n"
  422. "void main()\n"
  423. "{\n"
  424. " Frag_UV = UV;\n"
  425. " Frag_Color = Color;\n"
  426. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  427. "}\n";
  428. const GLchar* vertex_shader_glsl_410_core =
  429. "layout (location = 0) in vec2 Position;\n"
  430. "layout (location = 1) in vec2 UV;\n"
  431. "layout (location = 2) in vec4 Color;\n"
  432. "uniform mat4 ProjMtx;\n"
  433. "out vec2 Frag_UV;\n"
  434. "out vec4 Frag_Color;\n"
  435. "void main()\n"
  436. "{\n"
  437. " Frag_UV = UV;\n"
  438. " Frag_Color = Color;\n"
  439. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  440. "}\n";
  441. const GLchar* fragment_shader_glsl_120 =
  442. "#ifdef GL_ES\n"
  443. " precision mediump float;\n"
  444. "#endif\n"
  445. "uniform sampler2D Texture;\n"
  446. "varying vec2 Frag_UV;\n"
  447. "varying vec4 Frag_Color;\n"
  448. "void main()\n"
  449. "{\n"
  450. " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
  451. "}\n";
  452. const GLchar* fragment_shader_glsl_130 =
  453. "uniform sampler2D Texture;\n"
  454. "in vec2 Frag_UV;\n"
  455. "in vec4 Frag_Color;\n"
  456. "out vec4 Out_Color;\n"
  457. "void main()\n"
  458. "{\n"
  459. " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
  460. "}\n";
  461. const GLchar* fragment_shader_glsl_300_es =
  462. "precision mediump float;\n"
  463. "uniform sampler2D Texture;\n"
  464. "in vec2 Frag_UV;\n"
  465. "in vec4 Frag_Color;\n"
  466. "layout (location = 0) out vec4 Out_Color;\n"
  467. "void main()\n"
  468. "{\n"
  469. " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
  470. "}\n";
  471. const GLchar* fragment_shader_glsl_410_core =
  472. "in vec2 Frag_UV;\n"
  473. "in vec4 Frag_Color;\n"
  474. "uniform sampler2D Texture;\n"
  475. "layout (location = 0) out vec4 Out_Color;\n"
  476. "void main()\n"
  477. "{\n"
  478. " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
  479. "}\n";
  480. // Select shaders matching our GLSL versions
  481. const GLchar* vertex_shader = NULL;
  482. const GLchar* fragment_shader = NULL;
  483. if (glsl_version < 130)
  484. {
  485. vertex_shader = vertex_shader_glsl_120;
  486. fragment_shader = fragment_shader_glsl_120;
  487. }
  488. else if (glsl_version >= 410)
  489. {
  490. vertex_shader = vertex_shader_glsl_410_core;
  491. fragment_shader = fragment_shader_glsl_410_core;
  492. }
  493. else if (glsl_version == 300)
  494. {
  495. vertex_shader = vertex_shader_glsl_300_es;
  496. fragment_shader = fragment_shader_glsl_300_es;
  497. }
  498. else
  499. {
  500. vertex_shader = vertex_shader_glsl_130;
  501. fragment_shader = fragment_shader_glsl_130;
  502. }
  503. // Create shaders
  504. const GLchar* vertex_shader_with_version[2] = { g_GlslVersionString, vertex_shader };
  505. g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
  506. glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL);
  507. glCompileShader(g_VertHandle);
  508. CheckShader(g_VertHandle, "vertex shader");
  509. const GLchar* fragment_shader_with_version[2] = { g_GlslVersionString, fragment_shader };
  510. g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
  511. glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL);
  512. glCompileShader(g_FragHandle);
  513. CheckShader(g_FragHandle, "fragment shader");
  514. g_ShaderHandle = glCreateProgram();
  515. glAttachShader(g_ShaderHandle, g_VertHandle);
  516. glAttachShader(g_ShaderHandle, g_FragHandle);
  517. glLinkProgram(g_ShaderHandle);
  518. CheckProgram(g_ShaderHandle, "shader program");
  519. g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
  520. g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
  521. g_AttribLocationVtxPos = glGetAttribLocation(g_ShaderHandle, "Position");
  522. g_AttribLocationVtxUV = glGetAttribLocation(g_ShaderHandle, "UV");
  523. g_AttribLocationVtxColor = glGetAttribLocation(g_ShaderHandle, "Color");
  524. // Create buffers
  525. glGenBuffers(1, &g_VboHandle);
  526. glGenBuffers(1, &g_ElementsHandle);
  527. ImGui_ImplOpenGL3_CreateFontsTexture();
  528. // Restore modified GL state
  529. glBindTexture(GL_TEXTURE_2D, last_texture);
  530. glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
  531. #ifndef IMGUI_IMPL_OPENGL_ES2
  532. glBindVertexArray(last_vertex_array);
  533. #endif
  534. return true;
  535. }
  536. void ImGui_ImplOpenGL3_DestroyDeviceObjects()
  537. {
  538. if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
  539. if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
  540. g_VboHandle = g_ElementsHandle = 0;
  541. if (g_ShaderHandle && g_VertHandle) glDetachShader(g_ShaderHandle, g_VertHandle);
  542. if (g_VertHandle) glDeleteShader(g_VertHandle);
  543. g_VertHandle = 0;
  544. if (g_ShaderHandle && g_FragHandle) glDetachShader(g_ShaderHandle, g_FragHandle);
  545. if (g_FragHandle) glDeleteShader(g_FragHandle);
  546. g_FragHandle = 0;
  547. if (g_ShaderHandle) glDeleteProgram(g_ShaderHandle);
  548. g_ShaderHandle = 0;
  549. ImGui_ImplOpenGL3_DestroyFontsTexture();
  550. }