D3D9Graphics.cpp 83 KB

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