D3D9Graphics.cpp 84 KB

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