D3D9Graphics.cpp 81 KB

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