D3D9Graphics.cpp 76 KB

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