OGLGraphics.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392
  1. //
  2. // Copyright (c) 2008-2018 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 "../../Core/Context.h"
  24. #include "../../Core/Mutex.h"
  25. #include "../../Core/ProcessUtils.h"
  26. #include "../../Core/Profiler.h"
  27. #include "../../Graphics/ConstantBuffer.h"
  28. #include "../../Graphics/Graphics.h"
  29. #include "../../Graphics/GraphicsEvents.h"
  30. #include "../../Graphics/GraphicsImpl.h"
  31. #include "../../Graphics/IndexBuffer.h"
  32. #include "../../Graphics/RenderSurface.h"
  33. #include "../../Graphics/Shader.h"
  34. #include "../../Graphics/ShaderPrecache.h"
  35. #include "../../Graphics/ShaderProgram.h"
  36. #include "../../Graphics/ShaderVariation.h"
  37. #include "../../Graphics/Texture2D.h"
  38. #include "../../Graphics/TextureCube.h"
  39. #include "../../Graphics/VertexBuffer.h"
  40. #include "../../IO/File.h"
  41. #include "../../IO/Log.h"
  42. #include "../../Resource/ResourceCache.h"
  43. #include <SDL/SDL.h>
  44. #include "../../DebugNew.h"
  45. #ifdef GL_ES_VERSION_2_0
  46. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  47. #define glClearDepth glClearDepthf
  48. #endif
  49. #ifdef __EMSCRIPTEN__
  50. // Emscripten provides even all GL extension functions via static linking. However there is
  51. // no GLES2-specific extension header at the moment to include instanced rendering declarations,
  52. // so declare them manually from GLES3 gl2ext.h. Emscripten will provide these when linking final output.
  53. extern "C"
  54. {
  55. GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
  56. GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
  57. GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE (GLuint index, GLuint divisor);
  58. }
  59. #endif
  60. #ifdef _WIN32
  61. // Prefer the high-performance GPU on switchable GPU systems
  62. #include <windows.h>
  63. extern "C"
  64. {
  65. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  66. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  67. }
  68. #endif
  69. namespace Urho3D
  70. {
  71. static const unsigned glCmpFunc[] =
  72. {
  73. GL_ALWAYS,
  74. GL_EQUAL,
  75. GL_NOTEQUAL,
  76. GL_LESS,
  77. GL_LEQUAL,
  78. GL_GREATER,
  79. GL_GEQUAL
  80. };
  81. static const unsigned glSrcBlend[] =
  82. {
  83. GL_ONE,
  84. GL_ONE,
  85. GL_DST_COLOR,
  86. GL_SRC_ALPHA,
  87. GL_SRC_ALPHA,
  88. GL_ONE,
  89. GL_ONE_MINUS_DST_ALPHA,
  90. GL_ONE,
  91. GL_SRC_ALPHA
  92. };
  93. static const unsigned glDestBlend[] =
  94. {
  95. GL_ZERO,
  96. GL_ONE,
  97. GL_ZERO,
  98. GL_ONE_MINUS_SRC_ALPHA,
  99. GL_ONE,
  100. GL_ONE_MINUS_SRC_ALPHA,
  101. GL_DST_ALPHA,
  102. GL_ONE,
  103. GL_ONE
  104. };
  105. static const unsigned glBlendOp[] =
  106. {
  107. GL_FUNC_ADD,
  108. GL_FUNC_ADD,
  109. GL_FUNC_ADD,
  110. GL_FUNC_ADD,
  111. GL_FUNC_ADD,
  112. GL_FUNC_ADD,
  113. GL_FUNC_ADD,
  114. GL_FUNC_REVERSE_SUBTRACT,
  115. GL_FUNC_REVERSE_SUBTRACT
  116. };
  117. #ifndef GL_ES_VERSION_2_0
  118. static const unsigned glFillMode[] =
  119. {
  120. GL_FILL,
  121. GL_LINE,
  122. GL_POINT
  123. };
  124. static const unsigned glStencilOps[] =
  125. {
  126. GL_KEEP,
  127. GL_ZERO,
  128. GL_REPLACE,
  129. GL_INCR_WRAP,
  130. GL_DECR_WRAP
  131. };
  132. #endif
  133. static const unsigned glElementTypes[] =
  134. {
  135. GL_INT,
  136. GL_FLOAT,
  137. GL_FLOAT,
  138. GL_FLOAT,
  139. GL_FLOAT,
  140. GL_UNSIGNED_BYTE,
  141. GL_UNSIGNED_BYTE
  142. };
  143. static const unsigned glElementComponents[] =
  144. {
  145. 1,
  146. 1,
  147. 2,
  148. 3,
  149. 4,
  150. 4,
  151. 4
  152. };
  153. #ifdef GL_ES_VERSION_2_0
  154. static unsigned glesDepthStencilFormat = GL_DEPTH_COMPONENT16;
  155. static unsigned glesReadableDepthFormat = GL_DEPTH_COMPONENT;
  156. #endif
  157. static String extensions;
  158. bool CheckExtension(const String& name)
  159. {
  160. if (extensions.Empty())
  161. extensions = (const char*)glGetString(GL_EXTENSIONS);
  162. return extensions.Contains(name);
  163. }
  164. static void GetGLPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount, GLenum& glPrimitiveType)
  165. {
  166. switch (type)
  167. {
  168. case TRIANGLE_LIST:
  169. primitiveCount = elementCount / 3;
  170. glPrimitiveType = GL_TRIANGLES;
  171. break;
  172. case LINE_LIST:
  173. primitiveCount = elementCount / 2;
  174. glPrimitiveType = GL_LINES;
  175. break;
  176. case POINT_LIST:
  177. primitiveCount = elementCount;
  178. glPrimitiveType = GL_POINTS;
  179. break;
  180. case TRIANGLE_STRIP:
  181. primitiveCount = elementCount - 2;
  182. glPrimitiveType = GL_TRIANGLE_STRIP;
  183. break;
  184. case LINE_STRIP:
  185. primitiveCount = elementCount - 1;
  186. glPrimitiveType = GL_LINE_STRIP;
  187. break;
  188. case TRIANGLE_FAN:
  189. primitiveCount = elementCount - 2;
  190. glPrimitiveType = GL_TRIANGLE_FAN;
  191. break;
  192. }
  193. }
  194. const Vector2 Graphics::pixelUVOffset(0.0f, 0.0f);
  195. bool Graphics::gl3Support = false;
  196. Graphics::Graphics(Context* context) :
  197. Object(context),
  198. impl_(new GraphicsImpl()),
  199. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  200. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  201. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  202. shaderPath_("Shaders/GLSL/"),
  203. shaderExtension_(".glsl"),
  204. orientations_("LandscapeLeft LandscapeRight"),
  205. #ifndef GL_ES_VERSION_2_0
  206. apiName_("GL2")
  207. #else
  208. apiName_("GLES2")
  209. #endif
  210. {
  211. SetTextureUnitMappings();
  212. ResetCachedState();
  213. context_->RequireSDL(SDL_INIT_VIDEO);
  214. // Register Graphics library object factories
  215. RegisterGraphicsLibrary(context_);
  216. }
  217. Graphics::~Graphics()
  218. {
  219. Close();
  220. delete impl_;
  221. impl_ = nullptr;
  222. context_->ReleaseSDL();
  223. }
  224. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool highDPI, bool vsync,
  225. bool tripleBuffer, int multiSample, int monitor, int refreshRate)
  226. {
  227. URHO3D_PROFILE(SetScreenMode);
  228. bool maximize = false;
  229. #if defined(IOS) || defined(TVOS)
  230. // iOS and tvOS app always take the fullscreen (and with status bar hidden)
  231. fullscreen = true;
  232. #endif
  233. // Make sure monitor index is not bigger than the currently detected monitors
  234. int monitors = SDL_GetNumVideoDisplays();
  235. if (monitor >= monitors || monitor < 0)
  236. monitor = 0; // this monitor is not present, use first monitor
  237. // Fullscreen or Borderless can not be resizable
  238. if (fullscreen || borderless)
  239. resizable = false;
  240. // Borderless cannot be fullscreen, they are mutually exclusive
  241. if (borderless)
  242. fullscreen = false;
  243. multiSample = Clamp(multiSample, 1, 16);
  244. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ &&
  245. resizable == resizable_ && vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  246. return true;
  247. // If only vsync changes, do not destroy/recreate the context
  248. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ &&
  249. resizable == resizable_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  250. {
  251. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  252. vsync_ = vsync;
  253. return true;
  254. }
  255. // If zero dimensions in windowed mode, set windowed mode to maximize and set a predefined default restored window size.
  256. // If zero in fullscreen, use desktop mode
  257. if (!width || !height)
  258. {
  259. if (fullscreen || borderless)
  260. {
  261. SDL_DisplayMode mode;
  262. SDL_GetDesktopDisplayMode(monitor, &mode);
  263. width = mode.w;
  264. height = mode.h;
  265. }
  266. else
  267. {
  268. maximize = resizable;
  269. width = 1024;
  270. height = 768;
  271. }
  272. }
  273. // Check fullscreen mode validity (desktop only). Use a closest match if not found
  274. #ifdef DESKTOP_GRAPHICS
  275. if (fullscreen)
  276. {
  277. PODVector<IntVector3> resolutions = GetResolutions(monitor);
  278. if (resolutions.Size())
  279. {
  280. unsigned best = 0;
  281. unsigned bestError = M_MAX_UNSIGNED;
  282. for (unsigned i = 0; i < resolutions.Size(); ++i)
  283. {
  284. unsigned error = Abs(resolutions[i].x_ - width) + Abs(resolutions[i].y_ - height);
  285. if (error < bestError)
  286. {
  287. best = i;
  288. bestError = error;
  289. }
  290. }
  291. width = resolutions[best].x_;
  292. height = resolutions[best].y_;
  293. refreshRate = resolutions[best].z_;
  294. }
  295. }
  296. #endif
  297. // With an external window, only the size can change after initial setup, so do not recreate context
  298. if (!externalWindow_ || !impl_->context_)
  299. {
  300. // Close the existing window and OpenGL context, mark GPU objects as lost
  301. Release(false, true);
  302. #ifdef IOS
  303. // On iOS window needs to be resizable to handle orientation changes properly
  304. resizable = true;
  305. #endif
  306. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  307. #ifndef GL_ES_VERSION_2_0
  308. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  309. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  310. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  311. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  312. if (externalWindow_)
  313. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  314. else
  315. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  316. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  317. if (!forceGL2_)
  318. {
  319. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  320. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
  321. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  322. }
  323. else
  324. {
  325. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  326. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  327. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  328. }
  329. #else
  330. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  331. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  332. #endif
  333. if (multiSample > 1)
  334. {
  335. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  336. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  337. }
  338. else
  339. {
  340. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  341. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  342. }
  343. SDL_Rect display_rect;
  344. SDL_GetDisplayBounds(monitor, &display_rect);
  345. bool reposition = fullscreen || (borderless && width >= display_rect.w && height >= display_rect.h);
  346. int x = reposition ? display_rect.x : position_.x_;
  347. int y = reposition ? display_rect.y : position_.y_;
  348. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  349. if (fullscreen)
  350. flags |= SDL_WINDOW_FULLSCREEN;
  351. if (borderless)
  352. flags |= SDL_WINDOW_BORDERLESS;
  353. if (resizable)
  354. flags |= SDL_WINDOW_RESIZABLE;
  355. if (highDPI)
  356. flags |= SDL_WINDOW_ALLOW_HIGHDPI;
  357. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  358. for (;;)
  359. {
  360. if (!externalWindow_)
  361. window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  362. else
  363. {
  364. #ifndef __EMSCRIPTEN__
  365. if (!window_)
  366. window_ = SDL_CreateWindowFrom(externalWindow_, SDL_WINDOW_OPENGL);
  367. fullscreen = false;
  368. #endif
  369. }
  370. if (window_)
  371. break;
  372. else
  373. {
  374. if (multiSample > 1)
  375. {
  376. // If failed with multisampling, retry first without
  377. multiSample = 1;
  378. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  379. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  380. }
  381. else
  382. {
  383. URHO3D_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  384. return false;
  385. }
  386. }
  387. }
  388. // Reposition the window on the specified monitor
  389. if (reposition)
  390. SDL_SetWindowPosition(window_, display_rect.x, display_rect.y);
  391. CreateWindowIcon();
  392. if (maximize)
  393. {
  394. Maximize();
  395. SDL_GL_GetDrawableSize(window_, &width, &height);
  396. }
  397. // Create/restore context and GPU objects and set initial renderstate
  398. Restore();
  399. // Specific error message is already logged by Restore() when context creation or OpenGL extensions check fails
  400. if (!impl_->context_)
  401. return false;
  402. }
  403. // Set vsync
  404. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  405. // Store the system FBO on iOS/tvOS now
  406. #if defined(IOS) || defined(TVOS)
  407. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFBO_);
  408. #endif
  409. fullscreen_ = fullscreen;
  410. borderless_ = borderless;
  411. resizable_ = resizable;
  412. vsync_ = vsync;
  413. tripleBuffer_ = tripleBuffer;
  414. multiSample_ = multiSample;
  415. monitor_ = monitor;
  416. refreshRate_ = refreshRate;
  417. SDL_GL_GetDrawableSize(window_, &width_, &height_);
  418. if (!fullscreen)
  419. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  420. int logicalWidth, logicalHeight;
  421. SDL_GetWindowSize(window_, &logicalWidth, &logicalHeight);
  422. highDPI_ = (width_ != logicalWidth) || (height_ != logicalHeight);
  423. // Reset rendertargets and viewport for the new screen mode
  424. ResetRenderTargets();
  425. // Clear the initial window contents to black
  426. Clear(CLEAR_COLOR);
  427. SDL_GL_SwapWindow(window_);
  428. CheckFeatureSupport();
  429. #ifdef URHO3D_LOGGING
  430. String msg;
  431. msg.AppendWithFormat("Set screen mode %dx%d %s monitor %d", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"), monitor_);
  432. if (borderless_)
  433. msg.Append(" borderless");
  434. if (resizable_)
  435. msg.Append(" resizable");
  436. if (multiSample > 1)
  437. msg.AppendWithFormat(" multisample %d", multiSample);
  438. URHO3D_LOGINFO(msg);
  439. #endif
  440. using namespace ScreenMode;
  441. VariantMap& eventData = GetEventDataMap();
  442. eventData[P_WIDTH] = width_;
  443. eventData[P_HEIGHT] = height_;
  444. eventData[P_FULLSCREEN] = fullscreen_;
  445. eventData[P_BORDERLESS] = borderless_;
  446. eventData[P_RESIZABLE] = resizable_;
  447. eventData[P_HIGHDPI] = highDPI_;
  448. eventData[P_MONITOR] = monitor_;
  449. eventData[P_REFRESHRATE] = refreshRate_;
  450. SendEvent(E_SCREENMODE, eventData);
  451. return true;
  452. }
  453. bool Graphics::SetMode(int width, int height)
  454. {
  455. return SetMode(width, height, fullscreen_, borderless_, resizable_, highDPI_, vsync_, tripleBuffer_, multiSample_, monitor_, refreshRate_);
  456. }
  457. void Graphics::SetSRGB(bool enable)
  458. {
  459. enable &= sRGBWriteSupport_;
  460. if (enable != sRGB_)
  461. {
  462. sRGB_ = enable;
  463. impl_->fboDirty_ = true;
  464. }
  465. }
  466. void Graphics::SetDither(bool enable)
  467. {
  468. if (enable)
  469. glEnable(GL_DITHER);
  470. else
  471. glDisable(GL_DITHER);
  472. }
  473. void Graphics::SetFlushGPU(bool enable)
  474. {
  475. // Currently unimplemented on OpenGL
  476. }
  477. void Graphics::SetForceGL2(bool enable)
  478. {
  479. if (IsInitialized())
  480. {
  481. URHO3D_LOGERROR("OpenGL 2 can only be forced before setting the initial screen mode");
  482. return;
  483. }
  484. forceGL2_ = enable;
  485. }
  486. void Graphics::Close()
  487. {
  488. if (!IsInitialized())
  489. return;
  490. // Actually close the window
  491. Release(true, true);
  492. }
  493. bool Graphics::TakeScreenShot(Image& destImage)
  494. {
  495. URHO3D_PROFILE(TakeScreenShot);
  496. if (!IsInitialized())
  497. return false;
  498. if (IsDeviceLost())
  499. {
  500. URHO3D_LOGERROR("Can not take screenshot while device is lost");
  501. return false;
  502. }
  503. ResetRenderTargets();
  504. #ifndef GL_ES_VERSION_2_0
  505. destImage.SetSize(width_, height_, 3);
  506. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  507. #else
  508. // Use RGBA format on OpenGL ES, as otherwise (at least on Android) the produced image is all black
  509. destImage.SetSize(width_, height_, 4);
  510. glReadPixels(0, 0, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE, destImage.GetData());
  511. #endif
  512. // On OpenGL we need to flip the image vertically after reading
  513. destImage.FlipVertical();
  514. return true;
  515. }
  516. bool Graphics::BeginFrame()
  517. {
  518. if (!IsInitialized() || IsDeviceLost())
  519. return false;
  520. // If using an external window, check it for size changes, and reset screen mode if necessary
  521. if (externalWindow_)
  522. {
  523. int width, height;
  524. SDL_GL_GetDrawableSize(window_, &width, &height);
  525. if (width != width_ || height != height_)
  526. SetMode(width, height);
  527. }
  528. // Re-enable depth test and depth func in case a third party program has modified it
  529. glEnable(GL_DEPTH_TEST);
  530. glDepthFunc(glCmpFunc[depthTestMode_]);
  531. // Set default rendertarget and depth buffer
  532. ResetRenderTargets();
  533. // Cleanup textures from previous frame
  534. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  535. SetTexture(i, nullptr);
  536. // Enable color and depth write
  537. SetColorWrite(true);
  538. SetDepthWrite(true);
  539. numPrimitives_ = 0;
  540. numBatches_ = 0;
  541. SendEvent(E_BEGINRENDERING);
  542. return true;
  543. }
  544. void Graphics::EndFrame()
  545. {
  546. if (!IsInitialized())
  547. return;
  548. URHO3D_PROFILE(Present);
  549. SendEvent(E_ENDRENDERING);
  550. SDL_GL_SwapWindow(window_);
  551. // Clean up too large scratch buffers
  552. CleanupScratchBuffers();
  553. }
  554. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  555. {
  556. PrepareDraw();
  557. #ifdef GL_ES_VERSION_2_0
  558. flags &= ~CLEAR_STENCIL;
  559. #endif
  560. bool oldColorWrite = colorWrite_;
  561. bool oldDepthWrite = depthWrite_;
  562. if (flags & CLEAR_COLOR && !oldColorWrite)
  563. SetColorWrite(true);
  564. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  565. SetDepthWrite(true);
  566. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  567. glStencilMask(M_MAX_UNSIGNED);
  568. unsigned glFlags = 0;
  569. if (flags & CLEAR_COLOR)
  570. {
  571. glFlags |= GL_COLOR_BUFFER_BIT;
  572. glClearColor(color.r_, color.g_, color.b_, color.a_);
  573. }
  574. if (flags & CLEAR_DEPTH)
  575. {
  576. glFlags |= GL_DEPTH_BUFFER_BIT;
  577. glClearDepth(depth);
  578. }
  579. if (flags & CLEAR_STENCIL)
  580. {
  581. glFlags |= GL_STENCIL_BUFFER_BIT;
  582. glClearStencil(stencil);
  583. }
  584. // If viewport is less than full screen, set a scissor to limit the clear
  585. /// \todo Any user-set scissor test will be lost
  586. IntVector2 viewSize = GetRenderTargetDimensions();
  587. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  588. SetScissorTest(true, IntRect(0, 0, viewport_.Width(), viewport_.Height()));
  589. else
  590. SetScissorTest(false);
  591. glClear(glFlags);
  592. SetScissorTest(false);
  593. SetColorWrite(oldColorWrite);
  594. SetDepthWrite(oldDepthWrite);
  595. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  596. glStencilMask(stencilWriteMask_);
  597. }
  598. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  599. {
  600. if (!destination || !destination->GetRenderSurface())
  601. return false;
  602. URHO3D_PROFILE(ResolveToTexture);
  603. IntRect vpCopy = viewport;
  604. if (vpCopy.right_ <= vpCopy.left_)
  605. vpCopy.right_ = vpCopy.left_ + 1;
  606. if (vpCopy.bottom_ <= vpCopy.top_)
  607. vpCopy.bottom_ = vpCopy.top_ + 1;
  608. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  609. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  610. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  611. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  612. // Make sure the FBO is not in use
  613. ResetRenderTargets();
  614. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  615. SetTextureForUpdate(destination);
  616. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.Width(), vpCopy.Height());
  617. SetTexture(0, nullptr);
  618. return true;
  619. }
  620. bool Graphics::ResolveToTexture(Texture2D* texture)
  621. {
  622. #ifndef GL_ES_VERSION_2_0
  623. if (!texture)
  624. return false;
  625. RenderSurface* surface = texture->GetRenderSurface();
  626. if (!surface || !surface->GetRenderBuffer())
  627. return false;
  628. URHO3D_PROFILE(ResolveToTexture);
  629. texture->SetResolveDirty(false);
  630. surface->SetResolveDirty(false);
  631. // Use separate FBOs for resolve to not disturb the currently set rendertarget(s)
  632. if (!impl_->resolveSrcFBO_)
  633. impl_->resolveSrcFBO_ = CreateFramebuffer();
  634. if (!impl_->resolveDestFBO_)
  635. impl_->resolveDestFBO_ = CreateFramebuffer();
  636. if (!gl3Support)
  637. {
  638. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, impl_->resolveSrcFBO_);
  639. glFramebufferRenderbufferEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT,
  640. surface->GetRenderBuffer());
  641. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, impl_->resolveDestFBO_);
  642. glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture->GetGPUObjectName(),
  643. 0);
  644. glBlitFramebufferEXT(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  645. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  646. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
  647. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
  648. }
  649. else
  650. {
  651. glBindFramebuffer(GL_READ_FRAMEBUFFER, impl_->resolveSrcFBO_);
  652. glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, surface->GetRenderBuffer());
  653. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, impl_->resolveDestFBO_);
  654. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->GetGPUObjectName(), 0);
  655. glBlitFramebuffer(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  656. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  657. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  658. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  659. }
  660. // Restore previously bound FBO
  661. BindFramebuffer(impl_->boundFBO_);
  662. return true;
  663. #else
  664. // Not supported on GLES
  665. return false;
  666. #endif
  667. }
  668. bool Graphics::ResolveToTexture(TextureCube* texture)
  669. {
  670. #ifndef GL_ES_VERSION_2_0
  671. if (!texture)
  672. return false;
  673. URHO3D_PROFILE(ResolveToTexture);
  674. texture->SetResolveDirty(false);
  675. // Use separate FBOs for resolve to not disturb the currently set rendertarget(s)
  676. if (!impl_->resolveSrcFBO_)
  677. impl_->resolveSrcFBO_ = CreateFramebuffer();
  678. if (!impl_->resolveDestFBO_)
  679. impl_->resolveDestFBO_ = CreateFramebuffer();
  680. if (!gl3Support)
  681. {
  682. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  683. {
  684. // Resolve only the surface(s) that were actually rendered to
  685. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  686. if (!surface->IsResolveDirty())
  687. continue;
  688. surface->SetResolveDirty(false);
  689. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, impl_->resolveSrcFBO_);
  690. glFramebufferRenderbufferEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT,
  691. surface->GetRenderBuffer());
  692. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, impl_->resolveDestFBO_);
  693. glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
  694. texture->GetGPUObjectName(), 0);
  695. glBlitFramebufferEXT(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  696. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  697. }
  698. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
  699. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
  700. }
  701. else
  702. {
  703. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  704. {
  705. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  706. if (!surface->IsResolveDirty())
  707. continue;
  708. surface->SetResolveDirty(false);
  709. glBindFramebuffer(GL_READ_FRAMEBUFFER, impl_->resolveSrcFBO_);
  710. glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, surface->GetRenderBuffer());
  711. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, impl_->resolveDestFBO_);
  712. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
  713. texture->GetGPUObjectName(), 0);
  714. glBlitFramebuffer(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  715. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  716. }
  717. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  718. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  719. }
  720. // Restore previously bound FBO
  721. BindFramebuffer(impl_->boundFBO_);
  722. return true;
  723. #else
  724. // Not supported on GLES
  725. return false;
  726. #endif
  727. }
  728. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  729. {
  730. if (!vertexCount)
  731. return;
  732. PrepareDraw();
  733. unsigned primitiveCount;
  734. GLenum glPrimitiveType;
  735. GetGLPrimitiveType(vertexCount, type, primitiveCount, glPrimitiveType);
  736. glDrawArrays(glPrimitiveType, vertexStart, vertexCount);
  737. numPrimitives_ += primitiveCount;
  738. ++numBatches_;
  739. }
  740. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  741. {
  742. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName())
  743. return;
  744. PrepareDraw();
  745. unsigned indexSize = indexBuffer_->GetIndexSize();
  746. unsigned primitiveCount;
  747. GLenum glPrimitiveType;
  748. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  749. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  750. glDrawElements(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  751. numPrimitives_ += primitiveCount;
  752. ++numBatches_;
  753. }
  754. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  755. {
  756. #ifndef GL_ES_VERSION_2_0
  757. if (!gl3Support || !indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName())
  758. return;
  759. PrepareDraw();
  760. unsigned indexSize = indexBuffer_->GetIndexSize();
  761. unsigned primitiveCount;
  762. GLenum glPrimitiveType;
  763. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  764. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  765. glDrawElementsBaseVertex(glPrimitiveType, indexCount, indexType, reinterpret_cast<GLvoid*>(indexStart * indexSize), baseVertexIndex);
  766. numPrimitives_ += primitiveCount;
  767. ++numBatches_;
  768. #endif
  769. }
  770. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  771. unsigned instanceCount)
  772. {
  773. #if !defined(GL_ES_VERSION_2_0) || defined(__EMSCRIPTEN__)
  774. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName() || !instancingSupport_)
  775. return;
  776. PrepareDraw();
  777. unsigned indexSize = indexBuffer_->GetIndexSize();
  778. unsigned primitiveCount;
  779. GLenum glPrimitiveType;
  780. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  781. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  782. #ifdef __EMSCRIPTEN__
  783. glDrawElementsInstancedANGLE(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  784. instanceCount);
  785. #else
  786. if (gl3Support)
  787. {
  788. glDrawElementsInstanced(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  789. instanceCount);
  790. }
  791. else
  792. {
  793. glDrawElementsInstancedARB(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  794. instanceCount);
  795. }
  796. #endif
  797. numPrimitives_ += instanceCount * primitiveCount;
  798. ++numBatches_;
  799. #endif
  800. }
  801. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex,
  802. unsigned vertexCount, unsigned instanceCount)
  803. {
  804. #ifndef GL_ES_VERSION_2_0
  805. if (!gl3Support || !indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName() || !instancingSupport_)
  806. return;
  807. PrepareDraw();
  808. unsigned indexSize = indexBuffer_->GetIndexSize();
  809. unsigned primitiveCount;
  810. GLenum glPrimitiveType;
  811. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  812. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  813. glDrawElementsInstancedBaseVertex(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  814. instanceCount, baseVertexIndex);
  815. numPrimitives_ += instanceCount * primitiveCount;
  816. ++numBatches_;
  817. #endif
  818. }
  819. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  820. {
  821. // Note: this is not multi-instance safe
  822. static PODVector<VertexBuffer*> vertexBuffers(1);
  823. vertexBuffers[0] = buffer;
  824. SetVertexBuffers(vertexBuffers);
  825. }
  826. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, unsigned instanceOffset)
  827. {
  828. if (buffers.Size() > MAX_VERTEX_STREAMS)
  829. {
  830. URHO3D_LOGERROR("Too many vertex buffers");
  831. return false;
  832. }
  833. if (instanceOffset != impl_->lastInstanceOffset_)
  834. {
  835. impl_->lastInstanceOffset_ = instanceOffset;
  836. impl_->vertexBuffersDirty_ = true;
  837. }
  838. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  839. {
  840. VertexBuffer* buffer = nullptr;
  841. if (i < buffers.Size())
  842. buffer = buffers[i];
  843. if (buffer != vertexBuffers_[i])
  844. {
  845. vertexBuffers_[i] = buffer;
  846. impl_->vertexBuffersDirty_ = true;
  847. }
  848. }
  849. return true;
  850. }
  851. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, unsigned instanceOffset)
  852. {
  853. return SetVertexBuffers(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), instanceOffset);
  854. }
  855. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  856. {
  857. if (indexBuffer_ == buffer)
  858. return;
  859. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer ? buffer->GetGPUObjectName() : 0);
  860. indexBuffer_ = buffer;
  861. }
  862. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  863. {
  864. if (vs == vertexShader_ && ps == pixelShader_)
  865. return;
  866. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  867. if (vs && !vs->GetGPUObjectName())
  868. {
  869. if (vs->GetCompilerOutput().Empty())
  870. {
  871. URHO3D_PROFILE(CompileVertexShader);
  872. bool success = vs->Create();
  873. if (success)
  874. URHO3D_LOGDEBUG("Compiled vertex shader " + vs->GetFullName());
  875. else
  876. {
  877. URHO3D_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  878. vs = nullptr;
  879. }
  880. }
  881. else
  882. vs = nullptr;
  883. }
  884. if (ps && !ps->GetGPUObjectName())
  885. {
  886. if (ps->GetCompilerOutput().Empty())
  887. {
  888. URHO3D_PROFILE(CompilePixelShader);
  889. bool success = ps->Create();
  890. if (success)
  891. URHO3D_LOGDEBUG("Compiled pixel shader " + ps->GetFullName());
  892. else
  893. {
  894. URHO3D_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  895. ps = nullptr;
  896. }
  897. }
  898. else
  899. ps = nullptr;
  900. }
  901. if (!vs || !ps)
  902. {
  903. glUseProgram(0);
  904. vertexShader_ = nullptr;
  905. pixelShader_ = nullptr;
  906. impl_->shaderProgram_ = nullptr;
  907. }
  908. else
  909. {
  910. vertexShader_ = vs;
  911. pixelShader_ = ps;
  912. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  913. ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Find(combination);
  914. if (i != impl_->shaderPrograms_.End())
  915. {
  916. // Use the existing linked program
  917. if (i->second_->GetGPUObjectName())
  918. {
  919. glUseProgram(i->second_->GetGPUObjectName());
  920. impl_->shaderProgram_ = i->second_;
  921. }
  922. else
  923. {
  924. glUseProgram(0);
  925. impl_->shaderProgram_ = nullptr;
  926. }
  927. }
  928. else
  929. {
  930. // Link a new combination
  931. URHO3D_PROFILE(LinkShaders);
  932. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  933. if (newProgram->Link())
  934. {
  935. URHO3D_LOGDEBUG("Linked vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName());
  936. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  937. // so it is not necessary to call it again
  938. impl_->shaderProgram_ = newProgram;
  939. }
  940. else
  941. {
  942. URHO3D_LOGERROR("Failed to link vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName() + ":\n" +
  943. newProgram->GetLinkerOutput());
  944. glUseProgram(0);
  945. impl_->shaderProgram_ = nullptr;
  946. }
  947. impl_->shaderPrograms_[combination] = newProgram;
  948. }
  949. }
  950. // Update the clip plane uniform on GL3, and set constant buffers
  951. #ifndef GL_ES_VERSION_2_0
  952. if (gl3Support && impl_->shaderProgram_)
  953. {
  954. const SharedPtr<ConstantBuffer>* constantBuffers = impl_->shaderProgram_->GetConstantBuffers();
  955. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS * 2; ++i)
  956. {
  957. ConstantBuffer* buffer = constantBuffers[i].Get();
  958. if (buffer != impl_->constantBuffers_[i])
  959. {
  960. unsigned object = buffer ? buffer->GetGPUObjectName() : 0;
  961. glBindBufferBase(GL_UNIFORM_BUFFER, i, object);
  962. // Calling glBindBufferBase also affects the generic buffer binding point
  963. impl_->boundUBO_ = object;
  964. impl_->constantBuffers_[i] = buffer;
  965. ShaderProgram::ClearGlobalParameterSource((ShaderParameterGroup)(i % MAX_SHADER_PARAMETER_GROUPS));
  966. }
  967. }
  968. SetShaderParameter(VSP_CLIPPLANE, useClipPlane_ ? clipPlane_ : Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  969. }
  970. #endif
  971. // Store shader combination if shader dumping in progress
  972. if (shaderPrecache_)
  973. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  974. if (impl_->shaderProgram_)
  975. {
  976. impl_->usedVertexAttributes_ = impl_->shaderProgram_->GetUsedVertexAttributes();
  977. impl_->vertexAttributes_ = &impl_->shaderProgram_->GetVertexAttributes();
  978. }
  979. else
  980. {
  981. impl_->usedVertexAttributes_ = 0;
  982. impl_->vertexAttributes_ = nullptr;
  983. }
  984. impl_->vertexBuffersDirty_ = true;
  985. }
  986. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  987. {
  988. if (impl_->shaderProgram_)
  989. {
  990. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  991. if (info)
  992. {
  993. if (info->bufferPtr_)
  994. {
  995. ConstantBuffer* buffer = info->bufferPtr_;
  996. if (!buffer->IsDirty())
  997. impl_->dirtyConstantBuffers_.Push(buffer);
  998. buffer->SetParameter(info->offset_, (unsigned)(count * sizeof(float)), data);
  999. return;
  1000. }
  1001. switch (info->glType_)
  1002. {
  1003. case GL_FLOAT:
  1004. glUniform1fv(info->location_, count, data);
  1005. break;
  1006. case GL_FLOAT_VEC2:
  1007. glUniform2fv(info->location_, count / 2, data);
  1008. break;
  1009. case GL_FLOAT_VEC3:
  1010. glUniform3fv(info->location_, count / 3, data);
  1011. break;
  1012. case GL_FLOAT_VEC4:
  1013. glUniform4fv(info->location_, count / 4, data);
  1014. break;
  1015. case GL_FLOAT_MAT3:
  1016. glUniformMatrix3fv(info->location_, count / 9, GL_FALSE, data);
  1017. break;
  1018. case GL_FLOAT_MAT4:
  1019. glUniformMatrix4fv(info->location_, count / 16, GL_FALSE, data);
  1020. break;
  1021. default: break;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. void Graphics::SetShaderParameter(StringHash param, float value)
  1027. {
  1028. if (impl_->shaderProgram_)
  1029. {
  1030. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1031. if (info)
  1032. {
  1033. if (info->bufferPtr_)
  1034. {
  1035. ConstantBuffer* buffer = info->bufferPtr_;
  1036. if (!buffer->IsDirty())
  1037. impl_->dirtyConstantBuffers_.Push(buffer);
  1038. buffer->SetParameter(info->offset_, sizeof(float), &value);
  1039. return;
  1040. }
  1041. glUniform1fv(info->location_, 1, &value);
  1042. }
  1043. }
  1044. }
  1045. void Graphics::SetShaderParameter(StringHash param, int value)
  1046. {
  1047. if (impl_->shaderProgram_)
  1048. {
  1049. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1050. if (info)
  1051. {
  1052. if (info->bufferPtr_)
  1053. {
  1054. ConstantBuffer* buffer = info->bufferPtr_;
  1055. if (!buffer->IsDirty())
  1056. impl_->dirtyConstantBuffers_.Push(buffer);
  1057. buffer->SetParameter(info->offset_, sizeof(int), &value);
  1058. return;
  1059. }
  1060. glUniform1i(info->location_, value);
  1061. }
  1062. }
  1063. }
  1064. void Graphics::SetShaderParameter(StringHash param, bool value)
  1065. {
  1066. // \todo Not tested
  1067. if (impl_->shaderProgram_)
  1068. {
  1069. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1070. if (info)
  1071. {
  1072. if (info->bufferPtr_)
  1073. {
  1074. ConstantBuffer* buffer = info->bufferPtr_;
  1075. if (!buffer->IsDirty())
  1076. impl_->dirtyConstantBuffers_.Push(buffer);
  1077. buffer->SetParameter(info->offset_, sizeof(bool), &value);
  1078. return;
  1079. }
  1080. glUniform1i(info->location_, (int)value);
  1081. }
  1082. }
  1083. }
  1084. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  1085. {
  1086. SetShaderParameter(param, color.Data(), 4);
  1087. }
  1088. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  1089. {
  1090. if (impl_->shaderProgram_)
  1091. {
  1092. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1093. if (info)
  1094. {
  1095. if (info->bufferPtr_)
  1096. {
  1097. ConstantBuffer* buffer = info->bufferPtr_;
  1098. if (!buffer->IsDirty())
  1099. impl_->dirtyConstantBuffers_.Push(buffer);
  1100. buffer->SetParameter(info->offset_, sizeof(Vector2), &vector);
  1101. return;
  1102. }
  1103. // Check the uniform type to avoid mismatch
  1104. switch (info->glType_)
  1105. {
  1106. case GL_FLOAT:
  1107. glUniform1fv(info->location_, 1, vector.Data());
  1108. break;
  1109. case GL_FLOAT_VEC2:
  1110. glUniform2fv(info->location_, 1, vector.Data());
  1111. break;
  1112. default: break;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1118. {
  1119. if (impl_->shaderProgram_)
  1120. {
  1121. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1122. if (info)
  1123. {
  1124. if (info->bufferPtr_)
  1125. {
  1126. ConstantBuffer* buffer = info->bufferPtr_;
  1127. if (!buffer->IsDirty())
  1128. impl_->dirtyConstantBuffers_.Push(buffer);
  1129. buffer->SetVector3ArrayParameter(info->offset_, 3, &matrix);
  1130. return;
  1131. }
  1132. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Data());
  1133. }
  1134. }
  1135. }
  1136. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1137. {
  1138. if (impl_->shaderProgram_)
  1139. {
  1140. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1141. if (info)
  1142. {
  1143. if (info->bufferPtr_)
  1144. {
  1145. ConstantBuffer* buffer = info->bufferPtr_;
  1146. if (!buffer->IsDirty())
  1147. impl_->dirtyConstantBuffers_.Push(buffer);
  1148. buffer->SetParameter(info->offset_, sizeof(Vector3), &vector);
  1149. return;
  1150. }
  1151. // Check the uniform type to avoid mismatch
  1152. switch (info->glType_)
  1153. {
  1154. case GL_FLOAT:
  1155. glUniform1fv(info->location_, 1, vector.Data());
  1156. break;
  1157. case GL_FLOAT_VEC2:
  1158. glUniform2fv(info->location_, 1, vector.Data());
  1159. break;
  1160. case GL_FLOAT_VEC3:
  1161. glUniform3fv(info->location_, 1, vector.Data());
  1162. break;
  1163. default: break;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1169. {
  1170. if (impl_->shaderProgram_)
  1171. {
  1172. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1173. if (info)
  1174. {
  1175. if (info->bufferPtr_)
  1176. {
  1177. ConstantBuffer* buffer = info->bufferPtr_;
  1178. if (!buffer->IsDirty())
  1179. impl_->dirtyConstantBuffers_.Push(buffer);
  1180. buffer->SetParameter(info->offset_, sizeof(Matrix4), &matrix);
  1181. return;
  1182. }
  1183. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Data());
  1184. }
  1185. }
  1186. }
  1187. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1188. {
  1189. if (impl_->shaderProgram_)
  1190. {
  1191. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1192. if (info)
  1193. {
  1194. if (info->bufferPtr_)
  1195. {
  1196. ConstantBuffer* buffer = info->bufferPtr_;
  1197. if (!buffer->IsDirty())
  1198. impl_->dirtyConstantBuffers_.Push(buffer);
  1199. buffer->SetParameter(info->offset_, sizeof(Vector4), &vector);
  1200. return;
  1201. }
  1202. // Check the uniform type to avoid mismatch
  1203. switch (info->glType_)
  1204. {
  1205. case GL_FLOAT:
  1206. glUniform1fv(info->location_, 1, vector.Data());
  1207. break;
  1208. case GL_FLOAT_VEC2:
  1209. glUniform2fv(info->location_, 1, vector.Data());
  1210. break;
  1211. case GL_FLOAT_VEC3:
  1212. glUniform3fv(info->location_, 1, vector.Data());
  1213. break;
  1214. case GL_FLOAT_VEC4:
  1215. glUniform4fv(info->location_, 1, vector.Data());
  1216. break;
  1217. default: break;
  1218. }
  1219. }
  1220. }
  1221. }
  1222. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1223. {
  1224. if (impl_->shaderProgram_)
  1225. {
  1226. const ShaderParameter* info = impl_->shaderProgram_->GetParameter(param);
  1227. if (info)
  1228. {
  1229. // Expand to a full Matrix4
  1230. static Matrix4 fullMatrix;
  1231. fullMatrix.m00_ = matrix.m00_;
  1232. fullMatrix.m01_ = matrix.m01_;
  1233. fullMatrix.m02_ = matrix.m02_;
  1234. fullMatrix.m03_ = matrix.m03_;
  1235. fullMatrix.m10_ = matrix.m10_;
  1236. fullMatrix.m11_ = matrix.m11_;
  1237. fullMatrix.m12_ = matrix.m12_;
  1238. fullMatrix.m13_ = matrix.m13_;
  1239. fullMatrix.m20_ = matrix.m20_;
  1240. fullMatrix.m21_ = matrix.m21_;
  1241. fullMatrix.m22_ = matrix.m22_;
  1242. fullMatrix.m23_ = matrix.m23_;
  1243. if (info->bufferPtr_)
  1244. {
  1245. ConstantBuffer* buffer = info->bufferPtr_;
  1246. if (!buffer->IsDirty())
  1247. impl_->dirtyConstantBuffers_.Push(buffer);
  1248. buffer->SetParameter(info->offset_, sizeof(Matrix4), &fullMatrix);
  1249. return;
  1250. }
  1251. glUniformMatrix4fv(info->location_, 1, GL_FALSE, fullMatrix.Data());
  1252. }
  1253. }
  1254. }
  1255. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1256. {
  1257. return impl_->shaderProgram_ ? impl_->shaderProgram_->NeedParameterUpdate(group, source) : false;
  1258. }
  1259. bool Graphics::HasShaderParameter(StringHash param)
  1260. {
  1261. return impl_->shaderProgram_ && impl_->shaderProgram_->HasParameter(param);
  1262. }
  1263. bool Graphics::HasTextureUnit(TextureUnit unit)
  1264. {
  1265. return impl_->shaderProgram_ && impl_->shaderProgram_->HasTextureUnit(unit);
  1266. }
  1267. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1268. {
  1269. if (impl_->shaderProgram_)
  1270. impl_->shaderProgram_->ClearParameterSource(group);
  1271. }
  1272. void Graphics::ClearParameterSources()
  1273. {
  1274. ShaderProgram::ClearParameterSources();
  1275. }
  1276. void Graphics::ClearTransformSources()
  1277. {
  1278. if (impl_->shaderProgram_)
  1279. {
  1280. impl_->shaderProgram_->ClearParameterSource(SP_CAMERA);
  1281. impl_->shaderProgram_->ClearParameterSource(SP_OBJECT);
  1282. }
  1283. }
  1284. void Graphics::SetTexture(unsigned index, Texture* texture)
  1285. {
  1286. if (index >= MAX_TEXTURE_UNITS)
  1287. return;
  1288. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1289. if (texture)
  1290. {
  1291. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1292. texture = texture->GetBackupTexture();
  1293. else
  1294. {
  1295. // Resolve multisampled texture now as necessary
  1296. if (texture->GetMultiSample() > 1 && texture->GetAutoResolve() && texture->IsResolveDirty())
  1297. {
  1298. if (texture->GetType() == Texture2D::GetTypeStatic())
  1299. ResolveToTexture(static_cast<Texture2D*>(texture));
  1300. if (texture->GetType() == TextureCube::GetTypeStatic())
  1301. ResolveToTexture(static_cast<TextureCube*>(texture));
  1302. }
  1303. }
  1304. }
  1305. if (textures_[index] != texture)
  1306. {
  1307. if (impl_->activeTexture_ != index)
  1308. {
  1309. glActiveTexture(GL_TEXTURE0 + index);
  1310. impl_->activeTexture_ = index;
  1311. }
  1312. if (texture)
  1313. {
  1314. unsigned glType = texture->GetTarget();
  1315. // Unbind old texture type if necessary
  1316. if (impl_->textureTypes_[index] && impl_->textureTypes_[index] != glType)
  1317. glBindTexture(impl_->textureTypes_[index], 0);
  1318. glBindTexture(glType, texture->GetGPUObjectName());
  1319. impl_->textureTypes_[index] = glType;
  1320. if (texture->GetParametersDirty())
  1321. texture->UpdateParameters();
  1322. if (texture->GetLevelsDirty())
  1323. texture->RegenerateLevels();
  1324. }
  1325. else if (impl_->textureTypes_[index])
  1326. {
  1327. glBindTexture(impl_->textureTypes_[index], 0);
  1328. impl_->textureTypes_[index] = 0;
  1329. }
  1330. textures_[index] = texture;
  1331. }
  1332. else
  1333. {
  1334. if (texture && (texture->GetParametersDirty() || texture->GetLevelsDirty()))
  1335. {
  1336. if (impl_->activeTexture_ != index)
  1337. {
  1338. glActiveTexture(GL_TEXTURE0 + index);
  1339. impl_->activeTexture_ = index;
  1340. }
  1341. glBindTexture(texture->GetTarget(), texture->GetGPUObjectName());
  1342. if (texture->GetParametersDirty())
  1343. texture->UpdateParameters();
  1344. if (texture->GetLevelsDirty())
  1345. texture->RegenerateLevels();
  1346. }
  1347. }
  1348. }
  1349. void Graphics::SetTextureForUpdate(Texture* texture)
  1350. {
  1351. if (impl_->activeTexture_ != 0)
  1352. {
  1353. glActiveTexture(GL_TEXTURE0);
  1354. impl_->activeTexture_ = 0;
  1355. }
  1356. unsigned glType = texture->GetTarget();
  1357. // Unbind old texture type if necessary
  1358. if (impl_->textureTypes_[0] && impl_->textureTypes_[0] != glType)
  1359. glBindTexture(impl_->textureTypes_[0], 0);
  1360. glBindTexture(glType, texture->GetGPUObjectName());
  1361. impl_->textureTypes_[0] = glType;
  1362. textures_[0] = texture;
  1363. }
  1364. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1365. {
  1366. if (mode != defaultTextureFilterMode_)
  1367. {
  1368. defaultTextureFilterMode_ = mode;
  1369. SetTextureParametersDirty();
  1370. }
  1371. }
  1372. void Graphics::SetDefaultTextureAnisotropy(unsigned level)
  1373. {
  1374. level = Max(level, 1U);
  1375. if (level != defaultTextureAnisotropy_)
  1376. {
  1377. defaultTextureAnisotropy_ = level;
  1378. SetTextureParametersDirty();
  1379. }
  1380. }
  1381. void Graphics::SetTextureParametersDirty()
  1382. {
  1383. MutexLock lock(gpuObjectMutex_);
  1384. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1385. {
  1386. auto* texture = dynamic_cast<Texture*>(*i);
  1387. if (texture)
  1388. texture->SetParametersDirty();
  1389. }
  1390. }
  1391. void Graphics::ResetRenderTargets()
  1392. {
  1393. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1394. SetRenderTarget(i, (RenderSurface*)nullptr);
  1395. SetDepthStencil((RenderSurface*)nullptr);
  1396. SetViewport(IntRect(0, 0, width_, height_));
  1397. }
  1398. void Graphics::ResetRenderTarget(unsigned index)
  1399. {
  1400. SetRenderTarget(index, (RenderSurface*)nullptr);
  1401. }
  1402. void Graphics::ResetDepthStencil()
  1403. {
  1404. SetDepthStencil((RenderSurface*)nullptr);
  1405. }
  1406. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1407. {
  1408. if (index >= MAX_RENDERTARGETS)
  1409. return;
  1410. if (renderTarget != renderTargets_[index])
  1411. {
  1412. renderTargets_[index] = renderTarget;
  1413. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1414. if (renderTarget)
  1415. {
  1416. Texture* parentTexture = renderTarget->GetParentTexture();
  1417. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1418. {
  1419. if (textures_[i] == parentTexture)
  1420. SetTexture(i, textures_[i]->GetBackupTexture());
  1421. }
  1422. // If multisampled, mark the texture & surface needing resolve
  1423. if (parentTexture->GetMultiSample() > 1 && parentTexture->GetAutoResolve())
  1424. {
  1425. parentTexture->SetResolveDirty(true);
  1426. renderTarget->SetResolveDirty(true);
  1427. }
  1428. // If mipmapped, mark the levels needing regeneration
  1429. if (parentTexture->GetLevels() > 1)
  1430. parentTexture->SetLevelsDirty();
  1431. }
  1432. impl_->fboDirty_ = true;
  1433. }
  1434. }
  1435. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1436. {
  1437. RenderSurface* renderTarget = nullptr;
  1438. if (texture)
  1439. renderTarget = texture->GetRenderSurface();
  1440. SetRenderTarget(index, renderTarget);
  1441. }
  1442. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1443. {
  1444. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1445. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1446. // Only do this for non-multisampled rendertargets; when using multisampled target a similarly multisampled
  1447. // depth-stencil should also be provided (backbuffer depth isn't compatible)
  1448. if (renderTargets_[0] && renderTargets_[0]->GetMultiSample() == 1 && !depthStencil)
  1449. {
  1450. int width = renderTargets_[0]->GetWidth();
  1451. int height = renderTargets_[0]->GetHeight();
  1452. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1453. // Check size similarly
  1454. if (width <= width_ && height <= height_)
  1455. {
  1456. unsigned searchKey = (width << 16u) | height;
  1457. HashMap<unsigned, SharedPtr<Texture2D> >::Iterator i = impl_->depthTextures_.Find(searchKey);
  1458. if (i != impl_->depthTextures_.End())
  1459. depthStencil = i->second_->GetRenderSurface();
  1460. else
  1461. {
  1462. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1463. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1464. impl_->depthTextures_[searchKey] = newDepthTexture;
  1465. depthStencil = newDepthTexture->GetRenderSurface();
  1466. }
  1467. }
  1468. }
  1469. if (depthStencil != depthStencil_)
  1470. {
  1471. depthStencil_ = depthStencil;
  1472. impl_->fboDirty_ = true;
  1473. }
  1474. }
  1475. void Graphics::SetDepthStencil(Texture2D* texture)
  1476. {
  1477. RenderSurface* depthStencil = nullptr;
  1478. if (texture)
  1479. depthStencil = texture->GetRenderSurface();
  1480. SetDepthStencil(depthStencil);
  1481. }
  1482. void Graphics::SetViewport(const IntRect& rect)
  1483. {
  1484. PrepareDraw();
  1485. IntVector2 rtSize = GetRenderTargetDimensions();
  1486. IntRect rectCopy = rect;
  1487. if (rectCopy.right_ <= rectCopy.left_)
  1488. rectCopy.right_ = rectCopy.left_ + 1;
  1489. if (rectCopy.bottom_ <= rectCopy.top_)
  1490. rectCopy.bottom_ = rectCopy.top_ + 1;
  1491. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1492. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1493. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1494. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1495. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1496. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.Width(), rectCopy.Height());
  1497. viewport_ = rectCopy;
  1498. // Disable scissor test, needs to be re-enabled by the user
  1499. SetScissorTest(false);
  1500. }
  1501. void Graphics::SetBlendMode(BlendMode mode, bool alphaToCoverage)
  1502. {
  1503. if (mode != blendMode_)
  1504. {
  1505. if (mode == BLEND_REPLACE)
  1506. glDisable(GL_BLEND);
  1507. else
  1508. {
  1509. glEnable(GL_BLEND);
  1510. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1511. glBlendEquation(glBlendOp[mode]);
  1512. }
  1513. blendMode_ = mode;
  1514. }
  1515. if (alphaToCoverage != alphaToCoverage_)
  1516. {
  1517. if (alphaToCoverage)
  1518. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1519. else
  1520. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1521. alphaToCoverage_ = alphaToCoverage;
  1522. }
  1523. }
  1524. void Graphics::SetColorWrite(bool enable)
  1525. {
  1526. if (enable != colorWrite_)
  1527. {
  1528. if (enable)
  1529. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1530. else
  1531. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1532. colorWrite_ = enable;
  1533. }
  1534. }
  1535. void Graphics::SetCullMode(CullMode mode)
  1536. {
  1537. if (mode != cullMode_)
  1538. {
  1539. if (mode == CULL_NONE)
  1540. glDisable(GL_CULL_FACE);
  1541. else
  1542. {
  1543. // Use Direct3D convention, ie. clockwise vertices define a front face
  1544. glEnable(GL_CULL_FACE);
  1545. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1546. }
  1547. cullMode_ = mode;
  1548. }
  1549. }
  1550. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1551. {
  1552. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1553. {
  1554. #ifndef GL_ES_VERSION_2_0
  1555. if (slopeScaledBias != 0.0f)
  1556. {
  1557. // OpenGL constant bias is unreliable and dependent on depth buffer bitdepth, apply in the projection matrix instead
  1558. glEnable(GL_POLYGON_OFFSET_FILL);
  1559. glPolygonOffset(slopeScaledBias, 0.0f);
  1560. }
  1561. else
  1562. glDisable(GL_POLYGON_OFFSET_FILL);
  1563. #endif
  1564. constantDepthBias_ = constantBias;
  1565. slopeScaledDepthBias_ = slopeScaledBias;
  1566. // Force update of the projection matrix shader parameter
  1567. ClearParameterSource(SP_CAMERA);
  1568. }
  1569. }
  1570. void Graphics::SetDepthTest(CompareMode mode)
  1571. {
  1572. if (mode != depthTestMode_)
  1573. {
  1574. glDepthFunc(glCmpFunc[mode]);
  1575. depthTestMode_ = mode;
  1576. }
  1577. }
  1578. void Graphics::SetDepthWrite(bool enable)
  1579. {
  1580. if (enable != depthWrite_)
  1581. {
  1582. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1583. depthWrite_ = enable;
  1584. }
  1585. }
  1586. void Graphics::SetFillMode(FillMode mode)
  1587. {
  1588. #ifndef GL_ES_VERSION_2_0
  1589. if (mode != fillMode_)
  1590. {
  1591. glPolygonMode(GL_FRONT_AND_BACK, glFillMode[mode]);
  1592. fillMode_ = mode;
  1593. }
  1594. #endif
  1595. }
  1596. void Graphics::SetLineAntiAlias(bool enable)
  1597. {
  1598. #ifndef GL_ES_VERSION_2_0
  1599. if (enable != lineAntiAlias_)
  1600. {
  1601. if (enable)
  1602. glEnable(GL_LINE_SMOOTH);
  1603. else
  1604. glDisable(GL_LINE_SMOOTH);
  1605. lineAntiAlias_ = enable;
  1606. }
  1607. #endif
  1608. }
  1609. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1610. {
  1611. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1612. // Disable scissor in that case to reduce state changes
  1613. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1614. enable = false;
  1615. if (enable)
  1616. {
  1617. IntVector2 rtSize(GetRenderTargetDimensions());
  1618. IntVector2 viewSize(viewport_.Size());
  1619. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1620. IntRect intRect;
  1621. int expand = borderInclusive ? 1 : 0;
  1622. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1623. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1624. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1625. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1626. if (intRect.right_ == intRect.left_)
  1627. intRect.right_++;
  1628. if (intRect.bottom_ == intRect.top_)
  1629. intRect.bottom_++;
  1630. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1631. enable = false;
  1632. if (enable && scissorRect_ != intRect)
  1633. {
  1634. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1635. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1636. scissorRect_ = intRect;
  1637. }
  1638. }
  1639. else
  1640. scissorRect_ = IntRect::ZERO;
  1641. if (enable != scissorTest_)
  1642. {
  1643. if (enable)
  1644. glEnable(GL_SCISSOR_TEST);
  1645. else
  1646. glDisable(GL_SCISSOR_TEST);
  1647. scissorTest_ = enable;
  1648. }
  1649. }
  1650. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1651. {
  1652. IntVector2 rtSize(GetRenderTargetDimensions());
  1653. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1654. if (enable)
  1655. {
  1656. IntRect intRect;
  1657. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1658. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1659. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1660. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1661. if (intRect.right_ == intRect.left_)
  1662. intRect.right_++;
  1663. if (intRect.bottom_ == intRect.top_)
  1664. intRect.bottom_++;
  1665. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1666. enable = false;
  1667. if (enable && scissorRect_ != intRect)
  1668. {
  1669. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1670. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1671. scissorRect_ = intRect;
  1672. }
  1673. }
  1674. else
  1675. scissorRect_ = IntRect::ZERO;
  1676. if (enable != scissorTest_)
  1677. {
  1678. if (enable)
  1679. glEnable(GL_SCISSOR_TEST);
  1680. else
  1681. glDisable(GL_SCISSOR_TEST);
  1682. scissorTest_ = enable;
  1683. }
  1684. }
  1685. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1686. {
  1687. #ifndef GL_ES_VERSION_2_0
  1688. if (enable != useClipPlane_)
  1689. {
  1690. if (enable)
  1691. glEnable(GL_CLIP_PLANE0);
  1692. else
  1693. glDisable(GL_CLIP_PLANE0);
  1694. useClipPlane_ = enable;
  1695. }
  1696. if (enable)
  1697. {
  1698. Matrix4 viewProj = projection * view;
  1699. clipPlane_ = clipPlane.Transformed(viewProj).ToVector4();
  1700. if (!gl3Support)
  1701. {
  1702. GLdouble planeData[4];
  1703. planeData[0] = clipPlane_.x_;
  1704. planeData[1] = clipPlane_.y_;
  1705. planeData[2] = clipPlane_.z_;
  1706. planeData[3] = clipPlane_.w_;
  1707. glClipPlane(GL_CLIP_PLANE0, &planeData[0]);
  1708. }
  1709. }
  1710. #endif
  1711. }
  1712. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1713. unsigned compareMask, unsigned writeMask)
  1714. {
  1715. #ifndef GL_ES_VERSION_2_0
  1716. if (enable != stencilTest_)
  1717. {
  1718. if (enable)
  1719. glEnable(GL_STENCIL_TEST);
  1720. else
  1721. glDisable(GL_STENCIL_TEST);
  1722. stencilTest_ = enable;
  1723. }
  1724. if (enable)
  1725. {
  1726. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1727. {
  1728. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1729. stencilTestMode_ = mode;
  1730. stencilRef_ = stencilRef;
  1731. stencilCompareMask_ = compareMask;
  1732. }
  1733. if (writeMask != stencilWriteMask_)
  1734. {
  1735. glStencilMask(writeMask);
  1736. stencilWriteMask_ = writeMask;
  1737. }
  1738. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1739. {
  1740. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1741. stencilPass_ = pass;
  1742. stencilFail_ = fail;
  1743. stencilZFail_ = zFail;
  1744. }
  1745. }
  1746. #endif
  1747. }
  1748. bool Graphics::IsInitialized() const
  1749. {
  1750. return window_ != nullptr;
  1751. }
  1752. bool Graphics::GetDither() const
  1753. {
  1754. return glIsEnabled(GL_DITHER) ? true : false;
  1755. }
  1756. bool Graphics::IsDeviceLost() const
  1757. {
  1758. // On iOS and tvOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1759. #if defined(IOS) || defined(TVOS)
  1760. if (window_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED) != 0)
  1761. return true;
  1762. #endif
  1763. return impl_->context_ == nullptr;
  1764. }
  1765. PODVector<int> Graphics::GetMultiSampleLevels() const
  1766. {
  1767. PODVector<int> ret;
  1768. // No multisampling always supported
  1769. ret.Push(1);
  1770. #ifndef GL_ES_VERSION_2_0
  1771. int maxSamples = 0;
  1772. glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);
  1773. for (int i = 2; i <= maxSamples && i <= 16; i *= 2)
  1774. ret.Push(i);
  1775. #endif
  1776. return ret;
  1777. }
  1778. unsigned Graphics::GetFormat(CompressedFormat format) const
  1779. {
  1780. switch (format)
  1781. {
  1782. case CF_RGBA:
  1783. return GL_RGBA;
  1784. case CF_DXT1:
  1785. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : 0;
  1786. #if !defined(GL_ES_VERSION_2_0) || defined(__EMSCRIPTEN__)
  1787. case CF_DXT3:
  1788. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : 0;
  1789. case CF_DXT5:
  1790. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : 0;
  1791. #endif
  1792. #ifdef GL_ES_VERSION_2_0
  1793. case CF_ETC1:
  1794. return etcTextureSupport_ ? GL_ETC1_RGB8_OES : 0;
  1795. case CF_PVRTC_RGB_2BPP:
  1796. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0;
  1797. case CF_PVRTC_RGB_4BPP:
  1798. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0;
  1799. case CF_PVRTC_RGBA_2BPP:
  1800. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0;
  1801. case CF_PVRTC_RGBA_4BPP:
  1802. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0;
  1803. #endif
  1804. default:
  1805. return 0;
  1806. }
  1807. }
  1808. unsigned Graphics::GetMaxBones()
  1809. {
  1810. #ifdef RPI
  1811. // At the moment all RPI GPUs are low powered and only have limited number of uniforms
  1812. return 32;
  1813. #else
  1814. return gl3Support ? 128 : 64;
  1815. #endif
  1816. }
  1817. bool Graphics::GetGL3Support()
  1818. {
  1819. return gl3Support;
  1820. }
  1821. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1822. {
  1823. return GetShader(type, name.CString(), defines.CString());
  1824. }
  1825. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1826. {
  1827. if (lastShaderName_ != name || !lastShader_)
  1828. {
  1829. auto* cache = GetSubsystem<ResourceCache>();
  1830. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1831. // Try to reduce repeated error log prints because of missing shaders
  1832. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1833. return nullptr;
  1834. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1835. lastShaderName_ = name;
  1836. }
  1837. return lastShader_ ? lastShader_->GetVariation(type, defines) : nullptr;
  1838. }
  1839. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1840. {
  1841. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : nullptr;
  1842. }
  1843. ShaderProgram* Graphics::GetShaderProgram() const
  1844. {
  1845. return impl_->shaderProgram_;
  1846. }
  1847. TextureUnit Graphics::GetTextureUnit(const String& name)
  1848. {
  1849. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1850. if (i != textureUnits_.End())
  1851. return i->second_;
  1852. else
  1853. return MAX_TEXTURE_UNITS;
  1854. }
  1855. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1856. {
  1857. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1858. {
  1859. if (i->second_ == unit)
  1860. return i->first_;
  1861. }
  1862. return String::EMPTY;
  1863. }
  1864. Texture* Graphics::GetTexture(unsigned index) const
  1865. {
  1866. return index < MAX_TEXTURE_UNITS ? textures_[index] : nullptr;
  1867. }
  1868. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1869. {
  1870. return index < MAX_RENDERTARGETS ? renderTargets_[index] : nullptr;
  1871. }
  1872. IntVector2 Graphics::GetRenderTargetDimensions() const
  1873. {
  1874. int width, height;
  1875. if (renderTargets_[0])
  1876. {
  1877. width = renderTargets_[0]->GetWidth();
  1878. height = renderTargets_[0]->GetHeight();
  1879. }
  1880. else if (depthStencil_)
  1881. {
  1882. width = depthStencil_->GetWidth();
  1883. height = depthStencil_->GetHeight();
  1884. }
  1885. else
  1886. {
  1887. width = width_;
  1888. height = height_;
  1889. }
  1890. return IntVector2(width, height);
  1891. }
  1892. void Graphics::OnWindowResized()
  1893. {
  1894. if (!window_)
  1895. return;
  1896. int newWidth, newHeight;
  1897. SDL_GL_GetDrawableSize(window_, &newWidth, &newHeight);
  1898. if (newWidth == width_ && newHeight == height_)
  1899. return;
  1900. width_ = newWidth;
  1901. height_ = newHeight;
  1902. int logicalWidth, logicalHeight;
  1903. SDL_GetWindowSize(window_, &logicalWidth, &logicalHeight);
  1904. highDPI_ = (width_ != logicalWidth) || (height_ != logicalHeight);
  1905. // Reset rendertargets and viewport for the new screen size. Also clean up any FBO's, as they may be screen size dependent
  1906. CleanupFramebuffers();
  1907. ResetRenderTargets();
  1908. URHO3D_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1909. using namespace ScreenMode;
  1910. VariantMap& eventData = GetEventDataMap();
  1911. eventData[P_WIDTH] = width_;
  1912. eventData[P_HEIGHT] = height_;
  1913. eventData[P_FULLSCREEN] = fullscreen_;
  1914. eventData[P_RESIZABLE] = resizable_;
  1915. eventData[P_BORDERLESS] = borderless_;
  1916. eventData[P_HIGHDPI] = highDPI_;
  1917. SendEvent(E_SCREENMODE, eventData);
  1918. }
  1919. void Graphics::OnWindowMoved()
  1920. {
  1921. if (!window_ || fullscreen_)
  1922. return;
  1923. int newX, newY;
  1924. SDL_GetWindowPosition(window_, &newX, &newY);
  1925. if (newX == position_.x_ && newY == position_.y_)
  1926. return;
  1927. position_.x_ = newX;
  1928. position_.y_ = newY;
  1929. URHO3D_LOGTRACEF("Window was moved to %d,%d", position_.x_, position_.y_);
  1930. using namespace WindowPos;
  1931. VariantMap& eventData = GetEventDataMap();
  1932. eventData[P_X] = position_.x_;
  1933. eventData[P_Y] = position_.y_;
  1934. SendEvent(E_WINDOWPOS, eventData);
  1935. }
  1936. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1937. {
  1938. if (!surface)
  1939. return;
  1940. // Flush pending FBO changes first if any
  1941. PrepareDraw();
  1942. unsigned currentFBO = impl_->boundFBO_;
  1943. // Go through all FBOs and clean up the surface from them
  1944. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1945. i != impl_->frameBuffers_.End(); ++i)
  1946. {
  1947. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1948. {
  1949. if (i->second_.colorAttachments_[j] == surface)
  1950. {
  1951. if (currentFBO != i->second_.fbo_)
  1952. {
  1953. BindFramebuffer(i->second_.fbo_);
  1954. currentFBO = i->second_.fbo_;
  1955. }
  1956. BindColorAttachment(j, GL_TEXTURE_2D, 0, false);
  1957. i->second_.colorAttachments_[j] = nullptr;
  1958. // Mark drawbuffer bits to need recalculation
  1959. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1960. }
  1961. }
  1962. if (i->second_.depthAttachment_ == surface)
  1963. {
  1964. if (currentFBO != i->second_.fbo_)
  1965. {
  1966. BindFramebuffer(i->second_.fbo_);
  1967. currentFBO = i->second_.fbo_;
  1968. }
  1969. BindDepthAttachment(0, false);
  1970. BindStencilAttachment(0, false);
  1971. i->second_.depthAttachment_ = nullptr;
  1972. }
  1973. }
  1974. // Restore previously bound FBO now if needed
  1975. if (currentFBO != impl_->boundFBO_)
  1976. BindFramebuffer(impl_->boundFBO_);
  1977. }
  1978. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  1979. {
  1980. for (ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Begin(); i != impl_->shaderPrograms_.End();)
  1981. {
  1982. if (i->second_->GetVertexShader() == variation || i->second_->GetPixelShader() == variation)
  1983. i = impl_->shaderPrograms_.Erase(i);
  1984. else
  1985. ++i;
  1986. }
  1987. if (vertexShader_ == variation || pixelShader_ == variation)
  1988. impl_->shaderProgram_ = nullptr;
  1989. }
  1990. ConstantBuffer* Graphics::GetOrCreateConstantBuffer(ShaderType /*type*/, unsigned index, unsigned size)
  1991. {
  1992. // Note: shaderType parameter is not used on OpenGL, instead binding index should already use the PS range
  1993. // for PS constant buffers
  1994. unsigned key = (index << 16u) | size;
  1995. HashMap<unsigned, SharedPtr<ConstantBuffer> >::Iterator i = impl_->allConstantBuffers_.Find(key);
  1996. if (i == impl_->allConstantBuffers_.End())
  1997. {
  1998. i = impl_->allConstantBuffers_.Insert(MakePair(key, SharedPtr<ConstantBuffer>(new ConstantBuffer(context_))));
  1999. i->second_->SetSize(size);
  2000. }
  2001. return i->second_.Get();
  2002. }
  2003. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  2004. {
  2005. if (!window_)
  2006. return;
  2007. {
  2008. MutexLock lock(gpuObjectMutex_);
  2009. if (clearGPUObjects)
  2010. {
  2011. // Shutting down: release all GPU objects that still exist
  2012. // Shader programs are also GPU objects; clear them first to avoid list modification during iteration
  2013. impl_->shaderPrograms_.Clear();
  2014. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2015. (*i)->Release();
  2016. gpuObjects_.Clear();
  2017. }
  2018. else
  2019. {
  2020. // We are not shutting down, but recreating the context: mark GPU objects lost
  2021. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2022. (*i)->OnDeviceLost();
  2023. // In this case clear shader programs last so that they do not attempt to delete their OpenGL program
  2024. // from a context that may no longer exist
  2025. impl_->shaderPrograms_.Clear();
  2026. SendEvent(E_DEVICELOST);
  2027. }
  2028. }
  2029. CleanupFramebuffers();
  2030. impl_->depthTextures_.Clear();
  2031. // End fullscreen mode first to counteract transition and getting stuck problems on OS X
  2032. #if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  2033. if (closeWindow && fullscreen_ && !externalWindow_)
  2034. SDL_SetWindowFullscreen(window_, 0);
  2035. #endif
  2036. if (impl_->context_)
  2037. {
  2038. // Do not log this message if we are exiting
  2039. if (!clearGPUObjects)
  2040. URHO3D_LOGINFO("OpenGL context lost");
  2041. SDL_GL_DeleteContext(impl_->context_);
  2042. impl_->context_ = nullptr;
  2043. }
  2044. if (closeWindow)
  2045. {
  2046. SDL_ShowCursor(SDL_TRUE);
  2047. // Do not destroy external window except when shutting down
  2048. if (!externalWindow_ || clearGPUObjects)
  2049. {
  2050. SDL_DestroyWindow(window_);
  2051. window_ = nullptr;
  2052. }
  2053. }
  2054. }
  2055. void Graphics::Restore()
  2056. {
  2057. if (!window_)
  2058. return;
  2059. #ifdef __ANDROID__
  2060. // On Android the context may be lost behind the scenes as the application is minimized
  2061. if (impl_->context_ && !SDL_GL_GetCurrentContext())
  2062. {
  2063. impl_->context_ = 0;
  2064. // Mark GPU objects lost without a current context. In this case they just mark their internal state lost
  2065. // but do not perform OpenGL commands to delete the GL objects
  2066. Release(false, false);
  2067. }
  2068. #endif
  2069. // Ensure first that the context exists
  2070. if (!impl_->context_)
  2071. {
  2072. impl_->context_ = SDL_GL_CreateContext(window_);
  2073. #ifndef GL_ES_VERSION_2_0
  2074. // If we're trying to use OpenGL 3, but context creation fails, retry with 2
  2075. if (!forceGL2_ && !impl_->context_)
  2076. {
  2077. forceGL2_ = true;
  2078. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  2079. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  2080. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  2081. impl_->context_ = SDL_GL_CreateContext(window_);
  2082. }
  2083. #endif
  2084. #if defined(IOS) || defined(TVOS)
  2085. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFBO_);
  2086. #endif
  2087. if (!impl_->context_)
  2088. {
  2089. URHO3D_LOGERRORF("Could not create OpenGL context, root cause '%s'", SDL_GetError());
  2090. return;
  2091. }
  2092. // Clear cached extensions string from the previous context
  2093. extensions.Clear();
  2094. // Initialize OpenGL extensions library (desktop only)
  2095. #ifndef GL_ES_VERSION_2_0
  2096. GLenum err = glewInit();
  2097. if (GLEW_OK != err)
  2098. {
  2099. URHO3D_LOGERRORF("Could not initialize OpenGL extensions, root cause: '%s'", glewGetErrorString(err));
  2100. return;
  2101. }
  2102. if (!forceGL2_ && GLEW_VERSION_3_2)
  2103. {
  2104. gl3Support = true;
  2105. apiName_ = "GL3";
  2106. // Create and bind a vertex array object that will stay in use throughout
  2107. unsigned vertexArrayObject;
  2108. glGenVertexArrays(1, &vertexArrayObject);
  2109. glBindVertexArray(vertexArrayObject);
  2110. }
  2111. else if (GLEW_VERSION_2_0)
  2112. {
  2113. if (!GLEW_EXT_framebuffer_object || !GLEW_EXT_packed_depth_stencil)
  2114. {
  2115. URHO3D_LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  2116. return;
  2117. }
  2118. gl3Support = false;
  2119. apiName_ = "GL2";
  2120. }
  2121. else
  2122. {
  2123. URHO3D_LOGERROR("OpenGL 2.0 is required");
  2124. return;
  2125. }
  2126. // Enable seamless cubemap if possible
  2127. // Note: even though we check the extension, this can lead to software fallback on some old GPU's
  2128. // See https://github.com/urho3d/Urho3D/issues/1380 or
  2129. // http://distrustsimplicity.net/articles/gl_texture_cube_map_seamless-on-os-x/
  2130. // In case of trouble or for wanting maximum compatibility, simply remove the glEnable below.
  2131. if (gl3Support || GLEW_ARB_seamless_cube_map)
  2132. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  2133. #endif
  2134. // Set up texture data read/write alignment. It is important that this is done before uploading any texture data
  2135. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  2136. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  2137. ResetCachedState();
  2138. }
  2139. {
  2140. MutexLock lock(gpuObjectMutex_);
  2141. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2142. (*i)->OnDeviceReset();
  2143. }
  2144. SendEvent(E_DEVICERESET);
  2145. }
  2146. void Graphics::MarkFBODirty()
  2147. {
  2148. impl_->fboDirty_ = true;
  2149. }
  2150. void Graphics::SetVBO(unsigned object)
  2151. {
  2152. if (impl_->boundVBO_ != object)
  2153. {
  2154. if (object)
  2155. glBindBuffer(GL_ARRAY_BUFFER, object);
  2156. impl_->boundVBO_ = object;
  2157. }
  2158. }
  2159. void Graphics::SetUBO(unsigned object)
  2160. {
  2161. #ifndef GL_ES_VERSION_2_0
  2162. if (impl_->boundUBO_ != object)
  2163. {
  2164. if (object)
  2165. glBindBuffer(GL_UNIFORM_BUFFER, object);
  2166. impl_->boundUBO_ = object;
  2167. }
  2168. #endif
  2169. }
  2170. unsigned Graphics::GetAlphaFormat()
  2171. {
  2172. #ifndef GL_ES_VERSION_2_0
  2173. // Alpha format is deprecated on OpenGL 3+
  2174. if (gl3Support)
  2175. return GL_R8;
  2176. #endif
  2177. return GL_ALPHA;
  2178. }
  2179. unsigned Graphics::GetLuminanceFormat()
  2180. {
  2181. #ifndef GL_ES_VERSION_2_0
  2182. // Luminance format is deprecated on OpenGL 3+
  2183. if (gl3Support)
  2184. return GL_R8;
  2185. #endif
  2186. return GL_LUMINANCE;
  2187. }
  2188. unsigned Graphics::GetLuminanceAlphaFormat()
  2189. {
  2190. #ifndef GL_ES_VERSION_2_0
  2191. // Luminance alpha format is deprecated on OpenGL 3+
  2192. if (gl3Support)
  2193. return GL_RG8;
  2194. #endif
  2195. return GL_LUMINANCE_ALPHA;
  2196. }
  2197. unsigned Graphics::GetRGBFormat()
  2198. {
  2199. return GL_RGB;
  2200. }
  2201. unsigned Graphics::GetRGBAFormat()
  2202. {
  2203. return GL_RGBA;
  2204. }
  2205. unsigned Graphics::GetRGBA16Format()
  2206. {
  2207. #ifndef GL_ES_VERSION_2_0
  2208. return GL_RGBA16;
  2209. #else
  2210. return GL_RGBA;
  2211. #endif
  2212. }
  2213. unsigned Graphics::GetRGBAFloat16Format()
  2214. {
  2215. #ifndef GL_ES_VERSION_2_0
  2216. return GL_RGBA16F_ARB;
  2217. #else
  2218. return GL_RGBA;
  2219. #endif
  2220. }
  2221. unsigned Graphics::GetRGBAFloat32Format()
  2222. {
  2223. #ifndef GL_ES_VERSION_2_0
  2224. return GL_RGBA32F_ARB;
  2225. #else
  2226. return GL_RGBA;
  2227. #endif
  2228. }
  2229. unsigned Graphics::GetRG16Format()
  2230. {
  2231. #ifndef GL_ES_VERSION_2_0
  2232. return GL_RG16;
  2233. #else
  2234. return GL_RGBA;
  2235. #endif
  2236. }
  2237. unsigned Graphics::GetRGFloat16Format()
  2238. {
  2239. #ifndef GL_ES_VERSION_2_0
  2240. return GL_RG16F;
  2241. #else
  2242. return GL_RGBA;
  2243. #endif
  2244. }
  2245. unsigned Graphics::GetRGFloat32Format()
  2246. {
  2247. #ifndef GL_ES_VERSION_2_0
  2248. return GL_RG32F;
  2249. #else
  2250. return GL_RGBA;
  2251. #endif
  2252. }
  2253. unsigned Graphics::GetFloat16Format()
  2254. {
  2255. #ifndef GL_ES_VERSION_2_0
  2256. return GL_R16F;
  2257. #else
  2258. return GL_LUMINANCE;
  2259. #endif
  2260. }
  2261. unsigned Graphics::GetFloat32Format()
  2262. {
  2263. #ifndef GL_ES_VERSION_2_0
  2264. return GL_R32F;
  2265. #else
  2266. return GL_LUMINANCE;
  2267. #endif
  2268. }
  2269. unsigned Graphics::GetLinearDepthFormat()
  2270. {
  2271. #ifndef GL_ES_VERSION_2_0
  2272. // OpenGL 3 can use different color attachment formats
  2273. if (gl3Support)
  2274. return GL_R32F;
  2275. #endif
  2276. // OpenGL 2 requires color attachments to have the same format, therefore encode deferred depth to RGBA manually
  2277. // if not using a readable hardware depth texture
  2278. return GL_RGBA;
  2279. }
  2280. unsigned Graphics::GetDepthStencilFormat()
  2281. {
  2282. #ifndef GL_ES_VERSION_2_0
  2283. return GL_DEPTH24_STENCIL8_EXT;
  2284. #else
  2285. return glesDepthStencilFormat;
  2286. #endif
  2287. }
  2288. unsigned Graphics::GetReadableDepthFormat()
  2289. {
  2290. #ifndef GL_ES_VERSION_2_0
  2291. return GL_DEPTH_COMPONENT24;
  2292. #else
  2293. return glesReadableDepthFormat;
  2294. #endif
  2295. }
  2296. unsigned Graphics::GetFormat(const String& formatName)
  2297. {
  2298. String nameLower = formatName.ToLower().Trimmed();
  2299. if (nameLower == "a")
  2300. return GetAlphaFormat();
  2301. if (nameLower == "l")
  2302. return GetLuminanceFormat();
  2303. if (nameLower == "la")
  2304. return GetLuminanceAlphaFormat();
  2305. if (nameLower == "rgb")
  2306. return GetRGBFormat();
  2307. if (nameLower == "rgba")
  2308. return GetRGBAFormat();
  2309. if (nameLower == "rgba16")
  2310. return GetRGBA16Format();
  2311. if (nameLower == "rgba16f")
  2312. return GetRGBAFloat16Format();
  2313. if (nameLower == "rgba32f")
  2314. return GetRGBAFloat32Format();
  2315. if (nameLower == "rg16")
  2316. return GetRG16Format();
  2317. if (nameLower == "rg16f")
  2318. return GetRGFloat16Format();
  2319. if (nameLower == "rg32f")
  2320. return GetRGFloat32Format();
  2321. if (nameLower == "r16f")
  2322. return GetFloat16Format();
  2323. if (nameLower == "r32f" || nameLower == "float")
  2324. return GetFloat32Format();
  2325. if (nameLower == "lineardepth" || nameLower == "depth")
  2326. return GetLinearDepthFormat();
  2327. if (nameLower == "d24s8")
  2328. return GetDepthStencilFormat();
  2329. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  2330. return GetReadableDepthFormat();
  2331. return GetRGBFormat();
  2332. }
  2333. void Graphics::CheckFeatureSupport()
  2334. {
  2335. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  2336. lightPrepassSupport_ = false;
  2337. deferredSupport_ = false;
  2338. #ifndef GL_ES_VERSION_2_0
  2339. int numSupportedRTs = 1;
  2340. if (gl3Support)
  2341. {
  2342. // Work around GLEW failure to check extensions properly from a GL3 context
  2343. instancingSupport_ = glDrawElementsInstanced != nullptr && glVertexAttribDivisor != nullptr;
  2344. dxtTextureSupport_ = true;
  2345. anisotropySupport_ = true;
  2346. sRGBSupport_ = true;
  2347. sRGBWriteSupport_ = true;
  2348. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &numSupportedRTs);
  2349. }
  2350. else
  2351. {
  2352. instancingSupport_ = GLEW_ARB_instanced_arrays != 0;
  2353. dxtTextureSupport_ = GLEW_EXT_texture_compression_s3tc != 0;
  2354. anisotropySupport_ = GLEW_EXT_texture_filter_anisotropic != 0;
  2355. sRGBSupport_ = GLEW_EXT_texture_sRGB != 0;
  2356. sRGBWriteSupport_ = GLEW_EXT_framebuffer_sRGB != 0;
  2357. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  2358. }
  2359. // Must support 2 rendertargets for light pre-pass, and 4 for deferred
  2360. if (numSupportedRTs >= 2)
  2361. lightPrepassSupport_ = true;
  2362. if (numSupportedRTs >= 4)
  2363. deferredSupport_ = true;
  2364. #if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  2365. // On macOS check for an Intel driver and use shadow map RGBA dummy color textures, because mixing
  2366. // depth-only FBO rendering and backbuffer rendering will bug, resulting in a black screen in full
  2367. // screen mode, and incomplete shadow maps in windowed mode
  2368. String renderer((const char*)glGetString(GL_RENDERER));
  2369. if (renderer.Contains("Intel", false))
  2370. dummyColorFormat_ = GetRGBAFormat();
  2371. #endif
  2372. #else
  2373. // Check for supported compressed texture formats
  2374. #ifdef __EMSCRIPTEN__
  2375. dxtTextureSupport_ = CheckExtension("WEBGL_compressed_texture_s3tc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  2376. etcTextureSupport_ = CheckExtension("WEBGL_compressed_texture_etc1"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/
  2377. pvrtcTextureSupport_ = CheckExtension("WEBGL_compressed_texture_pvrtc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  2378. // Instancing is in core in WebGL 2, so the extension may not be present anymore. In WebGL 1, find https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays/
  2379. // TODO: In the distant future, this may break if WebGL 3 is introduced, so either improve the GL_VERSION parsing here, or keep track of which WebGL version we attempted to initialize.
  2380. instancingSupport_ = (strstr((const char *)glGetString(GL_VERSION), "WebGL 2.") != 0) || CheckExtension("ANGLE_instanced_arrays");
  2381. #else
  2382. dxtTextureSupport_ = CheckExtension("EXT_texture_compression_dxt1");
  2383. etcTextureSupport_ = CheckExtension("OES_compressed_ETC1_RGB8_texture");
  2384. pvrtcTextureSupport_ = CheckExtension("IMG_texture_compression_pvrtc");
  2385. #endif
  2386. // Check for best supported depth renderbuffer format for GLES2
  2387. if (CheckExtension("GL_OES_depth24"))
  2388. glesDepthStencilFormat = GL_DEPTH_COMPONENT24_OES;
  2389. if (CheckExtension("GL_OES_packed_depth_stencil"))
  2390. glesDepthStencilFormat = GL_DEPTH24_STENCIL8_OES;
  2391. #ifdef __EMSCRIPTEN__
  2392. if (!CheckExtension("WEBGL_depth_texture"))
  2393. #else
  2394. if (!CheckExtension("GL_OES_depth_texture"))
  2395. #endif
  2396. {
  2397. shadowMapFormat_ = 0;
  2398. hiresShadowMapFormat_ = 0;
  2399. glesReadableDepthFormat = 0;
  2400. }
  2401. else
  2402. {
  2403. #if defined(IOS) || defined(TVOS)
  2404. // iOS hack: depth renderbuffer seems to fail, so use depth textures for everything if supported
  2405. glesDepthStencilFormat = GL_DEPTH_COMPONENT;
  2406. #endif
  2407. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  2408. hiresShadowMapFormat_ = 0;
  2409. // WebGL shadow map rendering seems to be extremely slow without an attached dummy color texture
  2410. #ifdef __EMSCRIPTEN__
  2411. dummyColorFormat_ = GetRGBAFormat();
  2412. #endif
  2413. }
  2414. #endif
  2415. // Consider OpenGL shadows always hardware sampled, if supported at all
  2416. hardwareShadowSupport_ = shadowMapFormat_ != 0;
  2417. }
  2418. void Graphics::PrepareDraw()
  2419. {
  2420. #ifndef GL_ES_VERSION_2_0
  2421. if (gl3Support)
  2422. {
  2423. for (PODVector<ConstantBuffer*>::Iterator i = impl_->dirtyConstantBuffers_.Begin(); i != impl_->dirtyConstantBuffers_.End(); ++i)
  2424. (*i)->Apply();
  2425. impl_->dirtyConstantBuffers_.Clear();
  2426. }
  2427. #endif
  2428. if (impl_->fboDirty_)
  2429. {
  2430. impl_->fboDirty_ = false;
  2431. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  2432. bool noFbo = !depthStencil_;
  2433. if (noFbo)
  2434. {
  2435. for (auto& renderTarget : renderTargets_)
  2436. {
  2437. if (renderTarget)
  2438. {
  2439. noFbo = false;
  2440. break;
  2441. }
  2442. }
  2443. }
  2444. if (noFbo)
  2445. {
  2446. if (impl_->boundFBO_ != impl_->systemFBO_)
  2447. {
  2448. BindFramebuffer(impl_->systemFBO_);
  2449. impl_->boundFBO_ = impl_->systemFBO_;
  2450. }
  2451. #ifndef GL_ES_VERSION_2_0
  2452. // Disable/enable sRGB write
  2453. if (sRGBWriteSupport_)
  2454. {
  2455. bool sRGBWrite = sRGB_;
  2456. if (sRGBWrite != impl_->sRGBWrite_)
  2457. {
  2458. if (sRGBWrite)
  2459. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2460. else
  2461. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2462. impl_->sRGBWrite_ = sRGBWrite;
  2463. }
  2464. }
  2465. #endif
  2466. return;
  2467. }
  2468. // Search for a new framebuffer based on format & size, or create new
  2469. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  2470. unsigned format = 0;
  2471. if (renderTargets_[0])
  2472. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  2473. else if (depthStencil_)
  2474. format = depthStencil_->GetParentTexture()->GetFormat();
  2475. auto fboKey = (unsigned long long)format << 32u | rtSize.x_ << 16u | rtSize.y_;
  2476. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  2477. if (i == impl_->frameBuffers_.End())
  2478. {
  2479. FrameBufferObject newFbo;
  2480. newFbo.fbo_ = CreateFramebuffer();
  2481. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  2482. }
  2483. if (impl_->boundFBO_ != i->second_.fbo_)
  2484. {
  2485. BindFramebuffer(i->second_.fbo_);
  2486. impl_->boundFBO_ = i->second_.fbo_;
  2487. }
  2488. #ifndef GL_ES_VERSION_2_0
  2489. // Setup readbuffers & drawbuffers if needed
  2490. if (i->second_.readBuffers_ != GL_NONE)
  2491. {
  2492. glReadBuffer(GL_NONE);
  2493. i->second_.readBuffers_ = GL_NONE;
  2494. }
  2495. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  2496. unsigned newDrawBuffers = 0;
  2497. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2498. {
  2499. if (renderTargets_[j])
  2500. newDrawBuffers |= 1u << j;
  2501. }
  2502. if (newDrawBuffers != i->second_.drawBuffers_)
  2503. {
  2504. // Check for no color rendertargets (depth rendering only)
  2505. if (!newDrawBuffers)
  2506. glDrawBuffer(GL_NONE);
  2507. else
  2508. {
  2509. int drawBufferIds[MAX_RENDERTARGETS];
  2510. unsigned drawBufferCount = 0;
  2511. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2512. {
  2513. if (renderTargets_[j])
  2514. {
  2515. if (!gl3Support)
  2516. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + j;
  2517. else
  2518. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0 + j;
  2519. }
  2520. }
  2521. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  2522. }
  2523. i->second_.drawBuffers_ = newDrawBuffers;
  2524. }
  2525. #endif
  2526. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2527. {
  2528. if (renderTargets_[j])
  2529. {
  2530. Texture* texture = renderTargets_[j]->GetParentTexture();
  2531. // Bind either a renderbuffer or texture, depending on what is available
  2532. unsigned renderBufferID = renderTargets_[j]->GetRenderBuffer();
  2533. if (!renderBufferID)
  2534. {
  2535. // If texture's parameters are dirty, update before attaching
  2536. if (texture->GetParametersDirty())
  2537. {
  2538. SetTextureForUpdate(texture);
  2539. texture->UpdateParameters();
  2540. SetTexture(0, nullptr);
  2541. }
  2542. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2543. {
  2544. BindColorAttachment(j, renderTargets_[j]->GetTarget(), texture->GetGPUObjectName(), false);
  2545. i->second_.colorAttachments_[j] = renderTargets_[j];
  2546. }
  2547. }
  2548. else
  2549. {
  2550. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2551. {
  2552. BindColorAttachment(j, renderTargets_[j]->GetTarget(), renderBufferID, true);
  2553. i->second_.colorAttachments_[j] = renderTargets_[j];
  2554. }
  2555. }
  2556. }
  2557. else
  2558. {
  2559. if (i->second_.colorAttachments_[j])
  2560. {
  2561. BindColorAttachment(j, GL_TEXTURE_2D, 0, false);
  2562. i->second_.colorAttachments_[j] = nullptr;
  2563. }
  2564. }
  2565. }
  2566. if (depthStencil_)
  2567. {
  2568. // Bind either a renderbuffer or a depth texture, depending on what is available
  2569. Texture* texture = depthStencil_->GetParentTexture();
  2570. #ifndef GL_ES_VERSION_2_0
  2571. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_EXT;
  2572. #else
  2573. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_OES;
  2574. #endif
  2575. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  2576. if (!renderBufferID)
  2577. {
  2578. // If texture's parameters are dirty, update before attaching
  2579. if (texture->GetParametersDirty())
  2580. {
  2581. SetTextureForUpdate(texture);
  2582. texture->UpdateParameters();
  2583. SetTexture(0, nullptr);
  2584. }
  2585. if (i->second_.depthAttachment_ != depthStencil_)
  2586. {
  2587. BindDepthAttachment(texture->GetGPUObjectName(), false);
  2588. BindStencilAttachment(hasStencil ? texture->GetGPUObjectName() : 0, false);
  2589. i->second_.depthAttachment_ = depthStencil_;
  2590. }
  2591. }
  2592. else
  2593. {
  2594. if (i->second_.depthAttachment_ != depthStencil_)
  2595. {
  2596. BindDepthAttachment(renderBufferID, true);
  2597. BindStencilAttachment(hasStencil ? renderBufferID : 0, true);
  2598. i->second_.depthAttachment_ = depthStencil_;
  2599. }
  2600. }
  2601. }
  2602. else
  2603. {
  2604. if (i->second_.depthAttachment_)
  2605. {
  2606. BindDepthAttachment(0, false);
  2607. BindStencilAttachment(0, false);
  2608. i->second_.depthAttachment_ = nullptr;
  2609. }
  2610. }
  2611. #ifndef GL_ES_VERSION_2_0
  2612. // Disable/enable sRGB write
  2613. if (sRGBWriteSupport_)
  2614. {
  2615. bool sRGBWrite = renderTargets_[0] ? renderTargets_[0]->GetParentTexture()->GetSRGB() : sRGB_;
  2616. if (sRGBWrite != impl_->sRGBWrite_)
  2617. {
  2618. if (sRGBWrite)
  2619. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2620. else
  2621. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2622. impl_->sRGBWrite_ = sRGBWrite;
  2623. }
  2624. }
  2625. #endif
  2626. }
  2627. if (impl_->vertexBuffersDirty_)
  2628. {
  2629. // Go through currently bound vertex buffers and set the attribute pointers that are available & required
  2630. // Use reverse order so that elements from higher index buffers will override lower index buffers
  2631. unsigned assignedLocations = 0;
  2632. for (unsigned i = MAX_VERTEX_STREAMS - 1; i < MAX_VERTEX_STREAMS; --i)
  2633. {
  2634. VertexBuffer* buffer = vertexBuffers_[i];
  2635. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  2636. // in which case the pointer will be invalid and cause a crash
  2637. if (!buffer || !buffer->GetGPUObjectName() || !impl_->vertexAttributes_)
  2638. continue;
  2639. const PODVector<VertexElement>& elements = buffer->GetElements();
  2640. for (PODVector<VertexElement>::ConstIterator j = elements.Begin(); j != elements.End(); ++j)
  2641. {
  2642. const VertexElement& element = *j;
  2643. HashMap<Pair<unsigned char, unsigned char>, unsigned>::ConstIterator k =
  2644. impl_->vertexAttributes_->Find(MakePair((unsigned char)element.semantic_, element.index_));
  2645. if (k != impl_->vertexAttributes_->End())
  2646. {
  2647. unsigned location = k->second_;
  2648. unsigned locationMask = 1u << location;
  2649. if (assignedLocations & locationMask)
  2650. continue; // Already assigned by higher index vertex buffer
  2651. assignedLocations |= locationMask;
  2652. // Enable attribute if not enabled yet
  2653. if (!(impl_->enabledVertexAttributes_ & locationMask))
  2654. {
  2655. glEnableVertexAttribArray(location);
  2656. impl_->enabledVertexAttributes_ |= locationMask;
  2657. }
  2658. // Enable/disable instancing divisor as necessary
  2659. unsigned dataStart = element.offset_;
  2660. if (element.perInstance_)
  2661. {
  2662. dataStart += impl_->lastInstanceOffset_ * buffer->GetVertexSize();
  2663. if (!(impl_->instancingVertexAttributes_ & locationMask))
  2664. {
  2665. SetVertexAttribDivisor(location, 1);
  2666. impl_->instancingVertexAttributes_ |= locationMask;
  2667. }
  2668. }
  2669. else
  2670. {
  2671. if (impl_->instancingVertexAttributes_ & locationMask)
  2672. {
  2673. SetVertexAttribDivisor(location, 0);
  2674. impl_->instancingVertexAttributes_ &= ~locationMask;
  2675. }
  2676. }
  2677. SetVBO(buffer->GetGPUObjectName());
  2678. glVertexAttribPointer(location, glElementComponents[element.type_], glElementTypes[element.type_],
  2679. element.type_ == TYPE_UBYTE4_NORM ? GL_TRUE : GL_FALSE, (unsigned)buffer->GetVertexSize(),
  2680. (const void *)(size_t)dataStart);
  2681. }
  2682. }
  2683. }
  2684. // Finally disable unnecessary vertex attributes
  2685. unsigned disableVertexAttributes = impl_->enabledVertexAttributes_ & (~impl_->usedVertexAttributes_);
  2686. unsigned location = 0;
  2687. while (disableVertexAttributes)
  2688. {
  2689. if (disableVertexAttributes & 1u)
  2690. {
  2691. glDisableVertexAttribArray(location);
  2692. impl_->enabledVertexAttributes_ &= ~(1u << location);
  2693. }
  2694. ++location;
  2695. disableVertexAttributes >>= 1;
  2696. }
  2697. impl_->vertexBuffersDirty_ = false;
  2698. }
  2699. }
  2700. void Graphics::CleanupFramebuffers()
  2701. {
  2702. if (!IsDeviceLost())
  2703. {
  2704. BindFramebuffer(impl_->systemFBO_);
  2705. impl_->boundFBO_ = impl_->systemFBO_;
  2706. impl_->fboDirty_ = true;
  2707. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  2708. i != impl_->frameBuffers_.End(); ++i)
  2709. DeleteFramebuffer(i->second_.fbo_);
  2710. if (impl_->resolveSrcFBO_)
  2711. DeleteFramebuffer(impl_->resolveSrcFBO_);
  2712. if (impl_->resolveDestFBO_)
  2713. DeleteFramebuffer(impl_->resolveDestFBO_);
  2714. impl_->resolveSrcFBO_ = 0;
  2715. impl_->resolveDestFBO_ = 0;
  2716. }
  2717. else
  2718. {
  2719. impl_->boundFBO_ = 0;
  2720. impl_->resolveSrcFBO_ = 0;
  2721. impl_->resolveDestFBO_ = 0;
  2722. }
  2723. impl_->frameBuffers_.Clear();
  2724. }
  2725. void Graphics::ResetCachedState()
  2726. {
  2727. for (auto& vertexBuffer : vertexBuffers_)
  2728. vertexBuffer = nullptr;
  2729. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2730. {
  2731. textures_[i] = nullptr;
  2732. impl_->textureTypes_[i] = 0;
  2733. }
  2734. for (auto& renderTarget : renderTargets_)
  2735. renderTarget = nullptr;
  2736. depthStencil_ = nullptr;
  2737. viewport_ = IntRect(0, 0, 0, 0);
  2738. indexBuffer_ = nullptr;
  2739. vertexShader_ = nullptr;
  2740. pixelShader_ = nullptr;
  2741. blendMode_ = BLEND_REPLACE;
  2742. alphaToCoverage_ = false;
  2743. colorWrite_ = true;
  2744. cullMode_ = CULL_NONE;
  2745. constantDepthBias_ = 0.0f;
  2746. slopeScaledDepthBias_ = 0.0f;
  2747. depthTestMode_ = CMP_ALWAYS;
  2748. depthWrite_ = false;
  2749. lineAntiAlias_ = false;
  2750. fillMode_ = FILL_SOLID;
  2751. scissorTest_ = false;
  2752. scissorRect_ = IntRect::ZERO;
  2753. stencilTest_ = false;
  2754. stencilTestMode_ = CMP_ALWAYS;
  2755. stencilPass_ = OP_KEEP;
  2756. stencilFail_ = OP_KEEP;
  2757. stencilZFail_ = OP_KEEP;
  2758. stencilRef_ = 0;
  2759. stencilCompareMask_ = M_MAX_UNSIGNED;
  2760. stencilWriteMask_ = M_MAX_UNSIGNED;
  2761. useClipPlane_ = false;
  2762. impl_->shaderProgram_ = nullptr;
  2763. impl_->lastInstanceOffset_ = 0;
  2764. impl_->activeTexture_ = 0;
  2765. impl_->enabledVertexAttributes_ = 0;
  2766. impl_->usedVertexAttributes_ = 0;
  2767. impl_->instancingVertexAttributes_ = 0;
  2768. impl_->boundFBO_ = impl_->systemFBO_;
  2769. impl_->boundVBO_ = 0;
  2770. impl_->boundUBO_ = 0;
  2771. impl_->sRGBWrite_ = false;
  2772. // Set initial state to match Direct3D
  2773. if (impl_->context_)
  2774. {
  2775. glEnable(GL_DEPTH_TEST);
  2776. SetCullMode(CULL_CCW);
  2777. SetDepthTest(CMP_LESSEQUAL);
  2778. SetDepthWrite(true);
  2779. }
  2780. for (auto& constantBuffer : impl_->constantBuffers_)
  2781. constantBuffer = nullptr;
  2782. impl_->dirtyConstantBuffers_.Clear();
  2783. }
  2784. void Graphics::SetTextureUnitMappings()
  2785. {
  2786. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2787. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2788. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  2789. textureUnits_["NormalMap"] = TU_NORMAL;
  2790. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2791. textureUnits_["SpecMap"] = TU_SPECULAR;
  2792. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2793. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2794. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2795. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2796. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2797. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2798. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2799. #ifndef GL_ES_VERSION_2_0
  2800. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2801. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2802. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2803. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2804. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2805. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2806. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2807. #endif
  2808. }
  2809. unsigned Graphics::CreateFramebuffer()
  2810. {
  2811. unsigned newFbo = 0;
  2812. #ifndef GL_ES_VERSION_2_0
  2813. if (!gl3Support)
  2814. glGenFramebuffersEXT(1, &newFbo);
  2815. else
  2816. #endif
  2817. glGenFramebuffers(1, &newFbo);
  2818. return newFbo;
  2819. }
  2820. void Graphics::DeleteFramebuffer(unsigned fbo)
  2821. {
  2822. #ifndef GL_ES_VERSION_2_0
  2823. if (!gl3Support)
  2824. glDeleteFramebuffersEXT(1, &fbo);
  2825. else
  2826. #endif
  2827. glDeleteFramebuffers(1, &fbo);
  2828. }
  2829. void Graphics::BindFramebuffer(unsigned fbo)
  2830. {
  2831. #ifndef GL_ES_VERSION_2_0
  2832. if (!gl3Support)
  2833. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
  2834. else
  2835. #endif
  2836. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2837. }
  2838. void Graphics::BindColorAttachment(unsigned index, unsigned target, unsigned object, bool isRenderBuffer)
  2839. {
  2840. if (!object)
  2841. isRenderBuffer = false;
  2842. #ifndef GL_ES_VERSION_2_0
  2843. if (!gl3Support)
  2844. {
  2845. if (!isRenderBuffer)
  2846. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, target, object, 0);
  2847. else
  2848. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_RENDERBUFFER_EXT, object);
  2849. }
  2850. else
  2851. #endif
  2852. {
  2853. if (!isRenderBuffer)
  2854. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, target, object, 0);
  2855. else
  2856. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, GL_RENDERBUFFER, object);
  2857. }
  2858. }
  2859. void Graphics::BindDepthAttachment(unsigned object, bool isRenderBuffer)
  2860. {
  2861. if (!object)
  2862. isRenderBuffer = false;
  2863. #ifndef GL_ES_VERSION_2_0
  2864. if (!gl3Support)
  2865. {
  2866. if (!isRenderBuffer)
  2867. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2868. else
  2869. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2870. }
  2871. else
  2872. #endif
  2873. {
  2874. if (!isRenderBuffer)
  2875. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2876. else
  2877. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, object);
  2878. }
  2879. }
  2880. void Graphics::BindStencilAttachment(unsigned object, bool isRenderBuffer)
  2881. {
  2882. if (!object)
  2883. isRenderBuffer = false;
  2884. #ifndef GL_ES_VERSION_2_0
  2885. if (!gl3Support)
  2886. {
  2887. if (!isRenderBuffer)
  2888. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2889. else
  2890. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2891. }
  2892. else
  2893. #endif
  2894. {
  2895. if (!isRenderBuffer)
  2896. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2897. else
  2898. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, object);
  2899. }
  2900. }
  2901. bool Graphics::CheckFramebuffer()
  2902. {
  2903. #ifndef GL_ES_VERSION_2_0
  2904. if (!gl3Support)
  2905. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  2906. else
  2907. #endif
  2908. return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
  2909. }
  2910. void Graphics::SetVertexAttribDivisor(unsigned location, unsigned divisor)
  2911. {
  2912. #ifndef GL_ES_VERSION_2_0
  2913. if (gl3Support && instancingSupport_)
  2914. glVertexAttribDivisor(location, divisor);
  2915. else if (instancingSupport_)
  2916. glVertexAttribDivisorARB(location, divisor);
  2917. #else
  2918. #ifdef __EMSCRIPTEN__
  2919. if (instancingSupport_)
  2920. glVertexAttribDivisorANGLE(location, divisor);
  2921. #endif
  2922. #endif
  2923. }
  2924. }