imgui_impl_sdlrenderer.cpp 9.0 KB

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