D3D9Graphics.cpp 71 KB

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