OGLGraphics.cpp 95 KB

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