OGLGraphics.cpp 96 KB

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