D3D9Graphics.cpp 85 KB

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