D3D11Graphics.cpp 82 KB

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