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