OGLGraphics.cpp 68 KB

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