D3D9Graphics.cpp 68 KB

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