imgui_impl_dx10.cpp 32 KB

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