1 
2 //          Copyright Marcelo S. N. Mancini(Hipreme) 2020.
3 // Distributed under the Boost Software License, Version 1.0.
4 //    (See accompanying file LICENSE_1_0.txt or copy at
5 //          http://www.boost.org/LICENSE_1_0.txt)
6 
7 module imgui_backend.impl_opengl3;
8 import bindbc.cimgui;
9 
10 import std.conv:to;
11 import core.stdc.stdio;
12 
13 import core.stdc.string;
14 import core.stdc.stdint : intptr_t;
15 
16 /// Whether to use the implementation defined in D or link to compiled ImGui backends instead
17 enum CIMGUI_USER_DEFINED_IMPLEMENTATION_GL = true;
18 
19 // dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline
20 // - Desktop GL: 2.x 3.x 4.x
21 // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
22 // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
23 
24 // Implemented features:
25 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
26 //  [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
27 
28 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
29 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
30 // https://github.com/ocornut/imgui
31 
32 // CHANGELOG
33 // (minor and older changes stripped away, please see git history for details)
34 //  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.
35 //  2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
36 //  2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
37 //  2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
38 //  2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
39 //  2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
40 //  2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
41 //  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.
42 //  2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
43 //  2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
44 //  2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
45 //  2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
46 //  2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
47 //  2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
48 //  2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
49 //  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.
50 //  2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data.FramebufferScale to allow multi-viewports for retina display.
51 //  2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
52 //  2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
53 //  2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
54 //  2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
55 //  2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
56 //  2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
57 //  2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
58 //  2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
59 //  2018-06-08: OpenGL: Use draw_data.DisplayPos and draw_data.DisplaySize to setup projection matrix and clipping rectangle.
60 //  2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
61 //  2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a null pointer.
62 //  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".
63 //  2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
64 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
65 //  2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
66 //  2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
67 //  2017-05-01: OpenGL: Fixed save and restore of current blend func state.
68 //  2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
69 //  2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
70 //  2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
71 
72 //----------------------------------------
73 // OpenGL    GLSL      GLSL
74 // version   version   string
75 //----------------------------------------
76 //  2.0       110       "#version 110"
77 //  2.1       120       "#version 120"
78 //  3.0       130       "#version 130"
79 //  3.1       140       "#version 140"
80 //  3.2       150       "#version 150"
81 //  3.3       330       "#version 330 core"
82 //  4.0       400       "#version 400 core"
83 //  4.1       410       "#version 410 core"
84 //  4.2       420       "#version 410 core"
85 //  4.3       430       "#version 430 core"
86 //  ES 2.0    100       "#version 100"      = WebGL 1.0
87 //  ES 3.0    300       "#version 300 es"   = WebGL 2.0
88 //----------------------------------------
89 
90 // OpenGL version specifiers
91 enum IMGUI_IMPL_OPENGL_ES2 = false;
92 enum GL_VERSION_3_2 = false;
93 enum GL_VERSION_3_3 = false;
94 enum IMGUI_IMPL_OPENGL_ES3 = false;
95 
96 enum IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER = false;
97 enum IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET = false;
98 
99 /// Unused
100 enum _MSC_VER = -1;
101 
102 static if(CIMGUI_USER_DEFINED_IMPLEMENTATION_GL)
103 {
104     // GL includes
105     static if(IMGUI_IMPL_OPENGL_ES2)
106     {
107         static assert(0, "This is not yet implemented");
108     }
109     static if(IMGUI_IMPL_OPENGL_ES3)
110     {
111         static assert(0, "This is not yet implemented");
112     }
113     else
114     {
115         import bindbc.opengl;
116         // About Desktop OpenGL function loaders:
117         //  Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
118         //  Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
119         //  You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
120         //  In this case you may also need to change some of this code
121 
122         // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
123         static if(GL_VERSION_3_2)
124         {
125             enum IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET = true;
126         }
127         // Desktop GL 3.3+ has glBindSampler()
128         static if(GL_VERSION_3_3)
129         {
130             enum IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER = true;
131         }
132     }
133 
134     // OpenGL Data
135     static GLuint       g_GlVersion = 0;                // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
136     static char[32]     g_GlslVersionString;   // Specified by user or detected based on compile time GL settings.
137     static GLuint       g_FontTexture = 0;
138     static GLuint       g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
139     static GLint        g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;                                // Uniforms location
140     static GLuint       g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location
141     static uint         g_VboHandle = 0, g_ElementsHandle = 0;
142 
143     // Functions
144     bool    ImGui_ImplOpenGL3_Init(const (char)* glsl_version)
145     {
146         // Query for GL version (e.g. 320 for GL 3.2)
147         static if(IMGUI_IMPL_OPENGL_ES2)
148         {
149             g_GlVersion = 200; // GLES 2
150         }
151         else
152         {
153             GLint major, minor;
154             glGetIntegerv(GL_MAJOR_VERSION, &major);
155             glGetIntegerv(GL_MINOR_VERSION, &minor);
156             g_GlVersion = cast(GLuint)(major * 100 + minor * 10);
157         }
158         
159 
160         // Setup back-end capabilities flags
161         ImGuiIO* io = igGetIO();
162         io.BackendRendererName = "imgui_impl_opengl3";
163         static if(IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET)
164         {
165             if (g_GlVersion >= 320)
166                 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;  // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
167         }
168         io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports;
169 
170         // Store GLSL version string so we can refer to it later in case we recreate shaders.
171         // Note: GLSL version is NOT the same as GL version. Leave this to null if unsure.
172         static if(IMGUI_IMPL_OPENGL_ES2)
173         {
174             if (glsl_version == "")
175                 glsl_version = "#version 100";
176         }
177         static if(IMGUI_IMPL_OPENGL_ES3)
178         {
179             if (glsl_version == "")
180                 glsl_version = "#version 300 es";
181         }
182         else
183         {
184             version(__APPLE__)
185             {
186                 if (glsl_version == "")
187                     glsl_version = "#version 150";
188             }
189             else
190             {
191                 if (glsl_version == "")
192                     glsl_version = "#version 130";
193             }
194         }
195         import std.conv : to;
196         IM_ASSERT(cast(int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
197         strcpy(g_GlslVersionString.ptr, glsl_version);
198         strcat(g_GlslVersionString.ptr, "\n");
199 
200         // Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected.
201         // The code actually never uses the 'gl_loader' variable! It is only here so you can read it!
202         // If auto-detection fails or doesn't select the same GL loader file as used by your application,
203         // you are likely to get a crash below.
204         // You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
205         const (char)* gl_loader = "bindbc-opengl";
206 
207         // Make an arbitrary GL call (we don't actually need the result)
208         // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code.
209         // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above.
210         // Why not just static assert that it is bound?
211         GLint current_texture;
212         glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
213 
214         if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
215             ImGui_ImplOpenGL3_InitPlatformInterface();
216 
217         return true;
218     }
219 
220     void    ImGui_ImplOpenGL3_Shutdown()
221     {
222         ImGui_ImplOpenGL3_ShutdownPlatformInterface();
223         ImGui_ImplOpenGL3_DestroyDeviceObjects();
224     }
225 
226     void    ImGui_ImplOpenGL3_NewFrame()
227     {
228         if (!g_ShaderHandle)
229             ImGui_ImplOpenGL3_CreateDeviceObjects();
230     }
231 
232     static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
233     {
234         // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
235         glEnable(GL_BLEND);
236         glBlendEquation(GL_FUNC_ADD);
237         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
238         glDisable(GL_CULL_FACE);
239         glDisable(GL_DEPTH_TEST);
240         glEnable(GL_SCISSOR_TEST);
241         static if(GL_POLYGON_MODE)
242         {
243             glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
244         }
245 
246         // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
247         bool clip_origin_lower_left = true;
248         static if (GL_CLIP_ORIGIN)
249         {
250             GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, cast(GLint*)&current_clip_origin);
251             if (current_clip_origin == GL_UPPER_LEFT)
252                 clip_origin_lower_left = false;
253         }
254 
255         // Setup viewport, orthographic projection matrix
256         // 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.
257         glViewport(0, 0, cast(GLsizei)fb_width, cast(GLsizei)fb_height);
258         float L = draw_data.DisplayPos.x;
259         float R = draw_data.DisplayPos.x + draw_data.DisplaySize.x;
260         float T = draw_data.DisplayPos.y;
261         float B = draw_data.DisplayPos.y + draw_data.DisplaySize.y;
262         if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
263         const float[4][4] ortho_projection =
264         [
265             [ 2.0f/(R-L),   0.0f,         0.0f,   0.0f ],
266             [ 0.0f,         2.0f/(T-B),   0.0f,   0.0f ],
267             [ 0.0f,         0.0f,        -1.0f,   0.0f ],
268             [ (R+L)/(L-R),  (T+B)/(B-T),  0.0f,   1.0f ],
269         ];
270         glUseProgram(g_ShaderHandle);
271         glUniform1i(g_AttribLocationTex, 0);
272         glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
273         
274         static if(IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER)
275         {
276             if (g_GlVersion >= 330)
277                 glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise.
278         }
279         cast(void)vertex_array_object;
280         static if(!IMGUI_IMPL_OPENGL_ES2)
281         {
282             glBindVertexArray(vertex_array_object);
283         }
284 
285         // Bind vertex/index buffers and setup attributes for ImDrawVert
286         glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
287         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
288         glEnableVertexAttribArray(g_AttribLocationVtxPos);
289         glEnableVertexAttribArray(g_AttribLocationVtxUV);
290         glEnableVertexAttribArray(g_AttribLocationVtxColor);
291         glVertexAttribPointer(g_AttribLocationVtxPos,   2, GL_FLOAT,         GL_FALSE, ImDrawVert.sizeof, cast(GLvoid*)IM_OFFSETOF!(ImDrawVert.pos));
292         glVertexAttribPointer(g_AttribLocationVtxUV,    2, GL_FLOAT,         GL_FALSE, ImDrawVert.sizeof, cast(GLvoid*)IM_OFFSETOF!(ImDrawVert.uv));
293         glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE,  ImDrawVert.sizeof, cast(GLvoid*)IM_OFFSETOF!(ImDrawVert.col));
294     }
295 
296     // OpenGL3 Render function.
297     // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
298     // 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.
299     void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
300     {
301         // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
302         int fb_width = cast(int)(draw_data.DisplaySize.x * draw_data.FramebufferScale.x);
303         int fb_height = cast(int)(draw_data.DisplaySize.y * draw_data.FramebufferScale.y);
304         if (fb_width <= 0 || fb_height <= 0)
305             return;
306 
307         // Backup GL state
308         GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, cast(GLint*)&last_active_texture);
309         glActiveTexture(GL_TEXTURE0);
310         GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, cast(GLint*)&last_program);
311         GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, cast(GLint*)&last_texture);
312         static if(IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER)
313         {
314             GLuint last_sampler; 
315             if (g_GlVersion >= 330) 
316                 glGetIntegerv(GL_SAMPLER_BINDING, cast(GLint*)&last_sampler); 
317             else 
318                 last_sampler = 0;
319         }
320         GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, cast(GLint*)&last_array_buffer);
321         static if(!IMGUI_IMPL_OPENGL_ES2)
322         {
323             GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, cast(GLint*)&last_vertex_array_object);
324         }
325         static if(GL_POLYGON_MODE)
326         {
327             GLint[2] last_polygon_mode;
328             glGetIntegerv(GL_POLYGON_MODE, &last_polygon_mode[0]);
329         }
330         GLint[4] last_viewport; glGetIntegerv(GL_VIEWPORT, &last_viewport[0]);
331         GLint[4] last_scissor_box; glGetIntegerv(GL_SCISSOR_BOX, &last_scissor_box[0]);
332         GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, cast(GLint*)&last_blend_src_rgb);
333         GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, cast(GLint*)&last_blend_dst_rgb);
334         GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, cast(GLint*)&last_blend_src_alpha);
335         GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, cast(GLint*)&last_blend_dst_alpha);
336         GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, cast(GLint*)&last_blend_equation_rgb);
337         GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, cast(GLint*)&last_blend_equation_alpha);
338         GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
339         GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
340         GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
341         GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
342 
343         // Setup desired GL state
344         // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
345         // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
346         GLuint vertex_array_object = 0;
347         static if(!IMGUI_IMPL_OPENGL_ES2)
348         {
349             glGenVertexArrays(1, &vertex_array_object);
350         }
351         ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
352 
353         // Will project scissor/clipping rectangles into framebuffer space
354         ImVec2 clip_off = draw_data.DisplayPos;         // (0,0) unless using multi-viewports
355         ImVec2 clip_scale = draw_data.FramebufferScale; // (1,1) unless using retina display which are often (2,2)
356 
357         // Render command lists
358         for (int n = 0; n < draw_data.CmdListsCount; n++)
359         {
360             ImDrawList* cmd_list = draw_data.CmdLists[n]; //Const was there
361 
362             // Upload vertex/index buffers
363             glBufferData(GL_ARRAY_BUFFER, cast(GLsizeiptr)cmd_list.VtxBuffer.Size * cast(int)ImDrawVert.sizeof, cast(const GLvoid*)cmd_list.VtxBuffer.Data, GL_STREAM_DRAW);
364             glBufferData(GL_ELEMENT_ARRAY_BUFFER, cast(GLsizeiptr)cmd_list.IdxBuffer.Size * cast(int)ImDrawIdx.sizeof, cast(const GLvoid*)cmd_list.IdxBuffer.Data, GL_STREAM_DRAW);
365 
366             for (int cmd_i = 0; cmd_i < cmd_list.CmdBuffer.Size; cmd_i++)
367             {
368                 const (ImDrawCmd)* pcmd = &(cmd_list.CmdBuffer.Data[cmd_i]);
369                 if (pcmd.UserCallback != null)
370                 {
371                     // User callback, registered via ImDrawList::AddCallback()
372                     // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
373                     if (pcmd.UserCallback == ImDrawCallback_ResetRenderState)
374                         ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
375                     else
376                         pcmd.UserCallback(cmd_list, pcmd);
377                 }
378                 else
379                 {
380                     // Project scissor/clipping rectangles into framebuffer space
381                     ImVec4 clip_rect;
382                     clip_rect.x = (pcmd.ClipRect.x - clip_off.x) * clip_scale.x;
383                     clip_rect.y = (pcmd.ClipRect.y - clip_off.y) * clip_scale.y;
384                     clip_rect.z = (pcmd.ClipRect.z - clip_off.x) * clip_scale.x;
385                     clip_rect.w = (pcmd.ClipRect.w - clip_off.y) * clip_scale.y;
386 
387                     if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
388                     {
389                         // Apply scissor/clipping rectangle
390                         glScissor(cast(int)clip_rect.x, cast(int)(fb_height - clip_rect.w), cast(int)(clip_rect.z - clip_rect.x), cast(int)(clip_rect.w - clip_rect.y));
391 
392                         // Bind texture, Draw
393                         glBindTexture(GL_TEXTURE_2D, cast(GLuint)cast(intptr_t)pcmd.TextureId);
394                         static if(IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET)
395                         {
396                             if (g_GlVersion >= 320)
397                                 glDrawElementsBaseVertex(GL_TRIANGLES, cast(GLsizei)pcmd.ElemCount, ImDrawIdx.sizeof == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, cast(void*)cast(intptr_t)(pcmd.IdxOffset * ImDrawIdx.sizeof), cast(GLint)pcmd.VtxOffset);
398                         }
399                         //If not drawelement base vertex
400                         glDrawElements(GL_TRIANGLES, cast(GLsizei)pcmd.ElemCount, ImDrawIdx.sizeof == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, cast(void*)cast(intptr_t)(pcmd.IdxOffset * ImDrawIdx.sizeof));
401                     }
402                 }
403             }
404         }
405 
406         // Destroy the temporary VAO
407         static if(!IMGUI_IMPL_OPENGL_ES2)
408         {
409             glDeleteVertexArrays(1, &vertex_array_object);
410         }
411 
412         // Restore modified GL state
413         glUseProgram(last_program);
414         glBindTexture(GL_TEXTURE_2D, last_texture);
415         static if(IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER)
416         {
417             if (g_GlVersion >= 330)
418                 glBindSampler(0, last_sampler);
419         }
420         glActiveTexture(last_active_texture);
421         static if(!IMGUI_IMPL_OPENGL_ES2)
422         {
423             glBindVertexArray(last_vertex_array_object);
424         }
425         glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
426         glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
427         glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
428         if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
429         if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
430         if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
431         if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
432         static if(GL_POLYGON_MODE)
433         {
434             glPolygonMode(GL_FRONT_AND_BACK, cast(GLenum)last_polygon_mode[0]);
435         }
436         glViewport(last_viewport[0], last_viewport[1], cast(GLsizei)last_viewport[2], cast(GLsizei)last_viewport[3]);
437         glScissor(last_scissor_box[0], last_scissor_box[1], cast(GLsizei)last_scissor_box[2], cast(GLsizei)last_scissor_box[3]);
438     }
439 
440     bool ImGui_ImplOpenGL3_CreateFontsTexture()
441     {
442         // Build texture atlas
443         ImGuiIO* io = igGetIO();
444         ubyte* pixels = null;
445         int width, height;
446         static int bytePerPixel = 4;
447 
448         ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, &pixels, &width, &height, &bytePerPixel);   // 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.
449 
450         import std.stdio;
451         // Upload texture to graphics system
452         GLint last_texture;
453         glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
454         glGenTextures(1, &g_FontTexture);
455         glBindTexture(GL_TEXTURE_2D, g_FontTexture);
456         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
457         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
458         static if(GL_UNPACK_ROW_LENGTH)
459         {
460             glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
461         }
462         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
463 
464         // Store our identifier
465         io.Fonts.TexID = cast(ImTextureID)cast(intptr_t)g_FontTexture;
466 
467         // Restore state
468         glBindTexture(GL_TEXTURE_2D, last_texture);
469         
470         return true;
471     }
472 
473     void ImGui_ImplOpenGL3_DestroyFontsTexture()
474     {
475         if (g_FontTexture)
476         {
477             ImGuiIO* io = igGetIO();
478             glDeleteTextures(1, &g_FontTexture);
479             io.Fonts.TexID = null; //Same as 0
480             g_FontTexture = 0;
481         }
482     }
483 
484     // 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.
485     static bool CheckShader(GLuint handle, const (char)* desc)
486     {
487         GLint status = 0, log_length = 0;
488         glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
489         glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
490 
491         if (cast(GLboolean)status == GL_FALSE)
492             fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc);
493         if (log_length > 1)
494         {
495             
496             // ImVector_char buf;
497             // buf.resize(cast(int)(log_length + 1));
498             // glGetShaderInfoLog(handle, log_length, null, cast(GLchar*)buf.begin());
499             // fprintf(stderr, "%s\n", buf.begin());
500         }
501         return cast(GLboolean)status == GL_TRUE;
502     }
503 
504     // If you get an error please report on GitHub. You may try different GL context version or GLSL version.
505     static bool CheckProgram(GLuint handle, const (char)* desc)
506     {
507         GLint status = 0, log_length = 0;
508         glGetProgramiv(handle, GL_LINK_STATUS, &status);
509         glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
510         if (cast(GLboolean)status == GL_FALSE)
511             fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, &g_GlslVersionString[0]);
512         if (log_length > 1)
513         {
514             // ImVector_char buf;
515             // buf.resize(cast(int)(log_length + 1));
516             // glGetProgramInfoLog(handle, log_length, null, cast(GLchar*)buf.begin());
517             // fprintf(stderr, "%s\n", buf.begin());
518         }
519         return cast(GLboolean)status == GL_TRUE;
520     }
521 
522     bool    ImGui_ImplOpenGL3_CreateDeviceObjects()
523     {
524         // Backup GL state
525         GLint last_texture, last_array_buffer;
526         glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
527         glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
528         static if(!IMGUI_IMPL_OPENGL_ES2)
529         {
530             GLint last_vertex_array;
531             glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
532         }
533 
534 
535 
536         // Parse GLSL version string
537         int glsl_version = 130;
538         sscanf(&g_GlslVersionString[0], "#version %d", &glsl_version);
539 
540         const (GLchar)* vertex_shader_glsl_120 =
541             "uniform mat4 ProjMtx;\n"~
542             "attribute vec2 Position;\n"~
543             "attribute vec2 UV;\n"~
544             "attribute vec4 Color;\n"~
545             "varying vec2 Frag_UV;\n"~
546             "varying vec4 Frag_Color;\n"~
547             "void main()\n"~
548             "{\n"~
549             "    Frag_UV = UV;\n"~
550             "    Frag_Color = Color;\n"~
551             "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"~
552             "}\n";
553 
554         const (GLchar)* vertex_shader_glsl_130 =
555             "uniform mat4 ProjMtx;\n"~
556             "in vec2 Position;\n"~
557             "in vec2 UV;\n"~
558             "in vec4 Color;\n"~
559             "out vec2 Frag_UV;\n"~
560             "out vec4 Frag_Color;\n"~
561             "void main()\n"~
562             "{\n"~
563             "    Frag_UV = UV;\n"~
564             "    Frag_Color = Color;\n"~
565             "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"~
566             "}\n";
567 
568         const (GLchar)* vertex_shader_glsl_300_es =
569             "precision mediump float;\n"~
570             "layout (location = 0) in vec2 Position;\n"~
571             "layout (location = 1) in vec2 UV;\n"~
572             "layout (location = 2) in vec4 Color;\n"~
573             "uniform mat4 ProjMtx;\n"~
574             "out vec2 Frag_UV;\n"~
575             "out vec4 Frag_Color;\n"~
576             "void main()\n"~
577             "{\n"~
578             "    Frag_UV = UV;\n"~
579             "    Frag_Color = Color;\n"~
580             "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"~
581             "}\n";
582 
583         const (GLchar)* vertex_shader_glsl_410_core =
584             "layout (location = 0) in vec2 Position;\n"~
585             "layout (location = 1) in vec2 UV;\n"~
586             "layout (location = 2) in vec4 Color;\n"~
587             "uniform mat4 ProjMtx;\n"~
588             "out vec2 Frag_UV;\n"~
589             "out vec4 Frag_Color;\n"~
590             "void main()\n"~
591             "{\n"~
592             "    Frag_UV = UV;\n"~
593             "    Frag_Color = Color;\n"~
594             "    gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"~
595             "}\n";
596 
597         const (GLchar)* fragment_shader_glsl_120 =
598             "#ifdef GL_ES\n"~
599             "    precision mediump float;\n"~
600             "#endif\n"~
601             "uniform sampler2D Texture;\n"~
602             "varying vec2 Frag_UV;\n"~
603             "varying vec4 Frag_Color;\n"~
604             "void main()\n"~
605             "{\n"~
606             "    gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"~
607             "}\n";
608 
609         const (GLchar)* fragment_shader_glsl_130 =
610             "uniform sampler2D Texture;\n"~
611             "in vec2 Frag_UV;\n"~
612             "in vec4 Frag_Color;\n"~
613             "out vec4 Out_Color;\n"~
614             "void main()\n"~
615             "{\n"~
616             "    Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"~
617             "}\n";
618 
619         const (GLchar)* fragment_shader_glsl_300_es =
620             "precision mediump float;\n"~
621             "uniform sampler2D Texture;\n"~
622             "in vec2 Frag_UV;\n"~
623             "in vec4 Frag_Color;\n"~
624             "layout (location = 0) out vec4 Out_Color;\n"~
625             "void main()\n"~
626             "{\n"~
627             "    Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"~
628             "}\n";
629 
630         const (GLchar)* fragment_shader_glsl_410_core =
631             "in vec2 Frag_UV;\n"~
632             "in vec4 Frag_Color;\n"~
633             "uniform sampler2D Texture;\n"~
634             "layout (location = 0) out vec4 Out_Color;\n"~
635             "void main()\n"~
636             "{\n"~
637             "    Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"~
638             "}\n";
639 
640         // Select shaders matching our GLSL versions
641         const (GLchar)* vertex_shader = null;
642         const (GLchar)* fragment_shader = null;
643         if (glsl_version < 130)
644         {
645             vertex_shader = vertex_shader_glsl_120;
646             fragment_shader = fragment_shader_glsl_120;
647         }
648         else if (glsl_version >= 410)
649         {
650             vertex_shader = vertex_shader_glsl_410_core;
651             fragment_shader = fragment_shader_glsl_410_core;
652         }
653         else if (glsl_version == 300)
654         {
655             vertex_shader = vertex_shader_glsl_300_es;
656             fragment_shader = fragment_shader_glsl_300_es;
657         }
658         else
659         {
660             vertex_shader = vertex_shader_glsl_130;
661             fragment_shader = fragment_shader_glsl_130;
662         }
663 
664         // Create shaders
665         const (GLchar)*[2] vertex_shader_with_version = [g_GlslVersionString.ptr, vertex_shader ];
666         g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
667         glShaderSource(g_VertHandle, 2, vertex_shader_with_version.ptr, null);
668         glCompileShader(g_VertHandle);
669         CheckShader(g_VertHandle, "vertex shader");
670 
671         const (GLchar)*[2] fragment_shader_with_version =  [g_GlslVersionString.ptr, fragment_shader];
672         g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
673         glShaderSource(g_FragHandle, 2, fragment_shader_with_version.ptr, null);
674         glCompileShader(g_FragHandle);
675         CheckShader(g_FragHandle, "fragment shader");
676 
677         g_ShaderHandle = glCreateProgram();
678         glAttachShader(g_ShaderHandle, g_VertHandle);
679         glAttachShader(g_ShaderHandle, g_FragHandle);
680         glLinkProgram(g_ShaderHandle);
681         CheckProgram(g_ShaderHandle, "shader program");
682 
683         g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
684         g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
685         g_AttribLocationVtxPos = cast(GLuint)glGetAttribLocation(g_ShaderHandle, "Position");
686         g_AttribLocationVtxUV = cast(GLuint)glGetAttribLocation(g_ShaderHandle, "UV");
687         g_AttribLocationVtxColor = cast(GLuint)glGetAttribLocation(g_ShaderHandle, "Color");
688 
689         // Create buffers
690         glGenBuffers(1, &g_VboHandle);
691         glGenBuffers(1, &g_ElementsHandle);
692 
693         ImGui_ImplOpenGL3_CreateFontsTexture();
694 
695         // Restore modified GL state
696         glBindTexture(GL_TEXTURE_2D, last_texture);
697         glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
698         static if(!IMGUI_IMPL_OPENGL_ES2)
699         {
700             glBindVertexArray(last_vertex_array);
701         }
702 
703         return true;
704     }
705 
706     void    ImGui_ImplOpenGL3_DestroyDeviceObjects()
707     {
708         if (g_VboHandle)        { glDeleteBuffers(1, &g_VboHandle); g_VboHandle = 0; }
709         if (g_ElementsHandle)   { glDeleteBuffers(1, &g_ElementsHandle); g_ElementsHandle = 0; }
710         if (g_ShaderHandle && g_VertHandle) { glDetachShader(g_ShaderHandle, g_VertHandle); }
711         if (g_ShaderHandle && g_FragHandle) { glDetachShader(g_ShaderHandle, g_FragHandle); }
712         if (g_VertHandle)       { glDeleteShader(g_VertHandle); g_VertHandle = 0; }
713         if (g_FragHandle)       { glDeleteShader(g_FragHandle); g_FragHandle = 0; }
714         if (g_ShaderHandle)     { glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; }
715 
716         ImGui_ImplOpenGL3_DestroyFontsTexture();
717     }
718 
719 
720     //--------------------------------------------------------------------------------------------------------
721     // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
722     // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
723     // 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..
724     //--------------------------------------------------------------------------------------------------------
725 
726     extern(C++) static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*)
727     {
728         //viewport = cast(ImGuiViewport*)param;
729         if (!(viewport.Flags & ImGuiViewportFlags_NoRendererClear))
730         {
731             ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
732             glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
733             glClear(GL_COLOR_BUFFER_BIT);
734         }
735         ImGui_ImplOpenGL3_RenderDrawData(viewport.DrawData);
736     }
737 
738     static void ImGui_ImplOpenGL3_InitPlatformInterface()
739     {
740         ImGuiPlatformIO* platform_io = igGetPlatformIO();
741         platform_io.Renderer_RenderWindow = &ImGui_ImplOpenGL3_RenderWindow;
742     }
743 
744     static void ImGui_ImplOpenGL3_ShutdownPlatformInterface()
745     {
746         igDestroyPlatformWindows();
747     }
748 
749 }
750 else
751 {
752     extern(C) @nogc nothrow
753     {
754         alias pImGui_ImplOpenGL3_Init = bool function(const (char)* glsl_version);
755         alias pImGui_ImplOpenGL3_Shutdown = void function();
756         alias pImGui_ImplOpenGL3_NewFrame = void function();
757         alias pImGui_ImplOpenGL3_RenderDrawData = void function(ImDrawData* draw_data);
758         alias pImGui_ImplOpenGL3_CreateFontsTexture = bool function();
759         alias pImGui_ImplOpenGL3_DestroyFontsTexture = void function();
760         alias pImGui_ImplOpenGL3_CreateDeviceObjects = bool function();
761         alias pImGui_ImplOpenGL3_DestroyDeviceObjects = void function();
762     }
763 
764     __gshared
765     {
766         pImGui_ImplOpenGL3_Init ImGui_ImplOpenGL3_Init;
767         pImGui_ImplOpenGL3_Shutdown ImGui_ImplOpenGL3_Shutdown;
768         pImGui_ImplOpenGL3_NewFrame ImGui_ImplOpenGL3_NewFrame;
769         pImGui_ImplOpenGL3_RenderDrawData ImGui_ImplOpenGL3_RenderDrawData;
770         pImGui_ImplOpenGL3_CreateFontsTexture ImGui_ImplOpenGL3_CreateFontsTexture;
771         pImGui_ImplOpenGL3_DestroyFontsTexture ImGui_ImplOpenGL3_DestroyFontsTexture;
772         pImGui_ImplOpenGL3_CreateDeviceObjects ImGui_ImplOpenGL3_CreateDeviceObjects;
773         pImGui_ImplOpenGL3_DestroyDeviceObjects ImGui_ImplOpenGL3_DestroyDeviceObjects;
774     }
775     import bindbc.loader:SharedLib, bindSymbol;
776     void bindGLImgui(SharedLib lib)
777     {
778         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_Init, "ImGui_ImplOpenGL3_Init");
779         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_Shutdown, "ImGui_ImplOpenGL3_Shutdown");
780         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_NewFrame, "ImGui_ImplOpenGL3_NewFrame");
781         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_RenderDrawData, "ImGui_ImplOpenGL3_RenderDrawData");
782         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_CreateFontsTexture, "ImGui_ImplOpenGL3_CreateFontsTexture");
783         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_DestroyFontsTexture, "ImGui_ImplOpenGL3_DestroyFontsTexture");
784         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_CreateDeviceObjects, "ImGui_ImplOpenGL3_CreateDeviceObjects");
785         lib.bindSymbol(cast(void**)&ImGui_ImplOpenGL3_DestroyDeviceObjects, "ImGui_ImplOpenGL3_DestroyDeviceObjects");
786     }
787 }