OGLGraphics.cpp 83 KB

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