D3D9Graphics.cpp 69 KB

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