main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. // ---------------------------------------------------------------------------
  2. // Simple Assimp Directx11 Sample
  3. // This is a very basic sample and only reads diffuse texture
  4. // but this can load both embedded textures in fbx and non-embedded textures
  5. //
  6. //
  7. // Replace ourModel->Load(hwnd, dev, devcon, "Models/myModel.fbx") this with your
  8. // model name (line 480)
  9. // If your model isn't a fbx with embedded textures make sure your model's
  10. // textures are in same directory as your model
  11. //
  12. //
  13. // Written by IAS. :)
  14. // ---------------------------------------------------------------------------
  15. #include <assimp/types.h>
  16. #include <Windows.h>
  17. #include <shellapi.h>
  18. #include <stdexcept>
  19. #include <windowsx.h>
  20. #include <d3d11_1.h>
  21. #include <dxgi1_2.h>
  22. #include <DirectXMath.h>
  23. #include <d3dcompiler.h>
  24. #include "ModelLoader.h"
  25. #include "SafeRelease.hpp"
  26. #ifdef _MSC_VER
  27. #pragma comment (lib, "d3d11.lib")
  28. #pragma comment (lib, "Dxgi.lib")
  29. #pragma comment(lib,"d3dcompiler.lib")
  30. #pragma comment (lib, "dxguid.lib")
  31. #endif // _MSC_VER
  32. using namespace DirectX;
  33. #define VERTEX_SHADER_FILE L"VertexShader.hlsl"
  34. #define PIXEL_SHADER_FILE L"PixelShader.hlsl"
  35. // ------------------------------------------------------------
  36. // Structs
  37. // ------------------------------------------------------------
  38. struct ConstantBuffer {
  39. XMMATRIX mWorld;
  40. XMMATRIX mView;
  41. XMMATRIX mProjection;
  42. };
  43. // ------------------------------------------------------------
  44. // Window Variables
  45. // ------------------------------------------------------------
  46. static constexpr uint32_t SCREEN_WIDTH = 800;
  47. static constexpr uint32_t SCREEN_HEIGHT = 600;
  48. constexpr char g_szClassName[] = "directxWindowClass";
  49. static std::string g_ModelPath;
  50. UINT width, height;
  51. HWND g_hwnd = nullptr;
  52. // ------------------------------------------------------------
  53. // DirectX Variables
  54. // ------------------------------------------------------------
  55. D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL;
  56. D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0;
  57. ID3D11Device *dev = nullptr;
  58. ID3D11Device1 *dev1 = nullptr;
  59. ID3D11DeviceContext *devcon = nullptr;
  60. ID3D11DeviceContext1 *devcon1 = nullptr;
  61. IDXGISwapChain *swapchain = nullptr;
  62. IDXGISwapChain1 *swapchain1 = nullptr;
  63. ID3D11RenderTargetView *backbuffer = nullptr;
  64. ID3D11VertexShader *pVS = nullptr;
  65. ID3D11PixelShader *pPS = nullptr;
  66. ID3D11InputLayout *pLayout = nullptr;
  67. ID3D11Buffer *pConstantBuffer = nullptr;
  68. ID3D11Texture2D *g_pDepthStencil = nullptr;
  69. ID3D11DepthStencilView *g_pDepthStencilView = nullptr;
  70. ID3D11SamplerState *TexSamplerState = nullptr;
  71. ID3D11RasterizerState *rasterstate = nullptr;
  72. ID3D11Debug* d3d11debug = nullptr;
  73. XMMATRIX m_World;
  74. XMMATRIX m_View;
  75. XMMATRIX m_Projection;
  76. // ------------------------------------------------------------
  77. // Function identifiers
  78. // ------------------------------------------------------------
  79. void InitD3D(HINSTANCE hinstance, HWND hWnd);
  80. void CleanD3D(void);
  81. void RenderFrame(void);
  82. void InitPipeline();
  83. void InitGraphics();
  84. HRESULT CompileShaderFromFile(LPCWSTR pFileName, const D3D_SHADER_MACRO* pDefines, LPCSTR pEntryPoint, LPCSTR pShaderModel, ID3DBlob** ppBytecodeBlob);
  85. void Throwanerror(LPCSTR errormessage);
  86. // ------------------------------------------------------------
  87. // Our Model
  88. // ------------------------------------------------------------
  89. ModelLoader *ourModel = nullptr;
  90. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  91. {
  92. switch (msg)
  93. {
  94. case WM_CLOSE:
  95. DestroyWindow(hwnd);
  96. break;
  97. case WM_DESTROY:
  98. PostQuitMessage(0);
  99. break;
  100. default:
  101. return DefWindowProc(hwnd, msg, wParam, lParam);
  102. }
  103. return 0;
  104. }
  105. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
  106. LPWSTR /*lpCmdLine*/, int nCmdShow)
  107. {
  108. int argc;
  109. LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  110. if (!argv) {
  111. MessageBox(nullptr,
  112. TEXT("An error occurred while reading command line arguments."),
  113. TEXT("Error!"),
  114. MB_ICONERROR | MB_OK);
  115. return EXIT_FAILURE;
  116. }
  117. // Free memory allocated from CommandLineToArgvW.
  118. auto free_command_line_allocated_memory = [&argv]() {
  119. if (argv) {
  120. LocalFree(argv);
  121. argv = nullptr;
  122. }
  123. };
  124. // Ensure that a model file has been specified.
  125. if (argc < 2) {
  126. MessageBox(nullptr,
  127. TEXT("No model file specified. The program will now close."),
  128. TEXT("Error!"),
  129. MB_ICONERROR | MB_OK);
  130. free_command_line_allocated_memory();
  131. return EXIT_FAILURE;
  132. }
  133. // Retrieve the model file path.
  134. std::wstring filename(argv[1]);
  135. char *targetStart = new char[filename.size()+1];
  136. memset(targetStart, '\0', filename.size() + 1);
  137. utf8::utf16to8(filename.c_str(), filename.c_str() + filename.size(), targetStart);
  138. g_ModelPath = targetStart;
  139. delete[] targetStart;
  140. free_command_line_allocated_memory();
  141. WNDCLASSEX wc;
  142. MSG msg;
  143. wc.cbSize = sizeof(WNDCLASSEX);
  144. wc.style = 0;
  145. wc.lpfnWndProc = WndProc;
  146. wc.cbClsExtra = 0;
  147. wc.cbWndExtra = 0;
  148. wc.hInstance = hInstance;
  149. wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
  150. wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
  151. wc.hbrBackground = nullptr;
  152. wc.lpszMenuName = nullptr;
  153. wc.lpszClassName = g_szClassName;
  154. wc.hIconSm = LoadIcon(nullptr, IDI_APPLICATION);
  155. if (!RegisterClassEx(&wc))
  156. {
  157. MessageBox(nullptr, "Window Registration Failed!", "Error!",
  158. MB_ICONEXCLAMATION | MB_OK);
  159. return 0;
  160. }
  161. RECT wr = { 0,0, SCREEN_WIDTH, SCREEN_HEIGHT };
  162. AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
  163. g_hwnd = CreateWindowEx(
  164. WS_EX_CLIENTEDGE,
  165. g_szClassName,
  166. " Simple Textured Directx11 Sample ",
  167. WS_OVERLAPPEDWINDOW,
  168. CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top,
  169. nullptr, nullptr, hInstance, nullptr
  170. );
  171. if (g_hwnd == nullptr)
  172. {
  173. MessageBox(nullptr, "Window Creation Failed!", "Error!",
  174. MB_ICONEXCLAMATION | MB_OK);
  175. return 0;
  176. }
  177. ShowWindow(g_hwnd, nCmdShow);
  178. UpdateWindow(g_hwnd);
  179. width = wr.right - wr.left;
  180. height = wr.bottom - wr.top;
  181. try {
  182. InitD3D(hInstance, g_hwnd);
  183. while (true)
  184. {
  185. if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
  186. {
  187. TranslateMessage(&msg);
  188. DispatchMessage(&msg);
  189. if (msg.message == WM_QUIT)
  190. break;
  191. }
  192. RenderFrame();
  193. }
  194. CleanD3D();
  195. return static_cast<int>(msg.wParam);
  196. } catch (const std::exception& e) {
  197. MessageBox(g_hwnd, e.what(), TEXT("Error!"), MB_ICONERROR | MB_OK);
  198. CleanD3D();
  199. return EXIT_FAILURE;
  200. } catch (...) {
  201. MessageBox(g_hwnd, TEXT("Caught an unknown exception."), TEXT("Error!"), MB_ICONERROR | MB_OK);
  202. CleanD3D();
  203. return EXIT_FAILURE;
  204. }
  205. }
  206. void InitD3D(HINSTANCE /*hinstance*/, HWND hWnd)
  207. {
  208. HRESULT hr;
  209. UINT createDeviceFlags = 0;
  210. #ifdef _DEBUG
  211. createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
  212. #endif
  213. D3D_DRIVER_TYPE driverTypes[] =
  214. {
  215. D3D_DRIVER_TYPE_HARDWARE,
  216. D3D_DRIVER_TYPE_WARP,
  217. D3D_DRIVER_TYPE_REFERENCE,
  218. };
  219. UINT numDriverTypes = ARRAYSIZE(driverTypes);
  220. D3D_FEATURE_LEVEL featureLevels[] =
  221. {
  222. D3D_FEATURE_LEVEL_11_1,
  223. D3D_FEATURE_LEVEL_11_0,
  224. D3D_FEATURE_LEVEL_10_1,
  225. D3D_FEATURE_LEVEL_10_0,
  226. };
  227. UINT numFeatureLevels = ARRAYSIZE(featureLevels);
  228. for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
  229. {
  230. g_driverType = driverTypes[driverTypeIndex];
  231. hr = D3D11CreateDevice(nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels,
  232. D3D11_SDK_VERSION, &dev, &g_featureLevel, &devcon);
  233. if (hr == E_INVALIDARG)
  234. {
  235. // DirectX 11.0 platforms will not recognize D3D_FEATURE_LEVEL_11_1 so we need to retry without it
  236. hr = D3D11CreateDevice(nullptr, g_driverType, nullptr, createDeviceFlags, &featureLevels[1], numFeatureLevels - 1,
  237. D3D11_SDK_VERSION, &dev, &g_featureLevel, &devcon);
  238. }
  239. if (SUCCEEDED(hr))
  240. break;
  241. }
  242. if (FAILED(hr))
  243. Throwanerror("Directx Device Creation Failed!");
  244. #if _DEBUG
  245. hr = dev->QueryInterface(IID_PPV_ARGS(&d3d11debug));
  246. if (FAILED(hr))
  247. OutputDebugString(TEXT("Failed to retrieve DirectX 11 debug interface.\n"));
  248. #endif
  249. UINT m4xMsaaQuality;
  250. dev->CheckMultisampleQualityLevels(
  251. DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality);
  252. // Obtain DXGI factory from device (since we used nullptr for pAdapter above)
  253. IDXGIFactory1* dxgiFactory = nullptr;
  254. {
  255. IDXGIDevice* dxgiDevice = nullptr;
  256. hr = dev->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice));
  257. if (SUCCEEDED(hr))
  258. {
  259. IDXGIAdapter* adapter = nullptr;
  260. hr = dxgiDevice->GetAdapter(&adapter);
  261. if (SUCCEEDED(hr))
  262. {
  263. hr = adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&dxgiFactory));
  264. adapter->Release();
  265. }
  266. dxgiDevice->Release();
  267. }
  268. }
  269. if (FAILED(hr))
  270. Throwanerror("DXGI Factory couldn't be obtained!");
  271. // Create swap chain
  272. IDXGIFactory2* dxgiFactory2 = nullptr;
  273. hr = dxgiFactory->QueryInterface(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&dxgiFactory2));
  274. if (dxgiFactory2)
  275. {
  276. // DirectX 11.1 or later
  277. hr = dev->QueryInterface(__uuidof(ID3D11Device1), reinterpret_cast<void**>(&dev1));
  278. if (SUCCEEDED(hr))
  279. {
  280. (void)devcon->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&devcon1));
  281. }
  282. DXGI_SWAP_CHAIN_DESC1 sd;
  283. ZeroMemory(&sd, sizeof(sd));
  284. sd.Width = SCREEN_WIDTH;
  285. sd.Height = SCREEN_HEIGHT;
  286. sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  287. sd.SampleDesc.Count = 4;
  288. sd.SampleDesc.Quality = m4xMsaaQuality - 1;
  289. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  290. sd.BufferCount = 1;
  291. hr = dxgiFactory2->CreateSwapChainForHwnd(dev, hWnd, &sd, nullptr, nullptr, &swapchain1);
  292. if (SUCCEEDED(hr))
  293. {
  294. hr = swapchain1->QueryInterface(__uuidof(IDXGISwapChain), reinterpret_cast<void**>(&swapchain));
  295. }
  296. dxgiFactory2->Release();
  297. }
  298. else
  299. {
  300. // DirectX 11.0 systems
  301. DXGI_SWAP_CHAIN_DESC sd;
  302. ZeroMemory(&sd, sizeof(sd));
  303. sd.BufferCount = 1;
  304. sd.BufferDesc.Width = SCREEN_WIDTH;
  305. sd.BufferDesc.Height = SCREEN_HEIGHT;
  306. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  307. sd.BufferDesc.RefreshRate.Numerator = 60;
  308. sd.BufferDesc.RefreshRate.Denominator = 1;
  309. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  310. sd.OutputWindow = hWnd;
  311. sd.SampleDesc.Count = 1;
  312. sd.SampleDesc.Quality = m4xMsaaQuality - 1;
  313. sd.Windowed = TRUE;
  314. hr = dxgiFactory->CreateSwapChain(dev, &sd, &swapchain);
  315. }
  316. // Note this tutorial doesn't handle full-screen swapchains so we block the ALT+ENTER shortcut
  317. dxgiFactory->MakeWindowAssociation(g_hwnd, DXGI_MWA_NO_ALT_ENTER);
  318. dxgiFactory->Release();
  319. if (FAILED(hr))
  320. Throwanerror("Swapchain Creation Failed!");
  321. ID3D11Texture2D *pBackBuffer;
  322. swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
  323. dev->CreateRenderTargetView(pBackBuffer, nullptr, &backbuffer);
  324. pBackBuffer->Release();
  325. D3D11_TEXTURE2D_DESC descDepth;
  326. ZeroMemory(&descDepth, sizeof(descDepth));
  327. descDepth.Width = SCREEN_WIDTH;
  328. descDepth.Height = SCREEN_HEIGHT;
  329. descDepth.MipLevels = 1;
  330. descDepth.ArraySize = 1;
  331. descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  332. descDepth.SampleDesc.Count = 4;
  333. descDepth.SampleDesc.Quality = m4xMsaaQuality - 1;
  334. descDepth.Usage = D3D11_USAGE_DEFAULT;
  335. descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  336. descDepth.CPUAccessFlags = 0;
  337. descDepth.MiscFlags = 0;
  338. hr = dev->CreateTexture2D(&descDepth, nullptr, &g_pDepthStencil);
  339. if (FAILED(hr))
  340. Throwanerror("Depth Stencil Texture couldn't be created!");
  341. // Create the depth stencil view
  342. D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
  343. ZeroMemory(&descDSV, sizeof(descDSV));
  344. descDSV.Format = descDepth.Format;
  345. descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  346. descDSV.Texture2D.MipSlice = 0;
  347. hr = dev->CreateDepthStencilView(g_pDepthStencil, 0, &g_pDepthStencilView);
  348. if (FAILED(hr))
  349. {
  350. Throwanerror("Depth Stencil View couldn't be created!");
  351. }
  352. devcon->OMSetRenderTargets(1, &backbuffer, g_pDepthStencilView);
  353. D3D11_RASTERIZER_DESC rasterDesc;
  354. rasterDesc.AntialiasedLineEnable = false;
  355. rasterDesc.CullMode = D3D11_CULL_BACK;
  356. rasterDesc.DepthBias = 0;
  357. rasterDesc.DepthBiasClamp = 0.0f;
  358. rasterDesc.DepthClipEnable = true;
  359. rasterDesc.FillMode = D3D11_FILL_SOLID;
  360. rasterDesc.FrontCounterClockwise = false;
  361. rasterDesc.MultisampleEnable = false;
  362. rasterDesc.ScissorEnable = false;
  363. rasterDesc.SlopeScaledDepthBias = 0.0f;
  364. dev->CreateRasterizerState(&rasterDesc, &rasterstate);
  365. devcon->RSSetState(rasterstate);
  366. D3D11_VIEWPORT viewport;
  367. ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
  368. viewport.TopLeftX = 0;
  369. viewport.TopLeftY = 0;
  370. viewport.MinDepth = 0.0f;
  371. viewport.MaxDepth = 1.0f;
  372. viewport.Width = SCREEN_WIDTH;
  373. viewport.Height = SCREEN_HEIGHT;
  374. devcon->RSSetViewports(1, &viewport);
  375. InitPipeline();
  376. InitGraphics();
  377. }
  378. void CleanD3D(void)
  379. {
  380. if (swapchain)
  381. swapchain->SetFullscreenState(FALSE, nullptr);
  382. if (ourModel) {
  383. ourModel->Close();
  384. delete ourModel;
  385. ourModel = nullptr;
  386. }
  387. SafeRelease(TexSamplerState);
  388. SafeRelease(pConstantBuffer);
  389. SafeRelease(pLayout);
  390. SafeRelease(pVS);
  391. SafeRelease(pPS);
  392. SafeRelease(rasterstate);
  393. SafeRelease(g_pDepthStencilView);
  394. SafeRelease(g_pDepthStencil);
  395. SafeRelease(backbuffer);
  396. SafeRelease(swapchain);
  397. SafeRelease(swapchain1);
  398. SafeRelease(devcon1);
  399. SafeRelease(dev1);
  400. SafeRelease(devcon);
  401. #if _DEBUG
  402. if (d3d11debug) {
  403. OutputDebugString(TEXT("Dumping DirectX 11 live objects.\n"));
  404. d3d11debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
  405. SafeRelease(d3d11debug);
  406. } else {
  407. OutputDebugString(TEXT("Unable to dump live objects: no DirectX 11 debug interface available.\n"));
  408. }
  409. #endif
  410. SafeRelease(dev);
  411. }
  412. void RenderFrame(void)
  413. {
  414. static float t = 0.0f;
  415. static ULONGLONG timeStart = 0;
  416. ULONGLONG timeCur = GetTickCount64();
  417. if (timeStart == 0)
  418. timeStart = timeCur;
  419. t = (timeCur - timeStart) / 1000.0f;
  420. float clearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
  421. devcon->ClearRenderTargetView(backbuffer, clearColor);
  422. devcon->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
  423. devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  424. m_World = XMMatrixRotationY(-t);
  425. ConstantBuffer cb;
  426. cb.mWorld = XMMatrixTranspose(m_World);
  427. cb.mView = XMMatrixTranspose(m_View);
  428. cb.mProjection = XMMatrixTranspose(m_Projection);
  429. devcon->UpdateSubresource(pConstantBuffer, 0, nullptr, &cb, 0, 0);
  430. devcon->VSSetShader(pVS, 0, 0);
  431. devcon->VSSetConstantBuffers(0, 1, &pConstantBuffer);
  432. devcon->PSSetShader(pPS, 0, 0);
  433. devcon->PSSetSamplers(0, 1, &TexSamplerState);
  434. ourModel->Draw(devcon);
  435. swapchain->Present(0, 0);
  436. }
  437. void InitPipeline()
  438. {
  439. ID3DBlob *VS, *PS;
  440. if(FAILED(CompileShaderFromFile(SHADER_PATH VERTEX_SHADER_FILE, 0, "main", "vs_4_0", &VS)))
  441. Throwanerror("Failed to compile shader from file");
  442. if(FAILED(CompileShaderFromFile(SHADER_PATH PIXEL_SHADER_FILE, 0, "main", "ps_4_0", &PS)))
  443. Throwanerror("Failed to compile shader from file ");
  444. dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), nullptr, &pVS);
  445. dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), nullptr, &pPS);
  446. D3D11_INPUT_ELEMENT_DESC ied[] =
  447. {
  448. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  449. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }
  450. };
  451. dev->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
  452. devcon->IASetInputLayout(pLayout);
  453. }
  454. void InitGraphics()
  455. {
  456. HRESULT hr;
  457. m_Projection = XMMatrixPerspectiveFovLH(XM_PIDIV4, SCREEN_WIDTH / (float)SCREEN_HEIGHT, 0.01f, 1000.0f);
  458. D3D11_BUFFER_DESC bd;
  459. ZeroMemory(&bd, sizeof(bd));
  460. bd.Usage = D3D11_USAGE_DEFAULT;
  461. bd.ByteWidth = sizeof(ConstantBuffer);
  462. bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  463. bd.CPUAccessFlags = 0;
  464. hr = dev->CreateBuffer(&bd, nullptr, &pConstantBuffer);
  465. if (FAILED(hr))
  466. Throwanerror("Constant buffer couldn't be created");
  467. D3D11_SAMPLER_DESC sampDesc;
  468. ZeroMemory(&sampDesc, sizeof(sampDesc));
  469. sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  470. sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  471. sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  472. sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  473. sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
  474. sampDesc.MinLOD = 0;
  475. sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
  476. hr = dev->CreateSamplerState(&sampDesc, &TexSamplerState);
  477. if (FAILED(hr))
  478. Throwanerror("Texture sampler state couldn't be created");
  479. XMVECTOR Eye = XMVectorSet(0.0f, 5.0f, -300.0f, 0.0f);
  480. XMVECTOR At = XMVectorSet(0.0f, 100.0f, 0.0f, 0.0f);
  481. XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
  482. m_View = XMMatrixLookAtLH(Eye, At, Up);
  483. ourModel = new ModelLoader;
  484. if (!ourModel->Load(g_hwnd, dev, devcon, g_ModelPath))
  485. Throwanerror("Model couldn't be loaded");
  486. }
  487. HRESULT CompileShaderFromFile(LPCWSTR pFileName, const D3D_SHADER_MACRO* pDefines, LPCSTR pEntryPoint, LPCSTR pShaderModel, ID3DBlob** ppBytecodeBlob)
  488. {
  489. UINT compileFlags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;
  490. #ifdef _DEBUG
  491. compileFlags |= D3DCOMPILE_DEBUG;
  492. #endif
  493. ID3DBlob* pErrorBlob = nullptr;
  494. HRESULT result = D3DCompileFromFile(pFileName, pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE, pEntryPoint, pShaderModel, compileFlags, 0, ppBytecodeBlob, &pErrorBlob);
  495. if (FAILED(result))
  496. {
  497. if (pErrorBlob != nullptr)
  498. OutputDebugStringA((LPCSTR)pErrorBlob->GetBufferPointer());
  499. }
  500. if (pErrorBlob != nullptr)
  501. pErrorBlob->Release();
  502. return result;
  503. }
  504. void Throwanerror(LPCSTR errormessage)
  505. {
  506. throw std::runtime_error(errormessage);
  507. }