D3D9Graphics.cpp 76 KB

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