D3D9Graphics.cpp 81 KB

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