main.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. // ImGui - standalone example application for DirectX 11
  2. #include <windows.h>
  3. #define STB_IMAGE_STATIC
  4. #define STB_IMAGE_IMPLEMENTATION
  5. #include "../shared/stb_image.h" // for .png loading
  6. #include "../../imgui.h"
  7. // DirectX 11
  8. #include <d3d11.h>
  9. #include <d3dcompiler.h>
  10. #define DIRECTINPUT_VERSION 0x0800
  11. #include <dinput.h>
  12. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
  13. static HWND hWnd;
  14. static ID3D11Device* g_pd3dDevice = NULL;
  15. static ID3D11DeviceContext* g_pd3dDeviceImmediateContext = NULL;
  16. static IDXGISwapChain* g_pSwapChain = NULL;
  17. static ID3D11Buffer* g_pVB = NULL;
  18. static ID3D11RenderTargetView* g_mainRenderTargetView;
  19. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  20. static ID3D11VertexShader* g_pVertexShader = NULL;
  21. static ID3D11InputLayout* g_pInputLayout = NULL;
  22. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  23. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  24. static ID3D11PixelShader* g_pPixelShader = NULL;
  25. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  26. static ID3D11SamplerState* g_pFontSampler = NULL;
  27. static ID3D11BlendState* g_blendState = NULL;
  28. struct CUSTOMVERTEX
  29. {
  30. float pos[2];
  31. float uv[2];
  32. unsigned int col;
  33. };
  34. struct VERTEX_CONSTANT_BUFFER
  35. {
  36. float mvp[4][4];
  37. };
  38. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  39. // If text or lines are blurry when integrating ImGui in your engine:
  40. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  41. // - try adjusting ImGui::GetIO().PixelCenterOffset to 0.5f or 0.375f
  42. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  43. {
  44. size_t total_vtx_count = 0;
  45. for (int n = 0; n < cmd_lists_count; n++)
  46. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  47. if (total_vtx_count == 0)
  48. return;
  49. // Copy and convert all vertices into a single contiguous buffer
  50. D3D11_MAPPED_SUBRESOURCE mappedResource;
  51. if (g_pd3dDeviceImmediateContext->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  52. return;
  53. CUSTOMVERTEX* vtx_dst = (CUSTOMVERTEX*)mappedResource.pData;
  54. for (int n = 0; n < cmd_lists_count; n++)
  55. {
  56. const ImDrawList* cmd_list = cmd_lists[n];
  57. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  58. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  59. {
  60. vtx_dst->pos[0] = vtx_src->pos.x;
  61. vtx_dst->pos[1] = vtx_src->pos.y;
  62. vtx_dst->uv[0] = vtx_src->uv.x;
  63. vtx_dst->uv[1] = vtx_src->uv.y;
  64. vtx_dst->col = vtx_src->col;
  65. vtx_dst++;
  66. vtx_src++;
  67. }
  68. }
  69. g_pd3dDeviceImmediateContext->Unmap(g_pVB, 0);
  70. // Setup orthographic projection matrix into our constant buffer
  71. {
  72. D3D11_MAPPED_SUBRESOURCE mappedResource;
  73. if (g_pd3dDeviceImmediateContext->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource) != S_OK)
  74. return;
  75. VERTEX_CONSTANT_BUFFER* pConstantBuffer = (VERTEX_CONSTANT_BUFFER*)mappedResource.pData;
  76. const float L = 0.0f;
  77. const float R = ImGui::GetIO().DisplaySize.x;
  78. const float B = ImGui::GetIO().DisplaySize.y;
  79. const float T = 0.0f;
  80. const float mvp[4][4] =
  81. {
  82. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f},
  83. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f,},
  84. { 0.0f, 0.0f, 0.5f, 0.0f },
  85. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  86. };
  87. memcpy(&pConstantBuffer->mvp, mvp, sizeof(mvp));
  88. g_pd3dDeviceImmediateContext->Unmap(g_pVertexConstantBuffer, 0);
  89. }
  90. // Setup viewport
  91. {
  92. D3D11_VIEWPORT vp;
  93. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  94. vp.Width = ImGui::GetIO().DisplaySize.x;
  95. vp.Height = ImGui::GetIO().DisplaySize.y;
  96. vp.MinDepth = 0.0f;
  97. vp.MaxDepth = 1.0f;
  98. vp.TopLeftX = 0;
  99. vp.TopLeftY = 0;
  100. g_pd3dDeviceImmediateContext->RSSetViewports(1, &vp);
  101. }
  102. // Bind shader and vertex buffers
  103. unsigned int stride = sizeof(CUSTOMVERTEX);
  104. unsigned int offset = 0;
  105. g_pd3dDeviceImmediateContext->IASetInputLayout(g_pInputLayout);
  106. g_pd3dDeviceImmediateContext->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  107. g_pd3dDeviceImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  108. g_pd3dDeviceImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
  109. g_pd3dDeviceImmediateContext->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  110. g_pd3dDeviceImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);
  111. g_pd3dDeviceImmediateContext->PSSetShaderResources(0, 1, &g_pFontTextureView);
  112. g_pd3dDeviceImmediateContext->PSSetSamplers(0, 1, &g_pFontSampler);
  113. // Setup render state
  114. const float blendFactor[4] = { 0.f, 0.f, 0.f, 0.f };
  115. g_pd3dDeviceImmediateContext->OMSetBlendState(g_blendState, blendFactor, 0xffffffff);
  116. // Render command lists
  117. int vtx_offset = 0;
  118. for (int n = 0; n < cmd_lists_count; n++)
  119. {
  120. // Render command list
  121. const ImDrawList* cmd_list = cmd_lists[n];
  122. for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++)
  123. {
  124. const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i];
  125. const D3D11_RECT r = { (LONG)pcmd->clip_rect.x, (LONG)pcmd->clip_rect.y, (LONG)pcmd->clip_rect.z, (LONG)pcmd->clip_rect.w };
  126. g_pd3dDeviceImmediateContext->RSSetScissorRects(1, &r);
  127. g_pd3dDeviceImmediateContext->Draw(pcmd->vtx_count, vtx_offset);
  128. vtx_offset += pcmd->vtx_count;
  129. }
  130. }
  131. // Restore modified state
  132. g_pd3dDeviceImmediateContext->IASetInputLayout(NULL);
  133. g_pd3dDeviceImmediateContext->PSSetShader(NULL, NULL, 0);
  134. g_pd3dDeviceImmediateContext->VSSetShader(NULL, NULL, 0);
  135. }
  136. HRESULT InitDeviceD3D(HWND hWnd)
  137. {
  138. // Setup swap chain
  139. DXGI_SWAP_CHAIN_DESC sd;
  140. {
  141. ZeroMemory(&sd, sizeof(sd));
  142. sd.BufferCount = 2;
  143. sd.BufferDesc.Width = (UINT)ImGui::GetIO().DisplaySize.x;
  144. sd.BufferDesc.Height = (UINT)ImGui::GetIO().DisplaySize.y;
  145. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  146. sd.BufferDesc.RefreshRate.Numerator = 60;
  147. sd.BufferDesc.RefreshRate.Denominator = 1;
  148. sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
  149. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  150. sd.OutputWindow = hWnd;
  151. sd.SampleDesc.Count = 1;
  152. sd.SampleDesc.Quality = 0;
  153. sd.Windowed = TRUE;
  154. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  155. }
  156. UINT createDeviceFlags = 0;
  157. #ifdef _DEBUG
  158. createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
  159. #endif
  160. D3D_FEATURE_LEVEL featureLevel;
  161. const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
  162. if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceImmediateContext) != S_OK)
  163. return E_FAIL;
  164. // Setup rasterizer
  165. {
  166. D3D11_RASTERIZER_DESC RSDesc;
  167. memset(&RSDesc, 0, sizeof(D3D11_RASTERIZER_DESC));
  168. RSDesc.FillMode = D3D11_FILL_SOLID;
  169. RSDesc.CullMode = D3D11_CULL_NONE;
  170. RSDesc.FrontCounterClockwise = FALSE;
  171. RSDesc.DepthBias = 0;
  172. RSDesc.SlopeScaledDepthBias = 0.0f;
  173. RSDesc.DepthBiasClamp = 0;
  174. RSDesc.DepthClipEnable = TRUE;
  175. RSDesc.ScissorEnable = TRUE;
  176. RSDesc.AntialiasedLineEnable = FALSE;
  177. RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;
  178. ID3D11RasterizerState* pRState = NULL;
  179. g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
  180. g_pd3dDeviceImmediateContext->RSSetState(pRState);
  181. pRState->Release();
  182. }
  183. // Create the render target
  184. {
  185. ID3D11Texture2D* pBackBuffer;
  186. D3D11_RENDER_TARGET_VIEW_DESC render_target_view_desc;
  187. ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
  188. render_target_view_desc.Format = sd.BufferDesc.Format;
  189. render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  190. g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
  191. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
  192. g_pd3dDeviceImmediateContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
  193. pBackBuffer->Release();
  194. }
  195. // Create the vertex shader
  196. {
  197. static const char* vertexShader =
  198. "cbuffer vertexBuffer : register(c0) \
  199. {\
  200. float4x4 ProjectionMatrix; \
  201. };\
  202. struct VS_INPUT\
  203. {\
  204. float2 pos : POSITION;\
  205. float4 col : COLOR0;\
  206. float2 uv : TEXCOORD0;\
  207. };\
  208. \
  209. struct PS_INPUT\
  210. {\
  211. float4 pos : SV_POSITION;\
  212. float4 col : COLOR0;\
  213. float2 uv : TEXCOORD0;\
  214. };\
  215. \
  216. PS_INPUT main(VS_INPUT input)\
  217. {\
  218. PS_INPUT output;\
  219. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  220. output.col = input.col;\
  221. output.uv = input.uv;\
  222. return output;\
  223. }";
  224. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
  225. if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  226. return E_FAIL;
  227. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  228. return E_FAIL;
  229. // Create the input layout
  230. D3D11_INPUT_ELEMENT_DESC localLayout[] = {
  231. { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  232. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((CUSTOMVERTEX*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  233. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((CUSTOMVERTEX*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  234. };
  235. if (g_pd3dDevice->CreateInputLayout(localLayout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  236. return E_FAIL;
  237. // Create the constant buffer
  238. {
  239. D3D11_BUFFER_DESC cbDesc;
  240. cbDesc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  241. cbDesc.Usage = D3D11_USAGE_DYNAMIC;
  242. cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  243. cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  244. cbDesc.MiscFlags = 0;
  245. g_pd3dDevice->CreateBuffer(&cbDesc, NULL, &g_pVertexConstantBuffer);
  246. }
  247. }
  248. // Create the pixel shader
  249. {
  250. static const char* pixelShader =
  251. "struct PS_INPUT\
  252. {\
  253. float4 pos : SV_POSITION;\
  254. float4 col : COLOR0;\
  255. float2 uv : TEXCOORD0;\
  256. };\
  257. sampler sampler0;\
  258. Texture2D texture0;\
  259. \
  260. float4 main(PS_INPUT input) : SV_Target\
  261. {\
  262. float4 out_col = texture0.Sample(sampler0, input.uv);\
  263. return input.col * out_col;\
  264. }";
  265. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
  266. if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  267. return E_FAIL;
  268. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  269. return E_FAIL;
  270. }
  271. // Create the blending setup
  272. {
  273. D3D11_BLEND_DESC desc;
  274. ZeroMemory(&desc, sizeof(desc));
  275. desc.AlphaToCoverageEnable = false;
  276. desc.RenderTarget[0].BlendEnable = true;
  277. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  278. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  279. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  280. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  281. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  282. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  283. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  284. g_pd3dDevice->CreateBlendState(&desc, &g_blendState);
  285. }
  286. return S_OK;
  287. }
  288. void CleanupDevice()
  289. {
  290. if (g_pd3dDeviceImmediateContext) g_pd3dDeviceImmediateContext->ClearState();
  291. // InitImGui
  292. if (g_pFontSampler) g_pFontSampler->Release();
  293. if (g_pFontTextureView) g_pFontTextureView->Release();
  294. if (g_pVB) g_pVB->Release();
  295. // InitDeviceD3D
  296. if (g_blendState) g_blendState->Release();
  297. if (g_pPixelShader) g_pPixelShader->Release();
  298. if (g_pPixelShaderBlob) g_pPixelShaderBlob->Release();
  299. if (g_pVertexConstantBuffer) g_pVertexConstantBuffer->Release();
  300. if (g_pInputLayout) g_pInputLayout->Release();
  301. if (g_pVertexShader) g_pVertexShader->Release();
  302. if (g_pVertexShaderBlob) g_pVertexShaderBlob->Release();
  303. if (g_mainRenderTargetView) g_mainRenderTargetView->Release();
  304. if (g_pSwapChain) g_pSwapChain->Release();
  305. if (g_pd3dDeviceImmediateContext) g_pd3dDeviceImmediateContext->Release();
  306. if (g_pd3dDevice) g_pd3dDevice->Release();
  307. }
  308. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  309. {
  310. ImGuiIO& io = ImGui::GetIO();
  311. switch (msg)
  312. {
  313. case WM_LBUTTONDOWN:
  314. io.MouseDown[0] = true;
  315. return true;
  316. case WM_LBUTTONUP:
  317. io.MouseDown[0] = false;
  318. return true;
  319. case WM_RBUTTONDOWN:
  320. io.MouseDown[1] = true;
  321. return true;
  322. case WM_RBUTTONUP:
  323. io.MouseDown[1] = false;
  324. return true;
  325. case WM_MOUSEWHEEL:
  326. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  327. return true;
  328. case WM_MOUSEMOVE:
  329. // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  330. io.MousePos.x = (signed short)(lParam);
  331. io.MousePos.y = (signed short)(lParam >> 16);
  332. return true;
  333. case WM_CHAR:
  334. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  335. if (wParam > 0 && wParam < 0x10000)
  336. io.AddInputCharacter((unsigned short)wParam);
  337. return true;
  338. case WM_DESTROY:
  339. CleanupDevice();
  340. PostQuitMessage(0);
  341. return 0;
  342. }
  343. return DefWindowProc(hWnd, msg, wParam, lParam);
  344. }
  345. void InitImGui()
  346. {
  347. RECT rect;
  348. GetClientRect(hWnd, &rect);
  349. int display_w = (int)(rect.right - rect.left);
  350. int display_h = (int)(rect.bottom - rect.top);
  351. ImGuiIO& io = ImGui::GetIO();
  352. io.DisplaySize = ImVec2((float)display_w, (float)display_h); // Display size, in pixels. For clamping windows positions.
  353. io.DeltaTime = 1.0f/60.0f; // Time elapsed since last frame, in seconds (in this sample app we'll override this every frame because our time step is variable)
  354. io.PixelCenterOffset = 0.0f; // Align Direct3D Texels
  355. io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  356. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  357. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  358. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  359. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  360. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  361. io.KeyMap[ImGuiKey_End] = VK_END;
  362. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  363. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  364. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  365. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  366. io.KeyMap[ImGuiKey_A] = 'A';
  367. io.KeyMap[ImGuiKey_C] = 'C';
  368. io.KeyMap[ImGuiKey_V] = 'V';
  369. io.KeyMap[ImGuiKey_X] = 'X';
  370. io.KeyMap[ImGuiKey_Y] = 'Y';
  371. io.KeyMap[ImGuiKey_Z] = 'Z';
  372. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  373. // Create the vertex buffer
  374. {
  375. D3D11_BUFFER_DESC bufferDesc;
  376. memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
  377. bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
  378. bufferDesc.ByteWidth = 10000 * sizeof(CUSTOMVERTEX);
  379. bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  380. bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  381. bufferDesc.MiscFlags = 0;
  382. if (g_pd3dDevice->CreateBuffer(&bufferDesc, NULL, &g_pVB) < 0)
  383. {
  384. IM_ASSERT(0);
  385. return;
  386. }
  387. }
  388. // Load font texture
  389. // Default font (embedded in code)
  390. const void* png_data;
  391. unsigned int png_size;
  392. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  393. int tex_x, tex_y, tex_comp;
  394. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  395. IM_ASSERT(tex_data != NULL);
  396. {
  397. D3D11_TEXTURE2D_DESC desc;
  398. ZeroMemory(&desc, sizeof(desc));
  399. desc.Width = tex_x;
  400. desc.Height = tex_y;
  401. desc.MipLevels = 1;
  402. desc.ArraySize = 1;
  403. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  404. desc.SampleDesc.Count = 1;
  405. desc.Usage = D3D11_USAGE_DEFAULT;
  406. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  407. desc.CPUAccessFlags = 0;
  408. ID3D11Texture2D *pTexture = NULL;
  409. D3D11_SUBRESOURCE_DATA subResource;
  410. subResource.pSysMem = tex_data;
  411. subResource.SysMemPitch = tex_x * 4;
  412. subResource.SysMemSlicePitch = 0;
  413. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  414. // Create texture view
  415. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  416. ZeroMemory(&srvDesc, sizeof(srvDesc));
  417. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  418. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  419. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  420. srvDesc.Texture2D.MostDetailedMip = 0;
  421. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  422. pTexture->Release();
  423. }
  424. // Create texture sampler
  425. {
  426. D3D11_SAMPLER_DESC desc;
  427. ZeroMemory(&desc, sizeof(desc));
  428. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
  429. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  430. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  431. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  432. desc.MipLODBias = 0.f;
  433. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  434. desc.MinLOD = 0.f;
  435. desc.MaxLOD = 0.f;
  436. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  437. }
  438. }
  439. INT64 ticks_per_second = 0;
  440. INT64 last_time = 0;
  441. void UpdateImGui()
  442. {
  443. ImGuiIO& io = ImGui::GetIO();
  444. // Setup time step
  445. INT64 current_time;
  446. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  447. io.DeltaTime = (float)(current_time - last_time) / ticks_per_second;
  448. last_time = current_time;
  449. // Setup inputs
  450. // (we already got mouse position, buttons, wheel from the window message callback)
  451. BYTE keystate[256];
  452. GetKeyboardState(keystate);
  453. for (int i = 0; i < 256; i++)
  454. io.KeysDown[i] = (keystate[i] & 0x80) != 0;
  455. io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
  456. io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
  457. // io.MousePos : filled by WM_MOUSEMOVE event
  458. // io.MouseDown : filled by WM_*BUTTON* events
  459. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  460. // Start the frame
  461. ImGui::NewFrame();
  462. }
  463. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
  464. {
  465. // Register the window class
  466. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, "ImGui Example", NULL };
  467. RegisterClassEx(&wc);
  468. // Create the application's window
  469. hWnd = CreateWindow("ImGui Example", "ImGui DirectX11 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  470. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  471. return 1;
  472. if (!QueryPerformanceCounter((LARGE_INTEGER *)&last_time))
  473. return 1;
  474. // Initialize Direct3D
  475. if (InitDeviceD3D(hWnd) < 0)
  476. {
  477. CleanupDevice();
  478. UnregisterClass("ImGui Example", wc.hInstance);
  479. return 1;
  480. }
  481. // Show the window
  482. ShowWindow(hWnd, SW_SHOWDEFAULT);
  483. UpdateWindow(hWnd);
  484. InitImGui();
  485. // Enter the message loop
  486. MSG msg;
  487. ZeroMemory(&msg, sizeof(msg));
  488. while (msg.message != WM_QUIT)
  489. {
  490. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  491. {
  492. TranslateMessage(&msg);
  493. DispatchMessage(&msg);
  494. continue;
  495. }
  496. UpdateImGui();
  497. static bool show_test_window = true;
  498. static bool show_another_window = false;
  499. // 1. Show a simple window
  500. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
  501. {
  502. static float f;
  503. ImGui::Text("Hello, world!");
  504. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  505. show_test_window ^= ImGui::Button("Test Window");
  506. show_another_window ^= ImGui::Button("Another Window");
  507. // Calculate and show frame rate
  508. static float ms_per_frame[120] = { 0 };
  509. static int ms_per_frame_idx = 0;
  510. static float ms_per_frame_accum = 0.0f;
  511. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  512. ms_per_frame[ms_per_frame_idx] = ImGui::GetIO().DeltaTime * 1000.0f;
  513. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  514. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  515. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  516. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  517. }
  518. // 2. Show another simple window, this time using an explicit Begin/End pair
  519. if (show_another_window)
  520. {
  521. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  522. ImGui::Text("Hello");
  523. ImGui::End();
  524. }
  525. // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
  526. if (show_test_window)
  527. {
  528. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCondition_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  529. ImGui::ShowTestWindow(&show_test_window);
  530. }
  531. // Rendering
  532. float clearColor[4] = { 204 / 255.f, 153 / 255.f, 153 / 255.f };
  533. g_pd3dDeviceImmediateContext->ClearRenderTargetView(g_mainRenderTargetView, clearColor);
  534. ImGui::Render();
  535. g_pSwapChain->Present(0, 0);
  536. }
  537. ImGui::Shutdown();
  538. UnregisterClass("ImGui Example", wc.hInstance);
  539. return 0;
  540. }