D3D9Graphics.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Precompiled.h"
  23. #include "../../Core/Context.h"
  24. #include "../../Core/ProcessUtils.h"
  25. #include "../../Core/Profiler.h"
  26. #include "../../Graphics/Graphics.h"
  27. #include "../../Graphics/GraphicsEvents.h"
  28. #include "../../Graphics/GraphicsImpl.h"
  29. #include "../../Graphics/IndexBuffer.h"
  30. #include "../../Graphics/Shader.h"
  31. #include "../../Graphics/ShaderPrecache.h"
  32. #include "../../Graphics/ShaderProgram.h"
  33. #include "../../Graphics/Texture2D.h"
  34. #include "../../Graphics/TextureCube.h"
  35. #include "../../Graphics/VertexBuffer.h"
  36. #include "../../Graphics/VertexDeclaration.h"
  37. #include "../../IO/File.h"
  38. #include "../../IO/Log.h"
  39. #include "../../Resource/ResourceCache.h"
  40. // ATOMIC BEGIN
  41. #include <SDL/include/SDL.h>
  42. #include <SDL/include/SDL_syswm.h>
  43. // ATOMIC END
  44. #include "../../DebugNew.h"
  45. #ifdef _MSC_VER
  46. #pragma warning(disable:4355)
  47. #endif
  48. // Prefer the high-performance GPU on switchable GPU systems
  49. extern "C"
  50. {
  51. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  52. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  53. }
  54. // Fix missing define in MinGW headers
  55. #ifndef D3DPRESENT_LINEAR_CONTENT
  56. #define D3DPRESENT_LINEAR_CONTENT 0x00000002L
  57. #endif
  58. #ifndef D3DSTREAMSOURCE_INDEXEDDATA
  59. #define D3DSTREAMSOURCE_INDEXEDDATA (1<<30)
  60. #endif
  61. #ifndef D3DSTREAMSOURCE_INSTANCEDATA
  62. #define D3DSTREAMSOURCE_INSTANCEDATA (2<<30)
  63. #endif
  64. namespace Atomic
  65. {
  66. static const D3DCMPFUNC d3dCmpFunc[] =
  67. {
  68. D3DCMP_ALWAYS,
  69. D3DCMP_EQUAL,
  70. D3DCMP_NOTEQUAL,
  71. D3DCMP_LESS,
  72. D3DCMP_LESSEQUAL,
  73. D3DCMP_GREATER,
  74. D3DCMP_GREATEREQUAL
  75. };
  76. static const D3DTEXTUREFILTERTYPE d3dMinMagFilter[] =
  77. {
  78. D3DTEXF_POINT,
  79. D3DTEXF_LINEAR,
  80. D3DTEXF_LINEAR,
  81. D3DTEXF_ANISOTROPIC
  82. };
  83. static const D3DTEXTUREFILTERTYPE d3dMipFilter[] =
  84. {
  85. D3DTEXF_POINT,
  86. D3DTEXF_POINT,
  87. D3DTEXF_LINEAR,
  88. D3DTEXF_ANISOTROPIC
  89. };
  90. static const D3DTEXTUREADDRESS d3dAddressMode[] =
  91. {
  92. D3DTADDRESS_WRAP,
  93. D3DTADDRESS_MIRROR,
  94. D3DTADDRESS_CLAMP,
  95. D3DTADDRESS_BORDER
  96. };
  97. static const DWORD d3dBlendEnable[] =
  98. {
  99. FALSE,
  100. TRUE,
  101. TRUE,
  102. TRUE,
  103. TRUE,
  104. TRUE,
  105. TRUE,
  106. TRUE
  107. };
  108. static const D3DBLEND d3dSrcBlend[] =
  109. {
  110. D3DBLEND_ONE,
  111. D3DBLEND_ONE,
  112. D3DBLEND_DESTCOLOR,
  113. D3DBLEND_SRCALPHA,
  114. D3DBLEND_SRCALPHA,
  115. D3DBLEND_ONE,
  116. D3DBLEND_INVDESTALPHA,
  117. D3DBLEND_ONE,
  118. D3DBLEND_SRCALPHA,
  119. };
  120. static const D3DBLEND d3dDestBlend[] =
  121. {
  122. D3DBLEND_ZERO,
  123. D3DBLEND_ONE,
  124. D3DBLEND_ZERO,
  125. D3DBLEND_INVSRCALPHA,
  126. D3DBLEND_ONE,
  127. D3DBLEND_INVSRCALPHA,
  128. D3DBLEND_DESTALPHA,
  129. D3DBLEND_ONE,
  130. D3DBLEND_ONE
  131. };
  132. static const D3DBLENDOP d3dBlendOp[] =
  133. {
  134. D3DBLENDOP_ADD,
  135. D3DBLENDOP_ADD,
  136. D3DBLENDOP_ADD,
  137. D3DBLENDOP_ADD,
  138. D3DBLENDOP_ADD,
  139. D3DBLENDOP_ADD,
  140. D3DBLENDOP_ADD,
  141. D3DBLENDOP_REVSUBTRACT,
  142. D3DBLENDOP_REVSUBTRACT
  143. };
  144. static const D3DCULL d3dCullMode[] =
  145. {
  146. D3DCULL_NONE,
  147. D3DCULL_CCW,
  148. D3DCULL_CW
  149. };
  150. static const D3DFILLMODE d3dFillMode[] =
  151. {
  152. D3DFILL_SOLID,
  153. D3DFILL_WIREFRAME,
  154. D3DFILL_POINT
  155. };
  156. static const D3DSTENCILOP d3dStencilOp[] =
  157. {
  158. D3DSTENCILOP_KEEP,
  159. D3DSTENCILOP_ZERO,
  160. D3DSTENCILOP_REPLACE,
  161. D3DSTENCILOP_INCR,
  162. D3DSTENCILOP_DECR
  163. };
  164. static unsigned GetD3DColor(const Color& color)
  165. {
  166. unsigned r = (unsigned)(Clamp(color.r_ * 255.0f, 0.0f, 255.0f));
  167. unsigned g = (unsigned)(Clamp(color.g_ * 255.0f, 0.0f, 255.0f));
  168. unsigned b = (unsigned)(Clamp(color.b_ * 255.0f, 0.0f, 255.0f));
  169. unsigned a = (unsigned)(Clamp(color.a_ * 255.0f, 0.0f, 255.0f));
  170. return (((a) & 0xff) << 24) | (((r) & 0xff) << 16) | (((g) & 0xff) << 8) | ((b) & 0xff);
  171. }
  172. static void GetD3DPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount,
  173. D3DPRIMITIVETYPE& d3dPrimitiveType)
  174. {
  175. switch (type)
  176. {
  177. case TRIANGLE_LIST:
  178. primitiveCount = elementCount / 3;
  179. d3dPrimitiveType = D3DPT_TRIANGLELIST;
  180. break;
  181. case LINE_LIST:
  182. primitiveCount = elementCount / 2;
  183. d3dPrimitiveType = D3DPT_LINELIST;
  184. break;
  185. case POINT_LIST:
  186. primitiveCount = elementCount;
  187. d3dPrimitiveType = D3DPT_POINTLIST;
  188. break;
  189. case TRIANGLE_STRIP:
  190. primitiveCount = elementCount - 2;
  191. d3dPrimitiveType = D3DPT_TRIANGLESTRIP;
  192. break;
  193. case LINE_STRIP:
  194. primitiveCount = elementCount - 1;
  195. d3dPrimitiveType = D3DPT_LINESTRIP;
  196. break;
  197. case TRIANGLE_FAN:
  198. primitiveCount = elementCount - 2;
  199. d3dPrimitiveType = D3DPT_TRIANGLEFAN;
  200. break;
  201. }
  202. }
  203. static HWND GetWindowHandle(SDL_Window* window)
  204. {
  205. SDL_SysWMinfo sysInfo;
  206. SDL_VERSION(&sysInfo.version);
  207. SDL_GetWindowWMInfo(window, &sysInfo);
  208. return sysInfo.info.win.window;
  209. }
  210. static unsigned readableDepthFormat = 0;
  211. const Vector2 Graphics::pixelUVOffset(0.5f, 0.5f);
  212. bool Graphics::gl3Support = false;
  213. Graphics::Graphics(Context* context) :
  214. Object(context),
  215. impl_(new GraphicsImpl()),
  216. window_(0),
  217. externalWindow_(0),
  218. width_(0),
  219. height_(0),
  220. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  221. multiSample_(1),
  222. fullscreen_(false),
  223. borderless_(false),
  224. resizable_(false),
  225. highDPI_(false),
  226. vsync_(false),
  227. tripleBuffer_(false),
  228. flushGPU_(false),
  229. sRGB_(false),
  230. anisotropySupport_(false),
  231. dxtTextureSupport_(false),
  232. etcTextureSupport_(false),
  233. pvrtcTextureSupport_(false),
  234. hardwareShadowSupport_(false),
  235. lightPrepassSupport_(false),
  236. deferredSupport_(false),
  237. instancingSupport_(false),
  238. sRGBSupport_(false),
  239. sRGBWriteSupport_(false),
  240. numPrimitives_(0),
  241. numBatches_(0),
  242. maxScratchBufferRequest_(0),
  243. defaultTextureFilterMode_(FILTER_TRILINEAR),
  244. shaderPath_("Shaders/HLSL/"),
  245. shaderExtension_(".hlsl"),
  246. orientations_("LandscapeLeft LandscapeRight"),
  247. apiName_("D3D9")
  248. {
  249. SetTextureUnitMappings();
  250. // Initialize SDL now. Graphics should be the first SDL-using subsystem to be created
  251. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_NOPARACHUTE
  252. | SDL_INIT_TIMER | SDL_INIT_HAPTIC ); // ATOMIC BEGIN HAPTIC //ATOMIC END
  253. // Register Graphics library object factories
  254. RegisterGraphicsLibrary(context_);
  255. }
  256. Graphics::~Graphics()
  257. {
  258. {
  259. MutexLock lock(gpuObjectMutex_);
  260. // Release all GPU objects that still exist
  261. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  262. (*i)->Release();
  263. gpuObjects_.Clear();
  264. }
  265. impl_->vertexDeclarations_.Clear();
  266. ATOMIC_SAFE_RELEASE(impl_->defaultColorSurface_);
  267. ATOMIC_SAFE_RELEASE(impl_->defaultDepthStencilSurface_);
  268. ATOMIC_SAFE_RELEASE(impl_->frameQuery_);
  269. ATOMIC_SAFE_RELEASE(impl_->device_);
  270. ATOMIC_SAFE_RELEASE(impl_->interface_);
  271. if (window_)
  272. {
  273. SDL_ShowCursor(SDL_TRUE);
  274. SDL_DestroyWindow(window_);
  275. window_ = 0;
  276. }
  277. delete impl_;
  278. impl_ = 0;
  279. // Shut down SDL now. Graphics should be the last SDL-using subsystem to be destroyed
  280. SDL_Quit();
  281. }
  282. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool highDPI, bool vsync,
  283. bool tripleBuffer, int multiSample)
  284. {
  285. ATOMIC_PROFILE(SetScreenMode);
  286. highDPI = false; // SDL does not support High DPI mode on Windows platform yet, so always disable it for now
  287. bool maximize = false;
  288. // Find out the full screen mode display format (match desktop color depth)
  289. SDL_DisplayMode mode;
  290. SDL_GetDesktopDisplayMode(0, &mode);
  291. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  292. // 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
  293. if (!width || !height)
  294. {
  295. if (fullscreen || borderless)
  296. {
  297. width = mode.w;
  298. height = mode.h;
  299. }
  300. else
  301. {
  302. maximize = resizable;
  303. width = 1024;
  304. height = 768;
  305. }
  306. }
  307. // Fullscreen or Borderless can not be resizable
  308. if (fullscreen || borderless)
  309. resizable = false;
  310. // Borderless cannot be fullscreen, they are mutually exclusive
  311. if (borderless)
  312. fullscreen = false;
  313. multiSample = Clamp(multiSample, 1, (int)D3DMULTISAMPLE_16_SAMPLES);
  314. // If nothing changes, do not reset the device
  315. if (width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  316. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  317. return true;
  318. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  319. if (!window_)
  320. {
  321. if (!OpenWindow(width, height, resizable, borderless))
  322. return false;
  323. }
  324. if (!impl_->interface_)
  325. {
  326. if (!CreateInterface())
  327. return false;
  328. CheckFeatureSupport();
  329. }
  330. // Note: GetMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  331. multiSample_ = multiSample;
  332. // Check fullscreen mode validity. Use a closest match if not found
  333. if (fullscreen)
  334. {
  335. PODVector<IntVector2> resolutions = GetResolutions();
  336. if (resolutions.Size())
  337. {
  338. unsigned best = 0;
  339. unsigned bestError = M_MAX_UNSIGNED;
  340. for (unsigned i = 0; i < resolutions.Size(); ++i)
  341. {
  342. unsigned error = (unsigned)(Abs(resolutions[i].x_ - width) + Abs(resolutions[i].y_ - height));
  343. if (error < bestError)
  344. {
  345. best = i;
  346. bestError = error;
  347. }
  348. }
  349. width = resolutions[best].x_;
  350. height = resolutions[best].y_;
  351. }
  352. }
  353. // Fall back to non-multisampled if unsupported multisampling mode
  354. if (multiSample > 1)
  355. {
  356. if (FAILED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  357. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  358. multiSample = 1;
  359. }
  360. AdjustWindow(width, height, fullscreen, borderless);
  361. if (maximize)
  362. {
  363. Maximize();
  364. SDL_GetWindowSize(window_, &width, &height);
  365. }
  366. if (fullscreen)
  367. {
  368. impl_->presentParams_.BackBufferFormat = fullscreenFormat;
  369. impl_->presentParams_.Windowed = false;
  370. }
  371. else
  372. {
  373. impl_->presentParams_.BackBufferFormat = D3DFMT_UNKNOWN;
  374. impl_->presentParams_.Windowed = true;
  375. }
  376. impl_->presentParams_.BackBufferWidth = (UINT)width;
  377. impl_->presentParams_.BackBufferHeight = (UINT)height;
  378. impl_->presentParams_.BackBufferCount = tripleBuffer ? 2 : 1;
  379. impl_->presentParams_.MultiSampleType = multiSample > 1 ? (D3DMULTISAMPLE_TYPE)multiSample : D3DMULTISAMPLE_NONE;
  380. impl_->presentParams_.MultiSampleQuality = 0;
  381. impl_->presentParams_.SwapEffect = D3DSWAPEFFECT_DISCARD;
  382. impl_->presentParams_.hDeviceWindow = GetWindowHandle(window_);
  383. impl_->presentParams_.EnableAutoDepthStencil = TRUE;
  384. impl_->presentParams_.AutoDepthStencilFormat = D3DFMT_D24S8;
  385. impl_->presentParams_.Flags = D3DPRESENT_LINEAR_CONTENT;
  386. impl_->presentParams_.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  387. if (vsync)
  388. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  389. else
  390. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  391. width_ = width;
  392. height_ = height;
  393. fullscreen_ = fullscreen;
  394. borderless_ = borderless;
  395. resizable_ = resizable;
  396. highDPI_ = highDPI;
  397. vsync_ = vsync;
  398. tripleBuffer_ = tripleBuffer;
  399. if (!impl_->device_)
  400. {
  401. unsigned adapter = D3DADAPTER_DEFAULT;
  402. unsigned deviceType = D3DDEVTYPE_HAL;
  403. // Check for PerfHUD adapter
  404. for (unsigned i = 0; i < impl_->interface_->GetAdapterCount(); ++i)
  405. {
  406. D3DADAPTER_IDENTIFIER9 identifier;
  407. impl_->interface_->GetAdapterIdentifier(i, 0, &identifier);
  408. if (strstr(identifier.Description, "PerfHUD") != 0)
  409. {
  410. adapter = i;
  411. deviceType = D3DDEVTYPE_REF;
  412. break;
  413. }
  414. }
  415. impl_->interface_->GetAdapterIdentifier(adapter, 0, &impl_->adapterIdentifier_);
  416. if (!CreateDevice(adapter, deviceType))
  417. return false;
  418. }
  419. else
  420. ResetDevice();
  421. // Clear the initial window contents to black
  422. impl_->device_->BeginScene();
  423. Clear(CLEAR_COLOR);
  424. impl_->device_->EndScene();
  425. impl_->device_->Present(0, 0, 0, 0);
  426. #ifdef ATOMIC_LOGGING
  427. String msg;
  428. msg.AppendWithFormat("Set screen mode %dx%d %s", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"));
  429. if (borderless_)
  430. msg.Append(" borderless");
  431. if (resizable_)
  432. msg.Append(" resizable");
  433. if (multiSample > 1)
  434. msg.AppendWithFormat(" multisample %d", multiSample);
  435. ATOMIC_LOGINFO(msg);
  436. #endif
  437. using namespace ScreenMode;
  438. VariantMap& eventData = GetEventDataMap();
  439. eventData[P_WIDTH] = width_;
  440. eventData[P_HEIGHT] = height_;
  441. eventData[P_FULLSCREEN] = fullscreen_;
  442. eventData[P_BORDERLESS] = borderless_;
  443. eventData[P_RESIZABLE] = resizable_;
  444. eventData[P_HIGHDPI] = highDPI_;
  445. SendEvent(E_SCREENMODE, eventData);
  446. return true;
  447. }
  448. bool Graphics::SetMode(int width, int height)
  449. {
  450. return SetMode(width, height, fullscreen_, borderless_, resizable_, highDPI_, vsync_, tripleBuffer_, multiSample_);
  451. }
  452. void Graphics::SetSRGB(bool enable)
  453. {
  454. sRGB_ = enable && sRGBWriteSupport_;
  455. }
  456. void Graphics::SetDither(bool enable)
  457. {
  458. // No effect on Direct3D9
  459. }
  460. void Graphics::SetFlushGPU(bool enable)
  461. {
  462. flushGPU_ = enable;
  463. }
  464. void Graphics::SetForceGL2(bool enable)
  465. {
  466. // No effect on Direct3D9
  467. }
  468. void Graphics::Close()
  469. {
  470. if (window_)
  471. {
  472. SDL_ShowCursor(SDL_TRUE);
  473. SDL_DestroyWindow(window_);
  474. window_ = 0;
  475. }
  476. }
  477. bool Graphics::TakeScreenShot(Image* destImage)
  478. {
  479. ATOMIC_PROFILE(TakeScreenShot);
  480. if (!impl_->device_)
  481. return false;
  482. if (IsDeviceLost())
  483. {
  484. ATOMIC_LOGERROR("Can not take screenshot while device is lost");
  485. return false;
  486. }
  487. D3DSURFACE_DESC surfaceDesc;
  488. impl_->defaultColorSurface_->GetDesc(&surfaceDesc);
  489. // If possible, get the backbuffer data, because it is a lot faster.
  490. // However, if we are multisampled, need to use the front buffer
  491. bool useBackBuffer = true;
  492. unsigned surfaceWidth = (unsigned)width_;
  493. unsigned surfaceHeight = (unsigned)height_;
  494. if (impl_->presentParams_.MultiSampleType)
  495. {
  496. // If windowed and multisampled, must still capture the whole screen
  497. if (!fullscreen_)
  498. {
  499. IntVector2 desktopSize = GetDesktopResolution();
  500. surfaceWidth = (unsigned)desktopSize.x_;
  501. surfaceHeight = (unsigned)desktopSize.y_;
  502. }
  503. useBackBuffer = false;
  504. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  505. }
  506. IDirect3DSurface9* surface = 0;
  507. HRESULT hr = impl_->device_->CreateOffscreenPlainSurface(surfaceWidth, surfaceHeight, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  508. if (FAILED(hr))
  509. {
  510. ATOMIC_SAFE_RELEASE(surface);
  511. ATOMIC_LOGD3DERROR("Could not create surface for taking a screenshot", hr);
  512. return false;
  513. }
  514. if (useBackBuffer)
  515. hr = impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  516. else
  517. hr = impl_->device_->GetFrontBufferData(0, surface);
  518. if (FAILED(hr))
  519. {
  520. ATOMIC_SAFE_RELEASE(surface);
  521. ATOMIC_LOGD3DERROR("Could not get rendertarget data for taking a screenshot", hr);
  522. return false;
  523. }
  524. // If capturing the whole screen, determine the window rect
  525. RECT sourceRect;
  526. if (surfaceHeight == height_ && surfaceWidth == width_)
  527. {
  528. sourceRect.left = 0;
  529. sourceRect.top = 0;
  530. sourceRect.right = width_;
  531. sourceRect.bottom = height_;
  532. }
  533. else
  534. {
  535. HWND hwnd = GetWindowHandle(window_);
  536. GetClientRect(hwnd, &sourceRect);
  537. ClientToScreen(hwnd, (LPPOINT)&sourceRect);
  538. }
  539. D3DLOCKED_RECT lockedRect;
  540. lockedRect.pBits = 0;
  541. hr = surface->LockRect(&lockedRect, &sourceRect, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  542. if (FAILED(hr) || !lockedRect.pBits)
  543. {
  544. ATOMIC_SAFE_RELEASE(surface);
  545. ATOMIC_LOGD3DERROR("Could not lock surface for taking a screenshot", hr);
  546. return false;
  547. }
  548. destImage->SetSize(width_, height_, 3);
  549. unsigned char* destData = destImage->GetData();
  550. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  551. {
  552. for (int y = 0; y < height_; ++y)
  553. {
  554. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  555. unsigned char* dest = destData + y * width_ * 3;
  556. for (int x = 0; x < width_; ++x)
  557. {
  558. unsigned short rgb = *src++;
  559. int b = rgb & 31;
  560. int g = (rgb >> 5) & 63;
  561. int r = (rgb >> 11);
  562. dest[0] = (unsigned char)(r * 255.0f / 31.0f);
  563. dest[1] = (unsigned char)(g * 255.0f / 63.0f);
  564. dest[2] = (unsigned char)(b * 255.0f / 31.0f);
  565. dest += 3;
  566. }
  567. }
  568. }
  569. else
  570. {
  571. for (int y = 0; y < height_; ++y)
  572. {
  573. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  574. unsigned char* dest = destData + y * width_ * 3;
  575. for (int x = 0; x < width_; ++x)
  576. {
  577. dest[0] = src[2];
  578. dest[1] = src[1];
  579. dest[2] = src[0];
  580. src += 4;
  581. dest += 3;
  582. }
  583. }
  584. }
  585. surface->UnlockRect();
  586. surface->Release();
  587. return true;
  588. }
  589. bool Graphics::BeginFrame()
  590. {
  591. if (!IsInitialized())
  592. return false;
  593. // If using an external window, check it for size changes, and reset screen mode if necessary
  594. if (externalWindow_)
  595. {
  596. int width, height;
  597. SDL_GetWindowSize(window_, &width, &height);
  598. if (width != width_ || height != height_)
  599. SetMode(width, height);
  600. }
  601. else
  602. {
  603. // To prevent a loop of endless device loss and flicker, do not attempt to render when in fullscreen
  604. // and the window is minimized
  605. if (fullscreen_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED))
  606. return false;
  607. }
  608. // Check for lost device before rendering
  609. HRESULT hr = impl_->device_->TestCooperativeLevel();
  610. if (hr != D3D_OK)
  611. {
  612. ATOMIC_PROFILE(DeviceLost);
  613. impl_->deviceLost_ = true;
  614. // The device can not be reset yet, sleep and try again eventually
  615. if (hr == D3DERR_DEVICELOST)
  616. {
  617. Time::Sleep(20);
  618. return false;
  619. }
  620. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  621. if (hr == D3DERR_DEVICENOTRESET)
  622. {
  623. ResetDevice();
  624. return false;
  625. }
  626. }
  627. impl_->device_->BeginScene();
  628. // Set default rendertarget and depth buffer
  629. ResetRenderTargets();
  630. // Cleanup textures from previous frame
  631. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  632. SetTexture(i, 0);
  633. numPrimitives_ = 0;
  634. numBatches_ = 0;
  635. SendEvent(E_BEGINRENDERING);
  636. return true;
  637. }
  638. void Graphics::EndFrame()
  639. {
  640. if (!IsInitialized())
  641. return;
  642. {
  643. ATOMIC_PROFILE(Present);
  644. SendEvent(E_ENDRENDERING);
  645. impl_->device_->EndScene();
  646. impl_->device_->Present(0, 0, 0, 0);
  647. }
  648. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to multiple frame buffering
  649. // If a query was issued on the previous frame, first wait for it to finish
  650. if (impl_->frameQuery_)
  651. {
  652. if (impl_->queryIssued_)
  653. {
  654. ATOMIC_PROFILE(FlushGPU);
  655. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  656. {
  657. }
  658. impl_->queryIssued_ = false;
  659. }
  660. if (flushGPU_)
  661. {
  662. impl_->frameQuery_->Issue(D3DISSUE_END);
  663. impl_->queryIssued_ = true;
  664. }
  665. }
  666. // Clean up too large scratch buffers
  667. CleanupScratchBuffers();
  668. }
  669. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  670. {
  671. DWORD d3dFlags = 0;
  672. if (flags & CLEAR_COLOR)
  673. d3dFlags |= D3DCLEAR_TARGET;
  674. if (flags & CLEAR_DEPTH)
  675. d3dFlags |= D3DCLEAR_ZBUFFER;
  676. if (flags & CLEAR_STENCIL)
  677. d3dFlags |= D3DCLEAR_STENCIL;
  678. impl_->device_->Clear(0, 0, d3dFlags, GetD3DColor(color), depth, stencil);
  679. }
  680. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  681. {
  682. if (!destination || !destination->GetRenderSurface())
  683. return false;
  684. ATOMIC_PROFILE(ResolveToTexture);
  685. IntRect vpCopy = viewport;
  686. if (vpCopy.right_ <= vpCopy.left_)
  687. vpCopy.right_ = vpCopy.left_ + 1;
  688. if (vpCopy.bottom_ <= vpCopy.top_)
  689. vpCopy.bottom_ = vpCopy.top_ + 1;
  690. RECT rect;
  691. rect.left = Clamp(vpCopy.left_, 0, width_);
  692. rect.top = Clamp(vpCopy.top_, 0, height_);
  693. rect.right = Clamp(vpCopy.right_, 0, width_);
  694. rect.bottom = Clamp(vpCopy.bottom_, 0, height_);
  695. RECT destRect;
  696. destRect.left = 0;
  697. destRect.top = 0;
  698. destRect.right = destination->GetWidth();
  699. destRect.bottom = destination->GetHeight();
  700. HRESULT hr = impl_->device_->StretchRect(impl_->defaultColorSurface_, &rect,
  701. (IDirect3DSurface9*)destination->GetRenderSurface()->GetSurface(), &destRect, D3DTEXF_NONE);
  702. if (FAILED(hr))
  703. {
  704. ATOMIC_LOGD3DERROR("Failed to resolve to texture", hr);
  705. return false;
  706. }
  707. else
  708. return true;
  709. }
  710. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  711. {
  712. if (!vertexCount)
  713. return;
  714. ResetStreamFrequencies();
  715. unsigned primitiveCount;
  716. D3DPRIMITIVETYPE d3dPrimitiveType;
  717. GetD3DPrimitiveType(vertexCount, type, primitiveCount, d3dPrimitiveType);
  718. impl_->device_->DrawPrimitive(d3dPrimitiveType, vertexStart, primitiveCount);
  719. numPrimitives_ += primitiveCount;
  720. ++numBatches_;
  721. }
  722. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  723. {
  724. if (!indexCount)
  725. return;
  726. ResetStreamFrequencies();
  727. unsigned primitiveCount;
  728. D3DPRIMITIVETYPE d3dPrimitiveType;
  729. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  730. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, 0, minVertex, vertexCount, indexStart, primitiveCount);
  731. numPrimitives_ += primitiveCount;
  732. ++numBatches_;
  733. }
  734. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  735. {
  736. if (!indexCount)
  737. return;
  738. ResetStreamFrequencies();
  739. unsigned primitiveCount;
  740. D3DPRIMITIVETYPE d3dPrimitiveType;
  741. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  742. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, baseVertexIndex, minVertex, vertexCount, indexStart, primitiveCount);
  743. numPrimitives_ += primitiveCount;
  744. ++numBatches_;
  745. }
  746. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  747. unsigned instanceCount)
  748. {
  749. if (!indexCount || !instanceCount)
  750. return;
  751. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  752. {
  753. VertexBuffer* buffer = vertexBuffers_[i];
  754. if (buffer)
  755. {
  756. const PODVector<VertexElement>& elements = buffer->GetElements();
  757. // Check if buffer has per-instance data
  758. if (elements.Size() && elements[0].perInstance_)
  759. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1u);
  760. else
  761. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  762. }
  763. }
  764. unsigned primitiveCount;
  765. D3DPRIMITIVETYPE d3dPrimitiveType;
  766. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  767. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, 0, minVertex, vertexCount, indexStart, primitiveCount);
  768. numPrimitives_ += instanceCount * primitiveCount;
  769. ++numBatches_;
  770. }
  771. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex,
  772. unsigned vertexCount, unsigned instanceCount)
  773. {
  774. if (!indexCount || !instanceCount)
  775. return;
  776. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  777. {
  778. VertexBuffer* buffer = vertexBuffers_[i];
  779. if (buffer)
  780. {
  781. const PODVector<VertexElement>& elements = buffer->GetElements();
  782. // Check if buffer has per-instance data
  783. if (elements.Size() && elements[0].perInstance_)
  784. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1u);
  785. else
  786. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  787. }
  788. }
  789. unsigned primitiveCount;
  790. D3DPRIMITIVETYPE d3dPrimitiveType;
  791. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  792. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, baseVertexIndex, minVertex, vertexCount, indexStart, primitiveCount);
  793. numPrimitives_ += instanceCount * primitiveCount;
  794. ++numBatches_;
  795. }
  796. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  797. {
  798. // Note: this is not multi-instance safe
  799. static PODVector<VertexBuffer*> vertexBuffers(1);
  800. vertexBuffers[0] = buffer;
  801. SetVertexBuffers(vertexBuffers);
  802. }
  803. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, unsigned instanceOffset)
  804. {
  805. if (buffers.Size() > MAX_VERTEX_STREAMS)
  806. {
  807. ATOMIC_LOGERROR("Too many vertex buffers");
  808. return false;
  809. }
  810. // Build vertex declaration hash code out of the buffers
  811. unsigned long long hash = 0;
  812. for (unsigned i = 0; i < buffers.Size(); ++i)
  813. {
  814. if (!buffers[i])
  815. continue;
  816. hash |= buffers[i]->GetBufferHash(i);
  817. }
  818. if (hash)
  819. {
  820. // If no previous vertex declaration for that hash, create new
  821. VertexDeclarationMap::Iterator i = impl_->vertexDeclarations_.Find(hash);
  822. if (i == impl_->vertexDeclarations_.End())
  823. {
  824. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers));
  825. if (!newDeclaration->GetDeclaration())
  826. return false;
  827. i = impl_->vertexDeclarations_.Insert(MakePair(hash, newDeclaration));
  828. }
  829. VertexDeclaration* declaration = i->second_;
  830. if (declaration != impl_->vertexDeclaration_)
  831. {
  832. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  833. impl_->vertexDeclaration_ = declaration;
  834. }
  835. }
  836. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  837. {
  838. VertexBuffer* buffer = 0;
  839. unsigned offset = 0;
  840. if (i < buffers.Size() && buffers[i])
  841. {
  842. buffer = buffers[i];
  843. const PODVector<VertexElement>& elements = buffer->GetElements();
  844. // Check if buffer has per-instance data; add instance offset in that case
  845. if (elements.Size() && elements[0].perInstance_)
  846. offset = instanceOffset * buffer->GetVertexSize();
  847. }
  848. if (buffer != vertexBuffers_[i] || offset != impl_->streamOffsets_[i])
  849. {
  850. if (buffer)
  851. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset,
  852. buffer->GetVertexSize());
  853. else
  854. impl_->device_->SetStreamSource(i, 0, 0, 0);
  855. vertexBuffers_[i] = buffer;
  856. impl_->streamOffsets_[i] = offset;
  857. }
  858. }
  859. return true;
  860. }
  861. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, unsigned instanceOffset)
  862. {
  863. return SetVertexBuffers(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), instanceOffset);
  864. }
  865. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  866. {
  867. if (buffer != indexBuffer_)
  868. {
  869. if (buffer)
  870. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  871. else
  872. impl_->device_->SetIndices(0);
  873. indexBuffer_ = buffer;
  874. }
  875. }
  876. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  877. {
  878. if (vs == vertexShader_ && ps == pixelShader_)
  879. return;
  880. ClearParameterSources();
  881. if (vs != vertexShader_)
  882. {
  883. // Create the shader now if not yet created. If already attempted, do not retry
  884. if (vs && !vs->GetGPUObject())
  885. {
  886. if (vs->GetCompilerOutput().Empty())
  887. {
  888. ATOMIC_PROFILE(CompileVertexShader);
  889. bool success = vs->Create();
  890. if (!success)
  891. {
  892. ATOMIC_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  893. vs = 0;
  894. }
  895. }
  896. else
  897. vs = 0;
  898. }
  899. if (vs && vs->GetShaderType() == VS)
  900. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  901. else
  902. {
  903. impl_->device_->SetVertexShader(0);
  904. vs = 0;
  905. }
  906. vertexShader_ = vs;
  907. }
  908. if (ps != pixelShader_)
  909. {
  910. if (ps && !ps->GetGPUObject())
  911. {
  912. if (ps->GetCompilerOutput().Empty())
  913. {
  914. ATOMIC_PROFILE(CompilePixelShader);
  915. bool success = ps->Create();
  916. if (!success)
  917. {
  918. ATOMIC_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  919. ps = 0;
  920. }
  921. }
  922. else
  923. ps = 0;
  924. }
  925. if (ps && ps->GetShaderType() == PS)
  926. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  927. else
  928. {
  929. impl_->device_->SetPixelShader(0);
  930. ps = 0;
  931. }
  932. pixelShader_ = ps;
  933. }
  934. // Update current available shader parameters
  935. if (vertexShader_ && pixelShader_)
  936. {
  937. Pair<ShaderVariation*, ShaderVariation*> key = MakePair(vertexShader_, pixelShader_);
  938. ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Find(key);
  939. if (i != impl_->shaderPrograms_.End())
  940. impl_->shaderProgram_ = i->second_.Get();
  941. else
  942. {
  943. ShaderProgram* newProgram = impl_->shaderPrograms_[key] = new ShaderProgram(vertexShader_, pixelShader_);
  944. impl_->shaderProgram_ = newProgram;
  945. }
  946. }
  947. else
  948. impl_->shaderProgram_ = 0;
  949. // Store shader combination if shader dumping in progress
  950. if (shaderPrecache_)
  951. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  952. }
  953. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  954. {
  955. HashMap<StringHash, ShaderParameter>::Iterator i;
  956. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  957. return;
  958. if (i->second_.type_ == VS)
  959. impl_->device_->SetVertexShaderConstantF(i->second_.register_, data, count / 4);
  960. else
  961. impl_->device_->SetPixelShaderConstantF(i->second_.register_, data, count / 4);
  962. }
  963. void Graphics::SetShaderParameter(StringHash param, float value)
  964. {
  965. HashMap<StringHash, ShaderParameter>::Iterator i;
  966. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  967. return;
  968. static Vector4 data(Vector4::ZERO);
  969. data.x_ = value;
  970. if (i->second_.type_ == VS)
  971. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  972. else
  973. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  974. }
  975. void Graphics::SetShaderParameter(StringHash param, bool value)
  976. {
  977. /// \todo Bool constants possibly have no effect on Direct3D9
  978. HashMap<StringHash, ShaderParameter>::Iterator i;
  979. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  980. return;
  981. BOOL data = value;
  982. if (i->second_.type_ == VS)
  983. impl_->device_->SetVertexShaderConstantB(i->second_.register_, &data, 1);
  984. else
  985. impl_->device_->SetPixelShaderConstantB(i->second_.register_, &data, 1);
  986. }
  987. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  988. {
  989. HashMap<StringHash, ShaderParameter>::Iterator i;
  990. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  991. return;
  992. if (i->second_.type_ == VS)
  993. impl_->device_->SetVertexShaderConstantF(i->second_.register_, color.Data(), 1);
  994. else
  995. impl_->device_->SetPixelShaderConstantF(i->second_.register_, color.Data(), 1);
  996. }
  997. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  998. {
  999. HashMap<StringHash, ShaderParameter>::Iterator i;
  1000. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1001. return;
  1002. static Vector4 data(Vector4::ZERO);
  1003. data.x_ = vector.x_;
  1004. data.y_ = vector.y_;
  1005. if (i->second_.type_ == VS)
  1006. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  1007. else
  1008. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  1009. }
  1010. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1011. {
  1012. HashMap<StringHash, ShaderParameter>::Iterator i;
  1013. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1014. return;
  1015. static Matrix3x4 data(Matrix3x4::ZERO);
  1016. data.m00_ = matrix.m00_;
  1017. data.m01_ = matrix.m01_;
  1018. data.m02_ = matrix.m02_;
  1019. data.m10_ = matrix.m10_;
  1020. data.m11_ = matrix.m11_;
  1021. data.m12_ = matrix.m12_;
  1022. data.m20_ = matrix.m20_;
  1023. data.m21_ = matrix.m21_;
  1024. data.m22_ = matrix.m22_;
  1025. if (i->second_.type_ == VS)
  1026. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.m00_, 3);
  1027. else
  1028. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.m00_, 3);
  1029. }
  1030. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1031. {
  1032. HashMap<StringHash, ShaderParameter>::Iterator i;
  1033. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1034. return;
  1035. static Vector4 data(Vector4::ZERO);
  1036. data.x_ = vector.x_;
  1037. data.y_ = vector.y_;
  1038. data.z_ = vector.z_;
  1039. if (i->second_.type_ == VS)
  1040. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  1041. else
  1042. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  1043. }
  1044. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1045. {
  1046. HashMap<StringHash, ShaderParameter>::Iterator i;
  1047. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1048. return;
  1049. if (i->second_.type_ == VS)
  1050. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1051. else
  1052. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1053. }
  1054. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1055. {
  1056. HashMap<StringHash, ShaderParameter>::Iterator i;
  1057. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1058. return;
  1059. if (i->second_.type_ == VS)
  1060. impl_->device_->SetVertexShaderConstantF(i->second_.register_, vector.Data(), 1);
  1061. else
  1062. impl_->device_->SetPixelShaderConstantF(i->second_.register_, vector.Data(), 1);
  1063. }
  1064. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1065. {
  1066. HashMap<StringHash, ShaderParameter>::Iterator i;
  1067. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1068. return;
  1069. if (i->second_.type_ == VS)
  1070. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1071. else
  1072. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1073. }
  1074. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1075. {
  1076. switch (value.GetType())
  1077. {
  1078. case VAR_BOOL:
  1079. SetShaderParameter(param, value.GetBool());
  1080. break;
  1081. case VAR_FLOAT:
  1082. SetShaderParameter(param, value.GetFloat());
  1083. break;
  1084. case VAR_VECTOR2:
  1085. SetShaderParameter(param, value.GetVector2());
  1086. break;
  1087. case VAR_VECTOR3:
  1088. SetShaderParameter(param, value.GetVector3());
  1089. break;
  1090. case VAR_VECTOR4:
  1091. SetShaderParameter(param, value.GetVector4());
  1092. break;
  1093. case VAR_COLOR:
  1094. SetShaderParameter(param, value.GetColor());
  1095. break;
  1096. case VAR_MATRIX3:
  1097. SetShaderParameter(param, value.GetMatrix3());
  1098. break;
  1099. case VAR_MATRIX3X4:
  1100. SetShaderParameter(param, value.GetMatrix3x4());
  1101. break;
  1102. case VAR_MATRIX4:
  1103. SetShaderParameter(param, value.GetMatrix4());
  1104. break;
  1105. case VAR_BUFFER:
  1106. {
  1107. const PODVector<unsigned char>& buffer = value.GetBuffer();
  1108. if (buffer.Size() >= sizeof(float))
  1109. SetShaderParameter(param, reinterpret_cast<const float*>(&buffer[0]), buffer.Size() / sizeof(float));
  1110. }
  1111. break;
  1112. default:
  1113. // Unsupported parameter type, do nothing
  1114. break;
  1115. }
  1116. }
  1117. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1118. {
  1119. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1120. {
  1121. shaderParameterSources_[group] = source;
  1122. return true;
  1123. }
  1124. else
  1125. return false;
  1126. }
  1127. bool Graphics::HasShaderParameter(StringHash param)
  1128. {
  1129. return impl_->shaderProgram_ && impl_->shaderProgram_->parameters_.Find(param) != impl_->shaderProgram_->parameters_.End();
  1130. }
  1131. bool Graphics::HasTextureUnit(TextureUnit unit)
  1132. {
  1133. return pixelShader_ && pixelShader_->HasTextureUnit(unit);
  1134. }
  1135. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1136. {
  1137. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1138. }
  1139. void Graphics::ClearParameterSources()
  1140. {
  1141. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1142. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1143. }
  1144. void Graphics::ClearTransformSources()
  1145. {
  1146. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1147. shaderParameterSources_[SP_OBJECT] = (const void*)M_MAX_UNSIGNED;
  1148. }
  1149. void Graphics::SetTexture(unsigned index, Texture* texture)
  1150. {
  1151. if (index >= MAX_TEXTURE_UNITS)
  1152. return;
  1153. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1154. if (texture)
  1155. {
  1156. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1157. texture = texture->GetBackupTexture();
  1158. }
  1159. if (texture != textures_[index])
  1160. {
  1161. if (texture)
  1162. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1163. else
  1164. impl_->device_->SetTexture(index, 0);
  1165. textures_[index] = texture;
  1166. }
  1167. if (texture)
  1168. {
  1169. TextureFilterMode filterMode = texture->GetFilterMode();
  1170. if (filterMode == FILTER_DEFAULT)
  1171. filterMode = defaultTextureFilterMode_;
  1172. D3DTEXTUREFILTERTYPE minMag, mip;
  1173. minMag = d3dMinMagFilter[filterMode];
  1174. if (minMag != impl_->minMagFilters_[index])
  1175. {
  1176. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1177. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1178. impl_->minMagFilters_[index] = minMag;
  1179. }
  1180. mip = d3dMipFilter[filterMode];
  1181. if (mip != impl_->mipFilters_[index])
  1182. {
  1183. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1184. impl_->mipFilters_[index] = mip;
  1185. }
  1186. D3DTEXTUREADDRESS u, v;
  1187. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1188. if (u != impl_->uAddressModes_[index])
  1189. {
  1190. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1191. impl_->uAddressModes_[index] = u;
  1192. }
  1193. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1194. if (v != impl_->vAddressModes_[index])
  1195. {
  1196. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1197. impl_->vAddressModes_[index] = v;
  1198. }
  1199. if (texture->GetType() == TextureCube::GetTypeStatic())
  1200. {
  1201. D3DTEXTUREADDRESS w = d3dAddressMode[texture->GetAddressMode(COORD_W)];
  1202. if (w != impl_->wAddressModes_[index])
  1203. {
  1204. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSW, w);
  1205. impl_->wAddressModes_[index] = w;
  1206. }
  1207. }
  1208. if (u == D3DTADDRESS_BORDER || v == D3DTADDRESS_BORDER)
  1209. {
  1210. const Color& borderColor = texture->GetBorderColor();
  1211. if (borderColor != impl_->borderColors_[index])
  1212. {
  1213. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, GetD3DColor(borderColor));
  1214. impl_->borderColors_[index] = borderColor;
  1215. }
  1216. }
  1217. if (sRGBSupport_)
  1218. {
  1219. bool sRGB = texture->GetSRGB();
  1220. if (sRGB != impl_->sRGBModes_[index])
  1221. {
  1222. impl_->device_->SetSamplerState(index, D3DSAMP_SRGBTEXTURE, sRGB ? TRUE : FALSE);
  1223. impl_->sRGBModes_[index] = sRGB;
  1224. }
  1225. }
  1226. }
  1227. }
  1228. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1229. {
  1230. defaultTextureFilterMode_ = mode;
  1231. }
  1232. void Graphics::ResetRenderTargets()
  1233. {
  1234. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1235. SetRenderTarget(i, (RenderSurface*)0);
  1236. SetDepthStencil((RenderSurface*)0);
  1237. SetViewport(IntRect(0, 0, width_, height_));
  1238. }
  1239. void Graphics::ResetRenderTarget(unsigned index)
  1240. {
  1241. SetRenderTarget(index, (RenderSurface*)0);
  1242. }
  1243. void Graphics::ResetDepthStencil()
  1244. {
  1245. SetDepthStencil((RenderSurface*)0);
  1246. }
  1247. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1248. {
  1249. if (index >= MAX_RENDERTARGETS)
  1250. return;
  1251. IDirect3DSurface9* newColorSurface = 0;
  1252. if (renderTarget)
  1253. {
  1254. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1255. return;
  1256. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1257. }
  1258. else
  1259. {
  1260. if (!index)
  1261. newColorSurface = impl_->defaultColorSurface_;
  1262. }
  1263. renderTargets_[index] = renderTarget;
  1264. if (newColorSurface != impl_->colorSurfaces_[index])
  1265. {
  1266. impl_->device_->SetRenderTarget(index, newColorSurface);
  1267. impl_->colorSurfaces_[index] = newColorSurface;
  1268. // Setting the first rendertarget causes viewport to be reset
  1269. if (!index)
  1270. {
  1271. IntVector2 rtSize = GetRenderTargetDimensions();
  1272. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1273. }
  1274. }
  1275. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1276. if (renderTarget)
  1277. {
  1278. Texture* parentTexture = renderTarget->GetParentTexture();
  1279. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1280. {
  1281. if (textures_[i] == parentTexture)
  1282. SetTexture(i, textures_[i]->GetBackupTexture());
  1283. }
  1284. }
  1285. // First rendertarget controls sRGB write mode
  1286. if (!index && sRGBWriteSupport_)
  1287. {
  1288. bool sRGBWrite = renderTarget ? renderTarget->GetParentTexture()->GetSRGB() : sRGB_;
  1289. if (sRGBWrite != impl_->sRGBWrite_)
  1290. {
  1291. impl_->device_->SetRenderState(D3DRS_SRGBWRITEENABLE, sRGBWrite ? TRUE : FALSE);
  1292. impl_->sRGBWrite_ = sRGBWrite;
  1293. }
  1294. }
  1295. }
  1296. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1297. {
  1298. RenderSurface* renderTarget = 0;
  1299. if (texture)
  1300. renderTarget = texture->GetRenderSurface();
  1301. SetRenderTarget(index, renderTarget);
  1302. }
  1303. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1304. {
  1305. IDirect3DSurface9* newDepthStencilSurface = 0;
  1306. if (depthStencil && depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL)
  1307. {
  1308. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1309. depthStencil_ = depthStencil;
  1310. }
  1311. if (!newDepthStencilSurface)
  1312. {
  1313. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1314. depthStencil_ = 0;
  1315. }
  1316. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1317. {
  1318. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1319. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1320. }
  1321. }
  1322. void Graphics::SetDepthStencil(Texture2D* texture)
  1323. {
  1324. RenderSurface* depthStencil = 0;
  1325. if (texture)
  1326. depthStencil = texture->GetRenderSurface();
  1327. SetDepthStencil(depthStencil);
  1328. }
  1329. void Graphics::SetViewport(const IntRect& rect)
  1330. {
  1331. IntVector2 size = GetRenderTargetDimensions();
  1332. IntRect rectCopy = rect;
  1333. if (rectCopy.right_ <= rectCopy.left_)
  1334. rectCopy.right_ = rectCopy.left_ + 1;
  1335. if (rectCopy.bottom_ <= rectCopy.top_)
  1336. rectCopy.bottom_ = rectCopy.top_ + 1;
  1337. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1338. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1339. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1340. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1341. D3DVIEWPORT9 vp;
  1342. vp.MinZ = 0.0f;
  1343. vp.MaxZ = 1.0f;
  1344. vp.X = (DWORD)rectCopy.left_;
  1345. vp.Y = (DWORD)rectCopy.top_;
  1346. vp.Width = (DWORD)rectCopy.Width();
  1347. vp.Height = (DWORD)rectCopy.Height();
  1348. impl_->device_->SetViewport(&vp);
  1349. viewport_ = rectCopy;
  1350. // Disable scissor test, needs to be re-enabled by the user
  1351. SetScissorTest(false);
  1352. }
  1353. void Graphics::SetTextureAnisotropy(unsigned level)
  1354. {
  1355. if (level < 1)
  1356. level = 1;
  1357. if (level != textureAnisotropy_)
  1358. {
  1359. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1360. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1361. textureAnisotropy_ = level;
  1362. }
  1363. }
  1364. void Graphics::SetBlendMode(BlendMode mode)
  1365. {
  1366. if (mode != blendMode_)
  1367. {
  1368. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1369. {
  1370. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1371. impl_->blendEnable_ = d3dBlendEnable[mode];
  1372. }
  1373. if (impl_->blendEnable_)
  1374. {
  1375. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1376. {
  1377. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1378. impl_->srcBlend_ = d3dSrcBlend[mode];
  1379. }
  1380. if (d3dDestBlend[mode] != impl_->destBlend_)
  1381. {
  1382. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1383. impl_->destBlend_ = d3dDestBlend[mode];
  1384. }
  1385. if (d3dBlendOp[mode] != impl_->blendOp_)
  1386. {
  1387. impl_->device_->SetRenderState(D3DRS_BLENDOP, d3dBlendOp[mode]);
  1388. impl_->blendOp_ = d3dBlendOp[mode];
  1389. }
  1390. }
  1391. blendMode_ = mode;
  1392. }
  1393. }
  1394. void Graphics::SetColorWrite(bool enable)
  1395. {
  1396. if (enable != colorWrite_)
  1397. {
  1398. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE,
  1399. enable ? D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA :
  1400. 0);
  1401. colorWrite_ = enable;
  1402. }
  1403. }
  1404. void Graphics::SetCullMode(CullMode mode)
  1405. {
  1406. if (mode != cullMode_)
  1407. {
  1408. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1409. cullMode_ = mode;
  1410. }
  1411. }
  1412. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1413. {
  1414. if (constantBias != constantDepthBias_)
  1415. {
  1416. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1417. constantDepthBias_ = constantBias;
  1418. }
  1419. if (slopeScaledBias != slopeScaledDepthBias_)
  1420. {
  1421. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1422. slopeScaledDepthBias_ = slopeScaledBias;
  1423. }
  1424. }
  1425. void Graphics::SetDepthTest(CompareMode mode)
  1426. {
  1427. if (mode != depthTestMode_)
  1428. {
  1429. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1430. depthTestMode_ = mode;
  1431. }
  1432. }
  1433. void Graphics::SetDepthWrite(bool enable)
  1434. {
  1435. if (enable != depthWrite_)
  1436. {
  1437. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1438. depthWrite_ = enable;
  1439. }
  1440. }
  1441. void Graphics::SetFillMode(FillMode mode)
  1442. {
  1443. if (mode != fillMode_)
  1444. {
  1445. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1446. fillMode_ = mode;
  1447. }
  1448. }
  1449. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1450. {
  1451. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1452. // Disable scissor in that case to reduce state changes
  1453. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1454. enable = false;
  1455. if (enable)
  1456. {
  1457. IntVector2 rtSize(GetRenderTargetDimensions());
  1458. IntVector2 viewSize(viewport_.Size());
  1459. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1460. IntRect intRect;
  1461. int expand = borderInclusive ? 1 : 0;
  1462. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1463. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1464. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1465. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1466. if (intRect.right_ == intRect.left_)
  1467. intRect.right_++;
  1468. if (intRect.bottom_ == intRect.top_)
  1469. intRect.bottom_++;
  1470. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1471. enable = false;
  1472. if (enable && scissorRect_ != intRect)
  1473. {
  1474. RECT d3dRect;
  1475. d3dRect.left = intRect.left_;
  1476. d3dRect.top = intRect.top_;
  1477. d3dRect.right = intRect.right_;
  1478. d3dRect.bottom = intRect.bottom_;
  1479. impl_->device_->SetScissorRect(&d3dRect);
  1480. scissorRect_ = intRect;
  1481. }
  1482. }
  1483. else
  1484. scissorRect_ = IntRect::ZERO;
  1485. if (enable != scissorTest_)
  1486. {
  1487. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1488. scissorTest_ = enable;
  1489. }
  1490. }
  1491. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1492. {
  1493. IntVector2 rtSize(GetRenderTargetDimensions());
  1494. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1495. if (enable)
  1496. {
  1497. IntRect intRect;
  1498. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1499. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1500. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1501. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1502. if (intRect.right_ == intRect.left_)
  1503. intRect.right_++;
  1504. if (intRect.bottom_ == intRect.top_)
  1505. intRect.bottom_++;
  1506. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1507. enable = false;
  1508. if (enable && scissorRect_ != intRect)
  1509. {
  1510. RECT d3dRect;
  1511. d3dRect.left = intRect.left_;
  1512. d3dRect.top = intRect.top_;
  1513. d3dRect.right = intRect.right_;
  1514. d3dRect.bottom = intRect.bottom_;
  1515. impl_->device_->SetScissorRect(&d3dRect);
  1516. scissorRect_ = intRect;
  1517. }
  1518. }
  1519. else
  1520. scissorRect_ = IntRect::ZERO;
  1521. if (enable != scissorTest_)
  1522. {
  1523. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1524. scissorTest_ = enable;
  1525. }
  1526. }
  1527. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1528. unsigned compareMask, unsigned writeMask)
  1529. {
  1530. if (enable != stencilTest_)
  1531. {
  1532. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1533. stencilTest_ = enable;
  1534. }
  1535. if (enable)
  1536. {
  1537. if (mode != stencilTestMode_)
  1538. {
  1539. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1540. stencilTestMode_ = mode;
  1541. }
  1542. if (pass != stencilPass_)
  1543. {
  1544. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1545. stencilPass_ = pass;
  1546. }
  1547. if (fail != stencilFail_)
  1548. {
  1549. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1550. stencilFail_ = fail;
  1551. }
  1552. if (zFail != stencilZFail_)
  1553. {
  1554. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1555. stencilZFail_ = zFail;
  1556. }
  1557. if (stencilRef != stencilRef_)
  1558. {
  1559. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1560. stencilRef_ = stencilRef;
  1561. }
  1562. if (compareMask != stencilCompareMask_)
  1563. {
  1564. impl_->device_->SetRenderState(D3DRS_STENCILMASK, compareMask);
  1565. stencilCompareMask_ = compareMask;
  1566. }
  1567. if (writeMask != stencilWriteMask_)
  1568. {
  1569. impl_->device_->SetRenderState(D3DRS_STENCILWRITEMASK, writeMask);
  1570. stencilWriteMask_ = writeMask;
  1571. }
  1572. }
  1573. }
  1574. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1575. {
  1576. if (enable != useClipPlane_)
  1577. {
  1578. impl_->device_->SetRenderState(D3DRS_CLIPPLANEENABLE, enable ? 1 : 0);
  1579. useClipPlane_ = enable;
  1580. }
  1581. if (enable)
  1582. {
  1583. Matrix4 viewProj = projection * view;
  1584. impl_->device_->SetClipPlane(0, clipPlane.Transformed(viewProj).ToVector4().Data());
  1585. }
  1586. }
  1587. void Graphics::BeginDumpShaders(const String& fileName)
  1588. {
  1589. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1590. }
  1591. void Graphics::EndDumpShaders()
  1592. {
  1593. shaderPrecache_.Reset();
  1594. }
  1595. void Graphics::PrecacheShaders(Deserializer& source)
  1596. {
  1597. ATOMIC_PROFILE(PrecacheShaders);
  1598. ShaderPrecache::LoadShaders(this, source);
  1599. }
  1600. bool Graphics::IsInitialized() const
  1601. {
  1602. return window_ != 0 && impl_->GetDevice() != 0;
  1603. }
  1604. PODVector<int> Graphics::GetMultiSampleLevels() const
  1605. {
  1606. PODVector<int> ret;
  1607. // No multisampling always supported
  1608. ret.Push(1);
  1609. if (!impl_->interface_)
  1610. return ret;
  1611. SDL_DisplayMode mode;
  1612. SDL_GetDesktopDisplayMode(0, &mode);
  1613. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  1614. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1615. {
  1616. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  1617. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1618. ret.Push(i);
  1619. }
  1620. return ret;
  1621. }
  1622. unsigned Graphics::GetFormat(CompressedFormat format) const
  1623. {
  1624. switch (format)
  1625. {
  1626. case CF_RGBA:
  1627. return D3DFMT_A8R8G8B8;
  1628. case CF_DXT1:
  1629. return D3DFMT_DXT1;
  1630. case CF_DXT3:
  1631. return D3DFMT_DXT3;
  1632. case CF_DXT5:
  1633. return D3DFMT_DXT5;
  1634. default:
  1635. return 0;
  1636. }
  1637. }
  1638. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1639. {
  1640. return GetShader(type, name.CString(), defines.CString());
  1641. }
  1642. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1643. {
  1644. if (lastShaderName_ != name || !lastShader_)
  1645. {
  1646. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1647. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1648. // Try to reduce repeated error log prints because of missing shaders
  1649. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1650. return 0;
  1651. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1652. lastShaderName_ = name;
  1653. }
  1654. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1655. }
  1656. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1657. {
  1658. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1659. }
  1660. TextureUnit Graphics::GetTextureUnit(const String& name)
  1661. {
  1662. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1663. if (i != textureUnits_.End())
  1664. return i->second_;
  1665. else
  1666. return MAX_TEXTURE_UNITS;
  1667. }
  1668. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1669. {
  1670. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1671. {
  1672. if (i->second_ == unit)
  1673. return i->first_;
  1674. }
  1675. return String::EMPTY;
  1676. }
  1677. Texture* Graphics::GetTexture(unsigned index) const
  1678. {
  1679. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1680. }
  1681. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1682. {
  1683. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1684. }
  1685. IntVector2 Graphics::GetRenderTargetDimensions() const
  1686. {
  1687. int width, height;
  1688. if (renderTargets_[0])
  1689. {
  1690. width = renderTargets_[0]->GetWidth();
  1691. height = renderTargets_[0]->GetHeight();
  1692. }
  1693. else
  1694. {
  1695. width = width_;
  1696. height = height_;
  1697. }
  1698. return IntVector2(width, height);
  1699. }
  1700. bool Graphics::GetDither() const
  1701. {
  1702. return false;
  1703. }
  1704. bool Graphics::IsDeviceLost() const
  1705. {
  1706. return impl_->deviceLost_;
  1707. }
  1708. void Graphics::OnWindowResized()
  1709. {
  1710. if (!impl_->device_ || !window_)
  1711. return;
  1712. int newWidth, newHeight;
  1713. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1714. if (newWidth == width_ && newHeight == height_)
  1715. return;
  1716. width_ = newWidth;
  1717. height_ = newHeight;
  1718. impl_->presentParams_.BackBufferWidth = (UINT)width_;
  1719. impl_->presentParams_.BackBufferHeight = (UINT)height_;
  1720. ResetDevice();
  1721. // Reset rendertargets and viewport for the new screen size
  1722. ResetRenderTargets();
  1723. ATOMIC_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1724. using namespace ScreenMode;
  1725. VariantMap& eventData = GetEventDataMap();
  1726. eventData[P_WIDTH] = width_;
  1727. eventData[P_HEIGHT] = height_;
  1728. eventData[P_FULLSCREEN] = fullscreen_;
  1729. eventData[P_RESIZABLE] = resizable_;
  1730. eventData[P_BORDERLESS] = borderless_;
  1731. SendEvent(E_SCREENMODE, eventData);
  1732. }
  1733. void Graphics::OnWindowMoved()
  1734. {
  1735. if (!impl_->device_ || !window_ || fullscreen_)
  1736. return;
  1737. int newX, newY;
  1738. SDL_GetWindowPosition(window_, &newX, &newY);
  1739. if (newX == position_.x_ && newY == position_.y_)
  1740. return;
  1741. position_.x_ = newX;
  1742. position_.y_ = newY;
  1743. ATOMIC_LOGDEBUGF("Window was moved to %d,%d", position_.x_, position_.y_);
  1744. using namespace WindowPos;
  1745. VariantMap& eventData = GetEventDataMap();
  1746. eventData[P_X] = position_.x_;
  1747. eventData[P_Y] = position_.y_;
  1748. SendEvent(E_WINDOWPOS, eventData);
  1749. }
  1750. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  1751. {
  1752. for (ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Begin(); i != impl_->shaderPrograms_.End();)
  1753. {
  1754. if (i->first_.first_ == variation || i->first_.second_ == variation)
  1755. i = impl_->shaderPrograms_.Erase(i);
  1756. else
  1757. ++i;
  1758. }
  1759. if (vertexShader_ == variation || pixelShader_ == variation)
  1760. impl_->shaderProgram_ = 0;
  1761. }
  1762. unsigned Graphics::GetAlphaFormat()
  1763. {
  1764. return D3DFMT_A8;
  1765. }
  1766. unsigned Graphics::GetLuminanceFormat()
  1767. {
  1768. return D3DFMT_L8;
  1769. }
  1770. unsigned Graphics::GetLuminanceAlphaFormat()
  1771. {
  1772. return D3DFMT_A8L8;
  1773. }
  1774. unsigned Graphics::GetRGBFormat()
  1775. {
  1776. return D3DFMT_X8R8G8B8;
  1777. }
  1778. unsigned Graphics::GetRGBAFormat()
  1779. {
  1780. return D3DFMT_A8R8G8B8;
  1781. }
  1782. unsigned Graphics::GetRGBA16Format()
  1783. {
  1784. return D3DFMT_A16B16G16R16;
  1785. }
  1786. unsigned Graphics::GetRGBAFloat16Format()
  1787. {
  1788. return D3DFMT_A16B16G16R16F;
  1789. }
  1790. unsigned Graphics::GetRGBAFloat32Format()
  1791. {
  1792. return D3DFMT_A32B32G32R32F;
  1793. }
  1794. unsigned Graphics::GetRG16Format()
  1795. {
  1796. return D3DFMT_G16R16;
  1797. }
  1798. unsigned Graphics::GetRGFloat16Format()
  1799. {
  1800. return D3DFMT_G16R16F;
  1801. }
  1802. unsigned Graphics::GetRGFloat32Format()
  1803. {
  1804. return D3DFMT_G32R32F;
  1805. }
  1806. unsigned Graphics::GetFloat16Format()
  1807. {
  1808. return D3DFMT_R16F;
  1809. }
  1810. unsigned Graphics::GetFloat32Format()
  1811. {
  1812. return D3DFMT_R32F;
  1813. }
  1814. unsigned Graphics::GetLinearDepthFormat()
  1815. {
  1816. return D3DFMT_R32F;
  1817. }
  1818. unsigned Graphics::GetDepthStencilFormat()
  1819. {
  1820. return D3DFMT_D24S8;
  1821. }
  1822. unsigned Graphics::GetReadableDepthFormat()
  1823. {
  1824. return readableDepthFormat;
  1825. }
  1826. unsigned Graphics::GetFormat(const String& formatName)
  1827. {
  1828. String nameLower = formatName.ToLower().Trimmed();
  1829. if (nameLower == "a")
  1830. return GetAlphaFormat();
  1831. if (nameLower == "l")
  1832. return GetLuminanceFormat();
  1833. if (nameLower == "la")
  1834. return GetLuminanceAlphaFormat();
  1835. if (nameLower == "rgb")
  1836. return GetRGBFormat();
  1837. if (nameLower == "rgba")
  1838. return GetRGBAFormat();
  1839. if (nameLower == "rgba16")
  1840. return GetRGBA16Format();
  1841. if (nameLower == "rgba16f")
  1842. return GetRGBAFloat16Format();
  1843. if (nameLower == "rgba32f")
  1844. return GetRGBAFloat32Format();
  1845. if (nameLower == "rg16")
  1846. return GetRG16Format();
  1847. if (nameLower == "rg16f")
  1848. return GetRGFloat16Format();
  1849. if (nameLower == "rg32f")
  1850. return GetRGFloat32Format();
  1851. if (nameLower == "r16f")
  1852. return GetFloat16Format();
  1853. if (nameLower == "r32f" || nameLower == "float")
  1854. return GetFloat32Format();
  1855. if (nameLower == "lineardepth" || nameLower == "depth")
  1856. return GetLinearDepthFormat();
  1857. if (nameLower == "d24s8")
  1858. return GetDepthStencilFormat();
  1859. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  1860. return GetReadableDepthFormat();
  1861. return GetRGBFormat();
  1862. }
  1863. unsigned Graphics::GetMaxBones()
  1864. {
  1865. return 64;
  1866. }
  1867. bool Graphics::GetGL3Support()
  1868. {
  1869. return gl3Support;
  1870. }
  1871. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1872. {
  1873. if (index < MAX_VERTEX_STREAMS && impl_->streamFrequencies_[index] != frequency)
  1874. {
  1875. impl_->device_->SetStreamSourceFreq(index, frequency);
  1876. impl_->streamFrequencies_[index] = frequency;
  1877. }
  1878. }
  1879. void Graphics::ResetStreamFrequencies()
  1880. {
  1881. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1882. {
  1883. if (impl_->streamFrequencies_[i] != 1)
  1884. {
  1885. impl_->device_->SetStreamSourceFreq(i, 1);
  1886. impl_->streamFrequencies_[i] = 1;
  1887. }
  1888. }
  1889. }
  1890. bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
  1891. {
  1892. if (!externalWindow_)
  1893. {
  1894. unsigned flags = 0;
  1895. if (resizable)
  1896. flags |= SDL_WINDOW_RESIZABLE;
  1897. if (borderless)
  1898. flags |= SDL_WINDOW_BORDERLESS;
  1899. window_ = SDL_CreateWindow(windowTitle_.CString(), position_.x_, position_.y_, width, height, flags);
  1900. }
  1901. else
  1902. window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1903. if (!window_)
  1904. {
  1905. ATOMIC_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  1906. return false;
  1907. }
  1908. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  1909. CreateWindowIcon();
  1910. return true;
  1911. }
  1912. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless)
  1913. {
  1914. if (!externalWindow_)
  1915. {
  1916. if (!newWidth || !newHeight)
  1917. {
  1918. SDL_MaximizeWindow(window_);
  1919. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1920. }
  1921. else
  1922. SDL_SetWindowSize(window_, newWidth, newHeight);
  1923. // Hack fix: on SDL 2.0.4 a fullscreen->windowed transition results in a maximized window when the D3D device is reset, so hide before
  1924. SDL_HideWindow(window_);
  1925. SDL_SetWindowFullscreen(window_, newFullscreen ? SDL_WINDOW_FULLSCREEN : 0);
  1926. SDL_SetWindowBordered(window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  1927. SDL_ShowWindow(window_);
  1928. }
  1929. else
  1930. {
  1931. // If external window, must ask its dimensions instead of trying to set them
  1932. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1933. newFullscreen = false;
  1934. }
  1935. }
  1936. bool Graphics::CreateInterface()
  1937. {
  1938. impl_->interface_ = Direct3DCreate9(D3D_SDK_VERSION);
  1939. if (!impl_->interface_)
  1940. {
  1941. ATOMIC_LOGERROR("Could not create Direct3D9 interface");
  1942. return false;
  1943. }
  1944. HRESULT hr = impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_);
  1945. if (FAILED(hr))
  1946. {
  1947. ATOMIC_LOGD3DERROR("Could not get Direct3D capabilities", hr);
  1948. return false;
  1949. }
  1950. hr = impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_);
  1951. if (FAILED(hr))
  1952. {
  1953. ATOMIC_LOGD3DERROR("Could not get Direct3D adapter identifier", hr);
  1954. return false;
  1955. }
  1956. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(3, 0))
  1957. {
  1958. ATOMIC_LOGERROR("Shader model 3.0 display adapter is required");
  1959. return false;
  1960. }
  1961. return true;
  1962. }
  1963. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1964. {
  1965. #ifdef ATOMIC_LUAJIT
  1966. DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
  1967. #else
  1968. DWORD behaviorFlags = 0;
  1969. #endif
  1970. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1971. {
  1972. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1973. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1974. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1975. }
  1976. else
  1977. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1978. HRESULT hr = impl_->interface_->CreateDevice(
  1979. adapter,
  1980. (D3DDEVTYPE)deviceType,
  1981. GetWindowHandle(window_),
  1982. behaviorFlags,
  1983. &impl_->presentParams_,
  1984. &impl_->device_);
  1985. if (FAILED(hr))
  1986. {
  1987. ATOMIC_LOGD3DERROR("Could not create Direct3D9 device", hr);
  1988. return false;
  1989. }
  1990. impl_->adapter_ = adapter;
  1991. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1992. OnDeviceReset();
  1993. ATOMIC_LOGINFO("Created Direct3D9 device");
  1994. return true;
  1995. }
  1996. void Graphics::CheckFeatureSupport()
  1997. {
  1998. anisotropySupport_ = true;
  1999. dxtTextureSupport_ = true;
  2000. // Reset features first
  2001. lightPrepassSupport_ = false;
  2002. deferredSupport_ = false;
  2003. hardwareShadowSupport_ = false;
  2004. instancingSupport_ = false;
  2005. readableDepthFormat = 0;
  2006. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  2007. shadowMapFormat_ = D3DFMT_D16;
  2008. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2009. {
  2010. hardwareShadowSupport_ = true;
  2011. // Check for hires depth support
  2012. hiresShadowMapFormat_ = D3DFMT_D24X8;
  2013. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2014. hiresShadowMapFormat_ = 0;
  2015. }
  2016. else
  2017. {
  2018. // ATI DF16 format needs manual depth compare in the shader
  2019. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  2020. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2021. {
  2022. // Check for hires depth support
  2023. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  2024. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2025. hiresShadowMapFormat_ = 0;
  2026. }
  2027. else
  2028. {
  2029. // No shadow map support
  2030. shadowMapFormat_ = 0;
  2031. hiresShadowMapFormat_ = 0;
  2032. }
  2033. }
  2034. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  2035. if (shadowMapFormat_ == D3DFMT_D16)
  2036. {
  2037. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  2038. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  2039. hardwareShadowSupport_ = false;
  2040. }
  2041. // Check for readable depth (INTZ hack)
  2042. D3DFORMAT intZFormat = (D3DFORMAT)MAKEFOURCC('I', 'N', 'T', 'Z');
  2043. if (impl_->CheckFormatSupport(intZFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2044. readableDepthFormat = intZFormat;
  2045. // Check for dummy color rendertarget format used with hardware shadow maps
  2046. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  2047. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  2048. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2049. dummyColorFormat_ = nullFormat;
  2050. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2051. dummyColorFormat_ = D3DFMT_R16F;
  2052. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2053. dummyColorFormat_ = D3DFMT_R5G6B5;
  2054. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2055. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  2056. // Check for light prepass and deferred rendering support
  2057. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  2058. D3DRTYPE_TEXTURE))
  2059. {
  2060. lightPrepassSupport_ = true;
  2061. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  2062. deferredSupport_ = true;
  2063. }
  2064. // Check for stream offset (needed for instancing)
  2065. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  2066. instancingSupport_ = true;
  2067. // Check for sRGB read & write
  2068. /// \todo Should be checked for each texture format separately
  2069. sRGBSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE);
  2070. sRGBWriteSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBWRITE, D3DRTYPE_TEXTURE);
  2071. }
  2072. void Graphics::ResetDevice()
  2073. {
  2074. OnDeviceLost();
  2075. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  2076. {
  2077. impl_->deviceLost_ = false;
  2078. OnDeviceReset();
  2079. }
  2080. }
  2081. void Graphics::OnDeviceLost()
  2082. {
  2083. ATOMIC_LOGINFO("Device lost");
  2084. if (impl_->defaultColorSurface_)
  2085. {
  2086. impl_->defaultColorSurface_->Release();
  2087. impl_->defaultColorSurface_ = 0;
  2088. }
  2089. if (impl_->defaultDepthStencilSurface_)
  2090. {
  2091. impl_->defaultDepthStencilSurface_->Release();
  2092. impl_->defaultDepthStencilSurface_ = 0;
  2093. }
  2094. if (impl_->frameQuery_)
  2095. {
  2096. impl_->frameQuery_->Release();
  2097. impl_->frameQuery_ = 0;
  2098. }
  2099. {
  2100. MutexLock lock(gpuObjectMutex_);
  2101. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2102. (*i)->OnDeviceLost();
  2103. }
  2104. SendEvent(E_DEVICELOST);
  2105. }
  2106. void Graphics::OnDeviceReset()
  2107. {
  2108. {
  2109. MutexLock lock(gpuObjectMutex_);
  2110. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2111. (*i)->OnDeviceReset();
  2112. }
  2113. // Get default surfaces
  2114. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  2115. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  2116. // Create frame query for flushing the GPU command buffer
  2117. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  2118. ResetCachedState();
  2119. SendEvent(E_DEVICERESET);
  2120. }
  2121. void Graphics::ResetCachedState()
  2122. {
  2123. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2124. {
  2125. vertexBuffers_[i] = 0;
  2126. impl_->streamOffsets_[i] = 0;
  2127. }
  2128. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2129. {
  2130. textures_[i] = 0;
  2131. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  2132. impl_->mipFilters_[i] = D3DTEXF_NONE;
  2133. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  2134. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  2135. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  2136. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2137. impl_->sRGBModes_[i] = false;
  2138. }
  2139. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2140. {
  2141. renderTargets_[i] = 0;
  2142. impl_->colorSurfaces_[i] = 0;
  2143. }
  2144. depthStencil_ = 0;
  2145. impl_->depthStencilSurface_ = 0;
  2146. viewport_ = IntRect(0, 0, width_, height_);
  2147. impl_->sRGBWrite_ = false;
  2148. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2149. impl_->streamFrequencies_[i] = 1;
  2150. indexBuffer_ = 0;
  2151. vertexShader_ = 0;
  2152. pixelShader_ = 0;
  2153. blendMode_ = BLEND_REPLACE;
  2154. textureAnisotropy_ = 1;
  2155. colorWrite_ = true;
  2156. cullMode_ = CULL_CCW;
  2157. constantDepthBias_ = 0.0f;
  2158. slopeScaledDepthBias_ = 0.0f;
  2159. depthTestMode_ = CMP_LESSEQUAL;
  2160. depthWrite_ = true;
  2161. fillMode_ = FILL_SOLID;
  2162. scissorTest_ = false;
  2163. scissorRect_ = IntRect::ZERO;
  2164. stencilTest_ = false;
  2165. stencilTestMode_ = CMP_ALWAYS;
  2166. stencilPass_ = OP_KEEP;
  2167. stencilFail_ = OP_KEEP;
  2168. stencilZFail_ = OP_KEEP;
  2169. stencilRef_ = 0;
  2170. stencilCompareMask_ = M_MAX_UNSIGNED;
  2171. stencilWriteMask_ = M_MAX_UNSIGNED;
  2172. useClipPlane_ = false;
  2173. impl_->blendEnable_ = FALSE;
  2174. impl_->srcBlend_ = D3DBLEND_ONE;
  2175. impl_->destBlend_ = D3DBLEND_ZERO;
  2176. impl_->blendOp_ = D3DBLENDOP_ADD;
  2177. impl_->vertexDeclaration_ = 0;
  2178. impl_->queryIssued_ = false;
  2179. }
  2180. void Graphics::SetTextureUnitMappings()
  2181. {
  2182. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2183. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2184. textureUnits_["NormalMap"] = TU_NORMAL;
  2185. textureUnits_["SpecMap"] = TU_SPECULAR;
  2186. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2187. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2188. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2189. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2190. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2191. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2192. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2193. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2194. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2195. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2196. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2197. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2198. }
  2199. // ATOMIC BEGIN
  2200. // To satisfy script binding linking
  2201. void Graphics::SetTextureForUpdate(Texture* texture)
  2202. {
  2203. }
  2204. void Graphics::SetTextureParametersDirty()
  2205. {
  2206. }
  2207. /// Return shader program. This is an API-specific class and should not be used by applications.
  2208. ShaderProgram* Graphics::GetShaderProgram() const
  2209. {
  2210. return 0;
  2211. }
  2212. /// Restore GPU objects and reinitialize state. Requires an open window. Used only on OpenGL.
  2213. void Graphics::Restore()
  2214. {
  2215. }
  2216. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  2217. {
  2218. }
  2219. ConstantBuffer* Graphics::GetOrCreateConstantBuffer(ShaderType type, unsigned index, unsigned size)
  2220. {
  2221. return 0;
  2222. }
  2223. void Graphics::MarkFBODirty()
  2224. {
  2225. }
  2226. void Graphics::SetVBO(unsigned object)
  2227. {
  2228. }
  2229. void Graphics::SetUBO(unsigned object)
  2230. {
  2231. }
  2232. // ATOMIC END
  2233. }