D3D11Graphics.cpp 83 KB

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