D3D9Graphics.cpp 81 KB

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