OGLGraphics.cpp 96 KB

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