OGLGraphics.cpp 89 KB

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