D3D11Graphics.cpp 82 KB

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