OGLGraphics.cpp 86 KB

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