OGLGraphics.cpp 92 KB

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