OGLGraphics.cpp 88 KB

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