OGLGraphics.cpp 92 KB

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