OGLGraphics.cpp 89 KB

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