OGLGraphics.cpp 88 KB

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