D3D9Graphics.cpp 79 KB

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