OGLGraphics.cpp 98 KB

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