D3D9Graphics.cpp 73 KB

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