38.9 KB、806行 生 Blame 履歴
1// dear imgui: Renderer Backend for DirectX10
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 'ID3D10ShaderResourceView*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
6// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
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// 2026-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
21// 2026-04-23: DirectX10: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. Obsoleting samplers from ImGui_ImplDX10_RenderState. (#9378)
22// 2026-01-19: DirectX10: Added 'SamplerNearest' in ImGui_ImplDX10_RenderState. Renamed 'SamplerDefault' to 'SamplerLinear'.
23// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
24// 2025-06-11: DirectX10: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
25// 2025-05-07: DirectX10: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
26// 2025-01-06: DirectX10: Expose selected render state in ImGui_ImplDX10_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
27// 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap.
28// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
29// 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).
30// 2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
31// 2021-02-18: DirectX10: Change blending equation to preserve alpha in output buffer.
32// 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData().
33// 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
34// 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
35// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
36// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
37// 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions.
38// 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example.
39// 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
40// 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other backends.
41// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself.
42// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
43// 2016-05-07: DirectX10: Disabling depth-write.
44
45#include "imgui.h"
46#ifndef IMGUI_DISABLE
47#include "imgui_impl_dx10.h"
48
49// DirectX
50#include <stdio.h>
51#include <d3d10_1.h>
52#include <d3d10.h>
53#include <d3dcompiler.h>
54#ifdef _MSC_VER
55#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
56#endif
57
58// Clang/GCC warnings with -Weverything
59#if defined(__clang__)
60#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
61#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
62#endif
63
64// DirectX10 data
65struct ImGui_ImplDX10_Texture
66{
67 ID3D10Texture2D* pTexture;
68 ID3D10ShaderResourceView* pTextureView;
69};
70
71struct ImGui_ImplDX10_Data
72{
73 ID3D10Device* pd3dDevice;
74 IDXGIFactory* pFactory;
75 ID3D10Buffer* pVB;
76 ID3D10Buffer* pIB;
77 ID3D10VertexShader* pVertexShader;
78 ID3D10InputLayout* pInputLayout;
79 ID3D10Buffer* pVertexConstantBuffer;
80 ID3D10PixelShader* pPixelShader;
81 ID3D10SamplerState* pTexSamplerLinear;
82 ID3D10SamplerState* pTexSamplerNearest;
83 ID3D10RasterizerState* pRasterizerState;
84 ID3D10BlendState* pBlendState;
85 ID3D10DepthStencilState* pDepthStencilState;
86 int VertexBufferSize;
87 int IndexBufferSize;
88
89 ImGui_ImplDX10_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
90};
91
92struct VERTEX_CONSTANT_BUFFER_DX10
93{
94 float mvp[4][4];
95};
96
97// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
98// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
99static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData()
100{
101 return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
102}
103
104// Forward Declarations
105static void ImGui_ImplDX10_InitMultiViewportSupport();
106static void ImGui_ImplDX10_ShutdownMultiViewportSupport();
107
108// Functions
109static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device)
110{
111 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
112
113 // Setup viewport
114 D3D10_VIEWPORT vp = {};
115 vp.Width = (UINT)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
116 vp.Height = (UINT)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
117 vp.MinDepth = 0.0f;
118 vp.MaxDepth = 1.0f;
119 vp.TopLeftX = vp.TopLeftY = 0;
120 device->RSSetViewports(1, &vp);
121
122 // Setup orthographic projection matrix into our constant buffer
123 // 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.
124 void* mapped_resource;
125 if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK)
126 {
127 VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource;
128 float L = draw_data->DisplayPos.x;
129 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
130 float T = draw_data->DisplayPos.y;
131 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
132 float mvp[4][4] =
133 {
134 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
135 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
136 { 0.0f, 0.0f, 0.5f, 0.0f },
137 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
138 };
139 memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
140 bd->pVertexConstantBuffer->Unmap();
141 }
142
143 // Setup shader and vertex buffers
144 unsigned int stride = sizeof(ImDrawVert);
145 unsigned int offset = 0;
146 device->IASetInputLayout(bd->pInputLayout);
147 device->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
148 device->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
149 device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
150 device->VSSetShader(bd->pVertexShader);
151 device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
152 device->PSSetShader(bd->pPixelShader);
153 device->PSSetSamplers(0, 1, &bd->pTexSamplerLinear);
154 device->GSSetShader(nullptr);
155
156 // Setup render state
157 const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
158 device->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
159 device->OMSetDepthStencilState(bd->pDepthStencilState, 0);
160 device->RSSetState(bd->pRasterizerState);
161}
162
163// Draw callbacks
164static void ImGui_ImplDX10_DrawCallback_ResetRenderState(const ImDrawList*, const ImDrawCmd*) {} // Intentionally empty. Used as an identifier for rendering loop to call its code. Simpler to implement this way.
165static void ImGui_ImplDX10_DrawCallback_SetSamplerLinear(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); bd->pd3dDevice->PSSetSamplers(0, 1, &bd->pTexSamplerLinear); }
166static void ImGui_ImplDX10_DrawCallback_SetSamplerNearest(const ImDrawList*, const ImDrawCmd*) { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); bd->pd3dDevice->PSSetSamplers(0, 1, &bd->pTexSamplerNearest); }
167
168// Render function
169void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
170{
171 // Avoid rendering when minimized
172 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
173 return;
174
175 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
176 ID3D10Device* device = bd->pd3dDevice;
177
178 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
179 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
180 if (draw_data->Textures != nullptr)
181 for (ImTextureData* tex : *draw_data->Textures)
182 if (tex->Status != ImTextureStatus_OK)
183 ImGui_ImplDX10_UpdateTexture(tex);
184
185 // Create and grow vertex/index buffers if needed
186 if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
187 {
188 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
189 bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
190 D3D10_BUFFER_DESC desc = {};
191 desc.Usage = D3D10_USAGE_DYNAMIC;
192 desc.ByteWidth = (UINT)bd->VertexBufferSize * sizeof(ImDrawVert);
193 desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
194 desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
195 desc.MiscFlags = 0;
196 if (device->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
197 return;
198 }
199
200 if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
201 {
202 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
203 bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
204 D3D10_BUFFER_DESC desc = {};
205 desc.Usage = D3D10_USAGE_DYNAMIC;
206 desc.ByteWidth = (UINT)bd->IndexBufferSize * sizeof(ImDrawIdx);
207 desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
208 desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
209 if (device->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
210 return;
211 }
212
213 // Copy and convert all vertices into a single contiguous buffer
214 ImDrawVert* vtx_dst = nullptr;
215 ImDrawIdx* idx_dst = nullptr;
216 bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
217 bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
218 for (const ImDrawList* draw_list : draw_data->CmdLists)
219 {
220 memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
221 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
222 vtx_dst += draw_list->VtxBuffer.Size;
223 idx_dst += draw_list->IdxBuffer.Size;
224 }
225 bd->pVB->Unmap();
226 bd->pIB->Unmap();
227
228 // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
229 struct BACKUP_DX10_STATE
230 {
231 UINT ScissorRectsCount, ViewportsCount;
232 D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
233 D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
234 ID3D10RasterizerState* RS;
235 ID3D10BlendState* BlendState;
236 FLOAT BlendFactor[4];
237 UINT SampleMask;
238 UINT StencilRef;
239 ID3D10DepthStencilState* DepthStencilState;
240 ID3D10ShaderResourceView* PSShaderResource;
241 ID3D10SamplerState* PSSampler;
242 ID3D10PixelShader* PS;
243 ID3D10VertexShader* VS;
244 ID3D10GeometryShader* GS;
245 D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
246 ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
247 UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
248 DXGI_FORMAT IndexBufferFormat;
249 ID3D10InputLayout* InputLayout;
250 };
251 BACKUP_DX10_STATE old = {};
252 old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
253 device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
254 device->RSGetViewports(&old.ViewportsCount, old.Viewports);
255 device->RSGetState(&old.RS);
256 device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
257 device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
258 device->PSGetShaderResources(0, 1, &old.PSShaderResource);
259 device->PSGetSamplers(0, 1, &old.PSSampler);
260 device->PSGetShader(&old.PS);
261 device->VSGetShader(&old.VS);
262 device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
263 device->GSGetShader(&old.GS);
264 device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
265 device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
266 device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
267 device->IAGetInputLayout(&old.InputLayout);
268
269 // Setup desired DX state
270 ImGui_ImplDX10_SetupRenderState(draw_data, device);
271 // Setup render state structure (for callbacks and custom texture bindings)
272 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
273 ImGui_ImplDX10_RenderState render_state;
274 render_state.Device = bd->pd3dDevice;
275 render_state.VertexConstantBuffer = bd->pVertexConstantBuffer;
276 platform_io.Renderer_RenderState = &render_state;
277
278 // Render command lists
279 // (Because we merged all buffers into a single one, we maintain our own offset into them)
280 int global_vtx_offset = 0;
281 int global_idx_offset = 0;
282 ImVec2 clip_off = draw_data->DisplayPos;
283 ImVec2 clip_scale = draw_data->FramebufferScale;
284 for (const ImDrawList* draw_list : draw_data->CmdLists)
285 {
286 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
287 {
288 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
289 if (pcmd->UserCallback != nullptr)
290 {
291 // User callback, registered via ImDrawList::AddCallback()
292 if (pcmd->UserCallback == ImGui_ImplDX10_DrawCallback_ResetRenderState)
293 ImGui_ImplDX10_SetupRenderState(draw_data, device);
294 else
295 pcmd->UserCallback(draw_list, pcmd);
296 }
297 else
298 {
299 // Project scissor/clipping rectangles into framebuffer space
300 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
301 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
302 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
303 continue;
304
305 // Apply scissor/clipping rectangle
306 const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
307 device->RSSetScissorRects(1, &r);
308
309 // Bind texture, Draw
310 ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID();
311 device->PSSetShaderResources(0, 1, &texture_srv);
312 device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
313 }
314 }
315 global_idx_offset += draw_list->IdxBuffer.Size;
316 global_vtx_offset += draw_list->VtxBuffer.Size;
317 }
318 platform_io.Renderer_RenderState = nullptr;
319
320 // Restore modified DX state
321 device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
322 device->RSSetViewports(old.ViewportsCount, old.Viewports);
323 device->RSSetState(old.RS); if (old.RS) old.RS->Release();
324 device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
325 device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
326 device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
327 device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
328 device->PSSetShader(old.PS); if (old.PS) old.PS->Release();
329 device->VSSetShader(old.VS); if (old.VS) old.VS->Release();
330 device->GSSetShader(old.GS); if (old.GS) old.GS->Release();
331 device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
332 device->IASetPrimitiveTopology(old.PrimitiveTopology);
333 device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
334 device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
335 device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
336}
337
338static void ImGui_ImplDX10_DestroyTexture(ImTextureData* tex)
339{
340 if (ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData)
341 {
342 IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID);
343 backend_tex->pTextureView->Release();
344 backend_tex->pTexture->Release();
345 IM_DELETE(backend_tex);
346
347 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
348 tex->SetTexID(ImTextureID_Invalid);
349 tex->BackendUserData = nullptr;
350 }
351 tex->SetStatus(ImTextureStatus_Destroyed);
352}
353
354void ImGui_ImplDX10_UpdateTexture(ImTextureData* tex)
355{
356 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
357 if (tex->Status == ImTextureStatus_WantCreate)
358 {
359 // Create and upload new texture to graphics system
360 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
361 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
362 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
363 unsigned int* pixels = (unsigned int*)tex->GetPixels();
364 ImGui_ImplDX10_Texture* backend_tex = IM_NEW(ImGui_ImplDX10_Texture)();
365
366 // Create texture
367 D3D10_TEXTURE2D_DESC desc;
368 ZeroMemory(&desc, sizeof(desc));
369 desc.Width = (UINT)tex->Width;
370 desc.Height = (UINT)tex->Height;
371 desc.MipLevels = 1;
372 desc.ArraySize = 1;
373 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
374 desc.SampleDesc.Count = 1;
375 desc.Usage = D3D10_USAGE_DEFAULT;
376 desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
377 desc.CPUAccessFlags = 0;
378
379 D3D10_SUBRESOURCE_DATA subResource;
380 subResource.pSysMem = pixels;
381 subResource.SysMemPitch = desc.Width * 4;
382 subResource.SysMemSlicePitch = 0;
383 bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &backend_tex->pTexture);
384 IM_ASSERT(backend_tex->pTexture != nullptr && "Backend failed to create texture!");
385
386 // Create texture view
387 D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
388 ZeroMemory(&srv_desc, sizeof(srv_desc));
389 srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
390 srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
391 srv_desc.Texture2D.MipLevels = desc.MipLevels;
392 srv_desc.Texture2D.MostDetailedMip = 0;
393 bd->pd3dDevice->CreateShaderResourceView(backend_tex->pTexture, &srv_desc, &backend_tex->pTextureView);
394 IM_ASSERT(backend_tex->pTextureView != nullptr && "Backend failed to create texture!");
395
396 // Store identifiers
397 tex->SetTexID((ImTextureID)(intptr_t)backend_tex->pTextureView);
398 tex->SetStatus(ImTextureStatus_OK);
399 tex->BackendUserData = backend_tex;
400 }
401 else if (tex->Status == ImTextureStatus_WantUpdates)
402 {
403 // Update selected blocks. We only ever write to textures regions which have never been used before!
404 // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
405 ImGui_ImplDX10_Texture* backend_tex = (ImGui_ImplDX10_Texture*)tex->BackendUserData;
406 IM_ASSERT(backend_tex->pTextureView == (ID3D10ShaderResourceView*)(intptr_t)tex->TexID);
407 for (ImTextureRect& r : tex->Updates)
408 {
409 D3D10_BOX box = { (UINT)r.x, (UINT)r.y, (UINT)0, (UINT)(r.x + r.w), (UINT)(r.y + r.h), (UINT)1 };
410 bd->pd3dDevice->UpdateSubresource(backend_tex->pTexture, 0, &box, tex->GetPixelsAt(r.x, r.y), (UINT)tex->GetPitch(), 0);
411 }
412 tex->SetStatus(ImTextureStatus_OK);
413 }
414 if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
415 ImGui_ImplDX10_DestroyTexture(tex);
416}
417
418bool ImGui_ImplDX10_CreateDeviceObjects()
419{
420 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
421 if (!bd->pd3dDevice)
422 return false;
423 ImGui_ImplDX10_InvalidateDeviceObjects();
424
425 // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
426 // If you would like to use this DX10 sample code but remove this dependency you can:
427 // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
428 // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
429 // See https://github.com/ocornut/imgui/pull/638 for sources and details.
430
431 // Create the vertex shader
432 {
433 static const char* vertexShader =
434 "cbuffer vertexBuffer : register(b0) \
435 {\
436 float4x4 ProjectionMatrix; \
437 };\
438 struct VS_INPUT\
439 {\
440 float2 pos : POSITION;\
441 float4 col : COLOR0;\
442 float2 uv : TEXCOORD0;\
443 };\
444 \
445 struct PS_INPUT\
446 {\
447 float4 pos : SV_POSITION;\
448 float4 col : COLOR0;\
449 float2 uv : TEXCOORD0;\
450 };\
451 \
452 PS_INPUT main(VS_INPUT input)\
453 {\
454 PS_INPUT output;\
455 output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
456 output.col = input.col;\
457 output.uv = input.uv;\
458 return output;\
459 }";
460
461 ID3DBlob* vertexShaderBlob;
462 if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
463 return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
464 if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK)
465 {
466 vertexShaderBlob->Release();
467 return false;
468 }
469
470 // Create the input layout
471 D3D10_INPUT_ELEMENT_DESC local_layout[] =
472 {
473 { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
474 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
475 { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
476 };
477 if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
478 {
479 vertexShaderBlob->Release();
480 return false;
481 }
482 vertexShaderBlob->Release();
483
484 // Create the constant buffer
485 {
486 D3D10_BUFFER_DESC desc = {};
487 desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10);
488 desc.Usage = D3D10_USAGE_DYNAMIC;
489 desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
490 desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
491 desc.MiscFlags = 0;
492 bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
493 }
494 }
495
496 // Create the pixel shader
497 {
498 static const char* pixelShader =
499 "struct PS_INPUT\
500 {\
501 float4 pos : SV_POSITION;\
502 float4 col : COLOR0;\
503 float2 uv : TEXCOORD0;\
504 };\
505 sampler sampler0;\
506 Texture2D texture0;\
507 \
508 float4 main(PS_INPUT input) : SV_Target\
509 {\
510 float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
511 return out_col; \
512 }";
513
514 ID3DBlob* pixelShaderBlob;
515 if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
516 return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
517 if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK)
518 {
519 pixelShaderBlob->Release();
520 return false;
521 }
522 pixelShaderBlob->Release();
523 }
524
525 // Create the blending setup
526 {
527 D3D10_BLEND_DESC desc;
528 ZeroMemory(&desc, sizeof(desc));
529 desc.AlphaToCoverageEnable = false;
530 desc.BlendEnable[0] = true;
531 desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
532 desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
533 desc.BlendOp = D3D10_BLEND_OP_ADD;
534 desc.SrcBlendAlpha = D3D10_BLEND_ONE;
535 desc.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
536 desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
537 desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
538 bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
539 }
540
541 // Create the rasterizer state
542 {
543 D3D10_RASTERIZER_DESC desc;
544 ZeroMemory(&desc, sizeof(desc));
545 desc.FillMode = D3D10_FILL_SOLID;
546 desc.CullMode = D3D10_CULL_NONE;
547 desc.ScissorEnable = true;
548 desc.DepthClipEnable = true;
549 bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
550 }
551
552 // Create depth-stencil State
553 {
554 D3D10_DEPTH_STENCIL_DESC desc;
555 ZeroMemory(&desc, sizeof(desc));
556 desc.DepthEnable = false;
557 desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
558 desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
559 desc.StencilEnable = false;
560 desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
561 desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
562 desc.BackFace = desc.FrontFace;
563 bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
564 }
565
566 // Create texture sampler
567 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
568 {
569 D3D10_SAMPLER_DESC desc;
570 ZeroMemory(&desc, sizeof(desc));
571 desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
572 desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
573 desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
574 desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
575 desc.MipLODBias = 0.f;
576 desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
577 desc.MinLOD = 0.f;
578 desc.MaxLOD = 0.f;
579 bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerLinear);
580 desc.Filter = D3D10_FILTER_MIN_MAG_MIP_POINT;
581 bd->pd3dDevice->CreateSamplerState(&desc, &bd->pTexSamplerNearest);
582 }
583
584 return true;
585}
586
587void ImGui_ImplDX10_InvalidateDeviceObjects()
588{
589 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
590 if (!bd->pd3dDevice)
591 return;
592
593 // Destroy all textures
594 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
595 if (tex->RefCount == 1)
596 ImGui_ImplDX10_DestroyTexture(tex);
597 if (bd->pTexSamplerLinear) { bd->pTexSamplerLinear->Release(); bd->pTexSamplerLinear = nullptr; }
598 if (bd->pTexSamplerNearest) { bd->pTexSamplerNearest->Release(); bd->pTexSamplerNearest = nullptr; }
599 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
600 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
601 if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
602 if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
603 if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
604 if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
605 if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
606 if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
607 if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
608}
609
610bool ImGui_ImplDX10_Init(ID3D10Device* device)
611{
612 ImGuiIO& io = ImGui::GetIO();
613 IMGUI_CHECKVERSION();
614 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
615
616 // Setup backend capabilities flags
617 ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)();
618 io.BackendRendererUserData = (void*)bd;
619 io.BackendRendererName = "imgui_impl_dx10";
620 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
621 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
622 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
623
624 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
625 platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
626 platform_io.DrawCallback_ResetRenderState = ImGui_ImplDX10_DrawCallback_ResetRenderState;
627 platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplDX10_DrawCallback_SetSamplerLinear;
628 platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplDX10_DrawCallback_SetSamplerNearest;
629
630 // Get factory from device
631 IDXGIDevice* pDXGIDevice = nullptr;
632 IDXGIAdapter* pDXGIAdapter = nullptr;
633 IDXGIFactory* pFactory = nullptr;
634 if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
635 if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
636 if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
637 {
638 bd->pd3dDevice = device;
639 bd->pFactory = pFactory;
640 }
641 if (pDXGIDevice) pDXGIDevice->Release();
642 if (pDXGIAdapter) pDXGIAdapter->Release();
643 bd->pd3dDevice->AddRef();
644
645 ImGui_ImplDX10_InitMultiViewportSupport();
646
647 return true;
648}
649
650void ImGui_ImplDX10_Shutdown()
651{
652 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
653 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
654 ImGuiIO& io = ImGui::GetIO();
655 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
656
657 ImGui_ImplDX10_ShutdownMultiViewportSupport();
658 ImGui_ImplDX10_InvalidateDeviceObjects();
659 if (bd->pFactory) { bd->pFactory->Release(); }
660 if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
661
662 io.BackendRendererName = nullptr;
663 io.BackendRendererUserData = nullptr;
664 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
665 platform_io.ClearRendererHandlers();
666 IM_DELETE(bd);
667}
668
669void ImGui_ImplDX10_NewFrame()
670{
671 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
672 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
673
674 if (!bd->pVertexShader)
675 if (!ImGui_ImplDX10_CreateDeviceObjects())
676 IM_ASSERT(0 && "ImGui_ImplDX10_CreateDeviceObjects() failed!");
677}
678
679//--------------------------------------------------------------------------------------------------------
680// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
681// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
682// 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..
683//--------------------------------------------------------------------------------------------------------
684
685// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
686struct ImGui_ImplDX10_ViewportData
687{
688 IDXGISwapChain* SwapChain;
689 ID3D10RenderTargetView* RTView;
690
691 ImGui_ImplDX10_ViewportData() { SwapChain = nullptr; RTView = nullptr; }
692 ~ImGui_ImplDX10_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); }
693};
694
695static void ImGui_ImplDX10_CreateWindow(ImGuiViewport* viewport)
696{
697 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
698 ImGui_ImplDX10_ViewportData* vd = IM_NEW(ImGui_ImplDX10_ViewportData)();
699 viewport->RendererUserData = vd;
700
701 // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL's WindowID).
702 // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
703 HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
704 IM_ASSERT(hwnd != 0);
705
706 // Create swap chain
707 DXGI_SWAP_CHAIN_DESC sd;
708 ZeroMemory(&sd, sizeof(sd));
709 sd.BufferDesc.Width = (UINT)viewport->Size.x;
710 sd.BufferDesc.Height = (UINT)viewport->Size.y;
711 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
712 sd.SampleDesc.Count = 1;
713 sd.SampleDesc.Quality = 0;
714 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
715 sd.BufferCount = 1;
716 sd.OutputWindow = hwnd;
717 sd.Windowed = TRUE;
718 sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
719 sd.Flags = 0;
720
721 IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr);
722 bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain);
723 bd->pFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); // Disable e.g. Alt+Enter
724
725 // Create the render target
726 if (vd->SwapChain)
727 {
728 ID3D10Texture2D* pBackBuffer;
729 vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
730 bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
731 pBackBuffer->Release();
732 }
733}
734
735static void ImGui_ImplDX10_DestroyWindow(ImGuiViewport* viewport)
736{
737 // The main viewport (owned by the application) will always have RendererUserData == 0 here since we didn't create the data for it.
738 if (ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData)
739 {
740 if (vd->SwapChain)
741 vd->SwapChain->Release();
742 vd->SwapChain = nullptr;
743 if (vd->RTView)
744 vd->RTView->Release();
745 vd->RTView = nullptr;
746 IM_DELETE(vd);
747 }
748 viewport->RendererUserData = nullptr;
749}
750
751static void ImGui_ImplDX10_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
752{
753 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
754 ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
755 if (vd->RTView)
756 {
757 vd->RTView->Release();
758 vd->RTView = nullptr;
759 }
760 if (vd->SwapChain)
761 {
762 ID3D10Texture2D* pBackBuffer = nullptr;
763 vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
764 vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
765 if (pBackBuffer == nullptr) { fprintf(stderr, "ImGui_ImplDX10_SetWindowSize() failed creating buffers.\n"); return; }
766 bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
767 pBackBuffer->Release();
768 }
769}
770
771static void ImGui_ImplDX10_RenderViewport(ImGuiViewport* viewport, void*)
772{
773 ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
774 ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
775 ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
776 bd->pd3dDevice->OMSetRenderTargets(1, &vd->RTView, nullptr);
777 if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
778 bd->pd3dDevice->ClearRenderTargetView(vd->RTView, (float*)&clear_color);
779 ImGui_ImplDX10_RenderDrawData(viewport->DrawData);
780}
781
782static void ImGui_ImplDX10_SwapBuffers(ImGuiViewport* viewport, void*)
783{
784 ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
785 if (vd->SwapChain)
786 vd->SwapChain->Present(0, 0); // Present without vsync
787}
788
789void ImGui_ImplDX10_InitMultiViewportSupport()
790{
791 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
792 platform_io.Renderer_CreateWindow = ImGui_ImplDX10_CreateWindow;
793 platform_io.Renderer_DestroyWindow = ImGui_ImplDX10_DestroyWindow;
794 platform_io.Renderer_SetWindowSize = ImGui_ImplDX10_SetWindowSize;
795 platform_io.Renderer_RenderWindow = ImGui_ImplDX10_RenderViewport;
796 platform_io.Renderer_SwapBuffers = ImGui_ImplDX10_SwapBuffers;
797}
798
799void ImGui_ImplDX10_ShutdownMultiViewportSupport()
800{
801 ImGui::DestroyPlatformWindows();
802}
803
804//-----------------------------------------------------------------------------
805
806#endif // #ifndef IMGUI_DISABLE