OGLGraphics.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "AnimatedModel.h"
  25. #include "Animation.h"
  26. #include "AnimationController.h"
  27. #include "BillboardSet.h"
  28. #include "Camera.h"
  29. #include "Context.h"
  30. #include "DebugRenderer.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 "Mutex.h"
  38. #include "Octree.h"
  39. #include "ParticleEmitter.h"
  40. #include "ProcessUtils.h"
  41. #include "Profiler.h"
  42. #include "RenderSurface.h"
  43. #include "Shader.h"
  44. #include "ShaderProgram.h"
  45. #include "ShaderVariation.h"
  46. #include "Skybox.h"
  47. #include "StringUtils.h"
  48. #include "Technique.h"
  49. #include "Texture2D.h"
  50. #include "TextureCube.h"
  51. #include "VertexBuffer.h"
  52. #include "Zone.h"
  53. #include <stdio.h>
  54. #include "DebugNew.h"
  55. #ifdef GL_ES_VERSION_2_0
  56. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  57. #define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER
  58. #define GL_RENDERBUFFER_EXT GL_RENDERBUFFER
  59. #define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0
  60. #define GL_DEPTH_ATTACHMENT_EXT GL_DEPTH_ATTACHMENT
  61. #define GL_STENCIL_ATTACHMENT_EXT GL_STENCIL_ATTACHMENT
  62. #define GL_FRAMEBUFFER_COMPLETE_EXT GL_FRAMEBUFFER_COMPLETE
  63. #define glClearDepth glClearDepthf
  64. #define glBindFramebufferEXT glBindFramebuffer
  65. #define glFramebufferTexture2DEXT glFramebufferTexture2D
  66. #define glFramebufferRenderbufferEXT glFramebufferRenderbuffer
  67. #define glGenFramebuffersEXT glGenFramebuffers
  68. #define glDeleteFramebuffersEXT glDeleteFramebuffers
  69. #define glCheckFramebufferStatusEXT glCheckFramebufferStatus
  70. #endif
  71. static const unsigned glCmpFunc[] =
  72. {
  73. GL_ALWAYS,
  74. GL_EQUAL,
  75. GL_NOTEQUAL,
  76. GL_LESS,
  77. GL_LEQUAL,
  78. GL_GREATER,
  79. GL_GEQUAL
  80. };
  81. static const unsigned glSrcBlend[] =
  82. {
  83. GL_ONE,
  84. GL_ONE,
  85. GL_DST_COLOR,
  86. GL_SRC_ALPHA,
  87. GL_SRC_ALPHA,
  88. GL_ONE,
  89. GL_ONE_MINUS_DST_ALPHA
  90. };
  91. static const unsigned glDestBlend[] =
  92. {
  93. GL_ZERO,
  94. GL_ONE,
  95. GL_ZERO,
  96. GL_ONE_MINUS_SRC_ALPHA,
  97. GL_ONE,
  98. GL_ONE_MINUS_SRC_ALPHA,
  99. GL_DST_ALPHA
  100. };
  101. static const unsigned glStencilOps[] =
  102. {
  103. GL_KEEP,
  104. GL_ZERO,
  105. GL_REPLACE,
  106. GL_INCR_WRAP,
  107. GL_DECR_WRAP
  108. };
  109. static unsigned numInstances = 0;
  110. static const String noParameter;
  111. static const unsigned MAX_FRAMEBUFFER_AGE = 2000;
  112. OBJECTTYPESTATIC(Graphics);
  113. bool CheckExtension(const String& name)
  114. {
  115. String extensions((const char*)glGetString(GL_EXTENSIONS));
  116. return extensions.Find(name) != String::NPOS;
  117. }
  118. Graphics::Graphics(Context* context_) :
  119. Object(context_),
  120. impl_(new GraphicsImpl()),
  121. width_(0),
  122. height_(0),
  123. multiSample_(1),
  124. fullscreen_(false),
  125. vsync_(false),
  126. tripleBuffer_(false),
  127. lightPrepassSupport_(false),
  128. deferredSupport_(false),
  129. hardwareDepthSupport_(false),
  130. compressedTextureSupport_(false),
  131. numPrimitives_(0),
  132. numBatches_(0),
  133. defaultTextureFilterMode_(FILTER_BILINEAR),
  134. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  135. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  136. shaderParameterFrame_(0)
  137. {
  138. ResetCachedState();
  139. SetTextureUnitMappings();
  140. // If first instance in this process, initialize SDL under static mutex. Note that Graphics subsystem will also be in charge
  141. // of shutting down SDL as a whole, so it should be the last SDL-using subsystem (Audio and Input also use SDL) alive
  142. {
  143. MutexLock lock(GetStaticMutex());
  144. if (!numInstances)
  145. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE);
  146. ++numInstances;
  147. }
  148. }
  149. Graphics::~Graphics()
  150. {
  151. Close();
  152. delete impl_;
  153. impl_ = 0;
  154. // If last instance in this process, shut down SDL under static mutex
  155. {
  156. MutexLock lock(GetStaticMutex());
  157. --numInstances;
  158. if (!numInstances)
  159. SDL_Quit();
  160. }
  161. }
  162. void Graphics::SetWindowTitle(const String& windowTitle)
  163. {
  164. windowTitle_ = windowTitle;
  165. if (impl_->window_)
  166. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  167. }
  168. bool Graphics::SetMode(int width, int height, bool fullscreen, bool vsync, bool tripleBuffer, int multiSample)
  169. {
  170. PROFILE(SetScreenMode);
  171. multiSample = Clamp(multiSample, 1, 16);
  172. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  173. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  174. return true;
  175. // If only vsync changes, do not destroy/recreate the context
  176. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  177. tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  178. {
  179. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  180. vsync_ = vsync;
  181. return true;
  182. }
  183. // If zero dimensions in windowed mode, set default. If zero in fullscreen, use desktop mode
  184. if (!width || !height)
  185. {
  186. if (!fullscreen)
  187. {
  188. width = 800;
  189. height = 600;
  190. }
  191. else
  192. {
  193. SDL_DisplayMode mode;
  194. SDL_GetDesktopDisplayMode(0, &mode);
  195. width = mode.w;
  196. height = mode.h;
  197. }
  198. }
  199. // Close the existing window and OpenGL context, mark GPU objects as lost
  200. Release(false, true);
  201. {
  202. // SDL window parameters are static, so need to operate under static lock
  203. MutexLock lock(GetStaticMutex());
  204. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  205. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  206. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  207. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  208. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  209. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  210. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  211. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  212. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  213. if (multiSample > 1)
  214. {
  215. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  216. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  217. }
  218. else
  219. {
  220. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  221. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  222. }
  223. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  224. int x = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  225. int y = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  226. if (fullscreen)
  227. flags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
  228. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  229. if (!impl_->window_)
  230. {
  231. LOGERROR("Could not open window");
  232. return false;
  233. }
  234. impl_->context_ = SDL_GL_CreateContext(impl_->window_);
  235. if (!impl_->context_)
  236. {
  237. LOGERROR("Could not create OpenGL context");
  238. return false;
  239. }
  240. // If OpenGL extensions not yet initialized, initialize now
  241. #ifndef GL_ES_VERSION_2_0
  242. if (!GLeeInitialized())
  243. GLeeInit();
  244. if (!_GLEE_VERSION_2_0)
  245. {
  246. LOGERROR("OpenGL 2.0 is required");
  247. Release(true, true);
  248. return false;
  249. }
  250. if (!CheckExtension("EXT_framebuffer_object") || !CheckExtension("EXT_packed_depth_stencil") ||
  251. !CheckExtension("EXT_texture_filter_anisotropic"))
  252. {
  253. LOGERROR("EXT_framebuffer_object, EXT_packed_depth_stencil and "
  254. "EXT_texture_filter_anisotropic OpenGL extensions are required");
  255. Release(true, true);
  256. return false;
  257. }
  258. #endif
  259. compressedTextureSupport_ = CheckExtension("EXT_texture_compression_s3tc");
  260. }
  261. // Set vsync
  262. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  263. // Query for system backbuffer depth
  264. glGetIntegerv(GL_DEPTH_BITS, &impl_->windowDepthBits_);
  265. impl_->depthBits_ = impl_->windowDepthBits_;
  266. // Set initial state to match Direct3D
  267. glEnable(GL_DEPTH_TEST);
  268. SetCullMode(CULL_CCW);
  269. SetDepthTest(CMP_LESSEQUAL);
  270. SDL_GetWindowSize(impl_->window_, &width_, &height_);
  271. fullscreen_ = fullscreen;
  272. vsync_ = vsync;
  273. tripleBuffer_ = tripleBuffer;
  274. multiSample_ = multiSample;
  275. // Reset rendertargets and viewport for the new screen mode
  276. ResetRenderTargets();
  277. // Clear the window to black now, because GPU object restore may take time
  278. Clear(CLEAR_COLOR);
  279. SDL_GL_SwapWindow(impl_->window_);
  280. // Let GPU objects restore themselves
  281. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  282. (*i)->OnDeviceReset();
  283. CheckFeatureSupport();
  284. if (multiSample > 1)
  285. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  286. " multisample " + String(multiSample));
  287. else
  288. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  289. using namespace ScreenMode;
  290. VariantMap eventData;
  291. eventData[P_WIDTH] = width_;
  292. eventData[P_HEIGHT] = height_;
  293. eventData[P_FULLSCREEN] = fullscreen_;
  294. SendEvent(E_SCREENMODE, eventData);
  295. return true;
  296. }
  297. bool Graphics::SetMode(int width, int height)
  298. {
  299. return SetMode(width, height, fullscreen_, vsync_, tripleBuffer_, multiSample_);
  300. }
  301. bool Graphics::ToggleFullscreen()
  302. {
  303. return SetMode(width_, height_, !fullscreen_, vsync_, tripleBuffer_, multiSample_);
  304. }
  305. void Graphics::Close()
  306. {
  307. if (!IsInitialized())
  308. return;
  309. // Actually close the window
  310. Release(true, true);
  311. }
  312. bool Graphics::TakeScreenShot(Image& destImage)
  313. {
  314. PROFILE(TakeScreenShot);
  315. ResetRenderTargets();
  316. destImage.SetSize(width_, height_, 3);
  317. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  318. return true;
  319. }
  320. bool Graphics::BeginFrame()
  321. {
  322. if (!IsInitialized())
  323. return false;
  324. // If we should be fullscreen, but are not currently active, do not render
  325. if (fullscreen_ && (SDL_GetWindowFlags(impl_->window_) & SDL_WINDOW_MINIMIZED))
  326. return false;
  327. // Set default rendertarget and depth buffer
  328. ResetRenderTargets();
  329. // Cleanup textures from previous frame
  330. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  331. SetTexture(i, 0);
  332. // Enable color and depth write
  333. SetColorWrite(true);
  334. SetDepthWrite(true);
  335. numPrimitives_ = 0;
  336. numBatches_ = 0;
  337. SendEvent(E_BEGINRENDERING);
  338. return true;
  339. }
  340. void Graphics::EndFrame()
  341. {
  342. if (!IsInitialized())
  343. return;
  344. PROFILE(Present);
  345. SendEvent(E_ENDRENDERING);
  346. SDL_GL_SwapWindow(impl_->window_);
  347. // Clean up FBO's that have not been used for a long time
  348. CleanupFramebuffers(false);
  349. }
  350. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  351. {
  352. if (impl_->fboDirty_)
  353. CommitFramebuffer();
  354. bool oldColorWrite = colorWrite_;
  355. bool oldDepthWrite = depthWrite_;
  356. if (flags & CLEAR_COLOR && !oldColorWrite)
  357. SetColorWrite(true);
  358. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  359. SetDepthWrite(true);
  360. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  361. glStencilMask(M_MAX_UNSIGNED);
  362. unsigned glFlags = 0;
  363. if (flags & CLEAR_COLOR)
  364. {
  365. glFlags |= GL_COLOR_BUFFER_BIT;
  366. glClearColor(color.r_, color.g_, color.b_, color.a_);
  367. }
  368. if (flags & CLEAR_DEPTH)
  369. {
  370. glFlags |= GL_DEPTH_BUFFER_BIT;
  371. glClearDepth(depth);
  372. }
  373. if (flags & CLEAR_STENCIL)
  374. {
  375. glFlags |= GL_STENCIL_BUFFER_BIT;
  376. glClearStencil(stencil);
  377. }
  378. // If viewport is less than full screen, set a scissor to limit the clear
  379. /// \todo Any user-set scissor test will be lost
  380. IntVector2 viewSize = GetRenderTargetDimensions();
  381. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  382. SetScissorTest(true, IntRect(0, 0, viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_));
  383. else
  384. SetScissorTest(false);
  385. glClear(glFlags);
  386. SetScissorTest(false);
  387. SetColorWrite(oldColorWrite);
  388. SetDepthWrite(oldDepthWrite);
  389. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  390. glStencilMask(stencilWriteMask_);
  391. }
  392. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  393. {
  394. if (!destination || !destination->GetRenderSurface() || destination->GetWidth() != width_ ||
  395. destination->GetHeight() != height_)
  396. return false;
  397. IntRect vpCopy = viewport;
  398. if (vpCopy.right_ <= vpCopy.left_)
  399. vpCopy.right_ = vpCopy.left_ + 1;
  400. if (vpCopy.bottom_ <= vpCopy.top_)
  401. vpCopy.bottom_ = vpCopy.top_ + 1;
  402. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  403. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  404. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  405. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  406. // Make sure the FBO is not in use
  407. ResetRenderTargets();
  408. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  409. SetTextureForUpdate(destination);
  410. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.left_, height_ - vpCopy.bottom_,
  411. vpCopy.right_ - vpCopy.left_, vpCopy.bottom_ - vpCopy.top_);
  412. SetTexture(0, 0);
  413. return true;
  414. }
  415. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  416. {
  417. if (!vertexCount)
  418. return;
  419. if (impl_->fboDirty_)
  420. CommitFramebuffer();
  421. unsigned primitiveCount = 0;
  422. switch (type)
  423. {
  424. case TRIANGLE_LIST:
  425. primitiveCount = vertexCount / 3;
  426. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  427. break;
  428. case LINE_LIST:
  429. primitiveCount = vertexCount / 2;
  430. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  431. break;
  432. }
  433. numPrimitives_ += primitiveCount;
  434. ++numBatches_;
  435. }
  436. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  437. {
  438. if (!indexCount || !indexBuffer_)
  439. return;
  440. if (impl_->fboDirty_)
  441. CommitFramebuffer();
  442. unsigned primitiveCount = 0;
  443. unsigned indexSize = indexBuffer_->GetIndexSize();
  444. switch (type)
  445. {
  446. case TRIANGLE_LIST:
  447. primitiveCount = indexCount / 3;
  448. if (indexSize == sizeof(unsigned short))
  449. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  450. else
  451. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  452. break;
  453. case LINE_LIST:
  454. primitiveCount = indexCount / 2;
  455. if (indexSize == sizeof(unsigned short))
  456. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  457. else
  458. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  459. break;
  460. }
  461. numPrimitives_ += primitiveCount;
  462. ++numBatches_;
  463. }
  464. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  465. {
  466. }
  467. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  468. {
  469. Vector<VertexBuffer*> vertexBuffers(1);
  470. PODVector<unsigned> elementMasks(1);
  471. vertexBuffers[0] = buffer;
  472. elementMasks[0] = MASK_DEFAULT;
  473. SetVertexBuffers(vertexBuffers, elementMasks);
  474. }
  475. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  476. unsigned instanceOffset)
  477. {
  478. if (buffers.Size() > MAX_VERTEX_STREAMS)
  479. {
  480. LOGERROR("Too many vertex buffers");
  481. return false;
  482. }
  483. if (buffers.Size() != elementMasks.Size())
  484. {
  485. LOGERROR("Amount of element masks and vertex buffers does not match");
  486. return false;
  487. }
  488. bool changed = false;
  489. unsigned newAttributes = 0;
  490. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  491. {
  492. VertexBuffer* buffer = 0;
  493. unsigned elementMask = 0;
  494. if (i < buffers.Size() && buffers[i])
  495. {
  496. buffer = buffers[i];
  497. if (elementMasks[i] == MASK_DEFAULT)
  498. elementMask = buffer->GetElementMask();
  499. else
  500. elementMask = buffer->GetElementMask() & elementMasks[i];
  501. }
  502. // If buffer and element mask have stayed the same, skip to the next buffer
  503. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && !changed)
  504. continue;
  505. vertexBuffers_[i] = buffer;
  506. elementMasks_[i] = elementMask;
  507. changed = true;
  508. if (!buffer)
  509. continue;
  510. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  511. unsigned vertexSize = buffer->GetVertexSize();
  512. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  513. {
  514. unsigned elementBit = 1 << j;
  515. if (elementMask & elementBit)
  516. {
  517. newAttributes |= elementBit;
  518. // Enable attribute if not enabled yet
  519. if ((impl_->enabledAttributes_ & elementBit) == 0)
  520. {
  521. glEnableVertexAttribArray(j);
  522. impl_->enabledAttributes_ |= elementBit;
  523. }
  524. // Set the attribute pointer
  525. glVertexAttribPointer(j, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  526. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  527. }
  528. }
  529. }
  530. if (!changed)
  531. return true;
  532. // Now check which vertex attributes should be disabled
  533. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  534. int disableIndex = 0;
  535. while (disableAttributes)
  536. {
  537. if (disableAttributes & 1)
  538. {
  539. glDisableVertexAttribArray(disableIndex);
  540. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  541. }
  542. disableAttributes >>= 1;
  543. ++disableIndex;
  544. }
  545. return true;
  546. }
  547. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  548. elementMasks, unsigned instanceOffset)
  549. {
  550. if (buffers.Size() > MAX_VERTEX_STREAMS)
  551. {
  552. LOGERROR("Too many vertex buffers");
  553. return false;
  554. }
  555. if (buffers.Size() != elementMasks.Size())
  556. {
  557. LOGERROR("Amount of element masks and vertex buffers does not match");
  558. return false;
  559. }
  560. bool changed = false;
  561. unsigned newAttributes = 0;
  562. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  563. {
  564. VertexBuffer* buffer = 0;
  565. unsigned elementMask = 0;
  566. if (i < buffers.Size() && buffers[i])
  567. {
  568. buffer = buffers[i];
  569. if (elementMasks[i] == MASK_DEFAULT)
  570. elementMask = buffer->GetElementMask();
  571. else
  572. elementMask = buffer->GetElementMask() & elementMasks[i];
  573. }
  574. // If buffer and element mask have stayed the same, skip to the next buffer
  575. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && !changed)
  576. continue;
  577. vertexBuffers_[i] = buffer;
  578. elementMasks_[i] = elementMask;
  579. changed = true;
  580. if (!buffer)
  581. continue;
  582. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  583. unsigned vertexSize = buffer->GetVertexSize();
  584. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  585. {
  586. unsigned elementBit = 1 << j;
  587. if (elementMask & elementBit)
  588. {
  589. newAttributes |= elementBit;
  590. // Enable attribute if not enabled yet
  591. if ((impl_->enabledAttributes_ & elementBit) == 0)
  592. {
  593. glEnableVertexAttribArray(j);
  594. impl_->enabledAttributes_ |= elementBit;
  595. }
  596. // Set the attribute pointer
  597. glVertexAttribPointer(j, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  598. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  599. }
  600. }
  601. }
  602. if (!changed)
  603. return true;
  604. // Now check which vertex attributes should be disabled
  605. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  606. int disableIndex = 0;
  607. while (disableAttributes)
  608. {
  609. if (disableAttributes & 1)
  610. {
  611. glDisableVertexAttribArray(disableIndex);
  612. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  613. }
  614. disableAttributes >>= 1;
  615. ++disableIndex;
  616. }
  617. return true;
  618. }
  619. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  620. {
  621. if (indexBuffer_ == buffer)
  622. return;
  623. if (buffer)
  624. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  625. else
  626. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  627. indexBuffer_ = buffer;
  628. }
  629. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  630. {
  631. if (vs == vertexShader_ && ps == pixelShader_)
  632. return;
  633. ClearParameterSources();
  634. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  635. if (vs && !vs->IsCompiled())
  636. {
  637. if (vs->GetCompilerOutput().Empty())
  638. {
  639. PROFILE(CompileVertexShader);
  640. bool success = vs->Create();
  641. if (success)
  642. LOGDEBUG("Compiled vertex shader " + vs->GetName());
  643. else
  644. {
  645. LOGERROR("Failed to compile vertex shader " + vs->GetName() + ":\n" + vs->GetCompilerOutput());
  646. vs = 0;
  647. }
  648. }
  649. else
  650. vs = 0;
  651. }
  652. if (ps && !ps->IsCompiled())
  653. {
  654. if (ps->GetCompilerOutput().Empty())
  655. {
  656. PROFILE(CompilePixelShader);
  657. bool success = ps->Create();
  658. if (success)
  659. LOGDEBUG("Compiled pixel shader " + ps->GetName());
  660. else
  661. {
  662. LOGERROR("Failed to compile pixel shader " + ps->GetName() + ":\n" + ps->GetCompilerOutput());
  663. ps = 0;
  664. }
  665. }
  666. else
  667. ps = 0;
  668. }
  669. if (!vs || !ps)
  670. {
  671. glUseProgram(0);
  672. vertexShader_ = 0;
  673. pixelShader_ = 0;
  674. shaderProgram_ = 0;
  675. }
  676. else
  677. {
  678. vertexShader_ = vs;
  679. pixelShader_ = ps;
  680. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  681. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  682. if (i != shaderPrograms_.End())
  683. {
  684. // Use the existing linked program
  685. if (i->second_->IsLinked())
  686. {
  687. glUseProgram(i->second_->GetGPUObject());
  688. shaderProgram_ = i->second_;
  689. }
  690. else
  691. {
  692. glUseProgram(0);
  693. shaderProgram_ = 0;
  694. }
  695. }
  696. else
  697. {
  698. // Link a new combination
  699. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  700. if (newProgram->Link())
  701. {
  702. LOGDEBUG("Linked vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName());
  703. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  704. // so it is not necessary to call it again
  705. shaderProgram_ = newProgram;
  706. }
  707. else
  708. {
  709. LOGERROR("Failed to link vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName() + ":\n" +
  710. newProgram->GetLinkerOutput());
  711. glUseProgram(0);
  712. shaderProgram_ = 0;
  713. }
  714. shaderPrograms_[combination] = newProgram;
  715. }
  716. }
  717. }
  718. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  719. {
  720. if (shaderProgram_)
  721. {
  722. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  723. if (info)
  724. {
  725. switch (info->type_)
  726. {
  727. case GL_FLOAT:
  728. glUniform1fv(info->location_, count, data);
  729. break;
  730. case GL_FLOAT_VEC2:
  731. glUniform2fv(info->location_, count / 2, data);
  732. break;
  733. case GL_FLOAT_VEC3:
  734. glUniform3fv(info->location_, count / 3, data);
  735. break;
  736. case GL_FLOAT_VEC4:
  737. glUniform4fv(info->location_, count / 4, data);
  738. break;
  739. case GL_FLOAT_MAT3:
  740. #ifndef GL_ES_VERSION_2_0
  741. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  742. #else
  743. {
  744. for (unsigned i = 0; i < count; i += 9)
  745. {
  746. Matrix3 matrix(&data[i]);
  747. glUniformMatrix3fv(info->location_ + i / 9, 1, GL_FALSE, matrix.Transpose().Data());
  748. }
  749. }
  750. #endif
  751. break;
  752. case GL_FLOAT_MAT4:
  753. #ifndef GL_ES_VERSION_2_0
  754. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  755. #else
  756. {
  757. for (unsigned i = 0; i < count; i += 16)
  758. {
  759. Matrix4 matrix(&data[i]);
  760. glUniformMatrix4fv(info->location_ + i / 16, 1, GL_FALSE, matrix.Transpose().Data());
  761. }
  762. }
  763. #endif
  764. break;
  765. }
  766. }
  767. }
  768. }
  769. void Graphics::SetShaderParameter(StringHash param, float value)
  770. {
  771. if (shaderProgram_)
  772. {
  773. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  774. if (info)
  775. glUniform1fv(info->location_, 1, &value);
  776. }
  777. }
  778. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  779. {
  780. SetShaderParameter(param, color.Data(), 4);
  781. }
  782. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  783. {
  784. if (shaderProgram_)
  785. {
  786. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  787. if (info)
  788. {
  789. #ifndef GL_ES_VERSION_2_0
  790. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.Data());
  791. #else
  792. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  793. #endif
  794. }
  795. }
  796. }
  797. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  798. {
  799. if (shaderProgram_)
  800. {
  801. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  802. if (info)
  803. {
  804. // Check the uniform type to avoid mismatch
  805. switch (info->type_)
  806. {
  807. case GL_FLOAT:
  808. glUniform1fv(info->location_, 1, vector.Data());
  809. break;
  810. case GL_FLOAT_VEC2:
  811. glUniform2fv(info->location_, 1, vector.Data());
  812. break;
  813. case GL_FLOAT_VEC3:
  814. glUniform3fv(info->location_, 1, vector.Data());
  815. break;
  816. }
  817. }
  818. }
  819. }
  820. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  821. {
  822. if (shaderProgram_)
  823. {
  824. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  825. if (info)
  826. {
  827. #ifndef GL_ES_VERSION_2_0
  828. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.Data());
  829. #else
  830. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  831. #endif
  832. }
  833. }
  834. }
  835. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  836. {
  837. if (shaderProgram_)
  838. {
  839. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  840. if (info)
  841. {
  842. // Check the uniform type to avoid mismatch
  843. switch (info->type_)
  844. {
  845. case GL_FLOAT:
  846. glUniform1fv(info->location_, 1, vector.Data());
  847. break;
  848. case GL_FLOAT_VEC2:
  849. glUniform2fv(info->location_, 1, vector.Data());
  850. break;
  851. case GL_FLOAT_VEC3:
  852. glUniform3fv(info->location_, 1, vector.Data());
  853. break;
  854. case GL_FLOAT_VEC4:
  855. glUniform4fv(info->location_, 1, vector.Data());
  856. break;
  857. }
  858. }
  859. }
  860. }
  861. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  862. {
  863. if (shaderProgram_)
  864. {
  865. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  866. if (info)
  867. {
  868. float data[16];
  869. data[0] = matrix.m00_;
  870. data[1] = matrix.m10_;
  871. data[2] = matrix.m20_;
  872. data[3] = 0.0f;
  873. data[4] = matrix.m01_;
  874. data[5] = matrix.m11_;
  875. data[6] = matrix.m21_;
  876. data[7] = 0.0f;
  877. data[8] = matrix.m02_;
  878. data[9] = matrix.m12_;
  879. data[10] = matrix.m22_;
  880. data[11] = 0.0f;
  881. data[12] = matrix.m03_;
  882. data[13] = matrix.m13_;
  883. data[14] = matrix.m23_;
  884. data[15] = 1.0f;
  885. glUniformMatrix4fv(info->location_, 1, GL_FALSE, data);
  886. }
  887. }
  888. }
  889. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  890. {
  891. if ((unsigned)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  892. {
  893. shaderParameterSources_[group] = source;
  894. return true;
  895. }
  896. else
  897. return false;
  898. }
  899. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  900. {
  901. return shaderProgram_ && shaderProgram_->HasParameter(param);
  902. }
  903. bool Graphics::HasTextureUnit(TextureUnit unit)
  904. {
  905. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  906. }
  907. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  908. {
  909. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  910. }
  911. void Graphics::ClearParameterSources()
  912. {
  913. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  914. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  915. }
  916. void Graphics::ClearTransformSources()
  917. {
  918. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  919. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  920. }
  921. void Graphics::CleanupShaderPrograms()
  922. {
  923. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  924. {
  925. ShaderProgramMap::Iterator current = i++;
  926. ShaderVariation* vs = current->second_->GetVertexShader();
  927. ShaderVariation* ps = current->second_->GetPixelShader();
  928. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  929. shaderPrograms_.Erase(current);
  930. }
  931. }
  932. void Graphics::SetTexture(unsigned index, Texture* texture)
  933. {
  934. if (index >= MAX_TEXTURE_UNITS)
  935. return;
  936. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  937. if (texture)
  938. {
  939. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  940. texture = texture->GetBackupTexture();
  941. }
  942. if (textures_[index] != texture)
  943. {
  944. if (impl_->activeTexture_ != index)
  945. {
  946. glActiveTexture(GL_TEXTURE0 + index);
  947. impl_->activeTexture_ = index;
  948. }
  949. if (texture)
  950. {
  951. unsigned glType = texture->GetTarget();
  952. if (glType != textureTypes_[index])
  953. {
  954. if (textureTypes_[index])
  955. glDisable(textureTypes_[index]);
  956. glEnable(glType);
  957. textureTypes_[index] = glType;
  958. }
  959. glBindTexture(glType, texture->GetGPUObject());
  960. if (texture->GetParametersDirty())
  961. texture->UpdateParameters();
  962. }
  963. else
  964. {
  965. if (textureTypes_[index])
  966. glBindTexture(textureTypes_[index], 0);
  967. }
  968. textures_[index] = texture;
  969. }
  970. else
  971. {
  972. if (texture && texture->GetParametersDirty())
  973. {
  974. if (impl_->activeTexture_ != index)
  975. {
  976. glActiveTexture(GL_TEXTURE0 + index);
  977. impl_->activeTexture_ = index;
  978. }
  979. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  980. texture->UpdateParameters();
  981. }
  982. }
  983. }
  984. void Graphics::SetTextureForUpdate(Texture* texture)
  985. {
  986. if (impl_->activeTexture_ != 0)
  987. {
  988. glActiveTexture(GL_TEXTURE0);
  989. impl_->activeTexture_ = 0;
  990. }
  991. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  992. textures_[0] = texture;
  993. }
  994. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  995. {
  996. if (mode != defaultTextureFilterMode_)
  997. {
  998. defaultTextureFilterMode_ = mode;
  999. SetTextureParametersDirty();
  1000. }
  1001. }
  1002. void Graphics::SetTextureAnisotropy(unsigned level)
  1003. {
  1004. if (level != textureAnisotropy_)
  1005. {
  1006. textureAnisotropy_ = level;
  1007. SetTextureParametersDirty();
  1008. }
  1009. }
  1010. void Graphics::SetTextureParametersDirty()
  1011. {
  1012. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1013. {
  1014. Texture* texture = dynamic_cast<Texture*>(*i);
  1015. if (texture)
  1016. texture->SetParametersDirty();
  1017. }
  1018. }
  1019. void Graphics::ResetRenderTargets()
  1020. {
  1021. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1022. SetRenderTarget(i, (RenderSurface*)0);
  1023. SetDepthStencil((RenderSurface*)0);
  1024. SetViewport(IntRect(0, 0, width_, height_));
  1025. }
  1026. void Graphics::ResetRenderTarget(unsigned index)
  1027. {
  1028. SetRenderTarget(index, (RenderSurface*)0);
  1029. }
  1030. void Graphics::ResetDepthStencil()
  1031. {
  1032. SetDepthStencil((RenderSurface*)0);
  1033. }
  1034. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1035. {
  1036. if (index >= MAX_RENDERTARGETS)
  1037. return;
  1038. if (renderTarget != renderTargets_[index])
  1039. {
  1040. renderTargets_[index] = renderTarget;
  1041. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1042. if (renderTarget)
  1043. {
  1044. Texture* parentTexture = renderTarget->GetParentTexture();
  1045. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1046. {
  1047. if (textures_[i] == parentTexture)
  1048. SetTexture(i, textures_[i]->GetBackupTexture());
  1049. }
  1050. }
  1051. impl_->fboDirty_ = true;
  1052. }
  1053. }
  1054. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1055. {
  1056. RenderSurface* renderTarget = 0;
  1057. if (texture)
  1058. renderTarget = texture->GetRenderSurface();
  1059. SetRenderTarget(index, renderTarget);
  1060. }
  1061. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1062. {
  1063. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1064. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1065. if (renderTargets_[0] && !depthStencil)
  1066. {
  1067. int width = renderTargets_[0]->GetWidth();
  1068. int height = renderTargets_[0]->GetHeight();
  1069. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1070. // Check size similarly
  1071. if (width <= width_ && height <= height_)
  1072. {
  1073. int searchKey = (width << 16) | height;
  1074. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1075. if (i != depthTextures_.End())
  1076. depthStencil = i->second_->GetRenderSurface();
  1077. else
  1078. {
  1079. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1080. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1081. depthTextures_[searchKey] = newDepthTexture;
  1082. depthStencil = newDepthTexture->GetRenderSurface();
  1083. }
  1084. }
  1085. }
  1086. if (depthStencil != depthStencil_)
  1087. {
  1088. depthStencil_ = depthStencil;
  1089. impl_->fboDirty_ = true;
  1090. }
  1091. }
  1092. void Graphics::SetDepthStencil(Texture2D* texture)
  1093. {
  1094. RenderSurface* depthStencil = 0;
  1095. if (texture)
  1096. depthStencil = texture->GetRenderSurface();
  1097. SetDepthStencil(depthStencil);
  1098. }
  1099. void Graphics::SetViewTexture(Texture* texture)
  1100. {
  1101. viewTexture_ = texture;
  1102. if (viewTexture_)
  1103. {
  1104. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1105. {
  1106. if (textures_[i] == viewTexture_)
  1107. SetTexture(i, textures_[i]->GetBackupTexture());
  1108. }
  1109. }
  1110. }
  1111. void Graphics::SetViewport(const IntRect& rect)
  1112. {
  1113. if (impl_->fboDirty_)
  1114. CommitFramebuffer();
  1115. IntVector2 rtSize = GetRenderTargetDimensions();
  1116. IntRect rectCopy = rect;
  1117. if (rectCopy.right_ <= rectCopy.left_)
  1118. rectCopy.right_ = rectCopy.left_ + 1;
  1119. if (rectCopy.bottom_ <= rectCopy.top_)
  1120. rectCopy.bottom_ = rectCopy.top_ + 1;
  1121. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1122. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1123. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1124. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1125. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1126. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1127. viewport_ = rectCopy;
  1128. // Disable scissor test, needs to be re-enabled by the user
  1129. SetScissorTest(false);
  1130. }
  1131. void Graphics::SetBlendMode(BlendMode mode)
  1132. {
  1133. if (mode != blendMode_)
  1134. {
  1135. if (mode == BLEND_REPLACE)
  1136. glDisable(GL_BLEND);
  1137. else
  1138. {
  1139. glEnable(GL_BLEND);
  1140. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1141. }
  1142. blendMode_ = mode;
  1143. }
  1144. }
  1145. void Graphics::SetColorWrite(bool enable)
  1146. {
  1147. if (enable != colorWrite_)
  1148. {
  1149. if (enable)
  1150. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1151. else
  1152. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1153. colorWrite_ = enable;
  1154. }
  1155. }
  1156. void Graphics::SetCullMode(CullMode mode)
  1157. {
  1158. if (mode != cullMode_)
  1159. {
  1160. if (mode == CULL_NONE)
  1161. glDisable(GL_CULL_FACE);
  1162. else
  1163. {
  1164. // Use Direct3D convention, ie. clockwise vertices define a front face
  1165. glEnable(GL_CULL_FACE);
  1166. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1167. }
  1168. cullMode_ = mode;
  1169. }
  1170. }
  1171. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1172. {
  1173. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1174. {
  1175. if (constantBias != 0.0f || slopeScaledBias != 0.0f)
  1176. {
  1177. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1178. // Zero depth bits may be returned if using the packed depth-stencil format. Assume 24bit in that case
  1179. #ifndef GL_ES_VERSION_2_0
  1180. int depthBits = Min(impl_->depthBits_, 23);
  1181. if (!depthBits)
  1182. depthBits = 23;
  1183. #else
  1184. int depthBits = 25;
  1185. #endif
  1186. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1187. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1188. glEnable(GL_POLYGON_OFFSET_FILL);
  1189. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1190. }
  1191. else
  1192. glDisable(GL_POLYGON_OFFSET_FILL);
  1193. constantDepthBias_ = constantBias;
  1194. slopeScaledDepthBias_ = slopeScaledBias;
  1195. }
  1196. }
  1197. void Graphics::SetDepthTest(CompareMode mode)
  1198. {
  1199. if (mode != depthTestMode_)
  1200. {
  1201. glDepthFunc(glCmpFunc[mode]);
  1202. depthTestMode_ = mode;
  1203. }
  1204. }
  1205. void Graphics::SetDepthWrite(bool enable)
  1206. {
  1207. if (enable != depthWrite_)
  1208. {
  1209. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1210. depthWrite_ = enable;
  1211. }
  1212. }
  1213. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1214. {
  1215. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1216. // Disable scissor in that case to reduce state changes
  1217. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1218. enable = false;
  1219. if (enable)
  1220. {
  1221. IntVector2 rtSize(GetRenderTargetDimensions());
  1222. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1223. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1224. IntRect intRect;
  1225. int expand = borderInclusive ? 1 : 0;
  1226. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1227. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1228. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1229. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1230. if (intRect.right_ == intRect.left_)
  1231. intRect.right_++;
  1232. if (intRect.bottom_ == intRect.top_)
  1233. intRect.bottom_++;
  1234. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1235. enable = false;
  1236. if (enable && scissorRect_ != intRect)
  1237. {
  1238. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1239. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1240. scissorRect_ = intRect;
  1241. }
  1242. }
  1243. else
  1244. scissorRect_ = IntRect::ZERO;
  1245. if (enable != scissorTest_)
  1246. {
  1247. if (enable)
  1248. glEnable(GL_SCISSOR_TEST);
  1249. else
  1250. glDisable(GL_SCISSOR_TEST);
  1251. scissorTest_ = enable;
  1252. }
  1253. }
  1254. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1255. {
  1256. IntVector2 rtSize(GetRenderTargetDimensions());
  1257. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1258. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1259. if (enable)
  1260. {
  1261. IntRect intRect;
  1262. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1263. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1264. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1265. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1266. if (intRect.right_ == intRect.left_)
  1267. intRect.right_++;
  1268. if (intRect.bottom_ == intRect.top_)
  1269. intRect.bottom_++;
  1270. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1271. enable = false;
  1272. if (enable && scissorRect_ != intRect)
  1273. {
  1274. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1275. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1276. scissorRect_ = intRect;
  1277. }
  1278. }
  1279. else
  1280. scissorRect_ = IntRect::ZERO;
  1281. if (enable != scissorTest_)
  1282. {
  1283. if (enable)
  1284. glEnable(GL_SCISSOR_TEST);
  1285. else
  1286. glDisable(GL_SCISSOR_TEST);
  1287. scissorTest_ = enable;
  1288. }
  1289. }
  1290. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1291. {
  1292. }
  1293. void Graphics::ResetStreamFrequencies()
  1294. {
  1295. }
  1296. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1297. {
  1298. #ifndef GL_ES_VERSION_2_0
  1299. if (enable != stencilTest_)
  1300. {
  1301. if (enable)
  1302. glEnable(GL_STENCIL_TEST);
  1303. else
  1304. glDisable(GL_STENCIL_TEST);
  1305. stencilTest_ = enable;
  1306. }
  1307. if (enable)
  1308. {
  1309. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1310. {
  1311. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1312. stencilTestMode_ = mode;
  1313. stencilRef_ = stencilRef;
  1314. stencilCompareMask_ = compareMask;
  1315. }
  1316. if (writeMask != stencilWriteMask_)
  1317. {
  1318. glStencilMask(writeMask);
  1319. stencilWriteMask_ = writeMask;
  1320. }
  1321. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1322. {
  1323. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1324. stencilPass_ = pass;
  1325. stencilFail_ = fail;
  1326. stencilZFail_ = zFail;
  1327. }
  1328. }
  1329. #endif
  1330. }
  1331. void Graphics::SetForceSM2(bool enable)
  1332. {
  1333. }
  1334. bool Graphics::IsInitialized() const
  1335. {
  1336. return impl_->window_ != 0;
  1337. }
  1338. void* Graphics::GetWindowHandle() const
  1339. {
  1340. return impl_->window_;
  1341. }
  1342. PODVector<IntVector2> Graphics::GetResolutions() const
  1343. {
  1344. PODVector<IntVector2> ret;
  1345. unsigned numModes = SDL_GetNumDisplayModes(0);
  1346. for (unsigned i = 0; i < numModes; ++i)
  1347. {
  1348. SDL_DisplayMode mode;
  1349. SDL_GetDisplayMode(0, i, &mode);
  1350. int width = mode.w;
  1351. int height = mode.h;
  1352. // Store mode if unique
  1353. bool unique = true;
  1354. for (unsigned j = 0; j < ret.Size(); ++i)
  1355. {
  1356. if (ret[j].x_ == width && ret[j].y_ == height)
  1357. {
  1358. unique = false;
  1359. break;
  1360. }
  1361. }
  1362. if (unique)
  1363. ret.Push(IntVector2(width, height));
  1364. }
  1365. return ret;
  1366. }
  1367. PODVector<int> Graphics::GetMultiSampleLevels() const
  1368. {
  1369. PODVector<int> ret;
  1370. // No multisampling always supported
  1371. ret.Push(1);
  1372. /// \todo Implement properly, if possible
  1373. return ret;
  1374. }
  1375. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1376. {
  1377. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1378. }
  1379. TextureUnit Graphics::GetTextureUnit(const String& name)
  1380. {
  1381. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1382. if (i != textureUnits_.End())
  1383. return i->second_;
  1384. else
  1385. return MAX_TEXTURE_UNITS;
  1386. }
  1387. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1388. {
  1389. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1390. {
  1391. if (i->second_ == unit)
  1392. return i->first_;
  1393. }
  1394. return noParameter;
  1395. }
  1396. Texture* Graphics::GetTexture(unsigned index) const
  1397. {
  1398. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1399. }
  1400. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1401. {
  1402. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1403. }
  1404. IntVector2 Graphics::GetRenderTargetDimensions() const
  1405. {
  1406. int width, height;
  1407. if (renderTargets_[0])
  1408. {
  1409. width = renderTargets_[0]->GetWidth();
  1410. height = renderTargets_[0]->GetHeight();
  1411. }
  1412. else if (depthStencil_)
  1413. {
  1414. width = depthStencil_->GetWidth();
  1415. height = depthStencil_->GetHeight();
  1416. }
  1417. else
  1418. {
  1419. width = width_;
  1420. height = height_;
  1421. }
  1422. return IntVector2(width, height);
  1423. }
  1424. void Graphics::AddGPUObject(GPUObject* object)
  1425. {
  1426. gpuObjects_.Push(object);
  1427. }
  1428. void Graphics::RemoveGPUObject(GPUObject* object)
  1429. {
  1430. gpuObjects_.Erase(gpuObjects_.Find(object));
  1431. }
  1432. void* Graphics::ReserveScratchBuffer(unsigned size)
  1433. {
  1434. if (!size)
  1435. return 0;
  1436. // First check for a free buffer that is large enough
  1437. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1438. {
  1439. if (!i->reserved_ && i->size_ >= size)
  1440. {
  1441. i->reserved_ = true;
  1442. return i->data_.Get();
  1443. }
  1444. }
  1445. // Then check if a free buffer can be resized
  1446. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1447. {
  1448. if (!i->reserved_)
  1449. {
  1450. i->data_ = new unsigned char[size];
  1451. i->size_ = size;
  1452. i->reserved_ = true;
  1453. return i->data_.Get();
  1454. }
  1455. }
  1456. // Finally allocate a new buffer
  1457. ScratchBuffer newBuffer;
  1458. newBuffer.data_ = new unsigned char[size];
  1459. newBuffer.size_ = size;
  1460. newBuffer.reserved_ = true;
  1461. scratchBuffers_.Push(newBuffer);
  1462. return newBuffer.data_.Get();
  1463. }
  1464. void Graphics::FreeScratchBuffer(void* buffer)
  1465. {
  1466. if (!buffer)
  1467. return;
  1468. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1469. {
  1470. if (i->reserved_ && i->data_.Get() == buffer)
  1471. {
  1472. i->reserved_ = false;
  1473. return;
  1474. }
  1475. }
  1476. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)buffer) + " not found");
  1477. }
  1478. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1479. {
  1480. if (!impl_->window_)
  1481. return;
  1482. if (clearGPUObjects)
  1483. {
  1484. // Shutting down: release all GPU objects that still exist, then delete the context
  1485. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1486. (*i)->Release();
  1487. gpuObjects_.Clear();
  1488. if (impl_->context_)
  1489. {
  1490. MutexLock lock(GetStaticMutex());
  1491. SDL_GL_DeleteContext(impl_->context_);
  1492. impl_->context_ = 0;
  1493. }
  1494. CleanupFramebuffers(true);
  1495. }
  1496. else
  1497. {
  1498. if (impl_->context_)
  1499. {
  1500. MutexLock lock(GetStaticMutex());
  1501. SDL_GL_DeleteContext(impl_->context_);
  1502. impl_->context_ = 0;
  1503. }
  1504. // We are not shutting down, but recreating the context: mark GPU objects lost
  1505. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1506. (*i)->OnDeviceLost();
  1507. }
  1508. CleanupFramebuffers(true);
  1509. depthTextures_.Clear();
  1510. shaderPrograms_.Clear();
  1511. // When the new context is initialized, it will have default state again
  1512. ResetCachedState();
  1513. ClearParameterSources();
  1514. if (closeWindow)
  1515. {
  1516. MutexLock lock(GetStaticMutex());
  1517. SDL_ShowCursor(SDL_TRUE);
  1518. SDL_DestroyWindow(impl_->window_);
  1519. impl_->window_ = 0;
  1520. }
  1521. }
  1522. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1523. {
  1524. if (!surface)
  1525. return;
  1526. // Flush pending FBO changes first if any
  1527. CommitFramebuffer();
  1528. unsigned currentFbo = impl_->boundFbo_;
  1529. // Go through all FBOs and clean up the surface from them
  1530. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();
  1531. ++i)
  1532. {
  1533. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1534. {
  1535. if (i->second_.colorAttachments_[j] == surface)
  1536. {
  1537. if (currentFbo != i->second_.fbo_)
  1538. {
  1539. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1540. currentFbo = i->second_.fbo_;
  1541. }
  1542. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1543. i->second_.colorAttachments_[j] = 0;
  1544. // Mark drawbuffer bits to need recalculation
  1545. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1546. }
  1547. }
  1548. if (i->second_.depthAttachment_ == surface)
  1549. {
  1550. if (currentFbo != i->second_.fbo_)
  1551. {
  1552. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1553. currentFbo = i->second_.fbo_;
  1554. }
  1555. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1556. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1557. i->second_.depthAttachment_ = 0;
  1558. }
  1559. }
  1560. // Restore previously bound FBO now if needed
  1561. if (currentFbo != impl_->boundFbo_)
  1562. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  1563. }
  1564. unsigned Graphics::GetAlphaFormat()
  1565. {
  1566. return GL_ALPHA;
  1567. }
  1568. unsigned Graphics::GetLuminanceFormat()
  1569. {
  1570. return GL_LUMINANCE;
  1571. }
  1572. unsigned Graphics::GetLuminanceAlphaFormat()
  1573. {
  1574. return GL_LUMINANCE_ALPHA;
  1575. }
  1576. unsigned Graphics::GetRGBFormat()
  1577. {
  1578. return GL_RGB;
  1579. }
  1580. unsigned Graphics::GetRGBAFormat()
  1581. {
  1582. return GL_RGBA;
  1583. }
  1584. unsigned Graphics::GetFloatFormat()
  1585. {
  1586. #ifndef GL_ES_VERSION_2_0
  1587. return GL_LUMINANCE32F_ARB;
  1588. #else
  1589. return GL_LUMINANCE;
  1590. #endif
  1591. }
  1592. unsigned Graphics::GetLinearDepthFormat()
  1593. {
  1594. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  1595. // manually if not using a readable hardware depth texture
  1596. return GL_RGBA;
  1597. }
  1598. unsigned Graphics::GetDepthStencilFormat()
  1599. {
  1600. #ifndef GL_ES_VERSION_2_0
  1601. return GL_DEPTH24_STENCIL8_EXT;
  1602. #else
  1603. return GL_DEPTH_COMPONENT;
  1604. #endif
  1605. }
  1606. void Graphics::CheckFeatureSupport()
  1607. {
  1608. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  1609. lightPrepassSupport_ = false;
  1610. deferredSupport_ = false;
  1611. hardwareDepthSupport_ = false;
  1612. int numSupportedRTs = 1;
  1613. #ifndef GL_ES_VERSION_2_0
  1614. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  1615. // For now hardware depth texture is only tested for on NVIDIA hardware because of visual artifacts and slowdown on ATI
  1616. String vendorString = String((const char*)glGetString(GL_VENDOR)).ToUpper();
  1617. if (vendorString.Find("NVIDIA") != String::NPOS)
  1618. {
  1619. SharedPtr<Texture2D> depthTexture(new Texture2D(context_));
  1620. hardwareDepthSupport_ = true;
  1621. // Note: Texture2D::SetSize() requires hardwareDepthSupport_ == true to create a texture instead of a renderbuffer
  1622. depthTexture->SetSize(256, 256, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1623. SetDepthStencil(depthTexture);
  1624. // If hardware depth textures work, this means also light pre-pass is automatically supported
  1625. if (CheckFramebuffer())
  1626. {
  1627. lightPrepassSupport_ = true;
  1628. if (numSupportedRTs >= 3)
  1629. deferredSupport_ = true;
  1630. }
  1631. else
  1632. hardwareDepthSupport_ = false;
  1633. ResetDepthStencil();
  1634. }
  1635. if (!hardwareDepthSupport_)
  1636. {
  1637. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  1638. if (numSupportedRTs >= 2)
  1639. lightPrepassSupport_ = true;
  1640. if (numSupportedRTs >= 4)
  1641. deferredSupport_ = true;
  1642. }
  1643. #else
  1644. if (!CheckExtension("GL_OES_depth_texture"))
  1645. {
  1646. shadowMapFormat_ = 0;
  1647. hiresShadowMapFormat_ = 0;
  1648. }
  1649. else
  1650. {
  1651. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  1652. hiresShadowMapFormat_ = GL_DEPTH_COMPONENT;
  1653. hardwareDepthSupport_ = true;
  1654. }
  1655. #endif
  1656. }
  1657. void Graphics::CommitFramebuffer()
  1658. {
  1659. if (!impl_->fboDirty_)
  1660. return;
  1661. impl_->fboDirty_ = false;
  1662. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  1663. bool noFbo = !depthStencil_;
  1664. if (noFbo)
  1665. {
  1666. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1667. {
  1668. if (renderTargets_[i])
  1669. {
  1670. noFbo = false;
  1671. break;
  1672. }
  1673. }
  1674. }
  1675. if (noFbo)
  1676. {
  1677. if (impl_->boundFbo_)
  1678. {
  1679. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1680. impl_->boundFbo_ = 0;
  1681. }
  1682. return;
  1683. }
  1684. // Search for a new framebuffer based on format & size, or create new
  1685. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  1686. unsigned format = 0;
  1687. if (renderTargets_[0])
  1688. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  1689. else if (depthStencil_)
  1690. format = depthStencil_->GetParentTexture()->GetFormat();
  1691. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  1692. Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  1693. if (i == impl_->frameBuffers_.End())
  1694. {
  1695. FrameBufferObject newFbo;
  1696. glGenFramebuffersEXT(1, &newFbo.fbo_);
  1697. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  1698. }
  1699. i->second_.useTimer_.Reset();
  1700. if (impl_->boundFbo_ != i->second_.fbo_)
  1701. {
  1702. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1703. impl_->boundFbo_ = i->second_.fbo_;
  1704. }
  1705. #ifndef GL_ES_VERSION_2_0
  1706. // Setup readbuffers & drawbuffers if needed
  1707. if (i->second_.readBuffers_ != GL_NONE)
  1708. {
  1709. glReadBuffer(GL_NONE);
  1710. i->second_.readBuffers_ = GL_NONE;
  1711. }
  1712. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1713. unsigned newDrawBuffers = 0;
  1714. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1715. {
  1716. if (renderTargets_[i])
  1717. newDrawBuffers |= 1 << i;
  1718. }
  1719. if (newDrawBuffers != i->second_.drawBuffers_)
  1720. {
  1721. // Check for no color rendertargets (depth rendering only)
  1722. if (!newDrawBuffers)
  1723. glDrawBuffer(GL_NONE);
  1724. else
  1725. {
  1726. int drawBufferIds[4];
  1727. unsigned drawBufferCount = 0;
  1728. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1729. {
  1730. if (renderTargets_[i])
  1731. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1732. }
  1733. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1734. }
  1735. i->second_.drawBuffers_ = newDrawBuffers;
  1736. }
  1737. #endif
  1738. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1739. {
  1740. if (renderTargets_[j])
  1741. {
  1742. Texture* texture = renderTargets_[j]->GetParentTexture();
  1743. // If texture's parameters are dirty, update before attaching
  1744. if (texture->GetParametersDirty())
  1745. {
  1746. SetTextureForUpdate(texture);
  1747. texture->UpdateParameters();
  1748. SetTexture(0, 0);
  1749. }
  1750. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  1751. {
  1752. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  1753. texture->GetGPUObject(), 0);
  1754. i->second_.colorAttachments_[j] = renderTargets_[j];
  1755. }
  1756. }
  1757. else
  1758. {
  1759. if (i->second_.colorAttachments_[j])
  1760. {
  1761. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1762. i->second_.colorAttachments_[j] = 0;
  1763. }
  1764. }
  1765. }
  1766. if (depthStencil_)
  1767. {
  1768. // Bind either a renderbuffer or a depth texture, depending on what is available
  1769. Texture* texture = depthStencil_->GetParentTexture();
  1770. #ifndef GL_ES_VERSION_2_0
  1771. bool hasStencil = texture->GetFormat() == GetDepthStencilFormat();
  1772. #else
  1773. bool hasStencil = false;
  1774. #endif
  1775. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  1776. if (!renderBufferID)
  1777. {
  1778. // If texture's parameters are dirty, update before attaching
  1779. if (texture->GetParametersDirty())
  1780. {
  1781. SetTextureForUpdate(texture);
  1782. texture->UpdateParameters();
  1783. SetTexture(0, 0);
  1784. }
  1785. if (i->second_.depthAttachment_ != depthStencil_)
  1786. {
  1787. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1788. if (hasStencil)
  1789. {
  1790. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  1791. texture->GetGPUObject(), 0);
  1792. }
  1793. else
  1794. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1795. i->second_.depthAttachment_ = depthStencil_;
  1796. }
  1797. }
  1798. else
  1799. {
  1800. if (i->second_.depthAttachment_ != depthStencil_)
  1801. {
  1802. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1803. if (hasStencil)
  1804. {
  1805. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  1806. renderBufferID);
  1807. }
  1808. else
  1809. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1810. i->second_.depthAttachment_ = depthStencil_;
  1811. }
  1812. }
  1813. impl_->depthBits_ = texture->GetDepthBits();
  1814. }
  1815. else
  1816. {
  1817. if (i->second_.depthAttachment_)
  1818. {
  1819. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1820. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1821. i->second_.depthAttachment_ = 0;
  1822. impl_->depthBits_ = impl_->windowDepthBits_;
  1823. }
  1824. }
  1825. }
  1826. bool Graphics::CheckFramebuffer()
  1827. {
  1828. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  1829. }
  1830. void Graphics::CleanupFramebuffers(bool contextLost)
  1831. {
  1832. if (!contextLost)
  1833. {
  1834. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();)
  1835. {
  1836. Map<unsigned long long, FrameBufferObject>::Iterator current = i++;
  1837. if (current->second_.fbo_ != impl_->boundFbo_ && current->second_.useTimer_.GetMSec(false) >
  1838. MAX_FRAMEBUFFER_AGE)
  1839. {
  1840. glDeleteFramebuffersEXT(1, &current->second_.fbo_);
  1841. impl_->frameBuffers_.Erase(current);
  1842. }
  1843. }
  1844. }
  1845. else
  1846. {
  1847. impl_->boundFbo_ = 0;
  1848. impl_->frameBuffers_.Clear();
  1849. }
  1850. }
  1851. void Graphics::ResetCachedState()
  1852. {
  1853. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1854. {
  1855. vertexBuffers_[i] = 0;
  1856. elementMasks_[i] = 0;
  1857. }
  1858. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1859. {
  1860. textures_[i] = 0;
  1861. textureTypes_[i] = 0;
  1862. }
  1863. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1864. renderTargets_[i] = 0;
  1865. depthStencil_ = 0;
  1866. viewTexture_ = 0;
  1867. viewport_ = IntRect(0, 0, 0, 0);
  1868. indexBuffer_ = 0;
  1869. vertexShader_ = 0;
  1870. pixelShader_ = 0;
  1871. shaderProgram_ = 0;
  1872. blendMode_ = BLEND_REPLACE;
  1873. textureAnisotropy_ = 1;
  1874. colorWrite_ = true;
  1875. cullMode_ = CULL_NONE;
  1876. constantDepthBias_ = 0.0f;
  1877. slopeScaledDepthBias_ = 0.0f;
  1878. depthTestMode_ = CMP_ALWAYS;
  1879. depthWrite_ = true;
  1880. scissorTest_ = false;
  1881. scissorRect_ = IntRect::ZERO;
  1882. stencilTest_ = false;
  1883. stencilTestMode_ = CMP_ALWAYS;
  1884. stencilPass_ = OP_KEEP;
  1885. stencilFail_ = OP_KEEP;
  1886. stencilZFail_ = OP_KEEP;
  1887. stencilRef_ = 0;
  1888. stencilCompareMask_ = M_MAX_UNSIGNED;
  1889. stencilWriteMask_ = M_MAX_UNSIGNED;
  1890. impl_->activeTexture_ = 0;
  1891. impl_->enabledAttributes_ = 0;
  1892. }
  1893. void Graphics::SetTextureUnitMappings()
  1894. {
  1895. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1896. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1897. textureUnits_["NormalMap"] = TU_NORMAL;
  1898. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1899. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1900. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1901. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1902. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1903. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1904. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1905. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1906. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1907. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  1908. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1909. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1910. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1911. }
  1912. void RegisterGraphicsLibrary(Context* context)
  1913. {
  1914. Animation::RegisterObject(context);
  1915. Material::RegisterObject(context);
  1916. Model::RegisterObject(context);
  1917. Shader::RegisterObject(context);
  1918. Technique::RegisterObject(context);
  1919. Texture2D::RegisterObject(context);
  1920. TextureCube::RegisterObject(context);
  1921. Camera::RegisterObject(context);
  1922. Drawable::RegisterObject(context);
  1923. Light::RegisterObject(context);
  1924. StaticModel::RegisterObject(context);
  1925. Skybox::RegisterObject(context);
  1926. AnimatedModel::RegisterObject(context);
  1927. AnimationController::RegisterObject(context);
  1928. BillboardSet::RegisterObject(context);
  1929. ParticleEmitter::RegisterObject(context);
  1930. DebugRenderer::RegisterObject(context);
  1931. Octree::RegisterObject(context);
  1932. Zone::RegisterObject(context);
  1933. }