OGLGraphics.cpp 79 KB

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