D3D11Graphics.cpp 84 KB

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