Graphics.cpp 76 KB

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