D3D9Graphics.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497
  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. IntVector2 Graphics::GetDesktopResolution() const
  1581. {
  1582. SDL_DisplayMode mode;
  1583. SDL_GetDesktopDisplayMode(0, &mode);
  1584. return IntVector2(mode.w, mode.h);
  1585. }
  1586. unsigned Graphics::GetFormat(CompressedFormat format) const
  1587. {
  1588. switch (format)
  1589. {
  1590. case CF_DXT1:
  1591. return D3DFMT_DXT1;
  1592. case CF_DXT3:
  1593. return D3DFMT_DXT3;
  1594. case CF_DXT5:
  1595. return D3DFMT_DXT5;
  1596. }
  1597. return 0;
  1598. }
  1599. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1600. {
  1601. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1602. }
  1603. TextureUnit Graphics::GetTextureUnit(const String& name)
  1604. {
  1605. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1606. if (i != textureUnits_.End())
  1607. return i->second_;
  1608. else
  1609. return MAX_TEXTURE_UNITS;
  1610. }
  1611. Texture* Graphics::GetTexture(unsigned index) const
  1612. {
  1613. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1614. }
  1615. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1616. {
  1617. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1618. }
  1619. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1620. {
  1621. return index < MAX_VERTEX_STREAMS ? streamFrequencies_[index] : 0;
  1622. }
  1623. IntVector2 Graphics::GetRenderTargetDimensions() const
  1624. {
  1625. int width, height;
  1626. if (renderTargets_[0])
  1627. {
  1628. width = renderTargets_[0]->GetWidth();
  1629. height = renderTargets_[0]->GetHeight();
  1630. }
  1631. else
  1632. {
  1633. width = width_;
  1634. height = height_;
  1635. }
  1636. return IntVector2(width, height);
  1637. }
  1638. void Graphics::WindowResized()
  1639. {
  1640. if (!impl_->device_ || !impl_->window_)
  1641. return;
  1642. int newWidth, newHeight;
  1643. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1644. if (newWidth == width_ && newHeight == height_)
  1645. return;
  1646. width_ = newWidth;
  1647. height_ = newHeight;
  1648. impl_->presentParams_.BackBufferWidth = width_;
  1649. impl_->presentParams_.BackBufferHeight = height_;
  1650. ResetDevice();
  1651. // Reset rendertargets and viewport for the new screen size
  1652. ResetRenderTargets();
  1653. LOGDEBUG(ToString("Window was resized to %dx%d", width_, height_));
  1654. using namespace ScreenMode;
  1655. VariantMap eventData;
  1656. eventData[P_WIDTH] = width_;
  1657. eventData[P_HEIGHT] = height_;
  1658. eventData[P_FULLSCREEN] = fullscreen_;
  1659. eventData[P_RESIZABLE] = resizable_;
  1660. SendEvent(E_SCREENMODE, eventData);
  1661. }
  1662. void Graphics::AddGPUObject(GPUObject* object)
  1663. {
  1664. gpuObjects_.Push(object);
  1665. }
  1666. void Graphics::RemoveGPUObject(GPUObject* object)
  1667. {
  1668. gpuObjects_.Remove(object);
  1669. }
  1670. void* Graphics::ReserveScratchBuffer(unsigned size)
  1671. {
  1672. if (!size)
  1673. return 0;
  1674. if (size > maxScratchBufferRequest_)
  1675. maxScratchBufferRequest_ = size;
  1676. // First check for a free buffer that is large enough
  1677. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1678. {
  1679. if (!i->reserved_ && i->size_ >= size)
  1680. {
  1681. i->reserved_ = true;
  1682. return i->data_.Get();
  1683. }
  1684. }
  1685. // Then check if a free buffer can be resized
  1686. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1687. {
  1688. if (!i->reserved_)
  1689. {
  1690. i->data_ = new unsigned char[size];
  1691. i->size_ = size;
  1692. i->reserved_ = true;
  1693. LOGDEBUG("Resized scratch buffer to size " + String(size));
  1694. return i->data_.Get();
  1695. }
  1696. }
  1697. // Finally allocate a new buffer
  1698. ScratchBuffer newBuffer;
  1699. newBuffer.data_ = new unsigned char[size];
  1700. newBuffer.size_ = size;
  1701. newBuffer.reserved_ = true;
  1702. scratchBuffers_.Push(newBuffer);
  1703. return newBuffer.data_.Get();
  1704. LOGDEBUG("Allocated scratch buffer with size " + String(size));
  1705. }
  1706. void Graphics::FreeScratchBuffer(void* buffer)
  1707. {
  1708. if (!buffer)
  1709. return;
  1710. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1711. {
  1712. if (i->reserved_ && i->data_.Get() == buffer)
  1713. {
  1714. i->reserved_ = false;
  1715. return;
  1716. }
  1717. }
  1718. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1719. }
  1720. void Graphics::CleanupScratchBuffers()
  1721. {
  1722. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1723. {
  1724. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1725. {
  1726. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1727. i->size_ = maxScratchBufferRequest_;
  1728. LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
  1729. }
  1730. }
  1731. maxScratchBufferRequest_ = 0;
  1732. }
  1733. unsigned Graphics::GetAlphaFormat()
  1734. {
  1735. return D3DFMT_A8;
  1736. }
  1737. unsigned Graphics::GetLuminanceFormat()
  1738. {
  1739. return D3DFMT_L8;
  1740. }
  1741. unsigned Graphics::GetLuminanceAlphaFormat()
  1742. {
  1743. return D3DFMT_A8L8;
  1744. }
  1745. unsigned Graphics::GetRGBFormat()
  1746. {
  1747. return D3DFMT_X8R8G8B8;
  1748. }
  1749. unsigned Graphics::GetRGBAFormat()
  1750. {
  1751. return D3DFMT_A8R8G8B8;
  1752. }
  1753. unsigned Graphics::GetRGBA16Format()
  1754. {
  1755. return D3DFMT_A16B16G16R16;
  1756. }
  1757. unsigned Graphics::GetRGBAFloat16Format()
  1758. {
  1759. return D3DFMT_A16B16G16R16F;
  1760. }
  1761. unsigned Graphics::GetRGBAFloat32Format()
  1762. {
  1763. return D3DFMT_A32B32G32R32F;
  1764. }
  1765. unsigned Graphics::GetRG16Format()
  1766. {
  1767. return D3DFMT_G16R16;
  1768. }
  1769. unsigned Graphics::GetRGFloat16Format()
  1770. {
  1771. return D3DFMT_G16R16F;
  1772. }
  1773. unsigned Graphics::GetRGFloat32Format()
  1774. {
  1775. return D3DFMT_G32R32F;
  1776. }
  1777. unsigned Graphics::GetFloat16Format()
  1778. {
  1779. return D3DFMT_R16F;
  1780. }
  1781. unsigned Graphics::GetFloat32Format()
  1782. {
  1783. return D3DFMT_R32F;
  1784. }
  1785. unsigned Graphics::GetLinearDepthFormat()
  1786. {
  1787. return D3DFMT_R32F;
  1788. }
  1789. unsigned Graphics::GetDepthStencilFormat()
  1790. {
  1791. return depthStencilFormat;
  1792. }
  1793. unsigned Graphics::GetFormat(const String& formatName)
  1794. {
  1795. String nameLower = formatName.ToLower().Trimmed();
  1796. if (nameLower == "a")
  1797. return GetAlphaFormat();
  1798. if (nameLower == "l")
  1799. return GetLuminanceFormat();
  1800. if (nameLower == "la")
  1801. return GetLuminanceAlphaFormat();
  1802. if (nameLower == "rgb")
  1803. return GetRGBFormat();
  1804. if (nameLower == "rgba")
  1805. return GetRGBAFormat();
  1806. if (nameLower == "rgba16")
  1807. return GetRGBA16Format();
  1808. if (nameLower == "rgba16f")
  1809. return GetRGBAFloat16Format();
  1810. if (nameLower == "rgba32f")
  1811. return GetRGBAFloat32Format();
  1812. if (nameLower == "rg16")
  1813. return GetRG16Format();
  1814. if (nameLower == "rg16f")
  1815. return GetRGFloat16Format();
  1816. if (nameLower == "rg32f")
  1817. return GetRGFloat32Format();
  1818. if (nameLower == "r16f")
  1819. return GetFloat16Format();
  1820. if (nameLower == "r32f" || nameLower == "float")
  1821. return GetFloat32Format();
  1822. if (nameLower == "lineardepth" || nameLower == "depth")
  1823. return GetLinearDepthFormat();
  1824. if (nameLower == "d24s8")
  1825. return GetDepthStencilFormat();
  1826. return GetRGBFormat();
  1827. }
  1828. bool Graphics::OpenWindow(int width, int height, bool resizable)
  1829. {
  1830. if (!externalWindow_)
  1831. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, resizable ? SDL_WINDOW_RESIZABLE : 0);
  1832. else
  1833. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1834. if (!impl_->window_)
  1835. {
  1836. LOGERROR("Could not create window");
  1837. return false;
  1838. }
  1839. return true;
  1840. }
  1841. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen)
  1842. {
  1843. if (!externalWindow_)
  1844. {
  1845. SDL_SetWindowSize(impl_->window_, newWidth, newHeight);
  1846. SDL_SetWindowFullscreen(impl_->window_, newFullscreen ? SDL_TRUE : SDL_FALSE);
  1847. }
  1848. else
  1849. {
  1850. // If external window, must ask its dimensions instead of trying to set them
  1851. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1852. newFullscreen = false;
  1853. }
  1854. }
  1855. bool Graphics::CreateInterface()
  1856. {
  1857. impl_->interface_ = Direct3DCreate9(D3D_SDK_VERSION);
  1858. if (!impl_->interface_)
  1859. {
  1860. LOGERROR("Could not create Direct3D9 interface");
  1861. return false;
  1862. }
  1863. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  1864. {
  1865. LOGERROR("Could not get Direct3D capabilities");
  1866. return false;
  1867. }
  1868. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  1869. {
  1870. LOGERROR("Could not get Direct3D adapter identifier");
  1871. return false;
  1872. }
  1873. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1874. {
  1875. LOGERROR("Shader model 2.0 display adapter is required");
  1876. return false;
  1877. }
  1878. return true;
  1879. }
  1880. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1881. {
  1882. #ifdef ENABLE_LUAJIT
  1883. DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
  1884. #else
  1885. DWORD behaviorFlags = 0;
  1886. #endif
  1887. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1888. {
  1889. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1890. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1891. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1892. }
  1893. else
  1894. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1895. if (FAILED(impl_->interface_->CreateDevice(
  1896. adapter,
  1897. (D3DDEVTYPE)deviceType,
  1898. WIN_GetWindowHandle(impl_->window_),
  1899. behaviorFlags,
  1900. &impl_->presentParams_,
  1901. &impl_->device_)))
  1902. {
  1903. LOGERROR("Could not create Direct3D9 device");
  1904. return false;
  1905. }
  1906. impl_->adapter_ = adapter;
  1907. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1908. OnDeviceReset();
  1909. LOGINFO("Created Direct3D9 device");
  1910. return true;
  1911. }
  1912. void Graphics::CheckFeatureSupport()
  1913. {
  1914. // Reset features first
  1915. lightPrepassSupport_ = false;
  1916. deferredSupport_ = false;
  1917. hardwareShadowSupport_ = false;
  1918. streamOffsetSupport_ = false;
  1919. hasSM3_ = false;
  1920. depthStencilFormat = D3DFMT_D24S8;
  1921. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  1922. shadowMapFormat_ = D3DFMT_D16;
  1923. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1924. {
  1925. hardwareShadowSupport_ = true;
  1926. // Check for hires depth support
  1927. hiresShadowMapFormat_ = D3DFMT_D24X8;
  1928. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1929. hiresShadowMapFormat_ = 0;
  1930. }
  1931. else
  1932. {
  1933. // ATI DF16 format needs manual depth compare in the shader
  1934. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  1935. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1936. {
  1937. // Check for hires depth support
  1938. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  1939. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1940. hiresShadowMapFormat_ = 0;
  1941. }
  1942. else
  1943. {
  1944. // No shadow map support
  1945. shadowMapFormat_ = 0;
  1946. hiresShadowMapFormat_ = 0;
  1947. }
  1948. }
  1949. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  1950. if (shadowMapFormat_ == D3DFMT_D16)
  1951. {
  1952. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  1953. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  1954. hardwareShadowSupport_ = false;
  1955. }
  1956. // Check for dummy color rendertarget format used with hardware shadow maps
  1957. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  1958. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  1959. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1960. dummyColorFormat_ = nullFormat;
  1961. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1962. dummyColorFormat_ = D3DFMT_R16F;
  1963. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1964. dummyColorFormat_ = D3DFMT_R5G6B5;
  1965. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1966. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  1967. // Check for Shader Model 3
  1968. if (!forceSM2_)
  1969. {
  1970. if (impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0) && impl_->deviceCaps_.PixelShaderVersion >=
  1971. D3DPS_VERSION(3, 0))
  1972. hasSM3_ = true;
  1973. }
  1974. // Check for light prepass and deferred rendering support
  1975. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  1976. D3DRTYPE_TEXTURE))
  1977. {
  1978. lightPrepassSupport_ = true;
  1979. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  1980. deferredSupport_ = true;
  1981. }
  1982. // Check for stream offset (needed for instancing)
  1983. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  1984. streamOffsetSupport_ = true;
  1985. // Check for sRGB read & write
  1986. /// \todo Should be checked for each texture format separately
  1987. sRGBSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE);
  1988. sRGBWriteSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBWRITE, D3DRTYPE_TEXTURE);
  1989. SendEvent(E_GRAPHICSFEATURES);
  1990. }
  1991. void Graphics::ResetDevice()
  1992. {
  1993. OnDeviceLost();
  1994. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  1995. {
  1996. deviceLost_ = false;
  1997. OnDeviceReset();
  1998. }
  1999. }
  2000. void Graphics::OnDeviceLost()
  2001. {
  2002. LOGINFO("Device lost");
  2003. if (impl_->defaultColorSurface_)
  2004. {
  2005. impl_->defaultColorSurface_->Release();
  2006. impl_->defaultColorSurface_ = 0;
  2007. }
  2008. if (impl_->defaultDepthStencilSurface_)
  2009. {
  2010. impl_->defaultDepthStencilSurface_->Release();
  2011. impl_->defaultDepthStencilSurface_ = 0;
  2012. }
  2013. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  2014. gpuObjects_[i]->OnDeviceLost();
  2015. }
  2016. void Graphics::OnDeviceReset()
  2017. {
  2018. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  2019. gpuObjects_[i]->OnDeviceReset();
  2020. // Get default surfaces
  2021. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  2022. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  2023. ResetCachedState();
  2024. }
  2025. void Graphics::ResetCachedState()
  2026. {
  2027. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2028. {
  2029. vertexBuffers_[i] = 0;
  2030. streamOffsets_[i] = 0;
  2031. }
  2032. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2033. {
  2034. textures_[i] = 0;
  2035. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  2036. impl_->mipFilters_[i] = D3DTEXF_NONE;
  2037. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  2038. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  2039. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  2040. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2041. impl_->sRGBModes_[i] = false;
  2042. }
  2043. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2044. {
  2045. renderTargets_[i] = 0;
  2046. impl_->colorSurfaces_[i] = 0;
  2047. }
  2048. depthStencil_ = 0;
  2049. impl_->depthStencilSurface_ = 0;
  2050. viewTexture_ = 0;
  2051. viewport_ = IntRect(0, 0, width_, height_);
  2052. impl_->sRGBWrite_ = false;
  2053. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2054. streamFrequencies_[i] = 1;
  2055. indexBuffer_ = 0;
  2056. vertexDeclaration_ = 0;
  2057. vertexShader_ = 0;
  2058. pixelShader_ = 0;
  2059. blendMode_ = BLEND_REPLACE;
  2060. textureAnisotropy_ = 1;
  2061. colorWrite_ = true;
  2062. cullMode_ = CULL_CCW;
  2063. constantDepthBias_ = 0.0f;
  2064. slopeScaledDepthBias_ = 0.0f;
  2065. depthTestMode_ = CMP_LESSEQUAL;
  2066. depthWrite_ = true;
  2067. fillMode_ = FILL_SOLID;
  2068. scissorTest_ = false;
  2069. scissorRect_ = IntRect::ZERO;
  2070. stencilTest_ = false;
  2071. stencilTestMode_ = CMP_ALWAYS;
  2072. stencilPass_ = OP_KEEP;
  2073. stencilFail_ = OP_KEEP;
  2074. stencilZFail_ = OP_KEEP;
  2075. stencilRef_ = 0;
  2076. stencilCompareMask_ = M_MAX_UNSIGNED;
  2077. stencilWriteMask_ = M_MAX_UNSIGNED;
  2078. impl_->blendEnable_ = FALSE;
  2079. impl_->srcBlend_ = D3DBLEND_ONE;
  2080. impl_->destBlend_ = D3DBLEND_ZERO;
  2081. }
  2082. void Graphics::SetTextureUnitMappings()
  2083. {
  2084. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2085. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2086. textureUnits_["NormalMap"] = TU_NORMAL;
  2087. textureUnits_["SpecMap"] = TU_SPECULAR;
  2088. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2089. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2090. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2091. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2092. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2093. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2094. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2095. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2096. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2097. }
  2098. void RegisterGraphicsLibrary(Context* context)
  2099. {
  2100. Animation::RegisterObject(context);
  2101. Material::RegisterObject(context);
  2102. Model::RegisterObject(context);
  2103. Shader::RegisterObject(context);
  2104. Technique::RegisterObject(context);
  2105. Texture2D::RegisterObject(context);
  2106. TextureCube::RegisterObject(context);
  2107. Camera::RegisterObject(context);
  2108. Drawable::RegisterObject(context);
  2109. Light::RegisterObject(context);
  2110. StaticModel::RegisterObject(context);
  2111. StaticModelGroup::RegisterObject(context);
  2112. Skybox::RegisterObject(context);
  2113. AnimatedModel::RegisterObject(context);
  2114. AnimationController::RegisterObject(context);
  2115. BillboardSet::RegisterObject(context);
  2116. ParticleEmitter::RegisterObject(context);
  2117. CustomGeometry::RegisterObject(context);
  2118. DecalSet::RegisterObject(context);
  2119. Terrain::RegisterObject(context);
  2120. TerrainPatch::RegisterObject(context);
  2121. DebugRenderer::RegisterObject(context);
  2122. Octree::RegisterObject(context);
  2123. Zone::RegisterObject(context);
  2124. }
  2125. }