OGLGraphics.cpp 97 KB

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