1// dear imgui: Renderer Backend for DirectX9
2// This needs to be used along with a Platform Backend (e.g. Win32)
3
4// Implemented features:
5// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
6// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7// [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
8// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
10// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12// Learn about Dear ImGui:
13// - FAQ https://dearimgui.com/faq
14// - Getting Started https://dearimgui.com/getting-started
15// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16// - Introduction, links and more at the top of imgui.cpp
17
18// CHANGELOG
19// (minor and older changes stripped away, please see git history for details)
20// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
21// 2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap.
22// 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575)
23// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
24// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
25// 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
26// 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
27// 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states.
28// 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857).
29// 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file.
30// 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer.
31// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
32// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
33// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
34// 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
35// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
36// 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
37// 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
38// 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
39// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
40// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
41
42#include "imgui.h"
43#ifndef IMGUI_DISABLE
44#include "imgui_impl_dx9.h"
45
46// DirectX
47#include <d3d9.h>
48
49// DirectX data
50struct ImGui_ImplDX9_Data
51{
52 LPDIRECT3DDEVICE9 pd3dDevice;
53 LPDIRECT3DVERTEXBUFFER9 pVB;
54 LPDIRECT3DINDEXBUFFER9 pIB;
55 LPDIRECT3DTEXTURE9 FontTexture;
56 int VertexBufferSize;
57 int IndexBufferSize;
58 bool HasRgbaSupport;
59
60 ImGui_ImplDX9_Data() { memset(s: (void*)this, c: 0, n: sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
61};
62
63struct CUSTOMVERTEX
64{
65 float pos[3];
66 D3DCOLOR col;
67 float uv[2];
68};
69#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
70
71#ifdef IMGUI_USE_BGRA_PACKED_COLOR
72#define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL)
73#else
74#define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16))
75#endif
76
77// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
78// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
79static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData()
80{
81 return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
82}
83
84// Forward Declarations
85static void ImGui_ImplDX9_InitMultiViewportSupport();
86static void ImGui_ImplDX9_ShutdownMultiViewportSupport();
87static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
88static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
89
90// Functions
91static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
92{
93 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
94
95 // Setup viewport
96 D3DVIEWPORT9 vp;
97 vp.X = vp.Y = 0;
98 vp.Width = (DWORD)draw_data->DisplaySize.x;
99 vp.Height = (DWORD)draw_data->DisplaySize.y;
100 vp.MinZ = 0.0f;
101 vp.MaxZ = 1.0f;
102
103 LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
104 device->SetViewport(&vp);
105
106 // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling.
107 device->SetPixelShader(nullptr);
108 device->SetVertexShader(nullptr);
109 device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
110 device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
111 device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
112 device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
113 device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
114 device->SetRenderState(D3DRS_ZENABLE, FALSE);
115 device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
116 device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
117 device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
118 device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
119 device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
120 device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
121 device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
122 device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
123 device->SetRenderState(D3DRS_FOGENABLE, FALSE);
124 device->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
125 device->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
126 device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
127 device->SetRenderState(D3DRS_CLIPPING, TRUE);
128 device->SetRenderState(D3DRS_LIGHTING, FALSE);
129 device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
130 device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
131 device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
132 device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
133 device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
134 device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
135 device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
136 device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
137 device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
138 device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
139 device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
140 device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
141
142 // Setup orthographic projection matrix
143 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
144 // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
145 {
146 float L = draw_data->DisplayPos.x + 0.5f;
147 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
148 float T = draw_data->DisplayPos.y + 0.5f;
149 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
150 D3DMATRIX mat_identity = { { { ._11: 1.0f, ._12: 0.0f, ._13: 0.0f, ._14: 0.0f, ._21: 0.0f, ._22: 1.0f, ._23: 0.0f, ._24: 0.0f, ._31: 0.0f, ._32: 0.0f, ._33: 1.0f, ._34: 0.0f, ._41: 0.0f, ._42: 0.0f, ._43: 0.0f, ._44: 1.0f } } };
151 D3DMATRIX mat_projection =
152 { { {
153 ._11: 2.0f/(R-L), ._12: 0.0f, ._13: 0.0f, ._14: 0.0f,
154 ._21: 0.0f, ._22: 2.0f/(T-B), ._23: 0.0f, ._24: 0.0f,
155 ._31: 0.0f, ._32: 0.0f, ._33: 0.5f, ._34: 0.0f,
156 ._41: (L+R)/(L-R), ._42: (T+B)/(B-T), ._43: 0.5f, ._44: 1.0f
157 } } };
158 device->SetTransform(D3DTS_WORLD, &mat_identity);
159 device->SetTransform(D3DTS_VIEW, &mat_identity);
160 device->SetTransform(D3DTS_PROJECTION, &mat_projection);
161 }
162}
163
164// Render function.
165void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
166{
167 // Avoid rendering when minimized
168 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
169 return;
170
171 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
172 LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
173
174 // Create and grow buffers if needed
175 if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
176 {
177 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
178 bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
179 if (device->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
180 return;
181 }
182 if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
183 {
184 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
185 bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
186 if (device->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0)
187 return;
188 }
189
190 // Backup the DX9 state
191 IDirect3DStateBlock9* state_block = nullptr;
192 if (device->CreateStateBlock(D3DSBT_ALL, &state_block) < 0)
193 return;
194 if (state_block->Capture() < 0)
195 {
196 state_block->Release();
197 return;
198 }
199
200 // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
201 D3DMATRIX last_world, last_view, last_projection;
202 device->GetTransform(D3DTS_WORLD, &last_world);
203 device->GetTransform(D3DTS_VIEW, &last_view);
204 device->GetTransform(D3DTS_PROJECTION, &last_projection);
205
206 // Allocate buffers
207 CUSTOMVERTEX* vtx_dst;
208 ImDrawIdx* idx_dst;
209 if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
210 {
211 state_block->Release();
212 return;
213 }
214 if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
215 {
216 bd->pVB->Unlock();
217 state_block->Release();
218 return;
219 }
220
221 // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
222 // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and
223 // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
224 // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
225 for (int n = 0; n < draw_data->CmdListsCount; n++)
226 {
227 const ImDrawList* draw_list = draw_data->CmdLists[n];
228 const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data;
229 for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
230 {
231 vtx_dst->pos[0] = vtx_src->pos.x;
232 vtx_dst->pos[1] = vtx_src->pos.y;
233 vtx_dst->pos[2] = 0.0f;
234 vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col);
235 vtx_dst->uv[0] = vtx_src->uv.x;
236 vtx_dst->uv[1] = vtx_src->uv.y;
237 vtx_dst++;
238 vtx_src++;
239 }
240 memcpy(dest: idx_dst, src: draw_list->IdxBuffer.Data, n: draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
241 idx_dst += draw_list->IdxBuffer.Size;
242 }
243 bd->pVB->Unlock();
244 bd->pIB->Unlock();
245 device->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
246 device->SetIndices(bd->pIB);
247 device->SetFVF(D3DFVF_CUSTOMVERTEX);
248
249 // Setup desired DX state
250 ImGui_ImplDX9_SetupRenderState(draw_data);
251
252 // Render command lists
253 // (Because we merged all buffers into a single one, we maintain our own offset into them)
254 int global_vtx_offset = 0;
255 int global_idx_offset = 0;
256 ImVec2 clip_off = draw_data->DisplayPos;
257 for (int n = 0; n < draw_data->CmdListsCount; n++)
258 {
259 const ImDrawList* draw_list = draw_data->CmdLists[n];
260 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
261 {
262 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
263 if (pcmd->UserCallback != nullptr)
264 {
265 // User callback, registered via ImDrawList::AddCallback()
266 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
267 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
268 ImGui_ImplDX9_SetupRenderState(draw_data);
269 else
270 pcmd->UserCallback(draw_list, pcmd);
271 }
272 else
273 {
274 // Project scissor/clipping rectangles into framebuffer space
275 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
276 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
277 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
278 continue;
279
280 // Apply scissor/clipping rectangle
281 const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
282 device->SetScissorRect(&r);
283
284 // Bind texture, Draw
285 const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
286 device->SetTexture(0, texture);
287 device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)draw_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
288 }
289 }
290 global_idx_offset += draw_list->IdxBuffer.Size;
291 global_vtx_offset += draw_list->VtxBuffer.Size;
292 }
293
294 // When using multi-viewports, it appears that there's an odd logic in DirectX9 which prevent subsequent windows
295 // from rendering until the first window submits at least one draw call, even once. That's our workaround. (see #2560)
296 if (global_vtx_offset == 0)
297 bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 0, 0, 0);
298
299 // Restore the DX9 transform
300 device->SetTransform(D3DTS_WORLD, &last_world);
301 device->SetTransform(D3DTS_VIEW, &last_view);
302 device->SetTransform(D3DTS_PROJECTION, &last_projection);
303
304 // Restore the DX9 state
305 state_block->Apply();
306 state_block->Release();
307}
308
309static bool ImGui_ImplDX9_CheckFormatSupport(LPDIRECT3DDEVICE9 pDevice, D3DFORMAT format)
310{
311 LPDIRECT3D9 pd3d = nullptr;
312 if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
313 return false;
314 D3DDEVICE_CREATION_PARAMETERS param = {};
315 D3DDISPLAYMODE mode = {};
316 if (pDevice->GetCreationParameters(&param) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
317 {
318 pd3d->Release();
319 return false;
320 }
321 // Font texture should support linear filter, color blend and write to render-target
322 bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
323 pd3d->Release();
324 return support;
325}
326
327bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
328{
329 ImGuiIO& io = ImGui::GetIO();
330 IMGUI_CHECKVERSION();
331 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
332
333 // Setup backend capabilities flags
334 ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)();
335 io.BackendRendererUserData = (void*)bd;
336 io.BackendRendererName = "imgui_impl_dx9";
337 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
338 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
339
340 bd->pd3dDevice = device;
341 bd->pd3dDevice->AddRef();
342 bd->HasRgbaSupport = ImGui_ImplDX9_CheckFormatSupport(pDevice: bd->pd3dDevice, format: D3DFMT_A8B8G8R8);
343
344 ImGui_ImplDX9_InitMultiViewportSupport();
345
346 return true;
347}
348
349void ImGui_ImplDX9_Shutdown()
350{
351 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
352 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
353 ImGuiIO& io = ImGui::GetIO();
354
355 ImGui_ImplDX9_ShutdownMultiViewportSupport();
356 ImGui_ImplDX9_InvalidateDeviceObjects();
357 if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
358 io.BackendRendererName = nullptr;
359 io.BackendRendererUserData = nullptr;
360 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
361 IM_DELETE(p: bd);
362}
363
364// Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
365static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h)
366{
367#ifndef IMGUI_USE_BGRA_PACKED_COLOR
368 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
369 const bool convert_rgba_to_bgra = (!bd->HasRgbaSupport && tex_use_colors);
370#else
371 const bool convert_rgba_to_bgra = false;
372 IM_UNUSED(tex_use_colors);
373#endif
374 for (int y = 0; y < h; y++)
375 {
376 ImU32* src_p = (ImU32*)((unsigned char*)src + src_pitch * y);
377 ImU32* dst_p = (ImU32*)((unsigned char*)dst + dst_pitch * y);
378 if (convert_rgba_to_bgra)
379 for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy
380 *dst_p = IMGUI_COL_TO_DX9_ARGB(*src_p);
381 else
382 memcpy(dest: dst_p, src: src_p, n: w * 4); // Raw copy
383 }
384}
385
386static bool ImGui_ImplDX9_CreateFontsTexture()
387{
388 // Build texture atlas
389 ImGuiIO& io = ImGui::GetIO();
390 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
391 unsigned char* pixels;
392 int width, height, bytes_per_pixel;
393 io.Fonts->GetTexDataAsRGBA32(out_pixels: &pixels, out_width: &width, out_height: &height, out_bytes_per_pixel: &bytes_per_pixel);
394
395 // Upload texture to graphics system
396 bd->FontTexture = nullptr;
397 if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
398 return false;
399 D3DLOCKED_RECT tex_locked_rect;
400 if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK)
401 return false;
402 ImGui_ImplDX9_CopyTextureRegion(tex_use_colors: io.Fonts->TexPixelsUseColors, src: (ImU32*)pixels, src_pitch: width * bytes_per_pixel, dst: (ImU32*)tex_locked_rect.pBits, dst_pitch: (int)tex_locked_rect.Pitch, w: width, h: height);
403 bd->FontTexture->UnlockRect(0);
404
405 // Store our identifier
406 io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
407 return true;
408}
409
410bool ImGui_ImplDX9_CreateDeviceObjects()
411{
412 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
413 if (!bd || !bd->pd3dDevice)
414 return false;
415 if (!ImGui_ImplDX9_CreateFontsTexture())
416 return false;
417 ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
418 return true;
419}
420
421void ImGui_ImplDX9_InvalidateDeviceObjects()
422{
423 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
424 if (!bd || !bd->pd3dDevice)
425 return;
426 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
427 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
428 if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
429 ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
430}
431
432void ImGui_ImplDX9_NewFrame()
433{
434 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
435 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?");
436
437 if (!bd->FontTexture)
438 ImGui_ImplDX9_CreateDeviceObjects();
439}
440
441//--------------------------------------------------------------------------------------------------------
442// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
443// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
444// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
445//--------------------------------------------------------------------------------------------------------
446
447// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
448struct ImGui_ImplDX9_ViewportData
449{
450 IDirect3DSwapChain9* SwapChain;
451 D3DPRESENT_PARAMETERS d3dpp;
452
453 ImGui_ImplDX9_ViewportData() { SwapChain = nullptr; ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); }
454 ~ImGui_ImplDX9_ViewportData() { IM_ASSERT(SwapChain == nullptr); }
455};
456
457static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport)
458{
459 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
460 ImGui_ImplDX9_ViewportData* vd = IM_NEW(ImGui_ImplDX9_ViewportData)();
461 viewport->RendererUserData = vd;
462
463 // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
464 // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
465 HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
466 IM_ASSERT(hwnd != 0);
467
468 ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
469 vd->d3dpp.Windowed = TRUE;
470 vd->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
471 vd->d3dpp.BackBufferWidth = (UINT)viewport->Size.x;
472 vd->d3dpp.BackBufferHeight = (UINT)viewport->Size.y;
473 vd->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
474 vd->d3dpp.hDeviceWindow = hwnd;
475 vd->d3dpp.EnableAutoDepthStencil = FALSE;
476 vd->d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
477 vd->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync
478
479 HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
480 IM_ASSERT(hr == D3D_OK);
481 IM_ASSERT(vd->SwapChain != nullptr);
482}
483
484static void ImGui_ImplDX9_DestroyWindow(ImGuiViewport* viewport)
485{
486 // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
487 if (ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData)
488 {
489 if (vd->SwapChain)
490 vd->SwapChain->Release();
491 vd->SwapChain = nullptr;
492 ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
493 IM_DELETE(p: vd);
494 }
495 viewport->RendererUserData = nullptr;
496}
497
498static void ImGui_ImplDX9_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
499{
500 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
501 ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
502 if (vd->SwapChain)
503 {
504 vd->SwapChain->Release();
505 vd->SwapChain = nullptr;
506 vd->d3dpp.BackBufferWidth = (UINT)size.x;
507 vd->d3dpp.BackBufferHeight = (UINT)size.y;
508 HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
509 IM_ASSERT(hr == D3D_OK);
510 }
511}
512
513static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*)
514{
515 ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
516 ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
517 ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
518
519 LPDIRECT3DSURFACE9 render_target = nullptr;
520 LPDIRECT3DSURFACE9 last_render_target = nullptr;
521 LPDIRECT3DSURFACE9 last_depth_stencil = nullptr;
522 vd->SwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &render_target);
523 bd->pd3dDevice->GetRenderTarget(0, &last_render_target);
524 bd->pd3dDevice->GetDepthStencilSurface(&last_depth_stencil);
525 bd->pd3dDevice->SetRenderTarget(0, render_target);
526 bd->pd3dDevice->SetDepthStencilSurface(nullptr);
527
528 if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
529 {
530 D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f));
531 bd->pd3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET, clear_col_dx, 1.0f, 0);
532 }
533
534 ImGui_ImplDX9_RenderDrawData(draw_data: viewport->DrawData);
535
536 // Restore render target
537 bd->pd3dDevice->SetRenderTarget(0, last_render_target);
538 bd->pd3dDevice->SetDepthStencilSurface(last_depth_stencil);
539 render_target->Release();
540 last_render_target->Release();
541 if (last_depth_stencil) last_depth_stencil->Release();
542}
543
544static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*)
545{
546 ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
547 HRESULT hr = vd->SwapChain->Present(nullptr, nullptr, vd->d3dpp.hDeviceWindow, nullptr, 0);
548 // Let main application handle D3DERR_DEVICELOST by resetting the device.
549 IM_ASSERT(SUCCEEDED(hr) || hr == D3DERR_DEVICELOST);
550}
551
552static void ImGui_ImplDX9_InitMultiViewportSupport()
553{
554 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
555 platform_io.Renderer_CreateWindow = ImGui_ImplDX9_CreateWindow;
556 platform_io.Renderer_DestroyWindow = ImGui_ImplDX9_DestroyWindow;
557 platform_io.Renderer_SetWindowSize = ImGui_ImplDX9_SetWindowSize;
558 platform_io.Renderer_RenderWindow = ImGui_ImplDX9_RenderWindow;
559 platform_io.Renderer_SwapBuffers = ImGui_ImplDX9_SwapBuffers;
560}
561
562static void ImGui_ImplDX9_ShutdownMultiViewportSupport()
563{
564 ImGui::DestroyPlatformWindows();
565}
566
567static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows()
568{
569 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
570 for (int i = 1; i < platform_io.Viewports.Size; i++)
571 if (!platform_io.Viewports[i]->RendererUserData)
572 ImGui_ImplDX9_CreateWindow(viewport: platform_io.Viewports[i]);
573}
574
575static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows()
576{
577 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
578 for (int i = 1; i < platform_io.Viewports.Size; i++)
579 if (platform_io.Viewports[i]->RendererUserData)
580 ImGui_ImplDX9_DestroyWindow(viewport: platform_io.Viewports[i]);
581}
582
583//-----------------------------------------------------------------------------
584
585#endif // #ifndef IMGUI_DISABLE
586

source code of imgui/backends/imgui_impl_dx9.cpp