imgui_impl_sdlrenderer.cpp 9.0 KB

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