OGLGraphics.cpp 103 KB

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