DX11GraphicsApi.cpp 43 KB

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