OGLGraphics.cpp 96 KB

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