D3D9Graphics.cpp 70 KB

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