OGLGraphics.cpp 68 KB

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