OGLGraphics.cpp 107 KB

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