OGLGraphics.cpp 103 KB

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