OGLGraphics.cpp 96 KB

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