D3D9Graphics.cpp 83 KB

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