OGLGraphics.cpp 85 KB

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