OGLGraphics.cpp 69 KB

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