D3D9Graphics.cpp 70 KB

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