OGLGraphics.cpp 70 KB

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