D3D9Graphics.cpp 80 KB

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