D3D9Graphics.cpp 70 KB

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