2
0

OGLGraphics.cpp 106 KB

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