OGLGraphics.cpp 75 KB

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