OGLGraphics.cpp 105 KB

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