imgui_impl_sdlrenderer.cpp 9.6 KB

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