imgui_impl_sdl.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. // ImGui SDL2 binding with OpenGL
  2. // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // If your context or own usage of OpenGL involve anything GL3/GL4, prefer using the code in sdl_opengl3_example.
  4. // If you are not sure what that means, prefer using the code in sdl_opengl3_example.
  5. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  6. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  7. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  8. // https://github.com/ocornut/imgui
  9. #include <SDL.h>
  10. #include <SDL_syswm.h>
  11. #include <SDL_opengl.h>
  12. #include <imgui.h>
  13. #include "imgui_impl_sdl.h"
  14. // Data
  15. static double g_Time = 0.0f;
  16. static bool g_MousePressed[3] = { false, false, false };
  17. static float g_MouseWheel = 0.0f;
  18. static GLuint g_FontTexture = 0;
  19. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  20. // 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.
  21. // If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  22. void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
  23. {
  24. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  25. ImGuiIO& io = ImGui::GetIO();
  26. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  27. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  28. if (fb_width == 0 || fb_height == 0)
  29. return;
  30. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  31. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  32. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
  33. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  34. GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
  35. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  36. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  37. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  38. glEnable(GL_BLEND);
  39. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  40. glDisable(GL_CULL_FACE);
  41. glDisable(GL_DEPTH_TEST);
  42. glEnable(GL_SCISSOR_TEST);
  43. glEnableClientState(GL_VERTEX_ARRAY);
  44. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  45. glEnableClientState(GL_COLOR_ARRAY);
  46. glEnable(GL_TEXTURE_2D);
  47. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  48. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
  49. // Setup viewport, orthographic projection matrix
  50. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  51. glMatrixMode(GL_PROJECTION);
  52. glPushMatrix();
  53. glLoadIdentity();
  54. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  55. glMatrixMode(GL_MODELVIEW);
  56. glPushMatrix();
  57. glLoadIdentity();
  58. // Render command lists
  59. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  60. for (int n = 0; n < draw_data->CmdListsCount; n++)
  61. {
  62. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  63. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  64. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  65. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, pos)));
  66. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, uv)));
  67. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, col)));
  68. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  69. {
  70. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  71. if (pcmd->UserCallback)
  72. {
  73. pcmd->UserCallback(cmd_list, pcmd);
  74. }
  75. else
  76. {
  77. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  78. glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  79. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
  80. }
  81. idx_buffer += pcmd->ElemCount;
  82. }
  83. }
  84. #undef OFFSETOF
  85. // Restore modified state
  86. glDisableClientState(GL_COLOR_ARRAY);
  87. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  88. glDisableClientState(GL_VERTEX_ARRAY);
  89. glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
  90. glMatrixMode(GL_MODELVIEW);
  91. glPopMatrix();
  92. glMatrixMode(GL_PROJECTION);
  93. glPopMatrix();
  94. glPopAttrib();
  95. glPolygonMode(GL_FRONT, last_polygon_mode[0]); glPolygonMode(GL_BACK, last_polygon_mode[1]);
  96. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  97. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  98. }
  99. static const char* ImGui_ImplSdl_GetClipboardText(void*)
  100. {
  101. return SDL_GetClipboardText();
  102. }
  103. static void ImGui_ImplSdl_SetClipboardText(void*, const char* text)
  104. {
  105. SDL_SetClipboardText(text);
  106. }
  107. bool ImGui_ImplSdlGL2_ProcessEvent(SDL_Event* event)
  108. {
  109. ImGuiIO& io = ImGui::GetIO();
  110. switch (event->type)
  111. {
  112. case SDL_MOUSEWHEEL:
  113. {
  114. if (event->wheel.y > 0)
  115. g_MouseWheel = 1;
  116. if (event->wheel.y < 0)
  117. g_MouseWheel = -1;
  118. return true;
  119. }
  120. case SDL_MOUSEBUTTONDOWN:
  121. {
  122. if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
  123. if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
  124. if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
  125. return true;
  126. }
  127. case SDL_TEXTINPUT:
  128. {
  129. io.AddInputCharactersUTF8(event->text.text);
  130. return true;
  131. }
  132. case SDL_KEYDOWN:
  133. case SDL_KEYUP:
  134. {
  135. int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK;
  136. io.KeysDown[key] = (event->type == SDL_KEYDOWN);
  137. io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
  138. io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
  139. io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
  140. io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
  141. return true;
  142. }
  143. }
  144. return false;
  145. }
  146. bool ImGui_ImplSdlGL2_CreateDeviceObjects()
  147. {
  148. // Build texture atlas
  149. ImGuiIO& io = ImGui::GetIO();
  150. unsigned char* pixels;
  151. int width, height;
  152. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
  153. // Upload texture to graphics system
  154. GLint last_texture;
  155. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  156. glGenTextures(1, &g_FontTexture);
  157. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  158. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  159. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  160. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  161. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
  162. // Store our identifier
  163. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  164. // Restore state
  165. glBindTexture(GL_TEXTURE_2D, last_texture);
  166. return true;
  167. }
  168. void ImGui_ImplSdlGL2_InvalidateDeviceObjects()
  169. {
  170. if (g_FontTexture)
  171. {
  172. glDeleteTextures(1, &g_FontTexture);
  173. ImGui::GetIO().Fonts->TexID = 0;
  174. g_FontTexture = 0;
  175. }
  176. }
  177. bool ImGui_ImplSdlGL2_Init(SDL_Window* window)
  178. {
  179. ImGuiIO& io = ImGui::GetIO();
  180. io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  181. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  182. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  183. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  184. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  185. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  186. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  187. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  188. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  189. io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
  190. io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
  191. io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
  192. io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
  193. io.KeyMap[ImGuiKey_A] = SDLK_a;
  194. io.KeyMap[ImGuiKey_C] = SDLK_c;
  195. io.KeyMap[ImGuiKey_V] = SDLK_v;
  196. io.KeyMap[ImGuiKey_X] = SDLK_x;
  197. io.KeyMap[ImGuiKey_Y] = SDLK_y;
  198. io.KeyMap[ImGuiKey_Z] = SDLK_z;
  199. io.RenderDrawListsFn = ImGui_ImplSdl_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  200. io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText;
  201. io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText;
  202. io.ClipboardUserData = NULL;
  203. #ifdef _WIN32
  204. SDL_SysWMinfo wmInfo;
  205. SDL_VERSION(&wmInfo.version);
  206. SDL_GetWindowWMInfo(window, &wmInfo);
  207. io.ImeWindowHandle = wmInfo.info.win.window;
  208. #else
  209. (void)window;
  210. #endif
  211. return true;
  212. }
  213. void ImGui_ImplSdlGL2_Shutdown()
  214. {
  215. ImGui_ImplSdlGL2_InvalidateDeviceObjects();
  216. ImGui::Shutdown();
  217. }
  218. void ImGui_ImplSdlGL2_NewFrame(SDL_Window *window)
  219. {
  220. if (!g_FontTexture)
  221. ImGui_ImplSdlGL2_CreateDeviceObjects();
  222. ImGuiIO& io = ImGui::GetIO();
  223. // Setup display size (every frame to accommodate for window resizing)
  224. int w, h;
  225. int display_w, display_h;
  226. SDL_GetWindowSize(window, &w, &h);
  227. SDL_GL_GetDrawableSize(window, &display_w, &display_h);
  228. io.DisplaySize = ImVec2((float)w, (float)h);
  229. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  230. // Setup time step
  231. Uint32 time = SDL_GetTicks();
  232. double current_time = time / 1000.0;
  233. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  234. g_Time = current_time;
  235. // Setup inputs
  236. // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent())
  237. int mx, my;
  238. Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
  239. if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
  240. io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  241. else
  242. io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
  243. io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
  244. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
  245. io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
  246. g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
  247. io.MouseWheel = g_MouseWheel;
  248. g_MouseWheel = 0.0f;
  249. // Hide OS mouse cursor if ImGui is drawing it
  250. SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
  251. // Start the frame
  252. ImGui::NewFrame();
  253. }