D3D9Graphics.cpp 71 KB

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