OGLGraphics.cpp 66 KB

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