OGLGraphics.cpp 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421
  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 GLenum 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 GLenum 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 GLenum 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 GLenum 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 GLenum glFillMode[] =
  151. {
  152. GL_FILL,
  153. GL_LINE,
  154. GL_POINT
  155. };
  156. static const GLenum 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 GLenum 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 GLint 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, u32 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_U32_MASK_ALL_BITS)
  517. glStencilMask(M_U32_MASK_ALL_BITS);
  518. GLbitfield 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((GLint)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_U32_MASK_ALL_BITS)
  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 Vector<VertexBuffer*> vertexBuffers(1);
  775. vertexBuffers[0] = buffer;
  776. SetVertexBuffers_OGL(vertexBuffers);
  777. }
  778. bool Graphics::SetVertexBuffers_OGL(const Vector<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 Vector<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 (Vector<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, u32 stencilRef,
  1685. u32 compareMask, u32 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], (GLint)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. Vector<int> Graphics::GetMultiSampleLevels_OGL() const
  1738. {
  1739. Vector<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 (Vector<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 (Vector<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 (Vector<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 (Vector<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 (i32 i = MAX_VERTEX_STREAMS - 1; i >= 0; --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 Vector<VertexElement>& elements = buffer->GetElements();
  2631. for (Vector<VertexElement>::ConstIterator j = elements.Begin(); j != elements.End(); ++j)
  2632. {
  2633. const VertexElement& element = *j;
  2634. HashMap<Pair<i8, i8>, unsigned>::ConstIterator k =
  2635. impl->vertexAttributes_->Find(MakePair((i8)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_U32_MASK_ALL_BITS;
  2749. stencilWriteMask_ = M_U32_MASK_ALL_BITS;
  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. }