D3D9Graphics.cpp 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764
  1. //
  2. // Copyright (c) 2008-2015 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 "../../Core/Context.h"
  24. #include "../../Core/ProcessUtils.h"
  25. #include "../../Core/Profiler.h"
  26. #include "../../Graphics/Camera.h"
  27. #include "../../Graphics/DebugRenderer.h"
  28. #include "../../Graphics/Graphics.h"
  29. #include "../../Graphics/GraphicsEvents.h"
  30. #include "../../Graphics/GraphicsImpl.h"
  31. #include "../../Graphics/IndexBuffer.h"
  32. #include "../../Graphics/Material.h"
  33. #include "../../Graphics/Octree.h"
  34. #include "../../Graphics/Shader.h"
  35. #include "../../Graphics/ShaderPrecache.h"
  36. #include "../../Graphics/ShaderProgram.h"
  37. #include "../../Graphics/Technique.h"
  38. #include "../../Graphics/Texture2D.h"
  39. #include "../../Graphics/Texture3D.h"
  40. #include "../../Graphics/TextureCube.h"
  41. #include "../../Graphics/VertexBuffer.h"
  42. #include "../../Graphics/VertexDeclaration.h"
  43. #include "../../Graphics/Zone.h"
  44. #include "../../IO/File.h"
  45. #include "../../IO/Log.h"
  46. #include "../../Resource/ResourceCache.h"
  47. #include <SDL/include/SDL_syswm.h>
  48. #include "../../DebugNew.h"
  49. #ifdef _MSC_VER
  50. #pragma warning(disable:4355)
  51. #endif
  52. // Prefer the high-performance GPU on switchable GPU systems
  53. extern "C"
  54. {
  55. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  56. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  57. }
  58. // Fix missing define in MinGW headers
  59. #ifndef D3DPRESENT_LINEAR_CONTENT
  60. #define D3DPRESENT_LINEAR_CONTENT 0x00000002L
  61. #endif
  62. namespace Atomic
  63. {
  64. static const D3DCMPFUNC d3dCmpFunc[] =
  65. {
  66. D3DCMP_ALWAYS,
  67. D3DCMP_EQUAL,
  68. D3DCMP_NOTEQUAL,
  69. D3DCMP_LESS,
  70. D3DCMP_LESSEQUAL,
  71. D3DCMP_GREATER,
  72. D3DCMP_GREATEREQUAL
  73. };
  74. static const D3DTEXTUREFILTERTYPE d3dMinMagFilter[] =
  75. {
  76. D3DTEXF_POINT,
  77. D3DTEXF_LINEAR,
  78. D3DTEXF_LINEAR,
  79. D3DTEXF_ANISOTROPIC
  80. };
  81. static const D3DTEXTUREFILTERTYPE d3dMipFilter[] =
  82. {
  83. D3DTEXF_POINT,
  84. D3DTEXF_POINT,
  85. D3DTEXF_LINEAR,
  86. D3DTEXF_ANISOTROPIC
  87. };
  88. static const D3DTEXTUREADDRESS d3dAddressMode[] =
  89. {
  90. D3DTADDRESS_WRAP,
  91. D3DTADDRESS_MIRROR,
  92. D3DTADDRESS_CLAMP,
  93. D3DTADDRESS_BORDER
  94. };
  95. static const DWORD d3dBlendEnable[] =
  96. {
  97. FALSE,
  98. TRUE,
  99. TRUE,
  100. TRUE,
  101. TRUE,
  102. TRUE,
  103. TRUE,
  104. TRUE
  105. };
  106. static const D3DBLEND d3dSrcBlend[] =
  107. {
  108. D3DBLEND_ONE,
  109. D3DBLEND_ONE,
  110. D3DBLEND_DESTCOLOR,
  111. D3DBLEND_SRCALPHA,
  112. D3DBLEND_SRCALPHA,
  113. D3DBLEND_ONE,
  114. D3DBLEND_INVDESTALPHA,
  115. D3DBLEND_ONE,
  116. D3DBLEND_SRCALPHA,
  117. };
  118. static const D3DBLEND d3dDestBlend[] =
  119. {
  120. D3DBLEND_ZERO,
  121. D3DBLEND_ONE,
  122. D3DBLEND_ZERO,
  123. D3DBLEND_INVSRCALPHA,
  124. D3DBLEND_ONE,
  125. D3DBLEND_INVSRCALPHA,
  126. D3DBLEND_DESTALPHA,
  127. D3DBLEND_ONE,
  128. D3DBLEND_ONE
  129. };
  130. static const D3DBLENDOP d3dBlendOp[] =
  131. {
  132. D3DBLENDOP_ADD,
  133. D3DBLENDOP_ADD,
  134. D3DBLENDOP_ADD,
  135. D3DBLENDOP_ADD,
  136. D3DBLENDOP_ADD,
  137. D3DBLENDOP_ADD,
  138. D3DBLENDOP_ADD,
  139. D3DBLENDOP_REVSUBTRACT,
  140. D3DBLENDOP_REVSUBTRACT
  141. };
  142. static const D3DCULL d3dCullMode[] =
  143. {
  144. D3DCULL_NONE,
  145. D3DCULL_CCW,
  146. D3DCULL_CW
  147. };
  148. static const D3DFILLMODE d3dFillMode[] =
  149. {
  150. D3DFILL_SOLID,
  151. D3DFILL_WIREFRAME,
  152. D3DFILL_POINT
  153. };
  154. static const D3DSTENCILOP d3dStencilOp[] =
  155. {
  156. D3DSTENCILOP_KEEP,
  157. D3DSTENCILOP_ZERO,
  158. D3DSTENCILOP_REPLACE,
  159. D3DSTENCILOP_INCR,
  160. D3DSTENCILOP_DECR
  161. };
  162. static unsigned GetD3DColor(const Color& color)
  163. {
  164. unsigned r = (unsigned)(Clamp(color.r_ * 255.0f, 0.0f, 255.0f));
  165. unsigned g = (unsigned)(Clamp(color.g_ * 255.0f, 0.0f, 255.0f));
  166. unsigned b = (unsigned)(Clamp(color.b_ * 255.0f, 0.0f, 255.0f));
  167. unsigned a = (unsigned)(Clamp(color.a_ * 255.0f, 0.0f, 255.0f));
  168. return (((a) & 0xff) << 24) | (((r) & 0xff) << 16) | (((g) & 0xff) << 8) | ((b) & 0xff);
  169. }
  170. static void GetD3DPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount,
  171. D3DPRIMITIVETYPE& d3dPrimitiveType)
  172. {
  173. switch (type)
  174. {
  175. case TRIANGLE_LIST:
  176. primitiveCount = elementCount / 3;
  177. d3dPrimitiveType = D3DPT_TRIANGLELIST;
  178. break;
  179. case LINE_LIST:
  180. primitiveCount = elementCount / 2;
  181. d3dPrimitiveType = D3DPT_LINELIST;
  182. break;
  183. case POINT_LIST:
  184. primitiveCount = elementCount;
  185. d3dPrimitiveType = D3DPT_POINTLIST;
  186. break;
  187. case TRIANGLE_STRIP:
  188. primitiveCount = elementCount - 2;
  189. d3dPrimitiveType = D3DPT_TRIANGLESTRIP;
  190. break;
  191. case LINE_STRIP:
  192. primitiveCount = elementCount - 1;
  193. d3dPrimitiveType = D3DPT_LINESTRIP;
  194. break;
  195. case TRIANGLE_FAN:
  196. primitiveCount = elementCount - 2;
  197. d3dPrimitiveType = D3DPT_TRIANGLEFAN;
  198. break;
  199. }
  200. }
  201. static HWND GetWindowHandle(SDL_Window* window)
  202. {
  203. SDL_SysWMinfo sysInfo;
  204. SDL_VERSION(&sysInfo.version);
  205. SDL_GetWindowWMInfo(window, &sysInfo);
  206. return sysInfo.info.win.window;
  207. }
  208. static unsigned readableDepthFormat = 0;
  209. const Vector2 Graphics::pixelUVOffset(0.5f, 0.5f);
  210. Graphics::Graphics(Context* context) :
  211. Object(context),
  212. impl_(new GraphicsImpl()),
  213. windowIcon_(0),
  214. externalWindow_(0),
  215. width_(0),
  216. height_(0),
  217. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  218. multiSample_(1),
  219. fullscreen_(false),
  220. borderless_(false),
  221. resizable_(false),
  222. vsync_(false),
  223. tripleBuffer_(false),
  224. flushGPU_(false),
  225. sRGB_(false),
  226. deviceLost_(false),
  227. queryIssued_(false),
  228. lightPrepassSupport_(false),
  229. deferredSupport_(false),
  230. instancingSupport_(false),
  231. sRGBSupport_(false),
  232. sRGBWriteSupport_(false),
  233. numPrimitives_(0),
  234. numBatches_(0),
  235. maxScratchBufferRequest_(0),
  236. defaultTextureFilterMode_(FILTER_TRILINEAR),
  237. shaderProgram_(0),
  238. shaderPath_("Shaders/HLSL/"),
  239. shaderExtension_(".hlsl"),
  240. orientations_("LandscapeLeft LandscapeRight"),
  241. apiName_("D3D9")
  242. {
  243. SetTextureUnitMappings();
  244. // Initialize SDL now. Graphics should be the first SDL-using subsystem to be created
  245. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_NOPARACHUTE);
  246. // Register Graphics library object factories
  247. RegisterGraphicsLibrary(context_);
  248. }
  249. Graphics::~Graphics()
  250. {
  251. {
  252. MutexLock lock(gpuObjectMutex_);
  253. // Release all GPU objects that still exist
  254. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  255. (*i)->Release();
  256. gpuObjects_.Clear();
  257. }
  258. vertexDeclarations_.Clear();
  259. if (impl_->defaultColorSurface_)
  260. {
  261. impl_->defaultColorSurface_->Release();
  262. impl_->defaultColorSurface_ = 0;
  263. }
  264. if (impl_->defaultDepthStencilSurface_)
  265. {
  266. impl_->defaultDepthStencilSurface_->Release();
  267. impl_->defaultDepthStencilSurface_ = 0;
  268. }
  269. if (impl_->frameQuery_)
  270. {
  271. impl_->frameQuery_->Release();
  272. impl_->frameQuery_ = 0;
  273. }
  274. if (impl_->device_)
  275. {
  276. impl_->device_->Release();
  277. impl_->device_ = 0;
  278. }
  279. if (impl_->interface_)
  280. {
  281. impl_->interface_->Release();
  282. impl_->interface_ = 0;
  283. }
  284. if (impl_->window_)
  285. {
  286. SDL_ShowCursor(SDL_TRUE);
  287. SDL_DestroyWindow(impl_->window_);
  288. impl_->window_ = 0;
  289. }
  290. delete impl_;
  291. impl_ = 0;
  292. // Shut down SDL now. Graphics should be the last SDL-using subsystem to be destroyed
  293. SDL_Quit();
  294. }
  295. void Graphics::SetExternalWindow(void* window)
  296. {
  297. if (!impl_->window_)
  298. externalWindow_ = window;
  299. else
  300. LOGERROR("Window already opened, can not set external window");
  301. }
  302. void Graphics::SetWindowTitle(const String& windowTitle)
  303. {
  304. windowTitle_ = windowTitle;
  305. if (impl_->window_)
  306. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  307. }
  308. void Graphics::SetWindowIcon(Image* windowIcon)
  309. {
  310. windowIcon_ = windowIcon;
  311. if (impl_->window_)
  312. CreateWindowIcon();
  313. }
  314. void Graphics::SetWindowPosition(const IntVector2& position)
  315. {
  316. if (impl_->window_)
  317. SDL_SetWindowPosition(impl_->window_, position.x_, position.y_);
  318. else
  319. position_ = position; // Sets as initial position for OpenWindow()
  320. }
  321. void Graphics::SetWindowPosition(int x, int y)
  322. {
  323. SetWindowPosition(IntVector2(x, y));
  324. }
  325. void Graphics::SetWindowSize(int width, int height)
  326. {
  327. if (impl_->window_)
  328. {
  329. SDL_SetWindowSize(impl_->window_, width, height);
  330. WindowResized();
  331. }
  332. }
  333. void Graphics::CenterWindow()
  334. {
  335. if (impl_->window_)
  336. {
  337. SDL_DisplayMode mode;
  338. SDL_GetDesktopDisplayMode(0, &mode);
  339. int width, height;
  340. SDL_GetWindowSize(impl_->window_, &width, &height);
  341. int x = mode.w/2 - width/2;
  342. int y = mode.h/2 - height/2;
  343. SetWindowPosition(x, y);
  344. }
  345. }
  346. void* Graphics::GetSDLWindow()
  347. {
  348. return impl_->window_;
  349. }
  350. void Graphics::RaiseWindow()
  351. {
  352. if (impl_->window_)
  353. SDL_RaiseWindow(impl_->window_);
  354. }
  355. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer,
  356. int multiSample)
  357. {
  358. PROFILE(SetScreenMode);
  359. bool maximize = false;
  360. // Find out the full screen mode display format (match desktop color depth)
  361. SDL_DisplayMode mode;
  362. SDL_GetDesktopDisplayMode(0, &mode);
  363. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  364. // If zero dimensions in windowed mode, set windowed mode to maximize and set a predefined default restored window size. If zero in fullscreen, use desktop mode
  365. if (!width || !height)
  366. {
  367. if (fullscreen || borderless)
  368. {
  369. width = mode.w;
  370. height = mode.h;
  371. }
  372. else
  373. {
  374. maximize = resizable;
  375. width = 1024;
  376. height = 768;
  377. }
  378. }
  379. // Fullscreen or Borderless can not be resizable
  380. if (fullscreen || borderless)
  381. resizable = false;
  382. // Borderless cannot be fullscreen, they are mutually exclusive
  383. if (borderless)
  384. fullscreen = false;
  385. multiSample = Clamp(multiSample, 1, (int)D3DMULTISAMPLE_16_SAMPLES);
  386. // If nothing changes, do not reset the device
  387. if (width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  388. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  389. return true;
  390. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  391. if (!impl_->window_)
  392. {
  393. if (!OpenWindow(width, height, resizable, borderless))
  394. return false;
  395. }
  396. if (!impl_->interface_)
  397. {
  398. if (!CreateInterface())
  399. return false;
  400. CheckFeatureSupport();
  401. }
  402. // Note: GetMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  403. multiSample_ = multiSample;
  404. // Check fullscreen mode validity. Use a closest match if not found
  405. if (fullscreen)
  406. {
  407. PODVector<IntVector2> resolutions = GetResolutions();
  408. if (resolutions.Empty())
  409. fullscreen = false;
  410. else
  411. {
  412. unsigned best = 0;
  413. unsigned bestError = M_MAX_UNSIGNED;
  414. for (unsigned i = 0; i < resolutions.Size(); ++i)
  415. {
  416. unsigned error = (unsigned)(Abs(resolutions[i].x_ - width) + Abs(resolutions[i].y_ - height));
  417. if (error < bestError)
  418. {
  419. best = i;
  420. bestError = error;
  421. }
  422. }
  423. width = resolutions[best].x_;
  424. height = resolutions[best].y_;
  425. }
  426. }
  427. // Fall back to non-multisampled if unsupported multisampling mode
  428. if (multiSample > 1)
  429. {
  430. if (FAILED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  431. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  432. multiSample = 1;
  433. }
  434. AdjustWindow(width, height, fullscreen, borderless);
  435. if (maximize)
  436. {
  437. Maximize();
  438. SDL_GetWindowSize(impl_->window_, &width, &height);
  439. }
  440. if (fullscreen)
  441. {
  442. impl_->presentParams_.BackBufferFormat = fullscreenFormat;
  443. impl_->presentParams_.Windowed = false;
  444. }
  445. else
  446. {
  447. impl_->presentParams_.BackBufferFormat = D3DFMT_UNKNOWN;
  448. impl_->presentParams_.Windowed = true;
  449. }
  450. impl_->presentParams_.BackBufferWidth = (UINT)width;
  451. impl_->presentParams_.BackBufferHeight = (UINT)height;
  452. impl_->presentParams_.BackBufferCount = tripleBuffer ? 2 : 1;
  453. impl_->presentParams_.MultiSampleType = multiSample > 1 ? (D3DMULTISAMPLE_TYPE)multiSample : D3DMULTISAMPLE_NONE;
  454. impl_->presentParams_.MultiSampleQuality = 0;
  455. impl_->presentParams_.SwapEffect = D3DSWAPEFFECT_DISCARD;
  456. impl_->presentParams_.hDeviceWindow = GetWindowHandle(impl_->window_);
  457. impl_->presentParams_.EnableAutoDepthStencil = TRUE;
  458. impl_->presentParams_.AutoDepthStencilFormat = D3DFMT_D24S8;
  459. impl_->presentParams_.Flags = D3DPRESENT_LINEAR_CONTENT;
  460. impl_->presentParams_.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  461. if (vsync)
  462. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  463. else
  464. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  465. width_ = width;
  466. height_ = height;
  467. fullscreen_ = fullscreen;
  468. borderless_ = borderless;
  469. resizable_ = resizable;
  470. vsync_ = vsync;
  471. tripleBuffer_ = tripleBuffer;
  472. if (!impl_->device_)
  473. {
  474. unsigned adapter = D3DADAPTER_DEFAULT;
  475. unsigned deviceType = D3DDEVTYPE_HAL;
  476. // Check for PerfHUD adapter
  477. for (unsigned i = 0; i < impl_->interface_->GetAdapterCount(); ++i)
  478. {
  479. D3DADAPTER_IDENTIFIER9 identifier;
  480. impl_->interface_->GetAdapterIdentifier(i, 0, &identifier);
  481. if (strstr(identifier.Description, "PerfHUD") != 0)
  482. {
  483. adapter = i;
  484. deviceType = D3DDEVTYPE_REF;
  485. break;
  486. }
  487. }
  488. impl_->interface_->GetAdapterIdentifier(adapter, 0, &impl_->adapterIdentifier_);
  489. if (!CreateDevice(adapter, deviceType))
  490. return false;
  491. }
  492. else
  493. ResetDevice();
  494. // Clear the initial window contents to black
  495. impl_->device_->BeginScene();
  496. Clear(CLEAR_COLOR);
  497. impl_->device_->EndScene();
  498. impl_->device_->Present(0, 0, 0, 0);
  499. #ifdef ATOMIC_LOGGING
  500. String msg;
  501. msg.AppendWithFormat("Set screen mode %dx%d %s", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"));
  502. if (borderless_)
  503. msg.Append(" borderless");
  504. if (resizable_)
  505. msg.Append(" resizable");
  506. if (multiSample > 1)
  507. msg.AppendWithFormat(" multisample %d", multiSample);
  508. LOGINFO(msg);
  509. #endif
  510. using namespace ScreenMode;
  511. VariantMap& eventData = GetEventDataMap();
  512. eventData[P_WIDTH] = width_;
  513. eventData[P_HEIGHT] = height_;
  514. eventData[P_FULLSCREEN] = fullscreen_;
  515. eventData[P_RESIZABLE] = resizable_;
  516. eventData[P_BORDERLESS] = borderless_;
  517. SendEvent(E_SCREENMODE, eventData);
  518. return true;
  519. }
  520. bool Graphics::SetMode(int width, int height)
  521. {
  522. return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  523. }
  524. void Graphics::SetSRGB(bool enable)
  525. {
  526. sRGB_ = enable && sRGBWriteSupport_;
  527. }
  528. void Graphics::SetFlushGPU(bool enable)
  529. {
  530. flushGPU_ = enable;
  531. }
  532. void Graphics::SetOrientations(const String& orientations)
  533. {
  534. orientations_ = orientations.Trimmed();
  535. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  536. }
  537. bool Graphics::ToggleFullscreen()
  538. {
  539. return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  540. }
  541. void Graphics::Close()
  542. {
  543. if (impl_->window_)
  544. {
  545. SDL_ShowCursor(SDL_TRUE);
  546. SDL_DestroyWindow(impl_->window_);
  547. impl_->window_ = 0;
  548. }
  549. }
  550. bool Graphics::TakeScreenShot(Image* destImage)
  551. {
  552. PROFILE(TakeScreenShot);
  553. if (!impl_->device_)
  554. return false;
  555. D3DSURFACE_DESC surfaceDesc;
  556. impl_->defaultColorSurface_->GetDesc(&surfaceDesc);
  557. // If possible, get the backbuffer data, because it is a lot faster.
  558. // However, if we are multisampled, need to use the front buffer
  559. bool useBackBuffer = true;
  560. unsigned surfaceWidth = (unsigned)width_;
  561. unsigned surfaceHeight = (unsigned)height_;
  562. if (impl_->presentParams_.MultiSampleType)
  563. {
  564. // If windowed and multisampled, must still capture the whole screen
  565. if (!fullscreen_)
  566. {
  567. IntVector2 desktopSize = GetDesktopResolution();
  568. surfaceWidth = (unsigned)desktopSize.x_;
  569. surfaceHeight = (unsigned)desktopSize.y_;
  570. }
  571. useBackBuffer = false;
  572. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  573. }
  574. IDirect3DSurface9* surface = 0;
  575. impl_->device_->CreateOffscreenPlainSurface(surfaceWidth, surfaceHeight, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  576. if (!surface)
  577. {
  578. LOGERROR("Could not create surface for taking a screenshot");
  579. return false;
  580. }
  581. if (useBackBuffer)
  582. impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  583. else
  584. impl_->device_->GetFrontBufferData(0, surface);
  585. // If capturing the whole screen, determine the window rect
  586. RECT sourceRect;
  587. if (surfaceHeight == height_ && surfaceWidth == width_)
  588. {
  589. sourceRect.left = 0;
  590. sourceRect.top = 0;
  591. sourceRect.right = width_;
  592. sourceRect.bottom = height_;
  593. }
  594. else
  595. {
  596. HWND hwnd = GetWindowHandle(impl_->window_);
  597. GetClientRect(hwnd, &sourceRect);
  598. ClientToScreen(hwnd, (LPPOINT)&sourceRect);
  599. }
  600. D3DLOCKED_RECT lockedRect;
  601. lockedRect.pBits = 0;
  602. surface->LockRect(&lockedRect, &sourceRect, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  603. if (!lockedRect.pBits)
  604. {
  605. LOGERROR("Could not lock surface for taking a screenshot");
  606. surface->Release();
  607. return false;
  608. }
  609. destImage->SetSize(width_, height_, 3);
  610. unsigned char* destData = destImage->GetData();
  611. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  612. {
  613. for (int y = 0; y < height_; ++y)
  614. {
  615. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  616. unsigned char* dest = destData + y * width_ * 3;
  617. for (int x = 0; x < width_; ++x)
  618. {
  619. unsigned short rgb = *src++;
  620. int b = rgb & 31;
  621. int g = (rgb >> 5) & 63;
  622. int r = (rgb >> 11);
  623. dest[0] = (unsigned char)(r * 255.0f / 31.0f);
  624. dest[1] = (unsigned char)(g * 255.0f / 63.0f);
  625. dest[2] = (unsigned char)(b * 255.0f / 31.0f);
  626. dest += 3;
  627. }
  628. }
  629. }
  630. else
  631. {
  632. for (int y = 0; y < height_; ++y)
  633. {
  634. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  635. unsigned char* dest = destData + y * width_ * 3;
  636. for (int x = 0; x < width_; ++x)
  637. {
  638. dest[0] = src[2];
  639. dest[1] = src[1];
  640. dest[2] = src[0];
  641. src += 4;
  642. dest += 3;
  643. }
  644. }
  645. }
  646. surface->UnlockRect();
  647. surface->Release();
  648. return true;
  649. }
  650. bool Graphics::BeginFrame()
  651. {
  652. if (!IsInitialized())
  653. return false;
  654. // If using an external window, check it for size changes, and reset screen mode if necessary
  655. if (externalWindow_)
  656. {
  657. int width, height;
  658. SDL_GetWindowSize(impl_->window_, &width, &height);
  659. if (width != width_ || height != height_)
  660. SetMode(width, height);
  661. }
  662. else
  663. {
  664. // To prevent a loop of endless device loss and flicker, do not attempt to render when in fullscreen
  665. // and the window is minimized
  666. if (fullscreen_ && (SDL_GetWindowFlags(impl_->window_) & SDL_WINDOW_MINIMIZED))
  667. return false;
  668. }
  669. // Check for lost device before rendering
  670. HRESULT hr = impl_->device_->TestCooperativeLevel();
  671. if (hr != D3D_OK)
  672. {
  673. PROFILE(DeviceLost);
  674. deviceLost_ = true;
  675. // The device can not be reset yet, sleep and try again eventually
  676. if (hr == D3DERR_DEVICELOST)
  677. {
  678. Time::Sleep(20);
  679. return false;
  680. }
  681. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  682. if (hr == D3DERR_DEVICENOTRESET)
  683. {
  684. ResetDevice();
  685. return false;
  686. }
  687. }
  688. impl_->device_->BeginScene();
  689. // Set default rendertarget and depth buffer
  690. ResetRenderTargets();
  691. // Cleanup textures from previous frame
  692. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  693. SetTexture(i, 0);
  694. numPrimitives_ = 0;
  695. numBatches_ = 0;
  696. SendEvent(E_BEGINRENDERING);
  697. return true;
  698. }
  699. void Graphics::EndFrame()
  700. {
  701. if (!IsInitialized())
  702. return;
  703. {
  704. PROFILE(Present);
  705. SendEvent(E_ENDRENDERING);
  706. impl_->device_->EndScene();
  707. impl_->device_->Present(0, 0, 0, 0);
  708. }
  709. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to multiple frame buffering
  710. // If a query was issued on the previous frame, first wait for it to finish
  711. if (impl_->frameQuery_)
  712. {
  713. if (queryIssued_)
  714. {
  715. PROFILE(FlushGPU);
  716. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  717. {
  718. }
  719. queryIssued_ = false;
  720. }
  721. if (flushGPU_)
  722. {
  723. impl_->frameQuery_->Issue(D3DISSUE_END);
  724. queryIssued_ = true;
  725. }
  726. }
  727. // Clean up too large scratch buffers
  728. CleanupScratchBuffers();
  729. }
  730. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  731. {
  732. DWORD d3dFlags = 0;
  733. if (flags & CLEAR_COLOR)
  734. d3dFlags |= D3DCLEAR_TARGET;
  735. if (flags & CLEAR_DEPTH)
  736. d3dFlags |= D3DCLEAR_ZBUFFER;
  737. if (flags & CLEAR_STENCIL)
  738. d3dFlags |= D3DCLEAR_STENCIL;
  739. impl_->device_->Clear(0, 0, d3dFlags, GetD3DColor(color), depth, stencil);
  740. }
  741. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  742. {
  743. if (!destination || !destination->GetRenderSurface())
  744. return false;
  745. PROFILE(ResolveToTexture);
  746. IntRect vpCopy = viewport;
  747. if (vpCopy.right_ <= vpCopy.left_)
  748. vpCopy.right_ = vpCopy.left_ + 1;
  749. if (vpCopy.bottom_ <= vpCopy.top_)
  750. vpCopy.bottom_ = vpCopy.top_ + 1;
  751. RECT rect;
  752. rect.left = Clamp(vpCopy.left_, 0, width_);
  753. rect.top = Clamp(vpCopy.top_, 0, height_);
  754. rect.right = Clamp(vpCopy.right_, 0, width_);
  755. rect.bottom = Clamp(vpCopy.bottom_, 0, height_);
  756. RECT destRect;
  757. destRect.left = 0;
  758. destRect.top = 0;
  759. destRect.right = destination->GetWidth();
  760. destRect.bottom = destination->GetHeight();
  761. return SUCCEEDED(impl_->device_->StretchRect(impl_->defaultColorSurface_, &rect,
  762. (IDirect3DSurface9*)destination->GetRenderSurface()->GetSurface(), &destRect, D3DTEXF_NONE));
  763. }
  764. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  765. {
  766. if (!vertexCount)
  767. return;
  768. ResetStreamFrequencies();
  769. unsigned primitiveCount;
  770. D3DPRIMITIVETYPE d3dPrimitiveType;
  771. GetD3DPrimitiveType(vertexCount, type, primitiveCount, d3dPrimitiveType);
  772. impl_->device_->DrawPrimitive(d3dPrimitiveType, vertexStart, primitiveCount);
  773. numPrimitives_ += primitiveCount;
  774. ++numBatches_;
  775. }
  776. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  777. {
  778. if (!indexCount)
  779. return;
  780. ResetStreamFrequencies();
  781. unsigned primitiveCount;
  782. D3DPRIMITIVETYPE d3dPrimitiveType;
  783. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  784. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, 0, minVertex, vertexCount, indexStart, primitiveCount);
  785. numPrimitives_ += primitiveCount;
  786. ++numBatches_;
  787. }
  788. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  789. unsigned instanceCount)
  790. {
  791. if (!indexCount || !instanceCount)
  792. return;
  793. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  794. {
  795. VertexBuffer* buffer = vertexBuffers_[i];
  796. if (buffer)
  797. {
  798. if (buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  799. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1u);
  800. else
  801. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  802. }
  803. }
  804. unsigned primitiveCount;
  805. D3DPRIMITIVETYPE d3dPrimitiveType;
  806. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  807. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, 0, minVertex, vertexCount, indexStart, primitiveCount);
  808. numPrimitives_ += instanceCount * primitiveCount;
  809. ++numBatches_;
  810. }
  811. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  812. {
  813. // Note: this is not multi-instance safe
  814. static PODVector<VertexBuffer*> vertexBuffers(1);
  815. static PODVector<unsigned> elementMasks(1);
  816. vertexBuffers[0] = buffer;
  817. elementMasks[0] = MASK_DEFAULT;
  818. SetVertexBuffers(vertexBuffers, elementMasks);
  819. }
  820. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  821. unsigned instanceOffset)
  822. {
  823. if (buffers.Size() > MAX_VERTEX_STREAMS)
  824. {
  825. LOGERROR("Too many vertex buffers");
  826. return false;
  827. }
  828. if (buffers.Size() != elementMasks.Size())
  829. {
  830. LOGERROR("Amount of element masks and vertex buffers does not match");
  831. return false;
  832. }
  833. // Build vertex declaration hash code out of the buffers & masks
  834. unsigned long long hash = 0;
  835. for (unsigned i = 0; i < buffers.Size(); ++i)
  836. {
  837. if (!buffers[i])
  838. continue;
  839. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  840. }
  841. if (hash)
  842. {
  843. // If no previous vertex declaration for that hash, create new
  844. if (!vertexDeclarations_.Contains(hash))
  845. {
  846. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  847. if (!newDeclaration->GetDeclaration())
  848. {
  849. LOGERROR("Failed to create vertex declaration");
  850. return false;
  851. }
  852. vertexDeclarations_[hash] = newDeclaration;
  853. }
  854. VertexDeclaration* declaration = vertexDeclarations_[hash];
  855. if (declaration != vertexDeclaration_)
  856. {
  857. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  858. vertexDeclaration_ = declaration;
  859. }
  860. }
  861. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  862. {
  863. VertexBuffer* buffer = 0;
  864. unsigned offset = 0;
  865. if (i < buffers.Size())
  866. {
  867. buffer = buffers[i];
  868. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  869. offset = instanceOffset * buffer->GetVertexSize();
  870. }
  871. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  872. {
  873. if (buffer)
  874. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset,
  875. buffer->GetVertexSize());
  876. else
  877. impl_->device_->SetStreamSource(i, 0, 0, 0);
  878. vertexBuffers_[i] = buffer;
  879. streamOffsets_[i] = offset;
  880. }
  881. }
  882. return true;
  883. }
  884. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>& elementMasks,
  885. unsigned instanceOffset)
  886. {
  887. return SetVertexBuffers(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), elementMasks, instanceOffset);
  888. }
  889. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  890. {
  891. if (buffer != indexBuffer_)
  892. {
  893. if (buffer)
  894. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  895. else
  896. impl_->device_->SetIndices(0);
  897. indexBuffer_ = buffer;
  898. }
  899. }
  900. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  901. {
  902. if (vs == vertexShader_ && ps == pixelShader_)
  903. return;
  904. ClearParameterSources();
  905. if (vs != vertexShader_)
  906. {
  907. // Create the shader now if not yet created. If already attempted, do not retry
  908. if (vs && !vs->GetGPUObject())
  909. {
  910. if (vs->GetCompilerOutput().Empty())
  911. {
  912. PROFILE(CompileVertexShader);
  913. bool success = vs->Create();
  914. if (!success)
  915. {
  916. LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  917. vs = 0;
  918. }
  919. }
  920. else
  921. vs = 0;
  922. }
  923. if (vs && vs->GetShaderType() == VS)
  924. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  925. else
  926. {
  927. impl_->device_->SetVertexShader(0);
  928. vs = 0;
  929. }
  930. vertexShader_ = vs;
  931. }
  932. if (ps != pixelShader_)
  933. {
  934. if (ps && !ps->GetGPUObject())
  935. {
  936. if (ps->GetCompilerOutput().Empty())
  937. {
  938. PROFILE(CompilePixelShader);
  939. bool success = ps->Create();
  940. if (!success)
  941. {
  942. LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  943. ps = 0;
  944. }
  945. }
  946. else
  947. ps = 0;
  948. }
  949. if (ps && ps->GetShaderType() == PS)
  950. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  951. else
  952. {
  953. impl_->device_->SetPixelShader(0);
  954. ps = 0;
  955. }
  956. pixelShader_ = ps;
  957. }
  958. // Update current available shader parameters
  959. if (vertexShader_ && pixelShader_)
  960. {
  961. Pair<ShaderVariation*, ShaderVariation*> key = MakePair(vertexShader_, pixelShader_);
  962. ShaderProgramMap::Iterator i = shaderPrograms_.Find(key);
  963. if (i != shaderPrograms_.End())
  964. shaderProgram_ = i->second_.Get();
  965. else
  966. {
  967. ShaderProgram* newProgram = shaderPrograms_[key] = new ShaderProgram(vertexShader_, pixelShader_);
  968. shaderProgram_ = newProgram;
  969. }
  970. }
  971. else
  972. shaderProgram_ = 0;
  973. // Store shader combination if shader dumping in progress
  974. if (shaderPrecache_)
  975. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  976. }
  977. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  978. {
  979. HashMap<StringHash, ShaderParameter>::Iterator i;
  980. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  981. return;
  982. if (i->second_.type_ == VS)
  983. impl_->device_->SetVertexShaderConstantF(i->second_.register_, data, count / 4);
  984. else
  985. impl_->device_->SetPixelShaderConstantF(i->second_.register_, data, count / 4);
  986. }
  987. void Graphics::SetShaderParameter(StringHash param, float value)
  988. {
  989. HashMap<StringHash, ShaderParameter>::Iterator i;
  990. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  991. return;
  992. static Vector4 data(Vector4::ZERO);
  993. data.x_ = value;
  994. if (i->second_.type_ == VS)
  995. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  996. else
  997. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  998. }
  999. void Graphics::SetShaderParameter(StringHash param, bool value)
  1000. {
  1001. /// \todo Bool constants possibly have no effect on Direct3D9
  1002. HashMap<StringHash, ShaderParameter>::Iterator i;
  1003. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1004. return;
  1005. BOOL data = value;
  1006. if (i->second_.type_ == VS)
  1007. impl_->device_->SetVertexShaderConstantB(i->second_.register_, &data, 1);
  1008. else
  1009. impl_->device_->SetPixelShaderConstantB(i->second_.register_, &data, 1);
  1010. }
  1011. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  1012. {
  1013. HashMap<StringHash, ShaderParameter>::Iterator i;
  1014. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1015. return;
  1016. if (i->second_.type_ == VS)
  1017. impl_->device_->SetVertexShaderConstantF(i->second_.register_, color.Data(), 1);
  1018. else
  1019. impl_->device_->SetPixelShaderConstantF(i->second_.register_, color.Data(), 1);
  1020. }
  1021. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  1022. {
  1023. HashMap<StringHash, ShaderParameter>::Iterator i;
  1024. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1025. return;
  1026. static Vector4 data(Vector4::ZERO);
  1027. data.x_ = vector.x_;
  1028. data.y_ = vector.y_;
  1029. if (i->second_.type_ == VS)
  1030. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  1031. else
  1032. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  1033. }
  1034. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1035. {
  1036. HashMap<StringHash, ShaderParameter>::Iterator i;
  1037. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1038. return;
  1039. static Matrix3x4 data(Matrix3x4::ZERO);
  1040. data.m00_ = matrix.m00_;
  1041. data.m01_ = matrix.m01_;
  1042. data.m02_ = matrix.m02_;
  1043. data.m10_ = matrix.m10_;
  1044. data.m11_ = matrix.m11_;
  1045. data.m12_ = matrix.m12_;
  1046. data.m20_ = matrix.m20_;
  1047. data.m21_ = matrix.m21_;
  1048. data.m22_ = matrix.m22_;
  1049. if (i->second_.type_ == VS)
  1050. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.m00_, 3);
  1051. else
  1052. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.m00_, 3);
  1053. }
  1054. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1055. {
  1056. HashMap<StringHash, ShaderParameter>::Iterator i;
  1057. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1058. return;
  1059. static Vector4 data(Vector4::ZERO);
  1060. data.x_ = vector.x_;
  1061. data.y_ = vector.y_;
  1062. data.z_ = vector.z_;
  1063. if (i->second_.type_ == VS)
  1064. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  1065. else
  1066. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  1067. }
  1068. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1069. {
  1070. HashMap<StringHash, ShaderParameter>::Iterator i;
  1071. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1072. return;
  1073. if (i->second_.type_ == VS)
  1074. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1075. else
  1076. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1077. }
  1078. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1079. {
  1080. HashMap<StringHash, ShaderParameter>::Iterator i;
  1081. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1082. return;
  1083. if (i->second_.type_ == VS)
  1084. impl_->device_->SetVertexShaderConstantF(i->second_.register_, vector.Data(), 1);
  1085. else
  1086. impl_->device_->SetPixelShaderConstantF(i->second_.register_, vector.Data(), 1);
  1087. }
  1088. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1089. {
  1090. HashMap<StringHash, ShaderParameter>::Iterator i;
  1091. if (!shaderProgram_ || (i = shaderProgram_->parameters_.Find(param)) == shaderProgram_->parameters_.End())
  1092. return;
  1093. if (i->second_.type_ == VS)
  1094. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1095. else
  1096. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1097. }
  1098. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1099. {
  1100. switch (value.GetType())
  1101. {
  1102. case VAR_BOOL:
  1103. SetShaderParameter(param, value.GetBool());
  1104. break;
  1105. case VAR_FLOAT:
  1106. SetShaderParameter(param, value.GetFloat());
  1107. break;
  1108. case VAR_VECTOR2:
  1109. SetShaderParameter(param, value.GetVector2());
  1110. break;
  1111. case VAR_VECTOR3:
  1112. SetShaderParameter(param, value.GetVector3());
  1113. break;
  1114. case VAR_VECTOR4:
  1115. SetShaderParameter(param, value.GetVector4());
  1116. break;
  1117. case VAR_COLOR:
  1118. SetShaderParameter(param, value.GetColor());
  1119. break;
  1120. case VAR_MATRIX3:
  1121. SetShaderParameter(param, value.GetMatrix3());
  1122. break;
  1123. case VAR_MATRIX3X4:
  1124. SetShaderParameter(param, value.GetMatrix3x4());
  1125. break;
  1126. case VAR_MATRIX4:
  1127. SetShaderParameter(param, value.GetMatrix4());
  1128. break;
  1129. default:
  1130. // Unsupported parameter type, do nothing
  1131. break;
  1132. }
  1133. }
  1134. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1135. {
  1136. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1137. {
  1138. shaderParameterSources_[group] = source;
  1139. return true;
  1140. }
  1141. else
  1142. return false;
  1143. }
  1144. bool Graphics::HasShaderParameter(StringHash param)
  1145. {
  1146. return shaderProgram_ && shaderProgram_->parameters_.Find(param) != shaderProgram_->parameters_.End();
  1147. }
  1148. bool Graphics::HasTextureUnit(TextureUnit unit)
  1149. {
  1150. return pixelShader_ && pixelShader_->HasTextureUnit(unit);
  1151. }
  1152. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1153. {
  1154. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1155. }
  1156. void Graphics::ClearParameterSources()
  1157. {
  1158. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1159. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1160. }
  1161. void Graphics::ClearTransformSources()
  1162. {
  1163. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1164. shaderParameterSources_[SP_OBJECT] = (const void*)M_MAX_UNSIGNED;
  1165. }
  1166. void Graphics::SetTexture(unsigned index, Texture* texture)
  1167. {
  1168. if (index >= MAX_TEXTURE_UNITS)
  1169. return;
  1170. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1171. if (texture)
  1172. {
  1173. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1174. texture = texture->GetBackupTexture();
  1175. }
  1176. if (texture != textures_[index])
  1177. {
  1178. if (texture)
  1179. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1180. else
  1181. impl_->device_->SetTexture(index, 0);
  1182. textures_[index] = texture;
  1183. }
  1184. if (texture)
  1185. {
  1186. TextureFilterMode filterMode = texture->GetFilterMode();
  1187. if (filterMode == FILTER_DEFAULT)
  1188. filterMode = defaultTextureFilterMode_;
  1189. D3DTEXTUREFILTERTYPE minMag, mip;
  1190. minMag = d3dMinMagFilter[filterMode];
  1191. if (minMag != impl_->minMagFilters_[index])
  1192. {
  1193. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1194. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1195. impl_->minMagFilters_[index] = minMag;
  1196. }
  1197. mip = d3dMipFilter[filterMode];
  1198. if (mip != impl_->mipFilters_[index])
  1199. {
  1200. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1201. impl_->mipFilters_[index] = mip;
  1202. }
  1203. D3DTEXTUREADDRESS u, v;
  1204. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1205. if (u != impl_->uAddressModes_[index])
  1206. {
  1207. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1208. impl_->uAddressModes_[index] = u;
  1209. }
  1210. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1211. if (v != impl_->vAddressModes_[index])
  1212. {
  1213. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1214. impl_->vAddressModes_[index] = v;
  1215. }
  1216. if (texture->GetType() == TextureCube::GetTypeStatic())
  1217. {
  1218. D3DTEXTUREADDRESS w = d3dAddressMode[texture->GetAddressMode(COORD_W)];
  1219. if (w != impl_->wAddressModes_[index])
  1220. {
  1221. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSW, w);
  1222. impl_->wAddressModes_[index] = w;
  1223. }
  1224. }
  1225. if (u == D3DTADDRESS_BORDER || v == D3DTADDRESS_BORDER)
  1226. {
  1227. const Color& borderColor = texture->GetBorderColor();
  1228. if (borderColor != impl_->borderColors_[index])
  1229. {
  1230. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, GetD3DColor(borderColor));
  1231. impl_->borderColors_[index] = borderColor;
  1232. }
  1233. }
  1234. if (sRGBSupport_)
  1235. {
  1236. bool sRGB = texture->GetSRGB();
  1237. if (sRGB != impl_->sRGBModes_[index])
  1238. {
  1239. impl_->device_->SetSamplerState(index, D3DSAMP_SRGBTEXTURE, sRGB ? TRUE : FALSE);
  1240. impl_->sRGBModes_[index] = sRGB;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1246. {
  1247. defaultTextureFilterMode_ = mode;
  1248. }
  1249. void Graphics::ResetRenderTargets()
  1250. {
  1251. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1252. SetRenderTarget(i, (RenderSurface*)0);
  1253. SetDepthStencil((RenderSurface*)0);
  1254. SetViewport(IntRect(0, 0, width_, height_));
  1255. }
  1256. void Graphics::ResetRenderTarget(unsigned index)
  1257. {
  1258. SetRenderTarget(index, (RenderSurface*)0);
  1259. }
  1260. void Graphics::ResetDepthStencil()
  1261. {
  1262. SetDepthStencil((RenderSurface*)0);
  1263. }
  1264. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1265. {
  1266. if (index >= MAX_RENDERTARGETS)
  1267. return;
  1268. IDirect3DSurface9* newColorSurface = 0;
  1269. if (renderTarget)
  1270. {
  1271. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1272. return;
  1273. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1274. }
  1275. else
  1276. {
  1277. if (!index)
  1278. newColorSurface = impl_->defaultColorSurface_;
  1279. }
  1280. renderTargets_[index] = renderTarget;
  1281. if (newColorSurface != impl_->colorSurfaces_[index])
  1282. {
  1283. impl_->device_->SetRenderTarget(index, newColorSurface);
  1284. impl_->colorSurfaces_[index] = newColorSurface;
  1285. // Setting the first rendertarget causes viewport to be reset
  1286. if (!index)
  1287. {
  1288. IntVector2 rtSize = GetRenderTargetDimensions();
  1289. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1290. }
  1291. }
  1292. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1293. if (renderTarget)
  1294. {
  1295. Texture* parentTexture = renderTarget->GetParentTexture();
  1296. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1297. {
  1298. if (textures_[i] == parentTexture)
  1299. SetTexture(i, textures_[i]->GetBackupTexture());
  1300. }
  1301. }
  1302. // First rendertarget controls sRGB write mode
  1303. if (!index && sRGBWriteSupport_)
  1304. {
  1305. bool sRGBWrite = renderTarget ? renderTarget->GetParentTexture()->GetSRGB() : sRGB_;
  1306. if (sRGBWrite != impl_->sRGBWrite_)
  1307. {
  1308. impl_->device_->SetRenderState(D3DRS_SRGBWRITEENABLE, sRGBWrite ? TRUE : FALSE);
  1309. impl_->sRGBWrite_ = sRGBWrite;
  1310. }
  1311. }
  1312. }
  1313. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1314. {
  1315. RenderSurface* renderTarget = 0;
  1316. if (texture)
  1317. renderTarget = texture->GetRenderSurface();
  1318. SetRenderTarget(index, renderTarget);
  1319. }
  1320. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1321. {
  1322. IDirect3DSurface9* newDepthStencilSurface = 0;
  1323. if (depthStencil && depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL)
  1324. {
  1325. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1326. depthStencil_ = depthStencil;
  1327. }
  1328. if (!newDepthStencilSurface)
  1329. {
  1330. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1331. depthStencil_ = 0;
  1332. }
  1333. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1334. {
  1335. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1336. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1337. }
  1338. }
  1339. void Graphics::SetDepthStencil(Texture2D* texture)
  1340. {
  1341. RenderSurface* depthStencil = 0;
  1342. if (texture)
  1343. depthStencil = texture->GetRenderSurface();
  1344. SetDepthStencil(depthStencil);
  1345. }
  1346. void Graphics::SetViewport(const IntRect& rect)
  1347. {
  1348. IntVector2 size = GetRenderTargetDimensions();
  1349. IntRect rectCopy = rect;
  1350. if (rectCopy.right_ <= rectCopy.left_)
  1351. rectCopy.right_ = rectCopy.left_ + 1;
  1352. if (rectCopy.bottom_ <= rectCopy.top_)
  1353. rectCopy.bottom_ = rectCopy.top_ + 1;
  1354. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1355. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1356. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1357. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1358. D3DVIEWPORT9 vp;
  1359. vp.MinZ = 0.0f;
  1360. vp.MaxZ = 1.0f;
  1361. vp.X = (DWORD)rectCopy.left_;
  1362. vp.Y = (DWORD)rectCopy.top_;
  1363. vp.Width = (DWORD)rectCopy.Width();
  1364. vp.Height = (DWORD)rectCopy.Height();
  1365. impl_->device_->SetViewport(&vp);
  1366. viewport_ = rectCopy;
  1367. // Disable scissor test, needs to be re-enabled by the user
  1368. SetScissorTest(false);
  1369. }
  1370. void Graphics::SetTextureAnisotropy(unsigned level)
  1371. {
  1372. if (level < 1)
  1373. level = 1;
  1374. if (level != textureAnisotropy_)
  1375. {
  1376. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1377. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1378. textureAnisotropy_ = level;
  1379. }
  1380. }
  1381. void Graphics::SetBlendMode(BlendMode mode)
  1382. {
  1383. if (mode != blendMode_)
  1384. {
  1385. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1386. {
  1387. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1388. impl_->blendEnable_ = d3dBlendEnable[mode];
  1389. }
  1390. if (impl_->blendEnable_)
  1391. {
  1392. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1393. {
  1394. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1395. impl_->srcBlend_ = d3dSrcBlend[mode];
  1396. }
  1397. if (d3dDestBlend[mode] != impl_->destBlend_)
  1398. {
  1399. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1400. impl_->destBlend_ = d3dDestBlend[mode];
  1401. }
  1402. if (d3dBlendOp[mode] != impl_->blendOp_)
  1403. {
  1404. impl_->device_->SetRenderState(D3DRS_BLENDOP, d3dBlendOp[mode]);
  1405. impl_->blendOp_ = d3dBlendOp[mode];
  1406. }
  1407. }
  1408. blendMode_ = mode;
  1409. }
  1410. }
  1411. void Graphics::SetColorWrite(bool enable)
  1412. {
  1413. if (enable != colorWrite_)
  1414. {
  1415. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE,
  1416. enable ? D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA :
  1417. 0);
  1418. colorWrite_ = enable;
  1419. }
  1420. }
  1421. void Graphics::SetCullMode(CullMode mode)
  1422. {
  1423. if (mode != cullMode_)
  1424. {
  1425. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1426. cullMode_ = mode;
  1427. }
  1428. }
  1429. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1430. {
  1431. if (constantBias != constantDepthBias_)
  1432. {
  1433. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1434. constantDepthBias_ = constantBias;
  1435. }
  1436. if (slopeScaledBias != slopeScaledDepthBias_)
  1437. {
  1438. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1439. slopeScaledDepthBias_ = slopeScaledBias;
  1440. }
  1441. }
  1442. void Graphics::SetDepthTest(CompareMode mode)
  1443. {
  1444. if (mode != depthTestMode_)
  1445. {
  1446. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1447. depthTestMode_ = mode;
  1448. }
  1449. }
  1450. void Graphics::SetDepthWrite(bool enable)
  1451. {
  1452. if (enable != depthWrite_)
  1453. {
  1454. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1455. depthWrite_ = enable;
  1456. }
  1457. }
  1458. void Graphics::SetFillMode(FillMode mode)
  1459. {
  1460. if (mode != fillMode_)
  1461. {
  1462. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1463. fillMode_ = mode;
  1464. }
  1465. }
  1466. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1467. {
  1468. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1469. // Disable scissor in that case to reduce state changes
  1470. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1471. enable = false;
  1472. if (enable)
  1473. {
  1474. IntVector2 rtSize(GetRenderTargetDimensions());
  1475. IntVector2 viewSize(viewport_.Size());
  1476. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1477. IntRect intRect;
  1478. int expand = borderInclusive ? 1 : 0;
  1479. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1480. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1481. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1482. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1483. if (intRect.right_ == intRect.left_)
  1484. intRect.right_++;
  1485. if (intRect.bottom_ == intRect.top_)
  1486. intRect.bottom_++;
  1487. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1488. enable = false;
  1489. if (enable && scissorRect_ != intRect)
  1490. {
  1491. RECT d3dRect;
  1492. d3dRect.left = intRect.left_;
  1493. d3dRect.top = intRect.top_;
  1494. d3dRect.right = intRect.right_;
  1495. d3dRect.bottom = intRect.bottom_;
  1496. impl_->device_->SetScissorRect(&d3dRect);
  1497. scissorRect_ = intRect;
  1498. }
  1499. }
  1500. else
  1501. scissorRect_ = IntRect::ZERO;
  1502. if (enable != scissorTest_)
  1503. {
  1504. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1505. scissorTest_ = enable;
  1506. }
  1507. }
  1508. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1509. {
  1510. IntVector2 rtSize(GetRenderTargetDimensions());
  1511. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1512. if (enable)
  1513. {
  1514. IntRect intRect;
  1515. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1516. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1517. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1518. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1519. if (intRect.right_ == intRect.left_)
  1520. intRect.right_++;
  1521. if (intRect.bottom_ == intRect.top_)
  1522. intRect.bottom_++;
  1523. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1524. enable = false;
  1525. if (enable && scissorRect_ != intRect)
  1526. {
  1527. RECT d3dRect;
  1528. d3dRect.left = intRect.left_;
  1529. d3dRect.top = intRect.top_;
  1530. d3dRect.right = intRect.right_;
  1531. d3dRect.bottom = intRect.bottom_;
  1532. impl_->device_->SetScissorRect(&d3dRect);
  1533. scissorRect_ = intRect;
  1534. }
  1535. }
  1536. else
  1537. scissorRect_ = IntRect::ZERO;
  1538. if (enable != scissorTest_)
  1539. {
  1540. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1541. scissorTest_ = enable;
  1542. }
  1543. }
  1544. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1545. unsigned compareMask, unsigned writeMask)
  1546. {
  1547. if (enable != stencilTest_)
  1548. {
  1549. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1550. stencilTest_ = enable;
  1551. }
  1552. if (enable)
  1553. {
  1554. if (mode != stencilTestMode_)
  1555. {
  1556. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1557. stencilTestMode_ = mode;
  1558. }
  1559. if (pass != stencilPass_)
  1560. {
  1561. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1562. stencilPass_ = pass;
  1563. }
  1564. if (fail != stencilFail_)
  1565. {
  1566. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1567. stencilFail_ = fail;
  1568. }
  1569. if (zFail != stencilZFail_)
  1570. {
  1571. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1572. stencilZFail_ = zFail;
  1573. }
  1574. if (stencilRef != stencilRef_)
  1575. {
  1576. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1577. stencilRef_ = stencilRef;
  1578. }
  1579. if (compareMask != stencilCompareMask_)
  1580. {
  1581. impl_->device_->SetRenderState(D3DRS_STENCILMASK, compareMask);
  1582. stencilCompareMask_ = compareMask;
  1583. }
  1584. if (writeMask != stencilWriteMask_)
  1585. {
  1586. impl_->device_->SetRenderState(D3DRS_STENCILWRITEMASK, writeMask);
  1587. stencilWriteMask_ = writeMask;
  1588. }
  1589. }
  1590. }
  1591. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1592. {
  1593. if (enable != useClipPlane_)
  1594. {
  1595. impl_->device_->SetRenderState(D3DRS_CLIPPLANEENABLE, enable ? 1 : 0);
  1596. useClipPlane_ = enable;
  1597. }
  1598. if (enable)
  1599. {
  1600. Matrix4 viewProj = projection * view;
  1601. impl_->device_->SetClipPlane(0, clipPlane.Transformed(viewProj).ToVector4().Data());
  1602. }
  1603. }
  1604. void Graphics::BeginDumpShaders(const String& fileName)
  1605. {
  1606. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1607. }
  1608. void Graphics::EndDumpShaders()
  1609. {
  1610. shaderPrecache_.Reset();
  1611. }
  1612. void Graphics::PrecacheShaders(Deserializer& source)
  1613. {
  1614. PROFILE(PrecacheShaders);
  1615. ShaderPrecache::LoadShaders(this, source);
  1616. }
  1617. bool Graphics::IsInitialized() const
  1618. {
  1619. return impl_->window_ != 0 && impl_->GetDevice() != 0;
  1620. }
  1621. IntVector2 Graphics::GetWindowPosition() const
  1622. {
  1623. if (impl_->window_)
  1624. return position_;
  1625. return IntVector2::ZERO;
  1626. }
  1627. PODVector<IntVector2> Graphics::GetResolutions() const
  1628. {
  1629. PODVector<IntVector2> ret;
  1630. unsigned numModes = (unsigned)SDL_GetNumDisplayModes(0);
  1631. for (unsigned i = 0; i < numModes; ++i)
  1632. {
  1633. SDL_DisplayMode mode;
  1634. SDL_GetDisplayMode(0, i, &mode);
  1635. int width = mode.w;
  1636. int height = mode.h;
  1637. // Store mode if unique
  1638. bool unique = true;
  1639. for (unsigned j = 0; j < ret.Size(); ++j)
  1640. {
  1641. if (ret[j].x_ == width && ret[j].y_ == height)
  1642. {
  1643. unique = false;
  1644. break;
  1645. }
  1646. }
  1647. if (unique)
  1648. ret.Push(IntVector2(width, height));
  1649. }
  1650. return ret;
  1651. }
  1652. PODVector<int> Graphics::GetMultiSampleLevels() const
  1653. {
  1654. PODVector<int> ret;
  1655. // No multisampling always supported
  1656. ret.Push(1);
  1657. if (!impl_->interface_)
  1658. return ret;
  1659. SDL_DisplayMode mode;
  1660. SDL_GetDesktopDisplayMode(0, &mode);
  1661. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  1662. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1663. {
  1664. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  1665. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1666. ret.Push(i);
  1667. }
  1668. return ret;
  1669. }
  1670. IntVector2 Graphics::GetDesktopResolution() const
  1671. {
  1672. SDL_DisplayMode mode;
  1673. SDL_GetDesktopDisplayMode(0, &mode);
  1674. return IntVector2(mode.w, mode.h);
  1675. }
  1676. unsigned Graphics::GetFormat(CompressedFormat format) const
  1677. {
  1678. switch (format)
  1679. {
  1680. case CF_RGBA:
  1681. return D3DFMT_A8R8G8B8;
  1682. case CF_DXT1:
  1683. return D3DFMT_DXT1;
  1684. case CF_DXT3:
  1685. return D3DFMT_DXT3;
  1686. case CF_DXT5:
  1687. return D3DFMT_DXT5;
  1688. default:
  1689. return 0;
  1690. }
  1691. }
  1692. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1693. {
  1694. return GetShader(type, name.CString(), defines.CString());
  1695. }
  1696. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1697. {
  1698. if (lastShaderName_ != name || !lastShader_)
  1699. {
  1700. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1701. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1702. // Try to reduce repeated error log prints because of missing shaders
  1703. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1704. return 0;
  1705. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1706. lastShaderName_ = name;
  1707. }
  1708. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1709. }
  1710. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1711. {
  1712. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1713. }
  1714. TextureUnit Graphics::GetTextureUnit(const String& name)
  1715. {
  1716. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1717. if (i != textureUnits_.End())
  1718. return i->second_;
  1719. else
  1720. return MAX_TEXTURE_UNITS;
  1721. }
  1722. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1723. {
  1724. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1725. {
  1726. if (i->second_ == unit)
  1727. return i->first_;
  1728. }
  1729. return String::EMPTY;
  1730. }
  1731. Texture* Graphics::GetTexture(unsigned index) const
  1732. {
  1733. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1734. }
  1735. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1736. {
  1737. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1738. }
  1739. IntVector2 Graphics::GetRenderTargetDimensions() const
  1740. {
  1741. int width, height;
  1742. if (renderTargets_[0])
  1743. {
  1744. width = renderTargets_[0]->GetWidth();
  1745. height = renderTargets_[0]->GetHeight();
  1746. }
  1747. else
  1748. {
  1749. width = width_;
  1750. height = height_;
  1751. }
  1752. return IntVector2(width, height);
  1753. }
  1754. void Graphics::WindowResized()
  1755. {
  1756. if (!impl_->device_ || !impl_->window_)
  1757. return;
  1758. int newWidth, newHeight;
  1759. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1760. if (newWidth == width_ && newHeight == height_)
  1761. return;
  1762. width_ = newWidth;
  1763. height_ = newHeight;
  1764. impl_->presentParams_.BackBufferWidth = (UINT)width_;
  1765. impl_->presentParams_.BackBufferHeight = (UINT)height_;
  1766. ResetDevice();
  1767. // Reset rendertargets and viewport for the new screen size
  1768. ResetRenderTargets();
  1769. LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1770. using namespace ScreenMode;
  1771. VariantMap& eventData = GetEventDataMap();
  1772. eventData[P_WIDTH] = width_;
  1773. eventData[P_HEIGHT] = height_;
  1774. eventData[P_FULLSCREEN] = fullscreen_;
  1775. eventData[P_RESIZABLE] = resizable_;
  1776. eventData[P_BORDERLESS] = borderless_;
  1777. SendEvent(E_SCREENMODE, eventData);
  1778. }
  1779. void Graphics::WindowMoved()
  1780. {
  1781. if (!impl_->device_ || !impl_->window_ || fullscreen_)
  1782. return;
  1783. int newX, newY;
  1784. SDL_GetWindowPosition(impl_->window_, &newX, &newY);
  1785. if (newX == position_.x_ && newY == position_.y_)
  1786. return;
  1787. position_.x_ = newX;
  1788. position_.y_ = newY;
  1789. LOGDEBUGF("Window was moved to %d,%d", position_.x_, position_.y_);
  1790. using namespace WindowPos;
  1791. VariantMap& eventData = GetEventDataMap();
  1792. eventData[P_X] = position_.x_;
  1793. eventData[P_Y] = position_.y_;
  1794. SendEvent(E_WINDOWPOS, eventData);
  1795. }
  1796. void Graphics::Maximize()
  1797. {
  1798. if (!impl_->window_)
  1799. return;
  1800. SDL_MaximizeWindow(impl_->window_);
  1801. }
  1802. void Graphics::Minimize()
  1803. {
  1804. if (!impl_->window_)
  1805. return;
  1806. SDL_MinimizeWindow(impl_->window_);
  1807. }
  1808. void Graphics::AddGPUObject(GPUObject* object)
  1809. {
  1810. MutexLock lock(gpuObjectMutex_);
  1811. gpuObjects_.Push(object);
  1812. }
  1813. void Graphics::RemoveGPUObject(GPUObject* object)
  1814. {
  1815. MutexLock lock(gpuObjectMutex_);
  1816. gpuObjects_.Remove(object);
  1817. }
  1818. void* Graphics::ReserveScratchBuffer(unsigned size)
  1819. {
  1820. if (!size)
  1821. return 0;
  1822. if (size > maxScratchBufferRequest_)
  1823. maxScratchBufferRequest_ = size;
  1824. // First check for a free buffer that is large enough
  1825. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1826. {
  1827. if (!i->reserved_ && i->size_ >= size)
  1828. {
  1829. i->reserved_ = true;
  1830. return i->data_.Get();
  1831. }
  1832. }
  1833. // Then check if a free buffer can be resized
  1834. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1835. {
  1836. if (!i->reserved_)
  1837. {
  1838. i->data_ = new unsigned char[size];
  1839. i->size_ = size;
  1840. i->reserved_ = true;
  1841. LOGDEBUG("Resized scratch buffer to size " + String(size));
  1842. return i->data_.Get();
  1843. }
  1844. }
  1845. // Finally allocate a new buffer
  1846. ScratchBuffer newBuffer;
  1847. newBuffer.data_ = new unsigned char[size];
  1848. newBuffer.size_ = size;
  1849. newBuffer.reserved_ = true;
  1850. scratchBuffers_.Push(newBuffer);
  1851. return newBuffer.data_.Get();
  1852. LOGDEBUG("Allocated scratch buffer with size " + String(size));
  1853. }
  1854. void Graphics::FreeScratchBuffer(void* buffer)
  1855. {
  1856. if (!buffer)
  1857. return;
  1858. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1859. {
  1860. if (i->reserved_ && i->data_.Get() == buffer)
  1861. {
  1862. i->reserved_ = false;
  1863. return;
  1864. }
  1865. }
  1866. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1867. }
  1868. void Graphics::CleanupScratchBuffers()
  1869. {
  1870. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1871. {
  1872. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1873. {
  1874. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1875. i->size_ = maxScratchBufferRequest_;
  1876. LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
  1877. }
  1878. }
  1879. maxScratchBufferRequest_ = 0;
  1880. }
  1881. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  1882. {
  1883. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  1884. {
  1885. if (i->first_.first_ == variation || i->first_.second_ == variation)
  1886. i = shaderPrograms_.Erase(i);
  1887. else
  1888. ++i;
  1889. }
  1890. if (vertexShader_ == variation || pixelShader_ == variation)
  1891. shaderProgram_ = 0;
  1892. }
  1893. unsigned Graphics::GetAlphaFormat()
  1894. {
  1895. return D3DFMT_A8;
  1896. }
  1897. unsigned Graphics::GetLuminanceFormat()
  1898. {
  1899. return D3DFMT_L8;
  1900. }
  1901. unsigned Graphics::GetLuminanceAlphaFormat()
  1902. {
  1903. return D3DFMT_A8L8;
  1904. }
  1905. unsigned Graphics::GetRGBFormat()
  1906. {
  1907. return D3DFMT_X8R8G8B8;
  1908. }
  1909. unsigned Graphics::GetRGBAFormat()
  1910. {
  1911. return D3DFMT_A8R8G8B8;
  1912. }
  1913. unsigned Graphics::GetRGBA16Format()
  1914. {
  1915. return D3DFMT_A16B16G16R16;
  1916. }
  1917. unsigned Graphics::GetRGBAFloat16Format()
  1918. {
  1919. return D3DFMT_A16B16G16R16F;
  1920. }
  1921. unsigned Graphics::GetRGBAFloat32Format()
  1922. {
  1923. return D3DFMT_A32B32G32R32F;
  1924. }
  1925. unsigned Graphics::GetRG16Format()
  1926. {
  1927. return D3DFMT_G16R16;
  1928. }
  1929. unsigned Graphics::GetRGFloat16Format()
  1930. {
  1931. return D3DFMT_G16R16F;
  1932. }
  1933. unsigned Graphics::GetRGFloat32Format()
  1934. {
  1935. return D3DFMT_G32R32F;
  1936. }
  1937. unsigned Graphics::GetFloat16Format()
  1938. {
  1939. return D3DFMT_R16F;
  1940. }
  1941. unsigned Graphics::GetFloat32Format()
  1942. {
  1943. return D3DFMT_R32F;
  1944. }
  1945. unsigned Graphics::GetLinearDepthFormat()
  1946. {
  1947. return D3DFMT_R32F;
  1948. }
  1949. unsigned Graphics::GetDepthStencilFormat()
  1950. {
  1951. return D3DFMT_D24S8;
  1952. }
  1953. unsigned Graphics::GetReadableDepthFormat()
  1954. {
  1955. return readableDepthFormat;
  1956. }
  1957. unsigned Graphics::GetFormat(const String& formatName)
  1958. {
  1959. String nameLower = formatName.ToLower().Trimmed();
  1960. if (nameLower == "a")
  1961. return GetAlphaFormat();
  1962. if (nameLower == "l")
  1963. return GetLuminanceFormat();
  1964. if (nameLower == "la")
  1965. return GetLuminanceAlphaFormat();
  1966. if (nameLower == "rgb")
  1967. return GetRGBFormat();
  1968. if (nameLower == "rgba")
  1969. return GetRGBAFormat();
  1970. if (nameLower == "rgba16")
  1971. return GetRGBA16Format();
  1972. if (nameLower == "rgba16f")
  1973. return GetRGBAFloat16Format();
  1974. if (nameLower == "rgba32f")
  1975. return GetRGBAFloat32Format();
  1976. if (nameLower == "rg16")
  1977. return GetRG16Format();
  1978. if (nameLower == "rg16f")
  1979. return GetRGFloat16Format();
  1980. if (nameLower == "rg32f")
  1981. return GetRGFloat32Format();
  1982. if (nameLower == "r16f")
  1983. return GetFloat16Format();
  1984. if (nameLower == "r32f" || nameLower == "float")
  1985. return GetFloat32Format();
  1986. if (nameLower == "lineardepth" || nameLower == "depth")
  1987. return GetLinearDepthFormat();
  1988. if (nameLower == "d24s8")
  1989. return GetDepthStencilFormat();
  1990. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  1991. return GetReadableDepthFormat();
  1992. return GetRGBFormat();
  1993. }
  1994. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1995. {
  1996. if (index < MAX_VERTEX_STREAMS && streamFrequencies_[index] != frequency)
  1997. {
  1998. impl_->device_->SetStreamSourceFreq(index, frequency);
  1999. streamFrequencies_[index] = frequency;
  2000. }
  2001. }
  2002. void Graphics::ResetStreamFrequencies()
  2003. {
  2004. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2005. {
  2006. if (streamFrequencies_[i] != 1)
  2007. {
  2008. impl_->device_->SetStreamSourceFreq(i, 1);
  2009. streamFrequencies_[i] = 1;
  2010. }
  2011. }
  2012. }
  2013. bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
  2014. {
  2015. if (!externalWindow_)
  2016. {
  2017. unsigned flags = 0;
  2018. if (resizable)
  2019. flags |= SDL_WINDOW_RESIZABLE;
  2020. if (borderless)
  2021. flags |= SDL_WINDOW_BORDERLESS;
  2022. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), position_.x_, position_.y_, width, height, flags);
  2023. }
  2024. else
  2025. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  2026. if (!impl_->window_)
  2027. {
  2028. LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  2029. return false;
  2030. }
  2031. SDL_GetWindowPosition(impl_->window_, &position_.x_, &position_.y_);
  2032. CreateWindowIcon();
  2033. return true;
  2034. }
  2035. void Graphics::CreateWindowIcon()
  2036. {
  2037. if (windowIcon_)
  2038. {
  2039. SDL_Surface* surface = windowIcon_->GetSDLSurface();
  2040. if (surface)
  2041. {
  2042. SDL_SetWindowIcon(impl_->window_, surface);
  2043. SDL_FreeSurface(surface);
  2044. }
  2045. }
  2046. }
  2047. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless)
  2048. {
  2049. if (!externalWindow_)
  2050. {
  2051. if (!newWidth || !newHeight)
  2052. {
  2053. SDL_MaximizeWindow(impl_->window_);
  2054. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  2055. }
  2056. else
  2057. SDL_SetWindowSize(impl_->window_, newWidth, newHeight);
  2058. SDL_SetWindowFullscreen(impl_->window_, newFullscreen ? SDL_TRUE : SDL_FALSE);
  2059. SDL_SetWindowBordered(impl_->window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  2060. }
  2061. else
  2062. {
  2063. // If external window, must ask its dimensions instead of trying to set them
  2064. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  2065. newFullscreen = false;
  2066. }
  2067. }
  2068. bool Graphics::CreateInterface()
  2069. {
  2070. impl_->interface_ = Direct3DCreate9(D3D_SDK_VERSION);
  2071. if (!impl_->interface_)
  2072. {
  2073. LOGERROR("Could not create Direct3D9 interface");
  2074. return false;
  2075. }
  2076. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  2077. {
  2078. LOGERROR("Could not get Direct3D capabilities");
  2079. return false;
  2080. }
  2081. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  2082. {
  2083. LOGERROR("Could not get Direct3D adapter identifier");
  2084. return false;
  2085. }
  2086. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(3, 0))
  2087. {
  2088. LOGERROR("Shader model 3.0 display adapter is required");
  2089. return false;
  2090. }
  2091. return true;
  2092. }
  2093. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  2094. {
  2095. #ifdef ATOMIC_LUAJIT
  2096. DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
  2097. #else
  2098. DWORD behaviorFlags = 0;
  2099. #endif
  2100. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  2101. {
  2102. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  2103. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  2104. behaviorFlags |= D3DCREATE_PUREDEVICE;
  2105. }
  2106. else
  2107. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  2108. if (FAILED(impl_->interface_->CreateDevice(
  2109. adapter,
  2110. (D3DDEVTYPE)deviceType,
  2111. GetWindowHandle(impl_->window_),
  2112. behaviorFlags,
  2113. &impl_->presentParams_,
  2114. &impl_->device_)))
  2115. {
  2116. LOGERROR("Could not create Direct3D9 device");
  2117. return false;
  2118. }
  2119. impl_->adapter_ = adapter;
  2120. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  2121. OnDeviceReset();
  2122. LOGINFO("Created Direct3D9 device");
  2123. return true;
  2124. }
  2125. void Graphics::CheckFeatureSupport()
  2126. {
  2127. // Reset features first
  2128. lightPrepassSupport_ = false;
  2129. deferredSupport_ = false;
  2130. hardwareShadowSupport_ = false;
  2131. instancingSupport_ = false;
  2132. readableDepthFormat = 0;
  2133. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  2134. shadowMapFormat_ = D3DFMT_D16;
  2135. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2136. {
  2137. hardwareShadowSupport_ = true;
  2138. // Check for hires depth support
  2139. hiresShadowMapFormat_ = D3DFMT_D24X8;
  2140. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2141. hiresShadowMapFormat_ = 0;
  2142. }
  2143. else
  2144. {
  2145. // ATI DF16 format needs manual depth compare in the shader
  2146. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  2147. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2148. {
  2149. // Check for hires depth support
  2150. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  2151. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2152. hiresShadowMapFormat_ = 0;
  2153. }
  2154. else
  2155. {
  2156. // No shadow map support
  2157. shadowMapFormat_ = 0;
  2158. hiresShadowMapFormat_ = 0;
  2159. }
  2160. }
  2161. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  2162. if (shadowMapFormat_ == D3DFMT_D16)
  2163. {
  2164. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  2165. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  2166. hardwareShadowSupport_ = false;
  2167. }
  2168. // Check for readable depth (INTZ hack)
  2169. D3DFORMAT intZFormat = (D3DFORMAT)MAKEFOURCC('I', 'N', 'T', 'Z');
  2170. if (impl_->CheckFormatSupport(intZFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2171. readableDepthFormat = intZFormat;
  2172. // Check for dummy color rendertarget format used with hardware shadow maps
  2173. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  2174. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  2175. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2176. dummyColorFormat_ = nullFormat;
  2177. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2178. dummyColorFormat_ = D3DFMT_R16F;
  2179. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2180. dummyColorFormat_ = D3DFMT_R5G6B5;
  2181. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2182. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  2183. // Check for light prepass and deferred rendering support
  2184. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  2185. D3DRTYPE_TEXTURE))
  2186. {
  2187. lightPrepassSupport_ = true;
  2188. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  2189. deferredSupport_ = true;
  2190. }
  2191. // Check for stream offset (needed for instancing)
  2192. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  2193. instancingSupport_ = true;
  2194. // Check for sRGB read & write
  2195. /// \todo Should be checked for each texture format separately
  2196. sRGBSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE);
  2197. sRGBWriteSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBWRITE, D3DRTYPE_TEXTURE);
  2198. }
  2199. void Graphics::ResetDevice()
  2200. {
  2201. OnDeviceLost();
  2202. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  2203. {
  2204. deviceLost_ = false;
  2205. OnDeviceReset();
  2206. }
  2207. }
  2208. void Graphics::OnDeviceLost()
  2209. {
  2210. LOGINFO("Device lost");
  2211. if (impl_->defaultColorSurface_)
  2212. {
  2213. impl_->defaultColorSurface_->Release();
  2214. impl_->defaultColorSurface_ = 0;
  2215. }
  2216. if (impl_->defaultDepthStencilSurface_)
  2217. {
  2218. impl_->defaultDepthStencilSurface_->Release();
  2219. impl_->defaultDepthStencilSurface_ = 0;
  2220. }
  2221. if (impl_->frameQuery_)
  2222. {
  2223. impl_->frameQuery_->Release();
  2224. impl_->frameQuery_ = 0;
  2225. }
  2226. {
  2227. MutexLock lock(gpuObjectMutex_);
  2228. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2229. (*i)->OnDeviceLost();
  2230. }
  2231. SendEvent(E_DEVICELOST);
  2232. }
  2233. void Graphics::OnDeviceReset()
  2234. {
  2235. {
  2236. MutexLock lock(gpuObjectMutex_);
  2237. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2238. (*i)->OnDeviceReset();
  2239. }
  2240. // Get default surfaces
  2241. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  2242. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  2243. // Create frame query for flushing the GPU command buffer
  2244. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  2245. ResetCachedState();
  2246. SendEvent(E_DEVICERESET);
  2247. }
  2248. void Graphics::ResetCachedState()
  2249. {
  2250. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2251. {
  2252. vertexBuffers_[i] = 0;
  2253. streamOffsets_[i] = 0;
  2254. }
  2255. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2256. {
  2257. textures_[i] = 0;
  2258. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  2259. impl_->mipFilters_[i] = D3DTEXF_NONE;
  2260. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  2261. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  2262. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  2263. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2264. impl_->sRGBModes_[i] = false;
  2265. }
  2266. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2267. {
  2268. renderTargets_[i] = 0;
  2269. impl_->colorSurfaces_[i] = 0;
  2270. }
  2271. depthStencil_ = 0;
  2272. impl_->depthStencilSurface_ = 0;
  2273. viewport_ = IntRect(0, 0, width_, height_);
  2274. impl_->sRGBWrite_ = false;
  2275. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2276. streamFrequencies_[i] = 1;
  2277. indexBuffer_ = 0;
  2278. vertexDeclaration_ = 0;
  2279. vertexShader_ = 0;
  2280. pixelShader_ = 0;
  2281. blendMode_ = BLEND_REPLACE;
  2282. textureAnisotropy_ = 1;
  2283. colorWrite_ = true;
  2284. cullMode_ = CULL_CCW;
  2285. constantDepthBias_ = 0.0f;
  2286. slopeScaledDepthBias_ = 0.0f;
  2287. depthTestMode_ = CMP_LESSEQUAL;
  2288. depthWrite_ = true;
  2289. fillMode_ = FILL_SOLID;
  2290. scissorTest_ = false;
  2291. scissorRect_ = IntRect::ZERO;
  2292. stencilTest_ = false;
  2293. stencilTestMode_ = CMP_ALWAYS;
  2294. stencilPass_ = OP_KEEP;
  2295. stencilFail_ = OP_KEEP;
  2296. stencilZFail_ = OP_KEEP;
  2297. stencilRef_ = 0;
  2298. stencilCompareMask_ = M_MAX_UNSIGNED;
  2299. stencilWriteMask_ = M_MAX_UNSIGNED;
  2300. useClipPlane_ = false;
  2301. impl_->blendEnable_ = FALSE;
  2302. impl_->srcBlend_ = D3DBLEND_ONE;
  2303. impl_->destBlend_ = D3DBLEND_ZERO;
  2304. impl_->blendOp_ = D3DBLENDOP_ADD;
  2305. queryIssued_ = false;
  2306. }
  2307. void Graphics::SetTextureUnitMappings()
  2308. {
  2309. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2310. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2311. textureUnits_["NormalMap"] = TU_NORMAL;
  2312. textureUnits_["SpecMap"] = TU_SPECULAR;
  2313. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2314. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2315. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2316. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2317. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2318. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2319. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2320. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2321. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2322. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2323. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2324. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2325. }
  2326. void RegisterGraphicsLibrary(Context* context)
  2327. {
  2328. Material::RegisterObject(context);
  2329. Shader::RegisterObject(context);
  2330. Technique::RegisterObject(context);
  2331. Texture2D::RegisterObject(context);
  2332. Texture3D::RegisterObject(context);
  2333. TextureCube::RegisterObject(context);
  2334. Camera::RegisterObject(context);
  2335. Drawable::RegisterObject(context);
  2336. Light::RegisterObject(context);
  2337. DebugRenderer::RegisterObject(context);
  2338. Octree::RegisterObject(context);
  2339. Zone::RegisterObject(context);
  2340. }
  2341. }