imgui_impl_dx10.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. // dear imgui: Renderer Backend for DirectX10
  2. // This needs to be used along with a Platform Backend (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  7. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  8. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  9. // Learn about Dear ImGui:
  10. // - FAQ https://dearimgui.com/faq
  11. // - Getting Started https://dearimgui.com/getting-started
  12. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  13. // - Introduction, links and more at the top of imgui.cpp
  14. // CHANGELOG
  15. // (minor and older changes stripped away, please see git history for details)
  16. // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  17. // 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.
  18. // 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  19. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  20. // 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).
  21. // 2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  22. // 2021-02-18: DirectX10: Change blending equation to preserve alpha in output buffer.
  23. // 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData().
  24. // 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  25. // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  26. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  27. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  28. // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions.
  29. // 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example.
  30. // 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
  31. // 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.
  32. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself.
  33. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  34. // 2016-05-07: DirectX10: Disabling depth-write.
  35. #include "imgui.h"
  36. #ifndef IMGUI_DISABLE
  37. #include "imgui_impl_dx10.h"
  38. // DirectX
  39. #include <stdio.h>
  40. #include <d3d10_1.h>
  41. #include <d3d10.h>
  42. #include <d3dcompiler.h>
  43. #ifdef _MSC_VER
  44. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  45. #endif
  46. // DirectX data
  47. struct ImGui_ImplDX10_Data
  48. {
  49. ID3D10Device* pd3dDevice;
  50. IDXGIFactory* pFactory;
  51. ID3D10Buffer* pVB;
  52. ID3D10Buffer* pIB;
  53. ID3D10VertexShader* pVertexShader;
  54. ID3D10InputLayout* pInputLayout;
  55. ID3D10Buffer* pVertexConstantBuffer;
  56. ID3D10PixelShader* pPixelShader;
  57. ID3D10SamplerState* pFontSampler;
  58. ID3D10ShaderResourceView* pFontTextureView;
  59. ID3D10RasterizerState* pRasterizerState;
  60. ID3D10BlendState* pBlendState;
  61. ID3D10DepthStencilState* pDepthStencilState;
  62. int VertexBufferSize;
  63. int IndexBufferSize;
  64. ImGui_ImplDX10_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
  65. };
  66. struct VERTEX_CONSTANT_BUFFER_DX10
  67. {
  68. float mvp[4][4];
  69. };
  70. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  71. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  72. static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData()
  73. {
  74. return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  75. }
  76. // Forward Declarations
  77. static void ImGui_ImplDX10_InitMultiViewportSupport();
  78. static void ImGui_ImplDX10_ShutdownMultiViewportSupport();
  79. // Functions
  80. static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device)
  81. {
  82. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  83. // Setup viewport
  84. D3D10_VIEWPORT vp;
  85. memset(&vp, 0, sizeof(D3D10_VIEWPORT));
  86. vp.Width = (UINT)draw_data->DisplaySize.x;
  87. vp.Height = (UINT)draw_data->DisplaySize.y;
  88. vp.MinDepth = 0.0f;
  89. vp.MaxDepth = 1.0f;
  90. vp.TopLeftX = vp.TopLeftY = 0;
  91. device->RSSetViewports(1, &vp);
  92. // Setup orthographic projection matrix into our constant buffer
  93. // 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.
  94. void* mapped_resource;
  95. if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK)
  96. {
  97. VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource;
  98. float L = draw_data->DisplayPos.x;
  99. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  100. float T = draw_data->DisplayPos.y;
  101. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  102. float mvp[4][4] =
  103. {
  104. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  105. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  106. { 0.0f, 0.0f, 0.5f, 0.0f },
  107. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  108. };
  109. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  110. bd->pVertexConstantBuffer->Unmap();
  111. }
  112. // Setup shader and vertex buffers
  113. unsigned int stride = sizeof(ImDrawVert);
  114. unsigned int offset = 0;
  115. device->IASetInputLayout(bd->pInputLayout);
  116. device->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
  117. device->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  118. device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  119. device->VSSetShader(bd->pVertexShader);
  120. device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
  121. device->PSSetShader(bd->pPixelShader);
  122. device->PSSetSamplers(0, 1, &bd->pFontSampler);
  123. device->GSSetShader(nullptr);
  124. // Setup render state
  125. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  126. device->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
  127. device->OMSetDepthStencilState(bd->pDepthStencilState, 0);
  128. device->RSSetState(bd->pRasterizerState);
  129. }
  130. // Render function
  131. void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
  132. {
  133. // Avoid rendering when minimized
  134. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  135. return;
  136. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  137. ID3D10Device* device = bd->pd3dDevice;
  138. // Create and grow vertex/index buffers if needed
  139. if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
  140. {
  141. if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
  142. bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  143. D3D10_BUFFER_DESC desc;
  144. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  145. desc.Usage = D3D10_USAGE_DYNAMIC;
  146. desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
  147. desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  148. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  149. desc.MiscFlags = 0;
  150. if (device->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
  151. return;
  152. }
  153. if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
  154. {
  155. if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
  156. bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  157. D3D10_BUFFER_DESC desc;
  158. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  159. desc.Usage = D3D10_USAGE_DYNAMIC;
  160. desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
  161. desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
  162. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  163. if (device->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
  164. return;
  165. }
  166. // Copy and convert all vertices into a single contiguous buffer
  167. ImDrawVert* vtx_dst = nullptr;
  168. ImDrawIdx* idx_dst = nullptr;
  169. bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
  170. bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
  171. for (int n = 0; n < draw_data->CmdListsCount; n++)
  172. {
  173. const ImDrawList* draw_list = draw_data->CmdLists[n];
  174. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  175. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  176. vtx_dst += draw_list->VtxBuffer.Size;
  177. idx_dst += draw_list->IdxBuffer.Size;
  178. }
  179. bd->pVB->Unmap();
  180. bd->pIB->Unmap();
  181. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  182. struct BACKUP_DX10_STATE
  183. {
  184. UINT ScissorRectsCount, ViewportsCount;
  185. D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  186. D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  187. ID3D10RasterizerState* RS;
  188. ID3D10BlendState* BlendState;
  189. FLOAT BlendFactor[4];
  190. UINT SampleMask;
  191. UINT StencilRef;
  192. ID3D10DepthStencilState* DepthStencilState;
  193. ID3D10ShaderResourceView* PSShaderResource;
  194. ID3D10SamplerState* PSSampler;
  195. ID3D10PixelShader* PS;
  196. ID3D10VertexShader* VS;
  197. ID3D10GeometryShader* GS;
  198. D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  199. ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  200. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  201. DXGI_FORMAT IndexBufferFormat;
  202. ID3D10InputLayout* InputLayout;
  203. };
  204. BACKUP_DX10_STATE old = {};
  205. old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  206. device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  207. device->RSGetViewports(&old.ViewportsCount, old.Viewports);
  208. device->RSGetState(&old.RS);
  209. device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  210. device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  211. device->PSGetShaderResources(0, 1, &old.PSShaderResource);
  212. device->PSGetSamplers(0, 1, &old.PSSampler);
  213. device->PSGetShader(&old.PS);
  214. device->VSGetShader(&old.VS);
  215. device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  216. device->GSGetShader(&old.GS);
  217. device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  218. device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  219. device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  220. device->IAGetInputLayout(&old.InputLayout);
  221. // Setup desired DX state
  222. ImGui_ImplDX10_SetupRenderState(draw_data, device);
  223. // Setup render state structure (for callbacks and custom texture bindings)
  224. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  225. ImGui_ImplDX10_RenderState render_state;
  226. render_state.Device = bd->pd3dDevice;
  227. render_state.SamplerDefault = bd->pFontSampler;
  228. render_state.VertexConstantBuffer = bd->pVertexConstantBuffer;
  229. platform_io.Renderer_RenderState = &render_state;
  230. // Render command lists
  231. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  232. int global_vtx_offset = 0;
  233. int global_idx_offset = 0;
  234. ImVec2 clip_off = draw_data->DisplayPos;
  235. for (int n = 0; n < draw_data->CmdListsCount; n++)
  236. {
  237. const ImDrawList* draw_list = draw_data->CmdLists[n];
  238. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  239. {
  240. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  241. if (pcmd->UserCallback != nullptr)
  242. {
  243. // User callback, registered via ImDrawList::AddCallback()
  244. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  245. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  246. ImGui_ImplDX10_SetupRenderState(draw_data, device);
  247. else
  248. pcmd->UserCallback(draw_list, pcmd);
  249. }
  250. else
  251. {
  252. // Project scissor/clipping rectangles into framebuffer space
  253. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  254. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  255. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  256. continue;
  257. // Apply scissor/clipping rectangle
  258. const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  259. device->RSSetScissorRects(1, &r);
  260. // Bind texture, Draw
  261. ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID();
  262. device->PSSetShaderResources(0, 1, &texture_srv);
  263. device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
  264. }
  265. }
  266. global_idx_offset += draw_list->IdxBuffer.Size;
  267. global_vtx_offset += draw_list->VtxBuffer.Size;
  268. }
  269. platform_io.Renderer_RenderState = nullptr;
  270. // Restore modified DX state
  271. device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  272. device->RSSetViewports(old.ViewportsCount, old.Viewports);
  273. device->RSSetState(old.RS); if (old.RS) old.RS->Release();
  274. device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  275. device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  276. device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  277. device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  278. device->PSSetShader(old.PS); if (old.PS) old.PS->Release();
  279. device->VSSetShader(old.VS); if (old.VS) old.VS->Release();
  280. device->GSSetShader(old.GS); if (old.GS) old.GS->Release();
  281. device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  282. device->IASetPrimitiveTopology(old.PrimitiveTopology);
  283. device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  284. device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  285. device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  286. }
  287. static void ImGui_ImplDX10_CreateFontsTexture()
  288. {
  289. // Build texture atlas
  290. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  291. ImGuiIO& io = ImGui::GetIO();
  292. unsigned char* pixels;
  293. int width, height;
  294. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  295. // Upload texture to graphics system
  296. {
  297. D3D10_TEXTURE2D_DESC desc;
  298. ZeroMemory(&desc, sizeof(desc));
  299. desc.Width = width;
  300. desc.Height = height;
  301. desc.MipLevels = 1;
  302. desc.ArraySize = 1;
  303. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  304. desc.SampleDesc.Count = 1;
  305. desc.Usage = D3D10_USAGE_DEFAULT;
  306. desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
  307. desc.CPUAccessFlags = 0;
  308. ID3D10Texture2D* pTexture = nullptr;
  309. D3D10_SUBRESOURCE_DATA subResource;
  310. subResource.pSysMem = pixels;
  311. subResource.SysMemPitch = desc.Width * 4;
  312. subResource.SysMemSlicePitch = 0;
  313. bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  314. IM_ASSERT(pTexture != nullptr);
  315. // Create texture view
  316. D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
  317. ZeroMemory(&srv_desc, sizeof(srv_desc));
  318. srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  319. srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
  320. srv_desc.Texture2D.MipLevels = desc.MipLevels;
  321. srv_desc.Texture2D.MostDetailedMip = 0;
  322. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &bd->pFontTextureView);
  323. pTexture->Release();
  324. }
  325. // Store our identifier
  326. io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
  327. }
  328. static void ImGui_ImplDX10_DestroyFontsTexture()
  329. {
  330. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  331. if (bd->pFontTextureView)
  332. {
  333. bd->pFontTextureView->Release();
  334. bd->pFontTextureView = nullptr;
  335. ImGui::GetIO().Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
  336. }
  337. }
  338. bool ImGui_ImplDX10_CreateDeviceObjects()
  339. {
  340. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  341. if (!bd->pd3dDevice)
  342. return false;
  343. if (bd->pFontSampler)
  344. ImGui_ImplDX10_InvalidateDeviceObjects();
  345. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  346. // If you would like to use this DX10 sample code but remove this dependency you can:
  347. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  348. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  349. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  350. // Create the vertex shader
  351. {
  352. static const char* vertexShader =
  353. "cbuffer vertexBuffer : register(b0) \
  354. {\
  355. float4x4 ProjectionMatrix; \
  356. };\
  357. struct VS_INPUT\
  358. {\
  359. float2 pos : POSITION;\
  360. float4 col : COLOR0;\
  361. float2 uv : TEXCOORD0;\
  362. };\
  363. \
  364. struct PS_INPUT\
  365. {\
  366. float4 pos : SV_POSITION;\
  367. float4 col : COLOR0;\
  368. float2 uv : TEXCOORD0;\
  369. };\
  370. \
  371. PS_INPUT main(VS_INPUT input)\
  372. {\
  373. PS_INPUT output;\
  374. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  375. output.col = input.col;\
  376. output.uv = input.uv;\
  377. return output;\
  378. }";
  379. ID3DBlob* vertexShaderBlob;
  380. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
  381. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  382. if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK)
  383. {
  384. vertexShaderBlob->Release();
  385. return false;
  386. }
  387. // Create the input layout
  388. D3D10_INPUT_ELEMENT_DESC local_layout[] =
  389. {
  390. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  391. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  392. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  393. };
  394. if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
  395. {
  396. vertexShaderBlob->Release();
  397. return false;
  398. }
  399. vertexShaderBlob->Release();
  400. // Create the constant buffer
  401. {
  402. D3D10_BUFFER_DESC desc;
  403. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10);
  404. desc.Usage = D3D10_USAGE_DYNAMIC;
  405. desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
  406. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  407. desc.MiscFlags = 0;
  408. bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
  409. }
  410. }
  411. // Create the pixel shader
  412. {
  413. static const char* pixelShader =
  414. "struct PS_INPUT\
  415. {\
  416. float4 pos : SV_POSITION;\
  417. float4 col : COLOR0;\
  418. float2 uv : TEXCOORD0;\
  419. };\
  420. sampler sampler0;\
  421. Texture2D texture0;\
  422. \
  423. float4 main(PS_INPUT input) : SV_Target\
  424. {\
  425. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  426. return out_col; \
  427. }";
  428. ID3DBlob* pixelShaderBlob;
  429. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
  430. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  431. if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK)
  432. {
  433. pixelShaderBlob->Release();
  434. return false;
  435. }
  436. pixelShaderBlob->Release();
  437. }
  438. // Create the blending setup
  439. {
  440. D3D10_BLEND_DESC desc;
  441. ZeroMemory(&desc, sizeof(desc));
  442. desc.AlphaToCoverageEnable = false;
  443. desc.BlendEnable[0] = true;
  444. desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
  445. desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
  446. desc.BlendOp = D3D10_BLEND_OP_ADD;
  447. desc.SrcBlendAlpha = D3D10_BLEND_ONE;
  448. desc.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
  449. desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
  450. desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
  451. bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
  452. }
  453. // Create the rasterizer state
  454. {
  455. D3D10_RASTERIZER_DESC desc;
  456. ZeroMemory(&desc, sizeof(desc));
  457. desc.FillMode = D3D10_FILL_SOLID;
  458. desc.CullMode = D3D10_CULL_NONE;
  459. desc.ScissorEnable = true;
  460. desc.DepthClipEnable = true;
  461. bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
  462. }
  463. // Create depth-stencil State
  464. {
  465. D3D10_DEPTH_STENCIL_DESC desc;
  466. ZeroMemory(&desc, sizeof(desc));
  467. desc.DepthEnable = false;
  468. desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
  469. desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
  470. desc.StencilEnable = false;
  471. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
  472. desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
  473. desc.BackFace = desc.FrontFace;
  474. bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
  475. }
  476. // Create texture sampler
  477. // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
  478. {
  479. D3D10_SAMPLER_DESC desc;
  480. ZeroMemory(&desc, sizeof(desc));
  481. desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
  482. desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
  483. desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
  484. desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
  485. desc.MipLODBias = 0.f;
  486. desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
  487. desc.MinLOD = 0.f;
  488. desc.MaxLOD = 0.f;
  489. bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
  490. }
  491. ImGui_ImplDX10_CreateFontsTexture();
  492. return true;
  493. }
  494. void ImGui_ImplDX10_InvalidateDeviceObjects()
  495. {
  496. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  497. if (!bd->pd3dDevice)
  498. return;
  499. ImGui_ImplDX10_DestroyFontsTexture();
  500. if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
  501. if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
  502. if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
  503. if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
  504. if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
  505. if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
  506. if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
  507. if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
  508. if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
  509. if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
  510. }
  511. bool ImGui_ImplDX10_Init(ID3D10Device* device)
  512. {
  513. ImGuiIO& io = ImGui::GetIO();
  514. IMGUI_CHECKVERSION();
  515. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  516. // Setup backend capabilities flags
  517. ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)();
  518. io.BackendRendererUserData = (void*)bd;
  519. io.BackendRendererName = "imgui_impl_dx10";
  520. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  521. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  522. // Get factory from device
  523. IDXGIDevice* pDXGIDevice = nullptr;
  524. IDXGIAdapter* pDXGIAdapter = nullptr;
  525. IDXGIFactory* pFactory = nullptr;
  526. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
  527. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
  528. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
  529. {
  530. bd->pd3dDevice = device;
  531. bd->pFactory = pFactory;
  532. }
  533. if (pDXGIDevice) pDXGIDevice->Release();
  534. if (pDXGIAdapter) pDXGIAdapter->Release();
  535. bd->pd3dDevice->AddRef();
  536. ImGui_ImplDX10_InitMultiViewportSupport();
  537. return true;
  538. }
  539. void ImGui_ImplDX10_Shutdown()
  540. {
  541. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  542. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  543. ImGuiIO& io = ImGui::GetIO();
  544. ImGui_ImplDX10_ShutdownMultiViewportSupport();
  545. ImGui_ImplDX10_InvalidateDeviceObjects();
  546. if (bd->pFactory) { bd->pFactory->Release(); }
  547. if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
  548. io.BackendRendererName = nullptr;
  549. io.BackendRendererUserData = nullptr;
  550. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
  551. IM_DELETE(bd);
  552. }
  553. void ImGui_ImplDX10_NewFrame()
  554. {
  555. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  556. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
  557. if (!bd->pVertexShader)
  558. ImGui_ImplDX10_CreateDeviceObjects();
  559. }
  560. //--------------------------------------------------------------------------------------------------------
  561. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  562. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  563. // 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..
  564. //--------------------------------------------------------------------------------------------------------
  565. // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
  566. struct ImGui_ImplDX10_ViewportData
  567. {
  568. IDXGISwapChain* SwapChain;
  569. ID3D10RenderTargetView* RTView;
  570. ImGui_ImplDX10_ViewportData() { SwapChain = nullptr; RTView = nullptr; }
  571. ~ImGui_ImplDX10_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); }
  572. };
  573. static void ImGui_ImplDX10_CreateWindow(ImGuiViewport* viewport)
  574. {
  575. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  576. ImGui_ImplDX10_ViewportData* vd = IM_NEW(ImGui_ImplDX10_ViewportData)();
  577. viewport->RendererUserData = vd;
  578. // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
  579. // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
  580. HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
  581. IM_ASSERT(hwnd != 0);
  582. // Create swap chain
  583. DXGI_SWAP_CHAIN_DESC sd;
  584. ZeroMemory(&sd, sizeof(sd));
  585. sd.BufferDesc.Width = (UINT)viewport->Size.x;
  586. sd.BufferDesc.Height = (UINT)viewport->Size.y;
  587. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  588. sd.SampleDesc.Count = 1;
  589. sd.SampleDesc.Quality = 0;
  590. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  591. sd.BufferCount = 1;
  592. sd.OutputWindow = hwnd;
  593. sd.Windowed = TRUE;
  594. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  595. sd.Flags = 0;
  596. IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr);
  597. bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain);
  598. // Create the render target
  599. if (vd->SwapChain)
  600. {
  601. ID3D10Texture2D* pBackBuffer;
  602. vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  603. bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
  604. pBackBuffer->Release();
  605. }
  606. }
  607. static void ImGui_ImplDX10_DestroyWindow(ImGuiViewport* viewport)
  608. {
  609. // The main viewport (owned by the application) will always have RendererUserData == 0 here since we didn't create the data for it.
  610. if (ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData)
  611. {
  612. if (vd->SwapChain)
  613. vd->SwapChain->Release();
  614. vd->SwapChain = nullptr;
  615. if (vd->RTView)
  616. vd->RTView->Release();
  617. vd->RTView = nullptr;
  618. IM_DELETE(vd);
  619. }
  620. viewport->RendererUserData = nullptr;
  621. }
  622. static void ImGui_ImplDX10_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  623. {
  624. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  625. ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
  626. if (vd->RTView)
  627. {
  628. vd->RTView->Release();
  629. vd->RTView = nullptr;
  630. }
  631. if (vd->SwapChain)
  632. {
  633. ID3D10Texture2D* pBackBuffer = nullptr;
  634. vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
  635. vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  636. if (pBackBuffer == nullptr) { fprintf(stderr, "ImGui_ImplDX10_SetWindowSize() failed creating buffers.\n"); return; }
  637. bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
  638. pBackBuffer->Release();
  639. }
  640. }
  641. static void ImGui_ImplDX10_RenderViewport(ImGuiViewport* viewport, void*)
  642. {
  643. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  644. ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
  645. ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  646. bd->pd3dDevice->OMSetRenderTargets(1, &vd->RTView, nullptr);
  647. if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
  648. bd->pd3dDevice->ClearRenderTargetView(vd->RTView, (float*)&clear_color);
  649. ImGui_ImplDX10_RenderDrawData(viewport->DrawData);
  650. }
  651. static void ImGui_ImplDX10_SwapBuffers(ImGuiViewport* viewport, void*)
  652. {
  653. ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
  654. vd->SwapChain->Present(0, 0); // Present without vsync
  655. }
  656. void ImGui_ImplDX10_InitMultiViewportSupport()
  657. {
  658. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  659. platform_io.Renderer_CreateWindow = ImGui_ImplDX10_CreateWindow;
  660. platform_io.Renderer_DestroyWindow = ImGui_ImplDX10_DestroyWindow;
  661. platform_io.Renderer_SetWindowSize = ImGui_ImplDX10_SetWindowSize;
  662. platform_io.Renderer_RenderWindow = ImGui_ImplDX10_RenderViewport;
  663. platform_io.Renderer_SwapBuffers = ImGui_ImplDX10_SwapBuffers;
  664. }
  665. void ImGui_ImplDX10_ShutdownMultiViewportSupport()
  666. {
  667. ImGui::DestroyPlatformWindows();
  668. }
  669. //-----------------------------------------------------------------------------
  670. #endif // #ifndef IMGUI_DISABLE