D3D9Graphics.cpp 81 KB

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