OGLGraphics.cpp 96 KB

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