D3D9Graphics.cpp 86 KB

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