2
0

OGLGraphics.cpp 68 KB

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