OGLGraphics.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966
  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 "ShaderPrecache.h"
  48. #include "ShaderProgram.h"
  49. #include "ShaderVariation.h"
  50. #include "Skybox.h"
  51. #include "StaticModelGroup.h"
  52. #include "Technique.h"
  53. #include "Terrain.h"
  54. #include "TerrainPatch.h"
  55. #include "Texture2D.h"
  56. #include "Texture3D.h"
  57. #include "TextureCube.h"
  58. #include "VertexBuffer.h"
  59. #include "Zone.h"
  60. #include <stdio.h>
  61. #include "DebugNew.h"
  62. #ifdef GL_ES_VERSION_2_0
  63. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  64. #define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER
  65. #define GL_RENDERBUFFER_EXT GL_RENDERBUFFER
  66. #define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0
  67. #define GL_DEPTH_ATTACHMENT_EXT GL_DEPTH_ATTACHMENT
  68. #define GL_STENCIL_ATTACHMENT_EXT GL_STENCIL_ATTACHMENT
  69. #define GL_FRAMEBUFFER_COMPLETE_EXT GL_FRAMEBUFFER_COMPLETE
  70. #define glClearDepth glClearDepthf
  71. #define glBindFramebufferEXT glBindFramebuffer
  72. #define glFramebufferTexture2DEXT glFramebufferTexture2D
  73. #define glFramebufferRenderbufferEXT glFramebufferRenderbuffer
  74. #define glGenFramebuffersEXT glGenFramebuffers
  75. #define glDeleteFramebuffersEXT glDeleteFramebuffers
  76. #define glCheckFramebufferStatusEXT glCheckFramebufferStatus
  77. #endif
  78. #ifdef WIN32
  79. // On Intel / NVIDIA setups prefer the NVIDIA GPU
  80. #include <windows.h>
  81. extern "C" {
  82. __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  83. }
  84. #endif
  85. namespace Urho3D
  86. {
  87. static const unsigned glCmpFunc[] =
  88. {
  89. GL_ALWAYS,
  90. GL_EQUAL,
  91. GL_NOTEQUAL,
  92. GL_LESS,
  93. GL_LEQUAL,
  94. GL_GREATER,
  95. GL_GEQUAL
  96. };
  97. static const unsigned glSrcBlend[] =
  98. {
  99. GL_ONE,
  100. GL_ONE,
  101. GL_DST_COLOR,
  102. GL_SRC_ALPHA,
  103. GL_SRC_ALPHA,
  104. GL_ONE,
  105. GL_ONE_MINUS_DST_ALPHA,
  106. GL_ONE,
  107. GL_SRC_ALPHA
  108. };
  109. static const unsigned glDestBlend[] =
  110. {
  111. GL_ZERO,
  112. GL_ONE,
  113. GL_ZERO,
  114. GL_ONE_MINUS_SRC_ALPHA,
  115. GL_ONE,
  116. GL_ONE_MINUS_SRC_ALPHA,
  117. GL_DST_ALPHA,
  118. GL_ONE,
  119. GL_ONE
  120. };
  121. static const unsigned glBlendOp[] =
  122. {
  123. GL_FUNC_ADD,
  124. GL_FUNC_ADD,
  125. GL_FUNC_ADD,
  126. GL_FUNC_ADD,
  127. GL_FUNC_ADD,
  128. GL_FUNC_ADD,
  129. GL_FUNC_ADD,
  130. GL_FUNC_REVERSE_SUBTRACT,
  131. GL_FUNC_REVERSE_SUBTRACT
  132. };
  133. #ifndef GL_ES_VERSION_2_0
  134. static const unsigned glFillMode[] =
  135. {
  136. GL_FILL,
  137. GL_LINE,
  138. GL_POINT
  139. };
  140. #endif
  141. static const unsigned glStencilOps[] =
  142. {
  143. GL_KEEP,
  144. GL_ZERO,
  145. GL_REPLACE,
  146. GL_INCR_WRAP,
  147. GL_DECR_WRAP
  148. };
  149. // Remap vertex attributes on OpenGL so that all usually needed attributes including skinning fit to the first 8.
  150. // This avoids a skinning bug on GLES2 devices which only support 8.
  151. static const unsigned glVertexAttrIndex[] =
  152. {
  153. 0, 1, 2, 3, 4, 8, 9, 5, 6, 7, 10, 11, 12
  154. };
  155. static const unsigned MAX_FRAMEBUFFER_AGE = 2000;
  156. #ifdef GL_ES_VERSION_2_0
  157. static unsigned glesDepthStencilFormat = GL_DEPTH_COMPONENT16;
  158. #endif
  159. bool CheckExtension(String& extensions, const String& name)
  160. {
  161. if (extensions.Empty())
  162. extensions = (const char*)glGetString(GL_EXTENSIONS);
  163. return extensions.Contains(name);
  164. }
  165. Graphics::Graphics(Context* context_) :
  166. Object(context_),
  167. impl_(new GraphicsImpl()),
  168. windowIcon_(0),
  169. externalWindow_(0),
  170. width_(0),
  171. height_(0),
  172. multiSample_(1),
  173. fullscreen_(false),
  174. borderless_(false),
  175. resizable_(false),
  176. vsync_(false),
  177. tripleBuffer_(false),
  178. sRGB_(false),
  179. instancingSupport_(false),
  180. lightPrepassSupport_(false),
  181. deferredSupport_(false),
  182. anisotropySupport_(false),
  183. dxtTextureSupport_(false),
  184. etcTextureSupport_(false),
  185. pvrtcTextureSupport_(false),
  186. sRGBSupport_(false),
  187. sRGBWriteSupport_(false),
  188. numPrimitives_(0),
  189. numBatches_(0),
  190. maxScratchBufferRequest_(0),
  191. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  192. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  193. defaultTextureFilterMode_(FILTER_BILINEAR),
  194. releasingGPUObjects_(false),
  195. shaderPath_("Shaders/GLSL/"),
  196. shaderExtension_(".glsl"),
  197. orientations_("LandscapeLeft LandscapeRight")
  198. {
  199. SetTextureUnitMappings();
  200. ResetCachedState();
  201. // Initialize SDL now. Graphics should be the first SDL-using subsystem to be created
  202. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_NOPARACHUTE);
  203. // Register Graphics library object factories
  204. RegisterGraphicsLibrary(context_);
  205. }
  206. Graphics::~Graphics()
  207. {
  208. Close();
  209. delete impl_;
  210. impl_ = 0;
  211. // Shut down SDL now. Graphics should be the last SDL-using subsystem to be destroyed
  212. SDL_Quit();
  213. }
  214. void Graphics::SetExternalWindow(void* window)
  215. {
  216. if (!impl_->window_)
  217. externalWindow_ = window;
  218. else
  219. LOGERROR("Window already opened, can not set external window");
  220. }
  221. void Graphics::SetWindowTitle(const String& windowTitle)
  222. {
  223. windowTitle_ = windowTitle;
  224. if (impl_->window_)
  225. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  226. }
  227. void Graphics::SetWindowIcon(Image* windowIcon)
  228. {
  229. windowIcon_ = windowIcon;
  230. if (impl_->window_)
  231. CreateWindowIcon();
  232. }
  233. void Graphics::SetWindowPosition(const IntVector2& position)
  234. {
  235. if (impl_->window_)
  236. SDL_SetWindowPosition(impl_->window_, position.x_, position.y_);
  237. }
  238. void Graphics::SetWindowPosition(int x, int y)
  239. {
  240. SetWindowPosition(IntVector2(x, y));
  241. }
  242. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool vsync, bool tripleBuffer, int multiSample)
  243. {
  244. PROFILE(SetScreenMode);
  245. bool maximize = false;
  246. // Fullscreen or Borderless can not be resizable
  247. if (fullscreen || borderless)
  248. resizable = false;
  249. // Borderless cannot be fullscreen, they are mutually exclusive
  250. if (borderless)
  251. fullscreen = false;
  252. multiSample = Clamp(multiSample, 1, 16);
  253. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  254. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  255. return true;
  256. // If only vsync changes, do not destroy/recreate the context
  257. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  258. tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  259. {
  260. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  261. vsync_ = vsync;
  262. return true;
  263. }
  264. // 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
  265. if (!width || !height)
  266. {
  267. if (fullscreen || borderless)
  268. {
  269. SDL_DisplayMode mode;
  270. SDL_GetDesktopDisplayMode(0, &mode);
  271. width = mode.w;
  272. height = mode.h;
  273. }
  274. else
  275. {
  276. maximize = resizable;
  277. width = 1024;
  278. height = 768;
  279. }
  280. }
  281. // Check fullscreen mode validity (desktop only). If not valid, revert to windowed
  282. #if !defined(ANDROID) && !defined(IOS) && !defined(RASPI)
  283. if (fullscreen)
  284. {
  285. PODVector<IntVector2> resolutions = GetResolutions();
  286. fullscreen = false;
  287. for (unsigned i = 0; i < resolutions.Size(); ++i)
  288. {
  289. if (width == resolutions[i].x_ && height == resolutions[i].y_)
  290. {
  291. fullscreen = true;
  292. break;
  293. }
  294. }
  295. }
  296. #endif
  297. String extensions;
  298. // With an external window, only the size can change after initial setup, so do not recreate context
  299. if (!externalWindow_ || !impl_->context_)
  300. {
  301. // Close the existing window and OpenGL context, mark GPU objects as lost
  302. Release(false, true);
  303. #ifdef IOS
  304. // On iOS window needs to be resizable to handle orientation changes properly
  305. resizable = true;
  306. #endif
  307. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  308. #ifndef GL_ES_VERSION_2_0
  309. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  310. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  311. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  312. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  313. if (externalWindow_)
  314. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  315. else
  316. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  317. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  318. #endif
  319. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  320. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  321. if (multiSample > 1)
  322. {
  323. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  324. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  325. }
  326. else
  327. {
  328. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  329. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  330. }
  331. int x = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  332. int y = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  333. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  334. if (fullscreen)
  335. flags |= SDL_WINDOW_FULLSCREEN;
  336. if (resizable)
  337. flags |= SDL_WINDOW_RESIZABLE;
  338. if (borderless)
  339. flags |= SDL_WINDOW_BORDERLESS;
  340. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  341. for (;;)
  342. {
  343. if (!externalWindow_)
  344. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  345. else
  346. {
  347. if (!impl_->window_)
  348. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, SDL_WINDOW_OPENGL);
  349. fullscreen = false;
  350. }
  351. if (impl_->window_)
  352. break;
  353. else
  354. {
  355. if (multiSample > 1)
  356. {
  357. // If failed with multisampling, retry first without
  358. multiSample = 1;
  359. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  360. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  361. }
  362. else
  363. {
  364. LOGERROR("Could not open window");
  365. return false;
  366. }
  367. }
  368. }
  369. CreateWindowIcon();
  370. if (maximize)
  371. {
  372. Maximize();
  373. SDL_GetWindowSize(impl_->window_, &width, &height);
  374. }
  375. // Create/restore context and GPU objects and set initial renderstate
  376. Restore();
  377. if (!impl_->context_)
  378. {
  379. LOGERROR("Could not create OpenGL context");
  380. return false;
  381. }
  382. // If OpenGL extensions not yet initialized, initialize now
  383. #ifndef GL_ES_VERSION_2_0
  384. GLenum err = glewInit();
  385. if (GLEW_OK != err)
  386. {
  387. LOGERROR("Cannot initialize OpenGL");
  388. Release(true, true);
  389. return false;
  390. }
  391. if (!GLEW_VERSION_2_0)
  392. {
  393. LOGERROR("OpenGL 2.0 is required");
  394. Release(true, true);
  395. return false;
  396. }
  397. if (!GLEW_EXT_framebuffer_object || !GLEW_EXT_packed_depth_stencil)
  398. {
  399. LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  400. Release(true, true);
  401. return false;
  402. }
  403. instancingSupport_ = GLEW_ARB_instanced_arrays != 0;
  404. dxtTextureSupport_ = GLEW_EXT_texture_compression_s3tc != 0;
  405. anisotropySupport_ = GLEW_EXT_texture_filter_anisotropic != 0;
  406. sRGBSupport_ = GLEW_EXT_texture_sRGB != 0;
  407. sRGBWriteSupport_ = GLEW_EXT_framebuffer_sRGB != 0;
  408. // Set up instancing divisors if supported
  409. if (instancingSupport_)
  410. {
  411. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX1, 1);
  412. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX2, 1);
  413. glVertexAttribDivisorARB(ELEMENT_INSTANCEMATRIX3, 1);
  414. }
  415. #else
  416. dxtTextureSupport_ = CheckExtension(extensions, "EXT_texture_compression_dxt1");
  417. etcTextureSupport_ = CheckExtension(extensions, "OES_compressed_ETC1_RGB8_texture");
  418. pvrtcTextureSupport_ = CheckExtension(extensions, "IMG_texture_compression_pvrtc");
  419. #endif
  420. // Set up texture data read/write alignment
  421. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  422. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  423. }
  424. // Set vsync
  425. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  426. // Store the system FBO on IOS now
  427. #ifdef IOS
  428. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFbo_);
  429. #endif
  430. fullscreen_ = fullscreen;
  431. resizable_ = resizable;
  432. borderless_ = borderless;
  433. vsync_ = vsync;
  434. tripleBuffer_ = tripleBuffer;
  435. multiSample_ = multiSample;
  436. SDL_GetWindowSize(impl_->window_, &width_, &height_);
  437. // Reset rendertargets and viewport for the new screen mode
  438. ResetRenderTargets();
  439. // Clear the initial window contents to black
  440. Clear(CLEAR_COLOR);
  441. SDL_GL_SwapWindow(impl_->window_);
  442. CheckFeatureSupport(extensions);
  443. #ifdef URHO3D_LOGGING
  444. String msg;
  445. msg.AppendWithFormat("Set screen mode %dx%d %s", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"));
  446. if (borderless_)
  447. msg.Append(" borderless");
  448. if (resizable_)
  449. msg.Append(" resizable");
  450. if (multiSample > 1)
  451. msg.AppendWithFormat(" multisample %d", multiSample);
  452. LOGINFO(msg);
  453. #endif
  454. using namespace ScreenMode;
  455. VariantMap& eventData = GetEventDataMap();
  456. eventData[P_WIDTH] = width_;
  457. eventData[P_HEIGHT] = height_;
  458. eventData[P_FULLSCREEN] = fullscreen_;
  459. eventData[P_RESIZABLE] = resizable_;
  460. eventData[P_BORDERLESS] = borderless_;
  461. SendEvent(E_SCREENMODE, eventData);
  462. return true;
  463. }
  464. bool Graphics::SetMode(int width, int height)
  465. {
  466. return SetMode(width, height, fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  467. }
  468. void Graphics::SetSRGB(bool enable)
  469. {
  470. enable &= sRGBWriteSupport_;
  471. if (enable != sRGB_)
  472. {
  473. sRGB_ = enable;
  474. impl_->fboDirty_ = true;
  475. }
  476. }
  477. void Graphics::SetOrientations(const String& orientations)
  478. {
  479. orientations_ = orientations.Trimmed();
  480. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  481. }
  482. bool Graphics::ToggleFullscreen()
  483. {
  484. return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, vsync_, tripleBuffer_, multiSample_);
  485. }
  486. void Graphics::Close()
  487. {
  488. if (!IsInitialized())
  489. return;
  490. // Actually close the window
  491. Release(true, true);
  492. }
  493. bool Graphics::TakeScreenShot(Image& destImage)
  494. {
  495. PROFILE(TakeScreenShot);
  496. ResetRenderTargets();
  497. destImage.SetSize(width_, height_, 3);
  498. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  499. // On OpenGL we need to flip the image vertically after reading
  500. destImage.FlipVertical();
  501. return true;
  502. }
  503. bool Graphics::BeginFrame()
  504. {
  505. if (!IsInitialized() || IsDeviceLost())
  506. return false;
  507. // If using an external window, check it for size changes, and reset screen mode if necessary
  508. if (externalWindow_)
  509. {
  510. int width, height;
  511. SDL_GetWindowSize(impl_->window_, &width, &height);
  512. if (width != width_ || height != height_)
  513. SetMode(width, height);
  514. }
  515. // Set default rendertarget and depth buffer
  516. ResetRenderTargets();
  517. // Cleanup textures from previous frame
  518. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  519. SetTexture(i, 0);
  520. // Enable color and depth write
  521. SetColorWrite(true);
  522. SetDepthWrite(true);
  523. numPrimitives_ = 0;
  524. numBatches_ = 0;
  525. SendEvent(E_BEGINRENDERING);
  526. return true;
  527. }
  528. void Graphics::EndFrame()
  529. {
  530. if (!IsInitialized())
  531. return;
  532. PROFILE(Present);
  533. SendEvent(E_ENDRENDERING);
  534. SDL_GL_SwapWindow(impl_->window_);
  535. // Clean up FBO's that have not been used for a long time, and too large scratch buffers
  536. CleanupFramebuffers();
  537. CleanupScratchBuffers();
  538. }
  539. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  540. {
  541. if (impl_->fboDirty_)
  542. CommitFramebuffer();
  543. #ifdef GL_ES_VERSION_2_0
  544. flags &= ~CLEAR_STENCIL;
  545. #endif
  546. bool oldColorWrite = colorWrite_;
  547. bool oldDepthWrite = depthWrite_;
  548. if (flags & CLEAR_COLOR && !oldColorWrite)
  549. SetColorWrite(true);
  550. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  551. SetDepthWrite(true);
  552. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  553. glStencilMask(M_MAX_UNSIGNED);
  554. unsigned glFlags = 0;
  555. if (flags & CLEAR_COLOR)
  556. {
  557. glFlags |= GL_COLOR_BUFFER_BIT;
  558. glClearColor(color.r_, color.g_, color.b_, color.a_);
  559. }
  560. if (flags & CLEAR_DEPTH)
  561. {
  562. glFlags |= GL_DEPTH_BUFFER_BIT;
  563. glClearDepth(depth);
  564. }
  565. if (flags & CLEAR_STENCIL)
  566. {
  567. glFlags |= GL_STENCIL_BUFFER_BIT;
  568. glClearStencil(stencil);
  569. }
  570. // If viewport is less than full screen, set a scissor to limit the clear
  571. /// \todo Any user-set scissor test will be lost
  572. IntVector2 viewSize = GetRenderTargetDimensions();
  573. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  574. SetScissorTest(true, IntRect(0, 0, viewport_.Width(), viewport_.Height()));
  575. else
  576. SetScissorTest(false);
  577. glClear(glFlags);
  578. SetScissorTest(false);
  579. SetColorWrite(oldColorWrite);
  580. SetDepthWrite(oldDepthWrite);
  581. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  582. glStencilMask(stencilWriteMask_);
  583. }
  584. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  585. {
  586. if (!destination || !destination->GetRenderSurface() || destination->GetWidth() != width_ ||
  587. destination->GetHeight() != height_)
  588. return false;
  589. PROFILE(ResolveToTexture);
  590. IntRect vpCopy = viewport;
  591. if (vpCopy.right_ <= vpCopy.left_)
  592. vpCopy.right_ = vpCopy.left_ + 1;
  593. if (vpCopy.bottom_ <= vpCopy.top_)
  594. vpCopy.bottom_ = vpCopy.top_ + 1;
  595. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  596. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  597. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  598. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  599. // Make sure the FBO is not in use
  600. ResetRenderTargets();
  601. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  602. SetTextureForUpdate(destination);
  603. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.left_, height_ - vpCopy.bottom_,
  604. vpCopy.Width(), vpCopy.Height());
  605. SetTexture(0, 0);
  606. return true;
  607. }
  608. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  609. {
  610. if (!vertexCount)
  611. return;
  612. if (impl_->fboDirty_)
  613. CommitFramebuffer();
  614. unsigned primitiveCount = 0;
  615. switch (type)
  616. {
  617. case TRIANGLE_LIST:
  618. primitiveCount = vertexCount / 3;
  619. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  620. break;
  621. case LINE_LIST:
  622. primitiveCount = vertexCount / 2;
  623. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  624. break;
  625. }
  626. numPrimitives_ += primitiveCount;
  627. ++numBatches_;
  628. }
  629. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  630. {
  631. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject())
  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. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  643. else
  644. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  645. break;
  646. case LINE_LIST:
  647. primitiveCount = indexCount / 2;
  648. if (indexSize == sizeof(unsigned short))
  649. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  650. else
  651. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  652. break;
  653. }
  654. numPrimitives_ += primitiveCount;
  655. ++numBatches_;
  656. }
  657. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  658. {
  659. #ifndef GL_ES_VERSION_2_0
  660. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject() || !instancingSupport_)
  661. return;
  662. if (impl_->fboDirty_)
  663. CommitFramebuffer();
  664. unsigned primitiveCount = 0;
  665. unsigned indexSize = indexBuffer_->GetIndexSize();
  666. switch (type)
  667. {
  668. case TRIANGLE_LIST:
  669. primitiveCount = indexCount / 3;
  670. if (indexSize == sizeof(unsigned short))
  671. {
  672. glDrawElementsInstancedARB(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  673. instanceCount);
  674. }
  675. else
  676. {
  677. glDrawElementsInstancedARB(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  678. instanceCount);
  679. }
  680. break;
  681. case LINE_LIST:
  682. primitiveCount = indexCount / 2;
  683. if (indexSize == sizeof(unsigned short))
  684. {
  685. glDrawElementsInstancedARB(GL_LINES, indexCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  686. instanceCount);
  687. }
  688. else
  689. {
  690. glDrawElementsInstancedARB(GL_LINES, indexCount, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  691. instanceCount);
  692. }
  693. break;
  694. }
  695. numPrimitives_ += instanceCount * primitiveCount;
  696. ++numBatches_;
  697. #endif
  698. }
  699. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  700. {
  701. // Note: this is not multi-instance safe
  702. static PODVector<VertexBuffer*> vertexBuffers(1);
  703. static PODVector<unsigned> elementMasks(1);
  704. vertexBuffers[0] = buffer;
  705. elementMasks[0] = MASK_DEFAULT;
  706. SetVertexBuffers(vertexBuffers, elementMasks);
  707. }
  708. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  709. unsigned instanceOffset)
  710. {
  711. if (buffers.Size() > MAX_VERTEX_STREAMS)
  712. {
  713. LOGERROR("Too many vertex buffers");
  714. return false;
  715. }
  716. if (buffers.Size() != elementMasks.Size())
  717. {
  718. LOGERROR("Amount of element masks and vertex buffers does not match");
  719. return false;
  720. }
  721. bool changed = false;
  722. unsigned newAttributes = 0;
  723. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  724. {
  725. VertexBuffer* buffer = 0;
  726. unsigned elementMask = 0;
  727. if (i < buffers.Size() && buffers[i])
  728. {
  729. buffer = buffers[i];
  730. if (elementMasks[i] == MASK_DEFAULT)
  731. elementMask = buffer->GetElementMask();
  732. else
  733. elementMask = buffer->GetElementMask() & elementMasks[i];
  734. }
  735. // If buffer and element mask have stayed the same, skip to the next buffer
  736. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && instanceOffset == lastInstanceOffset_ && !changed)
  737. {
  738. newAttributes |= elementMask;
  739. continue;
  740. }
  741. vertexBuffers_[i] = buffer;
  742. elementMasks_[i] = elementMask;
  743. changed = true;
  744. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  745. // in which case the pointer will be invalid and cause a crash
  746. if (!buffer || !buffer->GetGPUObject())
  747. continue;
  748. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  749. unsigned vertexSize = buffer->GetVertexSize();
  750. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  751. {
  752. unsigned attrIndex = glVertexAttrIndex[j];
  753. unsigned elementBit = 1 << j;
  754. if (elementMask & elementBit)
  755. {
  756. newAttributes |= elementBit;
  757. // Enable attribute if not enabled yet
  758. if ((impl_->enabledAttributes_ & elementBit) == 0)
  759. {
  760. glEnableVertexAttribArray(attrIndex);
  761. impl_->enabledAttributes_ |= elementBit;
  762. }
  763. // Set the attribute pointer. Add instance offset for the instance matrix pointers
  764. unsigned offset = j >= ELEMENT_INSTANCEMATRIX1 ? instanceOffset * vertexSize : 0;
  765. glVertexAttribPointer(attrIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  766. VertexBuffer::elementNormalize[j], vertexSize, reinterpret_cast<const GLvoid*>(buffer->GetElementOffset((VertexElement)j)
  767. + offset));
  768. }
  769. }
  770. }
  771. if (!changed)
  772. return true;
  773. lastInstanceOffset_ = instanceOffset;
  774. // Now check which vertex attributes should be disabled
  775. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  776. unsigned disableIndex = 0;
  777. while (disableAttributes)
  778. {
  779. if (disableAttributes & 1)
  780. {
  781. glDisableVertexAttribArray(glVertexAttrIndex[disableIndex]);
  782. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  783. }
  784. disableAttributes >>= 1;
  785. ++disableIndex;
  786. }
  787. return true;
  788. }
  789. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  790. elementMasks, unsigned instanceOffset)
  791. {
  792. if (buffers.Size() > MAX_VERTEX_STREAMS)
  793. {
  794. LOGERROR("Too many vertex buffers");
  795. return false;
  796. }
  797. if (buffers.Size() != elementMasks.Size())
  798. {
  799. LOGERROR("Amount of element masks and vertex buffers does not match");
  800. return false;
  801. }
  802. bool changed = false;
  803. unsigned newAttributes = 0;
  804. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  805. {
  806. VertexBuffer* buffer = 0;
  807. unsigned elementMask = 0;
  808. if (i < buffers.Size() && buffers[i])
  809. {
  810. buffer = buffers[i];
  811. if (elementMasks[i] == MASK_DEFAULT)
  812. elementMask = buffer->GetElementMask();
  813. else
  814. elementMask = buffer->GetElementMask() & elementMasks[i];
  815. }
  816. // If buffer and element mask have stayed the same, skip to the next buffer
  817. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && instanceOffset == lastInstanceOffset_ && !changed)
  818. {
  819. newAttributes |= elementMask;
  820. continue;
  821. }
  822. vertexBuffers_[i] = buffer;
  823. elementMasks_[i] = elementMask;
  824. changed = true;
  825. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  826. // in which case the pointer will be invalid and cause a crash
  827. if (!buffer || !buffer->GetGPUObject())
  828. continue;
  829. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  830. unsigned vertexSize = buffer->GetVertexSize();
  831. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  832. {
  833. unsigned attrIndex = glVertexAttrIndex[j];
  834. unsigned elementBit = 1 << j;
  835. if (elementMask & elementBit)
  836. {
  837. newAttributes |= elementBit;
  838. // Enable attribute if not enabled yet
  839. if ((impl_->enabledAttributes_ & elementBit) == 0)
  840. {
  841. glEnableVertexAttribArray(attrIndex);
  842. impl_->enabledAttributes_ |= elementBit;
  843. }
  844. // Set the attribute pointer. Add instance offset for the instance matrix pointers
  845. unsigned offset = j >= ELEMENT_INSTANCEMATRIX1 ? instanceOffset * vertexSize : 0;
  846. glVertexAttribPointer(attrIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  847. VertexBuffer::elementNormalize[j], vertexSize, reinterpret_cast<const GLvoid*>(buffer->GetElementOffset((VertexElement)j)
  848. + offset));
  849. }
  850. }
  851. }
  852. if (!changed)
  853. return true;
  854. lastInstanceOffset_ = instanceOffset;
  855. // Now check which vertex attributes should be disabled
  856. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  857. unsigned disableIndex = 0;
  858. while (disableAttributes)
  859. {
  860. if (disableAttributes & 1)
  861. {
  862. glDisableVertexAttribArray(glVertexAttrIndex[disableIndex]);
  863. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  864. }
  865. disableAttributes >>= 1;
  866. ++disableIndex;
  867. }
  868. return true;
  869. }
  870. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  871. {
  872. if (indexBuffer_ == buffer)
  873. return;
  874. if (buffer)
  875. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  876. else
  877. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  878. indexBuffer_ = buffer;
  879. }
  880. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  881. {
  882. if (vs == vertexShader_ && ps == pixelShader_)
  883. return;
  884. ClearParameterSources();
  885. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  886. if (vs && !vs->GetGPUObject())
  887. {
  888. if (vs->GetCompilerOutput().Empty())
  889. {
  890. PROFILE(CompileVertexShader);
  891. bool success = vs->Create();
  892. if (success)
  893. LOGDEBUG("Compiled vertex shader " + vs->GetFullName());
  894. else
  895. {
  896. LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  897. vs = 0;
  898. }
  899. }
  900. else
  901. vs = 0;
  902. }
  903. if (ps && !ps->GetGPUObject())
  904. {
  905. if (ps->GetCompilerOutput().Empty())
  906. {
  907. PROFILE(CompilePixelShader);
  908. bool success = ps->Create();
  909. if (success)
  910. LOGDEBUG("Compiled pixel shader " + ps->GetFullName());
  911. else
  912. {
  913. LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  914. ps = 0;
  915. }
  916. }
  917. else
  918. ps = 0;
  919. }
  920. if (!vs || !ps)
  921. {
  922. glUseProgram(0);
  923. vertexShader_ = 0;
  924. pixelShader_ = 0;
  925. shaderProgram_ = 0;
  926. }
  927. else
  928. {
  929. vertexShader_ = vs;
  930. pixelShader_ = ps;
  931. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  932. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  933. if (i != shaderPrograms_.End())
  934. {
  935. // Use the existing linked program
  936. if (i->second_->GetGPUObject())
  937. {
  938. glUseProgram(i->second_->GetGPUObject());
  939. shaderProgram_ = i->second_;
  940. }
  941. else
  942. {
  943. glUseProgram(0);
  944. shaderProgram_ = 0;
  945. }
  946. }
  947. else
  948. {
  949. // Link a new combination
  950. PROFILE(LinkShaders);
  951. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  952. if (newProgram->Link())
  953. {
  954. LOGDEBUG("Linked vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName());
  955. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  956. // so it is not necessary to call it again
  957. shaderProgram_ = newProgram;
  958. }
  959. else
  960. {
  961. LOGERROR("Failed to link vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName() + ":\n" +
  962. newProgram->GetLinkerOutput());
  963. glUseProgram(0);
  964. shaderProgram_ = 0;
  965. }
  966. shaderPrograms_[combination] = newProgram;
  967. }
  968. }
  969. // Store shader combination if shader dumping in progress
  970. if (shaderPrecache_)
  971. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  972. }
  973. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  974. {
  975. if (shaderProgram_)
  976. {
  977. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  978. if (info)
  979. {
  980. switch (info->type_)
  981. {
  982. case GL_FLOAT:
  983. glUniform1fv(info->location_, count, data);
  984. break;
  985. case GL_FLOAT_VEC2:
  986. glUniform2fv(info->location_, count / 2, data);
  987. break;
  988. case GL_FLOAT_VEC3:
  989. glUniform3fv(info->location_, count / 3, data);
  990. break;
  991. case GL_FLOAT_VEC4:
  992. glUniform4fv(info->location_, count / 4, data);
  993. break;
  994. case GL_FLOAT_MAT3:
  995. count = Min((int)count, (int)NUM_TEMP_MATRICES * 9);
  996. Matrix3::BulkTranspose(&tempMatrices3_[0].m00_, data, count / 9);
  997. glUniformMatrix3fv(info->location_, count / 9, GL_FALSE, tempMatrices3_[0].Data());
  998. break;
  999. case GL_FLOAT_MAT4:
  1000. count = Min((int)count, (int)NUM_TEMP_MATRICES * 16);
  1001. Matrix4::BulkTranspose(&tempMatrices4_[0].m00_, data, count / 16);
  1002. glUniformMatrix4fv(info->location_, count / 16, GL_FALSE, tempMatrices4_[0].Data());
  1003. break;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. void Graphics::SetShaderParameter(StringHash param, float value)
  1009. {
  1010. if (shaderProgram_)
  1011. {
  1012. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1013. if (info)
  1014. glUniform1fv(info->location_, 1, &value);
  1015. }
  1016. }
  1017. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  1018. {
  1019. SetShaderParameter(param, color.Data(), 4);
  1020. }
  1021. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  1022. {
  1023. if (shaderProgram_)
  1024. {
  1025. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1026. if (info)
  1027. {
  1028. // Check the uniform type to avoid mismatch
  1029. switch (info->type_)
  1030. {
  1031. case GL_FLOAT:
  1032. glUniform1fv(info->location_, 1, vector.Data());
  1033. break;
  1034. case GL_FLOAT_VEC2:
  1035. glUniform2fv(info->location_, 1, vector.Data());
  1036. break;
  1037. }
  1038. }
  1039. }
  1040. }
  1041. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1042. {
  1043. if (shaderProgram_)
  1044. {
  1045. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1046. if (info)
  1047. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  1048. }
  1049. }
  1050. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1051. {
  1052. if (shaderProgram_)
  1053. {
  1054. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1055. if (info)
  1056. {
  1057. // Check the uniform type to avoid mismatch
  1058. switch (info->type_)
  1059. {
  1060. case GL_FLOAT:
  1061. glUniform1fv(info->location_, 1, vector.Data());
  1062. break;
  1063. case GL_FLOAT_VEC2:
  1064. glUniform2fv(info->location_, 1, vector.Data());
  1065. break;
  1066. case GL_FLOAT_VEC3:
  1067. glUniform3fv(info->location_, 1, vector.Data());
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. }
  1073. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1074. {
  1075. if (shaderProgram_)
  1076. {
  1077. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1078. if (info)
  1079. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  1080. }
  1081. }
  1082. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1083. {
  1084. if (shaderProgram_)
  1085. {
  1086. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1087. if (info)
  1088. {
  1089. // Check the uniform type to avoid mismatch
  1090. switch (info->type_)
  1091. {
  1092. case GL_FLOAT:
  1093. glUniform1fv(info->location_, 1, vector.Data());
  1094. break;
  1095. case GL_FLOAT_VEC2:
  1096. glUniform2fv(info->location_, 1, vector.Data());
  1097. break;
  1098. case GL_FLOAT_VEC3:
  1099. glUniform3fv(info->location_, 1, vector.Data());
  1100. break;
  1101. case GL_FLOAT_VEC4:
  1102. glUniform4fv(info->location_, 1, vector.Data());
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1109. {
  1110. if (shaderProgram_)
  1111. {
  1112. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  1113. if (info)
  1114. {
  1115. float data[16];
  1116. data[0] = matrix.m00_;
  1117. data[1] = matrix.m10_;
  1118. data[2] = matrix.m20_;
  1119. data[3] = 0.0f;
  1120. data[4] = matrix.m01_;
  1121. data[5] = matrix.m11_;
  1122. data[6] = matrix.m21_;
  1123. data[7] = 0.0f;
  1124. data[8] = matrix.m02_;
  1125. data[9] = matrix.m12_;
  1126. data[10] = matrix.m22_;
  1127. data[11] = 0.0f;
  1128. data[12] = matrix.m03_;
  1129. data[13] = matrix.m13_;
  1130. data[14] = matrix.m23_;
  1131. data[15] = 1.0f;
  1132. glUniformMatrix4fv(info->location_, 1, GL_FALSE, data);
  1133. }
  1134. }
  1135. }
  1136. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1137. {
  1138. switch (value.GetType())
  1139. {
  1140. case VAR_BOOL:
  1141. SetShaderParameter(param, value.GetBool());
  1142. break;
  1143. case VAR_FLOAT:
  1144. SetShaderParameter(param, value.GetFloat());
  1145. break;
  1146. case VAR_VECTOR2:
  1147. SetShaderParameter(param, value.GetVector2());
  1148. break;
  1149. case VAR_VECTOR3:
  1150. SetShaderParameter(param, value.GetVector3());
  1151. break;
  1152. case VAR_VECTOR4:
  1153. SetShaderParameter(param, value.GetVector4());
  1154. break;
  1155. case VAR_COLOR:
  1156. SetShaderParameter(param, value.GetColor());
  1157. break;
  1158. case VAR_MATRIX3:
  1159. SetShaderParameter(param, value.GetMatrix3());
  1160. break;
  1161. case VAR_MATRIX3X4:
  1162. SetShaderParameter(param, value.GetMatrix3x4());
  1163. break;
  1164. case VAR_MATRIX4:
  1165. SetShaderParameter(param, value.GetMatrix4());
  1166. break;
  1167. default:
  1168. // Unsupported parameter type, do nothing
  1169. break;
  1170. }
  1171. }
  1172. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1173. {
  1174. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1175. {
  1176. shaderParameterSources_[group] = source;
  1177. return true;
  1178. }
  1179. else
  1180. return false;
  1181. }
  1182. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  1183. {
  1184. return shaderProgram_ && shaderProgram_->HasParameter(param);
  1185. }
  1186. bool Graphics::HasTextureUnit(TextureUnit unit)
  1187. {
  1188. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  1189. }
  1190. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1191. {
  1192. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1193. }
  1194. void Graphics::ClearParameterSources()
  1195. {
  1196. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1197. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1198. }
  1199. void Graphics::ClearTransformSources()
  1200. {
  1201. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1202. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  1203. }
  1204. void Graphics::CleanupShaderPrograms()
  1205. {
  1206. // Ignore individual call from ShaderVariation instance when Graphics subsystem is in process of
  1207. // releasing all GPU objects or recreating GPU objects due device lost, because the Graphics subsystem
  1208. // will eventually erase all the shader programs afterward as part of the release process.
  1209. if (releasingGPUObjects_)
  1210. return;
  1211. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  1212. {
  1213. ShaderVariation* vs = i->second_->GetVertexShader();
  1214. ShaderVariation* ps = i->second_->GetPixelShader();
  1215. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  1216. i = shaderPrograms_.Erase(i);
  1217. else
  1218. ++i;
  1219. }
  1220. }
  1221. void Graphics::SetTexture(unsigned index, Texture* texture)
  1222. {
  1223. if (index >= MAX_TEXTURE_UNITS)
  1224. return;
  1225. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1226. if (texture)
  1227. {
  1228. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1229. texture = texture->GetBackupTexture();
  1230. }
  1231. if (textures_[index] != texture)
  1232. {
  1233. if (impl_->activeTexture_ != index)
  1234. {
  1235. glActiveTexture(GL_TEXTURE0 + index);
  1236. impl_->activeTexture_ = index;
  1237. }
  1238. if (texture)
  1239. {
  1240. unsigned glType = texture->GetTarget();
  1241. if (glType != textureTypes_[index])
  1242. {
  1243. if (textureTypes_[index])
  1244. glDisable(textureTypes_[index]);
  1245. glEnable(glType);
  1246. textureTypes_[index] = glType;
  1247. }
  1248. glBindTexture(glType, texture->GetGPUObject());
  1249. if (texture->GetParametersDirty())
  1250. texture->UpdateParameters();
  1251. }
  1252. else
  1253. {
  1254. if (textureTypes_[index])
  1255. glBindTexture(textureTypes_[index], 0);
  1256. }
  1257. textures_[index] = texture;
  1258. }
  1259. else
  1260. {
  1261. if (texture && texture->GetParametersDirty())
  1262. {
  1263. if (impl_->activeTexture_ != index)
  1264. {
  1265. glActiveTexture(GL_TEXTURE0 + index);
  1266. impl_->activeTexture_ = index;
  1267. }
  1268. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1269. texture->UpdateParameters();
  1270. }
  1271. }
  1272. }
  1273. void Graphics::SetTextureForUpdate(Texture* texture)
  1274. {
  1275. if (impl_->activeTexture_ != 0)
  1276. {
  1277. glActiveTexture(GL_TEXTURE0);
  1278. impl_->activeTexture_ = 0;
  1279. }
  1280. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1281. textures_[0] = texture;
  1282. }
  1283. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1284. {
  1285. if (mode != defaultTextureFilterMode_)
  1286. {
  1287. defaultTextureFilterMode_ = mode;
  1288. SetTextureParametersDirty();
  1289. }
  1290. }
  1291. void Graphics::SetTextureAnisotropy(unsigned level)
  1292. {
  1293. if (level != textureAnisotropy_)
  1294. {
  1295. textureAnisotropy_ = level;
  1296. SetTextureParametersDirty();
  1297. }
  1298. }
  1299. void Graphics::SetTextureParametersDirty()
  1300. {
  1301. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1302. {
  1303. Texture* texture = dynamic_cast<Texture*>(*i);
  1304. if (texture)
  1305. texture->SetParametersDirty();
  1306. }
  1307. }
  1308. void Graphics::ResetRenderTargets()
  1309. {
  1310. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1311. SetRenderTarget(i, (RenderSurface*)0);
  1312. SetDepthStencil((RenderSurface*)0);
  1313. SetViewport(IntRect(0, 0, width_, height_));
  1314. }
  1315. void Graphics::ResetRenderTarget(unsigned index)
  1316. {
  1317. SetRenderTarget(index, (RenderSurface*)0);
  1318. }
  1319. void Graphics::ResetDepthStencil()
  1320. {
  1321. SetDepthStencil((RenderSurface*)0);
  1322. }
  1323. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1324. {
  1325. if (index >= MAX_RENDERTARGETS)
  1326. return;
  1327. if (renderTarget != renderTargets_[index])
  1328. {
  1329. renderTargets_[index] = renderTarget;
  1330. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1331. if (renderTarget)
  1332. {
  1333. Texture* parentTexture = renderTarget->GetParentTexture();
  1334. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1335. {
  1336. if (textures_[i] == parentTexture)
  1337. SetTexture(i, textures_[i]->GetBackupTexture());
  1338. }
  1339. }
  1340. impl_->fboDirty_ = true;
  1341. }
  1342. }
  1343. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1344. {
  1345. RenderSurface* renderTarget = 0;
  1346. if (texture)
  1347. renderTarget = texture->GetRenderSurface();
  1348. SetRenderTarget(index, renderTarget);
  1349. }
  1350. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1351. {
  1352. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1353. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1354. if (renderTargets_[0] && !depthStencil)
  1355. {
  1356. int width = renderTargets_[0]->GetWidth();
  1357. int height = renderTargets_[0]->GetHeight();
  1358. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1359. // Check size similarly
  1360. if (width <= width_ && height <= height_)
  1361. {
  1362. int searchKey = (width << 16) | height;
  1363. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1364. if (i != depthTextures_.End())
  1365. depthStencil = i->second_->GetRenderSurface();
  1366. else
  1367. {
  1368. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1369. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1370. depthTextures_[searchKey] = newDepthTexture;
  1371. depthStencil = newDepthTexture->GetRenderSurface();
  1372. }
  1373. }
  1374. }
  1375. if (depthStencil != depthStencil_)
  1376. {
  1377. depthStencil_ = depthStencil;
  1378. impl_->fboDirty_ = true;
  1379. }
  1380. }
  1381. void Graphics::SetDepthStencil(Texture2D* texture)
  1382. {
  1383. RenderSurface* depthStencil = 0;
  1384. if (texture)
  1385. depthStencil = texture->GetRenderSurface();
  1386. SetDepthStencil(depthStencil);
  1387. }
  1388. void Graphics::SetViewport(const IntRect& rect)
  1389. {
  1390. if (impl_->fboDirty_)
  1391. CommitFramebuffer();
  1392. IntVector2 rtSize = GetRenderTargetDimensions();
  1393. IntRect rectCopy = rect;
  1394. if (rectCopy.right_ <= rectCopy.left_)
  1395. rectCopy.right_ = rectCopy.left_ + 1;
  1396. if (rectCopy.bottom_ <= rectCopy.top_)
  1397. rectCopy.bottom_ = rectCopy.top_ + 1;
  1398. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1399. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1400. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1401. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1402. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1403. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.Width(), rectCopy.Height());
  1404. viewport_ = rectCopy;
  1405. // Disable scissor test, needs to be re-enabled by the user
  1406. SetScissorTest(false);
  1407. }
  1408. void Graphics::SetBlendMode(BlendMode mode)
  1409. {
  1410. if (mode != blendMode_)
  1411. {
  1412. if (mode == BLEND_REPLACE)
  1413. glDisable(GL_BLEND);
  1414. else
  1415. {
  1416. glEnable(GL_BLEND);
  1417. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1418. glBlendEquation(glBlendOp[mode]);
  1419. }
  1420. blendMode_ = mode;
  1421. }
  1422. }
  1423. void Graphics::SetColorWrite(bool enable)
  1424. {
  1425. if (enable != colorWrite_)
  1426. {
  1427. if (enable)
  1428. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1429. else
  1430. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1431. colorWrite_ = enable;
  1432. }
  1433. }
  1434. void Graphics::SetCullMode(CullMode mode)
  1435. {
  1436. if (mode != cullMode_)
  1437. {
  1438. if (mode == CULL_NONE)
  1439. glDisable(GL_CULL_FACE);
  1440. else
  1441. {
  1442. // Use Direct3D convention, ie. clockwise vertices define a front face
  1443. glEnable(GL_CULL_FACE);
  1444. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1445. }
  1446. cullMode_ = mode;
  1447. }
  1448. }
  1449. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1450. {
  1451. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1452. {
  1453. #ifndef GL_ES_VERSION_2_0
  1454. if (slopeScaledBias != 0.0f)
  1455. {
  1456. // OpenGL constant bias is unreliable and dependant on depth buffer bitdepth, apply in the projection matrix instead
  1457. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1458. glEnable(GL_POLYGON_OFFSET_FILL);
  1459. glPolygonOffset(adjustedSlopeScaledBias, 0.0f);
  1460. }
  1461. else
  1462. glDisable(GL_POLYGON_OFFSET_FILL);
  1463. #endif
  1464. constantDepthBias_ = constantBias;
  1465. slopeScaledDepthBias_ = slopeScaledBias;
  1466. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1467. }
  1468. }
  1469. void Graphics::SetDepthTest(CompareMode mode)
  1470. {
  1471. if (mode != depthTestMode_)
  1472. {
  1473. glDepthFunc(glCmpFunc[mode]);
  1474. depthTestMode_ = mode;
  1475. }
  1476. }
  1477. void Graphics::SetDepthWrite(bool enable)
  1478. {
  1479. if (enable != depthWrite_)
  1480. {
  1481. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1482. depthWrite_ = enable;
  1483. }
  1484. }
  1485. void Graphics::SetFillMode(FillMode mode)
  1486. {
  1487. #ifndef GL_ES_VERSION_2_0
  1488. if (mode != fillMode_)
  1489. {
  1490. glPolygonMode(GL_FRONT_AND_BACK, glFillMode[mode]);
  1491. fillMode_ = mode;
  1492. }
  1493. #endif
  1494. }
  1495. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1496. {
  1497. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1498. // Disable scissor in that case to reduce state changes
  1499. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1500. enable = false;
  1501. if (enable)
  1502. {
  1503. IntVector2 rtSize(GetRenderTargetDimensions());
  1504. IntVector2 viewSize(viewport_.Size());
  1505. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1506. IntRect intRect;
  1507. int expand = borderInclusive ? 1 : 0;
  1508. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1509. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1510. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1511. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1512. if (intRect.right_ == intRect.left_)
  1513. intRect.right_++;
  1514. if (intRect.bottom_ == intRect.top_)
  1515. intRect.bottom_++;
  1516. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1517. enable = false;
  1518. if (enable && scissorRect_ != intRect)
  1519. {
  1520. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1521. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1522. scissorRect_ = intRect;
  1523. }
  1524. }
  1525. else
  1526. scissorRect_ = IntRect::ZERO;
  1527. if (enable != scissorTest_)
  1528. {
  1529. if (enable)
  1530. glEnable(GL_SCISSOR_TEST);
  1531. else
  1532. glDisable(GL_SCISSOR_TEST);
  1533. scissorTest_ = enable;
  1534. }
  1535. }
  1536. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1537. {
  1538. IntVector2 rtSize(GetRenderTargetDimensions());
  1539. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1540. if (enable)
  1541. {
  1542. IntRect intRect;
  1543. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1544. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1545. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1546. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1547. if (intRect.right_ == intRect.left_)
  1548. intRect.right_++;
  1549. if (intRect.bottom_ == intRect.top_)
  1550. intRect.bottom_++;
  1551. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1552. enable = false;
  1553. if (enable && scissorRect_ != intRect)
  1554. {
  1555. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1556. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1557. scissorRect_ = intRect;
  1558. }
  1559. }
  1560. else
  1561. scissorRect_ = IntRect::ZERO;
  1562. if (enable != scissorTest_)
  1563. {
  1564. if (enable)
  1565. glEnable(GL_SCISSOR_TEST);
  1566. else
  1567. glDisable(GL_SCISSOR_TEST);
  1568. scissorTest_ = enable;
  1569. }
  1570. }
  1571. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1572. {
  1573. #ifndef GL_ES_VERSION_2_0
  1574. if (enable != useClipPlane_)
  1575. {
  1576. if (enable)
  1577. glEnable(GL_CLIP_PLANE0);
  1578. else
  1579. glDisable(GL_CLIP_PLANE0);
  1580. useClipPlane_ = enable;
  1581. }
  1582. if (enable)
  1583. {
  1584. Matrix4 viewProj = projection * view;
  1585. Vector4 planeVec = clipPlane.Transformed(viewProj).ToVector4();
  1586. GLdouble planeData[4];
  1587. planeData[0] = planeVec.x_;
  1588. planeData[1] = planeVec.y_;
  1589. planeData[2] = planeVec.z_;
  1590. planeData[3] = planeVec.w_;
  1591. glClipPlane(GL_CLIP_PLANE0, &planeData[0]);
  1592. }
  1593. #endif
  1594. }
  1595. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1596. {
  1597. }
  1598. void Graphics::ResetStreamFrequencies()
  1599. {
  1600. }
  1601. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1602. {
  1603. #ifndef GL_ES_VERSION_2_0
  1604. if (enable != stencilTest_)
  1605. {
  1606. if (enable)
  1607. glEnable(GL_STENCIL_TEST);
  1608. else
  1609. glDisable(GL_STENCIL_TEST);
  1610. stencilTest_ = enable;
  1611. }
  1612. if (enable)
  1613. {
  1614. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1615. {
  1616. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1617. stencilTestMode_ = mode;
  1618. stencilRef_ = stencilRef;
  1619. stencilCompareMask_ = compareMask;
  1620. }
  1621. if (writeMask != stencilWriteMask_)
  1622. {
  1623. glStencilMask(writeMask);
  1624. stencilWriteMask_ = writeMask;
  1625. }
  1626. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1627. {
  1628. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1629. stencilPass_ = pass;
  1630. stencilFail_ = fail;
  1631. stencilZFail_ = zFail;
  1632. }
  1633. }
  1634. #endif
  1635. }
  1636. void Graphics::SetForceSM2(bool enable)
  1637. {
  1638. }
  1639. void Graphics::BeginDumpShaders(const String& fileName)
  1640. {
  1641. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1642. }
  1643. void Graphics::EndDumpShaders()
  1644. {
  1645. shaderPrecache_.Reset();
  1646. }
  1647. void Graphics::PrecacheShaders(Deserializer& source)
  1648. {
  1649. PROFILE(PrecacheShaders);
  1650. ShaderPrecache::LoadShaders(this, source);
  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. }