gfxD3D11Device.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2015 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "console/console.h"
  23. #include "core/stream/fileStream.h"
  24. #include "core/strings/unicode.h"
  25. #include "core/util/journal/process.h"
  26. #include "gfx/D3D11/gfxD3D11Device.h"
  27. #include "gfx/D3D11/gfxD3D11CardProfiler.h"
  28. #include "gfx/D3D11/gfxD3D11VertexBuffer.h"
  29. #include "gfx/D3D11/gfxD3D11EnumTranslate.h"
  30. #include "gfx/D3D11/gfxD3D11QueryFence.h"
  31. #include "gfx/D3D11/gfxD3D11OcclusionQuery.h"
  32. #include "gfx/D3D11/gfxD3D11Shader.h"
  33. #include "gfx/D3D11/gfxD3D11Target.h"
  34. #include "platformWin32/platformWin32.h"
  35. #include "windowManager/win32/win32Window.h"
  36. #include "windowManager/platformWindow.h"
  37. #include "gfx/D3D11/screenshotD3D11.h"
  38. #include "materials/shaderData.h"
  39. #include "shaderGen/shaderGen.h"
  40. #ifdef TORQUE_DEBUG
  41. #include "d3d11sdklayers.h"
  42. #endif
  43. #pragma comment(lib, "dxgi.lib")
  44. #pragma comment(lib, "d3d11.lib")
  45. class GFXPCD3D11RegisterDevice
  46. {
  47. public:
  48. GFXPCD3D11RegisterDevice()
  49. {
  50. GFXInit::getRegisterDeviceSignal().notify(&GFXD3D11Device::enumerateAdapters);
  51. }
  52. };
  53. static GFXPCD3D11RegisterDevice pPCD3D11RegisterDevice;
  54. //-----------------------------------------------------------------------------
  55. /// Parse command line arguments for window creation
  56. //-----------------------------------------------------------------------------
  57. static void sgPCD3D11DeviceHandleCommandLine(S32 argc, const char **argv)
  58. {
  59. // useful to pass parameters by command line for d3d (e.g. -dx9 -dx11)
  60. for (U32 i = 1; i < argc; i++)
  61. {
  62. argv[i];
  63. }
  64. }
  65. // Register the command line parsing hook
  66. static ProcessRegisterCommandLine sgCommandLine(sgPCD3D11DeviceHandleCommandLine);
  67. GFXAdapter::CreateDeviceInstanceDelegate GFXD3D11Device::mCreateDeviceInstance(GFXD3D11Device::createInstance);
  68. GFXDevice *GFXD3D11Device::createInstance(U32 adapterIndex)
  69. {
  70. GFXD3D11Device* dev = new GFXD3D11Device(adapterIndex);
  71. return dev;
  72. }
  73. GFXD3D11Device::GFXD3D11Device(U32 index)
  74. {
  75. mDeviceSwizzle32 = &Swizzles::bgra;
  76. GFXVertexColor::setSwizzle(mDeviceSwizzle32);
  77. mDeviceSwizzle24 = &Swizzles::bgr;
  78. mAdapterIndex = index;
  79. mD3DDevice = NULL;
  80. mD3DDeviceContext = NULL;
  81. mD3DDevice1 = NULL;
  82. mD3DDeviceContext1 = NULL;
  83. mUserAnnotation = NULL;
  84. mVolatileVB = NULL;
  85. mCurrentPB = NULL;
  86. mDynamicPB = NULL;
  87. mLastVertShader = NULL;
  88. mLastPixShader = NULL;
  89. mCanCurrentlyRender = false;
  90. mTextureManager = NULL;
  91. mCurrentStateBlock = NULL;
  92. mResourceListHead = NULL;
  93. mPixVersion = 0.0;
  94. mVertexShaderTarget = String::EmptyString;
  95. mPixelShaderTarget = String::EmptyString;
  96. mShaderModel = String::EmptyString;
  97. mDrawInstancesCount = 0;
  98. mCardProfiler = NULL;
  99. mDeviceDepthStencil = NULL;
  100. mDeviceBackbuffer = NULL;
  101. mDeviceBackBufferView = NULL;
  102. mDeviceDepthStencilView = NULL;
  103. mCreateFenceType = -1; // Unknown, test on first allocate
  104. mCurrentConstBuffer = NULL;
  105. mOcclusionQuerySupported = false;
  106. mCbufferPartialSupported = false;
  107. mDebugLayers = false;
  108. for (U32 i = 0; i < GS_COUNT; ++i)
  109. mModelViewProjSC[i] = NULL;
  110. // Set up the Enum translation tables
  111. GFXD3D11EnumTranslate::init();
  112. }
  113. GFXD3D11Device::~GFXD3D11Device()
  114. {
  115. // Release our refcount on the current stateblock object
  116. mCurrentStateBlock = NULL;
  117. releaseDefaultPoolResources();
  118. mD3DDeviceContext->ClearState();
  119. mD3DDeviceContext->Flush();
  120. // Free the sampler states
  121. SamplerMap::Iterator sampIter = mSamplersMap.begin();
  122. for (; sampIter != mSamplersMap.end(); ++sampIter)
  123. SAFE_RELEASE(sampIter->value);
  124. // Free the vertex declarations.
  125. VertexDeclMap::Iterator iter = mVertexDecls.begin();
  126. for (; iter != mVertexDecls.end(); ++iter)
  127. delete iter->value;
  128. // Forcibly clean up the pools
  129. mVolatileVBList.setSize(0);
  130. mDynamicPB = NULL;
  131. // And release our D3D resources.
  132. SAFE_RELEASE(mDeviceDepthStencilView);
  133. SAFE_RELEASE(mDeviceBackBufferView);
  134. SAFE_RELEASE(mDeviceDepthStencil);
  135. SAFE_RELEASE(mDeviceBackbuffer);
  136. SAFE_RELEASE(mUserAnnotation);
  137. SAFE_RELEASE(mD3DDeviceContext1);
  138. SAFE_RELEASE(mD3DDeviceContext);
  139. SAFE_DELETE(mCardProfiler);
  140. SAFE_DELETE(gScreenShot);
  141. #ifdef TORQUE_DEBUG
  142. if (mDebugLayers)
  143. {
  144. ID3D11Debug *pDebug = NULL;
  145. mD3DDevice->QueryInterface(IID_PPV_ARGS(&pDebug));
  146. AssertFatal(pDebug, "~GFXD3D11Device- Failed to get debug layer");
  147. pDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
  148. SAFE_RELEASE(pDebug);
  149. }
  150. #endif
  151. SAFE_RELEASE(mSwapChain);
  152. SAFE_RELEASE(mD3DDevice1);
  153. SAFE_RELEASE(mD3DDevice);
  154. }
  155. GFXFormat GFXD3D11Device::selectSupportedFormat(GFXTextureProfile *profile, const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter)
  156. {
  157. U32 features = 0;
  158. if(texture)
  159. features |= D3D11_FORMAT_SUPPORT_TEXTURE2D;
  160. if(mustblend)
  161. features |= D3D11_FORMAT_SUPPORT_BLENDABLE;
  162. if(mustfilter)
  163. features |= D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;
  164. for(U32 i = 0; i < formats.size(); i++)
  165. {
  166. if(GFXD3D11TextureFormat[formats[i]] == DXGI_FORMAT_UNKNOWN)
  167. continue;
  168. U32 supportFlag = 0;
  169. mD3DDevice->CheckFormatSupport(GFXD3D11TextureFormat[formats[i]],&supportFlag);
  170. if(supportFlag & features)
  171. return formats[i];
  172. }
  173. return GFXFormatR8G8B8A8;
  174. }
  175. DXGI_SWAP_CHAIN_DESC GFXD3D11Device::setupPresentParams(const GFXVideoMode &mode, const HWND &hwnd)
  176. {
  177. DXGI_SWAP_CHAIN_DESC d3dpp;
  178. ZeroMemory(&d3dpp, sizeof(d3dpp));
  179. DXGI_SAMPLE_DESC sampleDesc;
  180. sampleDesc.Count = 1;
  181. sampleDesc.Quality = 0;
  182. mMultisampleDesc = sampleDesc;
  183. d3dpp.BufferCount = !smDisableVSync ? 2 : 1; // triple buffering when vsync is on.
  184. d3dpp.BufferDesc.Width = mode.resolution.x;
  185. d3dpp.BufferDesc.Height = mode.resolution.y;
  186. d3dpp.BufferDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  187. d3dpp.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  188. d3dpp.OutputWindow = hwnd;
  189. d3dpp.SampleDesc = sampleDesc;
  190. d3dpp.Windowed = !mode.fullScreen;
  191. d3dpp.BufferDesc.RefreshRate.Numerator = mode.refreshRate;
  192. d3dpp.BufferDesc.RefreshRate.Denominator = 1;
  193. d3dpp.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  194. if (mode.fullScreen)
  195. {
  196. d3dpp.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED;
  197. d3dpp.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  198. d3dpp.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
  199. }
  200. return d3dpp;
  201. }
  202. void GFXD3D11Device::enumerateAdapters(Vector<GFXAdapter*> &adapterList)
  203. {
  204. IDXGIAdapter1* EnumAdapter;
  205. IDXGIFactory1* DXGIFactory;
  206. CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
  207. for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
  208. {
  209. GFXAdapter *toAdd = new GFXAdapter;
  210. toAdd->mType = Direct3D11;
  211. toAdd->mIndex = adapterIndex;
  212. toAdd->mCreateDeviceInstanceDelegate = mCreateDeviceInstance;
  213. toAdd->mShaderModel = 5.0f;
  214. DXGI_ADAPTER_DESC1 desc;
  215. EnumAdapter->GetDesc1(&desc);
  216. // LUID identifies adapter for oculus rift
  217. dMemcpy(&toAdd->mLUID, &desc.AdapterLuid, sizeof(toAdd->mLUID));
  218. size_t size=wcslen(desc.Description);
  219. char *str = new char[size+1];
  220. wcstombs(str, desc.Description,size);
  221. str[size]='\0';
  222. String Description=str;
  223. SAFE_DELETE_ARRAY(str);
  224. dStrncpy(toAdd->mName, Description.c_str(), GFXAdapter::MaxAdapterNameLen);
  225. dStrncat(toAdd->mName, " (D3D11)", GFXAdapter::MaxAdapterNameLen);
  226. IDXGIOutput* pOutput = NULL;
  227. HRESULT hr;
  228. hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
  229. if(hr == DXGI_ERROR_NOT_FOUND)
  230. {
  231. SAFE_RELEASE(EnumAdapter);
  232. break;
  233. }
  234. if(FAILED(hr))
  235. AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> EnumOutputs call failure");
  236. UINT numModes = 0;
  237. DXGI_MODE_DESC* displayModes = NULL;
  238. DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  239. // Get the number of elements
  240. hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
  241. if(FAILED(hr))
  242. AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
  243. displayModes = new DXGI_MODE_DESC[numModes];
  244. // Get the list
  245. hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
  246. if(FAILED(hr))
  247. AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure");
  248. for(U32 numMode = 0; numMode < numModes; ++numMode)
  249. {
  250. GFXVideoMode vmAdd;
  251. vmAdd.fullScreen = true;
  252. vmAdd.bitDepth = 32;
  253. vmAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
  254. vmAdd.resolution.x = displayModes[numMode].Width;
  255. vmAdd.resolution.y = displayModes[numMode].Height;
  256. toAdd->mAvailableModes.push_back(vmAdd);
  257. }
  258. //Check adapater can handle feature level 10
  259. D3D_FEATURE_LEVEL deviceFeature;
  260. ID3D11Device *pTmpDevice = nullptr;
  261. // Create temp Direct3D11 device.
  262. bool suitable = true;
  263. UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  264. hr = D3D11CreateDevice(EnumAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, createDeviceFlags, NULL, 0, D3D11_SDK_VERSION, &pTmpDevice, &deviceFeature, NULL);
  265. if (FAILED(hr))
  266. suitable = false;
  267. if (deviceFeature < D3D_FEATURE_LEVEL_10_0)
  268. suitable = false;
  269. //double check we support required bgra format for LEVEL_10_0 & LEVEL_10_1
  270. if (deviceFeature == D3D_FEATURE_LEVEL_10_0 || deviceFeature == D3D_FEATURE_LEVEL_10_1)
  271. {
  272. U32 formatSupported = 0;
  273. pTmpDevice->CheckFormatSupport(DXGI_FORMAT_B8G8R8A8_UNORM, &formatSupported);
  274. U32 flagsRequired = D3D11_FORMAT_SUPPORT_RENDER_TARGET | D3D11_FORMAT_SUPPORT_DISPLAY;
  275. if (!(formatSupported && flagsRequired))
  276. {
  277. Con::printf("DXGI adapter: %s does not support BGRA", Description.c_str());
  278. suitable = false;
  279. }
  280. }
  281. delete[] displayModes;
  282. SAFE_RELEASE(pTmpDevice);
  283. SAFE_RELEASE(pOutput);
  284. SAFE_RELEASE(EnumAdapter);
  285. if (suitable)
  286. {
  287. adapterList.push_back(toAdd);
  288. }
  289. else
  290. {
  291. Con::printf("DXGI adapter: %s does not support D3D11 feature level 10 or better", Description.c_str());
  292. delete toAdd;
  293. }
  294. }
  295. SAFE_RELEASE(DXGIFactory);
  296. }
  297. void GFXD3D11Device::enumerateVideoModes()
  298. {
  299. mVideoModes.clear();
  300. IDXGIAdapter1* EnumAdapter;
  301. IDXGIFactory1* DXGIFactory;
  302. HRESULT hr;
  303. hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&DXGIFactory));
  304. if (FAILED(hr))
  305. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> CreateDXGIFactory1 call failure");
  306. for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex)
  307. {
  308. IDXGIOutput* pOutput = NULL;
  309. hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput);
  310. if(hr == DXGI_ERROR_NOT_FOUND)
  311. {
  312. SAFE_RELEASE(EnumAdapter);
  313. break;
  314. }
  315. if(FAILED(hr))
  316. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> EnumOutputs call failure");
  317. UINT numModes = 0;
  318. DXGI_MODE_DESC* displayModes = NULL;
  319. DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  320. // Get the number of elements
  321. hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL);
  322. if(FAILED(hr))
  323. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
  324. displayModes = new DXGI_MODE_DESC[numModes];
  325. // Get the list
  326. hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes);
  327. if(FAILED(hr))
  328. AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure");
  329. for(U32 numMode = 0; numMode < numModes; ++numMode)
  330. {
  331. GFXVideoMode toAdd;
  332. toAdd.fullScreen = false;
  333. toAdd.bitDepth = 32;
  334. toAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator;
  335. toAdd.resolution.x = displayModes[numMode].Width;
  336. toAdd.resolution.y = displayModes[numMode].Height;
  337. mVideoModes.push_back(toAdd);
  338. }
  339. delete[] displayModes;
  340. SAFE_RELEASE(pOutput);
  341. SAFE_RELEASE(EnumAdapter);
  342. }
  343. SAFE_RELEASE(DXGIFactory);
  344. }
  345. void GFXD3D11Device::init(const GFXVideoMode &mode, PlatformWindow *window)
  346. {
  347. AssertFatal(window, "GFXD3D11Device::init - must specify a window!");
  348. HWND winHwnd = (HWND)window->getSystemWindow( PlatformWindow::WindowSystem_Windows );
  349. UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  350. #ifdef TORQUE_DEBUG
  351. createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
  352. mDebugLayers = true;
  353. #endif
  354. DXGI_SWAP_CHAIN_DESC d3dpp = setupPresentParams(mode, winHwnd);
  355. // TODO support at least feature level 10 to match GL
  356. D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 };
  357. U32 nFeatureCount = ARRAYSIZE(pFeatureLevels);
  358. D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_HARDWARE;// use D3D_DRIVER_TYPE_REFERENCE for reference device
  359. // create a device, device context and swap chain using the information in the d3dpp struct
  360. HRESULT hres = D3D11CreateDeviceAndSwapChain(NULL,
  361. driverType,
  362. NULL,
  363. createDeviceFlags,
  364. pFeatureLevels,
  365. nFeatureCount,
  366. D3D11_SDK_VERSION,
  367. &d3dpp,
  368. &mSwapChain,
  369. &mD3DDevice,
  370. &mFeatureLevel,
  371. &mD3DDeviceContext);
  372. if(FAILED(hres))
  373. {
  374. #ifdef TORQUE_DEBUG
  375. //try again without debug device layer enabled
  376. createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG;
  377. hres = D3D11CreateDeviceAndSwapChain(NULL, driverType,NULL,createDeviceFlags,NULL, 0,
  378. D3D11_SDK_VERSION,
  379. &d3dpp,
  380. &mSwapChain,
  381. &mD3DDevice,
  382. &mFeatureLevel,
  383. &mD3DDeviceContext);
  384. //if we failed again than we definitely have a problem
  385. if (FAILED(hres))
  386. AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
  387. Con::warnf("GFXD3D11Device::init - Debug layers not detected!");
  388. mDebugLayers = false;
  389. #else
  390. AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!");
  391. #endif
  392. }
  393. // Grab DX 11.1 device and context if available and also ID3DUserDefinedAnnotation
  394. hres = mD3DDevice->QueryInterface(__uuidof(ID3D11Device1), reinterpret_cast<void**>(&mD3DDevice1));
  395. if (SUCCEEDED(hres))
  396. {
  397. //11.1 context
  398. mD3DDeviceContext->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&mD3DDeviceContext1));
  399. // ID3DUserDefinedAnnotation
  400. mD3DDeviceContext->QueryInterface(IID_PPV_ARGS(&mUserAnnotation));
  401. //Check what is supported, windows 7 supports very little from 11.1
  402. D3D11_FEATURE_DATA_D3D11_OPTIONS options;
  403. mD3DDevice1->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &options,
  404. sizeof(D3D11_FEATURE_DATA_D3D11_OPTIONS));
  405. //Cbuffer partial updates
  406. if (options.ConstantBufferOffsetting && options.ConstantBufferPartialUpdate)
  407. mCbufferPartialSupported = true;
  408. }
  409. //set the fullscreen state here if we need to
  410. if(mode.fullScreen)
  411. {
  412. hres = mSwapChain->SetFullscreenState(TRUE, NULL);
  413. if(FAILED(hres))
  414. {
  415. AssertFatal(false, "GFXD3D11Device::init- Failed to set fullscreen state!");
  416. }
  417. }
  418. mTextureManager = new GFXD3D11TextureManager();
  419. // Now reacquire all the resources we trashed earlier
  420. reacquireDefaultPoolResources();
  421. //set vert/pixel shader targets
  422. switch (mFeatureLevel)
  423. {
  424. case D3D_FEATURE_LEVEL_11_1:
  425. case D3D_FEATURE_LEVEL_11_0:
  426. mVertexShaderTarget = "vs_5_0";
  427. mPixelShaderTarget = "ps_5_0";
  428. mPixVersion = 5.0f;
  429. mShaderModel = "50";
  430. break;
  431. case D3D_FEATURE_LEVEL_10_1:
  432. mVertexShaderTarget = "vs_4_1";
  433. mPixelShaderTarget = "ps_4_1";
  434. mPixVersion = 4.1f;
  435. mShaderModel = "41";
  436. break;
  437. case D3D_FEATURE_LEVEL_10_0:
  438. mVertexShaderTarget = "vs_4_0";
  439. mPixelShaderTarget = "ps_4_0";
  440. mPixVersion = 4.0f;
  441. mShaderModel = "40";
  442. break;
  443. default:
  444. AssertFatal(false, "GFXD3D11Device::init - We don't support this feature level");
  445. }
  446. D3D11_QUERY_DESC queryDesc;
  447. queryDesc.Query = D3D11_QUERY_OCCLUSION;
  448. queryDesc.MiscFlags = 0;
  449. ID3D11Query *testQuery = NULL;
  450. // detect occlusion query support
  451. if (SUCCEEDED(mD3DDevice->CreateQuery(&queryDesc, &testQuery))) mOcclusionQuerySupported = true;
  452. SAFE_RELEASE(testQuery);
  453. Con::printf("Hardware occlusion query detected: %s", mOcclusionQuerySupported ? "Yes" : "No");
  454. mCardProfiler = new GFXD3D11CardProfiler();
  455. mCardProfiler->init();
  456. D3D11_TEXTURE2D_DESC desc;
  457. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  458. desc.CPUAccessFlags = 0;
  459. desc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
  460. desc.MipLevels = 1;
  461. desc.ArraySize = 1;
  462. desc.Usage = D3D11_USAGE_DEFAULT;
  463. desc.Width = mode.resolution.x;
  464. desc.Height = mode.resolution.y;
  465. desc.SampleDesc.Count =1;
  466. desc.SampleDesc.Quality =0;
  467. desc.MiscFlags = 0;
  468. HRESULT hr = mD3DDevice->CreateTexture2D(&desc, NULL, &mDeviceDepthStencil);
  469. if(FAILED(hr))
  470. {
  471. AssertFatal(false, "GFXD3D11Device::init - couldn't create device's depth-stencil surface.");
  472. }
  473. D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc;
  474. depthDesc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
  475. depthDesc.Flags =0 ;
  476. depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  477. depthDesc.Texture2D.MipSlice = 0;
  478. hr = mD3DDevice->CreateDepthStencilView(mDeviceDepthStencil, &depthDesc, &mDeviceDepthStencilView);
  479. if(FAILED(hr))
  480. {
  481. AssertFatal(false, "GFXD3D11Device::init - couldn't create depth stencil view");
  482. }
  483. hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mDeviceBackbuffer);
  484. if(FAILED(hr))
  485. AssertFatal(false, "GFXD3D11Device::init - coudln't retrieve backbuffer ref");
  486. //create back buffer view
  487. D3D11_RENDER_TARGET_VIEW_DESC RTDesc;
  488. RTDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  489. RTDesc.Texture2D.MipSlice = 0;
  490. RTDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  491. hr = mD3DDevice->CreateRenderTargetView(mDeviceBackbuffer, &RTDesc, &mDeviceBackBufferView);
  492. if(FAILED(hr))
  493. AssertFatal(false, "GFXD3D11Device::init - couldn't create back buffer target view");
  494. #ifdef TORQUE_DEBUG
  495. String backBufferName = "MainBackBuffer";
  496. String depthSteniclName = "MainDepthStencil";
  497. String backBuffViewName = "MainBackBuffView";
  498. String depthStencViewName = "MainDepthView";
  499. mDeviceBackbuffer->SetPrivateData(WKPDID_D3DDebugObjectName, backBufferName.size(), backBufferName.c_str());
  500. mDeviceDepthStencil->SetPrivateData(WKPDID_D3DDebugObjectName, depthSteniclName.size(), depthSteniclName.c_str());
  501. mDeviceDepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, depthStencViewName.size(), depthStencViewName.c_str());
  502. mDeviceBackBufferView->SetPrivateData(WKPDID_D3DDebugObjectName, backBuffViewName.size(), backBuffViewName.c_str());
  503. _suppressDebugMessages();
  504. #endif
  505. gScreenShot = new ScreenShotD3D11;
  506. mInitialized = true;
  507. deviceInited();
  508. }
  509. // Supress any debug layer messages we don't want to see
  510. void GFXD3D11Device::_suppressDebugMessages()
  511. {
  512. if (mDebugLayers)
  513. {
  514. ID3D11Debug *pDebug = NULL;
  515. if (SUCCEEDED(mD3DDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&pDebug)))
  516. {
  517. ID3D11InfoQueue *pInfoQueue = NULL;
  518. if (SUCCEEDED(pDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&pInfoQueue)))
  519. {
  520. //Disable breaking on error or corruption, this can be handy when using VS graphics debugging
  521. pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, false);
  522. pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, false);
  523. D3D11_MESSAGE_ID hide[] =
  524. {
  525. //this is harmless and no need to spam the console
  526. D3D11_MESSAGE_ID_QUERY_BEGIN_ABANDONING_PREVIOUS_RESULTS
  527. };
  528. D3D11_INFO_QUEUE_FILTER filter;
  529. memset(&filter, 0, sizeof(filter));
  530. filter.DenyList.NumIDs = _countof(hide);
  531. filter.DenyList.pIDList = hide;
  532. pInfoQueue->AddStorageFilterEntries(&filter);
  533. SAFE_RELEASE(pInfoQueue);
  534. }
  535. SAFE_RELEASE(pDebug);
  536. }
  537. }
  538. }
  539. bool GFXD3D11Device::beginSceneInternal()
  540. {
  541. mCanCurrentlyRender = true;
  542. return mCanCurrentlyRender;
  543. }
  544. GFXWindowTarget * GFXD3D11Device::allocWindowTarget(PlatformWindow *window)
  545. {
  546. AssertFatal(window,"GFXD3D11Device::allocWindowTarget - no window provided!");
  547. // Allocate the device.
  548. init(window->getVideoMode(), window);
  549. // Set up a new window target...
  550. GFXD3D11WindowTarget *gdwt = new GFXD3D11WindowTarget();
  551. gdwt->mWindow = window;
  552. gdwt->mSize = window->getClientExtent();
  553. gdwt->initPresentationParams();
  554. gdwt->registerResourceWithDevice(this);
  555. return gdwt;
  556. }
  557. GFXTextureTarget* GFXD3D11Device::allocRenderToTextureTarget()
  558. {
  559. GFXD3D11TextureTarget *targ = new GFXD3D11TextureTarget();
  560. targ->registerResourceWithDevice(this);
  561. return targ;
  562. }
  563. void GFXD3D11Device::reset(DXGI_SWAP_CHAIN_DESC &d3dpp)
  564. {
  565. if (!mD3DDevice)
  566. return;
  567. mInitialized = false;
  568. // Clean up some commonly dangling state. This helps prevents issues with
  569. // items that are destroyed by the texture manager callbacks and recreated
  570. // later, but still left bound.
  571. setVertexBuffer(NULL);
  572. setPrimitiveBuffer(NULL);
  573. for (S32 i = 0; i<getNumSamplers(); i++)
  574. setTexture(i, NULL);
  575. mD3DDeviceContext->ClearState();
  576. DXGI_MODE_DESC displayModes;
  577. displayModes.Format = d3dpp.BufferDesc.Format;
  578. displayModes.Height = d3dpp.BufferDesc.Height;
  579. displayModes.Width = d3dpp.BufferDesc.Width;
  580. displayModes.RefreshRate = d3dpp.BufferDesc.RefreshRate;
  581. displayModes.Scaling = d3dpp.BufferDesc.Scaling;
  582. displayModes.ScanlineOrdering = d3dpp.BufferDesc.ScanlineOrdering;
  583. HRESULT hr;
  584. if (!d3dpp.Windowed)
  585. {
  586. hr = mSwapChain->ResizeTarget(&displayModes);
  587. if (FAILED(hr))
  588. {
  589. AssertFatal(false, "D3D11Device::reset - failed to resize target!");
  590. }
  591. }
  592. // First release all the stuff we allocated from D3DPOOL_DEFAULT
  593. releaseDefaultPoolResources();
  594. //release the backbuffer, depthstencil, and their views
  595. SAFE_RELEASE(mDeviceBackBufferView);
  596. SAFE_RELEASE(mDeviceBackbuffer);
  597. SAFE_RELEASE(mDeviceDepthStencilView);
  598. SAFE_RELEASE(mDeviceDepthStencil);
  599. hr = mSwapChain->ResizeBuffers(d3dpp.BufferCount, d3dpp.BufferDesc.Width, d3dpp.BufferDesc.Height, d3dpp.BufferDesc.Format, d3dpp.Windowed ? 0 : DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
  600. if (FAILED(hr))
  601. {
  602. AssertFatal(false, "D3D11Device::reset - failed to resize back buffer!");
  603. }
  604. //recreate backbuffer view. depth stencil view and texture
  605. D3D11_TEXTURE2D_DESC desc;
  606. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  607. desc.CPUAccessFlags = 0;
  608. desc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
  609. desc.MipLevels = 1;
  610. desc.ArraySize = 1;
  611. desc.Usage = D3D11_USAGE_DEFAULT;
  612. desc.Width = d3dpp.BufferDesc.Width;
  613. desc.Height = d3dpp.BufferDesc.Height;
  614. desc.SampleDesc.Count = 1;
  615. desc.SampleDesc.Quality = 0;
  616. desc.MiscFlags = 0;
  617. hr = mD3DDevice->CreateTexture2D(&desc, NULL, &mDeviceDepthStencil);
  618. if (FAILED(hr))
  619. {
  620. AssertFatal(false, "GFXD3D11Device::reset - couldn't create device's depth-stencil surface.");
  621. }
  622. D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc;
  623. depthDesc.Format = GFXD3D11TextureFormat[GFXFormatD24S8];
  624. depthDesc.Flags = 0;
  625. depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  626. depthDesc.Texture2D.MipSlice = 0;
  627. hr = mD3DDevice->CreateDepthStencilView(mDeviceDepthStencil, &depthDesc, &mDeviceDepthStencilView);
  628. if (FAILED(hr))
  629. {
  630. AssertFatal(false, "GFXD3D11Device::reset - couldn't create depth stencil view");
  631. }
  632. hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mDeviceBackbuffer);
  633. if (FAILED(hr))
  634. AssertFatal(false, "GFXD3D11Device::reset - coudln't retrieve backbuffer ref");
  635. //create back buffer view
  636. D3D11_RENDER_TARGET_VIEW_DESC RTDesc;
  637. RTDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB];
  638. RTDesc.Texture2D.MipSlice = 0;
  639. RTDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  640. hr = mD3DDevice->CreateRenderTargetView(mDeviceBackbuffer, &RTDesc, &mDeviceBackBufferView);
  641. if (FAILED(hr))
  642. AssertFatal(false, "GFXD3D11Device::reset - couldn't create back buffer target view");
  643. mD3DDeviceContext->OMSetRenderTargets(1, &mDeviceBackBufferView, mDeviceDepthStencilView);
  644. hr = mSwapChain->SetFullscreenState(!d3dpp.Windowed, NULL);
  645. if (FAILED(hr))
  646. {
  647. AssertFatal(false, "D3D11Device::reset - failed to change screen states!");
  648. }
  649. //Microsoft recommend this, see DXGI documentation
  650. if (!d3dpp.Windowed)
  651. {
  652. displayModes.RefreshRate.Numerator = 0;
  653. displayModes.RefreshRate.Denominator = 0;
  654. hr = mSwapChain->ResizeTarget(&displayModes);
  655. if (FAILED(hr))
  656. {
  657. AssertFatal(false, "D3D11Device::reset - failed to resize target!");
  658. }
  659. }
  660. mInitialized = true;
  661. // Now re aquire all the resources we trashed earlier
  662. reacquireDefaultPoolResources();
  663. //set last bound shaders
  664. mD3DDeviceContext->PSSetShader(mLastPixShader, NULL, 0);
  665. mD3DDeviceContext->VSSetShader(mLastVertShader, NULL, 0);
  666. // Mark everything dirty and flush to card, for sanity.
  667. updateStates(true);
  668. }
  669. void GFXD3D11Device::setupGenericShaders(GenericShaderType type)
  670. {
  671. AssertFatal(type != GSTargetRestore, ""); //not used
  672. if(mGenericShader[GSColor] == NULL)
  673. {
  674. ShaderData *shaderData;
  675. //shader model 4.0 is enough for the generic shaders
  676. const char* shaderModel = "4.0";
  677. shaderData = new ShaderData();
  678. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/colorV.hlsl"));
  679. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/colorP.hlsl"));
  680. shaderData->setField("pixVersion", shaderModel);
  681. shaderData->registerObject();
  682. mGenericShader[GSColor] = shaderData->getShader();
  683. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  684. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle("$modelView");
  685. Sim::getRootGroup()->addObject(shaderData);
  686. shaderData = new ShaderData();
  687. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/modColorTextureV.hlsl"));
  688. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/modColorTextureP.hlsl"));
  689. shaderData->setField("pixVersion", shaderModel);
  690. shaderData->registerObject();
  691. mGenericShader[GSModColorTexture] = shaderData->getShader();
  692. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  693. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle("$modelView");
  694. Sim::getRootGroup()->addObject(shaderData);
  695. shaderData = new ShaderData();
  696. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/addColorTextureV.hlsl"));
  697. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/addColorTextureP.hlsl"));
  698. shaderData->setField("pixVersion", shaderModel);
  699. shaderData->registerObject();
  700. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  701. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  702. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle("$modelView");
  703. Sim::getRootGroup()->addObject(shaderData);
  704. shaderData = new ShaderData();
  705. shaderData->setField("DXVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/textureV.hlsl"));
  706. shaderData->setField("DXPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/textureP.hlsl"));
  707. shaderData->setField("pixVersion", shaderModel);
  708. shaderData->registerObject();
  709. mGenericShader[GSTexture] = shaderData->getShader();
  710. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  711. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle("$modelView");
  712. Sim::getRootGroup()->addObject(shaderData);
  713. //Force an update
  714. mViewportDirty = true;
  715. _updateRenderTargets();
  716. }
  717. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  718. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  719. setShader(mGenericShader[type]);
  720. setShaderConstBuffer(mGenericShaderBuffer[type]);
  721. }
  722. //-----------------------------------------------------------------------------
  723. /// Creates a state block object based on the desc passed in. This object
  724. /// represents an immutable state.
  725. GFXStateBlockRef GFXD3D11Device::createStateBlockInternal(const GFXStateBlockDesc& desc)
  726. {
  727. return GFXStateBlockRef(new GFXD3D11StateBlock(desc));
  728. }
  729. /// Activates a stateblock
  730. void GFXD3D11Device::setStateBlockInternal(GFXStateBlock* block, bool force)
  731. {
  732. AssertFatal(static_cast<GFXD3D11StateBlock*>(block), "Incorrect stateblock type for this device!");
  733. GFXD3D11StateBlock* d3dBlock = static_cast<GFXD3D11StateBlock*>(block);
  734. GFXD3D11StateBlock* d3dCurrent = static_cast<GFXD3D11StateBlock*>(mCurrentStateBlock.getPointer());
  735. if (force)
  736. d3dCurrent = NULL;
  737. d3dBlock->activate(d3dCurrent);
  738. }
  739. /// Called by base GFXDevice to actually set a const buffer
  740. void GFXD3D11Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  741. {
  742. if (buffer)
  743. {
  744. PROFILE_SCOPE(GFXD3D11Device_setShaderConstBufferInternal);
  745. AssertFatal(static_cast<GFXD3D11ShaderConstBuffer*>(buffer), "Incorrect shader const buffer type for this device!");
  746. GFXD3D11ShaderConstBuffer* d3dBuffer = static_cast<GFXD3D11ShaderConstBuffer*>(buffer);
  747. d3dBuffer->activate(mCurrentConstBuffer);
  748. mCurrentConstBuffer = d3dBuffer;
  749. }
  750. else
  751. {
  752. mCurrentConstBuffer = NULL;
  753. }
  754. }
  755. //-----------------------------------------------------------------------------
  756. void GFXD3D11Device::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
  757. {
  758. // Make sure we have flushed our render target state.
  759. _updateRenderTargets();
  760. UINT depthstencilFlag = 0;
  761. ID3D11RenderTargetView* rtView = NULL;
  762. ID3D11DepthStencilView* dsView = NULL;
  763. mD3DDeviceContext->OMGetRenderTargets(1, &rtView, &dsView);
  764. const FLOAT clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  765. if (flags & GFXClearTarget && rtView)
  766. mD3DDeviceContext->ClearRenderTargetView(rtView, clearColor);
  767. if (flags & GFXClearZBuffer)
  768. depthstencilFlag |= D3D11_CLEAR_DEPTH;
  769. if (flags & GFXClearStencil)
  770. depthstencilFlag |= D3D11_CLEAR_STENCIL;
  771. if (depthstencilFlag && dsView)
  772. mD3DDeviceContext->ClearDepthStencilView(dsView, depthstencilFlag, z, stencil);
  773. SAFE_RELEASE(rtView);
  774. SAFE_RELEASE(dsView);
  775. }
  776. void GFXD3D11Device::endSceneInternal()
  777. {
  778. mCanCurrentlyRender = false;
  779. }
  780. void GFXD3D11Device::_updateRenderTargets()
  781. {
  782. if (mRTDirty || (mCurrentRT && mCurrentRT->isPendingState()))
  783. {
  784. if (mRTDeactivate)
  785. {
  786. mRTDeactivate->deactivate();
  787. mRTDeactivate = NULL;
  788. }
  789. // NOTE: The render target changes are not really accurate
  790. // as the GFXTextureTarget supports MRT internally. So when
  791. // we activate a GFXTarget it could result in multiple calls
  792. // to SetRenderTarget on the actual device.
  793. mDeviceStatistics.mRenderTargetChanges++;
  794. mCurrentRT->activate();
  795. mRTDirty = false;
  796. }
  797. if (mViewportDirty)
  798. {
  799. D3D11_VIEWPORT viewport;
  800. viewport.TopLeftX = mViewport.point.x;
  801. viewport.TopLeftY = mViewport.point.y;
  802. viewport.Width = mViewport.extent.x;
  803. viewport.Height = mViewport.extent.y;
  804. viewport.MinDepth = 0.0f;
  805. viewport.MaxDepth = 1.0f;
  806. mD3DDeviceContext->RSSetViewports(1, &viewport);
  807. mViewportDirty = false;
  808. }
  809. }
  810. void GFXD3D11Device::releaseDefaultPoolResources()
  811. {
  812. // Release all the dynamic vertex buffer arrays
  813. // Forcibly clean up the pools
  814. for(U32 i=0; i<mVolatileVBList.size(); i++)
  815. {
  816. SAFE_RELEASE(mVolatileVBList[i]->vb);
  817. mVolatileVBList[i] = NULL;
  818. }
  819. mVolatileVBList.setSize(0);
  820. // We gotta clear the current const buffer else the next
  821. // activate may erroneously think the device is still holding
  822. // this state and fail to set it.
  823. mCurrentConstBuffer = NULL;
  824. // Set current VB to NULL and set state dirty
  825. for (U32 i=0; i < VERTEX_STREAM_COUNT; i++)
  826. {
  827. mCurrentVertexBuffer[i] = NULL;
  828. mVertexBufferDirty[i] = true;
  829. mVertexBufferFrequency[i] = 0;
  830. mVertexBufferFrequencyDirty[i] = true;
  831. }
  832. // Release dynamic index buffer
  833. if(mDynamicPB != NULL)
  834. {
  835. SAFE_RELEASE(mDynamicPB->ib);
  836. }
  837. // Set current PB/IB to NULL and set state dirty
  838. mCurrentPrimitiveBuffer = NULL;
  839. mCurrentPB = NULL;
  840. mPrimitiveBufferDirty = true;
  841. // Zombify texture manager (for D3D this only modifies default pool textures)
  842. if( mTextureManager )
  843. mTextureManager->zombify();
  844. // Set global dirty state so the IB/PB and VB get reset
  845. mStateDirty = true;
  846. // Walk the resource list and zombify everything.
  847. GFXResource *walk = mResourceListHead;
  848. while(walk)
  849. {
  850. walk->zombify();
  851. walk = walk->getNextResource();
  852. }
  853. }
  854. void GFXD3D11Device::reacquireDefaultPoolResources()
  855. {
  856. // Now do the dynamic index buffers
  857. if( mDynamicPB == NULL )
  858. mDynamicPB = new GFXD3D11PrimitiveBuffer(this, 0, 0, GFXBufferTypeDynamic);
  859. D3D11_BUFFER_DESC desc;
  860. desc.ByteWidth = sizeof(U16) * MAX_DYNAMIC_INDICES;
  861. desc.Usage = D3D11_USAGE_DYNAMIC;
  862. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  863. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  864. desc.MiscFlags = 0;
  865. desc.StructureByteStride = 0;
  866. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &mDynamicPB->ib);
  867. if(FAILED(hr))
  868. {
  869. AssertFatal(false, "Failed to allocate dynamic IB");
  870. }
  871. // Walk the resource list and zombify everything.
  872. GFXResource *walk = mResourceListHead;
  873. while(walk)
  874. {
  875. walk->resurrect();
  876. walk = walk->getNextResource();
  877. }
  878. if(mTextureManager)
  879. mTextureManager->resurrect();
  880. }
  881. GFXD3D11VertexBuffer* GFXD3D11Device::findVBPool( const GFXVertexFormat *vertexFormat, U32 vertsNeeded )
  882. {
  883. PROFILE_SCOPE( GFXD3D11Device_findVBPool );
  884. for( U32 i=0; i<mVolatileVBList.size(); i++ )
  885. if( mVolatileVBList[i]->mVertexFormat.isEqual( *vertexFormat ) )
  886. return mVolatileVBList[i];
  887. return NULL;
  888. }
  889. GFXD3D11VertexBuffer * GFXD3D11Device::createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize )
  890. {
  891. PROFILE_SCOPE( GFXD3D11Device_createVBPool );
  892. // this is a bit funky, but it will avoid problems with (lack of) copy constructors
  893. // with a push_back() situation
  894. mVolatileVBList.increment();
  895. StrongRefPtr<GFXD3D11VertexBuffer> newBuff;
  896. mVolatileVBList.last() = new GFXD3D11VertexBuffer();
  897. newBuff = mVolatileVBList.last();
  898. newBuff->mNumVerts = 0;
  899. newBuff->mBufferType = GFXBufferTypeVolatile;
  900. newBuff->mVertexFormat.copy( *vertexFormat );
  901. newBuff->mVertexSize = vertSize;
  902. newBuff->mDevice = this;
  903. // Requesting it will allocate it.
  904. vertexFormat->getDecl();
  905. D3D11_BUFFER_DESC desc;
  906. desc.ByteWidth = vertSize * MAX_DYNAMIC_VERTS;
  907. desc.Usage = D3D11_USAGE_DYNAMIC;
  908. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  909. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  910. desc.MiscFlags = 0;
  911. desc.StructureByteStride = 0;
  912. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &newBuff->vb);
  913. if(FAILED(hr))
  914. {
  915. AssertFatal(false, "Failed to allocate dynamic VB");
  916. }
  917. return newBuff;
  918. }
  919. //-----------------------------------------------------------------------------
  920. void GFXD3D11Device::setClipRect( const RectI &inRect )
  921. {
  922. // We transform the incoming rect by the view
  923. // matrix first, so that it can be used to pan
  924. // and scale the clip rect.
  925. //
  926. // This is currently used to take tiled screenshots.
  927. Point3F pos( inRect.point.x, inRect.point.y, 0.0f );
  928. Point3F extent( inRect.extent.x, inRect.extent.y, 0.0f );
  929. getViewMatrix().mulP( pos );
  930. getViewMatrix().mulV( extent );
  931. RectI rect( pos.x, pos.y, extent.x, extent.y );
  932. // Clip the rect against the renderable size.
  933. Point2I size = mCurrentRT->getSize();
  934. RectI maxRect(Point2I(0,0), size);
  935. rect.intersect(maxRect);
  936. mClipRect = rect;
  937. F32 l = F32( mClipRect.point.x );
  938. F32 r = F32( mClipRect.point.x + mClipRect.extent.x );
  939. F32 b = F32( mClipRect.point.y + mClipRect.extent.y );
  940. F32 t = F32( mClipRect.point.y );
  941. // Set up projection matrix,
  942. static Point4F pt;
  943. pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f);
  944. mTempMatrix.setColumn(0, pt);
  945. pt.set(0.0f, 2.0f/(t - b), 0.0f, 0.0f);
  946. mTempMatrix.setColumn(1, pt);
  947. pt.set(0.0f, 0.0f, 1.0f, 0.0f);
  948. mTempMatrix.setColumn(2, pt);
  949. pt.set((l+r)/(l-r), (t+b)/(b-t), 1.0f, 1.0f);
  950. mTempMatrix.setColumn(3, pt);
  951. setProjectionMatrix( mTempMatrix );
  952. // Set up world/view matrix
  953. mTempMatrix.identity();
  954. setWorldMatrix( mTempMatrix );
  955. setViewport( mClipRect );
  956. }
  957. void GFXD3D11Device::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  958. {
  959. GFXD3D11VertexBuffer *d3dBuffer = static_cast<GFXD3D11VertexBuffer*>( buffer );
  960. if ( stream == 0 )
  961. {
  962. // Set the volatile buffer which is used to
  963. // offset the start index when doing draw calls.
  964. if ( d3dBuffer && d3dBuffer->mVolatileStart > 0 )
  965. mVolatileVB = d3dBuffer;
  966. else
  967. mVolatileVB = NULL;
  968. }
  969. // NOTE: We do not use the stream offset here for stream 0
  970. // as that feature is *supposedly* not as well supported as
  971. // using the start index in drawPrimitive.
  972. //
  973. // If we can verify that this is not the case then we should
  974. // start using this method exclusively for all streams.
  975. U32 strides[1] = { d3dBuffer ? d3dBuffer->mVertexSize : 0 };
  976. U32 offset = d3dBuffer && stream != 0 ? d3dBuffer->mVolatileStart * d3dBuffer->mVertexSize : 0;
  977. ID3D11Buffer* buff = d3dBuffer ? d3dBuffer->vb : NULL;
  978. getDeviceContext()->IASetVertexBuffers(stream, 1, &buff, strides, &offset);
  979. }
  980. void GFXD3D11Device::setVertexStreamFrequency( U32 stream, U32 frequency )
  981. {
  982. if (stream == 0)
  983. mDrawInstancesCount = frequency; // instances count
  984. }
  985. void GFXD3D11Device::_setPrimitiveBuffer( GFXPrimitiveBuffer *buffer )
  986. {
  987. mCurrentPB = static_cast<GFXD3D11PrimitiveBuffer *>( buffer );
  988. mD3DDeviceContext->IASetIndexBuffer(mCurrentPB->ib, DXGI_FORMAT_R16_UINT, 0);
  989. }
  990. U32 GFXD3D11Device::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  991. {
  992. switch (primType)
  993. {
  994. case GFXPointList:
  995. return primitiveCount;
  996. break;
  997. case GFXLineList:
  998. return primitiveCount * 2;
  999. break;
  1000. case GFXLineStrip:
  1001. return primitiveCount + 1;
  1002. break;
  1003. case GFXTriangleList:
  1004. return primitiveCount * 3;
  1005. break;
  1006. case GFXTriangleStrip:
  1007. return 2 + primitiveCount;
  1008. break;
  1009. default:
  1010. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  1011. break;
  1012. }
  1013. return 0;
  1014. }
  1015. void GFXD3D11Device::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  1016. {
  1017. // This is done to avoid the function call overhead if possible
  1018. if( mStateDirty )
  1019. updateStates();
  1020. if (mCurrentShaderConstBuffer)
  1021. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  1022. if ( mVolatileVB )
  1023. vertexStart += mVolatileVB->mVolatileStart;
  1024. mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]);
  1025. if ( mDrawInstancesCount )
  1026. mD3DDeviceContext->DrawInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, vertexStart, 0);
  1027. else
  1028. mD3DDeviceContext->Draw(primCountToIndexCount(primType, primitiveCount), vertexStart);
  1029. mDeviceStatistics.mDrawCalls++;
  1030. if ( mVertexBufferFrequency[0] > 1 )
  1031. mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
  1032. else
  1033. mDeviceStatistics.mPolyCount += primitiveCount;
  1034. }
  1035. void GFXD3D11Device::drawIndexedPrimitive( GFXPrimitiveType primType,
  1036. U32 startVertex,
  1037. U32 minIndex,
  1038. U32 numVerts,
  1039. U32 startIndex,
  1040. U32 primitiveCount )
  1041. {
  1042. // This is done to avoid the function call overhead if possible
  1043. if( mStateDirty )
  1044. updateStates();
  1045. if (mCurrentShaderConstBuffer)
  1046. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  1047. AssertFatal( mCurrentPB != NULL, "Trying to call drawIndexedPrimitive with no current index buffer, call setIndexBuffer()" );
  1048. if ( mVolatileVB )
  1049. startVertex += mVolatileVB->mVolatileStart;
  1050. mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]);
  1051. if ( mDrawInstancesCount )
  1052. mD3DDeviceContext->DrawIndexedInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, mCurrentPB->mVolatileStart + startIndex, startVertex, 0);
  1053. else
  1054. mD3DDeviceContext->DrawIndexed(primCountToIndexCount(primType,primitiveCount), mCurrentPB->mVolatileStart + startIndex, startVertex);
  1055. mDeviceStatistics.mDrawCalls++;
  1056. if ( mVertexBufferFrequency[0] > 1 )
  1057. mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
  1058. else
  1059. mDeviceStatistics.mPolyCount += primitiveCount;
  1060. }
  1061. GFXShader* GFXD3D11Device::createShader()
  1062. {
  1063. GFXD3D11Shader* shader = new GFXD3D11Shader();
  1064. shader->registerResourceWithDevice( this );
  1065. return shader;
  1066. }
  1067. //-----------------------------------------------------------------------------
  1068. // Set shader - this function exists to make sure this is done in one place,
  1069. // and to make sure redundant shader states are not being
  1070. // sent to the card.
  1071. //-----------------------------------------------------------------------------
  1072. void GFXD3D11Device::setShader(GFXShader *shader, bool force)
  1073. {
  1074. if(shader)
  1075. {
  1076. GFXD3D11Shader *d3dShader = static_cast<GFXD3D11Shader*>(shader);
  1077. if (d3dShader->mPixShader != mLastPixShader || force)
  1078. {
  1079. mD3DDeviceContext->PSSetShader( d3dShader->mPixShader, NULL, 0);
  1080. mLastPixShader = d3dShader->mPixShader;
  1081. }
  1082. if (d3dShader->mVertShader != mLastVertShader || force)
  1083. {
  1084. mD3DDeviceContext->VSSetShader( d3dShader->mVertShader, NULL, 0);
  1085. mLastVertShader = d3dShader->mVertShader;
  1086. }
  1087. }
  1088. else
  1089. {
  1090. setupGenericShaders();
  1091. }
  1092. }
  1093. GFXPrimitiveBuffer * GFXD3D11Device::allocPrimitiveBuffer(U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void *data )
  1094. {
  1095. // Allocate a buffer to return
  1096. GFXD3D11PrimitiveBuffer * res = new GFXD3D11PrimitiveBuffer(this, numIndices, numPrimitives, bufferType);
  1097. // Determine usage flags
  1098. D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
  1099. // Assumptions:
  1100. // - static buffers are write once, use many
  1101. // - dynamic buffers are write many, use many
  1102. // - volatile buffers are write once, use once
  1103. // You may never read from a buffer.
  1104. //TODO: enable proper support for D3D11_USAGE_IMMUTABLE
  1105. switch(bufferType)
  1106. {
  1107. case GFXBufferTypeImmutable:
  1108. case GFXBufferTypeStatic:
  1109. usage = D3D11_USAGE_DEFAULT; //D3D11_USAGE_IMMUTABLE;
  1110. break;
  1111. case GFXBufferTypeDynamic:
  1112. case GFXBufferTypeVolatile:
  1113. usage = D3D11_USAGE_DYNAMIC;
  1114. break;
  1115. }
  1116. // Register resource
  1117. res->registerResourceWithDevice(this);
  1118. // Create d3d index buffer
  1119. if(bufferType == GFXBufferTypeVolatile)
  1120. {
  1121. // Get it from the pool if it's a volatile...
  1122. AssertFatal(numIndices < MAX_DYNAMIC_INDICES, "Cannot allocate that many indices in a volatile buffer, increase MAX_DYNAMIC_INDICES.");
  1123. res->ib = mDynamicPB->ib;
  1124. res->mVolatileBuffer = mDynamicPB;
  1125. }
  1126. else
  1127. {
  1128. // Otherwise, get it as a seperate buffer...
  1129. D3D11_BUFFER_DESC desc;
  1130. desc.ByteWidth = sizeof(U16) * numIndices;
  1131. desc.Usage = usage;
  1132. if(bufferType == GFXBufferTypeDynamic)
  1133. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a primitive buffer.
  1134. else
  1135. desc.CPUAccessFlags = 0;
  1136. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  1137. desc.MiscFlags = 0;
  1138. desc.StructureByteStride = 0;
  1139. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->ib);
  1140. if(FAILED(hr))
  1141. {
  1142. AssertFatal(false, "Failed to allocate an index buffer.");
  1143. }
  1144. }
  1145. if (data)
  1146. {
  1147. void* dest;
  1148. res->lock(0, numIndices, &dest);
  1149. dMemcpy(dest, data, sizeof(U16) * numIndices);
  1150. res->unlock();
  1151. }
  1152. return res;
  1153. }
  1154. GFXVertexBuffer * GFXD3D11Device::allocVertexBuffer(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize, GFXBufferType bufferType, void *data)
  1155. {
  1156. PROFILE_SCOPE( GFXD3D11Device_allocVertexBuffer );
  1157. GFXD3D11VertexBuffer *res = new GFXD3D11VertexBuffer( this,
  1158. numVerts,
  1159. vertexFormat,
  1160. vertSize,
  1161. bufferType );
  1162. // Determine usage flags
  1163. D3D11_USAGE usage = D3D11_USAGE_DEFAULT;
  1164. res->mNumVerts = 0;
  1165. // Assumptions:
  1166. // - static buffers are write once, use many
  1167. // - dynamic buffers are write many, use many
  1168. // - volatile buffers are write once, use once
  1169. // You may never read from a buffer.
  1170. //TODO: enable proper support for D3D11_USAGE_IMMUTABLE
  1171. switch(bufferType)
  1172. {
  1173. case GFXBufferTypeImmutable:
  1174. case GFXBufferTypeStatic:
  1175. usage = D3D11_USAGE_DEFAULT;
  1176. break;
  1177. case GFXBufferTypeDynamic:
  1178. case GFXBufferTypeVolatile:
  1179. usage = D3D11_USAGE_DYNAMIC;
  1180. break;
  1181. }
  1182. // Register resource
  1183. res->registerResourceWithDevice(this);
  1184. // Create vertex buffer
  1185. if(bufferType == GFXBufferTypeVolatile)
  1186. {
  1187. // NOTE: Volatile VBs are pooled and will be allocated at lock time.
  1188. AssertFatal(numVerts <= MAX_DYNAMIC_VERTS, "GFXD3D11Device::allocVertexBuffer - Volatile vertex buffer is too big... see MAX_DYNAMIC_VERTS!");
  1189. }
  1190. else
  1191. {
  1192. // Requesting it will allocate it.
  1193. vertexFormat->getDecl(); //-ALEX disabled to postpone until after shader is actually set...
  1194. // Get a new buffer...
  1195. D3D11_BUFFER_DESC desc;
  1196. desc.ByteWidth = vertSize * numVerts;
  1197. desc.Usage = usage;
  1198. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  1199. if(bufferType == GFXBufferTypeDynamic)
  1200. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a vertex buffer.
  1201. else
  1202. desc.CPUAccessFlags = 0;
  1203. desc.MiscFlags = 0;
  1204. desc.StructureByteStride = 0;
  1205. HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->vb);
  1206. if(FAILED(hr))
  1207. {
  1208. AssertFatal(false, "Failed to allocate VB");
  1209. }
  1210. }
  1211. res->mNumVerts = numVerts;
  1212. if (data)
  1213. {
  1214. void* dest;
  1215. res->lock(0, numVerts, &dest);
  1216. dMemcpy(dest, data, vertSize * numVerts);
  1217. res->unlock();
  1218. }
  1219. return res;
  1220. }
  1221. String GFXD3D11Device::_createTempShaderInternal(const GFXVertexFormat *vertexFormat)
  1222. {
  1223. U32 elemCount = vertexFormat->getElementCount();
  1224. //Input data
  1225. StringBuilder inputData;
  1226. inputData.append("struct VertIn {");
  1227. //Output data
  1228. StringBuilder outputData;
  1229. outputData.append("struct VertOut {");
  1230. // Shader main body data
  1231. StringBuilder mainBodyData;
  1232. //make shader
  1233. mainBodyData.append("VertOut main(VertIn IN){VertOut OUT;");
  1234. for (U32 i = 0; i < elemCount; i++)
  1235. {
  1236. const GFXVertexElement &element = vertexFormat->getElement(i);
  1237. String semantic = element.getSemantic();
  1238. String semanticOut = semantic;
  1239. String type;
  1240. if (element.isSemantic(GFXSemantic::POSITION))
  1241. {
  1242. semantic = "POSITION";
  1243. semanticOut = "SV_Position";
  1244. }
  1245. else if (element.isSemantic(GFXSemantic::NORMAL))
  1246. {
  1247. semantic = "NORMAL";
  1248. semanticOut = semantic;
  1249. }
  1250. else if (element.isSemantic(GFXSemantic::COLOR))
  1251. {
  1252. semantic = "COLOR";
  1253. semanticOut = semantic;
  1254. }
  1255. else if (element.isSemantic(GFXSemantic::TANGENT))
  1256. {
  1257. semantic = "TANGENT";
  1258. semanticOut = semantic;
  1259. }
  1260. else if (element.isSemantic(GFXSemantic::BINORMAL))
  1261. {
  1262. semantic = "BINORMAL";
  1263. semanticOut = semantic;
  1264. }
  1265. else if (element.isSemantic(GFXSemantic::BLENDINDICES))
  1266. {
  1267. semantic = String::ToString("BLENDINDICES%d", element.getSemanticIndex());
  1268. semanticOut = semantic;
  1269. }
  1270. else if (element.isSemantic(GFXSemantic::BLENDWEIGHT))
  1271. {
  1272. semantic = String::ToString("BLENDWEIGHT%d", element.getSemanticIndex());
  1273. semanticOut = semantic;
  1274. }
  1275. else
  1276. {
  1277. //Anything that falls thru to here will be a texture coord.
  1278. semantic = String::ToString("TEXCOORD%d", element.getSemanticIndex());
  1279. semanticOut = semantic;
  1280. }
  1281. switch (GFXD3D11DeclType[element.getType()])
  1282. {
  1283. case DXGI_FORMAT_R32_FLOAT:
  1284. type = "float";
  1285. break;
  1286. case DXGI_FORMAT_R32G32_FLOAT:
  1287. type = "float2";
  1288. break;
  1289. case DXGI_FORMAT_R32G32B32_FLOAT:
  1290. type = "float3";
  1291. break;
  1292. case DXGI_FORMAT_R32G32B32A32_FLOAT:
  1293. case DXGI_FORMAT_B8G8R8A8_UNORM:
  1294. case DXGI_FORMAT_R8G8B8A8_UNORM:
  1295. type = "float4";
  1296. break;
  1297. case DXGI_FORMAT_R8G8B8A8_UINT:
  1298. type = "uint4";
  1299. break;
  1300. }
  1301. StringBuilder in;
  1302. in.format("%s %s%d : %s;", type.c_str(), "var", i, semantic.c_str());
  1303. inputData.append(in.data());
  1304. //SV_Position must be float4
  1305. if (semanticOut == String("SV_Position"))
  1306. {
  1307. StringBuilder out;
  1308. out.format("float4 %s%d : %s;", "var", i, semanticOut.c_str());
  1309. outputData.append(out.data());
  1310. StringBuilder body;
  1311. body.format("OUT.%s%d = float4(IN.%s%d.xyz,1);", "var", i, "var", i);
  1312. mainBodyData.append(body.data());
  1313. }
  1314. else
  1315. {
  1316. StringBuilder out;
  1317. out.format("%s %s%d : %s;", type.c_str(), "var", i, semanticOut.c_str());
  1318. outputData.append(out.data());
  1319. StringBuilder body;
  1320. body.format("OUT.%s%d = IN.%s%d;", "var", i, "var", i);
  1321. mainBodyData.append(body.data());
  1322. }
  1323. }
  1324. inputData.append("};");
  1325. outputData.append("};");
  1326. mainBodyData.append("return OUT;}");
  1327. //final data
  1328. StringBuilder finalData;
  1329. finalData.append(inputData.data());
  1330. finalData.append(outputData.data());
  1331. finalData.append(mainBodyData.data());
  1332. return String(finalData.data());
  1333. }
  1334. GFXVertexDecl* GFXD3D11Device::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  1335. {
  1336. PROFILE_SCOPE( GFXD3D11Device_allocVertexDecl );
  1337. // First check the map... you shouldn't allocate VBs very often
  1338. // if you want performance. The map lookup should never become
  1339. // a performance bottleneck.
  1340. D3D11VertexDecl *decl = mVertexDecls[vertexFormat->getDescription()];
  1341. if ( decl )
  1342. return decl;
  1343. U32 elemCount = vertexFormat->getElementCount();
  1344. ID3DBlob* code = NULL;
  1345. // We have to generate a temporary shader here for now since the input layout creation
  1346. // expects a shader to be already compiled to verify the vertex layout structure. The problem
  1347. // is that most of the time the regular shaders are compiled AFTER allocVertexDecl is called.
  1348. if(!decl)
  1349. {
  1350. //TODO: Perhaps save/cache the ID3DBlob for later use on identical vertex formats,save creating/compiling the temp shader everytime
  1351. String shaderData = _createTempShaderInternal(vertexFormat);
  1352. #ifdef TORQUE_DEBUG
  1353. U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
  1354. #else
  1355. U32 flags = D3DCOMPILE_ENABLE_STRICTNESS;
  1356. #endif
  1357. ID3DBlob *errorBlob = NULL;
  1358. HRESULT hr = D3DCompile(shaderData.c_str(), shaderData.length(), NULL, NULL, NULL, "main", "vs_5_0", flags, 0, &code, &errorBlob);
  1359. StringBuilder error;
  1360. if(errorBlob)
  1361. {
  1362. error.append((char*)errorBlob->GetBufferPointer(), errorBlob->GetBufferSize());
  1363. AssertFatal(hr, error.data());
  1364. }
  1365. SAFE_RELEASE(errorBlob);
  1366. }
  1367. AssertFatal(code, "D3D11Device::allocVertexDecl - compiled vert shader code missing!");
  1368. // Setup the declaration struct.
  1369. U32 stream;
  1370. D3D11_INPUT_ELEMENT_DESC *vd = new D3D11_INPUT_ELEMENT_DESC[ elemCount];
  1371. S32 elemIndex = 0;
  1372. for (S32 i = 0; i < elemCount; i++, elemIndex++)
  1373. {
  1374. const GFXVertexElement &element = vertexFormat->getElement(elemIndex);
  1375. stream = element.getStreamIndex();
  1376. vd[i].InputSlot = stream;
  1377. vd[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
  1378. vd[i].Format = GFXD3D11DeclType[element.getType()];
  1379. // If instancing is enabled, the per instance data is only used on stream 1.
  1380. if (vertexFormat->hasInstancing() && stream == 1)
  1381. {
  1382. vd[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
  1383. vd[i].InstanceDataStepRate = 1;
  1384. }
  1385. else
  1386. {
  1387. vd[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
  1388. vd[i].InstanceDataStepRate = 0;
  1389. }
  1390. // We force the usage index of 0 for everything but
  1391. // texture coords for now... this may change later.
  1392. vd[i].SemanticIndex = 0;
  1393. if (element.isSemantic(GFXSemantic::POSITION))
  1394. vd[i].SemanticName = "POSITION";
  1395. else if (element.isSemantic(GFXSemantic::NORMAL))
  1396. vd[i].SemanticName = "NORMAL";
  1397. else if (element.isSemantic(GFXSemantic::COLOR))
  1398. vd[i].SemanticName = "COLOR";
  1399. else if (element.isSemantic(GFXSemantic::TANGENT))
  1400. vd[i].SemanticName = "TANGENT";
  1401. else if (element.isSemantic(GFXSemantic::BINORMAL))
  1402. vd[i].SemanticName = "BINORMAL";
  1403. else if (element.isSemantic(GFXSemantic::BLENDWEIGHT))
  1404. {
  1405. vd[i].SemanticName = "BLENDWEIGHT";
  1406. vd[i].SemanticIndex = element.getSemanticIndex();
  1407. }
  1408. else if (element.isSemantic(GFXSemantic::BLENDINDICES))
  1409. {
  1410. vd[i].SemanticName = "BLENDINDICES";
  1411. vd[i].SemanticIndex = element.getSemanticIndex();
  1412. }
  1413. else
  1414. {
  1415. //Anything that falls thru to here will be a texture coord.
  1416. vd[i].SemanticName = "TEXCOORD";
  1417. vd[i].SemanticIndex = element.getSemanticIndex();
  1418. }
  1419. }
  1420. decl = new D3D11VertexDecl();
  1421. HRESULT hr = mD3DDevice->CreateInputLayout(vd, elemCount,code->GetBufferPointer(), code->GetBufferSize(), &decl->decl);
  1422. if (FAILED(hr))
  1423. {
  1424. AssertFatal(false, "GFXD3D11Device::allocVertexDecl - Failed to create vertex input layout!");
  1425. }
  1426. delete [] vd;
  1427. SAFE_RELEASE(code);
  1428. // Store it in the cache.
  1429. mVertexDecls[vertexFormat->getDescription()] = decl;
  1430. return decl;
  1431. }
  1432. void GFXD3D11Device::setVertexDecl( const GFXVertexDecl *decl )
  1433. {
  1434. ID3D11InputLayout *dx11Decl = NULL;
  1435. if (decl)
  1436. dx11Decl = static_cast<const D3D11VertexDecl*>(decl)->decl;
  1437. mD3DDeviceContext->IASetInputLayout(dx11Decl);
  1438. }
  1439. //-----------------------------------------------------------------------------
  1440. // This function should ONLY be called from GFXDevice::updateStates() !!!
  1441. //-----------------------------------------------------------------------------
  1442. void GFXD3D11Device::setTextureInternal( U32 textureUnit, const GFXTextureObject *texture)
  1443. {
  1444. if( texture == NULL )
  1445. {
  1446. ID3D11ShaderResourceView *pView = NULL;
  1447. mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, &pView);
  1448. return;
  1449. }
  1450. GFXD3D11TextureObject *tex = (GFXD3D11TextureObject*)(texture);
  1451. mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, tex->getSRViewPtr());
  1452. }
  1453. GFXFence *GFXD3D11Device::createFence()
  1454. {
  1455. // Figure out what fence type we should be making if we don't know
  1456. if( mCreateFenceType == -1 )
  1457. {
  1458. D3D11_QUERY_DESC desc;
  1459. desc.MiscFlags = 0;
  1460. desc.Query = D3D11_QUERY_EVENT;
  1461. ID3D11Query *testQuery = NULL;
  1462. HRESULT hRes = mD3DDevice->CreateQuery(&desc, &testQuery);
  1463. if(FAILED(hRes))
  1464. {
  1465. mCreateFenceType = true;
  1466. }
  1467. else
  1468. {
  1469. mCreateFenceType = false;
  1470. }
  1471. SAFE_RELEASE(testQuery);
  1472. }
  1473. // Cool, use queries
  1474. if(!mCreateFenceType)
  1475. {
  1476. GFXFence* fence = new GFXD3D11QueryFence( this );
  1477. fence->registerResourceWithDevice(this);
  1478. return fence;
  1479. }
  1480. // CodeReview: At some point I would like a specialized implementation of
  1481. // the method used by the general fence, only without the overhead incurred
  1482. // by using the GFX constructs. Primarily the lock() method on texture handles
  1483. // will do a data copy, and this method doesn't require a copy, just a lock
  1484. // [5/10/2007 Pat]
  1485. GFXFence* fence = new GFXGeneralFence( this );
  1486. fence->registerResourceWithDevice(this);
  1487. return fence;
  1488. }
  1489. GFXOcclusionQuery* GFXD3D11Device::createOcclusionQuery()
  1490. {
  1491. GFXOcclusionQuery *query;
  1492. if (mOcclusionQuerySupported)
  1493. query = new GFXD3D11OcclusionQuery( this );
  1494. else
  1495. return NULL;
  1496. query->registerResourceWithDevice(this);
  1497. return query;
  1498. }
  1499. GFXCubemap * GFXD3D11Device::createCubemap()
  1500. {
  1501. GFXD3D11Cubemap* cube = new GFXD3D11Cubemap();
  1502. cube->registerResourceWithDevice(this);
  1503. return cube;
  1504. }
  1505. // Debug events
  1506. //------------------------------------------------------------------------------
  1507. void GFXD3D11Device::enterDebugEvent(ColorI color, const char *name)
  1508. {
  1509. if (mUserAnnotation)
  1510. {
  1511. WCHAR eventName[260];
  1512. MultiByteToWideChar(CP_ACP, 0, name, -1, eventName, 260);
  1513. mUserAnnotation->BeginEvent(eventName);
  1514. }
  1515. }
  1516. //------------------------------------------------------------------------------
  1517. void GFXD3D11Device::leaveDebugEvent()
  1518. {
  1519. if (mUserAnnotation)
  1520. mUserAnnotation->EndEvent();
  1521. }
  1522. //------------------------------------------------------------------------------
  1523. void GFXD3D11Device::setDebugMarker(ColorI color, const char *name)
  1524. {
  1525. if (mUserAnnotation)
  1526. {
  1527. WCHAR eventName[260];
  1528. MultiByteToWideChar(CP_ACP, 0, name, -1, eventName, 260);
  1529. mUserAnnotation->SetMarker(eventName);
  1530. }
  1531. }