OGLGraphics.cpp 64 KB

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