D3D11Graphics.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Precompiled.h"
  23. #include "../../Core/Context.h"
  24. #include "../../Core/ProcessUtils.h"
  25. #include "../../Core/Profiler.h"
  26. #include "../../Graphics/ConstantBuffer.h"
  27. #include "../../Graphics/Geometry.h"
  28. #include "../../Graphics/Graphics.h"
  29. #include "../../Graphics/GraphicsEvents.h"
  30. #include "../../Graphics/GraphicsImpl.h"
  31. #include "../../Graphics/IndexBuffer.h"
  32. #include "../../Graphics/Renderer.h"
  33. #include "../../Graphics/Shader.h"
  34. #include "../../Graphics/ShaderPrecache.h"
  35. #include "../../Graphics/ShaderProgram.h"
  36. #include "../../Graphics/Texture2D.h"
  37. #include "../../Graphics/TextureCube.h"
  38. #include "../../Graphics/VertexBuffer.h"
  39. #include "../../IO/File.h"
  40. #include "../../IO/Log.h"
  41. #include "../../Resource/ResourceCache.h"
  42. #include <SDL/SDL.h>
  43. #include <SDL/SDL_syswm.h>
  44. #include "../../DebugNew.h"
  45. #ifdef _MSC_VER
  46. #pragma warning(disable:4355)
  47. #endif
  48. // Prefer the high-performance GPU on switchable GPU systems
  49. extern "C"
  50. {
  51. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  52. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  53. }
  54. namespace Urho3D
  55. {
  56. static const D3D11_COMPARISON_FUNC d3dCmpFunc[] =
  57. {
  58. D3D11_COMPARISON_ALWAYS,
  59. D3D11_COMPARISON_EQUAL,
  60. D3D11_COMPARISON_NOT_EQUAL,
  61. D3D11_COMPARISON_LESS,
  62. D3D11_COMPARISON_LESS_EQUAL,
  63. D3D11_COMPARISON_GREATER,
  64. D3D11_COMPARISON_GREATER_EQUAL
  65. };
  66. static const DWORD d3dBlendEnable[] =
  67. {
  68. FALSE,
  69. TRUE,
  70. TRUE,
  71. TRUE,
  72. TRUE,
  73. TRUE,
  74. TRUE,
  75. TRUE,
  76. TRUE
  77. };
  78. static const D3D11_BLEND d3dSrcBlend[] =
  79. {
  80. D3D11_BLEND_ONE,
  81. D3D11_BLEND_ONE,
  82. D3D11_BLEND_DEST_COLOR,
  83. D3D11_BLEND_SRC_ALPHA,
  84. D3D11_BLEND_SRC_ALPHA,
  85. D3D11_BLEND_ONE,
  86. D3D11_BLEND_INV_DEST_ALPHA,
  87. D3D11_BLEND_ONE,
  88. D3D11_BLEND_SRC_ALPHA,
  89. };
  90. static const D3D11_BLEND d3dDestBlend[] =
  91. {
  92. D3D11_BLEND_ZERO,
  93. D3D11_BLEND_ONE,
  94. D3D11_BLEND_ZERO,
  95. D3D11_BLEND_INV_SRC_ALPHA,
  96. D3D11_BLEND_ONE,
  97. D3D11_BLEND_INV_SRC_ALPHA,
  98. D3D11_BLEND_DEST_ALPHA,
  99. D3D11_BLEND_ONE,
  100. D3D11_BLEND_ONE
  101. };
  102. static const D3D11_BLEND_OP d3dBlendOp[] =
  103. {
  104. D3D11_BLEND_OP_ADD,
  105. D3D11_BLEND_OP_ADD,
  106. D3D11_BLEND_OP_ADD,
  107. D3D11_BLEND_OP_ADD,
  108. D3D11_BLEND_OP_ADD,
  109. D3D11_BLEND_OP_ADD,
  110. D3D11_BLEND_OP_ADD,
  111. D3D11_BLEND_OP_REV_SUBTRACT,
  112. D3D11_BLEND_OP_REV_SUBTRACT
  113. };
  114. static const D3D11_STENCIL_OP d3dStencilOp[] =
  115. {
  116. D3D11_STENCIL_OP_KEEP,
  117. D3D11_STENCIL_OP_ZERO,
  118. D3D11_STENCIL_OP_REPLACE,
  119. D3D11_STENCIL_OP_INCR,
  120. D3D11_STENCIL_OP_DECR
  121. };
  122. static const D3D11_CULL_MODE d3dCullMode[] =
  123. {
  124. D3D11_CULL_NONE,
  125. D3D11_CULL_BACK,
  126. D3D11_CULL_FRONT
  127. };
  128. static const D3D11_FILL_MODE d3dFillMode[] =
  129. {
  130. D3D11_FILL_SOLID,
  131. D3D11_FILL_WIREFRAME,
  132. D3D11_FILL_WIREFRAME // Point fill mode not supported
  133. };
  134. static void GetD3DPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount,
  135. D3D_PRIMITIVE_TOPOLOGY& d3dPrimitiveType)
  136. {
  137. switch (type)
  138. {
  139. case TRIANGLE_LIST:
  140. primitiveCount = elementCount / 3;
  141. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  142. break;
  143. case LINE_LIST:
  144. primitiveCount = elementCount / 2;
  145. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_LINELIST;
  146. break;
  147. case POINT_LIST:
  148. primitiveCount = elementCount;
  149. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
  150. break;
  151. case TRIANGLE_STRIP:
  152. primitiveCount = elementCount - 2;
  153. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
  154. break;
  155. case LINE_STRIP:
  156. primitiveCount = elementCount - 1;
  157. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
  158. break;
  159. case TRIANGLE_FAN:
  160. // Triangle fan is not supported on D3D11
  161. primitiveCount = 0;
  162. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
  163. break;
  164. }
  165. }
  166. static HWND GetWindowHandle(SDL_Window* window)
  167. {
  168. SDL_SysWMinfo sysInfo;
  169. SDL_VERSION(&sysInfo.version);
  170. SDL_GetWindowWMInfo(window, &sysInfo);
  171. return sysInfo.info.win.window;
  172. }
  173. const Vector2 Graphics::pixelUVOffset(0.0f, 0.0f);
  174. bool Graphics::gl3Support = false;
  175. Graphics::Graphics(Context* context) :
  176. Object(context),
  177. impl_(new GraphicsImpl()),
  178. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  179. shaderPath_("Shaders/HLSL/"),
  180. shaderExtension_(".hlsl"),
  181. orientations_("LandscapeLeft LandscapeRight"),
  182. apiName_("D3D11")
  183. {
  184. SetTextureUnitMappings();
  185. ResetCachedState();
  186. context_->RequireSDL(SDL_INIT_VIDEO);
  187. // Register Graphics library object factories
  188. RegisterGraphicsLibrary(context_);
  189. }
  190. Graphics::~Graphics()
  191. {
  192. {
  193. MutexLock lock(gpuObjectMutex_);
  194. // Release all GPU objects that still exist
  195. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  196. (*i)->Release();
  197. gpuObjects_.Clear();
  198. }
  199. impl_->vertexDeclarations_.Clear();
  200. impl_->allConstantBuffers_.Clear();
  201. for (HashMap<unsigned, ID3D11BlendState*>::Iterator i = impl_->blendStates_.Begin(); i != impl_->blendStates_.End(); ++i)
  202. {
  203. URHO3D_SAFE_RELEASE(i->second_);
  204. }
  205. impl_->blendStates_.Clear();
  206. for (HashMap<unsigned, ID3D11DepthStencilState*>::Iterator i = impl_->depthStates_.Begin(); i != impl_->depthStates_.End(); ++i)
  207. {
  208. URHO3D_SAFE_RELEASE(i->second_);
  209. }
  210. impl_->depthStates_.Clear();
  211. for (HashMap<unsigned, ID3D11RasterizerState*>::Iterator i = impl_->rasterizerStates_.Begin();
  212. i != impl_->rasterizerStates_.End(); ++i)
  213. {
  214. URHO3D_SAFE_RELEASE(i->second_);
  215. }
  216. impl_->rasterizerStates_.Clear();
  217. URHO3D_SAFE_RELEASE(impl_->defaultRenderTargetView_);
  218. URHO3D_SAFE_RELEASE(impl_->defaultDepthStencilView_);
  219. URHO3D_SAFE_RELEASE(impl_->defaultDepthTexture_);
  220. URHO3D_SAFE_RELEASE(impl_->resolveTexture_);
  221. URHO3D_SAFE_RELEASE(impl_->swapChain_);
  222. URHO3D_SAFE_RELEASE(impl_->deviceContext_);
  223. URHO3D_SAFE_RELEASE(impl_->device_);
  224. if (window_)
  225. {
  226. SDL_ShowCursor(SDL_TRUE);
  227. SDL_DestroyWindow(window_);
  228. window_ = nullptr;
  229. }
  230. delete impl_;
  231. impl_ = nullptr;
  232. context_->ReleaseSDL();
  233. }
  234. bool Graphics::SetScreenMode(int width, int height, const ScreenModeParams& params, bool maximize)
  235. {
  236. URHO3D_PROFILE(SetScreenMode);
  237. // Ensure that parameters are properly filled
  238. ScreenModeParams newParams = params;
  239. AdjustScreenMode(width, height, newParams, maximize);
  240. // Find out the full screen mode display format (match desktop color depth)
  241. SDL_DisplayMode mode;
  242. SDL_GetDesktopDisplayMode(newParams.monitor_, &mode);
  243. const DXGI_FORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? DXGI_FORMAT_B5G6R5_UNORM : DXGI_FORMAT_R8G8B8A8_UNORM;
  244. // If nothing changes, do not reset the device
  245. if (width == width_ && height == height_ && newParams == screenParams_)
  246. return true;
  247. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  248. if (!window_)
  249. {
  250. if (!OpenWindow(width, height, newParams.resizable_, newParams.borderless_))
  251. return false;
  252. }
  253. AdjustWindow(width, height, newParams.fullscreen_, newParams.borderless_, newParams.monitor_);
  254. if (maximize)
  255. {
  256. Maximize();
  257. SDL_GetWindowSize(window_, &width, &height);
  258. }
  259. const int oldMultiSample = screenParams_.multiSample_;
  260. screenParams_ = newParams;
  261. if (!impl_->device_ || screenParams_.multiSample_ != oldMultiSample)
  262. CreateDevice(width, height);
  263. UpdateSwapChain(width, height);
  264. // Clear the initial window contents to black
  265. Clear(CLEAR_COLOR);
  266. impl_->swapChain_->Present(0, 0);
  267. OnScreenModeChanged();
  268. return true;
  269. }
  270. void Graphics::SetSRGB(bool enable)
  271. {
  272. bool newEnable = enable && sRGBWriteSupport_;
  273. if (newEnable != sRGB_)
  274. {
  275. sRGB_ = newEnable;
  276. if (impl_->swapChain_)
  277. {
  278. // Recreate swap chain for the new backbuffer format
  279. CreateDevice(width_, height_);
  280. UpdateSwapChain(width_, height_);
  281. }
  282. }
  283. }
  284. void Graphics::SetDither(bool enable)
  285. {
  286. // No effect on Direct3D11
  287. }
  288. void Graphics::SetFlushGPU(bool enable)
  289. {
  290. flushGPU_ = enable;
  291. if (impl_->device_)
  292. {
  293. IDXGIDevice1* dxgiDevice;
  294. impl_->device_->QueryInterface(IID_IDXGIDevice1, (void**)&dxgiDevice);
  295. if (dxgiDevice)
  296. {
  297. dxgiDevice->SetMaximumFrameLatency(enable ? 1 : 3);
  298. dxgiDevice->Release();
  299. }
  300. }
  301. }
  302. void Graphics::SetForceGL2(bool enable)
  303. {
  304. // No effect on Direct3D11
  305. }
  306. void Graphics::Close()
  307. {
  308. if (window_)
  309. {
  310. SDL_ShowCursor(SDL_TRUE);
  311. SDL_DestroyWindow(window_);
  312. window_ = nullptr;
  313. }
  314. }
  315. bool Graphics::TakeScreenShot(Image& destImage)
  316. {
  317. URHO3D_PROFILE(TakeScreenShot);
  318. if (!impl_->device_)
  319. return false;
  320. D3D11_TEXTURE2D_DESC textureDesc;
  321. memset(&textureDesc, 0, sizeof textureDesc);
  322. textureDesc.Width = (UINT)width_;
  323. textureDesc.Height = (UINT)height_;
  324. textureDesc.MipLevels = 1;
  325. textureDesc.ArraySize = 1;
  326. textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  327. textureDesc.SampleDesc.Count = 1;
  328. textureDesc.SampleDesc.Quality = 0;
  329. textureDesc.Usage = D3D11_USAGE_STAGING;
  330. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  331. ID3D11Texture2D* stagingTexture = nullptr;
  332. HRESULT hr = impl_->device_->CreateTexture2D(&textureDesc, nullptr, &stagingTexture);
  333. if (FAILED(hr))
  334. {
  335. URHO3D_SAFE_RELEASE(stagingTexture);
  336. URHO3D_LOGD3DERROR("Could not create staging texture for screenshot", hr);
  337. return false;
  338. }
  339. ID3D11Resource* source = nullptr;
  340. impl_->defaultRenderTargetView_->GetResource(&source);
  341. if (screenParams_.multiSample_ > 1)
  342. {
  343. // If backbuffer is multisampled, need another DEFAULT usage texture to resolve the data to first
  344. CreateResolveTexture();
  345. if (!impl_->resolveTexture_)
  346. {
  347. stagingTexture->Release();
  348. source->Release();
  349. return false;
  350. }
  351. impl_->deviceContext_->ResolveSubresource(impl_->resolveTexture_, 0, source, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
  352. impl_->deviceContext_->CopyResource(stagingTexture, impl_->resolveTexture_);
  353. }
  354. else
  355. impl_->deviceContext_->CopyResource(stagingTexture, source);
  356. source->Release();
  357. D3D11_MAPPED_SUBRESOURCE mappedData;
  358. mappedData.pData = nullptr;
  359. hr = impl_->deviceContext_->Map(stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  360. if (FAILED(hr) || !mappedData.pData)
  361. {
  362. URHO3D_LOGD3DERROR("Could not map staging texture for screenshot", hr);
  363. stagingTexture->Release();
  364. return false;
  365. }
  366. destImage.SetSize(width_, height_, 3);
  367. unsigned char* destData = destImage.GetData();
  368. for (int y = 0; y < height_; ++y)
  369. {
  370. unsigned char* src = (unsigned char*)mappedData.pData + y * mappedData.RowPitch;
  371. for (int x = 0; x < width_; ++x)
  372. {
  373. *destData++ = *src++;
  374. *destData++ = *src++;
  375. *destData++ = *src++;
  376. ++src;
  377. }
  378. }
  379. impl_->deviceContext_->Unmap(stagingTexture, 0);
  380. stagingTexture->Release();
  381. return true;
  382. }
  383. bool Graphics::BeginFrame()
  384. {
  385. if (!IsInitialized())
  386. return false;
  387. // If using an external window, check it for size changes, and reset screen mode if necessary
  388. if (externalWindow_)
  389. {
  390. int width, height;
  391. SDL_GetWindowSize(window_, &width, &height);
  392. if (width != width_ || height != height_)
  393. SetMode(width, height);
  394. }
  395. else
  396. {
  397. // To prevent a loop of endless device loss and flicker, do not attempt to render when in fullscreen
  398. // and the window is minimized
  399. if (screenParams_.fullscreen_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED))
  400. return false;
  401. }
  402. // Set default rendertarget and depth buffer
  403. ResetRenderTargets();
  404. // Cleanup textures from previous frame
  405. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  406. SetTexture(i, nullptr);
  407. numPrimitives_ = 0;
  408. numBatches_ = 0;
  409. SendEvent(E_BEGINRENDERING);
  410. return true;
  411. }
  412. void Graphics::EndFrame()
  413. {
  414. if (!IsInitialized())
  415. return;
  416. {
  417. URHO3D_PROFILE(Present);
  418. SendEvent(E_ENDRENDERING);
  419. impl_->swapChain_->Present(screenParams_.vsync_ ? 1 : 0, 0);
  420. }
  421. // Clean up too large scratch buffers
  422. CleanupScratchBuffers();
  423. }
  424. void Graphics::Clear(ClearTargetFlags flags, const Color& color, float depth, unsigned stencil)
  425. {
  426. IntVector2 rtSize = GetRenderTargetDimensions();
  427. bool oldColorWrite = colorWrite_;
  428. bool oldDepthWrite = depthWrite_;
  429. // D3D11 clear always clears the whole target regardless of viewport or scissor test settings
  430. // Emulate partial clear by rendering a quad
  431. if (!viewport_.left_ && !viewport_.top_ && viewport_.right_ == rtSize.x_ && viewport_.bottom_ == rtSize.y_)
  432. {
  433. // Make sure we use the read-write version of the depth stencil
  434. SetDepthWrite(true);
  435. PrepareDraw();
  436. if ((flags & CLEAR_COLOR) && impl_->renderTargetViews_[0])
  437. impl_->deviceContext_->ClearRenderTargetView(impl_->renderTargetViews_[0], color.Data());
  438. if ((flags & (CLEAR_DEPTH | CLEAR_STENCIL)) && impl_->depthStencilView_)
  439. {
  440. unsigned depthClearFlags = 0;
  441. if (flags & CLEAR_DEPTH)
  442. depthClearFlags |= D3D11_CLEAR_DEPTH;
  443. if (flags & CLEAR_STENCIL)
  444. depthClearFlags |= D3D11_CLEAR_STENCIL;
  445. impl_->deviceContext_->ClearDepthStencilView(impl_->depthStencilView_, depthClearFlags, depth, (UINT8)stencil);
  446. }
  447. }
  448. else
  449. {
  450. Renderer* renderer = GetSubsystem<Renderer>();
  451. if (!renderer)
  452. return;
  453. Geometry* geometry = renderer->GetQuadGeometry();
  454. Matrix3x4 model = Matrix3x4::IDENTITY;
  455. Matrix4 projection = Matrix4::IDENTITY;
  456. model.m23_ = Clamp(depth, 0.0f, 1.0f);
  457. SetBlendMode(BLEND_REPLACE);
  458. SetColorWrite(flags & CLEAR_COLOR);
  459. SetCullMode(CULL_NONE);
  460. SetDepthTest(CMP_ALWAYS);
  461. SetDepthWrite(flags & CLEAR_DEPTH);
  462. SetFillMode(FILL_SOLID);
  463. SetScissorTest(false);
  464. SetStencilTest(flags & CLEAR_STENCIL, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, stencil);
  465. SetShaders(GetShader(VS, "ClearFramebuffer"), GetShader(PS, "ClearFramebuffer"));
  466. SetShaderParameter(VSP_MODEL, model);
  467. SetShaderParameter(VSP_VIEWPROJ, projection);
  468. SetShaderParameter(PSP_MATDIFFCOLOR, color);
  469. geometry->Draw(this);
  470. SetStencilTest(false);
  471. ClearParameterSources();
  472. }
  473. // Restore color & depth write state now
  474. SetColorWrite(oldColorWrite);
  475. SetDepthWrite(oldDepthWrite);
  476. }
  477. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  478. {
  479. if (!destination || !destination->GetRenderSurface())
  480. return false;
  481. URHO3D_PROFILE(ResolveToTexture);
  482. IntRect vpCopy = viewport;
  483. if (vpCopy.right_ <= vpCopy.left_)
  484. vpCopy.right_ = vpCopy.left_ + 1;
  485. if (vpCopy.bottom_ <= vpCopy.top_)
  486. vpCopy.bottom_ = vpCopy.top_ + 1;
  487. D3D11_BOX srcBox;
  488. srcBox.left = Clamp(vpCopy.left_, 0, width_);
  489. srcBox.top = Clamp(vpCopy.top_, 0, height_);
  490. srcBox.right = Clamp(vpCopy.right_, 0, width_);
  491. srcBox.bottom = Clamp(vpCopy.bottom_, 0, height_);
  492. srcBox.front = 0;
  493. srcBox.back = 1;
  494. ID3D11Resource* source = nullptr;
  495. const bool resolve = screenParams_.multiSample_ > 1;
  496. impl_->defaultRenderTargetView_->GetResource(&source);
  497. if (!resolve)
  498. {
  499. if (!srcBox.left && !srcBox.top && srcBox.right == width_ && srcBox.bottom == height_)
  500. impl_->deviceContext_->CopyResource((ID3D11Resource*)destination->GetGPUObject(), source);
  501. else
  502. impl_->deviceContext_->CopySubresourceRegion((ID3D11Resource*)destination->GetGPUObject(), 0, 0, 0, 0, source, 0, &srcBox);
  503. }
  504. else
  505. {
  506. if (!srcBox.left && !srcBox.top && srcBox.right == width_ && srcBox.bottom == height_)
  507. {
  508. impl_->deviceContext_->ResolveSubresource((ID3D11Resource*)destination->GetGPUObject(), 0, source, 0, (DXGI_FORMAT)
  509. destination->GetFormat());
  510. }
  511. else
  512. {
  513. CreateResolveTexture();
  514. if (impl_->resolveTexture_)
  515. {
  516. impl_->deviceContext_->ResolveSubresource(impl_->resolveTexture_, 0, source, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
  517. impl_->deviceContext_->CopySubresourceRegion((ID3D11Resource*)destination->GetGPUObject(), 0, 0, 0, 0, impl_->resolveTexture_, 0, &srcBox);
  518. }
  519. }
  520. }
  521. source->Release();
  522. return true;
  523. }
  524. bool Graphics::ResolveToTexture(Texture2D* texture)
  525. {
  526. if (!texture)
  527. return false;
  528. RenderSurface* surface = texture->GetRenderSurface();
  529. if (!surface)
  530. return false;
  531. texture->SetResolveDirty(false);
  532. surface->SetResolveDirty(false);
  533. ID3D11Resource* source = (ID3D11Resource*)texture->GetGPUObject();
  534. ID3D11Resource* dest = (ID3D11Resource*)texture->GetResolveTexture();
  535. if (!source || !dest)
  536. return false;
  537. impl_->deviceContext_->ResolveSubresource(dest, 0, source, 0, (DXGI_FORMAT)texture->GetFormat());
  538. return true;
  539. }
  540. bool Graphics::ResolveToTexture(TextureCube* texture)
  541. {
  542. if (!texture)
  543. return false;
  544. texture->SetResolveDirty(false);
  545. ID3D11Resource* source = (ID3D11Resource*)texture->GetGPUObject();
  546. ID3D11Resource* dest = (ID3D11Resource*)texture->GetResolveTexture();
  547. if (!source || !dest)
  548. return false;
  549. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  550. {
  551. // Resolve only the surface(s) that were actually rendered to
  552. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  553. if (!surface->IsResolveDirty())
  554. continue;
  555. surface->SetResolveDirty(false);
  556. unsigned subResource = D3D11CalcSubresource(0, i, texture->GetLevels());
  557. impl_->deviceContext_->ResolveSubresource(dest, subResource, source, subResource, (DXGI_FORMAT)texture->GetFormat());
  558. }
  559. return true;
  560. }
  561. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  562. {
  563. if (!vertexCount || !impl_->shaderProgram_)
  564. return;
  565. PrepareDraw();
  566. unsigned primitiveCount;
  567. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  568. if (fillMode_ == FILL_POINT)
  569. type = POINT_LIST;
  570. GetD3DPrimitiveType(vertexCount, type, primitiveCount, d3dPrimitiveType);
  571. if (d3dPrimitiveType != primitiveType_)
  572. {
  573. impl_->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  574. primitiveType_ = d3dPrimitiveType;
  575. }
  576. impl_->deviceContext_->Draw(vertexCount, vertexStart);
  577. numPrimitives_ += primitiveCount;
  578. ++numBatches_;
  579. }
  580. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  581. {
  582. if (!vertexCount || !impl_->shaderProgram_)
  583. return;
  584. PrepareDraw();
  585. unsigned primitiveCount;
  586. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  587. if (fillMode_ == FILL_POINT)
  588. type = POINT_LIST;
  589. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  590. if (d3dPrimitiveType != primitiveType_)
  591. {
  592. impl_->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  593. primitiveType_ = d3dPrimitiveType;
  594. }
  595. impl_->deviceContext_->DrawIndexed(indexCount, indexStart, 0);
  596. numPrimitives_ += primitiveCount;
  597. ++numBatches_;
  598. }
  599. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  600. {
  601. if (!vertexCount || !impl_->shaderProgram_)
  602. return;
  603. PrepareDraw();
  604. unsigned primitiveCount;
  605. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  606. if (fillMode_ == FILL_POINT)
  607. type = POINT_LIST;
  608. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  609. if (d3dPrimitiveType != primitiveType_)
  610. {
  611. impl_->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  612. primitiveType_ = d3dPrimitiveType;
  613. }
  614. impl_->deviceContext_->DrawIndexed(indexCount, indexStart, baseVertexIndex);
  615. numPrimitives_ += primitiveCount;
  616. ++numBatches_;
  617. }
  618. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  619. unsigned instanceCount)
  620. {
  621. if (!indexCount || !instanceCount || !impl_->shaderProgram_)
  622. return;
  623. PrepareDraw();
  624. unsigned primitiveCount;
  625. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  626. if (fillMode_ == FILL_POINT)
  627. type = POINT_LIST;
  628. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  629. if (d3dPrimitiveType != primitiveType_)
  630. {
  631. impl_->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  632. primitiveType_ = d3dPrimitiveType;
  633. }
  634. impl_->deviceContext_->DrawIndexedInstanced(indexCount, instanceCount, indexStart, 0, 0);
  635. numPrimitives_ += instanceCount * primitiveCount;
  636. ++numBatches_;
  637. }
  638. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount,
  639. unsigned instanceCount)
  640. {
  641. if (!indexCount || !instanceCount || !impl_->shaderProgram_)
  642. return;
  643. PrepareDraw();
  644. unsigned primitiveCount;
  645. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  646. if (fillMode_ == FILL_POINT)
  647. type = POINT_LIST;
  648. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  649. if (d3dPrimitiveType != primitiveType_)
  650. {
  651. impl_->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  652. primitiveType_ = d3dPrimitiveType;
  653. }
  654. impl_->deviceContext_->DrawIndexedInstanced(indexCount, instanceCount, indexStart, baseVertexIndex, 0);
  655. numPrimitives_ += instanceCount * primitiveCount;
  656. ++numBatches_;
  657. }
  658. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  659. {
  660. // Note: this is not multi-instance safe
  661. static PODVector<VertexBuffer*> vertexBuffers(1);
  662. vertexBuffers[0] = buffer;
  663. SetVertexBuffers(vertexBuffers);
  664. }
  665. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, unsigned instanceOffset)
  666. {
  667. if (buffers.Size() > MAX_VERTEX_STREAMS)
  668. {
  669. URHO3D_LOGERROR("Too many vertex buffers");
  670. return false;
  671. }
  672. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  673. {
  674. VertexBuffer* buffer = nullptr;
  675. bool changed = false;
  676. buffer = i < buffers.Size() ? buffers[i] : nullptr;
  677. if (buffer)
  678. {
  679. const PODVector<VertexElement>& elements = buffer->GetElements();
  680. // Check if buffer has per-instance data
  681. bool hasInstanceData = elements.Size() && elements[0].perInstance_;
  682. unsigned offset = hasInstanceData ? instanceOffset * buffer->GetVertexSize() : 0;
  683. if (buffer != vertexBuffers_[i] || offset != impl_->vertexOffsets_[i])
  684. {
  685. vertexBuffers_[i] = buffer;
  686. impl_->vertexBuffers_[i] = (ID3D11Buffer*)buffer->GetGPUObject();
  687. impl_->vertexSizes_[i] = buffer->GetVertexSize();
  688. impl_->vertexOffsets_[i] = offset;
  689. changed = true;
  690. }
  691. }
  692. else if (vertexBuffers_[i])
  693. {
  694. vertexBuffers_[i] = nullptr;
  695. impl_->vertexBuffers_[i] = nullptr;
  696. impl_->vertexSizes_[i] = 0;
  697. impl_->vertexOffsets_[i] = 0;
  698. changed = true;
  699. }
  700. if (changed)
  701. {
  702. impl_->vertexDeclarationDirty_ = true;
  703. if (impl_->firstDirtyVB_ == M_MAX_UNSIGNED)
  704. impl_->firstDirtyVB_ = impl_->lastDirtyVB_ = i;
  705. else
  706. {
  707. if (i < impl_->firstDirtyVB_)
  708. impl_->firstDirtyVB_ = i;
  709. if (i > impl_->lastDirtyVB_)
  710. impl_->lastDirtyVB_ = i;
  711. }
  712. }
  713. }
  714. return true;
  715. }
  716. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, unsigned instanceOffset)
  717. {
  718. return SetVertexBuffers(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), instanceOffset);
  719. }
  720. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  721. {
  722. if (buffer != indexBuffer_)
  723. {
  724. if (buffer)
  725. impl_->deviceContext_->IASetIndexBuffer((ID3D11Buffer*)buffer->GetGPUObject(),
  726. buffer->GetIndexSize() == sizeof(unsigned short) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  727. else
  728. impl_->deviceContext_->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0);
  729. indexBuffer_ = buffer;
  730. }
  731. }
  732. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  733. {
  734. // Switch to the clip plane variations if necessary
  735. if (useClipPlane_)
  736. {
  737. if (vs)
  738. vs = vs->GetOwner()->GetVariation(VS, vs->GetDefinesClipPlane());
  739. if (ps)
  740. ps = ps->GetOwner()->GetVariation(PS, ps->GetDefinesClipPlane());
  741. }
  742. if (vs == vertexShader_ && ps == pixelShader_)
  743. return;
  744. if (vs != vertexShader_)
  745. {
  746. // Create the shader now if not yet created. If already attempted, do not retry
  747. if (vs && !vs->GetGPUObject())
  748. {
  749. if (vs->GetCompilerOutput().Empty())
  750. {
  751. URHO3D_PROFILE(CompileVertexShader);
  752. bool success = vs->Create();
  753. if (!success)
  754. {
  755. URHO3D_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  756. vs = nullptr;
  757. }
  758. }
  759. else
  760. vs = nullptr;
  761. }
  762. impl_->deviceContext_->VSSetShader((ID3D11VertexShader*)(vs ? vs->GetGPUObject() : nullptr), nullptr, 0);
  763. vertexShader_ = vs;
  764. impl_->vertexDeclarationDirty_ = true;
  765. }
  766. if (ps != pixelShader_)
  767. {
  768. if (ps && !ps->GetGPUObject())
  769. {
  770. if (ps->GetCompilerOutput().Empty())
  771. {
  772. URHO3D_PROFILE(CompilePixelShader);
  773. bool success = ps->Create();
  774. if (!success)
  775. {
  776. URHO3D_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  777. ps = nullptr;
  778. }
  779. }
  780. else
  781. ps = nullptr;
  782. }
  783. impl_->deviceContext_->PSSetShader((ID3D11PixelShader*)(ps ? ps->GetGPUObject() : nullptr), nullptr, 0);
  784. pixelShader_ = ps;
  785. }
  786. // Update current shader parameters & constant buffers
  787. if (vertexShader_ && pixelShader_)
  788. {
  789. Pair<ShaderVariation*, ShaderVariation*> key = MakePair(vertexShader_, pixelShader_);
  790. ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Find(key);
  791. if (i != impl_->shaderPrograms_.End())
  792. impl_->shaderProgram_ = i->second_.Get();
  793. else
  794. {
  795. ShaderProgram* newProgram = impl_->shaderPrograms_[key] = new ShaderProgram(this, vertexShader_, pixelShader_);
  796. impl_->shaderProgram_ = newProgram;
  797. }
  798. bool vsBuffersChanged = false;
  799. bool psBuffersChanged = false;
  800. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  801. {
  802. ID3D11Buffer* vsBuffer = impl_->shaderProgram_->vsConstantBuffers_[i] ? (ID3D11Buffer*)impl_->shaderProgram_->vsConstantBuffers_[i]->
  803. GetGPUObject() : nullptr;
  804. if (vsBuffer != impl_->constantBuffers_[VS][i])
  805. {
  806. impl_->constantBuffers_[VS][i] = vsBuffer;
  807. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  808. vsBuffersChanged = true;
  809. }
  810. ID3D11Buffer* psBuffer = impl_->shaderProgram_->psConstantBuffers_[i] ? (ID3D11Buffer*)impl_->shaderProgram_->psConstantBuffers_[i]->
  811. GetGPUObject() : nullptr;
  812. if (psBuffer != impl_->constantBuffers_[PS][i])
  813. {
  814. impl_->constantBuffers_[PS][i] = psBuffer;
  815. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  816. psBuffersChanged = true;
  817. }
  818. }
  819. if (vsBuffersChanged)
  820. impl_->deviceContext_->VSSetConstantBuffers(0, MAX_SHADER_PARAMETER_GROUPS, &impl_->constantBuffers_[VS][0]);
  821. if (psBuffersChanged)
  822. impl_->deviceContext_->PSSetConstantBuffers(0, MAX_SHADER_PARAMETER_GROUPS, &impl_->constantBuffers_[PS][0]);
  823. }
  824. else
  825. impl_->shaderProgram_ = nullptr;
  826. // Store shader combination if shader dumping in progress
  827. if (shaderPrecache_)
  828. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  829. // Update clip plane parameter if necessary
  830. if (useClipPlane_)
  831. SetShaderParameter(VSP_CLIPPLANE, clipPlane_);
  832. }
  833. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  834. {
  835. HashMap<StringHash, ShaderParameter>::Iterator i;
  836. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  837. return;
  838. ConstantBuffer* buffer = i->second_.bufferPtr_;
  839. if (!buffer->IsDirty())
  840. impl_->dirtyConstantBuffers_.Push(buffer);
  841. buffer->SetParameter(i->second_.offset_, (unsigned)(count * sizeof(float)), data);
  842. }
  843. void Graphics::SetShaderParameter(StringHash param, float value)
  844. {
  845. HashMap<StringHash, ShaderParameter>::Iterator i;
  846. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  847. return;
  848. ConstantBuffer* buffer = i->second_.bufferPtr_;
  849. if (!buffer->IsDirty())
  850. impl_->dirtyConstantBuffers_.Push(buffer);
  851. buffer->SetParameter(i->second_.offset_, sizeof(float), &value);
  852. }
  853. void Graphics::SetShaderParameter(StringHash param, int value)
  854. {
  855. HashMap<StringHash, ShaderParameter>::Iterator i;
  856. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  857. return;
  858. ConstantBuffer* buffer = i->second_.bufferPtr_;
  859. if (!buffer->IsDirty())
  860. impl_->dirtyConstantBuffers_.Push(buffer);
  861. buffer->SetParameter(i->second_.offset_, sizeof(int), &value);
  862. }
  863. void Graphics::SetShaderParameter(StringHash param, bool value)
  864. {
  865. HashMap<StringHash, ShaderParameter>::Iterator i;
  866. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  867. return;
  868. ConstantBuffer* buffer = i->second_.bufferPtr_;
  869. if (!buffer->IsDirty())
  870. impl_->dirtyConstantBuffers_.Push(buffer);
  871. buffer->SetParameter(i->second_.offset_, sizeof(bool), &value);
  872. }
  873. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  874. {
  875. HashMap<StringHash, ShaderParameter>::Iterator i;
  876. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  877. return;
  878. ConstantBuffer* buffer = i->second_.bufferPtr_;
  879. if (!buffer->IsDirty())
  880. impl_->dirtyConstantBuffers_.Push(buffer);
  881. buffer->SetParameter(i->second_.offset_, sizeof(Color), &color);
  882. }
  883. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  884. {
  885. HashMap<StringHash, ShaderParameter>::Iterator i;
  886. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  887. return;
  888. ConstantBuffer* buffer = i->second_.bufferPtr_;
  889. if (!buffer->IsDirty())
  890. impl_->dirtyConstantBuffers_.Push(buffer);
  891. buffer->SetParameter(i->second_.offset_, sizeof(Vector2), &vector);
  892. }
  893. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  894. {
  895. HashMap<StringHash, ShaderParameter>::Iterator i;
  896. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  897. return;
  898. ConstantBuffer* buffer = i->second_.bufferPtr_;
  899. if (!buffer->IsDirty())
  900. impl_->dirtyConstantBuffers_.Push(buffer);
  901. buffer->SetVector3ArrayParameter(i->second_.offset_, 3, &matrix);
  902. }
  903. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  904. {
  905. HashMap<StringHash, ShaderParameter>::Iterator i;
  906. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  907. return;
  908. ConstantBuffer* buffer = i->second_.bufferPtr_;
  909. if (!buffer->IsDirty())
  910. impl_->dirtyConstantBuffers_.Push(buffer);
  911. buffer->SetParameter(i->second_.offset_, sizeof(Vector3), &vector);
  912. }
  913. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  914. {
  915. HashMap<StringHash, ShaderParameter>::Iterator i;
  916. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  917. return;
  918. ConstantBuffer* buffer = i->second_.bufferPtr_;
  919. if (!buffer->IsDirty())
  920. impl_->dirtyConstantBuffers_.Push(buffer);
  921. buffer->SetParameter(i->second_.offset_, sizeof(Matrix4), &matrix);
  922. }
  923. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  924. {
  925. HashMap<StringHash, ShaderParameter>::Iterator i;
  926. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  927. return;
  928. ConstantBuffer* buffer = i->second_.bufferPtr_;
  929. if (!buffer->IsDirty())
  930. impl_->dirtyConstantBuffers_.Push(buffer);
  931. buffer->SetParameter(i->second_.offset_, sizeof(Vector4), &vector);
  932. }
  933. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  934. {
  935. HashMap<StringHash, ShaderParameter>::Iterator i;
  936. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  937. return;
  938. ConstantBuffer* buffer = i->second_.bufferPtr_;
  939. if (!buffer->IsDirty())
  940. impl_->dirtyConstantBuffers_.Push(buffer);
  941. buffer->SetParameter(i->second_.offset_, sizeof(Matrix3x4), &matrix);
  942. }
  943. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  944. {
  945. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  946. {
  947. shaderParameterSources_[group] = source;
  948. return true;
  949. }
  950. else
  951. return false;
  952. }
  953. bool Graphics::HasShaderParameter(StringHash param)
  954. {
  955. return impl_->shaderProgram_ && impl_->shaderProgram_->parameters_.Find(param) != impl_->shaderProgram_->parameters_.End();
  956. }
  957. bool Graphics::HasTextureUnit(TextureUnit unit)
  958. {
  959. return (vertexShader_ && vertexShader_->HasTextureUnit(unit)) || (pixelShader_ && pixelShader_->HasTextureUnit(unit));
  960. }
  961. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  962. {
  963. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  964. }
  965. void Graphics::ClearParameterSources()
  966. {
  967. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  968. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  969. }
  970. void Graphics::ClearTransformSources()
  971. {
  972. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  973. shaderParameterSources_[SP_OBJECT] = (const void*)M_MAX_UNSIGNED;
  974. }
  975. void Graphics::SetTexture(unsigned index, Texture* texture)
  976. {
  977. if (index >= MAX_TEXTURE_UNITS)
  978. return;
  979. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  980. if (texture)
  981. {
  982. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  983. texture = texture->GetBackupTexture();
  984. else
  985. {
  986. // Resolve multisampled texture now as necessary
  987. if (texture->GetMultiSample() > 1 && texture->GetAutoResolve() && texture->IsResolveDirty())
  988. {
  989. if (texture->GetType() == Texture2D::GetTypeStatic())
  990. ResolveToTexture(static_cast<Texture2D*>(texture));
  991. if (texture->GetType() == TextureCube::GetTypeStatic())
  992. ResolveToTexture(static_cast<TextureCube*>(texture));
  993. }
  994. }
  995. if (texture && texture->GetLevelsDirty())
  996. texture->RegenerateLevels();
  997. }
  998. if (texture && texture->GetParametersDirty())
  999. {
  1000. texture->UpdateParameters();
  1001. textures_[index] = nullptr; // Force reassign
  1002. }
  1003. if (texture != textures_[index])
  1004. {
  1005. if (impl_->firstDirtyTexture_ == M_MAX_UNSIGNED)
  1006. impl_->firstDirtyTexture_ = impl_->lastDirtyTexture_ = index;
  1007. else
  1008. {
  1009. if (index < impl_->firstDirtyTexture_)
  1010. impl_->firstDirtyTexture_ = index;
  1011. if (index > impl_->lastDirtyTexture_)
  1012. impl_->lastDirtyTexture_ = index;
  1013. }
  1014. textures_[index] = texture;
  1015. impl_->shaderResourceViews_[index] = texture ? (ID3D11ShaderResourceView*)texture->GetShaderResourceView() : nullptr;
  1016. impl_->samplers_[index] = texture ? (ID3D11SamplerState*)texture->GetSampler() : nullptr;
  1017. impl_->texturesDirty_ = true;
  1018. }
  1019. }
  1020. void SetTextureForUpdate(Texture* texture)
  1021. {
  1022. // No-op on Direct3D11
  1023. }
  1024. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1025. {
  1026. if (mode != defaultTextureFilterMode_)
  1027. {
  1028. defaultTextureFilterMode_ = mode;
  1029. SetTextureParametersDirty();
  1030. }
  1031. }
  1032. void Graphics::SetDefaultTextureAnisotropy(unsigned level)
  1033. {
  1034. level = Max(level, 1U);
  1035. if (level != defaultTextureAnisotropy_)
  1036. {
  1037. defaultTextureAnisotropy_ = level;
  1038. SetTextureParametersDirty();
  1039. }
  1040. }
  1041. void Graphics::Restore()
  1042. {
  1043. // No-op on Direct3D11
  1044. }
  1045. void Graphics::SetTextureParametersDirty()
  1046. {
  1047. MutexLock lock(gpuObjectMutex_);
  1048. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1049. {
  1050. Texture* texture = dynamic_cast<Texture*>(*i);
  1051. if (texture)
  1052. texture->SetParametersDirty();
  1053. }
  1054. }
  1055. void Graphics::ResetRenderTargets()
  1056. {
  1057. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1058. SetRenderTarget(i, (RenderSurface*)nullptr);
  1059. SetDepthStencil((RenderSurface*)nullptr);
  1060. SetViewport(IntRect(0, 0, width_, height_));
  1061. }
  1062. void Graphics::ResetRenderTarget(unsigned index)
  1063. {
  1064. SetRenderTarget(index, (RenderSurface*)nullptr);
  1065. }
  1066. void Graphics::ResetDepthStencil()
  1067. {
  1068. SetDepthStencil((RenderSurface*)nullptr);
  1069. }
  1070. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1071. {
  1072. if (index >= MAX_RENDERTARGETS)
  1073. return;
  1074. if (renderTarget != renderTargets_[index])
  1075. {
  1076. renderTargets_[index] = renderTarget;
  1077. impl_->renderTargetsDirty_ = true;
  1078. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1079. if (renderTarget)
  1080. {
  1081. Texture* parentTexture = renderTarget->GetParentTexture();
  1082. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1083. {
  1084. if (textures_[i] == parentTexture)
  1085. SetTexture(i, textures_[i]->GetBackupTexture());
  1086. }
  1087. // If multisampled, mark the texture & surface needing resolve
  1088. if (parentTexture->GetMultiSample() > 1 && parentTexture->GetAutoResolve())
  1089. {
  1090. parentTexture->SetResolveDirty(true);
  1091. renderTarget->SetResolveDirty(true);
  1092. }
  1093. // If mipmapped, mark the levels needing regeneration
  1094. if (parentTexture->GetLevels() > 1)
  1095. parentTexture->SetLevelsDirty();
  1096. }
  1097. }
  1098. }
  1099. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1100. {
  1101. RenderSurface* renderTarget = nullptr;
  1102. if (texture)
  1103. renderTarget = texture->GetRenderSurface();
  1104. SetRenderTarget(index, renderTarget);
  1105. }
  1106. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1107. {
  1108. if (depthStencil != depthStencil_)
  1109. {
  1110. depthStencil_ = depthStencil;
  1111. impl_->renderTargetsDirty_ = true;
  1112. }
  1113. }
  1114. void Graphics::SetDepthStencil(Texture2D* texture)
  1115. {
  1116. RenderSurface* depthStencil = nullptr;
  1117. if (texture)
  1118. depthStencil = texture->GetRenderSurface();
  1119. SetDepthStencil(depthStencil);
  1120. // Constant depth bias depends on the bitdepth
  1121. impl_->rasterizerStateDirty_ = true;
  1122. }
  1123. void Graphics::SetViewport(const IntRect& rect)
  1124. {
  1125. IntVector2 size = GetRenderTargetDimensions();
  1126. IntRect rectCopy = rect;
  1127. if (rectCopy.right_ <= rectCopy.left_)
  1128. rectCopy.right_ = rectCopy.left_ + 1;
  1129. if (rectCopy.bottom_ <= rectCopy.top_)
  1130. rectCopy.bottom_ = rectCopy.top_ + 1;
  1131. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1132. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1133. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1134. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1135. static D3D11_VIEWPORT d3dViewport;
  1136. d3dViewport.TopLeftX = (float)rectCopy.left_;
  1137. d3dViewport.TopLeftY = (float)rectCopy.top_;
  1138. d3dViewport.Width = (float)(rectCopy.right_ - rectCopy.left_);
  1139. d3dViewport.Height = (float)(rectCopy.bottom_ - rectCopy.top_);
  1140. d3dViewport.MinDepth = 0.0f;
  1141. d3dViewport.MaxDepth = 1.0f;
  1142. impl_->deviceContext_->RSSetViewports(1, &d3dViewport);
  1143. viewport_ = rectCopy;
  1144. // Disable scissor test, needs to be re-enabled by the user
  1145. SetScissorTest(false);
  1146. }
  1147. void Graphics::SetBlendMode(BlendMode mode, bool alphaToCoverage)
  1148. {
  1149. if (mode != blendMode_ || alphaToCoverage != alphaToCoverage_)
  1150. {
  1151. blendMode_ = mode;
  1152. alphaToCoverage_ = alphaToCoverage;
  1153. impl_->blendStateDirty_ = true;
  1154. }
  1155. }
  1156. void Graphics::SetColorWrite(bool enable)
  1157. {
  1158. if (enable != colorWrite_)
  1159. {
  1160. colorWrite_ = enable;
  1161. impl_->blendStateDirty_ = true;
  1162. }
  1163. }
  1164. void Graphics::SetCullMode(CullMode mode)
  1165. {
  1166. if (mode != cullMode_)
  1167. {
  1168. cullMode_ = mode;
  1169. impl_->rasterizerStateDirty_ = true;
  1170. }
  1171. }
  1172. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1173. {
  1174. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1175. {
  1176. constantDepthBias_ = constantBias;
  1177. slopeScaledDepthBias_ = slopeScaledBias;
  1178. impl_->rasterizerStateDirty_ = true;
  1179. }
  1180. }
  1181. void Graphics::SetDepthTest(CompareMode mode)
  1182. {
  1183. if (mode != depthTestMode_)
  1184. {
  1185. depthTestMode_ = mode;
  1186. impl_->depthStateDirty_ = true;
  1187. }
  1188. }
  1189. void Graphics::SetDepthWrite(bool enable)
  1190. {
  1191. if (enable != depthWrite_)
  1192. {
  1193. depthWrite_ = enable;
  1194. impl_->depthStateDirty_ = true;
  1195. // Also affects whether a read-only version of depth-stencil should be bound, to allow sampling
  1196. impl_->renderTargetsDirty_ = true;
  1197. }
  1198. }
  1199. void Graphics::SetFillMode(FillMode mode)
  1200. {
  1201. if (mode != fillMode_)
  1202. {
  1203. fillMode_ = mode;
  1204. impl_->rasterizerStateDirty_ = true;
  1205. }
  1206. }
  1207. void Graphics::SetLineAntiAlias(bool enable)
  1208. {
  1209. if (enable != lineAntiAlias_)
  1210. {
  1211. lineAntiAlias_ = enable;
  1212. impl_->rasterizerStateDirty_ = true;
  1213. }
  1214. }
  1215. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1216. {
  1217. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1218. // Disable scissor in that case to reduce state changes
  1219. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1220. enable = false;
  1221. if (enable)
  1222. {
  1223. IntVector2 rtSize(GetRenderTargetDimensions());
  1224. IntVector2 viewSize(viewport_.Size());
  1225. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1226. IntRect intRect;
  1227. int expand = borderInclusive ? 1 : 0;
  1228. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1229. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1230. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1231. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1232. if (intRect.right_ == intRect.left_)
  1233. intRect.right_++;
  1234. if (intRect.bottom_ == intRect.top_)
  1235. intRect.bottom_++;
  1236. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1237. enable = false;
  1238. if (enable && intRect != scissorRect_)
  1239. {
  1240. scissorRect_ = intRect;
  1241. impl_->scissorRectDirty_ = true;
  1242. }
  1243. }
  1244. if (enable != scissorTest_)
  1245. {
  1246. scissorTest_ = enable;
  1247. impl_->rasterizerStateDirty_ = true;
  1248. }
  1249. }
  1250. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1251. {
  1252. IntVector2 rtSize(GetRenderTargetDimensions());
  1253. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1254. if (enable)
  1255. {
  1256. IntRect intRect;
  1257. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1258. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1259. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1260. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1261. if (intRect.right_ == intRect.left_)
  1262. intRect.right_++;
  1263. if (intRect.bottom_ == intRect.top_)
  1264. intRect.bottom_++;
  1265. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1266. enable = false;
  1267. if (enable && intRect != scissorRect_)
  1268. {
  1269. scissorRect_ = intRect;
  1270. impl_->scissorRectDirty_ = true;
  1271. }
  1272. }
  1273. if (enable != scissorTest_)
  1274. {
  1275. scissorTest_ = enable;
  1276. impl_->rasterizerStateDirty_ = true;
  1277. }
  1278. }
  1279. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1280. unsigned compareMask, unsigned writeMask)
  1281. {
  1282. if (enable != stencilTest_)
  1283. {
  1284. stencilTest_ = enable;
  1285. impl_->depthStateDirty_ = true;
  1286. }
  1287. if (enable)
  1288. {
  1289. if (mode != stencilTestMode_)
  1290. {
  1291. stencilTestMode_ = mode;
  1292. impl_->depthStateDirty_ = true;
  1293. }
  1294. if (pass != stencilPass_)
  1295. {
  1296. stencilPass_ = pass;
  1297. impl_->depthStateDirty_ = true;
  1298. }
  1299. if (fail != stencilFail_)
  1300. {
  1301. stencilFail_ = fail;
  1302. impl_->depthStateDirty_ = true;
  1303. }
  1304. if (zFail != stencilZFail_)
  1305. {
  1306. stencilZFail_ = zFail;
  1307. impl_->depthStateDirty_ = true;
  1308. }
  1309. if (compareMask != stencilCompareMask_)
  1310. {
  1311. stencilCompareMask_ = compareMask;
  1312. impl_->depthStateDirty_ = true;
  1313. }
  1314. if (writeMask != stencilWriteMask_)
  1315. {
  1316. stencilWriteMask_ = writeMask;
  1317. impl_->depthStateDirty_ = true;
  1318. }
  1319. if (stencilRef != stencilRef_)
  1320. {
  1321. stencilRef_ = stencilRef;
  1322. impl_->stencilRefDirty_ = true;
  1323. impl_->depthStateDirty_ = true;
  1324. }
  1325. }
  1326. }
  1327. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1328. {
  1329. useClipPlane_ = enable;
  1330. if (enable)
  1331. {
  1332. Matrix4 viewProj = projection * view;
  1333. clipPlane_ = clipPlane.Transformed(viewProj).ToVector4();
  1334. SetShaderParameter(VSP_CLIPPLANE, clipPlane_);
  1335. }
  1336. }
  1337. bool Graphics::IsInitialized() const
  1338. {
  1339. return window_ != nullptr && impl_->GetDevice() != nullptr;
  1340. }
  1341. PODVector<int> Graphics::GetMultiSampleLevels() const
  1342. {
  1343. PODVector<int> ret;
  1344. ret.Push(1);
  1345. if (impl_->device_)
  1346. {
  1347. for (unsigned i = 2; i <= 16; ++i)
  1348. {
  1349. if (impl_->CheckMultiSampleSupport(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, i))
  1350. ret.Push(i);
  1351. }
  1352. }
  1353. return ret;
  1354. }
  1355. unsigned Graphics::GetFormat(CompressedFormat format) const
  1356. {
  1357. switch (format)
  1358. {
  1359. case CF_RGBA:
  1360. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1361. case CF_DXT1:
  1362. return DXGI_FORMAT_BC1_UNORM;
  1363. case CF_DXT3:
  1364. return DXGI_FORMAT_BC2_UNORM;
  1365. case CF_DXT5:
  1366. return DXGI_FORMAT_BC3_UNORM;
  1367. default:
  1368. return 0;
  1369. }
  1370. }
  1371. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1372. {
  1373. return GetShader(type, name.CString(), defines.CString());
  1374. }
  1375. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1376. {
  1377. if (lastShaderName_ != name || !lastShader_)
  1378. {
  1379. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1380. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1381. // Try to reduce repeated error log prints because of missing shaders
  1382. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1383. return nullptr;
  1384. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1385. lastShaderName_ = name;
  1386. }
  1387. return lastShader_ ? lastShader_->GetVariation(type, defines) : nullptr;
  1388. }
  1389. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1390. {
  1391. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : nullptr;
  1392. }
  1393. ShaderProgram* Graphics::GetShaderProgram() const
  1394. {
  1395. return impl_->shaderProgram_;
  1396. }
  1397. TextureUnit Graphics::GetTextureUnit(const String& name)
  1398. {
  1399. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1400. if (i != textureUnits_.End())
  1401. return i->second_;
  1402. else
  1403. return MAX_TEXTURE_UNITS;
  1404. }
  1405. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1406. {
  1407. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1408. {
  1409. if (i->second_ == unit)
  1410. return i->first_;
  1411. }
  1412. return String::EMPTY;
  1413. }
  1414. Texture* Graphics::GetTexture(unsigned index) const
  1415. {
  1416. return index < MAX_TEXTURE_UNITS ? textures_[index] : nullptr;
  1417. }
  1418. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1419. {
  1420. return index < MAX_RENDERTARGETS ? renderTargets_[index] : nullptr;
  1421. }
  1422. IntVector2 Graphics::GetRenderTargetDimensions() const
  1423. {
  1424. int width, height;
  1425. if (renderTargets_[0])
  1426. {
  1427. width = renderTargets_[0]->GetWidth();
  1428. height = renderTargets_[0]->GetHeight();
  1429. }
  1430. else if (depthStencil_) // Depth-only rendering
  1431. {
  1432. width = depthStencil_->GetWidth();
  1433. height = depthStencil_->GetHeight();
  1434. }
  1435. else
  1436. {
  1437. width = width_;
  1438. height = height_;
  1439. }
  1440. return IntVector2(width, height);
  1441. }
  1442. bool Graphics::GetDither() const
  1443. {
  1444. return false;
  1445. }
  1446. bool Graphics::IsDeviceLost() const
  1447. {
  1448. // Direct3D11 graphics context is never considered lost
  1449. /// \todo The device could be lost in case of graphics adapters getting disabled during runtime. This is not currently handled
  1450. return false;
  1451. }
  1452. void Graphics::OnWindowResized()
  1453. {
  1454. if (!impl_->device_ || !window_)
  1455. return;
  1456. int newWidth, newHeight;
  1457. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1458. if (newWidth == width_ && newHeight == height_)
  1459. return;
  1460. UpdateSwapChain(newWidth, newHeight);
  1461. // Reset rendertargets and viewport for the new screen size
  1462. ResetRenderTargets();
  1463. URHO3D_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1464. using namespace ScreenMode;
  1465. VariantMap& eventData = GetEventDataMap();
  1466. eventData[P_WIDTH] = width_;
  1467. eventData[P_HEIGHT] = height_;
  1468. eventData[P_FULLSCREEN] = screenParams_.fullscreen_;
  1469. eventData[P_RESIZABLE] = screenParams_.resizable_;
  1470. eventData[P_BORDERLESS] = screenParams_.borderless_;
  1471. eventData[P_HIGHDPI] = screenParams_.highDPI_;
  1472. SendEvent(E_SCREENMODE, eventData);
  1473. }
  1474. void Graphics::OnWindowMoved()
  1475. {
  1476. if (!impl_->device_ || !window_ || screenParams_.fullscreen_)
  1477. return;
  1478. int newX, newY;
  1479. SDL_GetWindowPosition(window_, &newX, &newY);
  1480. if (newX == position_.x_ && newY == position_.y_)
  1481. return;
  1482. position_.x_ = newX;
  1483. position_.y_ = newY;
  1484. URHO3D_LOGTRACEF("Window was moved to %d,%d", position_.x_, position_.y_);
  1485. using namespace WindowPos;
  1486. VariantMap& eventData = GetEventDataMap();
  1487. eventData[P_X] = position_.x_;
  1488. eventData[P_Y] = position_.y_;
  1489. SendEvent(E_WINDOWPOS, eventData);
  1490. }
  1491. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  1492. {
  1493. for (ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Begin(); i != impl_->shaderPrograms_.End();)
  1494. {
  1495. if (i->first_.first_ == variation || i->first_.second_ == variation)
  1496. i = impl_->shaderPrograms_.Erase(i);
  1497. else
  1498. ++i;
  1499. }
  1500. if (vertexShader_ == variation || pixelShader_ == variation)
  1501. impl_->shaderProgram_ = nullptr;
  1502. }
  1503. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1504. {
  1505. // No-op on Direct3D11
  1506. }
  1507. ConstantBuffer* Graphics::GetOrCreateConstantBuffer(ShaderType type, unsigned index, unsigned size)
  1508. {
  1509. // Ensure that different shader types and index slots get unique buffers, even if the size is same
  1510. unsigned key = type | (index << 1) | (size << 4);
  1511. ConstantBufferMap::Iterator i = impl_->allConstantBuffers_.Find(key);
  1512. if (i != impl_->allConstantBuffers_.End())
  1513. return i->second_.Get();
  1514. else
  1515. {
  1516. SharedPtr<ConstantBuffer> newConstantBuffer(new ConstantBuffer(context_));
  1517. newConstantBuffer->SetSize(size);
  1518. impl_->allConstantBuffers_[key] = newConstantBuffer;
  1519. return newConstantBuffer.Get();
  1520. }
  1521. }
  1522. unsigned Graphics::GetAlphaFormat()
  1523. {
  1524. return DXGI_FORMAT_A8_UNORM;
  1525. }
  1526. unsigned Graphics::GetLuminanceFormat()
  1527. {
  1528. // Note: not same sampling behavior as on D3D9; need to sample the R channel only
  1529. return DXGI_FORMAT_R8_UNORM;
  1530. }
  1531. unsigned Graphics::GetLuminanceAlphaFormat()
  1532. {
  1533. // Note: not same sampling behavior as on D3D9; need to sample the RG channels
  1534. return DXGI_FORMAT_R8G8_UNORM;
  1535. }
  1536. unsigned Graphics::GetRGBFormat()
  1537. {
  1538. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1539. }
  1540. unsigned Graphics::GetRGBAFormat()
  1541. {
  1542. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1543. }
  1544. unsigned Graphics::GetRGBA16Format()
  1545. {
  1546. return DXGI_FORMAT_R16G16B16A16_UNORM;
  1547. }
  1548. unsigned Graphics::GetRGBAFloat16Format()
  1549. {
  1550. return DXGI_FORMAT_R16G16B16A16_FLOAT;
  1551. }
  1552. unsigned Graphics::GetRGBAFloat32Format()
  1553. {
  1554. return DXGI_FORMAT_R32G32B32A32_FLOAT;
  1555. }
  1556. unsigned Graphics::GetRG16Format()
  1557. {
  1558. return DXGI_FORMAT_R16G16_UNORM;
  1559. }
  1560. unsigned Graphics::GetRGFloat16Format()
  1561. {
  1562. return DXGI_FORMAT_R16G16_FLOAT;
  1563. }
  1564. unsigned Graphics::GetRGFloat32Format()
  1565. {
  1566. return DXGI_FORMAT_R32G32_FLOAT;
  1567. }
  1568. unsigned Graphics::GetFloat16Format()
  1569. {
  1570. return DXGI_FORMAT_R16_FLOAT;
  1571. }
  1572. unsigned Graphics::GetFloat32Format()
  1573. {
  1574. return DXGI_FORMAT_R32_FLOAT;
  1575. }
  1576. unsigned Graphics::GetLinearDepthFormat()
  1577. {
  1578. return DXGI_FORMAT_R32_FLOAT;
  1579. }
  1580. unsigned Graphics::GetDepthStencilFormat()
  1581. {
  1582. return DXGI_FORMAT_R24G8_TYPELESS;
  1583. }
  1584. unsigned Graphics::GetReadableDepthFormat()
  1585. {
  1586. return DXGI_FORMAT_R24G8_TYPELESS;
  1587. }
  1588. unsigned Graphics::GetFormat(const String& formatName)
  1589. {
  1590. String nameLower = formatName.ToLower().Trimmed();
  1591. if (nameLower == "a")
  1592. return GetAlphaFormat();
  1593. if (nameLower == "l")
  1594. return GetLuminanceFormat();
  1595. if (nameLower == "la")
  1596. return GetLuminanceAlphaFormat();
  1597. if (nameLower == "rgb")
  1598. return GetRGBFormat();
  1599. if (nameLower == "rgba")
  1600. return GetRGBAFormat();
  1601. if (nameLower == "rgba16")
  1602. return GetRGBA16Format();
  1603. if (nameLower == "rgba16f")
  1604. return GetRGBAFloat16Format();
  1605. if (nameLower == "rgba32f")
  1606. return GetRGBAFloat32Format();
  1607. if (nameLower == "rg16")
  1608. return GetRG16Format();
  1609. if (nameLower == "rg16f")
  1610. return GetRGFloat16Format();
  1611. if (nameLower == "rg32f")
  1612. return GetRGFloat32Format();
  1613. if (nameLower == "r16f")
  1614. return GetFloat16Format();
  1615. if (nameLower == "r32f" || nameLower == "float")
  1616. return GetFloat32Format();
  1617. if (nameLower == "lineardepth" || nameLower == "depth")
  1618. return GetLinearDepthFormat();
  1619. if (nameLower == "d24s8")
  1620. return GetDepthStencilFormat();
  1621. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  1622. return GetReadableDepthFormat();
  1623. return GetRGBFormat();
  1624. }
  1625. unsigned Graphics::GetMaxBones()
  1626. {
  1627. return 128;
  1628. }
  1629. bool Graphics::GetGL3Support()
  1630. {
  1631. return gl3Support;
  1632. }
  1633. bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
  1634. {
  1635. if (!externalWindow_)
  1636. {
  1637. unsigned flags = 0;
  1638. if (resizable)
  1639. flags |= SDL_WINDOW_RESIZABLE;
  1640. if (borderless)
  1641. flags |= SDL_WINDOW_BORDERLESS;
  1642. window_ = SDL_CreateWindow(windowTitle_.CString(), position_.x_, position_.y_, width, height, flags);
  1643. }
  1644. else
  1645. window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1646. if (!window_)
  1647. {
  1648. URHO3D_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  1649. return false;
  1650. }
  1651. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  1652. CreateWindowIcon();
  1653. return true;
  1654. }
  1655. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless, int& monitor)
  1656. {
  1657. if (!externalWindow_)
  1658. {
  1659. // Keep current window position because it may change in intermediate callbacks
  1660. const IntVector2 oldPosition = position_;
  1661. bool reposition = false;
  1662. bool resizePostponed = false;
  1663. if (!newWidth || !newHeight)
  1664. {
  1665. SDL_MaximizeWindow(window_);
  1666. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1667. }
  1668. else
  1669. {
  1670. SDL_Rect display_rect;
  1671. SDL_GetDisplayBounds(monitor, &display_rect);
  1672. reposition = newFullscreen || (newBorderless && newWidth >= display_rect.w && newHeight >= display_rect.h);
  1673. if (reposition)
  1674. {
  1675. // Reposition the window on the specified monitor if it's supposed to cover the entire monitor
  1676. SDL_SetWindowPosition(window_, display_rect.x, display_rect.y);
  1677. }
  1678. // Postpone window resize if exiting fullscreen to avoid redundant resolution change
  1679. if (!newFullscreen && screenParams_.fullscreen_)
  1680. resizePostponed = true;
  1681. else
  1682. SDL_SetWindowSize(window_, newWidth, newHeight);
  1683. }
  1684. // Turn off window fullscreen mode so it gets repositioned to the correct monitor
  1685. SDL_SetWindowFullscreen(window_, SDL_FALSE);
  1686. // Hack fix: on SDL 2.0.4 a fullscreen->windowed transition results in a maximized window when the D3D device is reset, so hide before
  1687. if (!newFullscreen) SDL_HideWindow(window_);
  1688. SDL_SetWindowFullscreen(window_, newFullscreen ? SDL_WINDOW_FULLSCREEN : 0);
  1689. SDL_SetWindowBordered(window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  1690. if (!newFullscreen) SDL_ShowWindow(window_);
  1691. // Resize now if was postponed
  1692. if (resizePostponed)
  1693. SDL_SetWindowSize(window_, newWidth, newHeight);
  1694. // Ensure that window keeps its position
  1695. if (!reposition)
  1696. SDL_SetWindowPosition(window_, oldPosition.x_, oldPosition.y_);
  1697. else
  1698. position_ = oldPosition;
  1699. }
  1700. else
  1701. {
  1702. // If external window, must ask its dimensions instead of trying to set them
  1703. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1704. newFullscreen = false;
  1705. }
  1706. }
  1707. bool Graphics::CreateDevice(int width, int height)
  1708. {
  1709. // Device needs only to be created once
  1710. if (!impl_->device_)
  1711. {
  1712. HRESULT hr = D3D11CreateDevice(
  1713. nullptr,
  1714. D3D_DRIVER_TYPE_HARDWARE,
  1715. nullptr,
  1716. 0,
  1717. nullptr,
  1718. 0,
  1719. D3D11_SDK_VERSION,
  1720. &impl_->device_,
  1721. nullptr,
  1722. &impl_->deviceContext_
  1723. );
  1724. if (FAILED(hr))
  1725. {
  1726. URHO3D_SAFE_RELEASE(impl_->device_);
  1727. URHO3D_SAFE_RELEASE(impl_->deviceContext_);
  1728. URHO3D_LOGD3DERROR("Failed to create D3D11 device", hr);
  1729. return false;
  1730. }
  1731. CheckFeatureSupport();
  1732. // Set the flush mode now as the device has been created
  1733. SetFlushGPU(flushGPU_);
  1734. }
  1735. // Check that multisample level is supported
  1736. PODVector<int> multiSampleLevels = GetMultiSampleLevels();
  1737. if (!multiSampleLevels.Contains(screenParams_.multiSample_))
  1738. screenParams_.multiSample_ = 1;
  1739. // Create swap chain. Release old if necessary
  1740. if (impl_->swapChain_)
  1741. {
  1742. impl_->swapChain_->Release();
  1743. impl_->swapChain_ = nullptr;
  1744. }
  1745. IDXGIDevice* dxgiDevice = nullptr;
  1746. impl_->device_->QueryInterface(IID_IDXGIDevice, (void**)&dxgiDevice);
  1747. IDXGIAdapter* dxgiAdapter = nullptr;
  1748. dxgiDevice->GetParent(IID_IDXGIAdapter, (void**)&dxgiAdapter);
  1749. IDXGIFactory* dxgiFactory = nullptr;
  1750. dxgiAdapter->GetParent(IID_IDXGIFactory, (void**)&dxgiFactory);
  1751. DXGI_RATIONAL refreshRateRational = {};
  1752. IDXGIOutput* dxgiOutput = nullptr;
  1753. UINT numModes = 0;
  1754. dxgiAdapter->EnumOutputs(screenParams_.monitor_, &dxgiOutput);
  1755. dxgiOutput->GetDisplayModeList(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, 0);
  1756. // find the best matching refresh rate with the specified resolution
  1757. if (numModes > 0)
  1758. {
  1759. DXGI_MODE_DESC* modes = new DXGI_MODE_DESC[numModes];
  1760. dxgiOutput->GetDisplayModeList(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, modes);
  1761. unsigned bestMatchingRateIndex = -1;
  1762. unsigned bestError = M_MAX_UNSIGNED;
  1763. for (unsigned i = 0; i < numModes; ++i)
  1764. {
  1765. if (width != modes[i].Width || height != modes[i].Height)
  1766. continue;
  1767. float rate = (float)modes[i].RefreshRate.Numerator / modes[i].RefreshRate.Denominator;
  1768. unsigned error = (unsigned)(Abs(rate - screenParams_.refreshRate_));
  1769. if (error < bestError)
  1770. {
  1771. bestMatchingRateIndex = i;
  1772. bestError = error;
  1773. }
  1774. }
  1775. if (bestMatchingRateIndex != -1)
  1776. {
  1777. refreshRateRational.Numerator = modes[bestMatchingRateIndex].RefreshRate.Numerator;
  1778. refreshRateRational.Denominator = modes[bestMatchingRateIndex].RefreshRate.Denominator;
  1779. }
  1780. delete[] modes;
  1781. }
  1782. dxgiOutput->Release();
  1783. DXGI_SWAP_CHAIN_DESC swapChainDesc;
  1784. memset(&swapChainDesc, 0, sizeof swapChainDesc);
  1785. swapChainDesc.BufferCount = 1;
  1786. swapChainDesc.BufferDesc.Width = (UINT)width;
  1787. swapChainDesc.BufferDesc.Height = (UINT)height;
  1788. swapChainDesc.BufferDesc.Format = sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
  1789. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  1790. swapChainDesc.BufferDesc.RefreshRate.Numerator = refreshRateRational.Numerator;
  1791. swapChainDesc.BufferDesc.RefreshRate.Denominator = refreshRateRational.Denominator;
  1792. swapChainDesc.OutputWindow = GetWindowHandle(window_);
  1793. swapChainDesc.SampleDesc.Count = static_cast<UINT>(screenParams_.multiSample_);
  1794. swapChainDesc.SampleDesc.Quality = impl_->GetMultiSampleQuality(swapChainDesc.BufferDesc.Format, screenParams_.multiSample_);
  1795. swapChainDesc.Windowed = TRUE;
  1796. swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
  1797. HRESULT hr = dxgiFactory->CreateSwapChain(impl_->device_, &swapChainDesc, &impl_->swapChain_);
  1798. // After creating the swap chain, disable automatic Alt-Enter fullscreen/windowed switching
  1799. // (the application will switch manually if it wants to)
  1800. dxgiFactory->MakeWindowAssociation(GetWindowHandle(window_), DXGI_MWA_NO_ALT_ENTER);
  1801. #ifdef URHO3D_LOGGING
  1802. DXGI_ADAPTER_DESC desc;
  1803. dxgiAdapter->GetDesc(&desc);
  1804. String adapterDesc(desc.Description);
  1805. URHO3D_LOGINFO("Adapter used " + adapterDesc);
  1806. #endif
  1807. dxgiFactory->Release();
  1808. dxgiAdapter->Release();
  1809. dxgiDevice->Release();
  1810. if (FAILED(hr))
  1811. {
  1812. URHO3D_SAFE_RELEASE(impl_->swapChain_);
  1813. URHO3D_LOGD3DERROR("Failed to create D3D11 swap chain", hr);
  1814. return false;
  1815. }
  1816. return true;
  1817. }
  1818. bool Graphics::UpdateSwapChain(int width, int height)
  1819. {
  1820. bool success = true;
  1821. ID3D11RenderTargetView* nullView = nullptr;
  1822. impl_->deviceContext_->OMSetRenderTargets(1, &nullView, nullptr);
  1823. if (impl_->defaultRenderTargetView_)
  1824. {
  1825. impl_->defaultRenderTargetView_->Release();
  1826. impl_->defaultRenderTargetView_ = nullptr;
  1827. }
  1828. if (impl_->defaultDepthStencilView_)
  1829. {
  1830. impl_->defaultDepthStencilView_->Release();
  1831. impl_->defaultDepthStencilView_ = nullptr;
  1832. }
  1833. if (impl_->defaultDepthTexture_)
  1834. {
  1835. impl_->defaultDepthTexture_->Release();
  1836. impl_->defaultDepthTexture_ = nullptr;
  1837. }
  1838. if (impl_->resolveTexture_)
  1839. {
  1840. impl_->resolveTexture_->Release();
  1841. impl_->resolveTexture_ = nullptr;
  1842. }
  1843. impl_->depthStencilView_ = nullptr;
  1844. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1845. impl_->renderTargetViews_[i] = nullptr;
  1846. impl_->renderTargetsDirty_ = true;
  1847. impl_->swapChain_->ResizeBuffers(1, (UINT)width, (UINT)height, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
  1848. // Create default rendertarget view representing the backbuffer
  1849. ID3D11Texture2D* backbufferTexture;
  1850. HRESULT hr = impl_->swapChain_->GetBuffer(0, IID_ID3D11Texture2D, (void**)&backbufferTexture);
  1851. if (FAILED(hr))
  1852. {
  1853. URHO3D_SAFE_RELEASE(backbufferTexture);
  1854. URHO3D_LOGD3DERROR("Failed to get backbuffer texture", hr);
  1855. success = false;
  1856. }
  1857. else
  1858. {
  1859. hr = impl_->device_->CreateRenderTargetView(backbufferTexture, nullptr, &impl_->defaultRenderTargetView_);
  1860. backbufferTexture->Release();
  1861. if (FAILED(hr))
  1862. {
  1863. URHO3D_SAFE_RELEASE(impl_->defaultRenderTargetView_);
  1864. URHO3D_LOGD3DERROR("Failed to create backbuffer rendertarget view", hr);
  1865. success = false;
  1866. }
  1867. }
  1868. // Create default depth-stencil texture and view
  1869. D3D11_TEXTURE2D_DESC depthDesc;
  1870. memset(&depthDesc, 0, sizeof depthDesc);
  1871. depthDesc.Width = (UINT)width;
  1872. depthDesc.Height = (UINT)height;
  1873. depthDesc.MipLevels = 1;
  1874. depthDesc.ArraySize = 1;
  1875. depthDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  1876. depthDesc.SampleDesc.Count = static_cast<UINT>(screenParams_.multiSample_);
  1877. depthDesc.SampleDesc.Quality = impl_->GetMultiSampleQuality(depthDesc.Format, screenParams_.multiSample_);
  1878. depthDesc.Usage = D3D11_USAGE_DEFAULT;
  1879. depthDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  1880. depthDesc.CPUAccessFlags = 0;
  1881. depthDesc.MiscFlags = 0;
  1882. hr = impl_->device_->CreateTexture2D(&depthDesc, nullptr, &impl_->defaultDepthTexture_);
  1883. if (FAILED(hr))
  1884. {
  1885. URHO3D_SAFE_RELEASE(impl_->defaultDepthTexture_);
  1886. URHO3D_LOGD3DERROR("Failed to create backbuffer depth-stencil texture", hr);
  1887. success = false;
  1888. }
  1889. else
  1890. {
  1891. hr = impl_->device_->CreateDepthStencilView(impl_->defaultDepthTexture_, nullptr, &impl_->defaultDepthStencilView_);
  1892. if (FAILED(hr))
  1893. {
  1894. URHO3D_SAFE_RELEASE(impl_->defaultDepthStencilView_);
  1895. URHO3D_LOGD3DERROR("Failed to create backbuffer depth-stencil view", hr);
  1896. success = false;
  1897. }
  1898. }
  1899. // Update internally held backbuffer size
  1900. width_ = width;
  1901. height_ = height;
  1902. ResetRenderTargets();
  1903. return success;
  1904. }
  1905. void Graphics::CheckFeatureSupport()
  1906. {
  1907. anisotropySupport_ = true;
  1908. dxtTextureSupport_ = true;
  1909. lightPrepassSupport_ = true;
  1910. deferredSupport_ = true;
  1911. hardwareShadowSupport_ = true;
  1912. instancingSupport_ = true;
  1913. shadowMapFormat_ = DXGI_FORMAT_R16_TYPELESS;
  1914. hiresShadowMapFormat_ = DXGI_FORMAT_R32_TYPELESS;
  1915. dummyColorFormat_ = DXGI_FORMAT_UNKNOWN;
  1916. sRGBSupport_ = true;
  1917. sRGBWriteSupport_ = true;
  1918. }
  1919. void Graphics::ResetCachedState()
  1920. {
  1921. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1922. {
  1923. vertexBuffers_[i] = nullptr;
  1924. impl_->vertexBuffers_[i] = nullptr;
  1925. impl_->vertexSizes_[i] = 0;
  1926. impl_->vertexOffsets_[i] = 0;
  1927. }
  1928. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1929. {
  1930. textures_[i] = nullptr;
  1931. impl_->shaderResourceViews_[i] = nullptr;
  1932. impl_->samplers_[i] = nullptr;
  1933. }
  1934. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1935. {
  1936. renderTargets_[i] = nullptr;
  1937. impl_->renderTargetViews_[i] = nullptr;
  1938. }
  1939. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1940. {
  1941. impl_->constantBuffers_[VS][i] = nullptr;
  1942. impl_->constantBuffers_[PS][i] = nullptr;
  1943. }
  1944. depthStencil_ = nullptr;
  1945. impl_->depthStencilView_ = nullptr;
  1946. viewport_ = IntRect(0, 0, width_, height_);
  1947. indexBuffer_ = nullptr;
  1948. vertexDeclarationHash_ = 0;
  1949. primitiveType_ = 0;
  1950. vertexShader_ = nullptr;
  1951. pixelShader_ = nullptr;
  1952. blendMode_ = BLEND_REPLACE;
  1953. alphaToCoverage_ = false;
  1954. colorWrite_ = true;
  1955. cullMode_ = CULL_CCW;
  1956. constantDepthBias_ = 0.0f;
  1957. slopeScaledDepthBias_ = 0.0f;
  1958. depthTestMode_ = CMP_LESSEQUAL;
  1959. depthWrite_ = true;
  1960. fillMode_ = FILL_SOLID;
  1961. lineAntiAlias_ = false;
  1962. scissorTest_ = false;
  1963. scissorRect_ = IntRect::ZERO;
  1964. stencilTest_ = false;
  1965. stencilTestMode_ = CMP_ALWAYS;
  1966. stencilPass_ = OP_KEEP;
  1967. stencilFail_ = OP_KEEP;
  1968. stencilZFail_ = OP_KEEP;
  1969. stencilRef_ = 0;
  1970. stencilCompareMask_ = M_MAX_UNSIGNED;
  1971. stencilWriteMask_ = M_MAX_UNSIGNED;
  1972. useClipPlane_ = false;
  1973. impl_->shaderProgram_ = nullptr;
  1974. impl_->renderTargetsDirty_ = true;
  1975. impl_->texturesDirty_ = true;
  1976. impl_->vertexDeclarationDirty_ = true;
  1977. impl_->blendStateDirty_ = true;
  1978. impl_->depthStateDirty_ = true;
  1979. impl_->rasterizerStateDirty_ = true;
  1980. impl_->scissorRectDirty_ = true;
  1981. impl_->stencilRefDirty_ = true;
  1982. impl_->blendStateHash_ = M_MAX_UNSIGNED;
  1983. impl_->depthStateHash_ = M_MAX_UNSIGNED;
  1984. impl_->rasterizerStateHash_ = M_MAX_UNSIGNED;
  1985. impl_->firstDirtyTexture_ = impl_->lastDirtyTexture_ = M_MAX_UNSIGNED;
  1986. impl_->firstDirtyVB_ = impl_->lastDirtyVB_ = M_MAX_UNSIGNED;
  1987. impl_->dirtyConstantBuffers_.Clear();
  1988. }
  1989. void Graphics::PrepareDraw()
  1990. {
  1991. if (impl_->renderTargetsDirty_)
  1992. {
  1993. impl_->depthStencilView_ =
  1994. (depthStencil_ && depthStencil_->GetUsage() == TEXTURE_DEPTHSTENCIL) ?
  1995. (ID3D11DepthStencilView*)depthStencil_->GetRenderTargetView() : impl_->defaultDepthStencilView_;
  1996. // If possible, bind a read-only depth stencil view to allow reading depth in shader
  1997. if (!depthWrite_ && depthStencil_ && depthStencil_->GetReadOnlyView())
  1998. impl_->depthStencilView_ = (ID3D11DepthStencilView*)depthStencil_->GetReadOnlyView();
  1999. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2000. impl_->renderTargetViews_[i] =
  2001. (renderTargets_[i] && renderTargets_[i]->GetUsage() == TEXTURE_RENDERTARGET) ?
  2002. (ID3D11RenderTargetView*)renderTargets_[i]->GetRenderTargetView() : nullptr;
  2003. // If rendertarget 0 is null and not doing depth-only rendering, render to the backbuffer
  2004. // Special case: if rendertarget 0 is null and depth stencil has same size as backbuffer, assume the intention is to do
  2005. // backbuffer rendering with a custom depth stencil
  2006. if (!renderTargets_[0] &&
  2007. (!depthStencil_ || (depthStencil_ && depthStencil_->GetWidth() == width_ && depthStencil_->GetHeight() == height_)))
  2008. impl_->renderTargetViews_[0] = impl_->defaultRenderTargetView_;
  2009. impl_->deviceContext_->OMSetRenderTargets(MAX_RENDERTARGETS, &impl_->renderTargetViews_[0], impl_->depthStencilView_);
  2010. impl_->renderTargetsDirty_ = false;
  2011. }
  2012. if (impl_->texturesDirty_ && impl_->firstDirtyTexture_ < M_MAX_UNSIGNED)
  2013. {
  2014. // Set also VS textures to enable vertex texture fetch to work the same way as on OpenGL
  2015. impl_->deviceContext_->VSSetShaderResources(impl_->firstDirtyTexture_, impl_->lastDirtyTexture_ - impl_->firstDirtyTexture_ + 1,
  2016. &impl_->shaderResourceViews_[impl_->firstDirtyTexture_]);
  2017. impl_->deviceContext_->VSSetSamplers(impl_->firstDirtyTexture_, impl_->lastDirtyTexture_ - impl_->firstDirtyTexture_ + 1,
  2018. &impl_->samplers_[impl_->firstDirtyTexture_]);
  2019. impl_->deviceContext_->PSSetShaderResources(impl_->firstDirtyTexture_, impl_->lastDirtyTexture_ - impl_->firstDirtyTexture_ + 1,
  2020. &impl_->shaderResourceViews_[impl_->firstDirtyTexture_]);
  2021. impl_->deviceContext_->PSSetSamplers(impl_->firstDirtyTexture_, impl_->lastDirtyTexture_ - impl_->firstDirtyTexture_ + 1,
  2022. &impl_->samplers_[impl_->firstDirtyTexture_]);
  2023. impl_->firstDirtyTexture_ = impl_->lastDirtyTexture_ = M_MAX_UNSIGNED;
  2024. impl_->texturesDirty_ = false;
  2025. }
  2026. if (impl_->vertexDeclarationDirty_ && vertexShader_ && vertexShader_->GetByteCode().Size())
  2027. {
  2028. if (impl_->firstDirtyVB_ < M_MAX_UNSIGNED)
  2029. {
  2030. impl_->deviceContext_->IASetVertexBuffers(impl_->firstDirtyVB_, impl_->lastDirtyVB_ - impl_->firstDirtyVB_ + 1,
  2031. &impl_->vertexBuffers_[impl_->firstDirtyVB_], &impl_->vertexSizes_[impl_->firstDirtyVB_], &impl_->vertexOffsets_[impl_->firstDirtyVB_]);
  2032. impl_->firstDirtyVB_ = impl_->lastDirtyVB_ = M_MAX_UNSIGNED;
  2033. }
  2034. unsigned long long newVertexDeclarationHash = 0;
  2035. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2036. {
  2037. if (vertexBuffers_[i])
  2038. newVertexDeclarationHash |= vertexBuffers_[i]->GetBufferHash(i);
  2039. }
  2040. // Do not create input layout if no vertex buffers / elements
  2041. if (newVertexDeclarationHash)
  2042. {
  2043. /// \todo Using a 64bit total hash for vertex shader and vertex buffer elements hash may not guarantee uniqueness
  2044. newVertexDeclarationHash += vertexShader_->GetElementHash();
  2045. if (newVertexDeclarationHash != vertexDeclarationHash_)
  2046. {
  2047. VertexDeclarationMap::Iterator i =
  2048. impl_->vertexDeclarations_.Find(newVertexDeclarationHash);
  2049. if (i == impl_->vertexDeclarations_.End())
  2050. {
  2051. SharedPtr<VertexDeclaration> newVertexDeclaration(new VertexDeclaration(this, vertexShader_, vertexBuffers_));
  2052. i = impl_->vertexDeclarations_.Insert(MakePair(newVertexDeclarationHash, newVertexDeclaration));
  2053. }
  2054. impl_->deviceContext_->IASetInputLayout((ID3D11InputLayout*)i->second_->GetInputLayout());
  2055. vertexDeclarationHash_ = newVertexDeclarationHash;
  2056. }
  2057. }
  2058. impl_->vertexDeclarationDirty_ = false;
  2059. }
  2060. if (impl_->blendStateDirty_)
  2061. {
  2062. unsigned newBlendStateHash = (unsigned)((colorWrite_ ? 1 : 0) | (alphaToCoverage_ ? 2 : 0) | (blendMode_ << 2));
  2063. if (newBlendStateHash != impl_->blendStateHash_)
  2064. {
  2065. HashMap<unsigned, ID3D11BlendState*>::Iterator i = impl_->blendStates_.Find(newBlendStateHash);
  2066. if (i == impl_->blendStates_.End())
  2067. {
  2068. URHO3D_PROFILE(CreateBlendState);
  2069. D3D11_BLEND_DESC stateDesc;
  2070. memset(&stateDesc, 0, sizeof stateDesc);
  2071. stateDesc.AlphaToCoverageEnable = alphaToCoverage_ ? TRUE : FALSE;
  2072. stateDesc.IndependentBlendEnable = false;
  2073. stateDesc.RenderTarget[0].BlendEnable = d3dBlendEnable[blendMode_];
  2074. stateDesc.RenderTarget[0].SrcBlend = d3dSrcBlend[blendMode_];
  2075. stateDesc.RenderTarget[0].DestBlend = d3dDestBlend[blendMode_];
  2076. stateDesc.RenderTarget[0].BlendOp = d3dBlendOp[blendMode_];
  2077. stateDesc.RenderTarget[0].SrcBlendAlpha = d3dSrcBlend[blendMode_];
  2078. stateDesc.RenderTarget[0].DestBlendAlpha = d3dDestBlend[blendMode_];
  2079. stateDesc.RenderTarget[0].BlendOpAlpha = d3dBlendOp[blendMode_];
  2080. stateDesc.RenderTarget[0].RenderTargetWriteMask = colorWrite_ ? D3D11_COLOR_WRITE_ENABLE_ALL : 0x0;
  2081. ID3D11BlendState* newBlendState = nullptr;
  2082. HRESULT hr = impl_->device_->CreateBlendState(&stateDesc, &newBlendState);
  2083. if (FAILED(hr))
  2084. {
  2085. URHO3D_SAFE_RELEASE(newBlendState);
  2086. URHO3D_LOGD3DERROR("Failed to create blend state", hr);
  2087. }
  2088. i = impl_->blendStates_.Insert(MakePair(newBlendStateHash, newBlendState));
  2089. }
  2090. impl_->deviceContext_->OMSetBlendState(i->second_, nullptr, M_MAX_UNSIGNED);
  2091. impl_->blendStateHash_ = newBlendStateHash;
  2092. }
  2093. impl_->blendStateDirty_ = false;
  2094. }
  2095. if (impl_->depthStateDirty_)
  2096. {
  2097. unsigned newDepthStateHash =
  2098. (depthWrite_ ? 1 : 0) | (stencilTest_ ? 2 : 0) | (depthTestMode_ << 2) | ((stencilCompareMask_ & 0xff) << 5) |
  2099. ((stencilWriteMask_ & 0xff) << 13) | (stencilTestMode_ << 21) |
  2100. ((stencilFail_ + stencilZFail_ * 5 + stencilPass_ * 25) << 24);
  2101. if (newDepthStateHash != impl_->depthStateHash_ || impl_->stencilRefDirty_)
  2102. {
  2103. HashMap<unsigned, ID3D11DepthStencilState*>::Iterator i = impl_->depthStates_.Find(newDepthStateHash);
  2104. if (i == impl_->depthStates_.End())
  2105. {
  2106. URHO3D_PROFILE(CreateDepthState);
  2107. D3D11_DEPTH_STENCIL_DESC stateDesc;
  2108. memset(&stateDesc, 0, sizeof stateDesc);
  2109. stateDesc.DepthEnable = TRUE;
  2110. stateDesc.DepthWriteMask = depthWrite_ ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
  2111. stateDesc.DepthFunc = d3dCmpFunc[depthTestMode_];
  2112. stateDesc.StencilEnable = stencilTest_ ? TRUE : FALSE;
  2113. stateDesc.StencilReadMask = (unsigned char)stencilCompareMask_;
  2114. stateDesc.StencilWriteMask = (unsigned char)stencilWriteMask_;
  2115. stateDesc.FrontFace.StencilFailOp = d3dStencilOp[stencilFail_];
  2116. stateDesc.FrontFace.StencilDepthFailOp = d3dStencilOp[stencilZFail_];
  2117. stateDesc.FrontFace.StencilPassOp = d3dStencilOp[stencilPass_];
  2118. stateDesc.FrontFace.StencilFunc = d3dCmpFunc[stencilTestMode_];
  2119. stateDesc.BackFace.StencilFailOp = d3dStencilOp[stencilFail_];
  2120. stateDesc.BackFace.StencilDepthFailOp = d3dStencilOp[stencilZFail_];
  2121. stateDesc.BackFace.StencilPassOp = d3dStencilOp[stencilPass_];
  2122. stateDesc.BackFace.StencilFunc = d3dCmpFunc[stencilTestMode_];
  2123. ID3D11DepthStencilState* newDepthState = nullptr;
  2124. HRESULT hr = impl_->device_->CreateDepthStencilState(&stateDesc, &newDepthState);
  2125. if (FAILED(hr))
  2126. {
  2127. URHO3D_SAFE_RELEASE(newDepthState);
  2128. URHO3D_LOGD3DERROR("Failed to create depth state", hr);
  2129. }
  2130. i = impl_->depthStates_.Insert(MakePair(newDepthStateHash, newDepthState));
  2131. }
  2132. impl_->deviceContext_->OMSetDepthStencilState(i->second_, stencilRef_);
  2133. impl_->depthStateHash_ = newDepthStateHash;
  2134. }
  2135. impl_->depthStateDirty_ = false;
  2136. impl_->stencilRefDirty_ = false;
  2137. }
  2138. if (impl_->rasterizerStateDirty_)
  2139. {
  2140. unsigned depthBits = 24;
  2141. if (depthStencil_ && depthStencil_->GetParentTexture()->GetFormat() == DXGI_FORMAT_R16_TYPELESS)
  2142. depthBits = 16;
  2143. int scaledDepthBias = (int)(constantDepthBias_ * (1 << depthBits));
  2144. unsigned newRasterizerStateHash =
  2145. (scissorTest_ ? 1 : 0) | (lineAntiAlias_ ? 2 : 0) | (fillMode_ << 2) | (cullMode_ << 4) |
  2146. ((scaledDepthBias & 0x1fff) << 6) | (((int)(slopeScaledDepthBias_ * 100.0f) & 0x1fff) << 19);
  2147. if (newRasterizerStateHash != impl_->rasterizerStateHash_)
  2148. {
  2149. HashMap<unsigned, ID3D11RasterizerState*>::Iterator i = impl_->rasterizerStates_.Find(newRasterizerStateHash);
  2150. if (i == impl_->rasterizerStates_.End())
  2151. {
  2152. URHO3D_PROFILE(CreateRasterizerState);
  2153. D3D11_RASTERIZER_DESC stateDesc;
  2154. memset(&stateDesc, 0, sizeof stateDesc);
  2155. stateDesc.FillMode = d3dFillMode[fillMode_];
  2156. stateDesc.CullMode = d3dCullMode[cullMode_];
  2157. stateDesc.FrontCounterClockwise = FALSE;
  2158. stateDesc.DepthBias = scaledDepthBias;
  2159. stateDesc.DepthBiasClamp = M_INFINITY;
  2160. stateDesc.SlopeScaledDepthBias = slopeScaledDepthBias_;
  2161. stateDesc.DepthClipEnable = TRUE;
  2162. stateDesc.ScissorEnable = scissorTest_ ? TRUE : FALSE;
  2163. stateDesc.MultisampleEnable = lineAntiAlias_ ? FALSE : TRUE;
  2164. stateDesc.AntialiasedLineEnable = lineAntiAlias_ ? TRUE : FALSE;
  2165. ID3D11RasterizerState* newRasterizerState = nullptr;
  2166. HRESULT hr = impl_->device_->CreateRasterizerState(&stateDesc, &newRasterizerState);
  2167. if (FAILED(hr))
  2168. {
  2169. URHO3D_SAFE_RELEASE(newRasterizerState);
  2170. URHO3D_LOGD3DERROR("Failed to create rasterizer state", hr);
  2171. }
  2172. i = impl_->rasterizerStates_.Insert(MakePair(newRasterizerStateHash, newRasterizerState));
  2173. }
  2174. impl_->deviceContext_->RSSetState(i->second_);
  2175. impl_->rasterizerStateHash_ = newRasterizerStateHash;
  2176. }
  2177. impl_->rasterizerStateDirty_ = false;
  2178. }
  2179. if (impl_->scissorRectDirty_)
  2180. {
  2181. D3D11_RECT d3dRect;
  2182. d3dRect.left = scissorRect_.left_;
  2183. d3dRect.top = scissorRect_.top_;
  2184. d3dRect.right = scissorRect_.right_;
  2185. d3dRect.bottom = scissorRect_.bottom_;
  2186. impl_->deviceContext_->RSSetScissorRects(1, &d3dRect);
  2187. impl_->scissorRectDirty_ = false;
  2188. }
  2189. for (unsigned i = 0; i < impl_->dirtyConstantBuffers_.Size(); ++i)
  2190. impl_->dirtyConstantBuffers_[i]->Apply();
  2191. impl_->dirtyConstantBuffers_.Clear();
  2192. }
  2193. void Graphics::CreateResolveTexture()
  2194. {
  2195. if (impl_->resolveTexture_)
  2196. return;
  2197. D3D11_TEXTURE2D_DESC textureDesc;
  2198. memset(&textureDesc, 0, sizeof textureDesc);
  2199. textureDesc.Width = (UINT)width_;
  2200. textureDesc.Height = (UINT)height_;
  2201. textureDesc.MipLevels = 1;
  2202. textureDesc.ArraySize = 1;
  2203. textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  2204. textureDesc.SampleDesc.Count = 1;
  2205. textureDesc.SampleDesc.Quality = 0;
  2206. textureDesc.Usage = D3D11_USAGE_DEFAULT;
  2207. textureDesc.CPUAccessFlags = 0;
  2208. HRESULT hr = impl_->device_->CreateTexture2D(&textureDesc, nullptr, &impl_->resolveTexture_);
  2209. if (FAILED(hr))
  2210. {
  2211. URHO3D_SAFE_RELEASE(impl_->resolveTexture_);
  2212. URHO3D_LOGD3DERROR("Could not create resolve texture", hr);
  2213. }
  2214. }
  2215. void Graphics::SetTextureUnitMappings()
  2216. {
  2217. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2218. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2219. textureUnits_["NormalMap"] = TU_NORMAL;
  2220. textureUnits_["SpecMap"] = TU_SPECULAR;
  2221. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2222. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2223. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2224. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2225. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2226. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2227. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2228. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2229. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2230. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2231. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2232. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2233. }
  2234. }