D3D11Graphics.cpp 82 KB

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