D3D11Graphics.cpp 82 KB

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