D3D11Graphics.cpp 83 KB

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