OGLGraphics.cpp 80 KB

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