D3D11Graphics.cpp 84 KB

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