imgui_impl_sdlrenderer.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // dear imgui: Renderer Backend for SDL_Renderer
  2. // (Requires: SDL 2.0.17+)
  3. // Important to understand: SDL_Renderer is an _optional_ component of SDL.
  4. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
  5. // If your application will want to render any non trivial amount of graphics other than UI,
  6. // please be aware that SDL_Renderer offers a limited graphic API to the end-user and it might
  7. // be difficult to step out of those boundaries.
  8. // However, we understand it is a convenient choice to get an app started easily.
  9. // Implemented features:
  10. // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
  11. // Missing features:
  12. // [ ] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices (SDL_RenderGeometryRaw() is missing a vertex offset).
  13. // [ ] Renderer: Multi-viewport support (multiple windows).
  14. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  15. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  16. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  17. // CHANGELOG
  18. // 2021-10-06: Backup and restore modified ClipRect/Viewport.
  19. // 2021-09-21: Initial version.
  20. #include "imgui.h"
  21. #include "imgui_impl_sdlrenderer.h"
  22. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  23. #include <stddef.h> // intptr_t
  24. #else
  25. #include <stdint.h> // intptr_t
  26. #endif
  27. // SDL
  28. #include <SDL.h>
  29. #if !SDL_VERSION_ATLEAST(2,0,17)
  30. #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function
  31. #endif
  32. // SDL_Renderer data
  33. struct ImGui_ImplSDLRenderer_Data
  34. {
  35. SDL_Renderer* SDLRenderer;
  36. SDL_Texture* FontTexture;
  37. ImGui_ImplSDLRenderer_Data() { memset(this, 0, sizeof(*this)); }
  38. };
  39. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  40. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  41. static ImGui_ImplSDLRenderer_Data* ImGui_ImplSDLRenderer_GetBackendData()
  42. {
  43. return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer_Data*)ImGui::GetIO().BackendRendererUserData : NULL;
  44. }
  45. // Functions
  46. bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer)
  47. {
  48. ImGuiIO& io = ImGui::GetIO();
  49. IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!");
  50. IM_ASSERT(renderer != NULL && "SDL_Renderer not initialized!");
  51. // Setup backend capabilities flags
  52. ImGui_ImplSDLRenderer_Data* bd = IM_NEW(ImGui_ImplSDLRenderer_Data)();
  53. io.BackendRendererUserData = (void*)bd;
  54. io.BackendRendererName = "imgui_impl_sdlrenderer";
  55. bd->SDLRenderer = renderer;
  56. return true;
  57. }
  58. void ImGui_ImplSDLRenderer_Shutdown()
  59. {
  60. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  61. IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?");
  62. ImGuiIO& io = ImGui::GetIO();
  63. ImGui_ImplSDLRenderer_DestroyDeviceObjects();
  64. io.BackendRendererName = NULL;
  65. io.BackendRendererUserData = NULL;
  66. IM_DELETE(bd);
  67. }
  68. static void ImGui_ImplSDLRenderer_SetupRenderState()
  69. {
  70. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  71. // Clear out any viewports and cliprect set by the user
  72. // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
  73. SDL_RenderSetViewport(bd->SDLRenderer, NULL);
  74. SDL_RenderSetClipRect(bd->SDLRenderer, NULL);
  75. }
  76. void ImGui_ImplSDLRenderer_NewFrame()
  77. {
  78. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  79. IM_ASSERT(bd != NULL && "Did you call ImGui_ImplSDLRenderer_Init()?");
  80. if (!bd->FontTexture)
  81. ImGui_ImplSDLRenderer_CreateDeviceObjects();
  82. }
  83. void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data)
  84. {
  85. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  86. // If there's a scale factor set by the user, use that instead
  87. // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
  88. // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
  89. float rsx = 1.0f;
  90. float rsy = 1.0f;
  91. SDL_RenderGetScale(bd->SDLRenderer, &rsx, &rsy);
  92. ImVec2 render_scale;
  93. render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
  94. render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
  95. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  96. int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
  97. int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
  98. if (fb_width == 0 || fb_height == 0)
  99. return;
  100. // Backup SDL_Renderer state that will be modified to restore it afterwards
  101. struct BackupSDLRendererState
  102. {
  103. SDL_Rect Viewport;
  104. bool ClipEnabled;
  105. SDL_Rect ClipRect;
  106. };
  107. BackupSDLRendererState old = {};
  108. old.ClipEnabled = SDL_RenderIsClipEnabled(bd->SDLRenderer);
  109. SDL_RenderGetViewport(bd->SDLRenderer, &old.Viewport);
  110. SDL_RenderGetClipRect(bd->SDLRenderer, &old.ClipRect);
  111. // Will project scissor/clipping rectangles into framebuffer space
  112. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  113. ImVec2 clip_scale = render_scale;
  114. // Render command lists
  115. ImGui_ImplSDLRenderer_SetupRenderState();
  116. for (int n = 0; n < draw_data->CmdListsCount; n++)
  117. {
  118. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  119. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  120. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  121. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  122. {
  123. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  124. if (pcmd->UserCallback)
  125. {
  126. // User callback, registered via ImDrawList::AddCallback()
  127. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  128. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  129. ImGui_ImplSDLRenderer_SetupRenderState();
  130. else
  131. pcmd->UserCallback(cmd_list, pcmd);
  132. }
  133. else
  134. {
  135. // Project scissor/clipping rectangles into framebuffer space
  136. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  137. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  138. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  139. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  140. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  141. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  142. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  143. continue;
  144. SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) };
  145. SDL_RenderSetClipRect(bd->SDLRenderer, &r);
  146. const float* xy = (const float*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos));
  147. const float* uv = (const float*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv));
  148. const int* color = (const int*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col));
  149. // Bind texture, Draw
  150. SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
  151. SDL_RenderGeometryRaw(bd->SDLRenderer, tex,
  152. xy, (int)sizeof(ImDrawVert),
  153. color, (int)sizeof(ImDrawVert),
  154. uv, (int)sizeof(ImDrawVert),
  155. cmd_list->VtxBuffer.Size,
  156. idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
  157. }
  158. }
  159. }
  160. // Restore modified SDL_Renderer state
  161. SDL_RenderSetViewport(bd->SDLRenderer, &old.Viewport);
  162. SDL_RenderSetClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : NULL);
  163. }
  164. // Called by Init/NewFrame/Shutdown
  165. bool ImGui_ImplSDLRenderer_CreateFontsTexture()
  166. {
  167. ImGuiIO& io = ImGui::GetIO();
  168. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  169. // Build texture atlas
  170. unsigned char* pixels;
  171. int width, height;
  172. 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.
  173. // Upload texture to graphics system
  174. bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height);
  175. if (bd->FontTexture == NULL)
  176. {
  177. SDL_Log("error creating texture");
  178. return false;
  179. }
  180. SDL_UpdateTexture(bd->FontTexture, NULL, pixels, 4 * width);
  181. SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND);
  182. // Store our identifier
  183. io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
  184. return true;
  185. }
  186. void ImGui_ImplSDLRenderer_DestroyFontsTexture()
  187. {
  188. ImGuiIO& io = ImGui::GetIO();
  189. ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData();
  190. if (bd->FontTexture)
  191. {
  192. io.Fonts->SetTexID(0);
  193. SDL_DestroyTexture(bd->FontTexture);
  194. bd->FontTexture = NULL;
  195. }
  196. }
  197. bool ImGui_ImplSDLRenderer_CreateDeviceObjects()
  198. {
  199. return ImGui_ImplSDLRenderer_CreateFontsTexture();
  200. }
  201. void ImGui_ImplSDLRenderer_DestroyDeviceObjects()
  202. {
  203. ImGui_ImplSDLRenderer_DestroyFontsTexture();
  204. }