D3D9Graphics.cpp 74 KB

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