OGLGraphics.cpp 105 KB

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