imgui_impl_dx10.cpp 26 KB

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