D3D9Graphics.cpp 81 KB

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