D3D9Graphics.cpp 81 KB

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