OGLGraphics.cpp 70 KB

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