D3D9Graphics.cpp 83 KB

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