OGLGraphics.cpp 96 KB

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