Graphics.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "Geometry.h"
  31. #include "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "GraphicsImpl.h"
  34. #include "IndexBuffer.h"
  35. #include "Light.h"
  36. #include "Log.h"
  37. #include "Material.h"
  38. #include "Octree.h"
  39. #include "ParticleEmitter.h"
  40. #include "PixelShader.h"
  41. #include "Profiler.h"
  42. #include "Skybox.h"
  43. #include "StringUtils.h"
  44. #include "Technique.h"
  45. #include "Texture2D.h"
  46. #include "TextureCube.h"
  47. #include "VertexBuffer.h"
  48. #include "VertexDeclaration.h"
  49. #include "VertexShader.h"
  50. #include "Zone.h"
  51. #include <cstring>
  52. #include "DebugNew.h"
  53. #ifdef _MSC_VER
  54. #pragma warning(disable:4355)
  55. #endif
  56. static const D3DCMPFUNC d3dCmpFunc[] =
  57. {
  58. D3DCMP_ALWAYS,
  59. D3DCMP_EQUAL,
  60. D3DCMP_NOTEQUAL,
  61. D3DCMP_LESS,
  62. D3DCMP_LESSEQUAL,
  63. D3DCMP_GREATER,
  64. D3DCMP_GREATEREQUAL
  65. };
  66. static const D3DTEXTUREFILTERTYPE d3dMinMagFilter[] =
  67. {
  68. D3DTEXF_POINT,
  69. D3DTEXF_LINEAR,
  70. D3DTEXF_LINEAR,
  71. D3DTEXF_ANISOTROPIC
  72. };
  73. static const D3DTEXTUREFILTERTYPE d3dMipFilter[] =
  74. {
  75. D3DTEXF_POINT,
  76. D3DTEXF_POINT,
  77. D3DTEXF_LINEAR,
  78. D3DTEXF_ANISOTROPIC
  79. };
  80. static const D3DTEXTUREADDRESS d3dAddressMode[] =
  81. {
  82. D3DTADDRESS_WRAP,
  83. D3DTADDRESS_MIRROR,
  84. D3DTADDRESS_CLAMP,
  85. D3DTADDRESS_BORDER
  86. };
  87. static const DWORD d3dBlendEnable[] =
  88. {
  89. FALSE,
  90. TRUE,
  91. TRUE,
  92. TRUE,
  93. TRUE,
  94. TRUE,
  95. TRUE
  96. };
  97. static const D3DBLEND d3dSrcBlend[] =
  98. {
  99. D3DBLEND_ONE,
  100. D3DBLEND_ONE,
  101. D3DBLEND_DESTCOLOR,
  102. D3DBLEND_SRCALPHA,
  103. D3DBLEND_SRCALPHA,
  104. D3DBLEND_ONE,
  105. D3DBLEND_INVDESTALPHA,
  106. };
  107. static const D3DBLEND d3dDestBlend[] =
  108. {
  109. D3DBLEND_ZERO,
  110. D3DBLEND_ONE,
  111. D3DBLEND_ZERO,
  112. D3DBLEND_INVSRCALPHA,
  113. D3DBLEND_ONE,
  114. D3DBLEND_INVSRCALPHA,
  115. D3DBLEND_DESTALPHA
  116. };
  117. static const D3DCULL d3dCullMode[] =
  118. {
  119. D3DCULL_NONE,
  120. D3DCULL_CCW,
  121. D3DCULL_CW
  122. };
  123. static const D3DFILLMODE d3dFillMode[] =
  124. {
  125. D3DFILL_SOLID,
  126. D3DFILL_WIREFRAME
  127. };
  128. static const D3DSTENCILOP d3dStencilOp[] =
  129. {
  130. D3DSTENCILOP_KEEP,
  131. D3DSTENCILOP_ZERO,
  132. D3DSTENCILOP_REPLACE,
  133. D3DSTENCILOP_INCR,
  134. D3DSTENCILOP_DECR
  135. };
  136. static const std::string noParameter;
  137. static const DWORD windowStyle = WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX;
  138. static LRESULT CALLBACK wndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam);
  139. OBJECTTYPESTATIC(Graphics);
  140. Graphics::Graphics(Context* context) :
  141. Object(context),
  142. impl_(new GraphicsImpl()),
  143. mode_(RENDER_FORWARD),
  144. width_(0),
  145. height_(0),
  146. multiSample_(0),
  147. windowPosX_(0),
  148. windowPosY_(0),
  149. fullscreen_(false),
  150. vsync_(false),
  151. flushGPU_(true),
  152. deviceLost_(false),
  153. queryIssued_(false),
  154. deferredSupport_(false),
  155. prepassSupport_(false),
  156. hardwareShadowSupport_(false),
  157. hiresShadowSupport_(false),
  158. streamOffsetSupport_(false),
  159. hasSM3_(false),
  160. forceSM2_(false),
  161. numPrimitives_(0),
  162. numBatches_(0),
  163. immediateBuffer_(0),
  164. defaultTextureFilterMode_(FILTER_BILINEAR)
  165. {
  166. ResetCachedState();
  167. InitializeShaderParameters();
  168. SubscribeToEvent(E_WINDOWMESSAGE, HANDLER(Graphics, HandleWindowMessage));
  169. }
  170. Graphics::~Graphics()
  171. {
  172. // Release all GPU objects that still exist
  173. for (std::vector<GPUObject*>::iterator i = gpuObjects_.begin(); i != gpuObjects_.end(); ++i)
  174. (*i)->Release();
  175. gpuObjects_.clear();
  176. vertexDeclarations_.clear();
  177. if (impl_->frameQuery_)
  178. {
  179. impl_->frameQuery_->Release();
  180. impl_->frameQuery_ = 0;
  181. }
  182. if (impl_->defaultColorSurface_)
  183. {
  184. impl_->defaultColorSurface_->Release();
  185. impl_->defaultColorSurface_ = 0;
  186. }
  187. if (impl_->defaultDepthStencilSurface_)
  188. {
  189. impl_->defaultDepthStencilSurface_->Release();
  190. impl_->defaultDepthStencilSurface_ = 0;
  191. }
  192. if (impl_->device_)
  193. {
  194. impl_->device_->Release();
  195. impl_->device_ = 0;
  196. }
  197. if (impl_->interface_)
  198. {
  199. impl_->interface_->Release();
  200. impl_->interface_ = 0;
  201. }
  202. if (impl_->window_)
  203. {
  204. DestroyWindow(impl_->window_);
  205. impl_->window_ = 0;
  206. }
  207. delete impl_;
  208. impl_ = 0;
  209. }
  210. void Graphics::MessagePump()
  211. {
  212. MSG msg;
  213. while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  214. {
  215. TranslateMessage(&msg);
  216. DispatchMessage(&msg);
  217. }
  218. }
  219. void Graphics::SetWindowTitle(const std::string& windowTitle)
  220. {
  221. windowTitle_ = windowTitle;
  222. if (impl_->window_)
  223. SetWindowText(impl_->window_, windowTitle_.c_str());
  224. }
  225. bool Graphics::SetMode(RenderMode mode, int width, int height, bool fullscreen, bool vsync, int multiSample)
  226. {
  227. PROFILE(SetScreenMode);
  228. // Find out the full screen mode display format (match desktop color depth)
  229. D3DFORMAT fullscreenFormat = impl_->GetDesktopFormat();
  230. // If zero dimensions, use the desktop default
  231. if ((width <= 0) || (height <= 0))
  232. {
  233. if (fullscreen)
  234. {
  235. IntVector2 desktopResolution = impl_->GetDesktopResolution();
  236. width = desktopResolution.x_;
  237. height = desktopResolution.y_;
  238. }
  239. else
  240. {
  241. width = 800;
  242. height = 600;
  243. }
  244. }
  245. if ((mode == mode_) && (width == width_) && (height == height_) && (fullscreen == fullscreen_) && (vsync == vsync_)
  246. && (multiSample == multiSample_))
  247. return true;
  248. if (!impl_->window_)
  249. {
  250. if (!OpenWindow(width, height))
  251. return false;
  252. }
  253. if (!impl_->interface_)
  254. {
  255. if (!CreateInterface())
  256. return false;
  257. }
  258. // Disable deferred / light prepass rendering if not supported
  259. // Note: we do not fall back from deferred to light prepass, because there might not be shaders / materials
  260. // defined for it. Instead fall back directly to forward rendering
  261. if ((mode == RENDER_DEFERRED) && (!deferredSupport_))
  262. mode = RENDER_FORWARD;
  263. if ((mode == RENDER_PREPASS) && (!prepassSupport_))
  264. mode = RENDER_FORWARD;
  265. if (multiSample >= (int)D3DMULTISAMPLE_2_SAMPLES)
  266. multiSample = Clamp(multiSample, (int)D3DMULTISAMPLE_NONE, (int)D3DMULTISAMPLE_16_SAMPLES);
  267. else
  268. multiSample = 0;
  269. // Note: GetMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  270. // In deferred or light prepass mode, it is used to control the edge filter
  271. multiSample_ = multiSample;
  272. if (mode != RENDER_FORWARD)
  273. multiSample = 0;
  274. // Check fullscreen mode validity. If not valid, revert to windowed
  275. if (fullscreen)
  276. {
  277. std::vector<IntVector2> resolutions = GetResolutions();
  278. fullscreen = false;
  279. for (unsigned i = 0; i < resolutions.size(); ++i)
  280. {
  281. if ((width == resolutions[i].x_) && (height == resolutions[i].y_))
  282. {
  283. fullscreen = true;
  284. break;
  285. }
  286. }
  287. }
  288. // Fall back to non-multisampled if unsupported multisampling mode
  289. if (multiSample)
  290. {
  291. if (FAILED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  292. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  293. multiSample = 0;
  294. }
  295. // Save window placement if currently windowed
  296. if (!fullscreen_)
  297. {
  298. WINDOWPLACEMENT wndpl;
  299. wndpl.length = sizeof wndpl;
  300. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  301. {
  302. windowPosX_ = wndpl.rcNormalPosition.left;
  303. windowPosY_ = wndpl.rcNormalPosition.top;
  304. }
  305. }
  306. if (fullscreen)
  307. {
  308. impl_->presentParams_.BackBufferFormat = fullscreenFormat;
  309. impl_->presentParams_.Windowed = false;
  310. }
  311. else
  312. {
  313. impl_->presentParams_.BackBufferFormat = D3DFMT_UNKNOWN;
  314. impl_->presentParams_.Windowed = true;
  315. }
  316. impl_->presentParams_.BackBufferWidth = width;
  317. impl_->presentParams_.BackBufferHeight = height;
  318. impl_->presentParams_.BackBufferCount = 1;
  319. impl_->presentParams_.MultiSampleType = (D3DMULTISAMPLE_TYPE)multiSample;
  320. impl_->presentParams_.MultiSampleQuality = 0;
  321. impl_->presentParams_.SwapEffect = D3DSWAPEFFECT_DISCARD;
  322. impl_->presentParams_.hDeviceWindow = impl_->window_;
  323. impl_->presentParams_.EnableAutoDepthStencil = true;
  324. impl_->presentParams_.AutoDepthStencilFormat = D3DFMT_D24S8;
  325. impl_->presentParams_.Flags = 0;
  326. impl_->presentParams_.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  327. if (vsync)
  328. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  329. else
  330. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  331. width_ = width;
  332. height_ = height;
  333. fullscreen_ = fullscreen;
  334. vsync_ = vsync;
  335. mode_ = mode;
  336. if (!impl_->device_)
  337. {
  338. unsigned adapter = D3DADAPTER_DEFAULT;
  339. unsigned deviceType = D3DDEVTYPE_HAL;
  340. // Check for PerfHUD adapter
  341. for (unsigned i=0; i < impl_->interface_->GetAdapterCount(); ++i)
  342. {
  343. D3DADAPTER_IDENTIFIER9 identifier;
  344. impl_->interface_->GetAdapterIdentifier(i, 0, &identifier);
  345. if (strstr(identifier.Description, "PerfHUD") != 0)
  346. {
  347. adapter = i;
  348. deviceType = D3DDEVTYPE_REF;
  349. break;
  350. }
  351. }
  352. impl_->interface_->GetAdapterIdentifier(adapter, 0, &impl_->adapterIdentifier_);
  353. if (!CreateDevice(adapter, deviceType))
  354. return false;
  355. }
  356. else
  357. ResetDevice();
  358. // Adjust window style/size now
  359. if (fullscreen)
  360. {
  361. SetWindowLongPtr(impl_->window_, GWL_STYLE, WS_POPUP);
  362. SetWindowPos(impl_->window_, HWND_TOP, 0, 0, width, height, SWP_NOZORDER | SWP_SHOWWINDOW);
  363. }
  364. else
  365. {
  366. RECT rect = {0, 0, width, height};
  367. AdjustWindowRect(&rect, windowStyle, false);
  368. SetWindowLongPtr(impl_->window_, GWL_STYLE, windowStyle);
  369. SetWindowPos(impl_->window_, HWND_TOP, windowPosX_, windowPosY_, rect.right - rect.left, rect.bottom - rect.top,
  370. SWP_NOZORDER | SWP_SHOWWINDOW);
  371. // Clean up the desktop of the old window contents
  372. InvalidateRect(0, 0, true);
  373. }
  374. if (!multiSample)
  375. LOGINFO("Set screen mode " + ToString(width_) + "x" + ToString(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  376. else
  377. LOGINFO("Set screen mode " + ToString(width_) + "x" + ToString(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  378. " multisample " + ToString(multiSample));
  379. using namespace ScreenMode;
  380. VariantMap eventData;
  381. eventData[P_WIDTH] = width_;
  382. eventData[P_HEIGHT] = height_;
  383. eventData[P_FULLSCREEN] = fullscreen_;
  384. SendEvent(E_SCREENMODE, eventData);
  385. return true;
  386. }
  387. bool Graphics::SetMode(int width, int height)
  388. {
  389. return SetMode(mode_, width, height, fullscreen_, vsync_, multiSample_);
  390. }
  391. bool Graphics::SetMode(RenderMode mode)
  392. {
  393. return SetMode(mode, width_, height_, fullscreen_, vsync_, multiSample_);
  394. }
  395. bool Graphics::ToggleFullscreen()
  396. {
  397. return SetMode(mode_, width_, height_, !fullscreen_, vsync_, multiSample_);
  398. }
  399. void Graphics::Close()
  400. {
  401. if (impl_->window_)
  402. {
  403. diffBuffer_.Reset();
  404. normalBuffer_.Reset();
  405. depthBuffer_.Reset();
  406. immediatevertexBuffer_.clear();
  407. DestroyWindow(impl_->window_);
  408. impl_->window_ = 0;
  409. }
  410. }
  411. bool Graphics::TakeScreenShot(Image& destImage)
  412. {
  413. PROFILE(TakeScreenShot);
  414. if (!impl_->device_)
  415. return false;
  416. D3DSURFACE_DESC surfaceDesc;
  417. impl_->defaultColorSurface_->GetDesc(&surfaceDesc);
  418. // If possible, get the backbuffer data, because it is a lot faster.
  419. // However, if we are multisampled, need to use the front buffer
  420. bool useBackBuffer = true;
  421. if (impl_->presentParams_.MultiSampleType)
  422. {
  423. useBackBuffer = false;
  424. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  425. }
  426. IDirect3DSurface9* surface = 0;
  427. impl_->device_->CreateOffscreenPlainSurface(width_, height_, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  428. if (!surface)
  429. return false;
  430. if (useBackBuffer)
  431. impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  432. else
  433. impl_->device_->GetFrontBufferData(0, surface);
  434. D3DLOCKED_RECT lockedRect;
  435. lockedRect.pBits = 0;
  436. surface->LockRect(&lockedRect, 0, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  437. if (!lockedRect.pBits)
  438. {
  439. surface->Release();
  440. return false;
  441. }
  442. destImage.SetSize(width_, height_, 3);
  443. unsigned char* destData = destImage.GetData();
  444. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  445. {
  446. for (int y = 0; y < height_; ++y)
  447. {
  448. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  449. unsigned char* dest = destData + y * width_ * 3;
  450. for (int x = 0; x < width_; ++x)
  451. {
  452. unsigned short rgb = *src++;
  453. int b = rgb & 31;
  454. int g = (rgb >> 5) & 63;
  455. int r = (rgb >> 11);
  456. *dest++ = (int)(r * 255.0f / 31.0f);
  457. *dest++ = (int)(g * 255.0f / 63.0f);
  458. *dest++ = (int)(b * 255.0f / 31.0f);
  459. }
  460. }
  461. }
  462. else
  463. {
  464. for (int y = 0; y < height_; ++y)
  465. {
  466. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  467. unsigned char* dest = destData + y * width_ * 3;
  468. for (int x = 0; x < width_; ++x)
  469. {
  470. *dest++ = src[2];
  471. *dest++ = src[1];
  472. *dest++ = src[0];
  473. src += 4;
  474. }
  475. }
  476. }
  477. surface->UnlockRect();
  478. surface->Release();
  479. return true;
  480. }
  481. void Graphics::SetFlushGPU(bool enable)
  482. {
  483. flushGPU_ = enable;
  484. }
  485. bool Graphics::BeginFrame()
  486. {
  487. PROFILE(BeginRendering);
  488. if (!IsInitialized())
  489. return false;
  490. // Check for lost device before rendering
  491. HRESULT hr = impl_->device_->TestCooperativeLevel();
  492. if (hr != D3D_OK)
  493. {
  494. deviceLost_ = true;
  495. // The device can not be reset yet, sleep and try again eventually
  496. if (hr == D3DERR_DEVICELOST)
  497. {
  498. Sleep(20);
  499. return false;
  500. }
  501. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  502. if (hr == D3DERR_DEVICENOTRESET)
  503. {
  504. ResetDevice();
  505. return false;
  506. }
  507. }
  508. impl_->device_->BeginScene();
  509. // If a query was issued on the previous frame, wait for it to finish before beginning the next
  510. if ((impl_->frameQuery_) && (queryIssued_))
  511. {
  512. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  513. {
  514. }
  515. queryIssued_ = false;
  516. }
  517. // Set default rendertarget and depth buffer
  518. ResetRenderTargets();
  519. viewTexture_ = 0;
  520. // Cleanup textures from previous frame
  521. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  522. SetTexture(i, 0);
  523. // Cleanup stream frequencies from previous frame
  524. ResetStreamFrequencies();
  525. // Reset immediate mode vertex buffer positions
  526. for (std::map<unsigned, unsigned>::iterator i = immediateVertexBufferPos_.begin(); i != immediateVertexBufferPos_.end(); ++i)
  527. i->second = 0;
  528. numPrimitives_ = 0;
  529. numBatches_ = 0;
  530. SendEvent(E_BEGINRENDER);
  531. return true;
  532. }
  533. void Graphics::EndFrame()
  534. {
  535. PROFILE(EndRendering);
  536. if (!IsInitialized())
  537. return;
  538. SendEvent(E_ENDRENDER);
  539. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to pre-render
  540. if ((impl_->frameQuery_) && (flushGPU_))
  541. {
  542. impl_->frameQuery_->Issue(D3DISSUE_END);
  543. queryIssued_ = true;
  544. }
  545. {
  546. impl_->device_->EndScene();
  547. impl_->device_->Present(0, 0, 0, 0);
  548. }
  549. }
  550. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  551. {
  552. DWORD d3dFlags = 0;
  553. if (flags & CLEAR_COLOR)
  554. d3dFlags |= D3DCLEAR_TARGET;
  555. if (flags & CLEAR_DEPTH)
  556. d3dFlags |= D3DCLEAR_ZBUFFER;
  557. if (flags & CLEAR_STENCIL)
  558. d3dFlags |= D3DCLEAR_STENCIL;
  559. impl_->device_->Clear(0, 0, d3dFlags, color.ToUInt(), depth, stencil);
  560. }
  561. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  562. {
  563. if (!vertexCount)
  564. return;
  565. ResetStreamFrequencies();
  566. unsigned primitiveCount = 0;
  567. switch (type)
  568. {
  569. case TRIANGLE_LIST:
  570. primitiveCount = vertexCount / 3;
  571. impl_->device_->DrawPrimitive(D3DPT_TRIANGLELIST, vertexStart, primitiveCount);
  572. break;
  573. case LINE_LIST:
  574. primitiveCount = vertexCount / 2;
  575. impl_->device_->DrawPrimitive(D3DPT_LINELIST, vertexStart, primitiveCount);
  576. break;
  577. }
  578. numPrimitives_ += primitiveCount;
  579. numBatches_++;
  580. }
  581. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  582. {
  583. if (!indexCount)
  584. return;
  585. ResetStreamFrequencies();
  586. unsigned primitiveCount = 0;
  587. switch (type)
  588. {
  589. case TRIANGLE_LIST:
  590. primitiveCount = indexCount / 3;
  591. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  592. break;
  593. case LINE_LIST:
  594. primitiveCount = indexCount / 2;
  595. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  596. break;
  597. }
  598. numPrimitives_ += primitiveCount;
  599. numBatches_++;
  600. }
  601. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  602. unsigned instanceCount)
  603. {
  604. if ((!indexCount) || (!instanceCount))
  605. return;
  606. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  607. {
  608. VertexBuffer* buffer = vertexBuffer_[i];
  609. if (buffer)
  610. {
  611. if (buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  612. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1);
  613. else
  614. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  615. }
  616. }
  617. unsigned primitiveCount = 0;
  618. switch (type)
  619. {
  620. case TRIANGLE_LIST:
  621. primitiveCount = indexCount / 3;
  622. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  623. break;
  624. case LINE_LIST:
  625. primitiveCount = indexCount / 2;
  626. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  627. break;
  628. }
  629. numPrimitives_ += instanceCount * primitiveCount;
  630. numBatches_++;
  631. }
  632. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  633. {
  634. std::vector<VertexBuffer*> vertexBuffers(1);
  635. std::vector<unsigned> elementMasks(1);
  636. vertexBuffers[0] = buffer;
  637. elementMasks[0] = MASK_DEFAULT;
  638. SetVertexBuffers(vertexBuffers, elementMasks);
  639. }
  640. bool Graphics::SetVertexBuffers(const std::vector<VertexBuffer*>& buffers, const std::vector<unsigned>& elementMasks,
  641. unsigned instanceOffset)
  642. {
  643. if (buffers.size() > MAX_VERTEX_STREAMS)
  644. {
  645. LOGERROR("Too many vertex buffers");
  646. return false;
  647. }
  648. if (buffers.size() != elementMasks.size())
  649. {
  650. LOGERROR("Amount of element masks and vertex buffers does not match");
  651. return false;
  652. }
  653. // Build vertex declaration hash code out of the buffers & masks
  654. unsigned long long hash = 0;
  655. for (unsigned i = 0; i < buffers.size(); ++i)
  656. {
  657. if (!buffers[i])
  658. continue;
  659. hash |= buffers[i]->GetHash(i, elementMasks[i]);
  660. }
  661. if (hash)
  662. {
  663. // If no previous vertex declaration for that hash, create new
  664. if (vertexDeclarations_.find(hash) == vertexDeclarations_.end())
  665. {
  666. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  667. if (!newDeclaration->GetDeclaration())
  668. {
  669. LOGERROR("Failed to create vertex declaration");
  670. return false;
  671. }
  672. vertexDeclarations_[hash] = newDeclaration;
  673. }
  674. VertexDeclaration* declaration = vertexDeclarations_[hash];
  675. if (declaration != vertexDeclaration_)
  676. {
  677. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  678. vertexDeclaration_ = declaration;
  679. }
  680. }
  681. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  682. {
  683. VertexBuffer* buffer = 0;
  684. unsigned offset = 0;
  685. if (i < buffers.size())
  686. {
  687. buffer = buffers[i];
  688. if ((buffer) && (buffer->GetElementMask() & MASK_INSTANCEMATRIX1))
  689. offset = instanceOffset * buffer->GetVertexSize();
  690. }
  691. if ((buffer != vertexBuffer_[i]) || (offset != streamOffset_[i]))
  692. {
  693. if (buffer)
  694. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  695. else
  696. impl_->device_->SetStreamSource(i, 0, 0, 0);
  697. vertexBuffer_[i] = buffer;
  698. streamOffset_[i] = offset;
  699. }
  700. }
  701. return true;
  702. }
  703. bool Graphics::SetVertexBuffers(const std::vector<SharedPtr<VertexBuffer> >& buffers, const std::vector<unsigned>&
  704. elementMasks, unsigned instanceOffset)
  705. {
  706. if (buffers.size() > MAX_VERTEX_STREAMS)
  707. {
  708. LOGERROR("Too many vertex buffers");
  709. return false;
  710. }
  711. if (buffers.size() != elementMasks.size())
  712. {
  713. LOGERROR("Amount of element masks and vertex buffers does not match");
  714. return false;
  715. }
  716. // Build vertex declaration hash code out of the buffers & masks
  717. unsigned long long hash = 0;
  718. for (unsigned i = 0; i < buffers.size(); ++i)
  719. {
  720. if (!buffers[i])
  721. continue;
  722. hash |= buffers[i]->GetHash(i, elementMasks[i]);
  723. }
  724. if (hash)
  725. {
  726. // If no previous vertex declaration for that hash, create new
  727. if (vertexDeclarations_.find(hash) == vertexDeclarations_.end())
  728. {
  729. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  730. if (!newDeclaration->GetDeclaration())
  731. {
  732. LOGERROR("Failed to create vertex declaration");
  733. return false;
  734. }
  735. vertexDeclarations_[hash] = newDeclaration;
  736. }
  737. VertexDeclaration* declaration = vertexDeclarations_[hash];
  738. if (declaration != vertexDeclaration_)
  739. {
  740. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  741. vertexDeclaration_ = declaration;
  742. }
  743. }
  744. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  745. {
  746. VertexBuffer* buffer = 0;
  747. unsigned offset = 0;
  748. if (i < buffers.size())
  749. {
  750. buffer = buffers[i];
  751. if ((buffer) && (buffer->GetElementMask() & MASK_INSTANCEMATRIX1))
  752. offset = instanceOffset * buffer->GetVertexSize();
  753. }
  754. if ((buffer != vertexBuffer_[i]) || (offset != streamOffset_[i]))
  755. {
  756. if (buffer)
  757. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  758. else
  759. impl_->device_->SetStreamSource(i, 0, 0, 0);
  760. vertexBuffer_[i] = buffer;
  761. streamOffset_[i] = offset;
  762. }
  763. }
  764. return true;
  765. }
  766. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  767. {
  768. if (buffer != indexBuffer_)
  769. {
  770. if (buffer)
  771. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  772. else
  773. impl_->device_->SetIndices(0);
  774. indexBuffer_ = buffer;
  775. }
  776. }
  777. void Graphics::SetShaders(VertexShader* vs, PixelShader* ps)
  778. {
  779. if (vs != vertexShader_)
  780. {
  781. if (vs)
  782. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  783. else
  784. impl_->device_->SetVertexShader(0);
  785. vertexShader_ = vs;
  786. }
  787. if (ps != pixelShader_)
  788. {
  789. if (ps)
  790. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  791. else
  792. impl_->device_->SetPixelShader(0);
  793. pixelShader_ = ps;
  794. }
  795. }
  796. void Graphics::SetVertexShaderParameter(VSParameter param, const bool* data, unsigned count)
  797. {
  798. unsigned index = vsRegisters_[param];
  799. if (index >= MAX_CONSTANT_REGISTERS)
  800. return;
  801. impl_->device_->SetVertexShaderConstantB(index, (const BOOL*)data, count);
  802. }
  803. void Graphics::SetVertexShaderParameter(VSParameter param, const float* data, unsigned count)
  804. {
  805. unsigned index = vsRegisters_[param];
  806. if (index >= MAX_CONSTANT_REGISTERS)
  807. return;
  808. impl_->device_->SetVertexShaderConstantF(index, data, count / 4);
  809. }
  810. void Graphics::SetVertexShaderParameter(VSParameter param, const int* data, unsigned count)
  811. {
  812. unsigned index = vsRegisters_[param];
  813. if (index >= MAX_CONSTANT_REGISTERS)
  814. return;
  815. impl_->device_->SetVertexShaderConstantI(index, data, count / 4);
  816. }
  817. void Graphics::SetVertexShaderParameter(VSParameter param, float value)
  818. {
  819. unsigned index = vsRegisters_[param];
  820. if (index >= MAX_CONSTANT_REGISTERS)
  821. return;
  822. float data[4] =
  823. {
  824. 0.0f,
  825. 0.0f,
  826. 0.0f,
  827. 0.0f
  828. };
  829. data[0] = value;
  830. impl_->device_->SetVertexShaderConstantF(index, &data[0], 1);
  831. }
  832. void Graphics::SetVertexShaderParameter(VSParameter param, const Color& color)
  833. {
  834. unsigned index = vsRegisters_[param];
  835. if (index >= MAX_CONSTANT_REGISTERS)
  836. return;
  837. impl_->device_->SetVertexShaderConstantF(index, color.GetData(), 1);
  838. }
  839. void Graphics::SetVertexShaderParameter(VSParameter param, const Matrix3& matrix)
  840. {
  841. unsigned index = vsRegisters_[param];
  842. if (index >= MAX_CONSTANT_REGISTERS)
  843. return;
  844. float data[12];
  845. data[0] = matrix.m00_;
  846. data[1] = matrix.m01_;
  847. data[2] = matrix.m02_;
  848. data[3] = 0.0f;
  849. data[4] = matrix.m10_;
  850. data[5] = matrix.m11_;
  851. data[6] = matrix.m12_;
  852. data[7] = 0.0f;
  853. data[8] = matrix.m20_;
  854. data[9] = matrix.m21_;
  855. data[10] = matrix.m22_;
  856. data[11] = 0.0f;
  857. impl_->device_->SetVertexShaderConstantF(index, &data[0], 3);
  858. }
  859. void Graphics::SetVertexShaderParameter(VSParameter param, const Vector3& vector)
  860. {
  861. unsigned index = vsRegisters_[param];
  862. if (index >= MAX_CONSTANT_REGISTERS)
  863. return;
  864. float data[4] =
  865. {
  866. 0.0f,
  867. 0.0f,
  868. 0.0f,
  869. 0.0f
  870. };
  871. data[0] = vector.x_;
  872. data[1] = vector.y_;
  873. data[2] = vector.z_;
  874. impl_->device_->SetVertexShaderConstantF(index, &data[0], 1);
  875. }
  876. void Graphics::SetVertexShaderParameter(VSParameter param, const Matrix4& matrix)
  877. {
  878. unsigned index = vsRegisters_[param];
  879. if (index >= MAX_CONSTANT_REGISTERS)
  880. return;
  881. impl_->device_->SetVertexShaderConstantF(index, matrix.GetData(), 4);
  882. }
  883. void Graphics::SetVertexShaderParameter(VSParameter param, const Vector4& vector)
  884. {
  885. unsigned index = vsRegisters_[param];
  886. if (index >= MAX_CONSTANT_REGISTERS)
  887. return;
  888. impl_->device_->SetVertexShaderConstantF(index, vector.GetData(), 1);
  889. }
  890. void Graphics::SetVertexShaderParameter(VSParameter param, const Matrix4x3& matrix)
  891. {
  892. unsigned index = vsRegisters_[param];
  893. if (index >= MAX_CONSTANT_REGISTERS)
  894. return;
  895. impl_->device_->SetVertexShaderConstantF(index, matrix.GetData(), 3);
  896. }
  897. void Graphics::SetPixelShaderParameter(PSParameter param, const bool* data, unsigned count)
  898. {
  899. unsigned index = psRegisters_[param];
  900. if (index >= MAX_CONSTANT_REGISTERS)
  901. return;
  902. impl_->device_->SetPixelShaderConstantB(index, (const BOOL*)data, count);
  903. }
  904. void Graphics::SetPixelShaderParameter(PSParameter param, const float* data, unsigned count)
  905. {
  906. unsigned index = psRegisters_[param];
  907. if (index >= MAX_CONSTANT_REGISTERS)
  908. return;
  909. impl_->device_->SetPixelShaderConstantF(index, data, count / 4);
  910. }
  911. void Graphics::SetPixelShaderParameter(PSParameter param, const int* data, unsigned count)
  912. {
  913. unsigned index = psRegisters_[param];
  914. if (index >= MAX_CONSTANT_REGISTERS)
  915. return;
  916. impl_->device_->SetPixelShaderConstantI(index, data, count / 4);
  917. }
  918. void Graphics::SetPixelShaderParameter(PSParameter param, float value)
  919. {
  920. unsigned index = psRegisters_[param];
  921. if (index >= MAX_CONSTANT_REGISTERS)
  922. return;
  923. float data[4] =
  924. {
  925. 0.0f,
  926. 0.0f,
  927. 0.0f,
  928. 0.0f
  929. };
  930. data[0] = value;
  931. impl_->device_->SetPixelShaderConstantF(index, &data[0], 1);
  932. }
  933. void Graphics::SetPixelShaderParameter(PSParameter param, const Color& color)
  934. {
  935. unsigned index = psRegisters_[param];
  936. if (index >= MAX_CONSTANT_REGISTERS)
  937. return;
  938. impl_->device_->SetPixelShaderConstantF(index, color.GetData(), 1);
  939. }
  940. void Graphics::SetPixelShaderParameter(PSParameter param, const Matrix3& matrix)
  941. {
  942. unsigned index = psRegisters_[param];
  943. if (index >= MAX_CONSTANT_REGISTERS)
  944. return;
  945. float data[12];
  946. data[0] = matrix.m00_;
  947. data[1] = matrix.m01_;
  948. data[2] = matrix.m02_;
  949. data[3] = 0.0f;
  950. data[4] = matrix.m10_;
  951. data[5] = matrix.m11_;
  952. data[6] = matrix.m12_;
  953. data[7] = 0.0f;
  954. data[8] = matrix.m20_;
  955. data[9] = matrix.m21_;
  956. data[10] = matrix.m22_;
  957. data[11] = 0.0f;
  958. impl_->device_->SetPixelShaderConstantF(index, &data[0], 3);
  959. }
  960. void Graphics::SetPixelShaderParameter(PSParameter param, const Vector3& vector)
  961. {
  962. unsigned index = psRegisters_[param];
  963. if (index >= MAX_CONSTANT_REGISTERS)
  964. return;
  965. float data[4] =
  966. {
  967. 0.0f,
  968. 0.0f,
  969. 0.0f,
  970. 0.0f
  971. };
  972. data[0] = vector.x_;
  973. data[1] = vector.y_;
  974. data[2] = vector.z_;
  975. impl_->device_->SetPixelShaderConstantF(index, &data[0], 1);
  976. }
  977. void Graphics::SetPixelShaderParameter(PSParameter param, const Matrix4& matrix)
  978. {
  979. unsigned index = psRegisters_[param];
  980. if (index >= MAX_CONSTANT_REGISTERS)
  981. return;
  982. impl_->device_->SetPixelShaderConstantF(index, matrix.GetData(), 4);
  983. }
  984. void Graphics::SetPixelShaderParameter(PSParameter param, const Vector4& vector)
  985. {
  986. unsigned index = psRegisters_[param];
  987. if (index >= MAX_CONSTANT_REGISTERS)
  988. return;
  989. impl_->device_->SetPixelShaderConstantF(index, vector.GetData(), 1);
  990. }
  991. void Graphics::SetPixelShaderParameter(PSParameter param, const Matrix4x3& matrix)
  992. {
  993. unsigned index = psRegisters_[param];
  994. if (index >= MAX_CONSTANT_REGISTERS)
  995. return;
  996. impl_->device_->SetPixelShaderConstantF(index, matrix.GetData(), 3);
  997. }
  998. void Graphics::ClearLastParameterSources()
  999. {
  1000. for (unsigned i = 0; i < MAX_VS_PARAMETERS; ++i)
  1001. lastVSParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1002. for (unsigned i = 0; i < MAX_PS_PARAMETERS; ++i)
  1003. lastPSParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1004. }
  1005. void Graphics::ClearTransformSources()
  1006. {
  1007. lastVSParameterSources_[VSP_MODEL] = (const void*)M_MAX_UNSIGNED;
  1008. lastVSParameterSources_[VSP_VIEWPROJ] = (const void*)M_MAX_UNSIGNED;
  1009. }
  1010. void Graphics::SetTexture(unsigned index, Texture* texture)
  1011. {
  1012. if (index >= MAX_TEXTURE_UNITS)
  1013. return;
  1014. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  1015. if (texture)
  1016. {
  1017. if ((renderTarget_[0]) && (renderTarget_[0]->GetParentTexture() == texture))
  1018. texture = texture->GetBackupTexture();
  1019. // Check also for the view texture, in case a specific rendering pass does not bind the destination render target,
  1020. // but should still not sample it either
  1021. else if (texture == viewTexture_)
  1022. texture = texture->GetBackupTexture();
  1023. }
  1024. if (texture != texture_[index])
  1025. {
  1026. if (texture)
  1027. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1028. else
  1029. impl_->device_->SetTexture(index, 0);
  1030. texture_[index] = texture;
  1031. }
  1032. if (texture)
  1033. {
  1034. TextureFilterMode filterMode = texture->GetFilterMode();
  1035. if (filterMode == FILTER_DEFAULT)
  1036. filterMode = defaultTextureFilterMode_;
  1037. D3DTEXTUREFILTERTYPE minMag, mip;
  1038. minMag = d3dMinMagFilter[filterMode];
  1039. if (minMag != impl_->minMagFilter_[index])
  1040. {
  1041. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1042. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1043. impl_->minMagFilter_[index] = minMag;
  1044. }
  1045. mip = d3dMipFilter[filterMode];
  1046. if (mip != impl_->mipFilter_[index])
  1047. {
  1048. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1049. impl_->mipFilter_[index] = mip;
  1050. }
  1051. D3DTEXTUREADDRESS u, v;
  1052. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1053. if (u != impl_->uAddressMode_[index])
  1054. {
  1055. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1056. impl_->uAddressMode_[index] = u;
  1057. }
  1058. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1059. if (v != impl_->vAddressMode_[index])
  1060. {
  1061. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1062. impl_->vAddressMode_[index] = v;
  1063. }
  1064. if ((u == D3DTADDRESS_BORDER) || (v == D3DTADDRESS_BORDER))
  1065. {
  1066. const Color& borderColor = texture->GetBorderColor();
  1067. if (borderColor != impl_->borderColor_[index])
  1068. {
  1069. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, borderColor.ToUInt());
  1070. impl_->borderColor_[index] = borderColor;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1076. {
  1077. defaultTextureFilterMode_ = mode;
  1078. }
  1079. void Graphics::ResetRenderTargets()
  1080. {
  1081. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1082. SetRenderTarget(i, (RenderSurface*)0);
  1083. SetDepthStencil((RenderSurface*)0);
  1084. SetViewport(IntRect(0, 0, width_, height_));
  1085. }
  1086. void Graphics::ResetRenderTarget(unsigned index)
  1087. {
  1088. SetRenderTarget(index, (RenderSurface*)0);
  1089. }
  1090. void Graphics::ResetDepthStencil()
  1091. {
  1092. SetDepthStencil((RenderSurface*)0);
  1093. }
  1094. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1095. {
  1096. if (index >= MAX_RENDERTARGETS)
  1097. return;
  1098. IDirect3DSurface9* newColorSurface = 0;
  1099. if (renderTarget)
  1100. {
  1101. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1102. return;
  1103. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1104. }
  1105. else
  1106. {
  1107. if (!index)
  1108. newColorSurface = impl_->defaultColorSurface_;
  1109. }
  1110. renderTarget_[index] = renderTarget;
  1111. if (newColorSurface != impl_->colorSurface_[index])
  1112. {
  1113. impl_->device_->SetRenderTarget(index, newColorSurface);
  1114. impl_->colorSurface_[index] = newColorSurface;
  1115. }
  1116. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1117. if (renderTarget)
  1118. {
  1119. Texture* parentTexture = renderTarget->GetParentTexture();
  1120. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1121. {
  1122. if (texture_[i] == parentTexture)
  1123. SetTexture(i, texture_[i]->GetBackupTexture());
  1124. }
  1125. }
  1126. if (!index)
  1127. {
  1128. // Viewport has been reset
  1129. IntVector2 rtSize = GetRenderTargetDimensions();
  1130. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1131. // Disable scissor test, needs to be re-enabled by the user
  1132. SetScissorTest(false);
  1133. }
  1134. }
  1135. void Graphics::SetRenderTarget(unsigned index, Texture2D* renderTexture)
  1136. {
  1137. RenderSurface* renderTarget = 0;
  1138. if (renderTexture)
  1139. renderTarget = renderTexture->GetRenderSurface();
  1140. SetRenderTarget(index, renderTarget);
  1141. }
  1142. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1143. {
  1144. IDirect3DSurface9* newDepthStencilSurface = 0;
  1145. if ((depthStencil) && (depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL))
  1146. {
  1147. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1148. depthStencil_ = depthStencil;
  1149. }
  1150. if (!newDepthStencilSurface)
  1151. {
  1152. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1153. depthStencil_ = 0;
  1154. }
  1155. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1156. {
  1157. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1158. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1159. }
  1160. }
  1161. void Graphics::SetDepthStencil(Texture2D* depthTexture)
  1162. {
  1163. RenderSurface* depthStencil = 0;
  1164. if (depthTexture)
  1165. depthStencil = depthTexture->GetRenderSurface();
  1166. SetDepthStencil(depthStencil);
  1167. }
  1168. void Graphics::SetViewport(const IntRect& rect)
  1169. {
  1170. IntVector2 size = GetRenderTargetDimensions();
  1171. IntRect rectCopy = rect;
  1172. if (rectCopy.right_ <= rectCopy.left_)
  1173. rectCopy.right_ = rectCopy.left_ + 1;
  1174. if (rectCopy.bottom_ <= rectCopy.top_)
  1175. rectCopy.bottom_ = rectCopy.top_ + 1;
  1176. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1177. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1178. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1179. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1180. D3DVIEWPORT9 vp;
  1181. vp.MinZ = 0.0f;
  1182. vp.MaxZ = 1.0f;
  1183. vp.X = rectCopy.left_;
  1184. vp.Y = rectCopy.top_;
  1185. vp.Width = rectCopy.right_ - rectCopy.left_;
  1186. vp.Height = rectCopy.bottom_ - rectCopy.top_;
  1187. impl_->device_->SetViewport(&vp);
  1188. viewport_ = rectCopy;
  1189. // Disable scissor test, needs to be re-enabled by the user
  1190. SetScissorTest(false);
  1191. }
  1192. void Graphics::SetViewTexture(Texture* texture)
  1193. {
  1194. viewTexture_ = texture;
  1195. // Check for the view texture being currently bound
  1196. if (texture)
  1197. {
  1198. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1199. {
  1200. if (texture_[i] == texture)
  1201. SetTexture(i, texture_[i]->GetBackupTexture());
  1202. }
  1203. }
  1204. }
  1205. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1206. {
  1207. if (enable != alphaTest_)
  1208. {
  1209. impl_->device_->SetRenderState(D3DRS_ALPHATESTENABLE, enable ? TRUE : FALSE);
  1210. alphaTest_ = enable;
  1211. }
  1212. if (enable)
  1213. {
  1214. if (mode != alphaTestMode_)
  1215. {
  1216. impl_->device_->SetRenderState(D3DRS_ALPHAFUNC, d3dCmpFunc[mode]);
  1217. alphaTestMode_ = mode;
  1218. }
  1219. if (alphaRef < 0.0f)
  1220. alphaRef = 0.0f;
  1221. if (alphaRef > 1.0f)
  1222. alphaRef = 1.0f;
  1223. if (alphaRef != alphaRef_)
  1224. {
  1225. impl_->device_->SetRenderState(D3DRS_ALPHAREF, (DWORD)(alphaRef * 255.0f));
  1226. alphaRef_ = alphaRef;
  1227. }
  1228. }
  1229. }
  1230. void Graphics::SetTextureAnisotropy(unsigned level)
  1231. {
  1232. if (level < 1)
  1233. level = 1;
  1234. if (level != textureAnisotropy_)
  1235. {
  1236. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1237. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1238. textureAnisotropy_ = level;
  1239. }
  1240. }
  1241. void Graphics::SetBlendMode(BlendMode mode)
  1242. {
  1243. if (mode != blendMode_)
  1244. {
  1245. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1246. {
  1247. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1248. impl_->blendEnable_ = d3dBlendEnable[mode];
  1249. }
  1250. if (impl_->blendEnable_)
  1251. {
  1252. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1253. {
  1254. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1255. impl_->srcBlend_ = d3dSrcBlend[mode];
  1256. }
  1257. if (d3dDestBlend[mode] != impl_->destBlend_)
  1258. {
  1259. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1260. impl_->destBlend_ = d3dDestBlend[mode];
  1261. }
  1262. }
  1263. blendMode_ = mode;
  1264. }
  1265. }
  1266. void Graphics::SetColorWrite(bool enable)
  1267. {
  1268. if (enable != colorWrite_)
  1269. {
  1270. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1271. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1272. colorWrite_ = enable;
  1273. }
  1274. }
  1275. void Graphics::SetCullMode(CullMode mode)
  1276. {
  1277. if (mode != cullMode_)
  1278. {
  1279. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1280. cullMode_ = mode;
  1281. }
  1282. }
  1283. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1284. {
  1285. if (constantBias != constantDepthBias_)
  1286. {
  1287. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1288. constantDepthBias_ = constantBias;
  1289. }
  1290. if (slopeScaledBias != slopeScaledDepthBias_)
  1291. {
  1292. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1293. slopeScaledDepthBias_ = slopeScaledBias;
  1294. }
  1295. }
  1296. void Graphics::SetDepthTest(CompareMode mode)
  1297. {
  1298. if (mode != depthTestMode_)
  1299. {
  1300. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1301. depthTestMode_ = mode;
  1302. }
  1303. }
  1304. void Graphics::SetDepthWrite(bool enable)
  1305. {
  1306. if (enable != depthWrite_)
  1307. {
  1308. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1309. depthWrite_ = enable;
  1310. }
  1311. }
  1312. void Graphics::SetFillMode(FillMode mode)
  1313. {
  1314. if (mode != fillMode_)
  1315. {
  1316. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1317. fillMode_ = mode;
  1318. }
  1319. }
  1320. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1321. {
  1322. // During some light rendering loops, a full rect is Toggled on/off repeatedly.
  1323. // Disable scissor in that case to reduce state changes
  1324. if (rect == Rect::FULL)
  1325. enable = false;
  1326. // Check for illegal rect, disable in that case
  1327. if ((rect.max_.x_ < rect.min_.x_) || (rect.max_.y_ < rect.min_.y_))
  1328. enable = false;
  1329. if (enable)
  1330. {
  1331. IntVector2 rtSize(GetRenderTargetDimensions());
  1332. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1333. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1334. IntRect intRect;
  1335. int expand = borderInclusive ? 1 : 0;
  1336. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1337. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1338. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1339. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1340. if (intRect.right_ == intRect.left_)
  1341. intRect.right_++;
  1342. if (intRect.bottom_ == intRect.top_)
  1343. intRect.bottom_++;
  1344. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1345. enable = false;
  1346. if ((enable) && (scissorRect_ != intRect))
  1347. {
  1348. RECT d3dRect;
  1349. d3dRect.left = intRect.left_;
  1350. d3dRect.top = intRect.top_;
  1351. d3dRect.right = intRect.right_;
  1352. d3dRect.bottom = intRect.bottom_;
  1353. impl_->device_->SetScissorRect(&d3dRect);
  1354. scissorRect_ = intRect;
  1355. }
  1356. }
  1357. else
  1358. scissorRect_ = IntRect::ZERO;
  1359. if (enable != scissorTest_)
  1360. {
  1361. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1362. scissorTest_ = enable;
  1363. }
  1364. }
  1365. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1366. {
  1367. IntVector2 rtSize(GetRenderTargetDimensions());
  1368. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1369. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1370. // Full scissor is same as disabling the test
  1371. if ((rect.left_ <= 0) && (rect.right_ >= viewSize.x_) && (rect.top_ <= 0) && (rect.bottom_ >= viewSize.y_))
  1372. enable = false;
  1373. // Check for illegal rect, disable in that case
  1374. if ((rect.right_ < rect.left_) || (rect.bottom_ < rect.top_))
  1375. enable = false;
  1376. if (enable)
  1377. {
  1378. IntRect intRect;
  1379. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1380. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1381. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1382. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1383. if (intRect.right_ == intRect.left_)
  1384. intRect.right_++;
  1385. if (intRect.bottom_ == intRect.top_)
  1386. intRect.bottom_++;
  1387. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1388. enable = false;
  1389. if ((enable) && (scissorRect_ != intRect))
  1390. {
  1391. RECT d3dRect;
  1392. d3dRect.left = intRect.left_;
  1393. d3dRect.top = intRect.top_;
  1394. d3dRect.right = intRect.right_;
  1395. d3dRect.bottom = intRect.bottom_;
  1396. impl_->device_->SetScissorRect(&d3dRect);
  1397. scissorRect_ = intRect;
  1398. }
  1399. }
  1400. else
  1401. scissorRect_ = IntRect::ZERO;
  1402. if (enable != scissorTest_)
  1403. {
  1404. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1405. scissorTest_ = enable;
  1406. }
  1407. }
  1408. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1409. {
  1410. if (enable != stencilTest_)
  1411. {
  1412. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1413. stencilTest_ = enable;
  1414. }
  1415. if (enable)
  1416. {
  1417. if (mode != stencilTestMode_)
  1418. {
  1419. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1420. stencilTestMode_ = mode;
  1421. }
  1422. if (pass != stencilPass_)
  1423. {
  1424. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1425. stencilPass_ = pass;
  1426. }
  1427. if (fail != stencilFail_)
  1428. {
  1429. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1430. stencilFail_ = fail;
  1431. }
  1432. if (zFail != stencilZFail_)
  1433. {
  1434. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1435. stencilZFail_ = zFail;
  1436. }
  1437. if (stencilRef != stencilRef_)
  1438. {
  1439. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1440. stencilRef_ = stencilRef;
  1441. }
  1442. if (stencilMask != stencilMask_)
  1443. {
  1444. impl_->device_->SetRenderState(D3DRS_STENCILMASK, stencilMask);
  1445. stencilMask_ = stencilMask;
  1446. }
  1447. }
  1448. }
  1449. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1450. {
  1451. if ((index < MAX_VERTEX_STREAMS) && (streamFrequency_[index] != frequency))
  1452. {
  1453. impl_->device_->SetStreamSourceFreq(index, frequency);
  1454. streamFrequency_[index] = frequency;
  1455. }
  1456. }
  1457. void Graphics::ResetStreamFrequencies()
  1458. {
  1459. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1460. {
  1461. if (streamFrequency_[i] != 1)
  1462. {
  1463. impl_->device_->SetStreamSourceFreq(i, 1);
  1464. streamFrequency_[i] = 1;
  1465. }
  1466. }
  1467. }
  1468. bool Graphics::BeginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1469. {
  1470. if (immediateBuffer_)
  1471. {
  1472. LOGERROR("New immediate draw operation started before ending the last one");
  1473. return false;
  1474. }
  1475. if (!(elementMask & MASK_POSITION))
  1476. {
  1477. LOGERROR("Immediate draw operation must contain vertex positions");
  1478. return false;
  1479. }
  1480. if (!vertexCount)
  1481. return true;
  1482. // Start from default size, ensure that buffer is big enough to hold the immediate draw operation
  1483. unsigned newSize = IMMEDIATE_BUFFER_DEFAULT_SIZE;
  1484. while (newSize < vertexCount)
  1485. newSize <<= 1;
  1486. // See if buffer exists for this vertex format. If not, create new
  1487. if (immediatevertexBuffer_.find(elementMask) == immediatevertexBuffer_.end())
  1488. {
  1489. LOGDEBUG("Created immediate vertex buffer");
  1490. VertexBuffer* newBuffer = new VertexBuffer(context_);
  1491. newBuffer->SetSize(newSize, elementMask, true);
  1492. immediatevertexBuffer_[elementMask] = newBuffer;
  1493. immediateVertexBufferPos_[elementMask] = 0;
  1494. }
  1495. // Resize buffer if it is too small
  1496. VertexBuffer* buffer = immediatevertexBuffer_[elementMask];
  1497. if (buffer->GetVertexCount() < newSize)
  1498. {
  1499. LOGDEBUG("Resized immediate vertex buffer to " + ToString(newSize));
  1500. buffer->SetSize(newSize, elementMask);
  1501. immediateVertexBufferPos_[elementMask] = 0;
  1502. }
  1503. // Get the current lock position for the buffer
  1504. unsigned bufferPos = immediateVertexBufferPos_[elementMask];
  1505. if (bufferPos + vertexCount >= buffer->GetVertexCount())
  1506. bufferPos = 0;
  1507. LockMode lockMode = LOCK_DISCARD;
  1508. if (bufferPos != 0)
  1509. lockMode = LOCK_NOOVERWRITE;
  1510. // Note: the data pointer gets pre-decremented here, because the first call to DefineVertex() will increment it
  1511. immediateDataPtr_ = ((unsigned char*)buffer->Lock(bufferPos, vertexCount, lockMode)) - buffer->GetVertexSize();
  1512. immediateBuffer_ = buffer;
  1513. immediateType_= type;
  1514. immediateStartPos_ = bufferPos;
  1515. immediateVertexCount_ = vertexCount;
  1516. immediateCurrentVertex_ = 0;
  1517. // Store new buffer position for next lock into the same buffer
  1518. bufferPos += vertexCount;
  1519. if (bufferPos >= buffer->GetVertexCount())
  1520. bufferPos = 0;
  1521. immediateVertexBufferPos_[elementMask] = bufferPos;
  1522. return true;
  1523. }
  1524. bool Graphics::DefineVertex(const Vector3& vertex)
  1525. {
  1526. if ((!immediateBuffer_) || (immediateCurrentVertex_ >= immediateVertexCount_))
  1527. return false;
  1528. immediateDataPtr_ += immediateBuffer_->GetVertexSize();
  1529. ++immediateCurrentVertex_;
  1530. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_POSITION));
  1531. const float* src = vertex.GetData();
  1532. dest[0] = src[0];
  1533. dest[1] = src[1];
  1534. dest[2] = src[2];
  1535. return true;
  1536. }
  1537. bool Graphics::DefineNormal(const Vector3& normal)
  1538. {
  1539. if ((!immediateBuffer_) ||(!(immediateBuffer_->GetElementMask() & MASK_NORMAL)) || (!immediateCurrentVertex_))
  1540. return false;
  1541. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_NORMAL));
  1542. const float* src = normal.GetData();
  1543. dest[0] = src[0];
  1544. dest[1] = src[1];
  1545. dest[2] = src[2];
  1546. return true;
  1547. }
  1548. bool Graphics::DefineTexCoord(const Vector2& texCoord)
  1549. {
  1550. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_TEXCOORD1)) || (!immediateCurrentVertex_))
  1551. return false;
  1552. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_TEXCOORD1));
  1553. const float* src = texCoord.GetData();
  1554. dest[0] = src[0];
  1555. dest[1] = src[1];
  1556. return true;
  1557. }
  1558. bool Graphics::DefineColor(const Color& color)
  1559. {
  1560. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1561. return false;
  1562. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1563. *dest = color.ToUInt();
  1564. return true;
  1565. }
  1566. bool Graphics::DefineColor(unsigned color)
  1567. {
  1568. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1569. return false;
  1570. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1571. *dest = color;
  1572. return true;
  1573. }
  1574. void Graphics::EndImmediate()
  1575. {
  1576. if (immediateBuffer_)
  1577. {
  1578. immediateBuffer_->Unlock();
  1579. SetVertexBuffer(immediateBuffer_);
  1580. Draw(immediateType_, immediateStartPos_, immediateVertexCount_);
  1581. immediateBuffer_ = 0;
  1582. }
  1583. }
  1584. void Graphics::SetForceSM2(bool enable)
  1585. {
  1586. // Note: this only has effect before calling SetMode() for the first time
  1587. forceSM2_ = enable;
  1588. }
  1589. bool Graphics::IsInitialized() const
  1590. {
  1591. return (impl_->window_ != 0) && (impl_->GetDevice() != 0);
  1592. }
  1593. unsigned char* Graphics::GetImmediateDataPtr() const
  1594. {
  1595. if (!immediateBuffer_)
  1596. {
  1597. LOGERROR("Immediate draw operation not started");
  1598. return 0;
  1599. }
  1600. // Pointer was pre-decremented in BeginImmediate(). Undo that now
  1601. return immediateDataPtr_ + immediateBuffer_->GetVertexSize();
  1602. }
  1603. unsigned Graphics::GetWindowHandle() const
  1604. {
  1605. return (unsigned)impl_->window_;
  1606. }
  1607. std::vector<IntVector2> Graphics::GetResolutions() const
  1608. {
  1609. std::vector<IntVector2> ret;
  1610. if (!impl_->interface_)
  1611. return ret;
  1612. D3DFORMAT fullscreenFormat = impl_->GetDesktopFormat();
  1613. unsigned numModes = impl_->interface_->GetAdapterModeCount(impl_->adapter_, fullscreenFormat);
  1614. D3DDISPLAYMODE displayMode;
  1615. for (unsigned i = 0; i < numModes; ++i)
  1616. {
  1617. if (FAILED(impl_->interface_->EnumAdapterModes(impl_->adapter_, fullscreenFormat, i, &displayMode)))
  1618. continue;
  1619. if (displayMode.Format != fullscreenFormat)
  1620. continue;
  1621. IntVector2 newMode(displayMode.Width, displayMode.Height);
  1622. // Check for duplicate before storing
  1623. bool unique = true;
  1624. for (unsigned j = 0; j < ret.size(); ++j)
  1625. {
  1626. if (ret[j] == newMode)
  1627. {
  1628. unique = false;
  1629. break;
  1630. }
  1631. }
  1632. if (unique)
  1633. ret.push_back(newMode);
  1634. }
  1635. return ret;
  1636. }
  1637. std::vector<int> Graphics::GetMultiSampleLevels() const
  1638. {
  1639. std::vector<int> ret;
  1640. // No multisampling always supported
  1641. ret.push_back(0);
  1642. if (!impl_->interface_)
  1643. return ret;
  1644. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1645. {
  1646. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, D3DFMT_R8G8B8, FALSE,
  1647. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1648. ret.push_back(i);
  1649. }
  1650. return ret;
  1651. }
  1652. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1653. {
  1654. return index < MAX_VERTEX_STREAMS ? vertexBuffer_[index] : 0;
  1655. }
  1656. VSParameter Graphics::GetVSParameter(const std::string& name)
  1657. {
  1658. std::map<std::string, VSParameter>::iterator i = vsParameters_.find(name);
  1659. if (i != vsParameters_.end())
  1660. return i->second;
  1661. else
  1662. return MAX_VS_PARAMETERS;
  1663. }
  1664. PSParameter Graphics::GetPSParameter(const std::string& name)
  1665. {
  1666. std::map<std::string, PSParameter>::iterator i = psParameters_.find(name);
  1667. if (i != psParameters_.end())
  1668. return i->second;
  1669. else
  1670. return MAX_PS_PARAMETERS;
  1671. }
  1672. TextureUnit Graphics::GetTextureUnit(const std::string& name)
  1673. {
  1674. std::map<std::string, TextureUnit>::iterator i = textureUnits_.find(name);
  1675. if (i != textureUnits_.end())
  1676. return i->second;
  1677. else
  1678. return MAX_TEXTURE_UNITS;
  1679. }
  1680. const std::string& Graphics::GetVSParameterName(VSParameter parameter)
  1681. {
  1682. for (std::map<std::string, VSParameter>::iterator i = vsParameters_.begin(); i != vsParameters_.end(); ++i)
  1683. {
  1684. if (i->second == parameter)
  1685. return i->first;
  1686. }
  1687. return noParameter;
  1688. }
  1689. const std::string& Graphics::GetPSParameterName(PSParameter parameter)
  1690. {
  1691. for (std::map<std::string, PSParameter>::iterator i = psParameters_.begin(); i != psParameters_.end(); ++i)
  1692. {
  1693. if (i->second == parameter)
  1694. return i->first;
  1695. }
  1696. return noParameter;
  1697. }
  1698. const std::string& Graphics::GetTextureUnitName(TextureUnit unit)
  1699. {
  1700. for (std::map<std::string, TextureUnit>::iterator i = textureUnits_.begin(); i != textureUnits_.end(); ++i)
  1701. {
  1702. if (i->second == unit)
  1703. return i->first;
  1704. }
  1705. return noParameter;
  1706. }
  1707. Texture* Graphics::GetTexture(unsigned index) const
  1708. {
  1709. return index < MAX_TEXTURE_UNITS ? texture_[index] : 0;
  1710. }
  1711. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1712. {
  1713. return index < MAX_RENDERTARGETS ? renderTarget_[index] : 0;
  1714. }
  1715. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1716. {
  1717. return index < MAX_VERTEX_STREAMS ? streamFrequency_[index] : 0;
  1718. }
  1719. IntVector2 Graphics::GetRenderTargetDimensions() const
  1720. {
  1721. int width, height;
  1722. if (renderTarget_[0])
  1723. {
  1724. width = renderTarget_[0]->GetWidth();
  1725. height = renderTarget_[0]->GetHeight();
  1726. }
  1727. else
  1728. {
  1729. width = width_;
  1730. height = height_;
  1731. }
  1732. return IntVector2(width, height);
  1733. }
  1734. void Graphics::AddGPUObject(GPUObject* object)
  1735. {
  1736. gpuObjects_.push_back(object);
  1737. }
  1738. void Graphics::RemoveGPUObject(GPUObject* object)
  1739. {
  1740. for (std::vector<GPUObject*>::iterator i = gpuObjects_.begin(); i != gpuObjects_.end(); ++i)
  1741. {
  1742. if ((*i) == object)
  1743. {
  1744. gpuObjects_.erase(i);
  1745. return;
  1746. }
  1747. }
  1748. }
  1749. bool Graphics::OpenWindow(int width, int height)
  1750. {
  1751. WNDCLASS wc;
  1752. wc.style = CS_HREDRAW | CS_VREDRAW;
  1753. wc.lpfnWndProc = wndProc;
  1754. wc.cbClsExtra = 0;
  1755. wc.cbWndExtra = 0;
  1756. wc.hInstance = impl_->instance_;
  1757. wc.hIcon = LoadIcon(0, IDI_APPLICATION);
  1758. wc.hCursor = LoadCursor(0, IDC_ARROW);
  1759. wc.hbrBackground = 0;
  1760. wc.lpszMenuName = 0;
  1761. wc.lpszClassName = "D3DWindow";
  1762. RegisterClass(&wc);
  1763. RECT rect = {0, 0, width, height};
  1764. AdjustWindowRect(&rect, windowStyle, false);
  1765. impl_->window_ = CreateWindow("D3DWindow", windowTitle_.c_str(), windowStyle, CW_USEDEFAULT, CW_USEDEFAULT,
  1766. rect.right, rect.bottom, 0, 0, impl_->instance_, 0);
  1767. if (!impl_->window_)
  1768. {
  1769. LOGERROR("Could not create window");
  1770. return false;
  1771. }
  1772. SetWindowLongPtr(impl_->window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
  1773. // Save window placement
  1774. WINDOWPLACEMENT wndpl;
  1775. wndpl.length = sizeof wndpl;
  1776. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  1777. {
  1778. windowPosX_ = wndpl.rcNormalPosition.left;
  1779. windowPosY_ = wndpl.rcNormalPosition.top;
  1780. }
  1781. LOGINFO("Created application window");
  1782. return true;
  1783. }
  1784. bool Graphics::CreateInterface()
  1785. {
  1786. impl_->interface_ = Direct3DCreate9(D3D9b_SDK_VERSION);
  1787. if (!impl_->interface_)
  1788. {
  1789. LOGERROR("Could not create Direct3D9 interface");
  1790. return false;
  1791. }
  1792. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  1793. {
  1794. LOGERROR("Could not get Direct3D capabilities");
  1795. return false;
  1796. }
  1797. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  1798. {
  1799. LOGERROR("Could not get Direct3D adapter identifier");
  1800. return false;
  1801. }
  1802. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1803. {
  1804. LOGERROR("Shader model 2.0 display adapter is required");
  1805. return false;
  1806. }
  1807. // Check supported features: Shader Model 3, deferred / light prepass rendering, hardware depth texture, shadow map,
  1808. // dummy color surface, stream offset
  1809. if (!forceSM2_)
  1810. {
  1811. if ((impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0)) && (impl_->deviceCaps_.PixelShaderVersion >=
  1812. D3DPS_VERSION(3, 0)))
  1813. hasSM3_ = true;
  1814. }
  1815. if (impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1816. {
  1817. if (impl_->deviceCaps_.NumSimultaneousRTs >= 3)
  1818. deferredSupport_ = true;
  1819. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2)
  1820. prepassSupport_ = true;
  1821. }
  1822. // Prefer NVIDIA style hardware depth Compared shadow maps if available
  1823. shadowMapFormat_ = D3DFMT_D16;
  1824. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1825. {
  1826. hardwareShadowSupport_ = true;
  1827. // Check for hires depth support
  1828. hiresShadowMapFormat_ = D3DFMT_D24X8;
  1829. if (impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1830. hiresShadowSupport_ = true;
  1831. else
  1832. hiresShadowMapFormat_ = shadowMapFormat_;
  1833. }
  1834. else
  1835. {
  1836. // ATI DF16 format needs manual depth compare in the shader
  1837. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  1838. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1839. {
  1840. // Check for hires depth support
  1841. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  1842. if (impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1843. hiresShadowSupport_ = true;
  1844. else
  1845. hiresShadowMapFormat_ = shadowMapFormat_;
  1846. }
  1847. else
  1848. {
  1849. // No depth texture shadow map support -> no shadows at all
  1850. shadowMapFormat_ = D3DFMT_UNKNOWN;
  1851. hiresShadowMapFormat_ = D3DFMT_UNKNOWN;
  1852. }
  1853. }
  1854. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  1855. if (shadowMapFormat_ == D3DFMT_D16)
  1856. {
  1857. if ((impl_->adapterIdentifier_.VendorId == 0x8086) && (impl_->adapterIdentifier_.DeviceId == 0x2a42) &&
  1858. (impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL))
  1859. hardwareShadowSupport_ = false;
  1860. }
  1861. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  1862. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  1863. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1864. dummyColorFormat_ = nullFormat;
  1865. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1866. dummyColorFormat_ = D3DFMT_R16F;
  1867. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1868. dummyColorFormat_ = D3DFMT_R5G6B5;
  1869. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1870. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  1871. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  1872. streamOffsetSupport_ = true;
  1873. return true;
  1874. }
  1875. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1876. {
  1877. DWORD behaviorFlags = 0;
  1878. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1879. {
  1880. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1881. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1882. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1883. }
  1884. else
  1885. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1886. if (FAILED(impl_->interface_->CreateDevice(
  1887. adapter, // adapter
  1888. (D3DDEVTYPE)deviceType, // device type
  1889. impl_->window_, // window associated with device
  1890. behaviorFlags, // vertex processing
  1891. &impl_->presentParams_, // present parameters
  1892. &impl_->device_))) // return created device
  1893. {
  1894. LOGERROR("Could not create Direct3D9 device");
  1895. return false;
  1896. }
  1897. impl_->adapter_ = adapter;
  1898. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1899. OnDeviceReset();
  1900. LOGINFO("Created Direct3D9 device");
  1901. return true;
  1902. }
  1903. void Graphics::CreateRenderTargets()
  1904. {
  1905. if (mode_ != RENDER_FORWARD)
  1906. {
  1907. // In deferred rendering, the diffuse buffer stores diffuse albedo. In light prepass, it is used for light accumulation
  1908. if (!diffBuffer_)
  1909. {
  1910. diffBuffer_ = new Texture2D(context_);
  1911. diffBuffer_->SetSize(0, 0, D3DFMT_A8R8G8B8, TEXTURE_RENDERTARGET);
  1912. }
  1913. if (!normalBuffer_)
  1914. {
  1915. normalBuffer_ = new Texture2D(context_);
  1916. normalBuffer_->SetSize(0, 0, D3DFMT_A8R8G8B8, TEXTURE_RENDERTARGET);
  1917. }
  1918. if (!depthBuffer_)
  1919. {
  1920. depthBuffer_ = new Texture2D(context_);
  1921. depthBuffer_->SetSize(0, 0, D3DFMT_R32F, TEXTURE_RENDERTARGET);
  1922. }
  1923. // If deferred mode temporal AA is used, reserve screen buffers
  1924. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1925. // which will also be useful in forward rendering)
  1926. if (multiSample_)
  1927. {
  1928. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1929. {
  1930. screenBuffer_[i] = new Texture2D(context_);
  1931. screenBuffer_[i]->SetSize(0, 0, D3DFMT_A8R8G8B8, TEXTURE_RENDERTARGET);
  1932. }
  1933. }
  1934. else
  1935. {
  1936. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1937. screenBuffer_[i].Reset();
  1938. }
  1939. }
  1940. else
  1941. {
  1942. diffBuffer_.Reset();
  1943. normalBuffer_.Reset();
  1944. depthBuffer_.Reset();
  1945. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1946. screenBuffer_[i].Reset();
  1947. }
  1948. }
  1949. void Graphics::ResetDevice()
  1950. {
  1951. OnDeviceLost();
  1952. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  1953. {
  1954. deviceLost_ = false;
  1955. OnDeviceReset();
  1956. }
  1957. }
  1958. void Graphics::OnDeviceLost()
  1959. {
  1960. if (impl_->frameQuery_)
  1961. {
  1962. impl_->frameQuery_->Release();
  1963. impl_->frameQuery_ = 0;
  1964. }
  1965. if (impl_->defaultColorSurface_)
  1966. {
  1967. impl_->defaultColorSurface_->Release();
  1968. impl_->defaultColorSurface_ = 0;
  1969. }
  1970. if (impl_->defaultDepthStencilSurface_)
  1971. {
  1972. impl_->defaultDepthStencilSurface_->Release();
  1973. impl_->defaultDepthStencilSurface_ = 0;
  1974. }
  1975. for (unsigned i = 0; i < gpuObjects_.size(); ++i)
  1976. gpuObjects_[i]->OnDeviceLost();
  1977. }
  1978. void Graphics::OnDeviceReset()
  1979. {
  1980. ResetCachedState();
  1981. // Create frame query
  1982. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  1983. // Create deferred rendering buffers now
  1984. CreateRenderTargets();
  1985. for (unsigned i = 0; i < gpuObjects_.size(); ++i)
  1986. gpuObjects_[i]->OnDeviceReset();
  1987. // Get default surfaces
  1988. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  1989. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  1990. immediateBuffer_ = 0;
  1991. }
  1992. void Graphics::ResetCachedState()
  1993. {
  1994. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1995. {
  1996. vertexBuffer_[i] = 0;
  1997. streamOffset_[i] = 0;
  1998. }
  1999. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2000. {
  2001. texture_[i] = 0;
  2002. impl_->minMagFilter_[i] = D3DTEXF_POINT;
  2003. impl_->mipFilter_[i] = D3DTEXF_NONE;
  2004. impl_->uAddressMode_[i] = D3DTADDRESS_WRAP;
  2005. impl_->vAddressMode_[i] = D3DTADDRESS_WRAP;
  2006. impl_->borderColor_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2007. }
  2008. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2009. {
  2010. renderTarget_[i] = 0;
  2011. impl_->colorSurface_[i] = 0;
  2012. }
  2013. depthStencil_ = 0;
  2014. impl_->depthStencilSurface_ = 0;
  2015. viewport_ = IntRect(0, 0, width_, height_);
  2016. viewTexture_ = 0;
  2017. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2018. streamFrequency_[i] = 1;
  2019. indexBuffer_ = 0;
  2020. vertexDeclaration_ = 0;
  2021. vertexShader_ = 0;
  2022. pixelShader_ = 0;
  2023. blendMode_ = BLEND_REPLACE;
  2024. alphaTest_ = false;
  2025. alphaTestMode_ = CMP_ALWAYS;
  2026. alphaRef_ = 0.0f;
  2027. textureAnisotropy_ = 1;
  2028. colorWrite_ = true;
  2029. cullMode_ = CULL_CCW;
  2030. constantDepthBias_ = 0.0f;
  2031. slopeScaledDepthBias_ = 0.0f;
  2032. depthTestMode_ = CMP_LESSEQUAL;
  2033. depthWrite_ = true;
  2034. fillMode_ = FILL_SOLID;
  2035. scissorTest_ = false;
  2036. scissorRect_ = IntRect::ZERO;
  2037. stencilTest_ = false;
  2038. stencilTestMode_ = CMP_ALWAYS;
  2039. stencilPass_ = OP_KEEP;
  2040. stencilFail_ = OP_KEEP;
  2041. stencilZFail_ = OP_KEEP;
  2042. stencilRef_ = 0;
  2043. stencilMask_ = M_MAX_UNSIGNED;
  2044. impl_->blendEnable_ = FALSE;
  2045. impl_->srcBlend_ = D3DBLEND_ONE;
  2046. impl_->destBlend_ = D3DBLEND_ZERO;
  2047. queryIssued_ = false;
  2048. }
  2049. void Graphics::InitializeShaderParameters()
  2050. {
  2051. // Initialize all parameters as unknown
  2052. for (unsigned i = 0; i < MAX_VS_PARAMETERS; ++i)
  2053. vsRegisters_[i] = MAX_CONSTANT_REGISTERS;
  2054. for (unsigned i = 0; i < MAX_PS_PARAMETERS; ++i)
  2055. psRegisters_[i] = MAX_CONSTANT_REGISTERS;
  2056. // Map parameter names
  2057. vsParameters_["CameraPos"] = VSP_CAMERAPOS;
  2058. vsParameters_["CameraRot"] = VSP_CAMERAROT;
  2059. vsParameters_["DepthMode"] = VSP_DEPTHMODE;
  2060. vsParameters_["ElapsedTime"] = VSP_ELAPSEDTIME;
  2061. vsParameters_["FrustumSize"] = VSP_FRUSTUMSIZE;
  2062. vsParameters_["GBufferOffsets"] = VSP_GBUFFEROFFSETS;
  2063. vsParameters_["Model"] = VSP_MODEL;
  2064. vsParameters_["ShadowProj"] = VSP_SHADOWPROJ;
  2065. vsParameters_["SpotProj"] = VSP_SPOTPROJ;
  2066. vsParameters_["ViewProj"] = VSP_VIEWPROJ;
  2067. vsParameters_["UOffset"] = VSP_UOFFSET;
  2068. vsParameters_["VOffset"] = VSP_VOFFSET;
  2069. vsParameters_["ViewRightVector"] = VSP_VIEWRIGHTVECTOR;
  2070. vsParameters_["ViewUpVector"] = VSP_VIEWUPVECTOR;
  2071. vsParameters_["SkinMatrices"] = VSP_SKINMATRICES;
  2072. psParameters_["AmbientColor"] = PSP_AMBIENTCOLOR;
  2073. psParameters_["AntiAliasWeights"] = PSP_ANTIALIASWEIGHTS;
  2074. psParameters_["CameraPosPS"] = PSP_CAMERAPOS;
  2075. psParameters_["ElapsedTimePS"] = PSP_ELAPSEDTIME;
  2076. psParameters_["FogColor"] = PSP_FOGCOLOR;
  2077. psParameters_["FogParams"] = PSP_FOGPARAMS;
  2078. psParameters_["GBufferOffsetsPS"] = PSP_GBUFFEROFFSETS;
  2079. psParameters_["GBufferViewport"] = PSP_GBUFFERVIEWPORT;
  2080. psParameters_["LightAtten"] = PSP_LIGHTATTEN;
  2081. psParameters_["LightColor"] = PSP_LIGHTCOLOR;
  2082. psParameters_["LightDir"] = PSP_LIGHTDIR;
  2083. psParameters_["LightPos"] = PSP_LIGHTPOS;
  2084. psParameters_["LightSplits"] = PSP_LIGHTSPLITS;
  2085. psParameters_["LightVecRot"] = PSP_LIGHTVECROT;
  2086. psParameters_["MatDiffColor"] = PSP_MATDIFFCOLOR;
  2087. psParameters_["MatEmissiveColor"] = PSP_MATEMISSIVECOLOR;
  2088. psParameters_["MatSpecProperties"] = PSP_MATSPECPROPERTIES;
  2089. psParameters_["SampleOffsets"] = PSP_SAMPLEOFFSETS;
  2090. psParameters_["ShadowIntensity"] = PSP_SHADOWINTENSITY;
  2091. psParameters_["ShadowProjPS"] = PSP_SHADOWPROJ;
  2092. psParameters_["SpotProjPS"] = PSP_SPOTPROJ;
  2093. psParameters_["ViewProjPS"] = PSP_VIEWPROJ;
  2094. // Map texture units
  2095. textureUnits_["NormalMap"] = TU_NORMAL;
  2096. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2097. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2098. textureUnits_["SpecMap"] = TU_SPECULAR;
  2099. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2100. textureUnits_["DetailMap"] = TU_DETAIL;
  2101. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  2102. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  2103. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2104. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  2105. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  2106. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2107. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  2108. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2109. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2110. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2111. }
  2112. void Graphics::HandleWindowMessage(StringHash eventType, VariantMap& eventData)
  2113. {
  2114. using namespace WindowMessage;
  2115. if (eventData[P_WINDOW].GetInt() != (int)impl_->window_)
  2116. return;
  2117. switch (eventData[P_MSG].GetInt())
  2118. {
  2119. case WM_CLOSE:
  2120. Close();
  2121. eventData[P_HANDLED] = true;
  2122. break;
  2123. case WM_DESTROY:
  2124. eventData[P_HANDLED] = true;
  2125. break;
  2126. }
  2127. }
  2128. LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  2129. {
  2130. using namespace WindowMessage;
  2131. Graphics* graphics = reinterpret_cast<Graphics*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
  2132. if ((graphics) && (graphics->IsInitialized()))
  2133. {
  2134. VariantMap eventData;
  2135. eventData[P_WINDOW] = (int)hwnd;
  2136. eventData[P_MSG] = (int)msg;
  2137. eventData[P_WPARAM] = (int)wParam;
  2138. eventData[P_LPARAM] = (int)lParam;
  2139. eventData[P_HANDLED] = false;
  2140. graphics->SendEvent(E_WINDOWMESSAGE, eventData);
  2141. if (eventData[P_HANDLED].GetBool())
  2142. return 0;
  2143. }
  2144. return DefWindowProc(hwnd, msg, wParam, lParam);
  2145. }
  2146. void RegisterGraphicsLibrary(Context* context)
  2147. {
  2148. Animation::RegisterObject(context);
  2149. Material::RegisterObject(context);
  2150. Model::RegisterObject(context);
  2151. PixelShader::RegisterObject(context);
  2152. VertexShader::RegisterObject(context);
  2153. Technique::RegisterObject(context);
  2154. Texture2D::RegisterObject(context);
  2155. TextureCube::RegisterObject(context);
  2156. Camera::RegisterObject(context);
  2157. Drawable::RegisterObject(context);
  2158. Light::RegisterObject(context);
  2159. StaticModel::RegisterObject(context);
  2160. Skybox::RegisterObject(context);
  2161. AnimatedModel::RegisterObject(context);
  2162. AnimationController::RegisterObject(context);
  2163. BillboardSet::RegisterObject(context);
  2164. ParticleEmitter::RegisterObject(context);
  2165. DebugRenderer::RegisterObject(context);
  2166. Octree::RegisterObject(context);
  2167. Zone::RegisterObject(context);
  2168. }