OGLGraphics.cpp 98 KB

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