OGLGraphics.cpp 83 KB

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