OGLGraphics.cpp 85 KB

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