OGLGraphics.cpp 97 KB

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