2
0

OGLGraphics.cpp 102 KB

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