OGLGraphics.cpp 70 KB

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