OGLGraphics.cpp 84 KB

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