D3D9Graphics.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771
  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 ENABLE_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. // Check for lost device before rendering
  595. HRESULT hr = impl_->device_->TestCooperativeLevel();
  596. if (hr != D3D_OK)
  597. {
  598. PROFILE(DeviceLost);
  599. deviceLost_ = true;
  600. // The device can not be reset yet, sleep and try again eventually
  601. if (hr == D3DERR_DEVICELOST)
  602. {
  603. Time::Sleep(20);
  604. return false;
  605. }
  606. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  607. if (hr == D3DERR_DEVICENOTRESET)
  608. {
  609. ResetDevice();
  610. return false;
  611. }
  612. }
  613. // If a query was issued on the previous frame, wait for it to finish before beginning the next
  614. if (impl_->frameQuery_ && queryIssued_)
  615. {
  616. PROFILE(FlushGPU);
  617. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  618. {
  619. }
  620. queryIssued_ = false;
  621. }
  622. impl_->device_->BeginScene();
  623. // Set default rendertarget and depth buffer
  624. ResetRenderTargets();
  625. // Cleanup textures from previous frame
  626. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  627. SetTexture(i, 0);
  628. // Cleanup stream frequencies from previous frame
  629. ResetStreamFrequencies();
  630. numPrimitives_ = 0;
  631. numBatches_ = 0;
  632. SendEvent(E_BEGINRENDERING);
  633. return true;
  634. }
  635. void Graphics::EndFrame()
  636. {
  637. if (!IsInitialized())
  638. return;
  639. PROFILE(Present);
  640. SendEvent(E_ENDRENDERING);
  641. impl_->device_->EndScene();
  642. impl_->device_->Present(0, 0, 0, 0);
  643. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to pre-render
  644. if (impl_->frameQuery_ && flushGPU_)
  645. {
  646. impl_->frameQuery_->Issue(D3DISSUE_END);
  647. queryIssued_ = true;
  648. }
  649. // Clean up too large scratch buffers
  650. CleanupScratchBuffers();
  651. }
  652. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  653. {
  654. DWORD d3dFlags = 0;
  655. if (flags & CLEAR_COLOR)
  656. d3dFlags |= D3DCLEAR_TARGET;
  657. if (flags & CLEAR_DEPTH)
  658. d3dFlags |= D3DCLEAR_ZBUFFER;
  659. if (flags & CLEAR_STENCIL)
  660. d3dFlags |= D3DCLEAR_STENCIL;
  661. impl_->device_->Clear(0, 0, d3dFlags, GetD3DColor(color), depth, stencil);
  662. }
  663. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  664. {
  665. if (!destination || !destination->GetRenderSurface() || destination->GetWidth() != width_ ||
  666. destination->GetHeight() != height_)
  667. return false;
  668. PROFILE(ResolveToTexture);
  669. IntRect vpCopy = viewport;
  670. if (vpCopy.right_ <= vpCopy.left_)
  671. vpCopy.right_ = vpCopy.left_ + 1;
  672. if (vpCopy.bottom_ <= vpCopy.top_)
  673. vpCopy.bottom_ = vpCopy.top_ + 1;
  674. RECT rect;
  675. rect.left = Clamp(vpCopy.left_, 0, width_);
  676. rect.top = Clamp(vpCopy.top_, 0, height_);
  677. rect.right = Clamp(vpCopy.right_, 0, width_);
  678. rect.bottom = Clamp(vpCopy.bottom_, 0, height_);
  679. return SUCCEEDED(impl_->device_->StretchRect(impl_->defaultColorSurface_, &rect,
  680. (IDirect3DSurface9*)destination->GetRenderSurface()->GetSurface(), &rect, D3DTEXF_NONE));
  681. }
  682. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  683. {
  684. if (!vertexCount)
  685. return;
  686. ResetStreamFrequencies();
  687. unsigned primitiveCount = 0;
  688. switch (type)
  689. {
  690. case TRIANGLE_LIST:
  691. primitiveCount = vertexCount / 3;
  692. impl_->device_->DrawPrimitive(D3DPT_TRIANGLELIST, vertexStart, primitiveCount);
  693. break;
  694. case LINE_LIST:
  695. primitiveCount = vertexCount / 2;
  696. impl_->device_->DrawPrimitive(D3DPT_LINELIST, vertexStart, primitiveCount);
  697. break;
  698. }
  699. numPrimitives_ += primitiveCount;
  700. ++numBatches_;
  701. }
  702. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  703. {
  704. if (!indexCount)
  705. return;
  706. ResetStreamFrequencies();
  707. unsigned primitiveCount = 0;
  708. switch (type)
  709. {
  710. case TRIANGLE_LIST:
  711. primitiveCount = indexCount / 3;
  712. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  713. break;
  714. case LINE_LIST:
  715. primitiveCount = indexCount / 2;
  716. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  717. break;
  718. }
  719. numPrimitives_ += primitiveCount;
  720. ++numBatches_;
  721. }
  722. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  723. unsigned instanceCount)
  724. {
  725. if (!indexCount || !instanceCount)
  726. return;
  727. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  728. {
  729. VertexBuffer* buffer = vertexBuffers_[i];
  730. if (buffer)
  731. {
  732. if (buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  733. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1);
  734. else
  735. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  736. }
  737. }
  738. unsigned primitiveCount = 0;
  739. switch (type)
  740. {
  741. case TRIANGLE_LIST:
  742. primitiveCount = indexCount / 3;
  743. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  744. break;
  745. case LINE_LIST:
  746. primitiveCount = indexCount / 2;
  747. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  748. break;
  749. }
  750. numPrimitives_ += instanceCount * primitiveCount;
  751. ++numBatches_;
  752. }
  753. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  754. {
  755. // Note: this is not multi-instance safe
  756. static PODVector<VertexBuffer*> vertexBuffers(1);
  757. static PODVector<unsigned> elementMasks(1);
  758. vertexBuffers[0] = buffer;
  759. elementMasks[0] = MASK_DEFAULT;
  760. SetVertexBuffers(vertexBuffers, elementMasks);
  761. }
  762. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, const PODVector<unsigned>&
  763. elementMasks, unsigned instanceOffset)
  764. {
  765. if (buffers.Size() > MAX_VERTEX_STREAMS)
  766. {
  767. LOGERROR("Too many vertex buffers");
  768. return false;
  769. }
  770. if (buffers.Size() != elementMasks.Size())
  771. {
  772. LOGERROR("Amount of element masks and vertex buffers does not match");
  773. return false;
  774. }
  775. // Build vertex declaration hash code out of the buffers & masks
  776. unsigned long long hash = 0;
  777. for (unsigned i = 0; i < buffers.Size(); ++i)
  778. {
  779. if (!buffers[i])
  780. continue;
  781. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  782. }
  783. if (hash)
  784. {
  785. // If no previous vertex declaration for that hash, create new
  786. if (!vertexDeclarations_.Contains(hash))
  787. {
  788. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  789. if (!newDeclaration->GetDeclaration())
  790. {
  791. LOGERROR("Failed to create vertex declaration");
  792. return false;
  793. }
  794. vertexDeclarations_[hash] = newDeclaration;
  795. }
  796. VertexDeclaration* declaration = vertexDeclarations_[hash];
  797. if (declaration != vertexDeclaration_)
  798. {
  799. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  800. vertexDeclaration_ = declaration;
  801. }
  802. }
  803. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  804. {
  805. VertexBuffer* buffer = 0;
  806. unsigned offset = 0;
  807. if (i < buffers.Size())
  808. {
  809. buffer = buffers[i];
  810. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  811. offset = instanceOffset * buffer->GetVertexSize();
  812. }
  813. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  814. {
  815. if (buffer)
  816. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  817. else
  818. impl_->device_->SetStreamSource(i, 0, 0, 0);
  819. vertexBuffers_[i] = buffer;
  820. streamOffsets_[i] = offset;
  821. }
  822. }
  823. return true;
  824. }
  825. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  826. elementMasks, unsigned instanceOffset)
  827. {
  828. if (buffers.Size() > MAX_VERTEX_STREAMS)
  829. {
  830. LOGERROR("Too many vertex buffers");
  831. return false;
  832. }
  833. if (buffers.Size() != elementMasks.Size())
  834. {
  835. LOGERROR("Amount of element masks and vertex buffers does not match");
  836. return false;
  837. }
  838. unsigned long long hash = 0;
  839. for (unsigned i = 0; i < buffers.Size(); ++i)
  840. {
  841. if (!buffers[i])
  842. continue;
  843. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  844. }
  845. if (hash)
  846. {
  847. if (!vertexDeclarations_.Contains(hash))
  848. {
  849. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  850. if (!newDeclaration->GetDeclaration())
  851. {
  852. LOGERROR("Failed to create vertex declaration");
  853. return false;
  854. }
  855. vertexDeclarations_[hash] = newDeclaration;
  856. }
  857. VertexDeclaration* declaration = vertexDeclarations_[hash];
  858. if (declaration != vertexDeclaration_)
  859. {
  860. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  861. vertexDeclaration_ = declaration;
  862. }
  863. }
  864. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  865. {
  866. VertexBuffer* buffer = 0;
  867. unsigned offset = 0;
  868. if (i < buffers.Size())
  869. {
  870. buffer = buffers[i];
  871. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  872. offset = instanceOffset * buffer->GetVertexSize();
  873. }
  874. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  875. {
  876. if (buffer)
  877. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  878. else
  879. impl_->device_->SetStreamSource(i, 0, 0, 0);
  880. vertexBuffers_[i] = buffer;
  881. streamOffsets_[i] = offset;
  882. }
  883. }
  884. return true;
  885. }
  886. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  887. {
  888. if (buffer != indexBuffer_)
  889. {
  890. if (buffer)
  891. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  892. else
  893. impl_->device_->SetIndices(0);
  894. indexBuffer_ = buffer;
  895. }
  896. }
  897. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  898. {
  899. if (vs == vertexShader_ && ps == pixelShader_)
  900. return;
  901. ClearParameterSources();
  902. if (vs != vertexShader_)
  903. {
  904. // Clear all previous vertex shader register mappings
  905. for (HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  906. {
  907. if (i->second_.type_ == VS)
  908. i->second_.register_ = M_MAX_UNSIGNED;
  909. }
  910. // Create the shader now if not yet created. If already attempted, do not retry
  911. if (vs && !vs->GetGPUObject())
  912. {
  913. if (vs->GetCompilerOutput().Empty())
  914. {
  915. PROFILE(CompileVertexShader);
  916. bool success = vs->Create();
  917. if (!success)
  918. {
  919. LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  920. vs = 0;
  921. }
  922. }
  923. else
  924. vs = 0;
  925. }
  926. if (vs && vs->GetShaderType() == VS)
  927. {
  928. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  929. // Update the parameter-to-register mappings
  930. const HashMap<StringHash, ShaderParameter>& parameters = vs->GetParameters();
  931. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  932. shaderParameters_[i->first_].register_ = i->second_.register_;
  933. }
  934. else
  935. {
  936. impl_->device_->SetVertexShader(0);
  937. vs = 0;
  938. }
  939. vertexShader_ = vs;
  940. }
  941. if (ps != pixelShader_)
  942. {
  943. for (HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  944. {
  945. if (i->second_.type_ == PS)
  946. i->second_.register_ = M_MAX_UNSIGNED;
  947. }
  948. if (ps && !ps->GetGPUObject())
  949. {
  950. if (ps->GetCompilerOutput().Empty())
  951. {
  952. PROFILE(CompilePixelShader);
  953. bool success = ps->Create();
  954. if (!success)
  955. {
  956. LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  957. ps = 0;
  958. }
  959. }
  960. else
  961. ps = 0;
  962. }
  963. if (ps && ps->GetShaderType() == PS)
  964. {
  965. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  966. const HashMap<StringHash, ShaderParameter>& parameters = ps->GetParameters();
  967. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  968. shaderParameters_[i->first_].register_ = i->second_.register_;
  969. }
  970. else
  971. {
  972. impl_->device_->SetPixelShader(0);
  973. ps = 0;
  974. }
  975. pixelShader_ = ps;
  976. }
  977. // Store shader combination if shader dumping in progress
  978. if (shaderPrecache_)
  979. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  980. }
  981. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  982. {
  983. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  984. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  985. return;
  986. if (i->second_.type_ == VS)
  987. impl_->device_->SetVertexShaderConstantF(i->second_.register_, data, count / 4);
  988. else
  989. impl_->device_->SetPixelShaderConstantF(i->second_.register_, data, count / 4);
  990. }
  991. void Graphics::SetShaderParameter(StringHash param, float value)
  992. {
  993. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  994. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  995. return;
  996. float data[4];
  997. data[0] = value;
  998. data[1] = 0.0f;
  999. data[2] = 0.0f;
  1000. data[3] = 0.0f;
  1001. if (i->second_.type_ == VS)
  1002. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  1003. else
  1004. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  1005. }
  1006. void Graphics::SetShaderParameter(StringHash param, bool value)
  1007. {
  1008. /// \todo Bool constants possibly have no effect on Direct3D9
  1009. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1010. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1011. return;
  1012. BOOL data = value;
  1013. if (i->second_.type_ == VS)
  1014. impl_->device_->SetVertexShaderConstantB(i->second_.register_, &data, 1);
  1015. else
  1016. impl_->device_->SetPixelShaderConstantB(i->second_.register_, &data, 1);
  1017. }
  1018. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  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_, color.Data(), 1);
  1025. else
  1026. impl_->device_->SetPixelShaderConstantF(i->second_.register_, color.Data(), 1);
  1027. }
  1028. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  1029. {
  1030. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1031. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1032. return;
  1033. float data[4];
  1034. data[0] = vector.x_;
  1035. data[1] = vector.y_;
  1036. data[2] = 0.0f;
  1037. data[3] = 0.0f;
  1038. if (i->second_.type_ == VS)
  1039. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  1040. else
  1041. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  1042. }
  1043. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1044. {
  1045. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1046. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1047. return;
  1048. float data[12];
  1049. data[0] = matrix.m00_;
  1050. data[1] = matrix.m01_;
  1051. data[2] = matrix.m02_;
  1052. data[3] = 0.0f;
  1053. data[4] = matrix.m10_;
  1054. data[5] = matrix.m11_;
  1055. data[6] = matrix.m12_;
  1056. data[7] = 0.0f;
  1057. data[8] = matrix.m20_;
  1058. data[9] = matrix.m21_;
  1059. data[10] = matrix.m22_;
  1060. data[11] = 0.0f;
  1061. if (i->second_.type_ == VS)
  1062. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 3);
  1063. else
  1064. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 3);
  1065. }
  1066. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1067. {
  1068. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1069. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1070. return;
  1071. float data[4];
  1072. data[0] = vector.x_;
  1073. data[1] = vector.y_;
  1074. data[2] = vector.z_;
  1075. data[3] = 0.0f;
  1076. if (i->second_.type_ == VS)
  1077. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  1078. else
  1079. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  1080. }
  1081. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1082. {
  1083. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1084. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1085. return;
  1086. if (i->second_.type_ == VS)
  1087. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1088. else
  1089. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1090. }
  1091. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1092. {
  1093. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1094. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1095. return;
  1096. if (i->second_.type_ == VS)
  1097. impl_->device_->SetVertexShaderConstantF(i->second_.register_, vector.Data(), 1);
  1098. else
  1099. impl_->device_->SetPixelShaderConstantF(i->second_.register_, vector.Data(), 1);
  1100. }
  1101. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1102. {
  1103. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1104. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1105. return;
  1106. if (i->second_.type_ == VS)
  1107. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1108. else
  1109. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1110. }
  1111. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1112. {
  1113. switch (value.GetType())
  1114. {
  1115. case VAR_BOOL:
  1116. SetShaderParameter(param, value.GetBool());
  1117. break;
  1118. case VAR_FLOAT:
  1119. SetShaderParameter(param, value.GetFloat());
  1120. break;
  1121. case VAR_VECTOR2:
  1122. SetShaderParameter(param, value.GetVector2());
  1123. break;
  1124. case VAR_VECTOR3:
  1125. SetShaderParameter(param, value.GetVector3());
  1126. break;
  1127. case VAR_VECTOR4:
  1128. SetShaderParameter(param, value.GetVector4());
  1129. break;
  1130. case VAR_COLOR:
  1131. SetShaderParameter(param, value.GetColor());
  1132. break;
  1133. case VAR_MATRIX3:
  1134. SetShaderParameter(param, value.GetMatrix3());
  1135. break;
  1136. case VAR_MATRIX3X4:
  1137. SetShaderParameter(param, value.GetMatrix3x4());
  1138. break;
  1139. case VAR_MATRIX4:
  1140. SetShaderParameter(param, value.GetMatrix4());
  1141. break;
  1142. default:
  1143. // Unsupported parameter type, do nothing
  1144. break;
  1145. }
  1146. }
  1147. void Graphics::RegisterShaderParameter(StringHash param, const ShaderParameter& definition)
  1148. {
  1149. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1150. if (i == shaderParameters_.End())
  1151. {
  1152. // Define new parameter
  1153. i = shaderParameters_.Insert(MakePair(param, definition));
  1154. i->second_.register_ = M_MAX_UNSIGNED;
  1155. // Rehash the parameters to ensure minimum load factor and fast queries
  1156. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  1157. }
  1158. else
  1159. {
  1160. // Existing parameter: check that there is no conflict
  1161. if (i->second_.type_ != definition.type_)
  1162. LOGWARNING("Shader type mismatch on shader parameter " + String(param));
  1163. // The same parameter is possibly defined with different sizes in different shaders. Use the highest size
  1164. if (i->second_.regCount_ < definition.regCount_)
  1165. i->second_.regCount_ = definition.regCount_;
  1166. }
  1167. }
  1168. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1169. {
  1170. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1171. {
  1172. shaderParameterSources_[group] = source;
  1173. return true;
  1174. }
  1175. else
  1176. return false;
  1177. }
  1178. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  1179. {
  1180. if (type == VS)
  1181. return vertexShader_ && vertexShader_->HasParameter(param);
  1182. else
  1183. return pixelShader_ && pixelShader_->HasParameter(param);
  1184. }
  1185. bool Graphics::HasTextureUnit(TextureUnit unit)
  1186. {
  1187. return pixelShader_ && pixelShader_->HasTextureUnit(unit);
  1188. }
  1189. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1190. {
  1191. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1192. }
  1193. void Graphics::ClearParameterSources()
  1194. {
  1195. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1196. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1197. }
  1198. void Graphics::ClearTransformSources()
  1199. {
  1200. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1201. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  1202. }
  1203. void Graphics::SetTexture(unsigned index, Texture* texture)
  1204. {
  1205. if (index >= MAX_TEXTURE_UNITS)
  1206. return;
  1207. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1208. if (texture)
  1209. {
  1210. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1211. texture = texture->GetBackupTexture();
  1212. }
  1213. if (texture != textures_[index])
  1214. {
  1215. if (texture)
  1216. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1217. else
  1218. impl_->device_->SetTexture(index, 0);
  1219. textures_[index] = texture;
  1220. }
  1221. if (texture)
  1222. {
  1223. TextureFilterMode filterMode = texture->GetFilterMode();
  1224. if (filterMode == FILTER_DEFAULT)
  1225. filterMode = defaultTextureFilterMode_;
  1226. D3DTEXTUREFILTERTYPE minMag, mip;
  1227. minMag = d3dMinMagFilter[filterMode];
  1228. if (minMag != impl_->minMagFilters_[index])
  1229. {
  1230. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1231. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1232. impl_->minMagFilters_[index] = minMag;
  1233. }
  1234. mip = d3dMipFilter[filterMode];
  1235. if (mip != impl_->mipFilters_[index])
  1236. {
  1237. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1238. impl_->mipFilters_[index] = mip;
  1239. }
  1240. D3DTEXTUREADDRESS u, v;
  1241. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1242. if (u != impl_->uAddressModes_[index])
  1243. {
  1244. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1245. impl_->uAddressModes_[index] = u;
  1246. }
  1247. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1248. if (v != impl_->vAddressModes_[index])
  1249. {
  1250. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1251. impl_->vAddressModes_[index] = v;
  1252. }
  1253. if (texture->GetType() == TextureCube::GetTypeStatic())
  1254. {
  1255. D3DTEXTUREADDRESS w = d3dAddressMode[texture->GetAddressMode(COORD_W)];
  1256. if (w != impl_->wAddressModes_[index])
  1257. {
  1258. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSW, w);
  1259. impl_->wAddressModes_[index] = w;
  1260. }
  1261. }
  1262. if (u == D3DTADDRESS_BORDER || v == D3DTADDRESS_BORDER)
  1263. {
  1264. const Color& borderColor = texture->GetBorderColor();
  1265. if (borderColor != impl_->borderColors_[index])
  1266. {
  1267. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, GetD3DColor(borderColor));
  1268. impl_->borderColors_[index] = borderColor;
  1269. }
  1270. }
  1271. if (sRGBSupport_)
  1272. {
  1273. bool sRGB = texture->GetSRGB();
  1274. if (sRGB != impl_->sRGBModes_[index])
  1275. {
  1276. impl_->device_->SetSamplerState(index, D3DSAMP_SRGBTEXTURE, sRGB ? TRUE : FALSE);
  1277. impl_->sRGBModes_[index] = sRGB;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1283. {
  1284. defaultTextureFilterMode_ = mode;
  1285. }
  1286. void Graphics::ResetRenderTargets()
  1287. {
  1288. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1289. SetRenderTarget(i, (RenderSurface*)0);
  1290. SetDepthStencil((RenderSurface*)0);
  1291. SetViewport(IntRect(0, 0, width_, height_));
  1292. }
  1293. void Graphics::ResetRenderTarget(unsigned index)
  1294. {
  1295. SetRenderTarget(index, (RenderSurface*)0);
  1296. }
  1297. void Graphics::ResetDepthStencil()
  1298. {
  1299. SetDepthStencil((RenderSurface*)0);
  1300. }
  1301. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1302. {
  1303. if (index >= MAX_RENDERTARGETS)
  1304. return;
  1305. IDirect3DSurface9* newColorSurface = 0;
  1306. if (renderTarget)
  1307. {
  1308. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1309. return;
  1310. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1311. }
  1312. else
  1313. {
  1314. if (!index)
  1315. newColorSurface = impl_->defaultColorSurface_;
  1316. }
  1317. renderTargets_[index] = renderTarget;
  1318. if (newColorSurface != impl_->colorSurfaces_[index])
  1319. {
  1320. impl_->device_->SetRenderTarget(index, newColorSurface);
  1321. impl_->colorSurfaces_[index] = newColorSurface;
  1322. // Setting the first rendertarget causes viewport to be reset
  1323. if (!index)
  1324. {
  1325. IntVector2 rtSize = GetRenderTargetDimensions();
  1326. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1327. }
  1328. }
  1329. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1330. if (renderTarget)
  1331. {
  1332. Texture* parentTexture = renderTarget->GetParentTexture();
  1333. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1334. {
  1335. if (textures_[i] == parentTexture)
  1336. SetTexture(i, textures_[i]->GetBackupTexture());
  1337. }
  1338. }
  1339. // First rendertarget controls sRGB write mode
  1340. if (!index && sRGBWriteSupport_)
  1341. {
  1342. bool sRGBWrite = renderTarget ? renderTarget->GetParentTexture()->GetSRGB() : sRGB_;
  1343. if (sRGBWrite != impl_->sRGBWrite_)
  1344. {
  1345. impl_->device_->SetRenderState(D3DRS_SRGBWRITEENABLE, sRGBWrite ? TRUE : FALSE);
  1346. impl_->sRGBWrite_ = sRGBWrite;
  1347. }
  1348. }
  1349. }
  1350. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1351. {
  1352. RenderSurface* renderTarget = 0;
  1353. if (texture)
  1354. renderTarget = texture->GetRenderSurface();
  1355. SetRenderTarget(index, renderTarget);
  1356. }
  1357. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1358. {
  1359. IDirect3DSurface9* newDepthStencilSurface = 0;
  1360. if (depthStencil && depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL)
  1361. {
  1362. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1363. depthStencil_ = depthStencil;
  1364. }
  1365. if (!newDepthStencilSurface)
  1366. {
  1367. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1368. depthStencil_ = 0;
  1369. }
  1370. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1371. {
  1372. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1373. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1374. }
  1375. }
  1376. void Graphics::SetDepthStencil(Texture2D* texture)
  1377. {
  1378. RenderSurface* depthStencil = 0;
  1379. if (texture)
  1380. depthStencil = texture->GetRenderSurface();
  1381. SetDepthStencil(depthStencil);
  1382. }
  1383. void Graphics::SetViewport(const IntRect& rect)
  1384. {
  1385. IntVector2 size = GetRenderTargetDimensions();
  1386. IntRect rectCopy = rect;
  1387. if (rectCopy.right_ <= rectCopy.left_)
  1388. rectCopy.right_ = rectCopy.left_ + 1;
  1389. if (rectCopy.bottom_ <= rectCopy.top_)
  1390. rectCopy.bottom_ = rectCopy.top_ + 1;
  1391. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1392. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1393. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1394. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1395. D3DVIEWPORT9 vp;
  1396. vp.MinZ = 0.0f;
  1397. vp.MaxZ = 1.0f;
  1398. vp.X = rectCopy.left_;
  1399. vp.Y = rectCopy.top_;
  1400. vp.Width = rectCopy.Width();
  1401. vp.Height = rectCopy.Height();
  1402. impl_->device_->SetViewport(&vp);
  1403. viewport_ = rectCopy;
  1404. // Disable scissor test, needs to be re-enabled by the user
  1405. SetScissorTest(false);
  1406. }
  1407. void Graphics::SetTextureAnisotropy(unsigned level)
  1408. {
  1409. if (level < 1)
  1410. level = 1;
  1411. if (level != textureAnisotropy_)
  1412. {
  1413. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1414. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1415. textureAnisotropy_ = level;
  1416. }
  1417. }
  1418. void Graphics::SetBlendMode(BlendMode mode)
  1419. {
  1420. if (mode != blendMode_)
  1421. {
  1422. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1423. {
  1424. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1425. impl_->blendEnable_ = d3dBlendEnable[mode];
  1426. }
  1427. if (impl_->blendEnable_)
  1428. {
  1429. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1430. {
  1431. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1432. impl_->srcBlend_ = d3dSrcBlend[mode];
  1433. }
  1434. if (d3dDestBlend[mode] != impl_->destBlend_)
  1435. {
  1436. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1437. impl_->destBlend_ = d3dDestBlend[mode];
  1438. }
  1439. if (d3dBlendOp[mode] != impl_->blendOp_)
  1440. {
  1441. impl_->device_->SetRenderState(D3DRS_BLENDOP, d3dBlendOp[mode]);
  1442. impl_->blendOp_ = d3dBlendOp[mode];
  1443. }
  1444. }
  1445. blendMode_ = mode;
  1446. }
  1447. }
  1448. void Graphics::SetColorWrite(bool enable)
  1449. {
  1450. if (enable != colorWrite_)
  1451. {
  1452. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1453. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1454. colorWrite_ = enable;
  1455. }
  1456. }
  1457. void Graphics::SetCullMode(CullMode mode)
  1458. {
  1459. if (mode != cullMode_)
  1460. {
  1461. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1462. cullMode_ = mode;
  1463. }
  1464. }
  1465. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1466. {
  1467. if (constantBias != constantDepthBias_)
  1468. {
  1469. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1470. constantDepthBias_ = constantBias;
  1471. }
  1472. if (slopeScaledBias != slopeScaledDepthBias_)
  1473. {
  1474. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1475. slopeScaledDepthBias_ = slopeScaledBias;
  1476. }
  1477. }
  1478. void Graphics::SetDepthTest(CompareMode mode)
  1479. {
  1480. if (mode != depthTestMode_)
  1481. {
  1482. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1483. depthTestMode_ = mode;
  1484. }
  1485. }
  1486. void Graphics::SetDepthWrite(bool enable)
  1487. {
  1488. if (enable != depthWrite_)
  1489. {
  1490. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1491. depthWrite_ = enable;
  1492. }
  1493. }
  1494. void Graphics::SetFillMode(FillMode mode)
  1495. {
  1496. if (mode != fillMode_)
  1497. {
  1498. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1499. fillMode_ = mode;
  1500. }
  1501. }
  1502. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1503. {
  1504. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1505. // Disable scissor in that case to reduce state changes
  1506. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1507. enable = false;
  1508. if (enable)
  1509. {
  1510. IntVector2 rtSize(GetRenderTargetDimensions());
  1511. IntVector2 viewSize(viewport_.Size());
  1512. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1513. IntRect intRect;
  1514. int expand = borderInclusive ? 1 : 0;
  1515. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1516. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1517. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1518. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1519. if (intRect.right_ == intRect.left_)
  1520. intRect.right_++;
  1521. if (intRect.bottom_ == intRect.top_)
  1522. intRect.bottom_++;
  1523. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1524. enable = false;
  1525. if (enable && scissorRect_ != intRect)
  1526. {
  1527. RECT d3dRect;
  1528. d3dRect.left = intRect.left_;
  1529. d3dRect.top = intRect.top_;
  1530. d3dRect.right = intRect.right_;
  1531. d3dRect.bottom = intRect.bottom_;
  1532. impl_->device_->SetScissorRect(&d3dRect);
  1533. scissorRect_ = intRect;
  1534. }
  1535. }
  1536. else
  1537. scissorRect_ = IntRect::ZERO;
  1538. if (enable != scissorTest_)
  1539. {
  1540. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1541. scissorTest_ = enable;
  1542. }
  1543. }
  1544. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1545. {
  1546. IntVector2 rtSize(GetRenderTargetDimensions());
  1547. IntVector2 viewSize(viewport_.Size());
  1548. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1549. if (enable)
  1550. {
  1551. IntRect intRect;
  1552. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1553. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1554. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1555. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1556. if (intRect.right_ == intRect.left_)
  1557. intRect.right_++;
  1558. if (intRect.bottom_ == intRect.top_)
  1559. intRect.bottom_++;
  1560. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1561. enable = false;
  1562. if (enable && scissorRect_ != intRect)
  1563. {
  1564. RECT d3dRect;
  1565. d3dRect.left = intRect.left_;
  1566. d3dRect.top = intRect.top_;
  1567. d3dRect.right = intRect.right_;
  1568. d3dRect.bottom = intRect.bottom_;
  1569. impl_->device_->SetScissorRect(&d3dRect);
  1570. scissorRect_ = intRect;
  1571. }
  1572. }
  1573. else
  1574. scissorRect_ = IntRect::ZERO;
  1575. if (enable != scissorTest_)
  1576. {
  1577. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1578. scissorTest_ = enable;
  1579. }
  1580. }
  1581. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1582. {
  1583. if (enable != stencilTest_)
  1584. {
  1585. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1586. stencilTest_ = enable;
  1587. }
  1588. if (enable)
  1589. {
  1590. if (mode != stencilTestMode_)
  1591. {
  1592. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1593. stencilTestMode_ = mode;
  1594. }
  1595. if (pass != stencilPass_)
  1596. {
  1597. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1598. stencilPass_ = pass;
  1599. }
  1600. if (fail != stencilFail_)
  1601. {
  1602. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1603. stencilFail_ = fail;
  1604. }
  1605. if (zFail != stencilZFail_)
  1606. {
  1607. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1608. stencilZFail_ = zFail;
  1609. }
  1610. if (stencilRef != stencilRef_)
  1611. {
  1612. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1613. stencilRef_ = stencilRef;
  1614. }
  1615. if (compareMask != stencilCompareMask_)
  1616. {
  1617. impl_->device_->SetRenderState(D3DRS_STENCILMASK, compareMask);
  1618. stencilCompareMask_ = compareMask;
  1619. }
  1620. if (writeMask != stencilWriteMask_)
  1621. {
  1622. impl_->device_->SetRenderState(D3DRS_STENCILWRITEMASK, writeMask);
  1623. stencilWriteMask_ = writeMask;
  1624. }
  1625. }
  1626. }
  1627. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1628. {
  1629. if (enable != useClipPlane_)
  1630. {
  1631. impl_->device_->SetRenderState(D3DRS_CLIPPLANEENABLE, enable ? 1 : 0);
  1632. useClipPlane_ = enable;
  1633. }
  1634. if (enable)
  1635. {
  1636. Matrix4 viewProj = projection * view;
  1637. impl_->device_->SetClipPlane(0, clipPlane.Transformed(viewProj).ToVector4().Data());
  1638. }
  1639. }
  1640. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1641. {
  1642. if (index < MAX_VERTEX_STREAMS && streamFrequencies_[index] != frequency)
  1643. {
  1644. impl_->device_->SetStreamSourceFreq(index, frequency);
  1645. streamFrequencies_[index] = frequency;
  1646. }
  1647. }
  1648. void Graphics::ResetStreamFrequencies()
  1649. {
  1650. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1651. {
  1652. if (streamFrequencies_[i] != 1)
  1653. {
  1654. impl_->device_->SetStreamSourceFreq(i, 1);
  1655. streamFrequencies_[i] = 1;
  1656. }
  1657. }
  1658. }
  1659. void Graphics::SetForceSM2(bool enable)
  1660. {
  1661. if (!IsInitialized())
  1662. forceSM2_ = enable;
  1663. else
  1664. LOGERROR("Force Shader Model 2 can not be changed after setting the initial screen mode");
  1665. }
  1666. void Graphics::BeginDumpShaders(const String& fileName)
  1667. {
  1668. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1669. }
  1670. void Graphics::EndDumpShaders()
  1671. {
  1672. shaderPrecache_.Reset();
  1673. }
  1674. void Graphics::PrecacheShaders(Deserializer& source)
  1675. {
  1676. PROFILE(PrecacheShaders);
  1677. ShaderPrecache::LoadShaders(this, source);
  1678. }
  1679. bool Graphics::IsInitialized() const
  1680. {
  1681. return impl_->window_ != 0 && impl_->GetDevice() != 0;
  1682. }
  1683. IntVector2 Graphics::GetWindowPosition() const
  1684. {
  1685. IntVector2 ret(IntVector2::ZERO);
  1686. if (impl_->window_)
  1687. SDL_GetWindowPosition(impl_->window_, &ret.x_, &ret.y_);
  1688. return ret;
  1689. }
  1690. PODVector<IntVector2> Graphics::GetResolutions() const
  1691. {
  1692. PODVector<IntVector2> ret;
  1693. unsigned numModes = SDL_GetNumDisplayModes(0);
  1694. for (unsigned i = 0; i < numModes; ++i)
  1695. {
  1696. SDL_DisplayMode mode;
  1697. SDL_GetDisplayMode(0, i, &mode);
  1698. int width = mode.w;
  1699. int height = mode.h;
  1700. // Store mode if unique
  1701. bool unique = true;
  1702. for (unsigned j = 0; j < ret.Size(); ++j)
  1703. {
  1704. if (ret[j].x_ == width && ret[j].y_ == height)
  1705. {
  1706. unique = false;
  1707. break;
  1708. }
  1709. }
  1710. if (unique)
  1711. ret.Push(IntVector2(width, height));
  1712. }
  1713. return ret;
  1714. }
  1715. PODVector<int> Graphics::GetMultiSampleLevels() const
  1716. {
  1717. PODVector<int> ret;
  1718. // No multisampling always supported
  1719. ret.Push(1);
  1720. if (!impl_->interface_)
  1721. return ret;
  1722. SDL_DisplayMode mode;
  1723. SDL_GetDesktopDisplayMode(0, &mode);
  1724. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  1725. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1726. {
  1727. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  1728. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1729. ret.Push(i);
  1730. }
  1731. return ret;
  1732. }
  1733. IntVector2 Graphics::GetDesktopResolution() const
  1734. {
  1735. SDL_DisplayMode mode;
  1736. SDL_GetDesktopDisplayMode(0, &mode);
  1737. return IntVector2(mode.w, mode.h);
  1738. }
  1739. unsigned Graphics::GetFormat(CompressedFormat format) const
  1740. {
  1741. switch (format)
  1742. {
  1743. case CF_DXT1:
  1744. return D3DFMT_DXT1;
  1745. case CF_DXT3:
  1746. return D3DFMT_DXT3;
  1747. case CF_DXT5:
  1748. return D3DFMT_DXT5;
  1749. }
  1750. return 0;
  1751. }
  1752. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1753. {
  1754. return GetShader(type, name.CString(), defines.CString());
  1755. }
  1756. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1757. {
  1758. if (lastShaderName_ != name || !lastShader_)
  1759. {
  1760. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1761. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1762. // Try to reduce repeated error log prints because of missing shaders
  1763. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1764. return 0;
  1765. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1766. lastShaderName_ = name;
  1767. }
  1768. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1769. }
  1770. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1771. {
  1772. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1773. }
  1774. TextureUnit Graphics::GetTextureUnit(const String& name)
  1775. {
  1776. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1777. if (i != textureUnits_.End())
  1778. return i->second_;
  1779. else
  1780. return MAX_TEXTURE_UNITS;
  1781. }
  1782. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1783. {
  1784. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1785. {
  1786. if (i->second_ == unit)
  1787. return i->first_;
  1788. }
  1789. return String::EMPTY;
  1790. }
  1791. Texture* Graphics::GetTexture(unsigned index) const
  1792. {
  1793. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1794. }
  1795. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1796. {
  1797. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1798. }
  1799. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1800. {
  1801. return index < MAX_VERTEX_STREAMS ? streamFrequencies_[index] : 0;
  1802. }
  1803. IntVector2 Graphics::GetRenderTargetDimensions() const
  1804. {
  1805. int width, height;
  1806. if (renderTargets_[0])
  1807. {
  1808. width = renderTargets_[0]->GetWidth();
  1809. height = renderTargets_[0]->GetHeight();
  1810. }
  1811. else
  1812. {
  1813. width = width_;
  1814. height = height_;
  1815. }
  1816. return IntVector2(width, height);
  1817. }
  1818. void Graphics::WindowResized()
  1819. {
  1820. if (!impl_->device_ || !impl_->window_)
  1821. return;
  1822. int newWidth, newHeight;
  1823. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1824. if (newWidth == width_ && newHeight == height_)
  1825. return;
  1826. width_ = newWidth;
  1827. height_ = newHeight;
  1828. impl_->presentParams_.BackBufferWidth = width_;
  1829. impl_->presentParams_.BackBufferHeight = height_;
  1830. ResetDevice();
  1831. // Reset rendertargets and viewport for the new screen size
  1832. ResetRenderTargets();
  1833. LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1834. using namespace ScreenMode;
  1835. VariantMap& eventData = GetEventDataMap();
  1836. eventData[P_WIDTH] = width_;
  1837. eventData[P_HEIGHT] = height_;
  1838. eventData[P_FULLSCREEN] = fullscreen_;
  1839. eventData[P_RESIZABLE] = resizable_;
  1840. eventData[P_BORDERLESS] = borderless_;
  1841. SendEvent(E_SCREENMODE, eventData);
  1842. }
  1843. void Graphics::Maximize()
  1844. {
  1845. if (!impl_->window_)
  1846. return;
  1847. SDL_MaximizeWindow(impl_->window_);
  1848. }
  1849. void Graphics::Minimize()
  1850. {
  1851. if (!impl_->window_)
  1852. return;
  1853. SDL_MinimizeWindow(impl_->window_);
  1854. }
  1855. void Graphics::AddGPUObject(GPUObject* object)
  1856. {
  1857. gpuObjects_.Push(object);
  1858. }
  1859. void Graphics::RemoveGPUObject(GPUObject* object)
  1860. {
  1861. gpuObjects_.Remove(object);
  1862. }
  1863. void* Graphics::ReserveScratchBuffer(unsigned size)
  1864. {
  1865. if (!size)
  1866. return 0;
  1867. if (size > maxScratchBufferRequest_)
  1868. maxScratchBufferRequest_ = size;
  1869. // First check for a free buffer that is large enough
  1870. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1871. {
  1872. if (!i->reserved_ && i->size_ >= size)
  1873. {
  1874. i->reserved_ = true;
  1875. return i->data_.Get();
  1876. }
  1877. }
  1878. // Then check if a free buffer can be resized
  1879. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1880. {
  1881. if (!i->reserved_)
  1882. {
  1883. i->data_ = new unsigned char[size];
  1884. i->size_ = size;
  1885. i->reserved_ = true;
  1886. LOGDEBUG("Resized scratch buffer to size " + String(size));
  1887. return i->data_.Get();
  1888. }
  1889. }
  1890. // Finally allocate a new buffer
  1891. ScratchBuffer newBuffer;
  1892. newBuffer.data_ = new unsigned char[size];
  1893. newBuffer.size_ = size;
  1894. newBuffer.reserved_ = true;
  1895. scratchBuffers_.Push(newBuffer);
  1896. return newBuffer.data_.Get();
  1897. LOGDEBUG("Allocated scratch buffer with size " + String(size));
  1898. }
  1899. void Graphics::FreeScratchBuffer(void* buffer)
  1900. {
  1901. if (!buffer)
  1902. return;
  1903. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1904. {
  1905. if (i->reserved_ && i->data_.Get() == buffer)
  1906. {
  1907. i->reserved_ = false;
  1908. return;
  1909. }
  1910. }
  1911. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1912. }
  1913. void Graphics::CleanupScratchBuffers()
  1914. {
  1915. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1916. {
  1917. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1918. {
  1919. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1920. i->size_ = maxScratchBufferRequest_;
  1921. LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
  1922. }
  1923. }
  1924. maxScratchBufferRequest_ = 0;
  1925. }
  1926. unsigned Graphics::GetAlphaFormat()
  1927. {
  1928. return D3DFMT_A8;
  1929. }
  1930. unsigned Graphics::GetLuminanceFormat()
  1931. {
  1932. return D3DFMT_L8;
  1933. }
  1934. unsigned Graphics::GetLuminanceAlphaFormat()
  1935. {
  1936. return D3DFMT_A8L8;
  1937. }
  1938. unsigned Graphics::GetRGBFormat()
  1939. {
  1940. return D3DFMT_X8R8G8B8;
  1941. }
  1942. unsigned Graphics::GetRGBAFormat()
  1943. {
  1944. return D3DFMT_A8R8G8B8;
  1945. }
  1946. unsigned Graphics::GetRGBA16Format()
  1947. {
  1948. return D3DFMT_A16B16G16R16;
  1949. }
  1950. unsigned Graphics::GetRGBAFloat16Format()
  1951. {
  1952. return D3DFMT_A16B16G16R16F;
  1953. }
  1954. unsigned Graphics::GetRGBAFloat32Format()
  1955. {
  1956. return D3DFMT_A32B32G32R32F;
  1957. }
  1958. unsigned Graphics::GetRG16Format()
  1959. {
  1960. return D3DFMT_G16R16;
  1961. }
  1962. unsigned Graphics::GetRGFloat16Format()
  1963. {
  1964. return D3DFMT_G16R16F;
  1965. }
  1966. unsigned Graphics::GetRGFloat32Format()
  1967. {
  1968. return D3DFMT_G32R32F;
  1969. }
  1970. unsigned Graphics::GetFloat16Format()
  1971. {
  1972. return D3DFMT_R16F;
  1973. }
  1974. unsigned Graphics::GetFloat32Format()
  1975. {
  1976. return D3DFMT_R32F;
  1977. }
  1978. unsigned Graphics::GetLinearDepthFormat()
  1979. {
  1980. return D3DFMT_R32F;
  1981. }
  1982. unsigned Graphics::GetDepthStencilFormat()
  1983. {
  1984. return depthStencilFormat;
  1985. }
  1986. unsigned Graphics::GetFormat(const String& formatName)
  1987. {
  1988. String nameLower = formatName.ToLower().Trimmed();
  1989. if (nameLower == "a")
  1990. return GetAlphaFormat();
  1991. if (nameLower == "l")
  1992. return GetLuminanceFormat();
  1993. if (nameLower == "la")
  1994. return GetLuminanceAlphaFormat();
  1995. if (nameLower == "rgb")
  1996. return GetRGBFormat();
  1997. if (nameLower == "rgba")
  1998. return GetRGBAFormat();
  1999. if (nameLower == "rgba16")
  2000. return GetRGBA16Format();
  2001. if (nameLower == "rgba16f")
  2002. return GetRGBAFloat16Format();
  2003. if (nameLower == "rgba32f")
  2004. return GetRGBAFloat32Format();
  2005. if (nameLower == "rg16")
  2006. return GetRG16Format();
  2007. if (nameLower == "rg16f")
  2008. return GetRGFloat16Format();
  2009. if (nameLower == "rg32f")
  2010. return GetRGFloat32Format();
  2011. if (nameLower == "r16f")
  2012. return GetFloat16Format();
  2013. if (nameLower == "r32f" || nameLower == "float")
  2014. return GetFloat32Format();
  2015. if (nameLower == "lineardepth" || nameLower == "depth")
  2016. return GetLinearDepthFormat();
  2017. if (nameLower == "d24s8")
  2018. return GetDepthStencilFormat();
  2019. return GetRGBFormat();
  2020. }
  2021. bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
  2022. {
  2023. if (!externalWindow_)
  2024. {
  2025. unsigned flags = 0;
  2026. if (resizable)
  2027. flags |= SDL_WINDOW_RESIZABLE;
  2028. if (borderless)
  2029. flags |= SDL_WINDOW_BORDERLESS;
  2030. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags);
  2031. }
  2032. else
  2033. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  2034. if (!impl_->window_)
  2035. {
  2036. LOGERROR("Could not create window");
  2037. return false;
  2038. }
  2039. CreateWindowIcon();
  2040. return true;
  2041. }
  2042. void Graphics::CreateWindowIcon()
  2043. {
  2044. if (windowIcon_)
  2045. {
  2046. SDL_Surface* surface = windowIcon_->GetSDLSurface();
  2047. if (surface)
  2048. {
  2049. SDL_SetWindowIcon(impl_->window_, surface);
  2050. SDL_FreeSurface(surface);
  2051. }
  2052. }
  2053. }
  2054. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless)
  2055. {
  2056. if (!externalWindow_)
  2057. {
  2058. if (!newWidth || !newHeight)
  2059. {
  2060. SDL_MaximizeWindow(impl_->window_);
  2061. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  2062. }
  2063. else
  2064. SDL_SetWindowSize(impl_->window_, newWidth, newHeight);
  2065. SDL_SetWindowFullscreen(impl_->window_, newFullscreen ? SDL_TRUE : SDL_FALSE);
  2066. SDL_SetWindowBordered(impl_->window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  2067. }
  2068. else
  2069. {
  2070. // If external window, must ask its dimensions instead of trying to set them
  2071. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  2072. newFullscreen = false;
  2073. }
  2074. }
  2075. bool Graphics::CreateInterface()
  2076. {
  2077. impl_->interface_ = Direct3DCreate9(D3D_SDK_VERSION);
  2078. if (!impl_->interface_)
  2079. {
  2080. LOGERROR("Could not create Direct3D9 interface");
  2081. return false;
  2082. }
  2083. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  2084. {
  2085. LOGERROR("Could not get Direct3D capabilities");
  2086. return false;
  2087. }
  2088. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  2089. {
  2090. LOGERROR("Could not get Direct3D adapter identifier");
  2091. return false;
  2092. }
  2093. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  2094. {
  2095. LOGERROR("Shader model 2.0 display adapter is required");
  2096. return false;
  2097. }
  2098. return true;
  2099. }
  2100. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  2101. {
  2102. #ifdef ENABLE_LUAJIT
  2103. DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
  2104. #else
  2105. DWORD behaviorFlags = 0;
  2106. #endif
  2107. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  2108. {
  2109. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  2110. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  2111. behaviorFlags |= D3DCREATE_PUREDEVICE;
  2112. }
  2113. else
  2114. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  2115. if (FAILED(impl_->interface_->CreateDevice(
  2116. adapter,
  2117. (D3DDEVTYPE)deviceType,
  2118. GetWindowHandle(impl_->window_),
  2119. behaviorFlags,
  2120. &impl_->presentParams_,
  2121. &impl_->device_)))
  2122. {
  2123. LOGERROR("Could not create Direct3D9 device");
  2124. return false;
  2125. }
  2126. impl_->adapter_ = adapter;
  2127. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  2128. OnDeviceReset();
  2129. LOGINFO("Created Direct3D9 device");
  2130. return true;
  2131. }
  2132. void Graphics::CheckFeatureSupport()
  2133. {
  2134. // Reset features first
  2135. lightPrepassSupport_ = false;
  2136. deferredSupport_ = false;
  2137. hardwareShadowSupport_ = false;
  2138. streamOffsetSupport_ = false;
  2139. hasSM3_ = false;
  2140. depthStencilFormat = D3DFMT_D24S8;
  2141. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  2142. shadowMapFormat_ = D3DFMT_D16;
  2143. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2144. {
  2145. hardwareShadowSupport_ = true;
  2146. // Check for hires depth support
  2147. hiresShadowMapFormat_ = D3DFMT_D24X8;
  2148. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2149. hiresShadowMapFormat_ = 0;
  2150. }
  2151. else
  2152. {
  2153. // ATI DF16 format needs manual depth compare in the shader
  2154. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  2155. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2156. {
  2157. // Check for hires depth support
  2158. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  2159. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2160. hiresShadowMapFormat_ = 0;
  2161. }
  2162. else
  2163. {
  2164. // No shadow map support
  2165. shadowMapFormat_ = 0;
  2166. hiresShadowMapFormat_ = 0;
  2167. }
  2168. }
  2169. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  2170. if (shadowMapFormat_ == D3DFMT_D16)
  2171. {
  2172. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  2173. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  2174. hardwareShadowSupport_ = false;
  2175. }
  2176. // Check for dummy color rendertarget format used with hardware shadow maps
  2177. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  2178. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  2179. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2180. dummyColorFormat_ = nullFormat;
  2181. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2182. dummyColorFormat_ = D3DFMT_R16F;
  2183. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2184. dummyColorFormat_ = D3DFMT_R5G6B5;
  2185. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2186. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  2187. // Check for Shader Model 3
  2188. if (!forceSM2_)
  2189. {
  2190. if (impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0) && impl_->deviceCaps_.PixelShaderVersion >=
  2191. D3DPS_VERSION(3, 0))
  2192. hasSM3_ = true;
  2193. }
  2194. // Check for light prepass and deferred rendering support
  2195. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  2196. D3DRTYPE_TEXTURE))
  2197. {
  2198. lightPrepassSupport_ = true;
  2199. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  2200. deferredSupport_ = true;
  2201. }
  2202. // Check for stream offset (needed for instancing)
  2203. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  2204. streamOffsetSupport_ = true;
  2205. // Check for sRGB read & write
  2206. /// \todo Should be checked for each texture format separately
  2207. sRGBSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE);
  2208. sRGBWriteSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBWRITE, D3DRTYPE_TEXTURE);
  2209. SendEvent(E_GRAPHICSFEATURES);
  2210. }
  2211. void Graphics::ResetDevice()
  2212. {
  2213. OnDeviceLost();
  2214. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  2215. {
  2216. deviceLost_ = false;
  2217. OnDeviceReset();
  2218. }
  2219. }
  2220. void Graphics::OnDeviceLost()
  2221. {
  2222. LOGINFO("Device lost");
  2223. if (impl_->defaultColorSurface_)
  2224. {
  2225. impl_->defaultColorSurface_->Release();
  2226. impl_->defaultColorSurface_ = 0;
  2227. }
  2228. if (impl_->defaultDepthStencilSurface_)
  2229. {
  2230. impl_->defaultDepthStencilSurface_->Release();
  2231. impl_->defaultDepthStencilSurface_ = 0;
  2232. }
  2233. if (impl_->frameQuery_)
  2234. {
  2235. impl_->frameQuery_->Release();
  2236. impl_->frameQuery_ = 0;
  2237. }
  2238. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  2239. gpuObjects_[i]->OnDeviceLost();
  2240. }
  2241. void Graphics::OnDeviceReset()
  2242. {
  2243. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  2244. gpuObjects_[i]->OnDeviceReset();
  2245. // Get default surfaces
  2246. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  2247. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  2248. // Create frame query for flushing the GPU command buffer
  2249. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  2250. ResetCachedState();
  2251. }
  2252. void Graphics::ResetCachedState()
  2253. {
  2254. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2255. {
  2256. vertexBuffers_[i] = 0;
  2257. streamOffsets_[i] = 0;
  2258. }
  2259. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2260. {
  2261. textures_[i] = 0;
  2262. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  2263. impl_->mipFilters_[i] = D3DTEXF_NONE;
  2264. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  2265. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  2266. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  2267. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2268. impl_->sRGBModes_[i] = false;
  2269. }
  2270. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2271. {
  2272. renderTargets_[i] = 0;
  2273. impl_->colorSurfaces_[i] = 0;
  2274. }
  2275. depthStencil_ = 0;
  2276. impl_->depthStencilSurface_ = 0;
  2277. viewport_ = IntRect(0, 0, width_, height_);
  2278. impl_->sRGBWrite_ = false;
  2279. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2280. streamFrequencies_[i] = 1;
  2281. indexBuffer_ = 0;
  2282. vertexDeclaration_ = 0;
  2283. vertexShader_ = 0;
  2284. pixelShader_ = 0;
  2285. blendMode_ = BLEND_REPLACE;
  2286. textureAnisotropy_ = 1;
  2287. colorWrite_ = true;
  2288. cullMode_ = CULL_CCW;
  2289. constantDepthBias_ = 0.0f;
  2290. slopeScaledDepthBias_ = 0.0f;
  2291. depthTestMode_ = CMP_LESSEQUAL;
  2292. depthWrite_ = true;
  2293. fillMode_ = FILL_SOLID;
  2294. scissorTest_ = false;
  2295. scissorRect_ = IntRect::ZERO;
  2296. stencilTest_ = false;
  2297. stencilTestMode_ = CMP_ALWAYS;
  2298. stencilPass_ = OP_KEEP;
  2299. stencilFail_ = OP_KEEP;
  2300. stencilZFail_ = OP_KEEP;
  2301. stencilRef_ = 0;
  2302. stencilCompareMask_ = M_MAX_UNSIGNED;
  2303. stencilWriteMask_ = M_MAX_UNSIGNED;
  2304. useClipPlane_ = false;
  2305. impl_->blendEnable_ = FALSE;
  2306. impl_->srcBlend_ = D3DBLEND_ONE;
  2307. impl_->destBlend_ = D3DBLEND_ZERO;
  2308. impl_->blendOp_ = D3DBLENDOP_ADD;
  2309. queryIssued_ = false;
  2310. }
  2311. void Graphics::SetTextureUnitMappings()
  2312. {
  2313. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2314. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2315. textureUnits_["NormalMap"] = TU_NORMAL;
  2316. textureUnits_["SpecMap"] = TU_SPECULAR;
  2317. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2318. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2319. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2320. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2321. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2322. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2323. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2324. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2325. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2326. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2327. }
  2328. void RegisterGraphicsLibrary(Context* context)
  2329. {
  2330. Animation::RegisterObject(context);
  2331. Material::RegisterObject(context);
  2332. Model::RegisterObject(context);
  2333. Shader::RegisterObject(context);
  2334. Technique::RegisterObject(context);
  2335. Texture2D::RegisterObject(context);
  2336. Texture3D::RegisterObject(context);
  2337. TextureCube::RegisterObject(context);
  2338. Camera::RegisterObject(context);
  2339. Drawable::RegisterObject(context);
  2340. Light::RegisterObject(context);
  2341. StaticModel::RegisterObject(context);
  2342. StaticModelGroup::RegisterObject(context);
  2343. Skybox::RegisterObject(context);
  2344. AnimatedModel::RegisterObject(context);
  2345. AnimationController::RegisterObject(context);
  2346. BillboardSet::RegisterObject(context);
  2347. ParticleEmitter::RegisterObject(context);
  2348. CustomGeometry::RegisterObject(context);
  2349. DecalSet::RegisterObject(context);
  2350. Terrain::RegisterObject(context);
  2351. TerrainPatch::RegisterObject(context);
  2352. DebugRenderer::RegisterObject(context);
  2353. Octree::RegisterObject(context);
  2354. Zone::RegisterObject(context);
  2355. }
  2356. }