OGLGraphics.cpp 100 KB

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