OGLGraphics.cpp 81 KB

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