imgui_impl_sdl_gl2.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // ImGui SDL2 binding with OpenGL (legacy, fixed pipeline)
  2. // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
  3. // Implemented features:
  4. // [X] User texture binding. Cast 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
  5. // Missing features:
  6. // [ ] SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME.
  7. // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
  8. // **Prefer using the code in the sdl_opengl3_example/ folder**
  9. // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
  10. // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
  11. // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
  12. // confuse your GPU driver.
  13. // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
  14. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  15. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  16. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  17. // https://github.com/ocornut/imgui
  18. // CHANGELOG
  19. // (minor and older changes stripped away, please see git history for details)
  20. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  21. // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
  22. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL2_RenderDrawData() in the .h file so you can call it yourself.
  23. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  24. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  25. // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
  26. // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
  27. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  28. // 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
  29. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
  30. // 2017-09-01: OpenGL: Save and restore current polygon mode.
  31. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
  32. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
  33. // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
  34. // 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
  35. #include <SDL.h>
  36. #include <SDL_syswm.h>
  37. #include <SDL_opengl.h>
  38. #include "imgui.h"
  39. #include "imgui_impl_sdl_gl2.h"
  40. // Data
  41. static Uint64 g_Time = 0;
  42. static bool g_MousePressed[3] = { false, false, false };
  43. static GLuint g_FontTexture = 0;
  44. static SDL_Cursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = { 0 };
  45. // OpenGL2 Render function.
  46. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  47. // 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.
  48. void ImGui_ImplSdlGL2_RenderDrawData(ImDrawData* draw_data)
  49. {
  50. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  51. ImGuiIO& io = ImGui::GetIO();
  52. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  53. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  54. if (fb_width == 0 || fb_height == 0)
  55. return;
  56. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  57. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  58. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
  59. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  60. GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
  61. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  62. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  63. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  64. glEnable(GL_BLEND);
  65. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  66. glDisable(GL_CULL_FACE);
  67. glDisable(GL_DEPTH_TEST);
  68. glEnable(GL_SCISSOR_TEST);
  69. glEnableClientState(GL_VERTEX_ARRAY);
  70. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  71. glEnableClientState(GL_COLOR_ARRAY);
  72. glEnable(GL_TEXTURE_2D);
  73. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  74. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
  75. // Setup viewport, orthographic projection matrix
  76. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  77. glMatrixMode(GL_PROJECTION);
  78. glPushMatrix();
  79. glLoadIdentity();
  80. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  81. glMatrixMode(GL_MODELVIEW);
  82. glPushMatrix();
  83. glLoadIdentity();
  84. // Render command lists
  85. for (int n = 0; n < draw_data->CmdListsCount; n++)
  86. {
  87. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  88. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  89. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  90. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
  91. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
  92. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
  93. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  94. {
  95. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  96. if (pcmd->UserCallback)
  97. {
  98. pcmd->UserCallback(cmd_list, pcmd);
  99. }
  100. else
  101. {
  102. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  103. 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));
  104. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
  105. }
  106. idx_buffer += pcmd->ElemCount;
  107. }
  108. }
  109. // Restore modified state
  110. glDisableClientState(GL_COLOR_ARRAY);
  111. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  112. glDisableClientState(GL_VERTEX_ARRAY);
  113. glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
  114. glMatrixMode(GL_MODELVIEW);
  115. glPopMatrix();
  116. glMatrixMode(GL_PROJECTION);
  117. glPopMatrix();
  118. glPopAttrib();
  119. glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
  120. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  121. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  122. }
  123. static const char* ImGui_ImplSdlGL2_GetClipboardText(void*)
  124. {
  125. return SDL_GetClipboardText();
  126. }
  127. static void ImGui_ImplSdlGL2_SetClipboardText(void*, const char* text)
  128. {
  129. SDL_SetClipboardText(text);
  130. }
  131. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  132. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  133. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  134. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  135. bool ImGui_ImplSdlGL2_ProcessEvent(SDL_Event* event)
  136. {
  137. ImGuiIO& io = ImGui::GetIO();
  138. switch (event->type)
  139. {
  140. case SDL_MOUSEWHEEL:
  141. {
  142. if (event->wheel.x > 0) io.MouseWheelH += 1;
  143. if (event->wheel.x < 0) io.MouseWheelH -= 1;
  144. if (event->wheel.y > 0) io.MouseWheel += 1;
  145. if (event->wheel.y < 0) io.MouseWheel -= 1;
  146. return true;
  147. }
  148. case SDL_MOUSEBUTTONDOWN:
  149. {
  150. if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
  151. if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
  152. if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
  153. return true;
  154. }
  155. case SDL_TEXTINPUT:
  156. {
  157. io.AddInputCharactersUTF8(event->text.text);
  158. return true;
  159. }
  160. case SDL_KEYDOWN:
  161. case SDL_KEYUP:
  162. {
  163. int key = event->key.keysym.scancode;
  164. IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
  165. io.KeysDown[key] = (event->type == SDL_KEYDOWN);
  166. io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
  167. io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
  168. io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
  169. io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
  170. return true;
  171. }
  172. }
  173. return false;
  174. }
  175. bool ImGui_ImplSdlGL2_CreateDeviceObjects()
  176. {
  177. // Build texture atlas
  178. ImGuiIO& io = ImGui::GetIO();
  179. unsigned char* pixels;
  180. int width, height;
  181. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
  182. // Upload texture to graphics system
  183. GLint last_texture;
  184. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  185. glGenTextures(1, &g_FontTexture);
  186. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  187. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  188. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  189. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  190. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
  191. // Store our identifier
  192. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  193. // Restore state
  194. glBindTexture(GL_TEXTURE_2D, last_texture);
  195. return true;
  196. }
  197. void ImGui_ImplSdlGL2_InvalidateDeviceObjects()
  198. {
  199. if (g_FontTexture)
  200. {
  201. glDeleteTextures(1, &g_FontTexture);
  202. ImGui::GetIO().Fonts->TexID = 0;
  203. g_FontTexture = 0;
  204. }
  205. }
  206. bool ImGui_ImplSdlGL2_Init(SDL_Window* window)
  207. {
  208. // Setup back-end capabilities flags
  209. ImGuiIO& io = ImGui::GetIO();
  210. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  211. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
  212. io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
  213. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  214. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  215. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  216. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  217. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  218. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  219. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  220. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  221. io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
  222. io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
  223. io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
  224. io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE;
  225. io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
  226. io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
  227. io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
  228. io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
  229. io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
  230. io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
  231. io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
  232. io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;
  233. io.SetClipboardTextFn = ImGui_ImplSdlGL2_SetClipboardText;
  234. io.GetClipboardTextFn = ImGui_ImplSdlGL2_GetClipboardText;
  235. io.ClipboardUserData = NULL;
  236. g_MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
  237. g_MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
  238. g_MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
  239. g_MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
  240. g_MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
  241. g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
  242. g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
  243. #ifdef _WIN32
  244. SDL_SysWMinfo wmInfo;
  245. SDL_VERSION(&wmInfo.version);
  246. SDL_GetWindowWMInfo(window, &wmInfo);
  247. io.ImeWindowHandle = wmInfo.info.win.window;
  248. #else
  249. (void)window;
  250. #endif
  251. return true;
  252. }
  253. void ImGui_ImplSdlGL2_Shutdown()
  254. {
  255. // Destroy SDL mouse cursors
  256. for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
  257. SDL_FreeCursor(g_MouseCursors[cursor_n]);
  258. memset(g_MouseCursors, 0, sizeof(g_MouseCursors));
  259. // Destroy OpenGL objects
  260. ImGui_ImplSdlGL2_InvalidateDeviceObjects();
  261. }
  262. void ImGui_ImplSdlGL2_NewFrame(SDL_Window *window)
  263. {
  264. if (!g_FontTexture)
  265. ImGui_ImplSdlGL2_CreateDeviceObjects();
  266. ImGuiIO& io = ImGui::GetIO();
  267. // Setup display size (every frame to accommodate for window resizing)
  268. int w, h;
  269. int display_w, display_h;
  270. SDL_GetWindowSize(window, &w, &h);
  271. SDL_GL_GetDrawableSize(window, &display_w, &display_h);
  272. io.DisplaySize = ImVec2((float)w, (float)h);
  273. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  274. // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
  275. static Uint64 frequency = SDL_GetPerformanceFrequency();
  276. Uint64 current_time = SDL_GetPerformanceCounter();
  277. io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f);
  278. g_Time = current_time;
  279. // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler)
  280. int mx, my;
  281. Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my);
  282. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  283. io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & 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.
  284. io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
  285. io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
  286. g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
  287. // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016)
  288. #if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4)
  289. if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0)
  290. io.MousePos = ImVec2((float)mx, (float)my);
  291. bool any_mouse_button_down = false;
  292. for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
  293. any_mouse_button_down |= io.MouseDown[n];
  294. if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0)
  295. SDL_CaptureMouse(SDL_TRUE);
  296. if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0)
  297. SDL_CaptureMouse(SDL_FALSE);
  298. #else
  299. if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0)
  300. io.MousePos = ImVec2((float)mx, (float)my);
  301. #endif
  302. // Update OS/hardware mouse cursor if imgui isn't drawing a software cursor
  303. if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0)
  304. {
  305. ImGuiMouseCursor cursor = ImGui::GetMouseCursor();
  306. if (io.MouseDrawCursor || cursor == ImGuiMouseCursor_None)
  307. {
  308. SDL_ShowCursor(0);
  309. }
  310. else
  311. {
  312. SDL_SetCursor(g_MouseCursors[cursor] ? g_MouseCursors[cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
  313. SDL_ShowCursor(1);
  314. }
  315. }
  316. // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
  317. ImGui::NewFrame();
  318. }