D3D9Graphics.cpp 78 KB

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