OGLGraphics.cpp 76 KB

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