OGLGraphics.cpp 89 KB

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