imgui_impl_dx9.cpp
Go to the documentation of this file.
1 // dear imgui: Renderer for DirectX9
2 // This needs to be used along with a Platform Binding (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: Support for large meshes (64k+ vertices) with 16-bit indices.
7 
8 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
9 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
10 // https://github.com/ocornut/imgui
11 
12 // CHANGELOG
13 // (minor and older changes stripped away, please see git history for details)
14 // 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
15 // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
16 // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
17 // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
18 // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
19 // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
20 // 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
21 // 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
22 // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
23 // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
24 
25 #include "imgui.h"
26 #include "imgui_impl_dx9.h"
27 
28 // DirectX
29 #include <d3d9.h>
30 #define DIRECTINPUT_VERSION 0x0800
31 #include <dinput.h>
32 
33 // DirectX data
34 static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
35 static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL;
36 static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL;
37 static LPDIRECT3DTEXTURE9 g_FontTexture = NULL;
38 static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
39 
41 {
42  float pos[3];
43  D3DCOLOR col;
44  float uv[2];
45 };
46 #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
47 
49 {
50  // Setup viewport
51  D3DVIEWPORT9 vp;
52  vp.X = vp.Y = 0;
53  vp.Width = (DWORD)draw_data->DisplaySize.x;
54  vp.Height = (DWORD)draw_data->DisplaySize.y;
55  vp.MinZ = 0.0f;
56  vp.MaxZ = 1.0f;
57  g_pd3dDevice->SetViewport(&vp);
58 
59  // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient)
60  g_pd3dDevice->SetPixelShader(NULL);
61  g_pd3dDevice->SetVertexShader(NULL);
62  g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
63  g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
64  g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
65  g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
66  g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
67  g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
68  g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
69  g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
70  g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
71  g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
72  g_pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
73  g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
74  g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
75  g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
76  g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
77  g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
78  g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
79  g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
80  g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
81 
82  // Setup orthographic projection matrix
83  // 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.
84  // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
85  {
86  float L = draw_data->DisplayPos.x + 0.5f;
87  float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
88  float T = draw_data->DisplayPos.y + 0.5f;
89  float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
90  D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } };
91  D3DMATRIX mat_projection =
92  { { {
93  2.0f/(R-L), 0.0f, 0.0f, 0.0f,
94  0.0f, 2.0f/(T-B), 0.0f, 0.0f,
95  0.0f, 0.0f, 0.5f, 0.0f,
96  (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f
97  } } };
98  g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
99  g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
100  g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
101  }
102 }
103 
104 // Render function.
105 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
107 {
108  // Avoid rendering when minimized
109  if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
110  return;
111 
112  // Create and grow buffers if needed
113  if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
114  {
115  if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
116  g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
117  if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
118  return;
119  }
120  if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
121  {
122  if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
123  g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
124  if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0)
125  return;
126  }
127 
128  // Backup the DX9 state
129  IDirect3DStateBlock9* d3d9_state_block = NULL;
130  if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
131  return;
132 
133  // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
134  D3DMATRIX last_world, last_view, last_projection;
135  g_pd3dDevice->GetTransform(D3DTS_WORLD, &last_world);
136  g_pd3dDevice->GetTransform(D3DTS_VIEW, &last_view);
137  g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection);
138 
139  // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
140  // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and
141  // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
142  // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
143  CUSTOMVERTEX* vtx_dst;
144  ImDrawIdx* idx_dst;
145  if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
146  return;
147  if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
148  return;
149  for (int n = 0; n < draw_data->CmdListsCount; n++)
150  {
151  const ImDrawList* cmd_list = draw_data->CmdLists[n];
152  const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
153  for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
154  {
155  vtx_dst->pos[0] = vtx_src->pos.x;
156  vtx_dst->pos[1] = vtx_src->pos.y;
157  vtx_dst->pos[2] = 0.0f;
158  vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
159  vtx_dst->uv[0] = vtx_src->uv.x;
160  vtx_dst->uv[1] = vtx_src->uv.y;
161  vtx_dst++;
162  vtx_src++;
163  }
164  memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
165  idx_dst += cmd_list->IdxBuffer.Size;
166  }
167  g_pVB->Unlock();
168  g_pIB->Unlock();
169  g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
170  g_pd3dDevice->SetIndices(g_pIB);
172 
173  // Setup desired DX state
175 
176  // Render command lists
177  // (Because we merged all buffers into a single one, we maintain our own offset into them)
178  int global_vtx_offset = 0;
179  int global_idx_offset = 0;
180  ImVec2 clip_off = draw_data->DisplayPos;
181  for (int n = 0; n < draw_data->CmdListsCount; n++)
182  {
183  const ImDrawList* cmd_list = draw_data->CmdLists[n];
184  for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
185  {
186  const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
187  if (pcmd->UserCallback != NULL)
188  {
189  // User callback, registered via ImDrawList::AddCallback()
190  // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
193  else
194  pcmd->UserCallback(cmd_list, pcmd);
195  }
196  else
197  {
198  const RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) };
199  const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId;
200  g_pd3dDevice->SetTexture(0, texture);
201  g_pd3dDevice->SetScissorRect(&r);
202  g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount/3);
203  }
204  }
205  global_idx_offset += cmd_list->IdxBuffer.Size;
206  global_vtx_offset += cmd_list->VtxBuffer.Size;
207  }
208 
209  // Restore the DX9 transform
210  g_pd3dDevice->SetTransform(D3DTS_WORLD, &last_world);
211  g_pd3dDevice->SetTransform(D3DTS_VIEW, &last_view);
212  g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection);
213 
214  // Restore the DX9 state
215  d3d9_state_block->Apply();
216  d3d9_state_block->Release();
217 }
218 
219 bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
220 {
221  // Setup back-end capabilities flags
222  ImGuiIO& io = ImGui::GetIO();
223  io.BackendRendererName = "imgui_impl_dx9";
224  io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
225 
226  g_pd3dDevice = device;
227  g_pd3dDevice->AddRef();
228  return true;
229 }
230 
232 {
234  if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
235 }
236 
238 {
239  // Build texture atlas
240  ImGuiIO& io = ImGui::GetIO();
241  unsigned char* pixels;
242  int width, height, bytes_per_pixel;
243  io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
244 
245  // Upload texture to graphics system
247  if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0)
248  return false;
249  D3DLOCKED_RECT tex_locked_rect;
250  if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
251  return false;
252  for (int y = 0; y < height; y++)
253  memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
254  g_FontTexture->UnlockRect(0);
255 
256  // Store our identifier
258 
259  return true;
260 }
261 
263 {
264  if (!g_pd3dDevice)
265  return false;
267  return false;
268  return true;
269 }
270 
272 {
273  if (!g_pd3dDevice)
274  return;
275  if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
276  if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
277  if (g_FontTexture) { g_FontTexture->Release(); g_FontTexture = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
278 }
279 
281 {
282  if (!g_FontTexture)
284 }
ImDrawIdx
unsigned short ImDrawIdx
Definition: imgui.h:1888
height
GLint GLsizei GLsizei height
Definition: glcorearb.h:2768
ImDrawCmd::VtxOffset
unsigned int VtxOffset
Definition: imgui.h:1876
ImDrawData::DisplayPos
ImVec2 DisplayPos
Definition: imgui.h:2075
ImGuiIO::Fonts
ImFontAtlas * Fonts
Definition: imgui.h:1435
ImDrawList::IdxBuffer
ImVector< ImDrawIdx > IdxBuffer
Definition: imgui.h:1965
ImFontAtlas::TexID
ImTextureID TexID
Definition: imgui.h:2247
ImDrawData::CmdListsCount
int CmdListsCount
Definition: imgui.h:2072
NULL
NULL
Definition: test_security_zap.cpp:405
texture
GLuint texture
Definition: glcorearb.h:2840
ImVec4::z
float z
Definition: imgui.h:223
CUSTOMVERTEX
Definition: imgui_impl_dx9.cpp:40
g_VertexBufferSize
static int g_VertexBufferSize
Definition: imgui_impl_dx9.cpp:38
CUSTOMVERTEX::uv
float uv[2]
Definition: imgui_impl_dx9.cpp:44
ImDrawData::CmdLists
ImDrawList ** CmdLists
Definition: imgui.h:2071
ImDrawVert::uv
ImVec2 uv
Definition: imgui.h:1896
ImDrawList
Definition: imgui.h:1961
ImTextureID
void * ImTextureID
Definition: imgui.h:172
ImGui_ImplDX9_InvalidateDeviceObjects
void ImGui_ImplDX9_InvalidateDeviceObjects()
Definition: imgui_impl_dx9.cpp:271
imgui.h
y
GLint y
Definition: glcorearb.h:2768
ImVec2
Definition: imgui.h:208
ImGui::GetIO
IMGUI_API ImGuiIO & GetIO()
Definition: imgui.cpp:3286
T
#define T(upbtypeconst, upbtype, ctype, default_value)
g_FontTexture
static LPDIRECT3DTEXTURE9 g_FontTexture
Definition: imgui_impl_dx9.cpp:37
ImGui_ImplDX9_RenderDrawData
void ImGui_ImplDX9_RenderDrawData(ImDrawData *draw_data)
Definition: imgui_impl_dx9.cpp:106
ImDrawList::CmdBuffer
ImVector< ImDrawCmd > CmdBuffer
Definition: imgui.h:1964
ImDrawCmd
Definition: imgui.h:1871
ImDrawCmd::TextureId
ImTextureID TextureId
Definition: imgui.h:1875
ImDrawCmd::UserCallback
ImDrawCallback UserCallback
Definition: imgui.h:1878
ImVec4::y
float y
Definition: imgui.h:223
ImGui_ImplDX9_NewFrame
void ImGui_ImplDX9_NewFrame()
Definition: imgui_impl_dx9.cpp:280
ImVector::Data
T * Data
Definition: imgui.h:1305
ImGui_ImplDX9_Init
bool ImGui_ImplDX9_Init(IDirect3DDevice9 *device)
Definition: imgui_impl_dx9.cpp:219
ImDrawData
Definition: imgui.h:2068
ImVector::Size
int Size
Definition: imgui.h:1303
ImDrawVert
Definition: imgui.h:1893
ImVec2::x
float x
Definition: imgui.h:210
ImDrawCmd::ClipRect
ImVec4 ClipRect
Definition: imgui.h:1874
CUSTOMVERTEX::col
D3DCOLOR col
Definition: imgui_impl_dx9.cpp:43
D3DFVF_CUSTOMVERTEX
#define D3DFVF_CUSTOMVERTEX
Definition: imgui_impl_dx9.cpp:46
g_pIB
static LPDIRECT3DINDEXBUFFER9 g_pIB
Definition: imgui_impl_dx9.cpp:36
ImDrawData::TotalVtxCount
int TotalVtxCount
Definition: imgui.h:2074
ImVec4::x
float x
Definition: imgui.h:223
ImGuiBackendFlags_RendererHasVtxOffset
@ ImGuiBackendFlags_RendererHasVtxOffset
Definition: imgui.h:1080
n
GLdouble n
Definition: glcorearb.h:4153
ImDrawList::VtxBuffer
ImVector< ImDrawVert > VtxBuffer
Definition: imgui.h:1966
i
int i
Definition: gmock-matchers_test.cc:764
ImDrawVert::col
ImU32 col
Definition: imgui.h:1897
ImGui_ImplDX9_Shutdown
void ImGui_ImplDX9_Shutdown()
Definition: imgui_impl_dx9.cpp:231
g_pVB
static LPDIRECT3DVERTEXBUFFER9 g_pVB
Definition: imgui_impl_dx9.cpp:35
ImVec4::w
float w
Definition: imgui.h:223
g_pd3dDevice
static LPDIRECT3DDEVICE9 g_pd3dDevice
Definition: imgui_impl_dx9.cpp:34
ImDrawCallback_ResetRenderState
#define ImDrawCallback_ResetRenderState
Definition: imgui.h:1866
ImGuiIO::BackendRendererName
const char * BackendRendererName
Definition: imgui.h:1456
r
GLboolean r
Definition: glcorearb.h:3228
ImGui_ImplDX9_CreateDeviceObjects
bool ImGui_ImplDX9_CreateDeviceObjects()
Definition: imgui_impl_dx9.cpp:262
ImGuiIO
Definition: imgui.h:1414
g_IndexBufferSize
static int g_IndexBufferSize
Definition: imgui_impl_dx9.cpp:38
ImDrawData::TotalIdxCount
int TotalIdxCount
Definition: imgui.h:2073
ImGui_ImplDX9_CreateFontsTexture
static bool ImGui_ImplDX9_CreateFontsTexture()
Definition: imgui_impl_dx9.cpp:237
imgui_impl_dx9.h
ImDrawData::DisplaySize
ImVec2 DisplaySize
Definition: imgui.h:2076
f
GLfloat f
Definition: glcorearb.h:3964
ImDrawCmd::IdxOffset
unsigned int IdxOffset
Definition: imgui.h:1877
pixels
GLint GLint GLsizei GLint GLenum GLenum const GLvoid * pixels
Definition: glcorearb.h:2773
ImDrawVert::pos
ImVec2 pos
Definition: imgui.h:1895
ImGuiIO::BackendFlags
ImGuiBackendFlags BackendFlags
Definition: imgui.h:1421
ImGui_ImplDX9_SetupRenderState
static void ImGui_ImplDX9_SetupRenderState(ImDrawData *draw_data)
Definition: imgui_impl_dx9.cpp:48
ImVec2::y
float y
Definition: imgui.h:210
width
GLint GLsizei width
Definition: glcorearb.h:2768
CUSTOMVERTEX::pos
float pos[3]
Definition: imgui_impl_dx9.cpp:42
ImDrawCmd::ElemCount
unsigned int ElemCount
Definition: imgui.h:1873
ImFontAtlas::GetTexDataAsRGBA32
IMGUI_API void GetTexDataAsRGBA32(unsigned char **out_pixels, int *out_width, int *out_height, int *out_bytes_per_pixel=NULL)
Definition: imgui_draw.cpp:1679


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:54