OGLGraphics.cpp 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448
  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. // ATOMIC BEGIN
  44. #include <SDL/include/SDL.h>
  45. // ATOMIC END
  46. #include "../../DebugNew.h"
  47. #ifdef GL_ES_VERSION_2_0
  48. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  49. #define glClearDepth glClearDepthf
  50. #endif
  51. #ifdef __EMSCRIPTEN__
  52. // Emscripten provides even all GL extension functions via static linking. However there is
  53. // no GLES2-specific extension header at the moment to include instanced rendering declarations,
  54. // so declare them manually from GLES3 gl2ext.h. Emscripten will provide these when linking final output.
  55. extern "C"
  56. {
  57. GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
  58. GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
  59. GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE (GLuint index, GLuint divisor);
  60. }
  61. #endif
  62. #ifdef _WIN32
  63. // Prefer the high-performance GPU on switchable GPU systems
  64. #include <windows.h>
  65. extern "C"
  66. {
  67. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  68. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  69. }
  70. #endif
  71. namespace Atomic
  72. {
  73. static const unsigned glCmpFunc[] =
  74. {
  75. GL_ALWAYS,
  76. GL_EQUAL,
  77. GL_NOTEQUAL,
  78. GL_LESS,
  79. GL_LEQUAL,
  80. GL_GREATER,
  81. GL_GEQUAL
  82. };
  83. static const unsigned glSrcBlend[] =
  84. {
  85. GL_ONE,
  86. GL_ONE,
  87. GL_DST_COLOR,
  88. GL_SRC_ALPHA,
  89. GL_SRC_ALPHA,
  90. GL_ONE,
  91. GL_ONE_MINUS_DST_ALPHA,
  92. GL_ONE,
  93. GL_SRC_ALPHA
  94. };
  95. static const unsigned glDestBlend[] =
  96. {
  97. GL_ZERO,
  98. GL_ONE,
  99. GL_ZERO,
  100. GL_ONE_MINUS_SRC_ALPHA,
  101. GL_ONE,
  102. GL_ONE_MINUS_SRC_ALPHA,
  103. GL_DST_ALPHA,
  104. GL_ONE,
  105. GL_ONE
  106. };
  107. static const unsigned glBlendOp[] =
  108. {
  109. GL_FUNC_ADD,
  110. GL_FUNC_ADD,
  111. GL_FUNC_ADD,
  112. GL_FUNC_ADD,
  113. GL_FUNC_ADD,
  114. GL_FUNC_ADD,
  115. GL_FUNC_ADD,
  116. GL_FUNC_REVERSE_SUBTRACT,
  117. GL_FUNC_REVERSE_SUBTRACT
  118. };
  119. #ifndef GL_ES_VERSION_2_0
  120. static const unsigned glFillMode[] =
  121. {
  122. GL_FILL,
  123. GL_LINE,
  124. GL_POINT
  125. };
  126. static const unsigned glStencilOps[] =
  127. {
  128. GL_KEEP,
  129. GL_ZERO,
  130. GL_REPLACE,
  131. GL_INCR_WRAP,
  132. GL_DECR_WRAP
  133. };
  134. #endif
  135. static const unsigned glElementTypes[] =
  136. {
  137. GL_INT,
  138. GL_FLOAT,
  139. GL_FLOAT,
  140. GL_FLOAT,
  141. GL_FLOAT,
  142. GL_UNSIGNED_BYTE,
  143. GL_UNSIGNED_BYTE
  144. };
  145. static const unsigned glElementComponents[] =
  146. {
  147. 1,
  148. 1,
  149. 2,
  150. 3,
  151. 4,
  152. 4,
  153. 4
  154. };
  155. #ifdef GL_ES_VERSION_2_0
  156. static unsigned glesDepthStencilFormat = GL_DEPTH_COMPONENT16;
  157. static unsigned glesReadableDepthFormat = GL_DEPTH_COMPONENT;
  158. #endif
  159. static String extensions;
  160. bool CheckExtension(const String& name)
  161. {
  162. if (extensions.Empty())
  163. extensions = (const char*)glGetString(GL_EXTENSIONS);
  164. return extensions.Contains(name);
  165. }
  166. static void GetGLPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount, GLenum& glPrimitiveType)
  167. {
  168. switch (type)
  169. {
  170. case TRIANGLE_LIST:
  171. primitiveCount = elementCount / 3;
  172. glPrimitiveType = GL_TRIANGLES;
  173. break;
  174. case LINE_LIST:
  175. primitiveCount = elementCount / 2;
  176. glPrimitiveType = GL_LINES;
  177. break;
  178. case POINT_LIST:
  179. primitiveCount = elementCount;
  180. glPrimitiveType = GL_POINTS;
  181. break;
  182. case TRIANGLE_STRIP:
  183. primitiveCount = elementCount - 2;
  184. glPrimitiveType = GL_TRIANGLE_STRIP;
  185. break;
  186. case LINE_STRIP:
  187. primitiveCount = elementCount - 1;
  188. glPrimitiveType = GL_LINE_STRIP;
  189. break;
  190. case TRIANGLE_FAN:
  191. primitiveCount = elementCount - 2;
  192. glPrimitiveType = GL_TRIANGLE_FAN;
  193. break;
  194. }
  195. }
  196. const Vector2 Graphics::pixelUVOffset(0.0f, 0.0f);
  197. bool Graphics::gl3Support = false;
  198. Graphics::Graphics(Context* context_) :
  199. Object(context_),
  200. impl_(new GraphicsImpl()),
  201. window_(0),
  202. externalWindow_(0),
  203. width_(0),
  204. height_(0),
  205. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  206. multiSample_(1),
  207. fullscreen_(false),
  208. borderless_(false),
  209. resizable_(false),
  210. highDPI_(false),
  211. vsync_(false),
  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_ = 0;
  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. ATOMIC_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. int x = fullscreen || borderless ? display_rect.x : position_.x_;
  379. int y = fullscreen || borderless ? display_rect.y : position_.y_;
  380. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  381. if (fullscreen)
  382. flags |= SDL_WINDOW_FULLSCREEN;
  383. if (borderless)
  384. flags |= SDL_WINDOW_BORDERLESS;
  385. if (resizable)
  386. flags |= SDL_WINDOW_RESIZABLE;
  387. if (highDPI)
  388. flags |= SDL_WINDOW_ALLOW_HIGHDPI;
  389. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  390. for (;;)
  391. {
  392. if (!externalWindow_)
  393. window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  394. else
  395. {
  396. #ifndef __EMSCRIPTEN__
  397. if (!window_)
  398. window_ = SDL_CreateWindowFrom(externalWindow_, SDL_WINDOW_OPENGL);
  399. fullscreen = false;
  400. #endif
  401. }
  402. if (window_)
  403. break;
  404. else
  405. {
  406. if (multiSample > 1)
  407. {
  408. // If failed with multisampling, retry first without
  409. multiSample = 1;
  410. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  411. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  412. }
  413. else
  414. {
  415. ATOMIC_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  416. return false;
  417. }
  418. }
  419. }
  420. CreateWindowIcon();
  421. if (maximize)
  422. {
  423. Maximize();
  424. SDL_GL_GetDrawableSize(window_, &width, &height);
  425. }
  426. // Create/restore context and GPU objects and set initial renderstate
  427. Restore();
  428. // Specific error message is already logged by Restore() when context creation or OpenGL extensions check fails
  429. if (!impl_->context_)
  430. return false;
  431. }
  432. // Set vsync
  433. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  434. // Store the system FBO on IOS now
  435. #ifdef IOS
  436. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFBO_);
  437. #endif
  438. fullscreen_ = fullscreen;
  439. borderless_ = borderless;
  440. resizable_ = resizable;
  441. highDPI_ = highDPI;
  442. vsync_ = vsync;
  443. tripleBuffer_ = tripleBuffer;
  444. multiSample_ = multiSample;
  445. SDL_GL_GetDrawableSize(window_, &width_, &height_);
  446. if (!fullscreen)
  447. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  448. // Reset rendertargets and viewport for the new screen mode
  449. ResetRenderTargets();
  450. // Clear the initial window contents to black
  451. Clear(CLEAR_COLOR);
  452. SDL_GL_SwapWindow(window_);
  453. CheckFeatureSupport();
  454. #ifdef ATOMIC_LOGGING
  455. String msg;
  456. msg.AppendWithFormat("Set screen mode %dx%d %s monitor %d", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"), monitor_);
  457. if (borderless_)
  458. msg.Append(" borderless");
  459. if (resizable_)
  460. msg.Append(" resizable");
  461. if (multiSample > 1)
  462. msg.AppendWithFormat(" multisample %d", multiSample);
  463. ATOMIC_LOGINFO(msg);
  464. #endif
  465. using namespace ScreenMode;
  466. VariantMap& eventData = GetEventDataMap();
  467. eventData[P_WIDTH] = width_;
  468. eventData[P_HEIGHT] = height_;
  469. eventData[P_FULLSCREEN] = fullscreen_;
  470. eventData[P_BORDERLESS] = borderless_;
  471. eventData[P_RESIZABLE] = resizable_;
  472. eventData[P_HIGHDPI] = highDPI_;
  473. eventData[P_MONITOR] = monitor_;
  474. eventData[P_REFRESHRATE] = refreshRate_;
  475. SendEvent(E_SCREENMODE, eventData);
  476. return true;
  477. }
  478. bool Graphics::SetMode(int width, int height)
  479. {
  480. return SetMode(width, height, fullscreen_, borderless_, resizable_, highDPI_, vsync_, tripleBuffer_, multiSample_, monitor_, refreshRate_);
  481. }
  482. void Graphics::SetSRGB(bool enable)
  483. {
  484. enable &= sRGBWriteSupport_;
  485. if (enable != sRGB_)
  486. {
  487. sRGB_ = enable;
  488. impl_->fboDirty_ = true;
  489. }
  490. }
  491. void Graphics::SetDither(bool enable)
  492. {
  493. if (enable)
  494. glEnable(GL_DITHER);
  495. else
  496. glDisable(GL_DITHER);
  497. }
  498. void Graphics::SetFlushGPU(bool enable)
  499. {
  500. // Currently unimplemented on OpenGL
  501. }
  502. void Graphics::SetForceGL2(bool enable)
  503. {
  504. if (IsInitialized())
  505. {
  506. ATOMIC_LOGERROR("OpenGL 2 can only be forced before setting the initial screen mode");
  507. return;
  508. }
  509. forceGL2_ = enable;
  510. }
  511. void Graphics::Close()
  512. {
  513. if (!IsInitialized())
  514. return;
  515. // Actually close the window
  516. Release(true, true);
  517. }
  518. bool Graphics::TakeScreenShot(Image* destImage_)
  519. {
  520. ATOMIC_PROFILE(TakeScreenShot);
  521. if (!IsInitialized())
  522. return false;
  523. if (IsDeviceLost())
  524. {
  525. ATOMIC_LOGERROR("Can not take screenshot while device is lost");
  526. return false;
  527. }
  528. // ATOMIC BEGIN
  529. if (!destImage_)
  530. return false;
  531. Image& destImage = *destImage_;
  532. // ATOMIC END
  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, 0);
  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. ATOMIC_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. ATOMIC_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, 0);
  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. ATOMIC_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. ATOMIC_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. ATOMIC_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 = 0;
  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. ATOMIC_PROFILE(CompileVertexShader);
  902. bool success = vs->Create();
  903. if (success)
  904. ATOMIC_LOGDEBUG("Compiled vertex shader " + vs->GetFullName());
  905. else
  906. {
  907. ATOMIC_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  908. vs = 0;
  909. }
  910. }
  911. else
  912. vs = 0;
  913. }
  914. if (ps && !ps->GetGPUObjectName())
  915. {
  916. if (ps->GetCompilerOutput().Empty())
  917. {
  918. ATOMIC_PROFILE(CompilePixelShader);
  919. bool success = ps->Create();
  920. if (success)
  921. ATOMIC_LOGDEBUG("Compiled pixel shader " + ps->GetFullName());
  922. else
  923. {
  924. ATOMIC_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  925. ps = 0;
  926. }
  927. }
  928. else
  929. ps = 0;
  930. }
  931. if (!vs || !ps)
  932. {
  933. glUseProgram(0);
  934. vertexShader_ = 0;
  935. pixelShader_ = 0;
  936. impl_->shaderProgram_ = 0;
  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_ = 0;
  956. }
  957. }
  958. else
  959. {
  960. // Link a new combination
  961. ATOMIC_PROFILE(LinkShaders);
  962. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  963. if (newProgram->Link())
  964. {
  965. ATOMIC_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. ATOMIC_LOGERROR("Failed to link vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName() + ":\n" +
  973. newProgram->GetLinkerOutput());
  974. glUseProgram(0);
  975. impl_->shaderProgram_ = 0;
  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_ = 0;
  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*)0);
  1425. SetDepthStencil((RenderSurface*)0);
  1426. SetViewport(IntRect(0, 0, width_, height_));
  1427. }
  1428. void Graphics::ResetRenderTarget(unsigned index)
  1429. {
  1430. SetRenderTarget(index, (RenderSurface*)0);
  1431. }
  1432. void Graphics::ResetDepthStencil()
  1433. {
  1434. SetDepthStencil((RenderSurface*)0);
  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 = 0;
  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 = 0;
  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_ != 0;
  1781. }
  1782. bool Graphics::GetDither() const
  1783. {
  1784. return glIsEnabled(GL_DITHER) ? true : false;
  1785. }
  1786. bool Graphics::IsDeviceLost() const
  1787. {
  1788. // On iOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1789. #ifdef IOS
  1790. if (window_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED) != 0)
  1791. return true;
  1792. #endif
  1793. return impl_->context_ == 0;
  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 0;
  1864. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1865. lastShaderName_ = name;
  1866. }
  1867. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1868. }
  1869. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1870. {
  1871. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  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] : 0;
  1897. }
  1898. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1899. {
  1900. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  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. // Reset rendertargets and viewport for the new screen size. Also clean up any FBO's, as they may be screen size dependent
  1933. CleanupFramebuffers();
  1934. ResetRenderTargets();
  1935. ATOMIC_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1936. using namespace ScreenMode;
  1937. VariantMap& eventData = GetEventDataMap();
  1938. eventData[P_WIDTH] = width_;
  1939. eventData[P_HEIGHT] = height_;
  1940. eventData[P_FULLSCREEN] = fullscreen_;
  1941. eventData[P_RESIZABLE] = resizable_;
  1942. eventData[P_BORDERLESS] = borderless_;
  1943. SendEvent(E_SCREENMODE, eventData);
  1944. }
  1945. void Graphics::OnWindowMoved()
  1946. {
  1947. if (!window_ || fullscreen_)
  1948. return;
  1949. int newX, newY;
  1950. SDL_GetWindowPosition(window_, &newX, &newY);
  1951. if (newX == position_.x_ && newY == position_.y_)
  1952. return;
  1953. position_.x_ = newX;
  1954. position_.y_ = newY;
  1955. ATOMIC_LOGDEBUGF("Window was moved to %d,%d", position_.x_, position_.y_);
  1956. using namespace WindowPos;
  1957. VariantMap& eventData = GetEventDataMap();
  1958. eventData[P_X] = position_.x_;
  1959. eventData[P_Y] = position_.y_;
  1960. SendEvent(E_WINDOWPOS, eventData);
  1961. }
  1962. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1963. {
  1964. if (!surface)
  1965. return;
  1966. // Flush pending FBO changes first if any
  1967. PrepareDraw();
  1968. unsigned currentFBO = impl_->boundFBO_;
  1969. // Go through all FBOs and clean up the surface from them
  1970. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1971. i != impl_->frameBuffers_.End(); ++i)
  1972. {
  1973. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1974. {
  1975. if (i->second_.colorAttachments_[j] == surface)
  1976. {
  1977. if (currentFBO != i->second_.fbo_)
  1978. {
  1979. BindFramebuffer(i->second_.fbo_);
  1980. currentFBO = i->second_.fbo_;
  1981. }
  1982. BindColorAttachment(j, GL_TEXTURE_2D, 0, false);
  1983. i->second_.colorAttachments_[j] = 0;
  1984. // Mark drawbuffer bits to need recalculation
  1985. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1986. }
  1987. }
  1988. if (i->second_.depthAttachment_ == surface)
  1989. {
  1990. if (currentFBO != i->second_.fbo_)
  1991. {
  1992. BindFramebuffer(i->second_.fbo_);
  1993. currentFBO = i->second_.fbo_;
  1994. }
  1995. BindDepthAttachment(0, false);
  1996. BindStencilAttachment(0, false);
  1997. i->second_.depthAttachment_ = 0;
  1998. }
  1999. }
  2000. // Restore previously bound FBO now if needed
  2001. if (currentFBO != impl_->boundFBO_)
  2002. BindFramebuffer(impl_->boundFBO_);
  2003. }
  2004. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  2005. {
  2006. for (ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Begin(); i != impl_->shaderPrograms_.End();)
  2007. {
  2008. if (i->second_->GetVertexShader() == variation || i->second_->GetPixelShader() == variation)
  2009. i = impl_->shaderPrograms_.Erase(i);
  2010. else
  2011. ++i;
  2012. }
  2013. if (vertexShader_ == variation || pixelShader_ == variation)
  2014. impl_->shaderProgram_ = 0;
  2015. }
  2016. ConstantBuffer* Graphics::GetOrCreateConstantBuffer(ShaderType /*type*/, unsigned bindingIndex, unsigned size)
  2017. {
  2018. // Note: shaderType parameter is not used on OpenGL, instead binding index should already use the PS range
  2019. // for PS constant buffers
  2020. unsigned key = (bindingIndex << 16) | size;
  2021. HashMap<unsigned, SharedPtr<ConstantBuffer> >::Iterator i = impl_->allConstantBuffers_.Find(key);
  2022. if (i == impl_->allConstantBuffers_.End())
  2023. {
  2024. i = impl_->allConstantBuffers_.Insert(MakePair(key, SharedPtr<ConstantBuffer>(new ConstantBuffer(context_))));
  2025. i->second_->SetSize(size);
  2026. }
  2027. return i->second_.Get();
  2028. }
  2029. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  2030. {
  2031. if (!window_)
  2032. return;
  2033. {
  2034. MutexLock lock(gpuObjectMutex_);
  2035. if (clearGPUObjects)
  2036. {
  2037. // Shutting down: release all GPU objects that still exist
  2038. // Shader programs are also GPU objects; clear them first to avoid list modification during iteration
  2039. impl_->shaderPrograms_.Clear();
  2040. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2041. (*i)->Release();
  2042. gpuObjects_.Clear();
  2043. }
  2044. else
  2045. {
  2046. // We are not shutting down, but recreating the context: mark GPU objects lost
  2047. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2048. (*i)->OnDeviceLost();
  2049. // In this case clear shader programs last so that they do not attempt to delete their OpenGL program
  2050. // from a context that may no longer exist
  2051. impl_->shaderPrograms_.Clear();
  2052. SendEvent(E_DEVICELOST);
  2053. }
  2054. }
  2055. CleanupFramebuffers();
  2056. impl_->depthTextures_.Clear();
  2057. // End fullscreen mode first to counteract transition and getting stuck problems on OS X
  2058. #if defined(__APPLE__) && !defined(IOS)
  2059. if (closeWindow && fullscreen_ && !externalWindow_)
  2060. SDL_SetWindowFullscreen(window_, 0);
  2061. #endif
  2062. if (impl_->context_)
  2063. {
  2064. // Do not log this message if we are exiting
  2065. if (!clearGPUObjects)
  2066. ATOMIC_LOGINFO("OpenGL context lost");
  2067. SDL_GL_DeleteContext(impl_->context_);
  2068. impl_->context_ = 0;
  2069. }
  2070. if (closeWindow)
  2071. {
  2072. SDL_ShowCursor(SDL_TRUE);
  2073. // Do not destroy external window except when shutting down
  2074. if (!externalWindow_ || clearGPUObjects)
  2075. {
  2076. SDL_DestroyWindow(window_);
  2077. window_ = 0;
  2078. }
  2079. }
  2080. }
  2081. void Graphics::Restore()
  2082. {
  2083. if (!window_)
  2084. return;
  2085. #ifdef __ANDROID__
  2086. // On Android the context may be lost behind the scenes as the application is minimized
  2087. if (impl_->context_ && !SDL_GL_GetCurrentContext())
  2088. {
  2089. impl_->context_ = 0;
  2090. // Mark GPU objects lost without a current context. In this case they just mark their internal state lost
  2091. // but do not perform OpenGL commands to delete the GL objects
  2092. Release(false, false);
  2093. }
  2094. #endif
  2095. // Ensure first that the context exists
  2096. if (!impl_->context_)
  2097. {
  2098. impl_->context_ = SDL_GL_CreateContext(window_);
  2099. // ATOMIC BEGIN
  2100. #if defined(__linux__)
  2101. String driverx( (const char*)glGetString(GL_VERSION) );
  2102. Vector<String>tokens = driverx.Split (' ');
  2103. if (tokens.Size() > 2) // must have enough tokens to work with
  2104. {
  2105. // Size() - 2 is the manufacturer, "Mesa" is the target
  2106. if ( tokens[ tokens.Size()-2].Compare ( "Mesa", false ) == 0 )
  2107. {
  2108. // Size() - 1 is the version number, convert to long, can be n | n.n | n.n.n
  2109. Vector<String>versionx = tokens[tokens.Size()-1].Split ('.');
  2110. int majver = 0;
  2111. int minver = 0;
  2112. int pointver = 0;
  2113. if ( tokens.Size() > 1 ) majver = atoi(versionx[0].CString());
  2114. if ( tokens.Size() > 2 ) minver = atoi(versionx[1].CString());
  2115. if ( tokens.Size() > 3 ) pointver = atoi(versionx[2].CString());
  2116. int allver = (majver * 10000) + (minver * 1000) + pointver;
  2117. if ( allver < 101004 ) // Mesa drivers less than this version cause linux display artifacts
  2118. { // so remove this context and let it fall back to GL2
  2119. SDL_GL_DeleteContext(impl_->context_);
  2120. impl_->context_ = NULL;
  2121. ATOMIC_LOGINFOF ( "Mesa GL Driver: %s detected, forcing GL2 context creation. Please use gl2 command line option to avoid this warning.", driverx.CString() );
  2122. }
  2123. }
  2124. }
  2125. #endif
  2126. // ATOMIC END
  2127. #ifndef GL_ES_VERSION_2_0
  2128. // If we're trying to use OpenGL 3, but context creation fails, retry with 2
  2129. if (!forceGL2_ && !impl_->context_)
  2130. {
  2131. forceGL2_ = true;
  2132. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  2133. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  2134. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  2135. impl_->context_ = SDL_GL_CreateContext(window_);
  2136. }
  2137. #endif
  2138. #ifdef IOS
  2139. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFBO_);
  2140. #endif
  2141. if (!impl_->context_)
  2142. {
  2143. ATOMIC_LOGERRORF("Could not create OpenGL context, root cause '%s'", SDL_GetError());
  2144. return;
  2145. }
  2146. // Clear cached extensions string from the previous context
  2147. extensions.Clear();
  2148. // Initialize OpenGL extensions library (desktop only)
  2149. #ifndef GL_ES_VERSION_2_0
  2150. GLenum err = glewInit();
  2151. if (GLEW_OK != err)
  2152. {
  2153. ATOMIC_LOGERRORF("Could not initialize OpenGL extensions, root cause: '%s'", glewGetErrorString(err));
  2154. return;
  2155. }
  2156. if (!forceGL2_ && GLEW_VERSION_3_2)
  2157. {
  2158. gl3Support = true;
  2159. apiName_ = "GL3";
  2160. // Create and bind a vertex array object that will stay in use throughout
  2161. unsigned vertexArrayObject;
  2162. glGenVertexArrays(1, &vertexArrayObject);
  2163. glBindVertexArray(vertexArrayObject);
  2164. }
  2165. else if (GLEW_VERSION_2_0)
  2166. {
  2167. if (!GLEW_EXT_framebuffer_object || !GLEW_EXT_packed_depth_stencil)
  2168. {
  2169. ATOMIC_LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  2170. return;
  2171. }
  2172. gl3Support = false;
  2173. apiName_ = "GL2";
  2174. }
  2175. else
  2176. {
  2177. ATOMIC_LOGERROR("OpenGL 2.0 is required");
  2178. return;
  2179. }
  2180. // Enable seamless cubemap if possible
  2181. // Note: even though we check the extension, this can lead to software fallback on some old GPU's
  2182. // See https://github.com/urho3d/Urho3D/issues/1380 or
  2183. // http://distrustsimplicity.net/articles/gl_texture_cube_map_seamless-on-os-x/
  2184. // In case of trouble or for wanting maximum compatibility, simply remove the glEnable below.
  2185. if (gl3Support || GLEW_ARB_seamless_cube_map)
  2186. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  2187. #endif
  2188. // Set up texture data read/write alignment. It is important that this is done before uploading any texture data
  2189. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  2190. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  2191. ResetCachedState();
  2192. }
  2193. {
  2194. MutexLock lock(gpuObjectMutex_);
  2195. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2196. (*i)->OnDeviceReset();
  2197. }
  2198. SendEvent(E_DEVICERESET);
  2199. }
  2200. void Graphics::MarkFBODirty()
  2201. {
  2202. impl_->fboDirty_ = true;
  2203. }
  2204. void Graphics::SetVBO(unsigned object)
  2205. {
  2206. if (impl_->boundVBO_ != object)
  2207. {
  2208. if (object)
  2209. glBindBuffer(GL_ARRAY_BUFFER, object);
  2210. impl_->boundVBO_ = object;
  2211. }
  2212. }
  2213. void Graphics::SetUBO(unsigned object)
  2214. {
  2215. #ifndef GL_ES_VERSION_2_0
  2216. if (impl_->boundUBO_ != object)
  2217. {
  2218. if (object)
  2219. glBindBuffer(GL_UNIFORM_BUFFER, object);
  2220. impl_->boundUBO_ = object;
  2221. }
  2222. #endif
  2223. }
  2224. unsigned Graphics::GetAlphaFormat()
  2225. {
  2226. #ifndef GL_ES_VERSION_2_0
  2227. // Alpha format is deprecated on OpenGL 3+
  2228. if (gl3Support)
  2229. return GL_R8;
  2230. #endif
  2231. return GL_ALPHA;
  2232. }
  2233. unsigned Graphics::GetLuminanceFormat()
  2234. {
  2235. #ifndef GL_ES_VERSION_2_0
  2236. // Luminance format is deprecated on OpenGL 3+
  2237. if (gl3Support)
  2238. return GL_R8;
  2239. #endif
  2240. return GL_LUMINANCE;
  2241. }
  2242. unsigned Graphics::GetLuminanceAlphaFormat()
  2243. {
  2244. #ifndef GL_ES_VERSION_2_0
  2245. // Luminance alpha format is deprecated on OpenGL 3+
  2246. if (gl3Support)
  2247. return GL_RG8;
  2248. #endif
  2249. return GL_LUMINANCE_ALPHA;
  2250. }
  2251. unsigned Graphics::GetRGBFormat()
  2252. {
  2253. return GL_RGB;
  2254. }
  2255. unsigned Graphics::GetRGBAFormat()
  2256. {
  2257. return GL_RGBA;
  2258. }
  2259. unsigned Graphics::GetRGBA16Format()
  2260. {
  2261. #ifndef GL_ES_VERSION_2_0
  2262. return GL_RGBA16;
  2263. #else
  2264. return GL_RGBA;
  2265. #endif
  2266. }
  2267. unsigned Graphics::GetRGBAFloat16Format()
  2268. {
  2269. #ifndef GL_ES_VERSION_2_0
  2270. return GL_RGBA16F_ARB;
  2271. #else
  2272. return GL_RGBA;
  2273. #endif
  2274. }
  2275. unsigned Graphics::GetRGBAFloat32Format()
  2276. {
  2277. #ifndef GL_ES_VERSION_2_0
  2278. return GL_RGBA32F_ARB;
  2279. #else
  2280. return GL_RGBA;
  2281. #endif
  2282. }
  2283. unsigned Graphics::GetRG16Format()
  2284. {
  2285. #ifndef GL_ES_VERSION_2_0
  2286. return GL_RG16;
  2287. #else
  2288. return GL_RGBA;
  2289. #endif
  2290. }
  2291. unsigned Graphics::GetRGFloat16Format()
  2292. {
  2293. #ifndef GL_ES_VERSION_2_0
  2294. return GL_RG16F;
  2295. #else
  2296. return GL_RGBA;
  2297. #endif
  2298. }
  2299. unsigned Graphics::GetRGFloat32Format()
  2300. {
  2301. #ifndef GL_ES_VERSION_2_0
  2302. return GL_RG32F;
  2303. #else
  2304. return GL_RGBA;
  2305. #endif
  2306. }
  2307. unsigned Graphics::GetFloat16Format()
  2308. {
  2309. #ifndef GL_ES_VERSION_2_0
  2310. return GL_R16F;
  2311. #else
  2312. return GL_LUMINANCE;
  2313. #endif
  2314. }
  2315. unsigned Graphics::GetFloat32Format()
  2316. {
  2317. #ifndef GL_ES_VERSION_2_0
  2318. return GL_R32F;
  2319. #else
  2320. return GL_LUMINANCE;
  2321. #endif
  2322. }
  2323. unsigned Graphics::GetLinearDepthFormat()
  2324. {
  2325. #ifndef GL_ES_VERSION_2_0
  2326. // OpenGL 3 can use different color attachment formats
  2327. if (gl3Support)
  2328. return GL_R32F;
  2329. #endif
  2330. // OpenGL 2 requires color attachments to have the same format, therefore encode deferred depth to RGBA manually
  2331. // if not using a readable hardware depth texture
  2332. return GL_RGBA;
  2333. }
  2334. unsigned Graphics::GetDepthStencilFormat()
  2335. {
  2336. #ifndef GL_ES_VERSION_2_0
  2337. return GL_DEPTH24_STENCIL8_EXT;
  2338. #else
  2339. return glesDepthStencilFormat;
  2340. #endif
  2341. }
  2342. unsigned Graphics::GetReadableDepthFormat()
  2343. {
  2344. #ifndef GL_ES_VERSION_2_0
  2345. return GL_DEPTH_COMPONENT24;
  2346. #else
  2347. return glesReadableDepthFormat;
  2348. #endif
  2349. }
  2350. unsigned Graphics::GetFormat(const String& formatName)
  2351. {
  2352. String nameLower = formatName.ToLower().Trimmed();
  2353. if (nameLower == "a")
  2354. return GetAlphaFormat();
  2355. if (nameLower == "l")
  2356. return GetLuminanceFormat();
  2357. if (nameLower == "la")
  2358. return GetLuminanceAlphaFormat();
  2359. if (nameLower == "rgb")
  2360. return GetRGBFormat();
  2361. if (nameLower == "rgba")
  2362. return GetRGBAFormat();
  2363. if (nameLower == "rgba16")
  2364. return GetRGBA16Format();
  2365. if (nameLower == "rgba16f")
  2366. return GetRGBAFloat16Format();
  2367. if (nameLower == "rgba32f")
  2368. return GetRGBAFloat32Format();
  2369. if (nameLower == "rg16")
  2370. return GetRG16Format();
  2371. if (nameLower == "rg16f")
  2372. return GetRGFloat16Format();
  2373. if (nameLower == "rg32f")
  2374. return GetRGFloat32Format();
  2375. if (nameLower == "r16f")
  2376. return GetFloat16Format();
  2377. if (nameLower == "r32f" || nameLower == "float")
  2378. return GetFloat32Format();
  2379. if (nameLower == "lineardepth" || nameLower == "depth")
  2380. return GetLinearDepthFormat();
  2381. if (nameLower == "d24s8")
  2382. return GetDepthStencilFormat();
  2383. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  2384. return GetReadableDepthFormat();
  2385. return GetRGBFormat();
  2386. }
  2387. void Graphics::CheckFeatureSupport()
  2388. {
  2389. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  2390. lightPrepassSupport_ = false;
  2391. deferredSupport_ = false;
  2392. #ifndef GL_ES_VERSION_2_0
  2393. int numSupportedRTs = 1;
  2394. if (gl3Support)
  2395. {
  2396. // Work around GLEW failure to check extensions properly from a GL3 context
  2397. instancingSupport_ = glDrawElementsInstanced != 0 && glVertexAttribDivisor != 0;
  2398. dxtTextureSupport_ = true;
  2399. anisotropySupport_ = true;
  2400. sRGBSupport_ = true;
  2401. sRGBWriteSupport_ = true;
  2402. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &numSupportedRTs);
  2403. }
  2404. else
  2405. {
  2406. instancingSupport_ = GLEW_ARB_instanced_arrays != 0;
  2407. dxtTextureSupport_ = GLEW_EXT_texture_compression_s3tc != 0;
  2408. anisotropySupport_ = GLEW_EXT_texture_filter_anisotropic != 0;
  2409. sRGBSupport_ = GLEW_EXT_texture_sRGB != 0;
  2410. sRGBWriteSupport_ = GLEW_EXT_framebuffer_sRGB != 0;
  2411. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  2412. }
  2413. // Must support 2 rendertargets for light pre-pass, and 4 for deferred
  2414. if (numSupportedRTs >= 2)
  2415. lightPrepassSupport_ = true;
  2416. if (numSupportedRTs >= 4)
  2417. deferredSupport_ = true;
  2418. #if defined(__APPLE__) && !defined(IOS)
  2419. // On OS X check for an Intel driver and use shadow map RGBA dummy color textures, because mixing
  2420. // depth-only FBO rendering and backbuffer rendering will bug, resulting in a black screen in full
  2421. // screen mode, and incomplete shadow maps in windowed mode
  2422. String renderer((const char*)glGetString(GL_RENDERER));
  2423. if (renderer.Contains("Intel", false))
  2424. dummyColorFormat_ = GetRGBAFormat();
  2425. #endif
  2426. #else
  2427. // Check for supported compressed texture formats
  2428. #ifdef __EMSCRIPTEN__
  2429. dxtTextureSupport_ = CheckExtension("WEBGL_compressed_texture_s3tc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  2430. etcTextureSupport_ = CheckExtension("WEBGL_compressed_texture_etc1"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/
  2431. pvrtcTextureSupport_ = CheckExtension("WEBGL_compressed_texture_pvrtc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  2432. // 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/
  2433. // 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.
  2434. instancingSupport_ = (strstr((const char *)glGetString(GL_VERSION), "WebGL 2.") != 0) || CheckExtension("ANGLE_instanced_arrays");
  2435. #else
  2436. dxtTextureSupport_ = CheckExtension("EXT_texture_compression_dxt1");
  2437. etcTextureSupport_ = CheckExtension("OES_compressed_ETC1_RGB8_texture");
  2438. pvrtcTextureSupport_ = CheckExtension("IMG_texture_compression_pvrtc");
  2439. #endif
  2440. // Check for best supported depth renderbuffer format for GLES2
  2441. if (CheckExtension("GL_OES_depth24"))
  2442. glesDepthStencilFormat = GL_DEPTH_COMPONENT24_OES;
  2443. if (CheckExtension("GL_OES_packed_depth_stencil"))
  2444. glesDepthStencilFormat = GL_DEPTH24_STENCIL8_OES;
  2445. #ifdef __EMSCRIPTEN__
  2446. if (!CheckExtension("WEBGL_depth_texture"))
  2447. #else
  2448. if (!CheckExtension("GL_OES_depth_texture"))
  2449. #endif
  2450. {
  2451. shadowMapFormat_ = 0;
  2452. hiresShadowMapFormat_ = 0;
  2453. glesReadableDepthFormat = 0;
  2454. }
  2455. else
  2456. {
  2457. #ifdef IOS
  2458. // iOS hack: depth renderbuffer seems to fail, so use depth textures for everything
  2459. // if supported
  2460. glesDepthStencilFormat = GL_DEPTH_COMPONENT;
  2461. #endif
  2462. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  2463. hiresShadowMapFormat_ = 0;
  2464. // WebGL shadow map rendering seems to be extremely slow without an attached dummy color texture
  2465. #ifdef __EMSCRIPTEN__
  2466. dummyColorFormat_ = GetRGBAFormat();
  2467. #endif
  2468. }
  2469. #endif
  2470. // Consider OpenGL shadows always hardware sampled, if supported at all
  2471. hardwareShadowSupport_ = shadowMapFormat_ != 0;
  2472. }
  2473. void Graphics::PrepareDraw()
  2474. {
  2475. #ifndef GL_ES_VERSION_2_0
  2476. if (gl3Support)
  2477. {
  2478. for (PODVector<ConstantBuffer*>::Iterator i = impl_->dirtyConstantBuffers_.Begin(); i != impl_->dirtyConstantBuffers_.End(); ++i)
  2479. (*i)->Apply();
  2480. impl_->dirtyConstantBuffers_.Clear();
  2481. }
  2482. #endif
  2483. if (impl_->fboDirty_)
  2484. {
  2485. impl_->fboDirty_ = false;
  2486. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  2487. bool noFbo = !depthStencil_;
  2488. if (noFbo)
  2489. {
  2490. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2491. {
  2492. if (renderTargets_[i])
  2493. {
  2494. noFbo = false;
  2495. break;
  2496. }
  2497. }
  2498. }
  2499. if (noFbo)
  2500. {
  2501. if (impl_->boundFBO_ != impl_->systemFBO_)
  2502. {
  2503. BindFramebuffer(impl_->systemFBO_);
  2504. impl_->boundFBO_ = impl_->systemFBO_;
  2505. }
  2506. #ifndef GL_ES_VERSION_2_0
  2507. // Disable/enable sRGB write
  2508. if (sRGBWriteSupport_)
  2509. {
  2510. bool sRGBWrite = sRGB_;
  2511. if (sRGBWrite != impl_->sRGBWrite_)
  2512. {
  2513. if (sRGBWrite)
  2514. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2515. else
  2516. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2517. impl_->sRGBWrite_ = sRGBWrite;
  2518. }
  2519. }
  2520. #endif
  2521. return;
  2522. }
  2523. // Search for a new framebuffer based on format & size, or create new
  2524. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  2525. unsigned format = 0;
  2526. if (renderTargets_[0])
  2527. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  2528. else if (depthStencil_)
  2529. format = depthStencil_->GetParentTexture()->GetFormat();
  2530. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  2531. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  2532. if (i == impl_->frameBuffers_.End())
  2533. {
  2534. FrameBufferObject newFbo;
  2535. newFbo.fbo_ = CreateFramebuffer();
  2536. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  2537. }
  2538. if (impl_->boundFBO_ != i->second_.fbo_)
  2539. {
  2540. BindFramebuffer(i->second_.fbo_);
  2541. impl_->boundFBO_ = i->second_.fbo_;
  2542. }
  2543. #ifndef GL_ES_VERSION_2_0
  2544. // Setup readbuffers & drawbuffers if needed
  2545. if (i->second_.readBuffers_ != GL_NONE)
  2546. {
  2547. glReadBuffer(GL_NONE);
  2548. i->second_.readBuffers_ = GL_NONE;
  2549. }
  2550. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  2551. unsigned newDrawBuffers = 0;
  2552. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2553. {
  2554. if (renderTargets_[j])
  2555. newDrawBuffers |= 1 << j;
  2556. }
  2557. if (newDrawBuffers != i->second_.drawBuffers_)
  2558. {
  2559. // Check for no color rendertargets (depth rendering only)
  2560. if (!newDrawBuffers)
  2561. glDrawBuffer(GL_NONE);
  2562. else
  2563. {
  2564. int drawBufferIds[MAX_RENDERTARGETS];
  2565. unsigned drawBufferCount = 0;
  2566. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2567. {
  2568. if (renderTargets_[j])
  2569. {
  2570. if (!gl3Support)
  2571. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + j;
  2572. else
  2573. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0 + j;
  2574. }
  2575. }
  2576. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  2577. }
  2578. i->second_.drawBuffers_ = newDrawBuffers;
  2579. }
  2580. #endif
  2581. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2582. {
  2583. if (renderTargets_[j])
  2584. {
  2585. Texture* texture = renderTargets_[j]->GetParentTexture();
  2586. // Bind either a renderbuffer or texture, depending on what is available
  2587. unsigned renderBufferID = renderTargets_[j]->GetRenderBuffer();
  2588. if (!renderBufferID)
  2589. {
  2590. // If texture's parameters are dirty, update before attaching
  2591. if (texture->GetParametersDirty())
  2592. {
  2593. SetTextureForUpdate(texture);
  2594. texture->UpdateParameters();
  2595. SetTexture(0, 0);
  2596. }
  2597. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2598. {
  2599. BindColorAttachment(j, renderTargets_[j]->GetTarget(), texture->GetGPUObjectName(), false);
  2600. i->second_.colorAttachments_[j] = renderTargets_[j];
  2601. }
  2602. }
  2603. else
  2604. {
  2605. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2606. {
  2607. BindColorAttachment(j, renderTargets_[j]->GetTarget(), renderBufferID, true);
  2608. i->second_.colorAttachments_[j] = renderTargets_[j];
  2609. }
  2610. }
  2611. }
  2612. else
  2613. {
  2614. if (i->second_.colorAttachments_[j])
  2615. {
  2616. BindColorAttachment(j, GL_TEXTURE_2D, 0, false);
  2617. i->second_.colorAttachments_[j] = 0;
  2618. }
  2619. }
  2620. }
  2621. if (depthStencil_)
  2622. {
  2623. // Bind either a renderbuffer or a depth texture, depending on what is available
  2624. Texture* texture = depthStencil_->GetParentTexture();
  2625. #ifndef GL_ES_VERSION_2_0
  2626. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_EXT;
  2627. #else
  2628. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_OES;
  2629. #endif
  2630. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  2631. if (!renderBufferID)
  2632. {
  2633. // If texture's parameters are dirty, update before attaching
  2634. if (texture->GetParametersDirty())
  2635. {
  2636. SetTextureForUpdate(texture);
  2637. texture->UpdateParameters();
  2638. SetTexture(0, 0);
  2639. }
  2640. if (i->second_.depthAttachment_ != depthStencil_)
  2641. {
  2642. BindDepthAttachment(texture->GetGPUObjectName(), false);
  2643. BindStencilAttachment(hasStencil ? texture->GetGPUObjectName() : 0, false);
  2644. i->second_.depthAttachment_ = depthStencil_;
  2645. }
  2646. }
  2647. else
  2648. {
  2649. if (i->second_.depthAttachment_ != depthStencil_)
  2650. {
  2651. BindDepthAttachment(renderBufferID, true);
  2652. BindStencilAttachment(hasStencil ? renderBufferID : 0, true);
  2653. i->second_.depthAttachment_ = depthStencil_;
  2654. }
  2655. }
  2656. }
  2657. else
  2658. {
  2659. if (i->second_.depthAttachment_)
  2660. {
  2661. BindDepthAttachment(0, false);
  2662. BindStencilAttachment(0, false);
  2663. i->second_.depthAttachment_ = 0;
  2664. }
  2665. }
  2666. #ifndef GL_ES_VERSION_2_0
  2667. // Disable/enable sRGB write
  2668. if (sRGBWriteSupport_)
  2669. {
  2670. bool sRGBWrite = renderTargets_[0] ? renderTargets_[0]->GetParentTexture()->GetSRGB() : sRGB_;
  2671. if (sRGBWrite != impl_->sRGBWrite_)
  2672. {
  2673. if (sRGBWrite)
  2674. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2675. else
  2676. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2677. impl_->sRGBWrite_ = sRGBWrite;
  2678. }
  2679. }
  2680. #endif
  2681. }
  2682. if (impl_->vertexBuffersDirty_)
  2683. {
  2684. // Go through currently bound vertex buffers and set the attribute pointers that are available & required
  2685. // Use reverse order so that elements from higher index buffers will override lower index buffers
  2686. unsigned assignedLocations = 0;
  2687. for (unsigned i = MAX_VERTEX_STREAMS - 1; i < MAX_VERTEX_STREAMS; --i)
  2688. {
  2689. VertexBuffer* buffer = vertexBuffers_[i];
  2690. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  2691. // in which case the pointer will be invalid and cause a crash
  2692. if (!buffer || !buffer->GetGPUObjectName() || !impl_->vertexAttributes_)
  2693. continue;
  2694. const PODVector<VertexElement>& elements = buffer->GetElements();
  2695. for (PODVector<VertexElement>::ConstIterator j = elements.Begin(); j != elements.End(); ++j)
  2696. {
  2697. const VertexElement& element = *j;
  2698. HashMap<Pair<unsigned char, unsigned char>, unsigned>::ConstIterator k =
  2699. impl_->vertexAttributes_->Find(MakePair((unsigned char)element.semantic_, element.index_));
  2700. if (k != impl_->vertexAttributes_->End())
  2701. {
  2702. unsigned location = k->second_;
  2703. unsigned locationMask = 1 << location;
  2704. if (assignedLocations & locationMask)
  2705. continue; // Already assigned by higher index vertex buffer
  2706. assignedLocations |= locationMask;
  2707. // Enable attribute if not enabled yet
  2708. if (!(impl_->enabledVertexAttributes_ & locationMask))
  2709. {
  2710. glEnableVertexAttribArray(location);
  2711. impl_->enabledVertexAttributes_ |= locationMask;
  2712. }
  2713. // Enable/disable instancing divisor as necessary
  2714. unsigned dataStart = element.offset_;
  2715. if (element.perInstance_)
  2716. {
  2717. dataStart += impl_->lastInstanceOffset_ * buffer->GetVertexSize();
  2718. if (!(impl_->instancingVertexAttributes_ & locationMask))
  2719. {
  2720. SetVertexAttribDivisor(location, 1);
  2721. impl_->instancingVertexAttributes_ |= locationMask;
  2722. }
  2723. }
  2724. else
  2725. {
  2726. if (impl_->instancingVertexAttributes_ & locationMask)
  2727. {
  2728. SetVertexAttribDivisor(location, 0);
  2729. impl_->instancingVertexAttributes_ &= ~locationMask;
  2730. }
  2731. }
  2732. SetVBO(buffer->GetGPUObjectName());
  2733. glVertexAttribPointer(location, glElementComponents[element.type_], glElementTypes[element.type_],
  2734. element.type_ == TYPE_UBYTE4_NORM ? GL_TRUE : GL_FALSE, (unsigned)buffer->GetVertexSize(),
  2735. (const void *)(size_t)dataStart);
  2736. }
  2737. }
  2738. }
  2739. // Finally disable unnecessary vertex attributes
  2740. unsigned disableVertexAttributes = impl_->enabledVertexAttributes_ & (~impl_->usedVertexAttributes_);
  2741. unsigned location = 0;
  2742. while (disableVertexAttributes)
  2743. {
  2744. if (disableVertexAttributes & 1)
  2745. {
  2746. glDisableVertexAttribArray(location);
  2747. impl_->enabledVertexAttributes_ &= ~(1 << location);
  2748. }
  2749. ++location;
  2750. disableVertexAttributes >>= 1;
  2751. }
  2752. impl_->vertexBuffersDirty_ = false;
  2753. }
  2754. }
  2755. void Graphics::CleanupFramebuffers()
  2756. {
  2757. if (!IsDeviceLost())
  2758. {
  2759. BindFramebuffer(impl_->systemFBO_);
  2760. impl_->boundFBO_ = impl_->systemFBO_;
  2761. impl_->fboDirty_ = true;
  2762. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  2763. i != impl_->frameBuffers_.End(); ++i)
  2764. DeleteFramebuffer(i->second_.fbo_);
  2765. if (impl_->resolveSrcFBO_)
  2766. DeleteFramebuffer(impl_->resolveSrcFBO_);
  2767. if (impl_->resolveDestFBO_)
  2768. DeleteFramebuffer(impl_->resolveDestFBO_);
  2769. }
  2770. else
  2771. {
  2772. impl_->boundFBO_ = 0;
  2773. impl_->resolveSrcFBO_ = 0;
  2774. impl_->resolveDestFBO_ = 0;
  2775. }
  2776. impl_->frameBuffers_.Clear();
  2777. }
  2778. void Graphics::ResetCachedState()
  2779. {
  2780. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2781. vertexBuffers_[i] = 0;
  2782. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2783. {
  2784. textures_[i] = 0;
  2785. impl_->textureTypes_[i] = 0;
  2786. }
  2787. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2788. renderTargets_[i] = 0;
  2789. depthStencil_ = 0;
  2790. viewport_ = IntRect(0, 0, 0, 0);
  2791. indexBuffer_ = 0;
  2792. vertexShader_ = 0;
  2793. pixelShader_ = 0;
  2794. blendMode_ = BLEND_REPLACE;
  2795. alphaToCoverage_ = false;
  2796. colorWrite_ = true;
  2797. cullMode_ = CULL_NONE;
  2798. constantDepthBias_ = 0.0f;
  2799. slopeScaledDepthBias_ = 0.0f;
  2800. depthTestMode_ = CMP_ALWAYS;
  2801. depthWrite_ = false;
  2802. lineAntiAlias_ = false;
  2803. fillMode_ = FILL_SOLID;
  2804. scissorTest_ = false;
  2805. scissorRect_ = IntRect::ZERO;
  2806. stencilTest_ = false;
  2807. stencilTestMode_ = CMP_ALWAYS;
  2808. stencilPass_ = OP_KEEP;
  2809. stencilFail_ = OP_KEEP;
  2810. stencilZFail_ = OP_KEEP;
  2811. stencilRef_ = 0;
  2812. stencilCompareMask_ = M_MAX_UNSIGNED;
  2813. stencilWriteMask_ = M_MAX_UNSIGNED;
  2814. useClipPlane_ = false;
  2815. impl_->shaderProgram_ = 0;
  2816. impl_->lastInstanceOffset_ = 0;
  2817. impl_->activeTexture_ = 0;
  2818. impl_->enabledVertexAttributes_ = 0;
  2819. impl_->usedVertexAttributes_ = 0;
  2820. impl_->instancingVertexAttributes_ = 0;
  2821. impl_->boundFBO_ = impl_->systemFBO_;
  2822. impl_->boundVBO_ = 0;
  2823. impl_->boundUBO_ = 0;
  2824. impl_->sRGBWrite_ = false;
  2825. // Set initial state to match Direct3D
  2826. if (impl_->context_)
  2827. {
  2828. glEnable(GL_DEPTH_TEST);
  2829. SetCullMode(CULL_CCW);
  2830. SetDepthTest(CMP_LESSEQUAL);
  2831. SetDepthWrite(true);
  2832. }
  2833. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS * 2; ++i)
  2834. impl_->constantBuffers_[i] = 0;
  2835. impl_->dirtyConstantBuffers_.Clear();
  2836. }
  2837. void Graphics::SetTextureUnitMappings()
  2838. {
  2839. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2840. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2841. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  2842. textureUnits_["NormalMap"] = TU_NORMAL;
  2843. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2844. textureUnits_["SpecMap"] = TU_SPECULAR;
  2845. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2846. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2847. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2848. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2849. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2850. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2851. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2852. #ifndef GL_ES_VERSION_2_0
  2853. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2854. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2855. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2856. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2857. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2858. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2859. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2860. #endif
  2861. }
  2862. unsigned Graphics::CreateFramebuffer()
  2863. {
  2864. unsigned newFbo = 0;
  2865. #ifndef GL_ES_VERSION_2_0
  2866. if (!gl3Support)
  2867. glGenFramebuffersEXT(1, &newFbo);
  2868. else
  2869. #endif
  2870. glGenFramebuffers(1, &newFbo);
  2871. return newFbo;
  2872. }
  2873. void Graphics::DeleteFramebuffer(unsigned fbo)
  2874. {
  2875. #ifndef GL_ES_VERSION_2_0
  2876. if (!gl3Support)
  2877. glDeleteFramebuffersEXT(1, &fbo);
  2878. else
  2879. #endif
  2880. glDeleteFramebuffers(1, &fbo);
  2881. }
  2882. void Graphics::BindFramebuffer(unsigned fbo)
  2883. {
  2884. #ifndef GL_ES_VERSION_2_0
  2885. if (!gl3Support)
  2886. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
  2887. else
  2888. #endif
  2889. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2890. }
  2891. void Graphics::BindColorAttachment(unsigned index, unsigned target, unsigned object, bool isRenderBuffer)
  2892. {
  2893. if (!object)
  2894. isRenderBuffer = false;
  2895. #ifndef GL_ES_VERSION_2_0
  2896. if (!gl3Support)
  2897. {
  2898. if (!isRenderBuffer)
  2899. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, target, object, 0);
  2900. else
  2901. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_RENDERBUFFER_EXT, object);
  2902. }
  2903. else
  2904. #endif
  2905. {
  2906. if (!isRenderBuffer)
  2907. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, target, object, 0);
  2908. else
  2909. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, GL_RENDERBUFFER, object);
  2910. }
  2911. }
  2912. void Graphics::BindDepthAttachment(unsigned object, bool isRenderBuffer)
  2913. {
  2914. if (!object)
  2915. isRenderBuffer = false;
  2916. #ifndef GL_ES_VERSION_2_0
  2917. if (!gl3Support)
  2918. {
  2919. if (!isRenderBuffer)
  2920. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2921. else
  2922. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2923. }
  2924. else
  2925. #endif
  2926. {
  2927. if (!isRenderBuffer)
  2928. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2929. else
  2930. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, object);
  2931. }
  2932. }
  2933. void Graphics::BindStencilAttachment(unsigned object, bool isRenderBuffer)
  2934. {
  2935. if (!object)
  2936. isRenderBuffer = false;
  2937. #ifndef GL_ES_VERSION_2_0
  2938. if (!gl3Support)
  2939. {
  2940. if (!isRenderBuffer)
  2941. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2942. else
  2943. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2944. }
  2945. else
  2946. #endif
  2947. {
  2948. if (!isRenderBuffer)
  2949. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2950. else
  2951. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, object);
  2952. }
  2953. }
  2954. bool Graphics::CheckFramebuffer()
  2955. {
  2956. #ifndef GL_ES_VERSION_2_0
  2957. if (!gl3Support)
  2958. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  2959. else
  2960. #endif
  2961. return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
  2962. }
  2963. void Graphics::SetVertexAttribDivisor(unsigned location, unsigned divisor)
  2964. {
  2965. #ifndef GL_ES_VERSION_2_0
  2966. if (gl3Support && instancingSupport_)
  2967. glVertexAttribDivisor(location, divisor);
  2968. else if (instancingSupport_)
  2969. glVertexAttribDivisorARB(location, divisor);
  2970. #else
  2971. #ifdef __EMSCRIPTEN__
  2972. if (instancingSupport_)
  2973. glVertexAttribDivisorANGLE(location, divisor);
  2974. #endif
  2975. #endif
  2976. }
  2977. }