CmGLFBORenderTexture.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  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. */
  24. #include "CmGLFBORenderTexture.h"
  25. #include "CmGLPixelFormat.h"
  26. #include "OgreStringConverter.h"
  27. #include "CmGLHardwarePixelBuffer.h"
  28. #include "CmGLFBOMultiRenderTarget.h"
  29. namespace CamelotEngine {
  30. //-----------------------------------------------------------------------------
  31. GLFBORenderTexture::GLFBORenderTexture(GLFBOManager *manager, const String &name,
  32. const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa):
  33. GLRenderTexture(name, target, writeGamma, fsaa),
  34. mFB(manager, fsaa)
  35. {
  36. // Bind target to surface 0 and initialise
  37. mFB.bindSurface(0, target);
  38. // Get attributes
  39. mWidth = mFB.getWidth();
  40. mHeight = mFB.getHeight();
  41. }
  42. void GLFBORenderTexture::getCustomAttribute(const String& name, void* pData)
  43. {
  44. if(name=="FBO")
  45. {
  46. *static_cast<GLFrameBufferObject **>(pData) = &mFB;
  47. }
  48. else if (name == "GL_FBOID")
  49. {
  50. *static_cast<GLuint*>(pData) = mFB.getGLFBOID();
  51. }
  52. else if (name == "GL_MULTISAMPLEFBOID")
  53. {
  54. *static_cast<GLuint*>(pData) = mFB.getGLMultisampleFBOID();
  55. }
  56. }
  57. void GLFBORenderTexture::swapBuffers(bool waitForVSync)
  58. {
  59. mFB.swapBuffers();
  60. }
  61. /// Size of probe texture
  62. #define PROBE_SIZE 16
  63. /// Stencil and depth formats to be tried
  64. static const GLenum stencilFormats[] =
  65. {
  66. GL_NONE, // No stencil
  67. GL_STENCIL_INDEX1_EXT,
  68. GL_STENCIL_INDEX4_EXT,
  69. GL_STENCIL_INDEX8_EXT,
  70. GL_STENCIL_INDEX16_EXT
  71. };
  72. static const size_t stencilBits[] =
  73. {
  74. 0, 1, 4, 8, 16
  75. };
  76. #define STENCILFORMAT_COUNT (sizeof(stencilFormats)/sizeof(GLenum))
  77. static const GLenum depthFormats[] =
  78. {
  79. GL_NONE,
  80. GL_DEPTH_COMPONENT16,
  81. GL_DEPTH_COMPONENT24, // Prefer 24 bit depth
  82. GL_DEPTH_COMPONENT32,
  83. GL_DEPTH24_STENCIL8_EXT // packed depth / stencil
  84. };
  85. static const size_t depthBits[] =
  86. {
  87. 0,16,24,32,24
  88. };
  89. #define DEPTHFORMAT_COUNT (sizeof(depthFormats)/sizeof(GLenum))
  90. GLFBOManager::GLFBOManager(bool atimode):
  91. mATIMode(atimode)
  92. {
  93. detectFBOFormats();
  94. glGenFramebuffersEXT(1, &mTempFBO);
  95. }
  96. GLFBOManager::~GLFBOManager()
  97. {
  98. if(!mRenderBufferMap.empty())
  99. {
  100. // TODO LOG PORT - Log this somewhere
  101. //LogManager::getSingleton().logMessage("GL: Warning! GLFBOManager destructor called, but not all renderbuffers were released.");
  102. }
  103. glDeleteFramebuffersEXT(1, &mTempFBO);
  104. }
  105. /** Try a certain FBO format, and return the status. Also sets mDepthRB and mStencilRB.
  106. @returns true if this combo is supported
  107. false if this combo is not supported
  108. */
  109. GLuint GLFBOManager::_tryFormat(GLenum depthFormat, GLenum stencilFormat)
  110. {
  111. GLuint status, depthRB = 0, stencilRB = 0;
  112. bool failed = false; // flag on GL errors
  113. if(depthFormat != GL_NONE)
  114. {
  115. /// Generate depth renderbuffer
  116. glGenRenderbuffersEXT(1, &depthRB);
  117. /// Bind it to FBO
  118. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthRB);
  119. /// Allocate storage for depth buffer
  120. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, depthFormat,
  121. PROBE_SIZE, PROBE_SIZE);
  122. /// Attach depth
  123. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
  124. GL_RENDERBUFFER_EXT, depthRB);
  125. }
  126. if(stencilFormat != GL_NONE)
  127. {
  128. /// Generate stencil renderbuffer
  129. glGenRenderbuffersEXT(1, &stencilRB);
  130. /// Bind it to FBO
  131. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, stencilRB);
  132. glGetError(); // NV hack
  133. /// Allocate storage for stencil buffer
  134. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, stencilFormat,
  135. PROBE_SIZE, PROBE_SIZE);
  136. if(glGetError() != GL_NO_ERROR) // NV hack
  137. failed = true;
  138. /// Attach stencil
  139. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
  140. GL_RENDERBUFFER_EXT, stencilRB);
  141. if(glGetError() != GL_NO_ERROR) // NV hack
  142. failed = true;
  143. }
  144. status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  145. /// If status is negative, clean up
  146. // Detach and destroy
  147. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
  148. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
  149. if (depthRB)
  150. glDeleteRenderbuffersEXT(1, &depthRB);
  151. if (stencilRB)
  152. glDeleteRenderbuffersEXT(1, &stencilRB);
  153. return status == GL_FRAMEBUFFER_COMPLETE_EXT && !failed;
  154. }
  155. /** Try a certain packed depth/stencil format, and return the status.
  156. @returns true if this combo is supported
  157. false if this combo is not supported
  158. */
  159. bool GLFBOManager::_tryPackedFormat(GLenum packedFormat)
  160. {
  161. GLuint packedRB = 0;
  162. bool failed = false; // flag on GL errors
  163. /// Generate renderbuffer
  164. glGenRenderbuffersEXT(1, &packedRB);
  165. /// Bind it to FBO
  166. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, packedRB);
  167. /// Allocate storage for buffer
  168. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, packedFormat, PROBE_SIZE, PROBE_SIZE);
  169. glGetError(); // NV hack
  170. /// Attach depth
  171. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
  172. GL_RENDERBUFFER_EXT, packedRB);
  173. if(glGetError() != GL_NO_ERROR) // NV hack
  174. failed = true;
  175. /// Attach stencil
  176. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
  177. GL_RENDERBUFFER_EXT, packedRB);
  178. if(glGetError() != GL_NO_ERROR) // NV hack
  179. failed = true;
  180. GLuint status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  181. /// Detach and destroy
  182. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
  183. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
  184. glDeleteRenderbuffersEXT(1, &packedRB);
  185. return status == GL_FRAMEBUFFER_COMPLETE_EXT && !failed;
  186. }
  187. /** Detect which internal formats are allowed as RTT
  188. Also detect what combinations of stencil and depth are allowed with this internal
  189. format.
  190. */
  191. void GLFBOManager::detectFBOFormats()
  192. {
  193. // Try all formats, and report which ones work as target
  194. GLuint fb = 0, tid = 0;
  195. GLint old_drawbuffer = 0, old_readbuffer = 0;
  196. GLenum target = GL_TEXTURE_2D;
  197. glGetIntegerv (GL_DRAW_BUFFER, &old_drawbuffer);
  198. glGetIntegerv (GL_READ_BUFFER, &old_readbuffer);
  199. for(size_t x=0; x<PF_COUNT; ++x)
  200. {
  201. mProps[x].valid = false;
  202. // Fetch GL format token
  203. GLenum fmt = GLPixelUtil::getGLInternalFormat((PixelFormat)x);
  204. if(fmt == GL_NONE && x!=0)
  205. continue;
  206. // No test for compressed formats
  207. if(PixelUtil::isCompressed((PixelFormat)x))
  208. continue;
  209. // Buggy ATI cards *crash* on non-RGB(A) formats
  210. int depths[4];
  211. PixelUtil::getBitDepths((PixelFormat)x, depths);
  212. if(fmt!=GL_NONE && mATIMode && (!depths[0] || !depths[1] || !depths[2]))
  213. continue;
  214. // Create and attach framebuffer
  215. glGenFramebuffersEXT(1, &fb);
  216. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
  217. if (fmt!=GL_NONE)
  218. {
  219. // Create and attach texture
  220. glGenTextures(1, &tid);
  221. glBindTexture(target, tid);
  222. // Set some default parameters so it won't fail on NVidia cards
  223. if (GLEW_VERSION_1_2)
  224. glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 0);
  225. glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  226. glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  227. glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  228. glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  229. glTexImage2D(target, 0, fmt, PROBE_SIZE, PROBE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  230. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
  231. target, tid, 0);
  232. }
  233. else
  234. {
  235. // Draw to nowhere -- stencil/depth only
  236. glDrawBuffer(GL_NONE);
  237. glReadBuffer(GL_NONE);
  238. }
  239. // Check status
  240. GLuint status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  241. // Ignore status in case of fmt==GL_NONE, because no implementation will accept
  242. // a buffer without *any* attachment. Buffers with only stencil and depth attachment
  243. // might still be supported, so we must continue probing.
  244. if(fmt == GL_NONE || status == GL_FRAMEBUFFER_COMPLETE_EXT)
  245. {
  246. mProps[x].valid = true;
  247. StringUtil::StrStreamType str;
  248. str << "FBO " << PixelUtil::getFormatName((PixelFormat)x)
  249. << " depth/stencil support: ";
  250. // For each depth/stencil formats
  251. for (size_t depth = 0; depth < DEPTHFORMAT_COUNT; ++depth)
  252. {
  253. if (depthFormats[depth] != GL_DEPTH24_STENCIL8_EXT)
  254. {
  255. // General depth/stencil combination
  256. for (size_t stencil = 0; stencil < STENCILFORMAT_COUNT; ++stencil)
  257. {
  258. //StringUtil::StrStreamType l;
  259. //l << "Trying " << PixelUtil::getFormatName((PixelFormat)x)
  260. // << " D" << depthBits[depth]
  261. // << "S" << stencilBits[stencil];
  262. //LogManager::getSingleton().logMessage(l.str());
  263. if (_tryFormat(depthFormats[depth], stencilFormats[stencil]))
  264. {
  265. /// Add mode to allowed modes
  266. str << "D" << depthBits[depth] << "S" << stencilBits[stencil] << " ";
  267. FormatProperties::Mode mode;
  268. mode.depth = depth;
  269. mode.stencil = stencil;
  270. mProps[x].modes.push_back(mode);
  271. }
  272. }
  273. }
  274. else
  275. {
  276. // Packed depth/stencil format
  277. // #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
  278. // It now seems as if this workaround now *breaks* nvidia cards on Linux with the 169.12 drivers on Linux
  279. #if 0
  280. // Only query packed depth/stencil formats for 32-bit
  281. // non-floating point formats (ie not R32!)
  282. // Linux nVidia driver segfaults if you query others
  283. if (PixelUtil::getNumElemBits((PixelFormat)x) != 32 ||
  284. PixelUtil::isFloatingPoint((PixelFormat)x))
  285. {
  286. continue;
  287. }
  288. #endif
  289. if (_tryPackedFormat(depthFormats[depth]))
  290. {
  291. /// Add mode to allowed modes
  292. str << "Packed-D" << depthBits[depth] << "S" << 8 << " ";
  293. FormatProperties::Mode mode;
  294. mode.depth = depth;
  295. mode.stencil = 0; // unuse
  296. mProps[x].modes.push_back(mode);
  297. }
  298. }
  299. }
  300. }
  301. // Delete texture and framebuffer
  302. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  303. glDeleteFramebuffersEXT(1, &fb);
  304. // Workaround for NVIDIA / Linux 169.21 driver problem
  305. // see http://www.ogre3d.org/phpBB2/viewtopic.php?t=38037&start=25
  306. glFinish();
  307. if (fmt!=GL_NONE)
  308. glDeleteTextures(1, &tid);
  309. }
  310. // It seems a bug in nVidia driver: glBindFramebufferEXT should restore
  311. // draw and read buffers, but in some unclear circumstances it won't.
  312. glDrawBuffer(old_drawbuffer);
  313. glReadBuffer(old_readbuffer);
  314. String fmtstring = "";
  315. for(size_t x=0; x<PF_COUNT; ++x)
  316. {
  317. if(mProps[x].valid)
  318. fmtstring += PixelUtil::getFormatName((PixelFormat)x)+" ";
  319. }
  320. }
  321. void GLFBOManager::getBestDepthStencil(GLenum internalFormat, GLenum *depthFormat, GLenum *stencilFormat)
  322. {
  323. const FormatProperties &props = mProps[internalFormat];
  324. /// Decide what stencil and depth formats to use
  325. /// [best supported for internal format]
  326. size_t bestmode=0;
  327. int bestscore=-1;
  328. for(size_t mode=0; mode<props.modes.size(); mode++)
  329. {
  330. #if 0
  331. /// Always prefer D24S8
  332. if(stencilBits[props.modes[mode].stencil]==8 &&
  333. depthBits[props.modes[mode].depth]==24)
  334. {
  335. bestmode = mode;
  336. break;
  337. }
  338. #endif
  339. int desirability = 0;
  340. /// Find most desirable mode
  341. /// desirability == 0 if no depth, no stencil
  342. /// desirability == 1000...2000 if no depth, stencil
  343. /// desirability == 2000...3000 if depth, no stencil
  344. /// desirability == 3000+ if depth and stencil
  345. /// beyond this, the total numer of bits (stencil+depth) is maximised
  346. if(props.modes[mode].stencil)
  347. desirability += 1000;
  348. if(props.modes[mode].depth)
  349. desirability += 2000;
  350. if(depthBits[props.modes[mode].depth]==24) // Prefer 24 bit for now
  351. desirability += 500;
  352. if(depthFormats[props.modes[mode].depth]==GL_DEPTH24_STENCIL8_EXT) // Prefer 24/8 packed
  353. desirability += 5000;
  354. desirability += stencilBits[props.modes[mode].stencil] + depthBits[props.modes[mode].depth];
  355. if(desirability>bestscore)
  356. {
  357. bestscore = desirability;
  358. bestmode = mode;
  359. }
  360. }
  361. *depthFormat = depthFormats[props.modes[bestmode].depth];
  362. *stencilFormat = stencilFormats[props.modes[bestmode].stencil];
  363. }
  364. GLFBORenderTexture *GLFBOManager::createRenderTexture(const String &name,
  365. const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa)
  366. {
  367. GLFBORenderTexture *retval = new GLFBORenderTexture(this, name, target, writeGamma, fsaa);
  368. return retval;
  369. }
  370. MultiRenderTarget *GLFBOManager::createMultiRenderTarget(const String & name)
  371. {
  372. return new GLFBOMultiRenderTarget(this, name);
  373. }
  374. void GLFBOManager::bind(RenderTarget *target)
  375. {
  376. /// Check if the render target is in the rendertarget->FBO map
  377. GLFrameBufferObject *fbo = 0;
  378. target->getCustomAttribute("FBO", &fbo);
  379. if(fbo)
  380. fbo->bind();
  381. else
  382. // Old style context (window/pbuffer) or copying render texture
  383. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  384. }
  385. GLSurfaceDesc GLFBOManager::requestRenderBuffer(GLenum format, size_t width, size_t height, UINT32 fsaa)
  386. {
  387. GLSurfaceDesc retval;
  388. retval.buffer = 0; // Return 0 buffer if GL_NONE is requested
  389. if(format != GL_NONE)
  390. {
  391. RBFormat key(format, width, height, fsaa);
  392. RenderBufferMap::iterator it = mRenderBufferMap.find(key);
  393. if(it != mRenderBufferMap.end())
  394. {
  395. retval.buffer = it->second.buffer;
  396. retval.zoffset = 0;
  397. retval.numSamples = fsaa;
  398. // Increase refcount
  399. ++it->second.refcount;
  400. }
  401. else
  402. {
  403. // New one
  404. GLRenderBuffer *rb = new GLRenderBuffer(format, width, height, fsaa);
  405. mRenderBufferMap[key] = RBRef(rb);
  406. retval.buffer = rb;
  407. retval.zoffset = 0;
  408. retval.numSamples = fsaa;
  409. }
  410. }
  411. //std::cerr << "Requested renderbuffer with format " << std::hex << format << std::dec << " of " << width << "x" << height << " :" << retval.buffer << std::endl;
  412. return retval;
  413. }
  414. //-----------------------------------------------------------------------
  415. void GLFBOManager::requestRenderBuffer(const GLSurfaceDesc &surface)
  416. {
  417. if(surface.buffer == 0)
  418. return;
  419. RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples);
  420. RenderBufferMap::iterator it = mRenderBufferMap.find(key);
  421. assert(it != mRenderBufferMap.end());
  422. if (it != mRenderBufferMap.end()) // Just in case
  423. {
  424. assert(it->second.buffer == surface.buffer);
  425. // Increase refcount
  426. ++it->second.refcount;
  427. }
  428. }
  429. //-----------------------------------------------------------------------
  430. void GLFBOManager::releaseRenderBuffer(const GLSurfaceDesc &surface)
  431. {
  432. if(surface.buffer == 0)
  433. return;
  434. RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples);
  435. RenderBufferMap::iterator it = mRenderBufferMap.find(key);
  436. if(it != mRenderBufferMap.end())
  437. {
  438. // Decrease refcount
  439. --it->second.refcount;
  440. if(it->second.refcount==0)
  441. {
  442. // If refcount reaches zero, delete buffer and remove from map
  443. delete it->second.buffer;
  444. mRenderBufferMap.erase(it);
  445. //std::cerr << "Destroyed renderbuffer of format " << std::hex << key.format << std::dec
  446. // << " of " << key.width << "x" << key.height << std::endl;
  447. }
  448. }
  449. }
  450. }