OGLGraphics.cpp 64 KB

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