imgui_impl_dx10.cpp 33 KB

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