imgui

FORK: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
git clone https://git.neptards.moe/neptards/imgui.git
Log | Files | Refs

imgui_impl_opengl2.cpp (13115B)


      1 // dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline)
      2 // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
      3 
      4 // Implemented features:
      5 //  [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
      6 
      7 // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
      8 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
      9 // Read online: https://github.com/ocornut/imgui/tree/master/docs
     10 
     11 // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
     12 // **Prefer using the code in imgui_impl_opengl3.cpp**
     13 // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
     14 // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
     15 // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
     16 // confuse your GPU driver.
     17 // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
     18 
     19 // CHANGELOG
     20 // (minor and older changes stripped away, please see git history for details)
     21 //  2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
     22 //  2021-01-03: OpenGL: Backup, setup and restore GL_SHADE_MODEL state, disable GL_STENCIL_TEST and disable GL_NORMAL_ARRAY client state to increase compatibility with legacy OpenGL applications.
     23 //  2020-01-23: OpenGL: Backup, setup and restore GL_TEXTURE_ENV to increase compatibility with legacy OpenGL applications.
     24 //  2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
     25 //  2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
     26 //  2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
     27 //  2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications.
     28 //  2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples.
     29 //  2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
     30 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplOpenGL2_RenderDrawData() in the .h file so you can call it yourself.
     31 //  2017-09-01: OpenGL: Save and restore current polygon mode.
     32 //  2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal).
     33 //  2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
     34 
     35 #include "imgui.h"
     36 #include "imgui_impl_opengl2.h"
     37 #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
     38 #include <stddef.h>     // intptr_t
     39 #else
     40 #include <stdint.h>     // intptr_t
     41 #endif
     42 
     43 // Include OpenGL header (without an OpenGL loader) requires a bit of fiddling
     44 #if defined(_WIN32) && !defined(APIENTRY)
     45 #define APIENTRY __stdcall                  // It is customary to use APIENTRY for OpenGL function pointer declarations on all platforms.  Additionally, the Windows OpenGL header needs APIENTRY.
     46 #endif
     47 #if defined(_WIN32) && !defined(WINGDIAPI)
     48 #define WINGDIAPI __declspec(dllimport)     // Some Windows OpenGL headers need this
     49 #endif
     50 #if defined(__APPLE__)
     51 #define GL_SILENCE_DEPRECATION
     52 #include <OpenGL/gl.h>
     53 #else
     54 #include <GL/gl.h>
     55 #endif
     56 
     57 // OpenGL Data
     58 static GLuint       g_FontTexture = 0;
     59 
     60 // Functions
     61 bool    ImGui_ImplOpenGL2_Init()
     62 {
     63     // Setup backend capabilities flags
     64     ImGuiIO& io = ImGui::GetIO();
     65     io.BackendRendererName = "imgui_impl_opengl2";
     66     return true;
     67 }
     68 
     69 void    ImGui_ImplOpenGL2_Shutdown()
     70 {
     71     ImGui_ImplOpenGL2_DestroyDeviceObjects();
     72 }
     73 
     74 void    ImGui_ImplOpenGL2_NewFrame()
     75 {
     76     if (!g_FontTexture)
     77         ImGui_ImplOpenGL2_CreateDeviceObjects();
     78 }
     79 
     80 static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height)
     81 {
     82     // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
     83     glEnable(GL_BLEND);
     84     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
     85     //glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // In order to composite our output buffer we need to preserve alpha
     86     glDisable(GL_CULL_FACE);
     87     glDisable(GL_DEPTH_TEST);
     88     glDisable(GL_STENCIL_TEST);
     89     glDisable(GL_LIGHTING);
     90     glDisable(GL_COLOR_MATERIAL);
     91     glEnable(GL_SCISSOR_TEST);
     92     glEnableClientState(GL_VERTEX_ARRAY);
     93     glEnableClientState(GL_TEXTURE_COORD_ARRAY);
     94     glEnableClientState(GL_COLOR_ARRAY);
     95     glDisableClientState(GL_NORMAL_ARRAY);
     96     glEnable(GL_TEXTURE_2D);
     97     glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
     98     glShadeModel(GL_SMOOTH);
     99     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    100 
    101     // If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!),
    102     // you may need to backup/reset/restore other state, e.g. for current shader using the commented lines below.
    103     // (DO NOT MODIFY THIS FILE! Add the code in your calling function)
    104     //   GLint last_program;
    105     //   glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
    106     //   glUseProgram(0);
    107     //   ImGui_ImplOpenGL2_RenderDrawData(...);
    108     //   glUseProgram(last_program)
    109     // There are potentially many more states you could need to clear/setup that we can't access from default headers.
    110     // e.g. glBindBuffer(GL_ARRAY_BUFFER, 0), glDisable(GL_TEXTURE_CUBE_MAP).
    111 
    112     // Setup viewport, orthographic projection matrix
    113     // 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.
    114     glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    115     glMatrixMode(GL_PROJECTION);
    116     glPushMatrix();
    117     glLoadIdentity();
    118     glOrtho(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x, draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f, +1.0f);
    119     glMatrixMode(GL_MODELVIEW);
    120     glPushMatrix();
    121     glLoadIdentity();
    122 }
    123 
    124 // OpenGL2 Render function.
    125 // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
    126 // This is in order to be able to run within an OpenGL engine that doesn't do so.
    127 void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data)
    128 {
    129     // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
    130     int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
    131     int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
    132     if (fb_width == 0 || fb_height == 0)
    133         return;
    134 
    135     // Backup GL state
    136     GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    137     GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
    138     GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    139     GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
    140     GLint last_shade_model; glGetIntegerv(GL_SHADE_MODEL, &last_shade_model);
    141     GLint last_tex_env_mode; glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode);
    142     glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    143 
    144     // Setup desired GL state
    145     ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
    146 
    147     // Will project scissor/clipping rectangles into framebuffer space
    148     ImVec2 clip_off = draw_data->DisplayPos;         // (0,0) unless using multi-viewports
    149     ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
    150 
    151     // Render command lists
    152     for (int n = 0; n < draw_data->CmdListsCount; n++)
    153     {
    154         const ImDrawList* cmd_list = draw_data->CmdLists[n];
    155         const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
    156         const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
    157         glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
    158         glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
    159         glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
    160 
    161         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
    162         {
    163             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
    164             if (pcmd->UserCallback)
    165             {
    166                 // User callback, registered via ImDrawList::AddCallback()
    167                 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
    168                 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
    169                     ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
    170                 else
    171                     pcmd->UserCallback(cmd_list, pcmd);
    172             }
    173             else
    174             {
    175                 // Project scissor/clipping rectangles into framebuffer space
    176                 ImVec4 clip_rect;
    177                 clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
    178                 clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
    179                 clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
    180                 clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
    181 
    182                 if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
    183                 {
    184                     // Apply scissor/clipping rectangle
    185                     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));
    186 
    187                     // Bind texture, Draw
    188                     glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID());
    189                     glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
    190                 }
    191             }
    192             idx_buffer += pcmd->ElemCount;
    193         }
    194     }
    195 
    196     // Restore modified GL state
    197     glDisableClientState(GL_COLOR_ARRAY);
    198     glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    199     glDisableClientState(GL_VERTEX_ARRAY);
    200     glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
    201     glMatrixMode(GL_MODELVIEW);
    202     glPopMatrix();
    203     glMatrixMode(GL_PROJECTION);
    204     glPopMatrix();
    205     glPopAttrib();
    206     glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
    207     glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
    208     glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
    209     glShadeModel(last_shade_model);
    210     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode);
    211 }
    212 
    213 bool ImGui_ImplOpenGL2_CreateFontsTexture()
    214 {
    215     // Build texture atlas
    216     ImGuiIO& io = ImGui::GetIO();
    217     unsigned char* pixels;
    218     int width, height;
    219     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.
    220 
    221     // Upload texture to graphics system
    222     GLint last_texture;
    223     glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    224     glGenTextures(1, &g_FontTexture);
    225     glBindTexture(GL_TEXTURE_2D, g_FontTexture);
    226     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    227     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    228     glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    229     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    230 
    231     // Store our identifier
    232     io.Fonts->SetTexID((ImTextureID)(intptr_t)g_FontTexture);
    233 
    234     // Restore state
    235     glBindTexture(GL_TEXTURE_2D, last_texture);
    236 
    237     return true;
    238 }
    239 
    240 void ImGui_ImplOpenGL2_DestroyFontsTexture()
    241 {
    242     if (g_FontTexture)
    243     {
    244         ImGuiIO& io = ImGui::GetIO();
    245         glDeleteTextures(1, &g_FontTexture);
    246         io.Fonts->SetTexID(0);
    247         g_FontTexture = 0;
    248     }
    249 }
    250 
    251 bool    ImGui_ImplOpenGL2_CreateDeviceObjects()
    252 {
    253     return ImGui_ImplOpenGL2_CreateFontsTexture();
    254 }
    255 
    256 void    ImGui_ImplOpenGL2_DestroyDeviceObjects()
    257 {
    258     ImGui_ImplOpenGL2_DestroyFontsTexture();
    259 }