imgui_impl_dx10.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  7. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  8. // Learn about Dear ImGui:
  9. // - FAQ https://dearimgui.com/faq
  10. // - Getting Started https://dearimgui.com/getting-started
  11. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  12. // - Introduction, links and more at the top of imgui.cpp
  13. // CHANGELOG
  14. // (minor and older changes stripped away, please see git history for details)
  15. // 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.
  16. // 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  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. // DirectX10 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. // Functions
  75. static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device)
  76. {
  77. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  78. // Setup viewport
  79. D3D10_VIEWPORT vp;
  80. memset(&vp, 0, sizeof(D3D10_VIEWPORT));
  81. vp.Width = (UINT)draw_data->DisplaySize.x;
  82. vp.Height = (UINT)draw_data->DisplaySize.y;
  83. vp.MinDepth = 0.0f;
  84. vp.MaxDepth = 1.0f;
  85. vp.TopLeftX = vp.TopLeftY = 0;
  86. device->RSSetViewports(1, &vp);
  87. // Setup orthographic projection matrix into our constant buffer
  88. // 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.
  89. void* mapped_resource;
  90. if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) == S_OK)
  91. {
  92. VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource;
  93. float L = draw_data->DisplayPos.x;
  94. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  95. float T = draw_data->DisplayPos.y;
  96. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  97. float mvp[4][4] =
  98. {
  99. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  100. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  101. { 0.0f, 0.0f, 0.5f, 0.0f },
  102. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  103. };
  104. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  105. bd->pVertexConstantBuffer->Unmap();
  106. }
  107. // Setup shader and vertex buffers
  108. unsigned int stride = sizeof(ImDrawVert);
  109. unsigned int offset = 0;
  110. device->IASetInputLayout(bd->pInputLayout);
  111. device->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
  112. device->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  113. device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  114. device->VSSetShader(bd->pVertexShader);
  115. device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
  116. device->PSSetShader(bd->pPixelShader);
  117. device->PSSetSamplers(0, 1, &bd->pFontSampler);
  118. device->GSSetShader(nullptr);
  119. // Setup render state
  120. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  121. device->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
  122. device->OMSetDepthStencilState(bd->pDepthStencilState, 0);
  123. device->RSSetState(bd->pRasterizerState);
  124. }
  125. // Render function
  126. void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
  127. {
  128. // Avoid rendering when minimized
  129. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  130. return;
  131. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  132. ID3D10Device* device = bd->pd3dDevice;
  133. // Create and grow vertex/index buffers if needed
  134. if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
  135. {
  136. if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
  137. bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  138. D3D10_BUFFER_DESC desc;
  139. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  140. desc.Usage = D3D10_USAGE_DYNAMIC;
  141. desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
  142. desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  143. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  144. desc.MiscFlags = 0;
  145. if (device->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
  146. return;
  147. }
  148. if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
  149. {
  150. if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
  151. bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  152. D3D10_BUFFER_DESC desc;
  153. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  154. desc.Usage = D3D10_USAGE_DYNAMIC;
  155. desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
  156. desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
  157. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  158. if (device->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
  159. return;
  160. }
  161. // Copy and convert all vertices into a single contiguous buffer
  162. ImDrawVert* vtx_dst = nullptr;
  163. ImDrawIdx* idx_dst = nullptr;
  164. bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
  165. bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
  166. for (int n = 0; n < draw_data->CmdListsCount; n++)
  167. {
  168. const ImDrawList* draw_list = draw_data->CmdLists[n];
  169. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  170. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  171. vtx_dst += draw_list->VtxBuffer.Size;
  172. idx_dst += draw_list->IdxBuffer.Size;
  173. }
  174. bd->pVB->Unmap();
  175. bd->pIB->Unmap();
  176. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  177. struct BACKUP_DX10_STATE
  178. {
  179. UINT ScissorRectsCount, ViewportsCount;
  180. D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  181. D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  182. ID3D10RasterizerState* RS;
  183. ID3D10BlendState* BlendState;
  184. FLOAT BlendFactor[4];
  185. UINT SampleMask;
  186. UINT StencilRef;
  187. ID3D10DepthStencilState* DepthStencilState;
  188. ID3D10ShaderResourceView* PSShaderResource;
  189. ID3D10SamplerState* PSSampler;
  190. ID3D10PixelShader* PS;
  191. ID3D10VertexShader* VS;
  192. ID3D10GeometryShader* GS;
  193. D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  194. ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  195. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  196. DXGI_FORMAT IndexBufferFormat;
  197. ID3D10InputLayout* InputLayout;
  198. };
  199. BACKUP_DX10_STATE old = {};
  200. old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  201. device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  202. device->RSGetViewports(&old.ViewportsCount, old.Viewports);
  203. device->RSGetState(&old.RS);
  204. device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  205. device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  206. device->PSGetShaderResources(0, 1, &old.PSShaderResource);
  207. device->PSGetSamplers(0, 1, &old.PSSampler);
  208. device->PSGetShader(&old.PS);
  209. device->VSGetShader(&old.VS);
  210. device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  211. device->GSGetShader(&old.GS);
  212. device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  213. device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  214. device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  215. device->IAGetInputLayout(&old.InputLayout);
  216. // Setup desired DX state
  217. ImGui_ImplDX10_SetupRenderState(draw_data, device);
  218. // Setup render state structure (for callbacks and custom texture bindings)
  219. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  220. ImGui_ImplDX10_RenderState render_state;
  221. render_state.Device = bd->pd3dDevice;
  222. render_state.SamplerDefault = bd->pFontSampler;
  223. render_state.VertexConstantBuffer = bd->pVertexConstantBuffer;
  224. platform_io.Renderer_RenderState = &render_state;
  225. // Render command lists
  226. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  227. int global_vtx_offset = 0;
  228. int global_idx_offset = 0;
  229. ImVec2 clip_off = draw_data->DisplayPos;
  230. for (int n = 0; n < draw_data->CmdListsCount; n++)
  231. {
  232. const ImDrawList* draw_list = draw_data->CmdLists[n];
  233. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  234. {
  235. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  236. if (pcmd->UserCallback != nullptr)
  237. {
  238. // User callback, registered via ImDrawList::AddCallback()
  239. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  240. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  241. ImGui_ImplDX10_SetupRenderState(draw_data, device);
  242. else
  243. pcmd->UserCallback(draw_list, pcmd);
  244. }
  245. else
  246. {
  247. // Project scissor/clipping rectangles into framebuffer space
  248. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  249. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  250. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  251. continue;
  252. // Apply scissor/clipping rectangle
  253. const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  254. device->RSSetScissorRects(1, &r);
  255. // Bind texture, Draw
  256. ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID();
  257. device->PSSetShaderResources(0, 1, &texture_srv);
  258. device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
  259. }
  260. }
  261. global_idx_offset += draw_list->IdxBuffer.Size;
  262. global_vtx_offset += draw_list->VtxBuffer.Size;
  263. }
  264. platform_io.Renderer_RenderState = nullptr;
  265. // Restore modified DX state
  266. device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  267. device->RSSetViewports(old.ViewportsCount, old.Viewports);
  268. device->RSSetState(old.RS); if (old.RS) old.RS->Release();
  269. device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  270. device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  271. device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  272. device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  273. device->PSSetShader(old.PS); if (old.PS) old.PS->Release();
  274. device->VSSetShader(old.VS); if (old.VS) old.VS->Release();
  275. device->GSSetShader(old.GS); if (old.GS) old.GS->Release();
  276. device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  277. device->IASetPrimitiveTopology(old.PrimitiveTopology);
  278. device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  279. device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  280. device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  281. }
  282. static void ImGui_ImplDX10_CreateFontsTexture()
  283. {
  284. // Build texture atlas
  285. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  286. ImGuiIO& io = ImGui::GetIO();
  287. unsigned char* pixels;
  288. int width, height;
  289. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  290. // Upload texture to graphics system
  291. {
  292. D3D10_TEXTURE2D_DESC desc;
  293. ZeroMemory(&desc, sizeof(desc));
  294. desc.Width = width;
  295. desc.Height = height;
  296. desc.MipLevels = 1;
  297. desc.ArraySize = 1;
  298. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  299. desc.SampleDesc.Count = 1;
  300. desc.Usage = D3D10_USAGE_DEFAULT;
  301. desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
  302. desc.CPUAccessFlags = 0;
  303. ID3D10Texture2D* pTexture = nullptr;
  304. D3D10_SUBRESOURCE_DATA subResource;
  305. subResource.pSysMem = pixels;
  306. subResource.SysMemPitch = desc.Width * 4;
  307. subResource.SysMemSlicePitch = 0;
  308. bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  309. IM_ASSERT(pTexture != nullptr);
  310. // Create texture view
  311. D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
  312. ZeroMemory(&srv_desc, sizeof(srv_desc));
  313. srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  314. srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
  315. srv_desc.Texture2D.MipLevels = desc.MipLevels;
  316. srv_desc.Texture2D.MostDetailedMip = 0;
  317. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &bd->pFontTextureView);
  318. pTexture->Release();
  319. }
  320. // Store our identifier
  321. io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
  322. }
  323. static void ImGui_ImplDX10_DestroyFontsTexture()
  324. {
  325. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  326. if (bd->pFontTextureView)
  327. {
  328. bd->pFontTextureView->Release();
  329. bd->pFontTextureView = nullptr;
  330. ImGui::GetIO().Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
  331. }
  332. }
  333. bool ImGui_ImplDX10_CreateDeviceObjects()
  334. {
  335. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  336. if (!bd->pd3dDevice)
  337. return false;
  338. if (bd->pFontSampler)
  339. ImGui_ImplDX10_InvalidateDeviceObjects();
  340. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  341. // If you would like to use this DX10 sample code but remove this dependency you can:
  342. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  343. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  344. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  345. // Create the vertex shader
  346. {
  347. static const char* vertexShader =
  348. "cbuffer vertexBuffer : register(b0) \
  349. {\
  350. float4x4 ProjectionMatrix; \
  351. };\
  352. struct VS_INPUT\
  353. {\
  354. float2 pos : POSITION;\
  355. float4 col : COLOR0;\
  356. float2 uv : TEXCOORD0;\
  357. };\
  358. \
  359. struct PS_INPUT\
  360. {\
  361. float4 pos : SV_POSITION;\
  362. float4 col : COLOR0;\
  363. float2 uv : TEXCOORD0;\
  364. };\
  365. \
  366. PS_INPUT main(VS_INPUT input)\
  367. {\
  368. PS_INPUT output;\
  369. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  370. output.col = input.col;\
  371. output.uv = input.uv;\
  372. return output;\
  373. }";
  374. ID3DBlob* vertexShaderBlob;
  375. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
  376. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  377. if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK)
  378. {
  379. vertexShaderBlob->Release();
  380. return false;
  381. }
  382. // Create the input layout
  383. D3D10_INPUT_ELEMENT_DESC local_layout[] =
  384. {
  385. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  386. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  387. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  388. };
  389. if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
  390. {
  391. vertexShaderBlob->Release();
  392. return false;
  393. }
  394. vertexShaderBlob->Release();
  395. // Create the constant buffer
  396. {
  397. D3D10_BUFFER_DESC desc;
  398. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10);
  399. desc.Usage = D3D10_USAGE_DYNAMIC;
  400. desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
  401. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  402. desc.MiscFlags = 0;
  403. bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
  404. }
  405. }
  406. // Create the pixel shader
  407. {
  408. static const char* pixelShader =
  409. "struct PS_INPUT\
  410. {\
  411. float4 pos : SV_POSITION;\
  412. float4 col : COLOR0;\
  413. float2 uv : TEXCOORD0;\
  414. };\
  415. sampler sampler0;\
  416. Texture2D texture0;\
  417. \
  418. float4 main(PS_INPUT input) : SV_Target\
  419. {\
  420. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  421. return out_col; \
  422. }";
  423. ID3DBlob* pixelShaderBlob;
  424. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
  425. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  426. if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK)
  427. {
  428. pixelShaderBlob->Release();
  429. return false;
  430. }
  431. pixelShaderBlob->Release();
  432. }
  433. // Create the blending setup
  434. {
  435. D3D10_BLEND_DESC desc;
  436. ZeroMemory(&desc, sizeof(desc));
  437. desc.AlphaToCoverageEnable = false;
  438. desc.BlendEnable[0] = true;
  439. desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
  440. desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
  441. desc.BlendOp = D3D10_BLEND_OP_ADD;
  442. desc.SrcBlendAlpha = D3D10_BLEND_ONE;
  443. desc.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
  444. desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
  445. desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
  446. bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
  447. }
  448. // Create the rasterizer state
  449. {
  450. D3D10_RASTERIZER_DESC desc;
  451. ZeroMemory(&desc, sizeof(desc));
  452. desc.FillMode = D3D10_FILL_SOLID;
  453. desc.CullMode = D3D10_CULL_NONE;
  454. desc.ScissorEnable = true;
  455. desc.DepthClipEnable = true;
  456. bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
  457. }
  458. // Create depth-stencil State
  459. {
  460. D3D10_DEPTH_STENCIL_DESC desc;
  461. ZeroMemory(&desc, sizeof(desc));
  462. desc.DepthEnable = false;
  463. desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
  464. desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
  465. desc.StencilEnable = false;
  466. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
  467. desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
  468. desc.BackFace = desc.FrontFace;
  469. bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
  470. }
  471. // Create texture sampler
  472. // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
  473. {
  474. D3D10_SAMPLER_DESC desc;
  475. ZeroMemory(&desc, sizeof(desc));
  476. desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
  477. desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
  478. desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
  479. desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
  480. desc.MipLODBias = 0.f;
  481. desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
  482. desc.MinLOD = 0.f;
  483. desc.MaxLOD = 0.f;
  484. bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
  485. }
  486. ImGui_ImplDX10_CreateFontsTexture();
  487. return true;
  488. }
  489. void ImGui_ImplDX10_InvalidateDeviceObjects()
  490. {
  491. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  492. if (!bd->pd3dDevice)
  493. return;
  494. ImGui_ImplDX10_DestroyFontsTexture();
  495. if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
  496. if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
  497. if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
  498. if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
  499. if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
  500. if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
  501. if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
  502. if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
  503. if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
  504. if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
  505. }
  506. bool ImGui_ImplDX10_Init(ID3D10Device* device)
  507. {
  508. ImGuiIO& io = ImGui::GetIO();
  509. IMGUI_CHECKVERSION();
  510. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  511. // Setup backend capabilities flags
  512. ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)();
  513. io.BackendRendererUserData = (void*)bd;
  514. io.BackendRendererName = "imgui_impl_dx10";
  515. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  516. // Get factory from device
  517. IDXGIDevice* pDXGIDevice = nullptr;
  518. IDXGIAdapter* pDXGIAdapter = nullptr;
  519. IDXGIFactory* pFactory = nullptr;
  520. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
  521. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
  522. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
  523. {
  524. bd->pd3dDevice = device;
  525. bd->pFactory = pFactory;
  526. }
  527. if (pDXGIDevice) pDXGIDevice->Release();
  528. if (pDXGIAdapter) pDXGIAdapter->Release();
  529. bd->pd3dDevice->AddRef();
  530. return true;
  531. }
  532. void ImGui_ImplDX10_Shutdown()
  533. {
  534. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  535. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  536. ImGuiIO& io = ImGui::GetIO();
  537. ImGui_ImplDX10_InvalidateDeviceObjects();
  538. if (bd->pFactory) { bd->pFactory->Release(); }
  539. if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
  540. io.BackendRendererName = nullptr;
  541. io.BackendRendererUserData = nullptr;
  542. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  543. IM_DELETE(bd);
  544. }
  545. void ImGui_ImplDX10_NewFrame()
  546. {
  547. ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
  548. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
  549. if (!bd->pVertexShader)
  550. ImGui_ImplDX10_CreateDeviceObjects();
  551. }
  552. //-----------------------------------------------------------------------------
  553. #endif // #ifndef IMGUI_DISABLE