OGLGraphics.cpp 80 KB

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