D3D11Graphics.cpp 83 KB

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