OGLGraphics.cpp 98 KB

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