OGLGraphics.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209
  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. ClearParameterSources();
  624. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  625. if (vs && !vs->IsCompiled())
  626. {
  627. if (vs->GetCompilerOutput().Empty())
  628. {
  629. PROFILE(CompileVertexShader);
  630. bool success = vs->Create();
  631. if (success)
  632. LOGDEBUG("Compiled vertex shader " + vs->GetName());
  633. else
  634. {
  635. LOGERROR("Failed to compile vertex shader " + vs->GetName() + ":\n" + vs->GetCompilerOutput());
  636. vs = 0;
  637. }
  638. }
  639. else
  640. vs = 0;
  641. }
  642. if (ps && !ps->IsCompiled())
  643. {
  644. if (ps->GetCompilerOutput().Empty())
  645. {
  646. PROFILE(CompilePixelShader);
  647. bool success = ps->Create();
  648. if (success)
  649. LOGDEBUG("Compiled pixel shader " + ps->GetName());
  650. else
  651. {
  652. LOGERROR("Failed to compile pixel shader " + ps->GetName() + ":\n" + ps->GetCompilerOutput());
  653. ps = 0;
  654. }
  655. }
  656. else
  657. ps = 0;
  658. }
  659. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  660. {
  661. vertexBuffers_[i] = 0;
  662. elementMasks_[i] = 0;
  663. }
  664. if (!vs || !ps)
  665. {
  666. glUseProgram(0);
  667. vertexShader_ = 0;
  668. pixelShader_ = 0;
  669. shaderProgram_ = 0;
  670. }
  671. else
  672. {
  673. vertexShader_ = vs;
  674. pixelShader_ = ps;
  675. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  676. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  677. if (i != shaderPrograms_.End())
  678. {
  679. // Use the existing linked program
  680. if (i->second_->IsLinked())
  681. {
  682. glUseProgram(i->second_->GetGPUObject());
  683. shaderProgram_ = i->second_;
  684. }
  685. else
  686. {
  687. glUseProgram(0);
  688. shaderProgram_ = 0;
  689. }
  690. }
  691. else
  692. {
  693. // Link a new combination
  694. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  695. if (newProgram->Link())
  696. {
  697. LOGDEBUG("Linked vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName());
  698. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  699. // so it is not necessary to call it again
  700. shaderProgram_ = newProgram;
  701. }
  702. else
  703. {
  704. LOGERROR("Failed to link vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName() + ":\n" +
  705. newProgram->GetLinkerOutput());
  706. glUseProgram(0);
  707. shaderProgram_ = 0;
  708. }
  709. shaderPrograms_[combination] = newProgram;
  710. }
  711. }
  712. }
  713. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  714. {
  715. if (shaderProgram_)
  716. {
  717. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  718. if (info)
  719. {
  720. switch (info->type_)
  721. {
  722. case GL_FLOAT:
  723. glUniform1fv(info->location_, count, data);
  724. break;
  725. case GL_FLOAT_VEC2:
  726. glUniform2fv(info->location_, count / 2, data);
  727. break;
  728. case GL_FLOAT_VEC3:
  729. glUniform3fv(info->location_, count / 3, data);
  730. break;
  731. case GL_FLOAT_VEC4:
  732. glUniform4fv(info->location_, count / 4, data);
  733. break;
  734. case GL_FLOAT_MAT3:
  735. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  736. break;
  737. case GL_FLOAT_MAT4:
  738. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  739. break;
  740. }
  741. }
  742. }
  743. }
  744. void Graphics::SetShaderParameter(StringHash param, float value)
  745. {
  746. if (shaderProgram_)
  747. {
  748. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  749. if (info)
  750. glUniform1fv(info->location_, 1, &value);
  751. }
  752. }
  753. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  754. {
  755. SetShaderParameter(param, color.Data(), 4);
  756. }
  757. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  758. {
  759. if (shaderProgram_)
  760. {
  761. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  762. if (info)
  763. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.Data());
  764. }
  765. }
  766. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  767. {
  768. if (shaderProgram_)
  769. {
  770. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  771. if (info)
  772. {
  773. // Check the uniform type to avoid mismatch
  774. switch (info->type_)
  775. {
  776. case GL_FLOAT:
  777. glUniform1fv(info->location_, 1, vector.Data());
  778. break;
  779. case GL_FLOAT_VEC2:
  780. glUniform2fv(info->location_, 1, vector.Data());
  781. break;
  782. case GL_FLOAT_VEC3:
  783. glUniform3fv(info->location_, 1, vector.Data());
  784. break;
  785. }
  786. }
  787. }
  788. }
  789. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  790. {
  791. if (shaderProgram_)
  792. {
  793. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  794. if (info)
  795. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.Data());
  796. }
  797. }
  798. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  799. {
  800. if (shaderProgram_)
  801. {
  802. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  803. if (info)
  804. {
  805. // Check the uniform type to avoid mismatch
  806. switch (info->type_)
  807. {
  808. case GL_FLOAT:
  809. glUniform1fv(info->location_, 1, vector.Data());
  810. break;
  811. case GL_FLOAT_VEC2:
  812. glUniform2fv(info->location_, 1, vector.Data());
  813. break;
  814. case GL_FLOAT_VEC3:
  815. glUniform3fv(info->location_, 1, vector.Data());
  816. break;
  817. case GL_FLOAT_VEC4:
  818. glUniform4fv(info->location_, 1, vector.Data());
  819. break;
  820. }
  821. }
  822. }
  823. }
  824. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  825. {
  826. if (shaderProgram_)
  827. {
  828. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  829. if (info)
  830. {
  831. float data[16];
  832. data[0] = matrix.m00_;
  833. data[1] = matrix.m01_;
  834. data[2] = matrix.m02_;
  835. data[3] = matrix.m03_;
  836. data[4] = matrix.m10_;
  837. data[5] = matrix.m11_;
  838. data[6] = matrix.m12_;
  839. data[7] = matrix.m13_;
  840. data[8] = matrix.m20_;
  841. data[9] = matrix.m21_;
  842. data[10] = matrix.m22_;
  843. data[11] = matrix.m23_;
  844. data[12] = 0.0f;
  845. data[13] = 0.0f;
  846. data[14] = 0.0f;
  847. data[15] = 1.0f;
  848. glUniformMatrix4fv(info->location_, 1, GL_TRUE, data);
  849. }
  850. }
  851. }
  852. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  853. {
  854. if ((unsigned)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  855. {
  856. shaderParameterSources_[group] = source;
  857. return true;
  858. }
  859. else
  860. return false;
  861. }
  862. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  863. {
  864. return shaderProgram_ && shaderProgram_->HasParameter(param);
  865. }
  866. bool Graphics::HasTextureUnit(TextureUnit unit)
  867. {
  868. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  869. }
  870. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  871. {
  872. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  873. }
  874. void Graphics::ClearParameterSources()
  875. {
  876. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  877. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  878. }
  879. void Graphics::ClearTransformSources()
  880. {
  881. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  882. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  883. }
  884. void Graphics::CleanupShaderPrograms()
  885. {
  886. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  887. {
  888. ShaderProgramMap::Iterator current = i++;
  889. ShaderVariation* vs = current->second_->GetVertexShader();
  890. ShaderVariation* ps = current->second_->GetPixelShader();
  891. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  892. shaderPrograms_.Erase(current);
  893. }
  894. }
  895. void Graphics::SetTexture(unsigned index, Texture* texture)
  896. {
  897. if (index >= MAX_TEXTURE_UNITS)
  898. return;
  899. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  900. if (texture)
  901. {
  902. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  903. texture = texture->GetBackupTexture();
  904. }
  905. if (textures_[index] != texture)
  906. {
  907. if (impl_->activeTexture_ != index)
  908. {
  909. glActiveTexture(GL_TEXTURE0 + index);
  910. impl_->activeTexture_ = index;
  911. }
  912. if (texture)
  913. {
  914. unsigned glType = texture->GetTarget();
  915. if (glType != textureTypes_[index])
  916. {
  917. if (textureTypes_[index])
  918. glDisable(textureTypes_[index]);
  919. glEnable(glType);
  920. textureTypes_[index] = glType;
  921. }
  922. glBindTexture(glType, texture->GetGPUObject());
  923. if (texture->GetParametersDirty())
  924. texture->UpdateParameters();
  925. }
  926. else
  927. {
  928. if (textureTypes_[index])
  929. glBindTexture(textureTypes_[index], 0);
  930. }
  931. textures_[index] = texture;
  932. }
  933. else
  934. {
  935. if (texture && texture->GetParametersDirty())
  936. {
  937. if (impl_->activeTexture_ != index)
  938. {
  939. glActiveTexture(GL_TEXTURE0 + index);
  940. impl_->activeTexture_ = index;
  941. }
  942. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  943. texture->UpdateParameters();
  944. }
  945. }
  946. }
  947. void Graphics::SetTextureForUpdate(Texture* texture)
  948. {
  949. if (impl_->activeTexture_ != 0)
  950. {
  951. glActiveTexture(GL_TEXTURE0);
  952. impl_->activeTexture_ = 0;
  953. }
  954. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  955. textures_[0] = texture;
  956. }
  957. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  958. {
  959. if (mode != defaultTextureFilterMode_)
  960. {
  961. defaultTextureFilterMode_ = mode;
  962. SetTextureParametersDirty();
  963. }
  964. }
  965. void Graphics::SetTextureAnisotropy(unsigned level)
  966. {
  967. if (level != textureAnisotropy_)
  968. {
  969. textureAnisotropy_ = level;
  970. SetTextureParametersDirty();
  971. }
  972. }
  973. void Graphics::SetTextureParametersDirty()
  974. {
  975. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  976. {
  977. Texture* texture = dynamic_cast<Texture*>(*i);
  978. if (texture)
  979. texture->SetParametersDirty();
  980. }
  981. }
  982. void Graphics::ResetRenderTargets()
  983. {
  984. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  985. SetRenderTarget(i, (RenderSurface*)0);
  986. SetDepthStencil((RenderSurface*)0);
  987. SetViewport(IntRect(0, 0, width_, height_));
  988. }
  989. void Graphics::ResetRenderTarget(unsigned index)
  990. {
  991. SetRenderTarget(index, (RenderSurface*)0);
  992. }
  993. void Graphics::ResetDepthStencil()
  994. {
  995. SetDepthStencil((RenderSurface*)0);
  996. }
  997. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  998. {
  999. if (index >= MAX_RENDERTARGETS)
  1000. return;
  1001. if (renderTarget != renderTargets_[index])
  1002. {
  1003. renderTargets_[index] = renderTarget;
  1004. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1005. if (renderTarget)
  1006. {
  1007. Texture* parentTexture = renderTarget->GetParentTexture();
  1008. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1009. {
  1010. if (textures_[i] == parentTexture)
  1011. SetTexture(i, textures_[i]->GetBackupTexture());
  1012. }
  1013. }
  1014. impl_->fboDirty_ = true;
  1015. }
  1016. }
  1017. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1018. {
  1019. RenderSurface* renderTarget = 0;
  1020. if (texture)
  1021. renderTarget = texture->GetRenderSurface();
  1022. SetRenderTarget(index, renderTarget);
  1023. }
  1024. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1025. {
  1026. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1027. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1028. if (renderTargets_[0] && !depthStencil)
  1029. {
  1030. int width = renderTargets_[0]->GetWidth();
  1031. int height = renderTargets_[0]->GetHeight();
  1032. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1033. // Check size similarly
  1034. if (width <= width_ && height <= height_)
  1035. {
  1036. int searchKey = (width << 16) | height;
  1037. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1038. if (i != depthTextures_.End())
  1039. depthStencil = i->second_->GetRenderSurface();
  1040. else
  1041. {
  1042. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1043. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1044. depthTextures_[searchKey] = newDepthTexture;
  1045. depthStencil = newDepthTexture->GetRenderSurface();
  1046. }
  1047. }
  1048. }
  1049. if (depthStencil != depthStencil_)
  1050. {
  1051. depthStencil_ = depthStencil;
  1052. impl_->fboDirty_ = true;
  1053. }
  1054. }
  1055. void Graphics::SetDepthStencil(Texture2D* texture)
  1056. {
  1057. RenderSurface* depthStencil = 0;
  1058. if (texture)
  1059. depthStencil = texture->GetRenderSurface();
  1060. SetDepthStencil(depthStencil);
  1061. }
  1062. void Graphics::SetViewTexture(Texture* texture)
  1063. {
  1064. viewTexture_ = texture;
  1065. if (viewTexture_)
  1066. {
  1067. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1068. {
  1069. if (textures_[i] == viewTexture_)
  1070. SetTexture(i, textures_[i]->GetBackupTexture());
  1071. }
  1072. }
  1073. }
  1074. void Graphics::SetViewport(const IntRect& rect)
  1075. {
  1076. if (impl_->fboDirty_)
  1077. CommitFramebuffer();
  1078. IntVector2 rtSize = GetRenderTargetDimensions();
  1079. IntRect rectCopy = rect;
  1080. if (rectCopy.right_ <= rectCopy.left_)
  1081. rectCopy.right_ = rectCopy.left_ + 1;
  1082. if (rectCopy.bottom_ <= rectCopy.top_)
  1083. rectCopy.bottom_ = rectCopy.top_ + 1;
  1084. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1085. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1086. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1087. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1088. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1089. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1090. viewport_ = rectCopy;
  1091. // Disable scissor test, needs to be re-enabled by the user
  1092. SetScissorTest(false);
  1093. }
  1094. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1095. {
  1096. if (enable != alphaTest_)
  1097. {
  1098. if (enable)
  1099. glEnable(GL_ALPHA_TEST);
  1100. else
  1101. glDisable(GL_ALPHA_TEST);
  1102. alphaTest_ = enable;
  1103. }
  1104. if (enable)
  1105. {
  1106. alphaRef = Clamp(alphaRef, 0.0f, 1.0f);
  1107. if (mode != alphaTestMode_ || alphaRef != alphaRef_)
  1108. {
  1109. glAlphaFunc(glCmpFunc[mode], alphaRef);
  1110. alphaTestMode_ = mode;
  1111. alphaRef_ = alphaRef;
  1112. }
  1113. }
  1114. }
  1115. void Graphics::SetBlendMode(BlendMode mode)
  1116. {
  1117. if (mode != blendMode_)
  1118. {
  1119. if (mode == BLEND_REPLACE)
  1120. glDisable(GL_BLEND);
  1121. else
  1122. {
  1123. glEnable(GL_BLEND);
  1124. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1125. }
  1126. blendMode_ = mode;
  1127. }
  1128. }
  1129. void Graphics::SetColorWrite(bool enable)
  1130. {
  1131. if (enable != colorWrite_)
  1132. {
  1133. if (enable)
  1134. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1135. else
  1136. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1137. colorWrite_ = enable;
  1138. }
  1139. }
  1140. void Graphics::SetCullMode(CullMode mode)
  1141. {
  1142. if (mode != cullMode_)
  1143. {
  1144. if (mode == CULL_NONE)
  1145. glDisable(GL_CULL_FACE);
  1146. else
  1147. {
  1148. // Use Direct3D convention, ie. clockwise vertices define a front face
  1149. glEnable(GL_CULL_FACE);
  1150. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1151. }
  1152. cullMode_ = mode;
  1153. }
  1154. }
  1155. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1156. {
  1157. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1158. {
  1159. if (constantBias != 0.0f || slopeScaledBias != 0.0f)
  1160. {
  1161. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1162. // Zero depth bits may be returned if using the packed depth-stencil format. Assume 24bit in that case
  1163. int depthBits = Min(impl_->depthBits_, 23);
  1164. if (!depthBits)
  1165. depthBits = 23;
  1166. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1167. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1168. glEnable(GL_POLYGON_OFFSET_FILL);
  1169. glEnable(GL_POLYGON_OFFSET_LINE);
  1170. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1171. }
  1172. else
  1173. {
  1174. glDisable(GL_POLYGON_OFFSET_FILL);
  1175. glDisable(GL_POLYGON_OFFSET_LINE);
  1176. }
  1177. constantDepthBias_ = constantBias;
  1178. slopeScaledDepthBias_ = slopeScaledBias;
  1179. }
  1180. }
  1181. void Graphics::SetDepthTest(CompareMode mode)
  1182. {
  1183. if (mode != depthTestMode_)
  1184. {
  1185. glDepthFunc(glCmpFunc[mode]);
  1186. depthTestMode_ = mode;
  1187. }
  1188. }
  1189. void Graphics::SetDepthWrite(bool enable)
  1190. {
  1191. if (enable != depthWrite_)
  1192. {
  1193. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1194. depthWrite_ = enable;
  1195. }
  1196. }
  1197. void Graphics::SetFillMode(FillMode mode)
  1198. {
  1199. if (mode != fillMode_)
  1200. {
  1201. glPolygonMode(GL_FRONT_AND_BACK, mode == FILL_SOLID ? GL_FILL : GL_LINE);
  1202. fillMode_ = mode;
  1203. }
  1204. }
  1205. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1206. {
  1207. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1208. // Disable scissor in that case to reduce state changes
  1209. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1210. enable = false;
  1211. if (enable)
  1212. {
  1213. IntVector2 rtSize(GetRenderTargetDimensions());
  1214. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1215. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1216. IntRect intRect;
  1217. int expand = borderInclusive ? 1 : 0;
  1218. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1219. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1220. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1221. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1222. if (intRect.right_ == intRect.left_)
  1223. intRect.right_++;
  1224. if (intRect.bottom_ == intRect.top_)
  1225. intRect.bottom_++;
  1226. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1227. enable = false;
  1228. if (enable && scissorRect_ != intRect)
  1229. {
  1230. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1231. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1232. scissorRect_ = intRect;
  1233. }
  1234. }
  1235. else
  1236. scissorRect_ = IntRect::ZERO;
  1237. if (enable != scissorTest_)
  1238. {
  1239. if (enable)
  1240. glEnable(GL_SCISSOR_TEST);
  1241. else
  1242. glDisable(GL_SCISSOR_TEST);
  1243. scissorTest_ = enable;
  1244. }
  1245. }
  1246. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1247. {
  1248. IntVector2 rtSize(GetRenderTargetDimensions());
  1249. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1250. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1251. if (enable)
  1252. {
  1253. IntRect intRect;
  1254. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1255. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1256. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1257. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1258. if (intRect.right_ == intRect.left_)
  1259. intRect.right_++;
  1260. if (intRect.bottom_ == intRect.top_)
  1261. intRect.bottom_++;
  1262. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1263. enable = false;
  1264. if (enable && scissorRect_ != intRect)
  1265. {
  1266. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1267. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1268. scissorRect_ = intRect;
  1269. }
  1270. }
  1271. else
  1272. scissorRect_ = IntRect::ZERO;
  1273. if (enable != scissorTest_)
  1274. {
  1275. if (enable)
  1276. glEnable(GL_SCISSOR_TEST);
  1277. else
  1278. glDisable(GL_SCISSOR_TEST);
  1279. scissorTest_ = enable;
  1280. }
  1281. }
  1282. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1283. {
  1284. }
  1285. void Graphics::ResetStreamFrequencies()
  1286. {
  1287. }
  1288. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1289. {
  1290. if (enable != stencilTest_)
  1291. {
  1292. if (enable)
  1293. glEnable(GL_STENCIL_TEST);
  1294. else
  1295. glDisable(GL_STENCIL_TEST);
  1296. stencilTest_ = enable;
  1297. }
  1298. if (enable)
  1299. {
  1300. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1301. {
  1302. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1303. stencilTestMode_ = mode;
  1304. stencilRef_ = stencilRef;
  1305. stencilCompareMask_ = compareMask;
  1306. }
  1307. if (writeMask != stencilWriteMask_)
  1308. {
  1309. glStencilMask(writeMask);
  1310. stencilWriteMask_ = writeMask;
  1311. }
  1312. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1313. {
  1314. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1315. stencilPass_ = pass;
  1316. stencilFail_ = fail;
  1317. stencilZFail_ = zFail;
  1318. }
  1319. }
  1320. }
  1321. void Graphics::SetForceSM2(bool enable)
  1322. {
  1323. }
  1324. bool Graphics::IsInitialized() const
  1325. {
  1326. return impl_->window_ != 0;
  1327. }
  1328. void* Graphics::GetWindowHandle() const
  1329. {
  1330. return impl_->window_;
  1331. }
  1332. PODVector<IntVector2> Graphics::GetResolutions() const
  1333. {
  1334. PODVector<IntVector2> ret;
  1335. unsigned numModes = SDL_GetNumDisplayModes(0);
  1336. for (unsigned i = 0; i < numModes; ++i)
  1337. {
  1338. SDL_DisplayMode mode;
  1339. SDL_GetDisplayMode(0, i, &mode);
  1340. int width = mode.w;
  1341. int height = mode.h;
  1342. // Store mode if unique
  1343. bool unique = true;
  1344. for (unsigned j = 0; j < ret.Size(); ++i)
  1345. {
  1346. if (ret[j].x_ == width && ret[j].y_ == height)
  1347. {
  1348. unique = false;
  1349. break;
  1350. }
  1351. }
  1352. if (unique)
  1353. ret.Push(IntVector2(width, height));
  1354. }
  1355. return ret;
  1356. }
  1357. PODVector<int> Graphics::GetMultiSampleLevels() const
  1358. {
  1359. PODVector<int> ret;
  1360. // No multisampling always supported
  1361. ret.Push(1);
  1362. /// \todo Implement properly, if possible
  1363. return ret;
  1364. }
  1365. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1366. {
  1367. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1368. }
  1369. TextureUnit Graphics::GetTextureUnit(const String& name)
  1370. {
  1371. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1372. if (i != textureUnits_.End())
  1373. return i->second_;
  1374. else
  1375. return MAX_TEXTURE_UNITS;
  1376. }
  1377. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1378. {
  1379. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1380. {
  1381. if (i->second_ == unit)
  1382. return i->first_;
  1383. }
  1384. return noParameter;
  1385. }
  1386. Texture* Graphics::GetTexture(unsigned index) const
  1387. {
  1388. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1389. }
  1390. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1391. {
  1392. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1393. }
  1394. IntVector2 Graphics::GetRenderTargetDimensions() const
  1395. {
  1396. int width, height;
  1397. if (renderTargets_[0])
  1398. {
  1399. width = renderTargets_[0]->GetWidth();
  1400. height = renderTargets_[0]->GetHeight();
  1401. }
  1402. else if (depthStencil_)
  1403. {
  1404. width = depthStencil_->GetWidth();
  1405. height = depthStencil_->GetHeight();
  1406. }
  1407. else
  1408. {
  1409. width = width_;
  1410. height = height_;
  1411. }
  1412. return IntVector2(width, height);
  1413. }
  1414. void Graphics::AddGPUObject(GPUObject* object)
  1415. {
  1416. gpuObjects_.Push(object);
  1417. }
  1418. void Graphics::RemoveGPUObject(GPUObject* object)
  1419. {
  1420. gpuObjects_.Erase(gpuObjects_.Find(object));
  1421. }
  1422. void* Graphics::ReserveDiscardLockBuffer(unsigned size)
  1423. {
  1424. // First check for a free buffer that is large enough
  1425. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1426. {
  1427. if (!i->reserved_ && i->size_ >= size)
  1428. {
  1429. i->reserved_ = true;
  1430. return i->data_.Get();
  1431. }
  1432. }
  1433. // Then check if a free buffer can be resized
  1434. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1435. {
  1436. if (!i->reserved_)
  1437. {
  1438. i->data_ = new unsigned char[size];
  1439. i->size_ = size;
  1440. i->reserved_ = true;
  1441. return i->data_.Get();
  1442. }
  1443. }
  1444. // Finally allocate a new buffer
  1445. DiscardLockBuffer newBuffer;
  1446. newBuffer.data_ = new unsigned char[size];
  1447. newBuffer.size_ = size;
  1448. newBuffer.reserved_ = true;
  1449. discardLockBuffers_.Push(newBuffer);
  1450. return newBuffer.data_.Get();
  1451. }
  1452. void Graphics::FreeDiscardLockBuffer(void* buffer)
  1453. {
  1454. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1455. {
  1456. if (i->reserved_ && i->data_.Get() == buffer)
  1457. {
  1458. i->reserved_ = false;
  1459. return;
  1460. }
  1461. }
  1462. LOGWARNING("Reserved discard lock buffer " + ToStringHex((unsigned)buffer) + " not found");
  1463. }
  1464. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1465. {
  1466. if (!impl_->window_)
  1467. return;
  1468. CleanupFramebuffers(true);
  1469. depthTextures_.Clear();
  1470. if (clearGPUObjects)
  1471. {
  1472. // Shutting down: release all GPU objects that still exist
  1473. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1474. (*i)->Release();
  1475. gpuObjects_.Clear();
  1476. }
  1477. else
  1478. {
  1479. // We are not shutting down, but recreating the context: mark GPU objects lost
  1480. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1481. (*i)->OnDeviceLost();
  1482. }
  1483. // When the new context is initialized, it will have default state again
  1484. ResetCachedState();
  1485. ClearParameterSources();
  1486. {
  1487. MutexLock lock(GetStaticMutex());
  1488. if (impl_->context_)
  1489. {
  1490. SDL_GL_DeleteContext(impl_->context_);
  1491. impl_->context_ = 0;
  1492. }
  1493. if (closeWindow)
  1494. {
  1495. SDL_ShowCursor(SDL_TRUE);
  1496. SDL_DestroyWindow(impl_->window_);
  1497. impl_->window_ = 0;
  1498. }
  1499. }
  1500. }
  1501. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1502. {
  1503. if (!surface)
  1504. return;
  1505. // Flush pending FBO changes first if any
  1506. CommitFramebuffer();
  1507. unsigned currentFbo = impl_->boundFbo_;
  1508. // Go through all FBOs and clean up the surface from them
  1509. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();
  1510. ++i)
  1511. {
  1512. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1513. {
  1514. if (i->second_.colorAttachments_[j] == surface)
  1515. {
  1516. if (currentFbo != i->second_.fbo_)
  1517. {
  1518. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1519. currentFbo = i->second_.fbo_;
  1520. }
  1521. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1522. i->second_.colorAttachments_[j] = 0;
  1523. // Mark drawbuffer bits to need recalculation
  1524. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1525. }
  1526. }
  1527. if (i->second_.depthAttachment_ == surface)
  1528. {
  1529. if (currentFbo != i->second_.fbo_)
  1530. {
  1531. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1532. currentFbo = i->second_.fbo_;
  1533. }
  1534. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1535. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1536. i->second_.depthAttachment_ = 0;
  1537. }
  1538. }
  1539. // Restore previously bound FBO now if needed
  1540. if (currentFbo != impl_->boundFbo_)
  1541. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  1542. }
  1543. unsigned Graphics::GetAlphaFormat()
  1544. {
  1545. return GL_ALPHA;
  1546. }
  1547. unsigned Graphics::GetLuminanceFormat()
  1548. {
  1549. return GL_LUMINANCE;
  1550. }
  1551. unsigned Graphics::GetLuminanceAlphaFormat()
  1552. {
  1553. return GL_LUMINANCE_ALPHA;
  1554. }
  1555. unsigned Graphics::GetRGBFormat()
  1556. {
  1557. return GL_RGB;
  1558. }
  1559. unsigned Graphics::GetRGBAFormat()
  1560. {
  1561. return GL_RGBA;
  1562. }
  1563. unsigned Graphics::GetFloatFormat()
  1564. {
  1565. return GL_LUMINANCE32F_ARB;
  1566. }
  1567. unsigned Graphics::GetLinearDepthFormat()
  1568. {
  1569. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  1570. // manually if not using a readable hardware depth texture
  1571. return GL_RGBA;
  1572. }
  1573. unsigned Graphics::GetDepthStencilFormat()
  1574. {
  1575. return GL_DEPTH24_STENCIL8_EXT;
  1576. }
  1577. void Graphics::CheckFeatureSupport()
  1578. {
  1579. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  1580. lightPrepassSupport_ = false;
  1581. deferredSupport_ = false;
  1582. hardwareDepthSupport_ = false;
  1583. int numSupportedRTs = 1;
  1584. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  1585. // For now hardware depth texture is only tested for on NVIDIA hardware because of visual artifacts and slowdown on ATI
  1586. String vendorString = String((const char*)glGetString(GL_VENDOR)).ToUpper();
  1587. if (vendorString.Find("NVIDIA") != String::NPOS)
  1588. {
  1589. SharedPtr<Texture2D> depthTexture(new Texture2D(context_));
  1590. hardwareDepthSupport_ = true;
  1591. // Note: Texture2D::SetSize() requires hardwareDepthSupport_ == true to create a texture instead of a renderbuffer
  1592. depthTexture->SetSize(256, 256, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1593. SetDepthStencil(depthTexture);
  1594. // If hardware depth textures work, this means also light pre-pass is automatically supported
  1595. if (CheckFramebuffer())
  1596. {
  1597. lightPrepassSupport_ = true;
  1598. if (numSupportedRTs >= 3)
  1599. deferredSupport_ = true;
  1600. }
  1601. else
  1602. hardwareDepthSupport_ = false;
  1603. ResetDepthStencil();
  1604. }
  1605. if (!hardwareDepthSupport_)
  1606. {
  1607. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  1608. if (numSupportedRTs >= 2)
  1609. lightPrepassSupport_ = true;
  1610. if (numSupportedRTs >= 4)
  1611. deferredSupport_ = true;
  1612. }
  1613. }
  1614. void Graphics::CommitFramebuffer()
  1615. {
  1616. if (!impl_->fboDirty_)
  1617. return;
  1618. impl_->fboDirty_ = false;
  1619. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  1620. bool noFbo = !depthStencil_;
  1621. if (noFbo)
  1622. {
  1623. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1624. {
  1625. if (renderTargets_[i])
  1626. {
  1627. noFbo = false;
  1628. break;
  1629. }
  1630. }
  1631. }
  1632. if (noFbo)
  1633. {
  1634. if (impl_->boundFbo_)
  1635. {
  1636. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1637. impl_->boundFbo_ = 0;
  1638. }
  1639. return;
  1640. }
  1641. // Search for a new framebuffer based on format & size, or create new
  1642. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  1643. unsigned format = 0;
  1644. if (renderTargets_[0])
  1645. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  1646. else if (depthStencil_)
  1647. format = depthStencil_->GetParentTexture()->GetFormat();
  1648. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  1649. Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  1650. if (i == impl_->frameBuffers_.End())
  1651. {
  1652. FrameBufferObject newFbo;
  1653. glGenFramebuffersEXT(1, &newFbo.fbo_);
  1654. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  1655. }
  1656. i->second_.useTimer_.Reset();
  1657. if (impl_->boundFbo_ != i->second_.fbo_)
  1658. {
  1659. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1660. impl_->boundFbo_ = i->second_.fbo_;
  1661. }
  1662. // Setup readbuffers & drawbuffers if needed
  1663. if (i->second_.readBuffers_ != GL_NONE)
  1664. {
  1665. glReadBuffer(GL_NONE);
  1666. i->second_.readBuffers_ = GL_NONE;
  1667. }
  1668. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1669. unsigned newDrawBuffers = 0;
  1670. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1671. {
  1672. if (renderTargets_[i])
  1673. newDrawBuffers |= 1 << i;
  1674. }
  1675. if (newDrawBuffers != i->second_.drawBuffers_)
  1676. {
  1677. // Check for no color rendertargets (depth rendering only)
  1678. if (!newDrawBuffers)
  1679. glDrawBuffer(GL_NONE);
  1680. else
  1681. {
  1682. int drawBufferIds[4];
  1683. unsigned drawBufferCount = 0;
  1684. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1685. {
  1686. if (renderTargets_[i])
  1687. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1688. }
  1689. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1690. }
  1691. i->second_.drawBuffers_ = newDrawBuffers;
  1692. }
  1693. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1694. {
  1695. if (renderTargets_[j])
  1696. {
  1697. Texture* texture = renderTargets_[j]->GetParentTexture();
  1698. // If texture's parameters are dirty, update before attaching
  1699. if (texture->GetParametersDirty())
  1700. {
  1701. SetTextureForUpdate(texture);
  1702. texture->UpdateParameters();
  1703. SetTexture(0, 0);
  1704. }
  1705. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  1706. {
  1707. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  1708. texture->GetGPUObject(), 0);
  1709. i->second_.colorAttachments_[j] = renderTargets_[j];
  1710. }
  1711. }
  1712. else
  1713. {
  1714. if (i->second_.colorAttachments_[j])
  1715. {
  1716. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1717. i->second_.colorAttachments_[j] = 0;
  1718. }
  1719. }
  1720. }
  1721. if (depthStencil_)
  1722. {
  1723. // Bind either a renderbuffer or a depth texture, depending on what is available
  1724. Texture* texture = depthStencil_->GetParentTexture();
  1725. bool hasStencil = texture->GetFormat() == GetDepthStencilFormat();
  1726. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  1727. if (!renderBufferID)
  1728. {
  1729. // If texture's parameters are dirty, update before attaching
  1730. if (texture->GetParametersDirty())
  1731. {
  1732. SetTextureForUpdate(texture);
  1733. texture->UpdateParameters();
  1734. SetTexture(0, 0);
  1735. }
  1736. if (i->second_.depthAttachment_ != depthStencil_)
  1737. {
  1738. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1739. if (hasStencil)
  1740. {
  1741. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  1742. texture->GetGPUObject(), 0);
  1743. }
  1744. else
  1745. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1746. i->second_.depthAttachment_ = depthStencil_;
  1747. }
  1748. }
  1749. else
  1750. {
  1751. if (i->second_.depthAttachment_ != depthStencil_)
  1752. {
  1753. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1754. if (hasStencil)
  1755. {
  1756. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  1757. renderBufferID);
  1758. }
  1759. else
  1760. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1761. i->second_.depthAttachment_ = depthStencil_;
  1762. }
  1763. }
  1764. impl_->depthBits_ = texture->GetDepthBits();
  1765. }
  1766. else
  1767. {
  1768. if (i->second_.depthAttachment_)
  1769. {
  1770. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1771. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1772. i->second_.depthAttachment_ = 0;
  1773. impl_->depthBits_ = impl_->windowDepthBits_;
  1774. }
  1775. }
  1776. }
  1777. bool Graphics::CheckFramebuffer()
  1778. {
  1779. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  1780. }
  1781. void Graphics::CleanupFramebuffers(bool deleteAll)
  1782. {
  1783. if (deleteAll && impl_->boundFbo_)
  1784. {
  1785. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1786. impl_->boundFbo_ = 0;
  1787. }
  1788. for (Map<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin(); i != impl_->frameBuffers_.End();)
  1789. {
  1790. Map<unsigned long long, FrameBufferObject>::Iterator current = i++;
  1791. if (deleteAll || (current->second_.fbo_ != impl_->boundFbo_ && current->second_.useTimer_.GetMSec(false) > MAX_FRAMEBUFFER_AGE))
  1792. {
  1793. glDeleteFramebuffersEXT(1, &current->second_.fbo_);
  1794. impl_->frameBuffers_.Erase(current);
  1795. }
  1796. }
  1797. }
  1798. void Graphics::ResetCachedState()
  1799. {
  1800. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1801. {
  1802. vertexBuffers_[i] = 0;
  1803. elementMasks_[i] = 0;
  1804. }
  1805. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1806. {
  1807. textures_[i] = 0;
  1808. textureTypes_[i] = 0;
  1809. }
  1810. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1811. renderTargets_[i] = 0;
  1812. depthStencil_ = 0;
  1813. viewTexture_ = 0;
  1814. viewport_ = IntRect(0, 0, 0, 0);
  1815. indexBuffer_ = 0;
  1816. vertexShader_ = 0;
  1817. pixelShader_ = 0;
  1818. shaderProgram_ = 0;
  1819. blendMode_ = BLEND_REPLACE;
  1820. alphaTest_ = false;
  1821. alphaTestMode_ = CMP_ALWAYS;
  1822. alphaRef_ = 0.0f;
  1823. textureAnisotropy_ = 1;
  1824. colorWrite_ = true;
  1825. cullMode_ = CULL_NONE;
  1826. constantDepthBias_ = 0.0f;
  1827. slopeScaledDepthBias_ = 0.0f;
  1828. depthTestMode_ = CMP_ALWAYS;
  1829. depthWrite_ = true;
  1830. fillMode_ = FILL_SOLID;
  1831. scissorTest_ = false;
  1832. scissorRect_ = IntRect::ZERO;
  1833. stencilTest_ = false;
  1834. stencilTestMode_ = CMP_ALWAYS;
  1835. stencilPass_ = OP_KEEP;
  1836. stencilFail_ = OP_KEEP;
  1837. stencilZFail_ = OP_KEEP;
  1838. stencilRef_ = 0;
  1839. stencilCompareMask_ = M_MAX_UNSIGNED;
  1840. stencilWriteMask_ = M_MAX_UNSIGNED;
  1841. impl_->activeTexture_ = 0;
  1842. impl_->enabledAttributes_ = 0;
  1843. }
  1844. void Graphics::SetTextureUnitMappings()
  1845. {
  1846. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1847. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1848. textureUnits_["NormalMap"] = TU_NORMAL;
  1849. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1850. textureUnits_["DetailMap"] = TU_DETAIL;
  1851. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1852. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1853. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1854. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1855. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1856. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1857. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1858. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1859. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  1860. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1861. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1862. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1863. }
  1864. void RegisterGraphicsLibrary(Context* context)
  1865. {
  1866. Animation::RegisterObject(context);
  1867. Material::RegisterObject(context);
  1868. Model::RegisterObject(context);
  1869. Shader::RegisterObject(context);
  1870. Technique::RegisterObject(context);
  1871. Texture2D::RegisterObject(context);
  1872. TextureCube::RegisterObject(context);
  1873. Camera::RegisterObject(context);
  1874. Drawable::RegisterObject(context);
  1875. Light::RegisterObject(context);
  1876. StaticModel::RegisterObject(context);
  1877. Skybox::RegisterObject(context);
  1878. AnimatedModel::RegisterObject(context);
  1879. AnimationController::RegisterObject(context);
  1880. BillboardSet::RegisterObject(context);
  1881. ParticleEmitter::RegisterObject(context);
  1882. DebugRenderer::RegisterObject(context);
  1883. Octree::RegisterObject(context);
  1884. Zone::RegisterObject(context);
  1885. }