OGLGraphics.cpp 71 KB

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