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 in imgui.cpp.
6 
7 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
8 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
9 // https://github.com/ocornut/imgui
10 
11 // CHANGELOG
12 // (minor and older changes stripped away, please see git history for details)
13 //  2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
14 //  2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
15 //  2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
16 //  2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
17 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
18 //  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
19 
20 #include "imgui.h"
21 #include "imgui_impl_dx9.h"
22 
23 // DirectX
24 #include <d3d9.h>
25 #define DIRECTINPUT_VERSION 0x0800
26 #include <dinput.h>
27 
28 // DirectX data
29 static LPDIRECT3DDEVICE9        g_pd3dDevice = NULL;
30 static LPDIRECT3DVERTEXBUFFER9  g_pVB = NULL;
31 static LPDIRECT3DINDEXBUFFER9   g_pIB = NULL;
32 static LPDIRECT3DTEXTURE9       g_FontTexture = NULL;
33 static int                      g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
34 
35 struct CUSTOMVERTEX
36 {
37     float    pos[3];
38     D3DCOLOR col;
39     float    uv[2];
40 };
41 #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
42 
43 // Render function.
44 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
ImGui_ImplDX9_RenderDrawData(ImDrawData * draw_data)45 void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
46 {
47     // Avoid rendering when minimized
48     if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
49         return;
50 
51     // Create and grow buffers if needed
52     if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
53     {
54         if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
55         g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
56         if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
57             return;
58     }
59     if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
60     {
61         if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
62         g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
63         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)
64             return;
65     }
66 
67     // Backup the DX9 state
68     IDirect3DStateBlock9* d3d9_state_block = NULL;
69     if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
70         return;
71 
72     // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
73     D3DMATRIX last_world, last_view, last_projection;
74     g_pd3dDevice->GetTransform(D3DTS_WORLD, &last_world);
75     g_pd3dDevice->GetTransform(D3DTS_VIEW, &last_view);
76     g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection);
77 
78     // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
79     // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and
80     //  1) to avoid repacking colors:   #define IMGUI_USE_BGRA_PACKED_COLOR
81     //  2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
82     CUSTOMVERTEX* vtx_dst;
83     ImDrawIdx* idx_dst;
84     if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
85         return;
86     if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
87         return;
88     for (int n = 0; n < draw_data->CmdListsCount; n++)
89     {
90         const ImDrawList* cmd_list = draw_data->CmdLists[n];
91         const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
92         for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
93         {
94             vtx_dst->pos[0] = vtx_src->pos.x;
95             vtx_dst->pos[1] = vtx_src->pos.y;
96             vtx_dst->pos[2] = 0.0f;
97             vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16);     // RGBA --> ARGB for DirectX9
98             vtx_dst->uv[0] = vtx_src->uv.x;
99             vtx_dst->uv[1] = vtx_src->uv.y;
100             vtx_dst++;
101             vtx_src++;
102         }
103         memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
104         idx_dst += cmd_list->IdxBuffer.Size;
105     }
106     g_pVB->Unlock();
107     g_pIB->Unlock();
108     g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
109     g_pd3dDevice->SetIndices(g_pIB);
110     g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
111 
112     // Setup viewport
113     D3DVIEWPORT9 vp;
114     vp.X = vp.Y = 0;
115     vp.Width = (DWORD)draw_data->DisplaySize.x;
116     vp.Height = (DWORD)draw_data->DisplaySize.y;
117     vp.MinZ = 0.0f;
118     vp.MaxZ = 1.0f;
119     g_pd3dDevice->SetViewport(&vp);
120 
121     // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient)
122     g_pd3dDevice->SetPixelShader(NULL);
123     g_pd3dDevice->SetVertexShader(NULL);
124     g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
125     g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false);
126     g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
127     g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
128     g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false);
129     g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
130     g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
131     g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
132     g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true);
133     g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
134     g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
135     g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
136     g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
137     g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
138     g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
139     g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
140     g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
141     g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
142 
143     // Setup orthographic projection matrix
144     // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
145     // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
146     {
147         float L = draw_data->DisplayPos.x + 0.5f;
148         float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
149         float T = draw_data->DisplayPos.y + 0.5f;
150         float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
151         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 } };
152         D3DMATRIX mat_projection =
153         {
154             2.0f/(R-L),   0.0f,         0.0f,  0.0f,
155             0.0f,         2.0f/(T-B),   0.0f,  0.0f,
156             0.0f,         0.0f,         0.5f,  0.0f,
157             (L+R)/(L-R),  (T+B)/(B-T),  0.5f,  1.0f,
158         };
159         g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
160         g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
161         g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
162     }
163 
164     // Render command lists
165     int vtx_offset = 0;
166     int idx_offset = 0;
167     ImVec2 pos = draw_data->DisplayPos;
168     for (int n = 0; n < draw_data->CmdListsCount; n++)
169     {
170         const ImDrawList* cmd_list = draw_data->CmdLists[n];
171         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
172         {
173             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
174             if (pcmd->UserCallback)
175             {
176                 pcmd->UserCallback(cmd_list, pcmd);
177             }
178             else
179             {
180                 const RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) };
181                 const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId;
182                 g_pd3dDevice->SetTexture(0, texture);
183                 g_pd3dDevice->SetScissorRect(&r);
184                 g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, idx_offset, pcmd->ElemCount/3);
185             }
186             idx_offset += pcmd->ElemCount;
187         }
188         vtx_offset += cmd_list->VtxBuffer.Size;
189     }
190 
191     // Restore the DX9 transform
192     g_pd3dDevice->SetTransform(D3DTS_WORLD, &last_world);
193     g_pd3dDevice->SetTransform(D3DTS_VIEW, &last_view);
194     g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection);
195 
196     // Restore the DX9 state
197     d3d9_state_block->Apply();
198     d3d9_state_block->Release();
199 }
200 
ImGui_ImplDX9_Init(IDirect3DDevice9 * device)201 bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
202 {
203     ImGuiIO& io = ImGui::GetIO();
204     io.BackendRendererName = "imgui_impl_dx9";
205 
206     g_pd3dDevice = device;
207     return true;
208 }
209 
ImGui_ImplDX9_Shutdown()210 void ImGui_ImplDX9_Shutdown()
211 {
212     ImGui_ImplDX9_InvalidateDeviceObjects();
213     g_pd3dDevice = NULL;
214 }
215 
ImGui_ImplDX9_CreateFontsTexture()216 static bool ImGui_ImplDX9_CreateFontsTexture()
217 {
218     // Build texture atlas
219     ImGuiIO& io = ImGui::GetIO();
220     unsigned char* pixels;
221     int width, height, bytes_per_pixel;
222     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
223 
224     // Upload texture to graphics system
225     g_FontTexture = NULL;
226     if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0)
227         return false;
228     D3DLOCKED_RECT tex_locked_rect;
229     if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
230         return false;
231     for (int y = 0; y < height; y++)
232         memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
233     g_FontTexture->UnlockRect(0);
234 
235     // Store our identifier
236     io.Fonts->TexID = (ImTextureID)g_FontTexture;
237 
238     return true;
239 }
240 
ImGui_ImplDX9_CreateDeviceObjects()241 bool ImGui_ImplDX9_CreateDeviceObjects()
242 {
243     if (!g_pd3dDevice)
244         return false;
245     if (!ImGui_ImplDX9_CreateFontsTexture())
246         return false;
247     return true;
248 }
249 
ImGui_ImplDX9_InvalidateDeviceObjects()250 void ImGui_ImplDX9_InvalidateDeviceObjects()
251 {
252     if (!g_pd3dDevice)
253         return;
254     if (g_pVB)
255     {
256         g_pVB->Release();
257         g_pVB = NULL;
258     }
259     if (g_pIB)
260     {
261         g_pIB->Release();
262         g_pIB = NULL;
263     }
264 
265     // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both.
266     ImGuiIO& io = ImGui::GetIO();
267     IM_ASSERT(g_FontTexture == io.Fonts->TexID);
268     if (g_FontTexture)
269         g_FontTexture->Release();
270     g_FontTexture = NULL;
271     io.Fonts->TexID = NULL;
272 }
273 
ImGui_ImplDX9_NewFrame()274 void ImGui_ImplDX9_NewFrame()
275 {
276     if (!g_FontTexture)
277         ImGui_ImplDX9_CreateDeviceObjects();
278 }
279