OGLGraphics.cpp 80 KB

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