OGLGraphics.cpp 64 KB

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