DX11GraphicsApi.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. #include "DX11GraphicsApi.h"
  2. #include <d3d11.h>
  3. #include <dxgi1_5.h>
  4. #include "Camera3D.h"
  5. #include "DLLRegister.h"
  6. #include "DX11Buffer.h"
  7. #include "DX11Shader.h"
  8. #include "DX11Texture.h"
  9. #include "Globals.h"
  10. #include "Image.h"
  11. #include "Logging.h"
  12. #include "Screen.h"
  13. #include "TextureList.h"
  14. #include "TextureModel.h"
  15. #include "UIPixelShader.h"
  16. #include "UIVertexShader.h"
  17. #include "Window.h"
  18. #include "World3D.h"
  19. using namespace Framework;
  20. struct TextureEffect
  21. {
  22. bool enabled;
  23. float percentage;
  24. };
  25. DirectX11::DirectX11()
  26. : GraphicsApi(DIRECTX11),
  27. d3d11Device(0),
  28. d3d11Context(0),
  29. d3d11SpawChain(0),
  30. uiTexture(0),
  31. vertexShader(0),
  32. pixelShader(0),
  33. sampleState(0),
  34. rtview(0),
  35. dsView(0),
  36. depthStencilBuffer(0),
  37. depthStencilState(0),
  38. depthDisabledStencilState(0),
  39. blendStateAlphaBlend(0),
  40. vp(0),
  41. texturModel(0),
  42. texturRegister(new TextureList()),
  43. texturRS(0),
  44. meshRS(0),
  45. defaultTexture(0),
  46. diffuseLights(0),
  47. pointLights(0),
  48. lastModelId(-1),
  49. indexBuffers(0),
  50. vertexBuffers(0)
  51. {}
  52. DirectX11::~DirectX11()
  53. {
  54. for (int i = 0; i <= lastModelId; i++)
  55. {
  56. indexBuffers[i]->release();
  57. vertexBuffers[i]->release();
  58. }
  59. delete[] indexBuffers;
  60. delete[] vertexBuffers;
  61. if (diffuseLights) diffuseLights->release();
  62. if (pointLights) pointLights->release();
  63. if (defaultTexture) defaultTexture->release();
  64. if (texturRS) texturRS->Release();
  65. if (meshRS) meshRS->Release();
  66. if (texturModel) texturModel->release();
  67. texturRegister->release();
  68. if (blendStateAlphaBlend)
  69. {
  70. blendStateAlphaBlend->Release();
  71. blendStateAlphaBlend = NULL;
  72. }
  73. if (uiTexture)
  74. {
  75. uiTexture->release();
  76. uiTexture = NULL;
  77. }
  78. if (sampleState)
  79. {
  80. sampleState->Release();
  81. sampleState = NULL;
  82. }
  83. if (pixelShader)
  84. {
  85. pixelShader->release();
  86. pixelShader = NULL;
  87. }
  88. if (vertexShader)
  89. {
  90. vertexShader->release();
  91. vertexShader = NULL;
  92. }
  93. if (depthDisabledStencilState)
  94. {
  95. depthDisabledStencilState->Release();
  96. depthDisabledStencilState = NULL;
  97. }
  98. delete vp;
  99. vp = 0;
  100. if (dsView)
  101. {
  102. dsView->Release();
  103. dsView = NULL;
  104. }
  105. if (depthStencilState)
  106. {
  107. depthStencilState->Release();
  108. depthStencilState = NULL;
  109. }
  110. if (depthStencilBuffer)
  111. {
  112. depthStencilBuffer->Release();
  113. depthStencilBuffer = NULL;
  114. }
  115. if (rtview)
  116. {
  117. rtview->Release();
  118. rtview = NULL;
  119. }
  120. if (d3d11SpawChain)
  121. {
  122. d3d11SpawChain->Release();
  123. d3d11SpawChain = NULL;
  124. }
  125. if (d3d11Device)
  126. {
  127. d3d11Device->Release();
  128. d3d11Device = NULL;
  129. }
  130. if (d3d11Context)
  131. {
  132. d3d11Context->Release();
  133. d3d11Context = NULL;
  134. getDLLRegister()->releaseDLL("d3d11.dll");
  135. getDLLRegister()->releaseDLL("dxgi.dll");
  136. }
  137. }
  138. typedef HRESULT(__stdcall* CreateDXGIFactory2Function)(UINT, REFIID, void**);
  139. typedef HRESULT(__stdcall* D3D11CreateDeviceAndSwapChainFunction)(IDXGIAdapter*,
  140. D3D_DRIVER_TYPE,
  141. HMODULE,
  142. UINT,
  143. const D3D_FEATURE_LEVEL*,
  144. UINT,
  145. UINT,
  146. const DXGI_SWAP_CHAIN_DESC*,
  147. IDXGISwapChain**,
  148. ID3D11Device**,
  149. D3D_FEATURE_LEVEL*,
  150. ID3D11DeviceContext**);
  151. void DirectX11::initialize(
  152. NativeWindow* fenster, Vec2<int> backBufferSize, bool fullScreen)
  153. {
  154. GraphicsApi::initialize(fenster, backBufferSize, fullScreen);
  155. //--------------------------------------------------------------------
  156. // Create Device
  157. HINSTANCE dxgiDLL = getDLLRegister()->loadDLL("dxgi.dll", "dxgi.dll");
  158. if (!dxgiDLL)
  159. {
  160. WMessageBox(fenster->getWindowHandle(),
  161. new Text("Fehler"),
  162. new Text("dxgi.dll konnte nicht gefunden werden."),
  163. MB_ICONERROR);
  164. return;
  165. }
  166. CreateDXGIFactory2Function createFactory
  167. = (CreateDXGIFactory2Function)GetProcAddress(
  168. dxgiDLL, "CreateDXGIFactory2");
  169. if (!createFactory)
  170. {
  171. getDLLRegister()->releaseDLL("dxgi.dll");
  172. WMessageBox(fenster->getWindowHandle(),
  173. new Text("Fehler"),
  174. new Text(
  175. "Der Einstiegspunkt CreateDXGIFactory2 fon dxgi.dll konnte "
  176. "nicht gefunden werden."),
  177. MB_ICONERROR);
  178. return;
  179. }
  180. IDXGIFactory5* factory;
  181. HRESULT res = createFactory(0, __uuidof(IDXGIFactory5), (void**)&factory);
  182. if (FAILED(res))
  183. {
  184. getDLLRegister()->releaseDLL("dxgi.dll");
  185. Logging::error() << "ERROR DXGI: createFactory returned " << res
  186. << "\n";
  187. WMessageBox(fenster->getWindowHandle(),
  188. new Text("Fehler"),
  189. new Text("createFactory ist Fehlgeschlagen."),
  190. MB_ICONERROR);
  191. return;
  192. }
  193. // search for gpu with max dedicated memory
  194. IDXGIAdapter* adapter = 0;
  195. IDXGIAdapter* usedAdapter = 0;
  196. unsigned __int64 dedicatedMemoryCount = 0;
  197. for (UINT adapterID = 0;
  198. DXGI_ERROR_NOT_FOUND != factory->EnumAdapters(adapterID, &adapter);
  199. ++adapterID)
  200. {
  201. DXGI_ADAPTER_DESC desc;
  202. adapter->GetDesc(&desc);
  203. if (dedicatedMemoryCount > desc.DedicatedVideoMemory)
  204. {
  205. continue;
  206. }
  207. dedicatedMemoryCount = desc.DedicatedVideoMemory;
  208. if (usedAdapter) usedAdapter->Release();
  209. usedAdapter = adapter;
  210. }
  211. HINSTANCE dll = getDLLRegister()->loadDLL("d3d11.dll", "d3d11.dll");
  212. if (!dll)
  213. {
  214. WMessageBox(fenster->getWindowHandle(),
  215. new Text("Fehler"),
  216. new Text("DirectX 11 konnte nicht gefunden werden."),
  217. MB_ICONERROR);
  218. return;
  219. }
  220. D3D11CreateDeviceAndSwapChainFunction createDeviceAndSwapChain
  221. = (D3D11CreateDeviceAndSwapChainFunction)GetProcAddress(
  222. dll, "D3D11CreateDeviceAndSwapChain");
  223. if (!createDeviceAndSwapChain)
  224. {
  225. getDLLRegister()->releaseDLL("d3d11.dll");
  226. getDLLRegister()->releaseDLL("dxgi.dll");
  227. WMessageBox(fenster->getWindowHandle(),
  228. new Text("Fehler"),
  229. new Text("Der Einstiegspunkt D3D11CreateDeviceAndSwapChain fon "
  230. "DirectX 11 konnte nicht gefunden werden."),
  231. MB_ICONERROR);
  232. return;
  233. }
  234. // create a struct to hold information about the swap chain
  235. DXGI_SWAP_CHAIN_DESC scd;
  236. // clear out the struct for use
  237. ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
  238. scd.Windowed = !fullScreen;
  239. scd.BufferCount = 2;
  240. scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  241. scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  242. scd.SampleDesc.Count = 1; // multisampling setting
  243. scd.SampleDesc.Quality = 0; // vendor-specific flag
  244. scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
  245. scd.OutputWindow = fenster ? fenster->getWindowHandle() : 0;
  246. scd.BufferDesc.Width = this->backBufferSize.x;
  247. scd.BufferDesc.Height = this->backBufferSize.y; // windowed/full-screen mode
  248. D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
  249. D3D_FEATURE_LEVEL support = D3D_FEATURE_LEVEL_11_0;
  250. // create a device, device context and swap chain using the information in
  251. // the scd struct
  252. UINT flag = 0;
  253. #ifdef _DEBUG
  254. if (debugDX) flag |= D3D11_CREATE_DEVICE_DEBUG;
  255. #endif
  256. HRESULT result = createDeviceAndSwapChain(usedAdapter,
  257. D3D_DRIVER_TYPE_UNKNOWN,
  258. NULL,
  259. flag,
  260. &featureLevel,
  261. 1,
  262. D3D11_SDK_VERSION,
  263. &scd,
  264. &d3d11SpawChain,
  265. &d3d11Device,
  266. &support,
  267. &d3d11Context);
  268. if (result != S_OK)
  269. {
  270. getDLLRegister()->releaseDLL("d3d11.dll");
  271. getDLLRegister()->releaseDLL("dxgi.dll");
  272. Logging::error() << "ERROR: D3D11CreateDeviceAndSwapChain returned "
  273. << result << "\n";
  274. WMessageBox(fenster->getWindowHandle(),
  275. new Text("Fehler"),
  276. new Text("DirectX 11 konnte nicht initialisiert werden."),
  277. MB_ICONERROR);
  278. return;
  279. }
  280. ID3D11Texture2D* backBufferPtr;
  281. // Get the pointer to the back buffer.
  282. result = d3d11SpawChain->GetBuffer(
  283. 0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
  284. if (result != S_OK)
  285. {
  286. Logging::error() << "ERROR: d3d11SpawChain->GetBuffer returned "
  287. << result << "\n";
  288. WMessageBox(fenster->getWindowHandle(),
  289. new Text("Fehler"),
  290. new Text("DirectX 11 konnte nicht initialisiert werden."),
  291. MB_ICONERROR);
  292. return;
  293. }
  294. vp = new D3D11_VIEWPORT();
  295. memset(vp, 0, sizeof(D3D11_VIEWPORT));
  296. vp->Width = (float)this->backBufferSize.x;
  297. vp->Height = (float)this->backBufferSize.y;
  298. vp->MinDepth = 0.0f;
  299. vp->MaxDepth = 1.0f;
  300. deviceLock.lock();
  301. d3d11Context->RSSetViewports(1, vp);
  302. deviceLock.unlock();
  303. // Create the render target view with the back buffer pointer.
  304. deviceLock.lock();
  305. result = d3d11Device->CreateRenderTargetView(backBufferPtr, NULL, &rtview);
  306. deviceLock.unlock();
  307. if (result != S_OK)
  308. {
  309. Logging::error()
  310. << "ERROR: d3d11Device->CreateRenderTargetView returned " << result
  311. << "\n";
  312. WMessageBox(fenster->getWindowHandle(),
  313. new Text("Fehler"),
  314. new Text("DirectX 11 konnte nicht initialisiert werden."),
  315. MB_ICONERROR);
  316. return;
  317. }
  318. // Release pointer to the back buffer as we no longer need it.
  319. backBufferPtr->Release();
  320. // Initialize the description of the depth buffer.
  321. D3D11_TEXTURE2D_DESC depthBufferDesc;
  322. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
  323. // Set up the description of the depth buffer.
  324. depthBufferDesc.Width = this->backBufferSize.x;
  325. depthBufferDesc.Height = this->backBufferSize.y;
  326. depthBufferDesc.MipLevels = 1;
  327. depthBufferDesc.ArraySize = 1;
  328. depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  329. depthBufferDesc.SampleDesc.Count = 1;
  330. depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
  331. depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  332. // Create the texture for the depth buffer using the filled out description.
  333. deviceLock.lock();
  334. result = d3d11Device->CreateTexture2D(
  335. &depthBufferDesc, NULL, &depthStencilBuffer);
  336. deviceLock.unlock();
  337. if (result != S_OK)
  338. {
  339. Logging::error() << "ERROR: d3d11Device->CreateTexture2D returned "
  340. << result << "\n";
  341. WMessageBox(fenster->getWindowHandle(),
  342. new Text("Fehler"),
  343. new Text("DirectX 11 konnte nicht initialisiert werden."),
  344. MB_ICONERROR);
  345. return;
  346. }
  347. // Initialize the description of the stencil state.
  348. D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
  349. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
  350. // Set up the description of the stencil state.
  351. depthStencilDesc.DepthEnable = true;
  352. depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  353. depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
  354. depthStencilDesc.StencilEnable = true;
  355. depthStencilDesc.StencilReadMask = 0xFF;
  356. depthStencilDesc.StencilWriteMask = 0xFF;
  357. // Stencil operations if pixel is front-facing.
  358. depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
  359. depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
  360. depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  361. depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  362. // Stencil operations if pixel is back-facing.
  363. depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
  364. depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
  365. depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  366. depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  367. // Create the depth stencil state.
  368. deviceLock.lock();
  369. result = d3d11Device->CreateDepthStencilState(
  370. &depthStencilDesc, &depthStencilState);
  371. deviceLock.unlock();
  372. if (result != S_OK)
  373. {
  374. Logging::error()
  375. << "ERROR: d3d11Device->CreateDepthStencilState returned " << result
  376. << "\n";
  377. WMessageBox(fenster->getWindowHandle(),
  378. new Text("Fehler"),
  379. new Text("DirectX 11 konnte nicht initialisiert werden."),
  380. MB_ICONERROR);
  381. return;
  382. }
  383. deviceLock.lock();
  384. d3d11Context->OMSetDepthStencilState(depthStencilState, 1);
  385. deviceLock.unlock();
  386. // Initialize the depth stencil view.
  387. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
  388. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
  389. // Set up the depth stencil view description.
  390. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  391. depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  392. // Create the depth stencil view.
  393. deviceLock.lock();
  394. result = d3d11Device->CreateDepthStencilView(
  395. depthStencilBuffer, &depthStencilViewDesc, &dsView);
  396. deviceLock.unlock();
  397. if (result != S_OK)
  398. {
  399. Logging::error()
  400. << "ERROR: d3d11Device->CreateDepthStencilView returned " << result
  401. << "\n";
  402. WMessageBox(fenster->getWindowHandle(),
  403. new Text("Fehler"),
  404. new Text("DirectX 11 konnte nicht initialisiert werden."),
  405. MB_ICONERROR);
  406. return;
  407. }
  408. deviceLock.lock();
  409. d3d11Context->OMSetRenderTargets(1, &rtview, dsView);
  410. deviceLock.unlock();
  411. D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
  412. // Clear the second depth stencil state before setting the parameters.
  413. ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
  414. // Now create a second depth stencil state which turns off the Z buffer for
  415. // 2D rendering. The only difference is that DepthEnable is set to false,
  416. // all other parameters are the same as the other depth stencil state.
  417. depthDisabledStencilDesc.DepthEnable = false;
  418. depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  419. depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
  420. depthDisabledStencilDesc.StencilEnable = true;
  421. depthDisabledStencilDesc.StencilReadMask = 0xFF;
  422. depthDisabledStencilDesc.StencilWriteMask = 0xFF;
  423. depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
  424. depthDisabledStencilDesc.FrontFace.StencilDepthFailOp
  425. = D3D11_STENCIL_OP_INCR;
  426. depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  427. depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  428. depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
  429. depthDisabledStencilDesc.BackFace.StencilDepthFailOp
  430. = D3D11_STENCIL_OP_DECR;
  431. depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  432. depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  433. // Create the state using the device.
  434. deviceLock.lock();
  435. result = d3d11Device->CreateDepthStencilState(
  436. &depthDisabledStencilDesc, &depthDisabledStencilState);
  437. deviceLock.unlock();
  438. if (result != S_OK)
  439. {
  440. Logging::error()
  441. << "ERROR: d3d11Device->CreateDepthStencilState returned " << result
  442. << "\n";
  443. WMessageBox(fenster->getWindowHandle(),
  444. new Text("Fehler"),
  445. new Text("DirectX 11 konnte nicht initialisiert werden."),
  446. MB_ICONERROR);
  447. return;
  448. }
  449. //-------------------------------------------------
  450. // Shaders
  451. vertexShader = initializeVertexShader(
  452. (unsigned char*)UIVertexShader, sizeof(UIVertexShader));
  453. pixelShader = initializePixelShader(
  454. (unsigned char*)UIPixelShader, sizeof(UIPixelShader));
  455. // Create a texture sampler state description.
  456. D3D11_SAMPLER_DESC samplerDesc;
  457. samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  458. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  459. samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  460. samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  461. samplerDesc.MipLODBias = 0.0f;
  462. samplerDesc.MaxAnisotropy = 1;
  463. samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  464. samplerDesc.BorderColor[0] = 0;
  465. samplerDesc.BorderColor[1] = 0;
  466. samplerDesc.BorderColor[2] = 0;
  467. samplerDesc.BorderColor[3] = 0;
  468. samplerDesc.MinLOD = 0;
  469. samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
  470. // Create the texture sampler state.
  471. deviceLock.lock();
  472. result = d3d11Device->CreateSamplerState(&samplerDesc, &sampleState);
  473. deviceLock.unlock();
  474. if (result != S_OK)
  475. {
  476. Logging::error() << "ERROR: d3d11Device->CreateSamplerState returned "
  477. << result << "\n";
  478. WMessageBox(fenster->getWindowHandle(),
  479. new Text("Fehler"),
  480. new Text("DirectX 11 konnte nicht initialisiert werden."),
  481. MB_ICONERROR);
  482. return;
  483. }
  484. //---------------------------------------------------------------
  485. // Framework Backbuffer Texture
  486. Image* renderB = new Image(1);
  487. renderB->setAlpha3D(1);
  488. renderB->newImage(this->backBufferSize.x, this->backBufferSize.y, 0);
  489. uiTexture = createOrGetTexture("_f_Render_Image", renderB, RAM_TO_GPU);
  490. ((DX11Texture*)uiTexture)->setUseMips(0);
  491. texturModel = new TextureModel(this, "_framework_gui_");
  492. texturModel->setSize(this->backBufferSize);
  493. texturModel->setTexture(dynamic_cast<Texture*>(uiTexture->getThis()));
  494. D3D11_BLEND_DESC blendState;
  495. ZeroMemory(&blendState, sizeof(D3D11_BLEND_DESC));
  496. blendState.AlphaToCoverageEnable = false;
  497. blendState.IndependentBlendEnable = false;
  498. blendState.RenderTarget[0].BlendEnable = true;
  499. blendState.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  500. blendState.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  501. blendState.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  502. blendState.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
  503. blendState.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
  504. blendState.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  505. blendState.RenderTarget[0].RenderTargetWriteMask
  506. = D3D11_COLOR_WRITE_ENABLE_ALL;
  507. deviceLock.lock();
  508. d3d11Device->CreateBlendState(&blendState, &blendStateAlphaBlend);
  509. d3d11Context->OMSetBlendState(blendStateAlphaBlend, 0, 0xFFFFFFFF);
  510. deviceLock.unlock();
  511. // Setup Render Objekt
  512. vertexShader->useShader();
  513. deviceLock.lock();
  514. d3d11Context->PSSetSamplers(0, 1, &sampleState);
  515. deviceLock.unlock();
  516. pixelShader->useShader();
  517. D3D11_RASTERIZER_DESC rasterDesc;
  518. ZeroMemory(&rasterDesc, sizeof(rasterDesc));
  519. rasterDesc.AntialiasedLineEnable = false;
  520. rasterDesc.CullMode = D3D11_CULL_BACK;
  521. rasterDesc.DepthBiasClamp = 0.0f;
  522. rasterDesc.DepthClipEnable = true;
  523. rasterDesc.FillMode = D3D11_FILL_SOLID;
  524. rasterDesc.FrontCounterClockwise = false;
  525. rasterDesc.MultisampleEnable = false;
  526. rasterDesc.ScissorEnable = false;
  527. rasterDesc.SlopeScaledDepthBias = 0.0f;
  528. deviceLock.lock();
  529. d3d11Device->CreateRasterizerState(&rasterDesc, &texturRS);
  530. deviceLock.unlock();
  531. ZeroMemory(&rasterDesc, sizeof(rasterDesc));
  532. rasterDesc.AntialiasedLineEnable = false;
  533. rasterDesc.CullMode = D3D11_CULL_BACK;
  534. rasterDesc.DepthBiasClamp = 0.0f;
  535. rasterDesc.DepthClipEnable = true;
  536. rasterDesc.FillMode = D3D11_FILL_WIREFRAME;
  537. rasterDesc.FrontCounterClockwise = false;
  538. rasterDesc.MultisampleEnable = false;
  539. rasterDesc.ScissorEnable = false;
  540. rasterDesc.SlopeScaledDepthBias = 0.0f;
  541. deviceLock.lock();
  542. d3d11Device->CreateRasterizerState(&rasterDesc, &meshRS);
  543. d3d11Context->RSSetState(texturRS);
  544. deviceLock.unlock();
  545. Image* b = new Image();
  546. b->newImage(10, 10, 0xFFFFFFFF);
  547. defaultTexture = createOrGetTexture("_default_textur", b, RAM_TO_GPU);
  548. diffuseLights = new DX11StructuredBuffer(
  549. sizeof(DiffuseLight), d3d11Device, d3d11Context, deviceLock);
  550. pointLights = new DX11StructuredBuffer(
  551. sizeof(PointLight), d3d11Device, d3d11Context, deviceLock);
  552. }
  553. void DirectX11::beginFrame(bool fill2D, bool fill3D, int fillColor)
  554. {
  555. if (fill2D) uiTexture->zImage()->setColor(fillColor);
  556. if (fill3D || true)
  557. {
  558. float color[4];
  559. // Setup the color to clear the buffer.
  560. color[0] = ((fillColor >> 16) & 0xFF) / 255.f; // R
  561. color[1] = ((fillColor >> 8) & 0xFF) / 255.f; // G
  562. color[2] = (fillColor & 0xFF) / 255.f; // B
  563. color[3] = ((fillColor >> 24) & 0xFF) / 255.f; // A
  564. deviceLock.lock();
  565. d3d11Context->ClearRenderTargetView(rtview, color);
  566. deviceLock.unlock();
  567. }
  568. deviceLock.lock();
  569. // Bind the render target view and depth stencil buffer to the output render
  570. // pipeline.
  571. d3d11Context->OMSetRenderTargets(1, &rtview, dsView);
  572. // Clear the depth buffer.
  573. d3d11Context->ClearDepthStencilView(
  574. dsView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1, 0);
  575. // Set the depth stencil state.
  576. d3d11Context->OMSetDepthStencilState(depthStencilState, 1);
  577. deviceLock.unlock();
  578. }
  579. void DirectX11::renderObject(Model3D* zObj)
  580. {
  581. if (!zObj->zModelData()) return;
  582. int curId = zObj->zModelData()->getId();
  583. if (curId < 0 || curId > lastModelId)
  584. {
  585. Framework::Logging::warning()
  586. << "DirectX11::renderObject: Model ID out of range: " << curId
  587. << " The model was not properly registered with DirectX11 during "
  588. "its creation. It can not be rendered by DirectX11.";
  589. return;
  590. }
  591. if (zObj->zModelData()->wasIndexBufferChanged())
  592. {
  593. this->indexBuffers[curId]->setData(
  594. (void*)zObj->zModelData()->getIndexBuffer(), true);
  595. this->indexBuffers[curId]->setLength(
  596. zObj->zModelData()->getIndexCount() * sizeof(int));
  597. this->indexBuffers[curId]->copyToGPU();
  598. zObj->zModelData()->setIndexBufferChanged(0);
  599. }
  600. if (zObj->zModelData()->wasVertexBufferChanged())
  601. {
  602. this->vertexBuffers[curId]->setData(
  603. (void*)zObj->zModelData()->zVertexBuffer(), true);
  604. this->vertexBuffers[curId]->setLength(
  605. zObj->zModelData()->getVertexCount() * sizeof(Vertex3D));
  606. this->vertexBuffers[curId]->copyToGPU();
  607. zObj->zModelData()->setVertexBufferChanged(0);
  608. }
  609. Mat4<float> trans = Mat4<float>::identity();
  610. int anz = zObj->calculateMatrices(trans, matrixBuffer);
  611. if (vertexShader)
  612. vertexShader->fillConstBuffer(
  613. (char*)matrixBuffer, 0, sizeof(Mat4<float>) * anz);
  614. float matirialBuffer[3]; // light factors (phong model)
  615. matirialBuffer[0] = zObj->getAmbientFactor();
  616. matirialBuffer[1] = zObj->getDiffusFactor();
  617. matirialBuffer[2] = zObj->getSpecularFactor();
  618. if (pixelShader)
  619. pixelShader->fillConstBuffer(
  620. (char*)matirialBuffer, 1, sizeof(float) * 3);
  621. unsigned int offset = 0;
  622. unsigned int es = (unsigned)this->vertexBuffers[curId]->getElementLength();
  623. ID3D11Buffer* vBuffer = this->vertexBuffers[curId]->zBuffer();
  624. deviceLock.lock();
  625. d3d11Context->IASetVertexBuffers(0, 1, &vBuffer, &es, &offset);
  626. deviceLock.unlock();
  627. Model3DTexture* zTexture = zObj->zTexture();
  628. int ind = 0;
  629. int current = 0;
  630. if (zObj->zEffectTexture())
  631. {
  632. ID3D11ShaderResourceView* v[1];
  633. DX11Texture* zEffectTexture = (DX11Texture*)zObj->zEffectTexture();
  634. if (zEffectTexture && zEffectTexture->needsUpdate())
  635. zEffectTexture->updateTextur();
  636. v[0] = *zEffectTexture;
  637. deviceLock.lock();
  638. d3d11Context->PSSetShaderResources(3, 1, v);
  639. deviceLock.unlock();
  640. TextureEffect e = {1, zObj->getEffectPercentage()};
  641. if (pixelShader)
  642. pixelShader->fillConstBuffer((char*)&e, 3, sizeof(TextureEffect));
  643. }
  644. else
  645. {
  646. TextureEffect e = {0, 0.f};
  647. if (pixelShader)
  648. pixelShader->fillConstBuffer((char*)&e, 3, sizeof(TextureEffect));
  649. }
  650. DXGI_FORMAT f = DXGI_FORMAT_R32_UINT;
  651. if (this->indexBuffers[curId]->getElementLength() == 2)
  652. f = DXGI_FORMAT_R16_UINT;
  653. if (this->indexBuffers[curId]->getElementLength() == 1)
  654. f = DXGI_FORMAT_R8_UINT;
  655. deviceLock.lock();
  656. d3d11Context->IASetIndexBuffer(this->indexBuffers[curId]->zBuffer(), f, 0);
  657. d3d11Context->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  658. deviceLock.unlock();
  659. zObj->beforeRender(this, vertexShader, pixelShader);
  660. for (auto i = zObj->zModelData()->getPolygons(); i; ++i)
  661. {
  662. if (zObj->needRenderPolygon(ind))
  663. {
  664. Texture* t = zTexture->zPolygonTexture(ind);
  665. if (t && t->needsUpdate()) t->updateTextur();
  666. if (t)
  667. {
  668. ID3D11ShaderResourceView* v[3];
  669. v[0] = *(DX11Texture*)t;
  670. v[1] = *diffuseLights;
  671. v[2] = *pointLights;
  672. deviceLock.lock();
  673. d3d11Context->PSSetShaderResources(0, 3, v);
  674. d3d11Context->DrawIndexed(i->indexAnz, current, 0);
  675. deviceLock.unlock();
  676. }
  677. else
  678. {
  679. deviceLock.lock();
  680. d3d11Context->RSSetState(meshRS);
  681. ID3D11ShaderResourceView* v[3];
  682. v[0] = *(DX11Texture*)defaultTexture;
  683. v[1] = *diffuseLights;
  684. v[2] = *pointLights;
  685. d3d11Context->PSSetShaderResources(0, 3, v);
  686. d3d11Context->DrawIndexed(i->indexAnz, current, 0);
  687. d3d11Context->RSSetState(texturRS);
  688. deviceLock.unlock();
  689. }
  690. }
  691. ind++;
  692. current += i->indexAnz;
  693. }
  694. zObj->afterRender(this, pixelShader, vertexShader);
  695. }
  696. // Checks whether a sphere is in the visible space of the world and needs to be
  697. // drawn
  698. // pos: The center of the sphere
  699. // radius: The radius of the sphere
  700. // dist: A pointer to a float where the square of the distance to the
  701. // camera position is stored if this function returns true and
  702. // the pointer is not 0
  703. bool DirectX11::isInFrustrum(
  704. const Vec3<float>& pos, float radius, float* dist) const
  705. {
  706. for (int i = 0; i < 6; i++)
  707. {
  708. if (frustrum[i] * pos + radius < 0) return 0;
  709. }
  710. if (dist) *dist = kamPos.distance(pos);
  711. return 1;
  712. }
  713. bool DirectX11::isInFrustrum(
  714. const Vec3<float>& pos, Vec3<float> radius, float* dist) const
  715. {
  716. for (int i = 0; i < 6; i++)
  717. {
  718. float r = abs(frustrum[i].normal() * radius);
  719. if (frustrum[i] * pos + r < 0) return 0;
  720. }
  721. if (dist) *dist = kamPos.distance(pos);
  722. return 1;
  723. }
  724. void DirectX11::renderKamera(Cam3D* zKamera)
  725. {
  726. deviceLock.lock();
  727. d3d11Context->RSSetViewports(1, (D3D11_VIEWPORT*)zKamera->zViewPort());
  728. deviceLock.unlock();
  729. Mat4<float> tmp = zKamera->getProjectionMatrix() * zKamera->getViewMatrix();
  730. frustrum[0].x = tmp.elements[3][0] + tmp.elements[0][0];
  731. frustrum[0].y = tmp.elements[3][1] + tmp.elements[0][1];
  732. frustrum[0].z = tmp.elements[3][2] + tmp.elements[0][2];
  733. frustrum[0].w = tmp.elements[3][3] + tmp.elements[0][3];
  734. frustrum[1].x = tmp.elements[3][0] - tmp.elements[0][0];
  735. frustrum[1].y = tmp.elements[3][1] - tmp.elements[0][1];
  736. frustrum[1].z = tmp.elements[3][2] - tmp.elements[0][2];
  737. frustrum[1].w = tmp.elements[3][3] - tmp.elements[0][3];
  738. frustrum[2].x = tmp.elements[3][0] - tmp.elements[1][0];
  739. frustrum[2].y = tmp.elements[3][1] - tmp.elements[1][1];
  740. frustrum[2].z = tmp.elements[3][2] - tmp.elements[1][2];
  741. frustrum[2].w = tmp.elements[3][3] - tmp.elements[1][3];
  742. frustrum[3].x = tmp.elements[3][0] + tmp.elements[1][0];
  743. frustrum[3].y = tmp.elements[3][1] + tmp.elements[1][1];
  744. frustrum[3].z = tmp.elements[3][2] + tmp.elements[1][2];
  745. frustrum[3].w = tmp.elements[3][3] + tmp.elements[1][3];
  746. frustrum[4].x = tmp.elements[2][0];
  747. frustrum[4].y = tmp.elements[2][1];
  748. frustrum[4].z = tmp.elements[2][2];
  749. frustrum[4].w = tmp.elements[2][3];
  750. frustrum[5].x = tmp.elements[3][0] - tmp.elements[2][0];
  751. frustrum[5].y = tmp.elements[3][1] - tmp.elements[2][1];
  752. frustrum[5].z = tmp.elements[3][2] - tmp.elements[2][2];
  753. frustrum[5].w = tmp.elements[3][3] - tmp.elements[2][3];
  754. for (int i = 0; i < 6; i++)
  755. frustrum[i].normalize();
  756. viewAndProj[0] = zKamera->getViewMatrix();
  757. viewAndProj[1] = zKamera->getProjectionMatrix();
  758. kamPos = zKamera->getWorldPosition();
  759. if (vertexShader)
  760. vertexShader->fillConstBuffer(
  761. (char*)viewAndProj, 1, sizeof(Mat4<float>) * 2);
  762. if (pixelShader)
  763. pixelShader->fillConstBuffer((char*)&kamPos, 0, sizeof(float) * 3);
  764. World3D* w = zKamera->zWorld();
  765. w->readLock().lock();
  766. int lc[] = {w->getDiffuseLightCount(), w->getPointLightCount()};
  767. pixelShader->fillConstBuffer((char*)lc, 2, sizeof(int) * 2);
  768. w->copyLight(diffuseLights, pointLights);
  769. int maxDist = 0;
  770. int minDist = 0x7FFFFFFF;
  771. Array<Model3D*> alphaModels;
  772. Array<int> distances;
  773. w->render([this, &minDist, &maxDist, &alphaModels, &lc, &distances](
  774. Model3D* obj) {
  775. float dist;
  776. if (isInFrustrum(obj->getPos(), obj->getRadius(), &dist))
  777. {
  778. if ((int)dist > maxDist) maxDist = (int)dist;
  779. if ((int)dist < minDist) minDist = (int)dist;
  780. if (obj->hasAlpha())
  781. {
  782. alphaModels.add(obj);
  783. distances.add((int)dist);
  784. }
  785. else
  786. {
  787. pixelShader->fillConstBuffer((char*)lc, 2, sizeof(int) * 2);
  788. renderObject(obj);
  789. }
  790. }
  791. });
  792. maxDist++;
  793. if (alphaModels.getEntryCount())
  794. {
  795. int size = maxDist - minDist;
  796. int* index = new int[size];
  797. memset(index, 0, size * 4);
  798. Model3D** sorted = new Model3D*[size * alphaModels.getEntryCount()];
  799. auto dist = distances.begin();
  800. for (auto obj : alphaModels)
  801. {
  802. sorted[dist.val() * alphaModels.getEntryCount()
  803. + index[dist.val()]++] = obj;
  804. dist++;
  805. }
  806. for (int i = 0; i < size; i++)
  807. {
  808. for (int j = 0; j < index[i]; j++)
  809. {
  810. renderObject(sorted[i * alphaModels.getEntryCount() + j]);
  811. }
  812. }
  813. delete[] index;
  814. delete[] sorted;
  815. }
  816. w->readLock().unlock();
  817. }
  818. void DirectX11::renderKamera(Cam3D* zKamera, Texture* zTarget)
  819. {
  820. ID3D11RenderTargetView* texturRtView;
  821. DX11Texture* d11Textur = dynamic_cast<DX11Texture*>(zTarget);
  822. if (!d11Textur || d11Textur->getDirection() != GPU_TO_RAM)
  823. throw "incompatible textur object was passed to renderKamera of "
  824. "DirectX11 GPU API";
  825. if (d11Textur->needsUpdate()) d11Textur->updateTextur();
  826. D3D11_TEXTURE2D_DESC depthBufferDesc;
  827. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
  828. // Set up the description of the depth buffer.
  829. depthBufferDesc.Width = zTarget->zImage()->getWidth();
  830. depthBufferDesc.Height = zTarget->zImage()->getHeight();
  831. depthBufferDesc.MipLevels = 1;
  832. depthBufferDesc.ArraySize = 1;
  833. depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  834. depthBufferDesc.SampleDesc.Count = 1;
  835. depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
  836. depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  837. ID3D11Texture2D* txtDepthStencilBuffer;
  838. // Create the texture for the depth buffer using the filled out description.
  839. deviceLock.lock();
  840. HRESULT result = d3d11Device->CreateTexture2D(
  841. &depthBufferDesc, NULL, &txtDepthStencilBuffer);
  842. deviceLock.unlock();
  843. if (result != S_OK) throw "could not create depth Stencil buffer";
  844. // Initialize the depth stencil view.
  845. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
  846. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
  847. // Set up the depth stencil view description.
  848. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  849. depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  850. ID3D11DepthStencilView* txtDsView;
  851. // Create the depth stencil view.
  852. deviceLock.lock();
  853. result = d3d11Device->CreateDepthStencilView(
  854. txtDepthStencilBuffer, &depthStencilViewDesc, &txtDsView);
  855. deviceLock.unlock();
  856. if (result != S_OK) throw "could not create depth stencil view";
  857. D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
  858. renderTargetViewDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  859. renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  860. renderTargetViewDesc.Texture2D.MipSlice = 0;
  861. deviceLock.lock();
  862. result = d3d11Device->CreateRenderTargetView(
  863. (ID3D11Texture2D*)*d11Textur, &renderTargetViewDesc, &texturRtView);
  864. deviceLock.unlock();
  865. if (result != S_OK)
  866. throw "could not create render target view for given texture";
  867. deviceLock.lock();
  868. d3d11Context->OMSetRenderTargets(1, &texturRtView, txtDsView);
  869. float color[4] = {0, 0, 0, 0};
  870. d3d11Context->ClearRenderTargetView(texturRtView, color);
  871. d3d11Context->ClearDepthStencilView(
  872. txtDsView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1, 0);
  873. deviceLock.unlock();
  874. renderKamera(zKamera);
  875. result = d3d11SpawChain->Present(0, 0);
  876. if (result != S_OK) throw "could not present the rendered content";
  877. deviceLock.lock();
  878. d3d11Context->OMSetRenderTargets(1, &rtview, dsView);
  879. deviceLock.unlock();
  880. texturRtView->Release();
  881. txtDsView->Release();
  882. txtDepthStencilBuffer->Release();
  883. }
  884. void DirectX11::presentFrame()
  885. {
  886. // Set the depth stencil state.
  887. deviceLock.lock();
  888. d3d11Context->OMSetDepthStencilState(depthDisabledStencilState, 1);
  889. deviceLock.unlock();
  890. uiTexture->updateTextur();
  891. deviceLock.lock();
  892. d3d11Context->RSSetViewports(1, vp);
  893. deviceLock.unlock();
  894. float screenAspect = (float)backBufferSize.x / (float)backBufferSize.y;
  895. Mat4<float> view
  896. = view.translation(Vec3<float>(0.f, 0.f, backBufferSize.y * 1.2075f));
  897. viewAndProj[0] = view;
  898. viewAndProj[1]
  899. = view.projektion((float)PI / 4.0f, screenAspect, 0.1f, 10000.f);
  900. kamPos = Vec3<float>(0.f, 0.f, backBufferSize.y * 1.2075f);
  901. if (vertexShader)
  902. vertexShader->fillConstBuffer(
  903. (char*)viewAndProj, 1, sizeof(Mat4<float>) * 2);
  904. if (pixelShader)
  905. pixelShader->fillConstBuffer((char*)&kamPos, 0, sizeof(float) * 3);
  906. if (fenster && !IsIconic(fenster->getWindowHandle()))
  907. renderObject(texturModel);
  908. HRESULT result = d3d11SpawChain->Present(0, 0);
  909. if (!SUCCEEDED(result))
  910. {
  911. deviceLock.lock();
  912. HRESULT res = d3d11Device->GetDeviceRemovedReason();
  913. deviceLock.unlock();
  914. WMessageBox(fenster ? fenster->getWindowHandle() : 0,
  915. new Text("Fehler"),
  916. new Text("Es ist ein Fehler beim rendern aufgetreten."),
  917. MB_ICONERROR);
  918. }
  919. }
  920. Image* DirectX11::zUIRenderImage() const
  921. {
  922. return uiTexture->zImage();
  923. }
  924. Texture* DirectX11::createOrGetTexture(
  925. const char* name, Image* b, TextureDirection dir)
  926. {
  927. if (!d3d11Device)
  928. {
  929. if (b) b->release();
  930. return 0;
  931. }
  932. if (texturRegister->hasTexture(name))
  933. {
  934. Texture* ret = texturRegister->getTexture(name);
  935. if (b) ret->setImageZ(b);
  936. return ret;
  937. }
  938. Texture* ret = new DX11Texture(d3d11Device, d3d11Context, deviceLock, dir);
  939. if (b) ret->setImageZ(b);
  940. texturRegister->addTexture(dynamic_cast<Texture*>(ret->getThis()), name);
  941. return ret;
  942. }
  943. typedef HRESULT(__stdcall* CreateDXGIFactory2Function)(UINT, REFIID, void**);
  944. typedef HRESULT(__stdcall* D3D11CreateDeviceFunction)(IDXGIAdapter*,
  945. D3D_DRIVER_TYPE,
  946. HMODULE,
  947. UINT,
  948. D3D_FEATURE_LEVEL*,
  949. UINT,
  950. UINT,
  951. ID3D11Device**,
  952. D3D_FEATURE_LEVEL*,
  953. ID3D11DeviceContext**);
  954. bool DirectX11::isAvailable()
  955. {
  956. HINSTANCE dxgiDLL = getDLLRegister()->loadDLL("dxgi.dll", "dxgi.dll");
  957. if (!dxgiDLL) return 0;
  958. HINSTANCE d3d11DLL = getDLLRegister()->loadDLL("d3d11.dll", "d3d11.dll");
  959. if (!d3d11DLL)
  960. {
  961. getDLLRegister()->releaseDLL("dxgi.dll");
  962. return 0;
  963. }
  964. CreateDXGIFactory2Function createFactory
  965. = (CreateDXGIFactory2Function)GetProcAddress(
  966. dxgiDLL, "CreateDXGIFactory2");
  967. if (!createFactory)
  968. {
  969. getDLLRegister()->releaseDLL("dxgi.dll");
  970. getDLLRegister()->releaseDLL("d3d11.dll");
  971. return 0;
  972. }
  973. D3D11CreateDeviceFunction createDevice
  974. = (D3D11CreateDeviceFunction)GetProcAddress(
  975. d3d11DLL, "D3D11CreateDevice");
  976. if (!createDevice)
  977. {
  978. getDLLRegister()->releaseDLL("dxgi.dll");
  979. getDLLRegister()->releaseDLL("d3d11.dll");
  980. return 0;
  981. }
  982. IDXGIFactory4* factory;
  983. UINT createFactoryFlags = 0;
  984. #if defined(_DEBUG)
  985. createFactoryFlags = DXGI_CREATE_FACTORY_DEBUG;
  986. #endif
  987. HRESULT res = createFactory(
  988. createFactoryFlags, __uuidof(IDXGIFactory4), (void**)&factory);
  989. if (FAILED(res))
  990. {
  991. getDLLRegister()->releaseDLL("dxgi.dll");
  992. getDLLRegister()->releaseDLL("d3d11.dll");
  993. return 0;
  994. }
  995. int index = 0;
  996. UINT flag = 0;
  997. #ifdef _DEBUG
  998. flag |= D3D11_CREATE_DEVICE_DEBUG;
  999. #endif
  1000. do
  1001. {
  1002. IDXGIAdapter1* current;
  1003. res = factory->EnumAdapters1(index++, &current);
  1004. if (res == S_OK)
  1005. {
  1006. DXGI_ADAPTER_DESC1 dxgiAdapterDesc1;
  1007. current->GetDesc1(&dxgiAdapterDesc1);
  1008. ID3D11Device* device = 0;
  1009. ID3D11DeviceContext* context = 0;
  1010. D3D_FEATURE_LEVEL level = D3D_FEATURE_LEVEL_11_0;
  1011. if ((dxgiAdapterDesc1.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0
  1012. && SUCCEEDED(createDevice(current,
  1013. D3D_DRIVER_TYPE_UNKNOWN,
  1014. 0,
  1015. flag,
  1016. &level,
  1017. 1,
  1018. D3D11_SDK_VERSION,
  1019. &device,
  1020. 0,
  1021. &context)))
  1022. {
  1023. context->Release();
  1024. device->Release();
  1025. current->Release();
  1026. factory->Release();
  1027. getDLLRegister()->releaseDLL("dxgi.dll");
  1028. getDLLRegister()->releaseDLL("d3d11.dll");
  1029. return 1;
  1030. }
  1031. current->Release();
  1032. }
  1033. } while (res != DXGI_ERROR_NOT_FOUND);
  1034. factory->Release();
  1035. getDLLRegister()->releaseDLL("dxgi.dll");
  1036. getDLLRegister()->releaseDLL("d3d11.dll");
  1037. return 0;
  1038. }
  1039. DX11Buffer* DirectX11::createIndexBuffer()
  1040. {
  1041. return new DX11Buffer(sizeof(int),
  1042. d3d11Device,
  1043. d3d11Context,
  1044. D3D11_BIND_INDEX_BUFFER,
  1045. deviceLock);
  1046. }
  1047. DX11Buffer* DirectX11::createVertexBuffer()
  1048. {
  1049. return new DX11Buffer(sizeof(Vertex3D),
  1050. d3d11Device,
  1051. d3d11Context,
  1052. D3D11_BIND_VERTEX_BUFFER,
  1053. deviceLock);
  1054. }
  1055. DX11VertexShader* DirectX11::initializeVertexShader(
  1056. unsigned char* byteCode, int size)
  1057. {
  1058. DX11VertexShader* vertexShader
  1059. = new DX11VertexShader(d3d11Device, d3d11Context, deviceLock);
  1060. vertexShader->setCompiledByteArray(byteCode, size);
  1061. D3D11_INPUT_ELEMENT_DESC polygonLayout[5];
  1062. // Create the vertex input layout description.
  1063. // This setup needs to match the VertexType stucture in the ModelClass and
  1064. // in the shader.
  1065. polygonLayout[0].SemanticName = "POSITION";
  1066. polygonLayout[0].SemanticIndex = 0;
  1067. polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
  1068. polygonLayout[0].InputSlot = 0;
  1069. polygonLayout[0].AlignedByteOffset = 0;
  1070. polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1071. polygonLayout[0].InstanceDataStepRate = 0;
  1072. polygonLayout[1].SemanticName = "TEXCOORD";
  1073. polygonLayout[1].SemanticIndex = 0;
  1074. polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
  1075. polygonLayout[1].InputSlot = 0;
  1076. polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  1077. polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1078. polygonLayout[1].InstanceDataStepRate = 0;
  1079. polygonLayout[2].SemanticName = "NORMAL";
  1080. polygonLayout[2].SemanticIndex = 0;
  1081. polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
  1082. polygonLayout[2].InputSlot = 0;
  1083. polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  1084. polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1085. polygonLayout[2].InstanceDataStepRate = 0;
  1086. polygonLayout[3].SemanticName = "KNOCHEN_ID";
  1087. polygonLayout[3].SemanticIndex = 0;
  1088. polygonLayout[3].Format = DXGI_FORMAT_R32_UINT;
  1089. polygonLayout[3].InputSlot = 0;
  1090. polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  1091. polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1092. polygonLayout[3].InstanceDataStepRate = 0;
  1093. polygonLayout[4].SemanticName = "VERTEX_ID";
  1094. polygonLayout[4].SemanticIndex = 0;
  1095. polygonLayout[4].Format = DXGI_FORMAT_R32_UINT;
  1096. polygonLayout[4].InputSlot = 0;
  1097. polygonLayout[4].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  1098. polygonLayout[4].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1099. polygonLayout[4].InstanceDataStepRate = 0;
  1100. vertexShader->createInputLayout(polygonLayout, 5);
  1101. vertexShader->createConstBuffer(sizeof(Mat4<float>) * MAX_KNOCHEN_ANZ,
  1102. vertexShader
  1103. ->getFirstUninitializedBufferIndex()); // matrices for skeleton
  1104. // animations
  1105. vertexShader->createConstBuffer(sizeof(Mat4<float>) * 2,
  1106. vertexShader
  1107. ->getFirstUninitializedBufferIndex()); // View and Projection Matrix
  1108. return vertexShader;
  1109. }
  1110. DX11PixelShader* DirectX11::initializePixelShader(
  1111. unsigned char* byteCode, int size)
  1112. {
  1113. DX11PixelShader* pixelShader
  1114. = new DX11PixelShader(d3d11Device, d3d11Context, deviceLock);
  1115. pixelShader->setCompiledByteArray((unsigned char*)byteCode, size);
  1116. pixelShader->createConstBuffer(sizeof(float) * 3,
  1117. pixelShader->getFirstUninitializedBufferIndex()); // Camera position
  1118. pixelShader->createConstBuffer(sizeof(float) * 3,
  1119. pixelShader->getFirstUninitializedBufferIndex()); // material constants
  1120. // using phong model
  1121. pixelShader->createConstBuffer(
  1122. sizeof(int) * 2, pixelShader->getFirstUninitializedBufferIndex());
  1123. pixelShader->createConstBuffer(
  1124. sizeof(TextureEffect), pixelShader->getFirstUninitializedBufferIndex());
  1125. // TODO: Remove Following Test Code
  1126. int lc[] = {0, 0};
  1127. pixelShader->fillConstBuffer((char*)lc, 2, sizeof(int) * 2);
  1128. TextureEffect e = {0, 0.f};
  1129. pixelShader->fillConstBuffer((char*)&e, 3, sizeof(TextureEffect));
  1130. return pixelShader;
  1131. }
  1132. ID3D11DeviceContext* DirectX11::zContext()
  1133. {
  1134. return d3d11Context;
  1135. }
  1136. DXBuffer* DirectX11::createStructuredBuffer(int eSize)
  1137. {
  1138. return new DX11StructuredBuffer(
  1139. eSize, d3d11Device, d3d11Context, deviceLock);
  1140. }
  1141. Model3DData* DirectX11::createModel(const char* name)
  1142. {
  1143. Model3DData* result = GraphicsApi::createModel(name);
  1144. lastModelId = result->getId();
  1145. if (result)
  1146. {
  1147. DX11Buffer** newIndexBuffers = new DX11Buffer*[lastModelId + 1];
  1148. DX11Buffer** newVertexBuffers = new DX11Buffer*[lastModelId + 1];
  1149. memcpy(
  1150. newIndexBuffers, indexBuffers, sizeof(DX11Buffer*) * lastModelId);
  1151. memcpy(
  1152. newVertexBuffers, vertexBuffers, sizeof(DX11Buffer*) * lastModelId);
  1153. indexBuffers[lastModelId] = createIndexBuffer();
  1154. vertexBuffers[lastModelId] = createVertexBuffer();
  1155. }
  1156. return result;
  1157. }