CmGLHardwarePixelBuffer.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 "CmGLHardwarePixelBuffer.h"
  25. #include "CmGLTexture.h"
  26. #include "CmGLSupport.h"
  27. #include "CmGLPixelFormat.h"
  28. #include "CmException.h"
  29. #include "CmBitwise.h"
  30. #include "CmGLFBORenderTexture.h"
  31. #include "CmRenderSystemManager.h"
  32. namespace CamelotEngine {
  33. //-----------------------------------------------------------------------------
  34. GLHardwarePixelBuffer::GLHardwarePixelBuffer(size_t inWidth, size_t inHeight, size_t inDepth,
  35. PixelFormat inFormat,
  36. HardwareBuffer::Usage usage):
  37. HardwarePixelBuffer(inWidth, inHeight, inDepth, inFormat, usage, false, false),
  38. mBuffer(inWidth, inHeight, inDepth, inFormat),
  39. mGLInternalFormat(GL_NONE)
  40. {
  41. mCurrentLockOptions = (LockOptions)0;
  42. }
  43. //-----------------------------------------------------------------------------
  44. GLHardwarePixelBuffer::~GLHardwarePixelBuffer()
  45. {
  46. // Force free buffer
  47. delete [] (UINT8*)mBuffer.data;
  48. }
  49. //-----------------------------------------------------------------------------
  50. void GLHardwarePixelBuffer::allocateBuffer()
  51. {
  52. if(mBuffer.data)
  53. // Already allocated
  54. return;
  55. mBuffer.data = new UINT8[mSizeInBytes];
  56. // TODO: use PBO if we're HBU_DYNAMIC
  57. }
  58. //-----------------------------------------------------------------------------
  59. void GLHardwarePixelBuffer::freeBuffer()
  60. {
  61. // Free buffer if we're STATIC to save memory
  62. if(mUsage & HBU_STATIC)
  63. {
  64. delete [] (UINT8*)mBuffer.data;
  65. mBuffer.data = 0;
  66. }
  67. }
  68. //-----------------------------------------------------------------------------
  69. PixelData GLHardwarePixelBuffer::lockImpl(const Box lockBox, LockOptions options)
  70. {
  71. allocateBuffer();
  72. if(options != HardwareBuffer::HBL_DISCARD)
  73. {
  74. // Download the old contents of the texture
  75. download(mBuffer);
  76. }
  77. mCurrentLockOptions = options;
  78. mLockedBox = lockBox;
  79. return mBuffer.getSubVolume(lockBox);
  80. }
  81. //-----------------------------------------------------------------------------
  82. void GLHardwarePixelBuffer::unlockImpl(void)
  83. {
  84. if (mCurrentLockOptions != HardwareBuffer::HBL_READ_ONLY)
  85. {
  86. // From buffer to card, only upload if was locked for writing
  87. upload(mCurrentLock, mLockedBox);
  88. }
  89. freeBuffer();
  90. }
  91. //-----------------------------------------------------------------------------
  92. void GLHardwarePixelBuffer::blitFromMemory(const PixelData &src, const Box &dstBox)
  93. {
  94. if(!mBuffer.contains(dstBox))
  95. CM_EXCEPT(InvalidParametersException, "destination box out of range");
  96. PixelData scaled;
  97. if(src.getWidth() != dstBox.getWidth() ||
  98. src.getHeight() != dstBox.getHeight() ||
  99. src.getDepth() != dstBox.getDepth())
  100. {
  101. // Scale to destination size. Use DevIL and not iluScale because ILU screws up for
  102. // floating point textures and cannot cope with 3D images.
  103. // This also does pixel format conversion if needed
  104. allocateBuffer();
  105. scaled = mBuffer.getSubVolume(dstBox);
  106. PixelUtil::scale(src, scaled, PixelUtil::FILTER_BILINEAR);
  107. }
  108. else if(GLPixelUtil::getGLOriginFormat(src.format) == 0)
  109. {
  110. // Extents match, but format is not accepted as valid source format for GL
  111. // do conversion in temporary buffer
  112. allocateBuffer();
  113. scaled = mBuffer.getSubVolume(dstBox);
  114. PixelUtil::bulkPixelConversion(src, scaled);
  115. }
  116. else
  117. {
  118. allocateBuffer();
  119. // No scaling or conversion needed
  120. scaled = src;
  121. }
  122. upload(scaled, dstBox);
  123. freeBuffer();
  124. }
  125. //-----------------------------------------------------------------------------
  126. void GLHardwarePixelBuffer::blitToMemory(const Box &srcBox, const PixelData &dst)
  127. {
  128. if(!mBuffer.contains(srcBox))
  129. CM_EXCEPT(InvalidParametersException, "source box out of range");
  130. if(srcBox.left == 0 && srcBox.right == getWidth() &&
  131. srcBox.top == 0 && srcBox.bottom == getHeight() &&
  132. srcBox.front == 0 && srcBox.back == getDepth() &&
  133. dst.getWidth() == getWidth() &&
  134. dst.getHeight() == getHeight() &&
  135. dst.getDepth() == getDepth() &&
  136. GLPixelUtil::getGLOriginFormat(dst.format) != 0)
  137. {
  138. // The direct case: the user wants the entire texture in a format supported by GL
  139. // so we don't need an intermediate buffer
  140. download(dst);
  141. }
  142. else
  143. {
  144. // Use buffer for intermediate copy
  145. allocateBuffer();
  146. // Download entire buffer
  147. download(mBuffer);
  148. if(srcBox.getWidth() != dst.getWidth() ||
  149. srcBox.getHeight() != dst.getHeight() ||
  150. srcBox.getDepth() != dst.getDepth())
  151. {
  152. // We need scaling
  153. PixelUtil::scale(mBuffer.getSubVolume(srcBox), dst, PixelUtil::FILTER_BILINEAR);
  154. }
  155. else
  156. {
  157. // Just copy the bit that we need
  158. PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst);
  159. }
  160. freeBuffer();
  161. }
  162. }
  163. //-----------------------------------------------------------------------------
  164. void GLHardwarePixelBuffer::upload(const PixelData &data, const Box &dest)
  165. {
  166. CM_EXCEPT(RenderingAPIException,
  167. "Upload not possible for this pixelbuffer type");
  168. }
  169. //-----------------------------------------------------------------------------
  170. void GLHardwarePixelBuffer::download(const PixelData &data)
  171. {
  172. CM_EXCEPT(RenderingAPIException, "Download not possible for this pixelbuffer type");
  173. }
  174. //-----------------------------------------------------------------------------
  175. void GLHardwarePixelBuffer::bindToFramebuffer(GLenum attachment, size_t zoffset)
  176. {
  177. CM_EXCEPT(RenderingAPIException, "Framebuffer bind not possible for this pixelbuffer type");
  178. }
  179. //********* GLTextureBuffer
  180. GLTextureBuffer::GLTextureBuffer(const String &baseName, GLenum target, GLuint id,
  181. GLint face, GLint level, Usage usage, bool crappyCard,
  182. bool writeGamma, UINT32 fsaa):
  183. GLHardwarePixelBuffer(0, 0, 0, PF_UNKNOWN, usage),
  184. mTarget(target), mFaceTarget(0), mTextureID(id), mFace(face), mLevel(level),
  185. mSoftwareMipmap(crappyCard), mSliceTRT(0)
  186. {
  187. // devise mWidth, mHeight and mDepth and mFormat
  188. GLint value = 0;
  189. glBindTexture( mTarget, mTextureID );
  190. // Get face identifier
  191. mFaceTarget = mTarget;
  192. if(mTarget == GL_TEXTURE_CUBE_MAP)
  193. mFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
  194. // Get width
  195. glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_WIDTH, &value);
  196. mWidth = value;
  197. // Get height
  198. if(target == GL_TEXTURE_1D)
  199. value = 1; // Height always 1 for 1D textures
  200. else
  201. glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_HEIGHT, &value);
  202. mHeight = value;
  203. // Get depth
  204. if(target != GL_TEXTURE_3D)
  205. value = 1; // Depth always 1 for non-3D textures
  206. else
  207. glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_DEPTH, &value);
  208. mDepth = value;
  209. // Get format
  210. glGetTexLevelParameteriv(mFaceTarget, level, GL_TEXTURE_INTERNAL_FORMAT, &value);
  211. mGLInternalFormat = value;
  212. mFormat = GLPixelUtil::getClosestOGREFormat(value);
  213. // Default
  214. mRowPitch = mWidth;
  215. mSlicePitch = mHeight*mWidth;
  216. mSizeInBytes = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat);
  217. // Log a message
  218. /*
  219. std::stringstream str;
  220. str << "GLHardwarePixelBuffer constructed for texture " << mTextureID
  221. << " face " << mFace << " level " << mLevel << ": "
  222. << "width=" << mWidth << " height="<< mHeight << " depth=" << mDepth
  223. << "format=" << PixelUtil::getFormatName(mFormat) << "(internal 0x"
  224. << std::hex << value << ")";
  225. LogManager::getSingleton().logMessage(
  226. LML_NORMAL, str.str());
  227. */
  228. // Set up pixel box
  229. mBuffer = PixelData(mWidth, mHeight, mDepth, mFormat);
  230. if(mWidth==0 || mHeight==0 || mDepth==0)
  231. /// We are invalid, do not allocate a buffer
  232. return;
  233. // Allocate buffer
  234. //if(mUsage & HBU_STATIC)
  235. // allocateBuffer();
  236. // Is this a render target?
  237. if(mUsage & TU_RENDERTARGET)
  238. {
  239. // Create render target for each slice
  240. mSliceTRT.reserve(mDepth);
  241. for(size_t zoffset=0; zoffset<mDepth; ++zoffset)
  242. {
  243. String name;
  244. name = "rtt/" + toString((size_t)this) + "/" + baseName;
  245. GLSurfaceDesc surface;
  246. surface.buffer = this;
  247. surface.zoffset = zoffset;
  248. RenderTexture *trt = GLRTTManager::instance().createRenderTexture(name, surface, writeGamma, fsaa);
  249. mSliceTRT.push_back(trt);
  250. CamelotEngine::RenderSystemManager::getActive()->attachRenderTarget_internal(*mSliceTRT[zoffset]);
  251. }
  252. }
  253. }
  254. GLTextureBuffer::~GLTextureBuffer()
  255. {
  256. if(mUsage & TU_RENDERTARGET)
  257. {
  258. // Delete all render targets that are not yet deleted via _clearSliceRTT because the rendertarget
  259. // was deleted by the user.
  260. for (SliceTRT::const_iterator it = mSliceTRT.begin(); it != mSliceTRT.end(); ++it)
  261. {
  262. CamelotEngine::RenderSystemManager::getActive()->destroyRenderTarget_internal((*it)->getName());
  263. }
  264. }
  265. }
  266. //-----------------------------------------------------------------------------
  267. void GLTextureBuffer::upload(const PixelData &data, const Box &dest)
  268. {
  269. glBindTexture( mTarget, mTextureID );
  270. if(PixelUtil::isCompressed(data.format))
  271. {
  272. if(data.format != mFormat || !data.isConsecutive())
  273. CM_EXCEPT(InvalidParametersException,
  274. "Compressed images must be consecutive, in the source format");
  275. GLenum format = GLPixelUtil::getClosestGLInternalFormat(mFormat);
  276. // Data must be consecutive and at beginning of buffer as PixelStorei not allowed
  277. // for compressed formats
  278. switch(mTarget) {
  279. case GL_TEXTURE_1D:
  280. // some systems (e.g. old Apple) don't like compressed subimage calls
  281. // so prefer non-sub versions
  282. if (dest.left == 0)
  283. {
  284. glCompressedTexImage1DARB(GL_TEXTURE_1D, mLevel,
  285. format,
  286. dest.getWidth(),
  287. 0,
  288. data.getConsecutiveSize(),
  289. data.data);
  290. }
  291. else
  292. {
  293. glCompressedTexSubImage1DARB(GL_TEXTURE_1D, mLevel,
  294. dest.left,
  295. dest.getWidth(),
  296. format, data.getConsecutiveSize(),
  297. data.data);
  298. }
  299. break;
  300. case GL_TEXTURE_2D:
  301. case GL_TEXTURE_CUBE_MAP:
  302. // some systems (e.g. old Apple) don't like compressed subimage calls
  303. // so prefer non-sub versions
  304. if (dest.left == 0 && dest.top == 0)
  305. {
  306. glCompressedTexImage2DARB(mFaceTarget, mLevel,
  307. format,
  308. dest.getWidth(),
  309. dest.getHeight(),
  310. 0,
  311. data.getConsecutiveSize(),
  312. data.data);
  313. }
  314. else
  315. {
  316. glCompressedTexSubImage2DARB(mFaceTarget, mLevel,
  317. dest.left, dest.top,
  318. dest.getWidth(), dest.getHeight(),
  319. format, data.getConsecutiveSize(),
  320. data.data);
  321. }
  322. break;
  323. case GL_TEXTURE_3D:
  324. // some systems (e.g. old Apple) don't like compressed subimage calls
  325. // so prefer non-sub versions
  326. if (dest.left == 0 && dest.top == 0 && dest.front == 0)
  327. {
  328. glCompressedTexImage3DARB(GL_TEXTURE_3D, mLevel,
  329. format,
  330. dest.getWidth(),
  331. dest.getHeight(),
  332. dest.getDepth(),
  333. 0,
  334. data.getConsecutiveSize(),
  335. data.data);
  336. }
  337. else
  338. {
  339. glCompressedTexSubImage3DARB(GL_TEXTURE_3D, mLevel,
  340. dest.left, dest.top, dest.front,
  341. dest.getWidth(), dest.getHeight(), dest.getDepth(),
  342. format, data.getConsecutiveSize(),
  343. data.data);
  344. }
  345. break;
  346. }
  347. }
  348. else if(mSoftwareMipmap)
  349. {
  350. GLint components = PixelUtil::getComponentCount(mFormat);
  351. if(data.getWidth() != data.rowPitch)
  352. glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch);
  353. if(data.getHeight()*data.getWidth() != data.slicePitch)
  354. glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()));
  355. if(data.left > 0 || data.top > 0 || data.front > 0)
  356. glPixelStorei(GL_UNPACK_SKIP_PIXELS, data.left + data.rowPitch * data.top + data.slicePitch * data.front);
  357. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  358. switch(mTarget)
  359. {
  360. case GL_TEXTURE_1D:
  361. gluBuild1DMipmaps(
  362. GL_TEXTURE_1D, components,
  363. dest.getWidth(),
  364. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  365. data.data);
  366. break;
  367. case GL_TEXTURE_2D:
  368. case GL_TEXTURE_CUBE_MAP:
  369. gluBuild2DMipmaps(
  370. mFaceTarget,
  371. components, dest.getWidth(), dest.getHeight(),
  372. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  373. data.data);
  374. break;
  375. case GL_TEXTURE_3D:
  376. /* Requires GLU 1.3 which is harder to come by than cards doing hardware mipmapping
  377. Most 3D textures don't need mipmaps?
  378. gluBuild3DMipmaps(
  379. GL_TEXTURE_3D, internalFormat,
  380. data.getWidth(), data.getHeight(), data.getDepth(),
  381. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  382. data.data);
  383. */
  384. glTexImage3D(
  385. GL_TEXTURE_3D, 0, components,
  386. dest.getWidth(), dest.getHeight(), dest.getDepth(), 0,
  387. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  388. data.data );
  389. break;
  390. }
  391. }
  392. else
  393. {
  394. if(data.getWidth() != data.rowPitch)
  395. glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch);
  396. if(data.getHeight()*data.getWidth() != data.slicePitch)
  397. glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()));
  398. if(data.left > 0 || data.top > 0 || data.front > 0)
  399. glPixelStorei(GL_UNPACK_SKIP_PIXELS, data.left + data.rowPitch * data.top + data.slicePitch * data.front);
  400. if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) {
  401. // Standard alignment of 4 is not right
  402. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  403. }
  404. switch(mTarget) {
  405. case GL_TEXTURE_1D:
  406. glTexSubImage1D(GL_TEXTURE_1D, mLevel,
  407. dest.left,
  408. dest.getWidth(),
  409. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  410. data.data);
  411. break;
  412. case GL_TEXTURE_2D:
  413. case GL_TEXTURE_CUBE_MAP:
  414. glTexSubImage2D(mFaceTarget, mLevel,
  415. dest.left, dest.top,
  416. dest.getWidth(), dest.getHeight(),
  417. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  418. data.data);
  419. break;
  420. case GL_TEXTURE_3D:
  421. glTexSubImage3D(
  422. GL_TEXTURE_3D, mLevel,
  423. dest.left, dest.top, dest.front,
  424. dest.getWidth(), dest.getHeight(), dest.getDepth(),
  425. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  426. data.data);
  427. break;
  428. }
  429. }
  430. // Restore defaults
  431. glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  432. if (GLEW_VERSION_1_2)
  433. glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
  434. glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
  435. glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
  436. }
  437. //-----------------------------------------------------------------------------
  438. void GLTextureBuffer::download(const PixelData &data)
  439. {
  440. if(data.getWidth() != getWidth() ||
  441. data.getHeight() != getHeight() ||
  442. data.getDepth() != getDepth())
  443. CM_EXCEPT(InvalidParametersException, "only download of entire buffer is supported by GL");
  444. glBindTexture( mTarget, mTextureID );
  445. if(PixelUtil::isCompressed(data.format))
  446. {
  447. if(data.format != mFormat || !data.isConsecutive())
  448. CM_EXCEPT(InvalidParametersException,
  449. "Compressed images must be consecutive, in the source format");
  450. // Data must be consecutive and at beginning of buffer as PixelStorei not allowed
  451. // for compressed formate
  452. glGetCompressedTexImageARB(mFaceTarget, mLevel, data.data);
  453. }
  454. else
  455. {
  456. if(data.getWidth() != data.rowPitch)
  457. glPixelStorei(GL_PACK_ROW_LENGTH, data.rowPitch);
  458. if(data.getHeight()*data.getWidth() != data.slicePitch)
  459. glPixelStorei(GL_PACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()));
  460. if(data.left > 0 || data.top > 0 || data.front > 0)
  461. glPixelStorei(GL_PACK_SKIP_PIXELS, data.left + data.rowPitch * data.top + data.slicePitch * data.front);
  462. if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) {
  463. // Standard alignment of 4 is not right
  464. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  465. }
  466. // We can only get the entire texture
  467. glGetTexImage(mFaceTarget, mLevel,
  468. GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format),
  469. data.data);
  470. // Restore defaults
  471. glPixelStorei(GL_PACK_ROW_LENGTH, 0);
  472. glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
  473. glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
  474. glPixelStorei(GL_PACK_ALIGNMENT, 4);
  475. }
  476. }
  477. //-----------------------------------------------------------------------------
  478. void GLTextureBuffer::bindToFramebuffer(GLenum attachment, size_t zoffset)
  479. {
  480. assert(zoffset < mDepth);
  481. switch(mTarget)
  482. {
  483. case GL_TEXTURE_1D:
  484. glFramebufferTexture1DEXT(GL_FRAMEBUFFER_EXT, attachment,
  485. mFaceTarget, mTextureID, mLevel);
  486. break;
  487. case GL_TEXTURE_2D:
  488. case GL_TEXTURE_CUBE_MAP:
  489. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment,
  490. mFaceTarget, mTextureID, mLevel);
  491. break;
  492. case GL_TEXTURE_3D:
  493. glFramebufferTexture3DEXT(GL_FRAMEBUFFER_EXT, attachment,
  494. mFaceTarget, mTextureID, mLevel, zoffset);
  495. break;
  496. }
  497. }
  498. //-----------------------------------------------------------------------------
  499. void GLTextureBuffer::copyFromFramebuffer(size_t zoffset)
  500. {
  501. glBindTexture(mTarget, mTextureID);
  502. switch(mTarget)
  503. {
  504. case GL_TEXTURE_1D:
  505. glCopyTexSubImage1D(mFaceTarget, mLevel, 0, 0, 0, mWidth);
  506. break;
  507. case GL_TEXTURE_2D:
  508. case GL_TEXTURE_CUBE_MAP:
  509. glCopyTexSubImage2D(mFaceTarget, mLevel, 0, 0, 0, 0, mWidth, mHeight);
  510. break;
  511. case GL_TEXTURE_3D:
  512. glCopyTexSubImage3D(mFaceTarget, mLevel, 0, 0, zoffset, 0, 0, mWidth, mHeight);
  513. break;
  514. }
  515. }
  516. //-----------------------------------------------------------------------------
  517. void GLTextureBuffer::blit(const HardwarePixelBufferPtr &src, const Box &srcBox, const Box &dstBox)
  518. {
  519. GLTextureBuffer *srct = static_cast<GLTextureBuffer *>(src.get());
  520. /// Check for FBO support first
  521. /// Destination texture must be 1D, 2D, 3D, or Cube
  522. /// Source texture must be 1D, 2D or 3D
  523. // This does not sem to work for RTTs after the first update
  524. // I have no idea why! For the moment, disable
  525. if(GLEW_EXT_framebuffer_object && (src->getUsage() & TU_RENDERTARGET) == 0 &&
  526. (srct->mTarget==GL_TEXTURE_1D||srct->mTarget==GL_TEXTURE_2D||srct->mTarget==GL_TEXTURE_3D))
  527. {
  528. blitFromTexture(srct, srcBox, dstBox);
  529. }
  530. else
  531. {
  532. GLHardwarePixelBuffer::blit(src, srcBox, dstBox);
  533. }
  534. }
  535. //-----------------------------------------------------------------------------
  536. /// Very fast texture-to-texture blitter and hardware bi/trilinear scaling implementation using FBO
  537. /// Destination texture must be 1D, 2D, 3D, or Cube
  538. /// Source texture must be 1D, 2D or 3D
  539. /// Supports compressed formats as both source and destination format, it will use the hardware DXT compressor
  540. /// if available.
  541. /// @author W.J. van der Laan
  542. void GLTextureBuffer::blitFromTexture(GLTextureBuffer *src, const Box &srcBox, const Box &dstBox)
  543. {
  544. //std::cerr << "GLTextureBuffer::blitFromTexture " <<
  545. //src->mTextureID << ":" << srcBox.left << "," << srcBox.top << "," << srcBox.right << "," << srcBox.bottom << " " <<
  546. //mTextureID << ":" << dstBox.left << "," << dstBox.top << "," << dstBox.right << "," << dstBox.bottom << std::endl;
  547. /// Store reference to FBO manager
  548. GLFBOManager *fboMan = static_cast<GLFBOManager *>(GLRTTManager::instancePtr());
  549. /// Save and clear GL state for rendering
  550. glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT |
  551. GL_FOG_BIT | GL_LIGHTING_BIT | GL_POLYGON_BIT | GL_SCISSOR_BIT | GL_STENCIL_BUFFER_BIT |
  552. GL_TEXTURE_BIT | GL_VIEWPORT_BIT);
  553. // Important to disable all other texture units
  554. RenderSystem* rsys = CamelotEngine::RenderSystemManager::getActive();
  555. rsys->disableTextureUnitsFrom_internal(0);
  556. if (GLEW_VERSION_1_2)
  557. {
  558. glActiveTextureARB(GL_TEXTURE0);
  559. }
  560. /// Disable alpha, depth and scissor testing, disable blending,
  561. /// disable culling, disble lighting, disable fog and reset foreground
  562. /// colour.
  563. glDisable(GL_ALPHA_TEST);
  564. glDisable(GL_DEPTH_TEST);
  565. glDisable(GL_SCISSOR_TEST);
  566. glDisable(GL_BLEND);
  567. glDisable(GL_CULL_FACE);
  568. glDisable(GL_LIGHTING);
  569. glDisable(GL_FOG);
  570. glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
  571. /// Save and reset matrices
  572. glMatrixMode(GL_MODELVIEW);
  573. glPushMatrix();
  574. glLoadIdentity();
  575. glMatrixMode(GL_PROJECTION);
  576. glPushMatrix();
  577. glLoadIdentity();
  578. glMatrixMode(GL_TEXTURE);
  579. glPushMatrix();
  580. glLoadIdentity();
  581. /// Set up source texture
  582. glBindTexture(src->mTarget, src->mTextureID);
  583. /// Set filtering modes depending on the dimensions and source
  584. if(srcBox.getWidth()==dstBox.getWidth() &&
  585. srcBox.getHeight()==dstBox.getHeight() &&
  586. srcBox.getDepth()==dstBox.getDepth())
  587. {
  588. /// Dimensions match -- use nearest filtering (fastest and pixel correct)
  589. glTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  590. glTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  591. }
  592. else
  593. {
  594. /// Dimensions don't match -- use bi or trilinear filtering depending on the
  595. /// source texture.
  596. if(src->mUsage & TU_AUTOMIPMAP)
  597. {
  598. /// Automatic mipmaps, we can safely use trilinear filter which
  599. /// brings greatly imporoved quality for minimisation.
  600. glTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  601. glTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  602. }
  603. else
  604. {
  605. /// Manual mipmaps, stay safe with bilinear filtering so that no
  606. /// intermipmap leakage occurs.
  607. glTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  608. glTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  609. }
  610. }
  611. /// Clamp to edge (fastest)
  612. glTexParameteri(src->mTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  613. glTexParameteri(src->mTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  614. glTexParameteri(src->mTarget, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  615. /// Set origin base level mipmap to make sure we source from the right mip
  616. /// level.
  617. glTexParameteri(src->mTarget, GL_TEXTURE_BASE_LEVEL, src->mLevel);
  618. /// Store old binding so it can be restored later
  619. GLint oldfb;
  620. glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb);
  621. /// Set up temporary FBO
  622. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboMan->getTemporaryFBO());
  623. GLuint tempTex = 0;
  624. if(!fboMan->checkFormat(mFormat))
  625. {
  626. /// If target format not directly supported, create intermediate texture
  627. GLenum tempFormat = GLPixelUtil::getClosestGLInternalFormat(fboMan->getSupportedAlternative(mFormat));
  628. glGenTextures(1, &tempTex);
  629. glBindTexture(GL_TEXTURE_2D, tempTex);
  630. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  631. /// Allocate temporary texture of the size of the destination area
  632. glTexImage2D(GL_TEXTURE_2D, 0, tempFormat,
  633. GLPixelUtil::optionalPO2(dstBox.getWidth()), GLPixelUtil::optionalPO2(dstBox.getHeight()),
  634. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  635. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
  636. GL_TEXTURE_2D, tempTex, 0);
  637. /// Set viewport to size of destination slice
  638. glViewport(0, 0, dstBox.getWidth(), dstBox.getHeight());
  639. }
  640. else
  641. {
  642. /// We are going to bind directly, so set viewport to size and position of destination slice
  643. glViewport(dstBox.left, dstBox.top, dstBox.getWidth(), dstBox.getHeight());
  644. }
  645. /// Process each destination slice
  646. for(size_t slice=dstBox.front; slice<dstBox.back; ++slice)
  647. {
  648. if(!tempTex)
  649. {
  650. /// Bind directly
  651. bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, slice);
  652. }
  653. /// Calculate source texture coordinates
  654. float u1 = (float)srcBox.left / (float)src->mWidth;
  655. float v1 = (float)srcBox.top / (float)src->mHeight;
  656. float u2 = (float)srcBox.right / (float)src->mWidth;
  657. float v2 = (float)srcBox.bottom / (float)src->mHeight;
  658. /// Calculate source slice for this destination slice
  659. float w = (float)(slice - dstBox.front) / (float)dstBox.getDepth();
  660. /// Get slice # in source
  661. w = w * (float)(srcBox.getDepth() + srcBox.front);
  662. /// Normalise to texture coordinate in 0.0 .. 1.0
  663. w = (w+0.5f) / (float)src->mDepth;
  664. /// Finally we're ready to rumble
  665. glBindTexture(src->mTarget, src->mTextureID);
  666. glEnable(src->mTarget);
  667. glBegin(GL_QUADS);
  668. glTexCoord3f(u1, v1, w);
  669. glVertex2f(-1.0f, -1.0f);
  670. glTexCoord3f(u2, v1, w);
  671. glVertex2f(1.0f, -1.0f);
  672. glTexCoord3f(u2, v2, w);
  673. glVertex2f(1.0f, 1.0f);
  674. glTexCoord3f(u1, v2, w);
  675. glVertex2f(-1.0f, 1.0f);
  676. glEnd();
  677. glDisable(src->mTarget);
  678. if(tempTex)
  679. {
  680. /// Copy temporary texture
  681. glBindTexture(mTarget, mTextureID);
  682. switch(mTarget)
  683. {
  684. case GL_TEXTURE_1D:
  685. glCopyTexSubImage1D(mFaceTarget, mLevel,
  686. dstBox.left,
  687. 0, 0, dstBox.getWidth());
  688. break;
  689. case GL_TEXTURE_2D:
  690. case GL_TEXTURE_CUBE_MAP:
  691. glCopyTexSubImage2D(mFaceTarget, mLevel,
  692. dstBox.left, dstBox.top,
  693. 0, 0, dstBox.getWidth(), dstBox.getHeight());
  694. break;
  695. case GL_TEXTURE_3D:
  696. glCopyTexSubImage3D(mFaceTarget, mLevel,
  697. dstBox.left, dstBox.top, slice,
  698. 0, 0, dstBox.getWidth(), dstBox.getHeight());
  699. break;
  700. }
  701. }
  702. }
  703. /// Finish up
  704. if(!tempTex)
  705. {
  706. /// Generate mipmaps
  707. if(mUsage & TU_AUTOMIPMAP)
  708. {
  709. glBindTexture(mTarget, mTextureID);
  710. glGenerateMipmapEXT(mTarget);
  711. }
  712. }
  713. /// Reset source texture to sane state
  714. glBindTexture(src->mTarget, src->mTextureID);
  715. glTexParameteri(src->mTarget, GL_TEXTURE_BASE_LEVEL, 0);
  716. /// Detach texture from temporary framebuffer
  717. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
  718. GL_RENDERBUFFER_EXT, 0);
  719. /// Restore old framebuffer
  720. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, oldfb);
  721. /// Restore matrix stacks and render state
  722. glMatrixMode(GL_TEXTURE);
  723. glPopMatrix();
  724. glMatrixMode(GL_PROJECTION);
  725. glPopMatrix();
  726. glMatrixMode(GL_MODELVIEW);
  727. glPopMatrix();
  728. glPopAttrib();
  729. glDeleteTextures(1, &tempTex);
  730. }
  731. //-----------------------------------------------------------------------------
  732. /// blitFromMemory doing hardware trilinear scaling
  733. void GLTextureBuffer::blitFromMemory(const PixelData &src_orig, const Box &dstBox)
  734. {
  735. /// Fall back to normal GLHardwarePixelBuffer::blitFromMemory in case
  736. /// - FBO is not supported
  737. /// - Either source or target is luminance due doesn't looks like supported by hardware
  738. /// - the source dimensions match the destination ones, in which case no scaling is needed
  739. if(!GLEW_EXT_framebuffer_object ||
  740. PixelUtil::isLuminance(src_orig.format) ||
  741. PixelUtil::isLuminance(mFormat) ||
  742. (src_orig.getWidth() == dstBox.getWidth() &&
  743. src_orig.getHeight() == dstBox.getHeight() &&
  744. src_orig.getDepth() == dstBox.getDepth()))
  745. {
  746. GLHardwarePixelBuffer::blitFromMemory(src_orig, dstBox);
  747. return;
  748. }
  749. if(!mBuffer.contains(dstBox))
  750. CM_EXCEPT(InvalidParametersException, "destination box out of range");
  751. /// For scoped deletion of conversion buffer
  752. void* data = NULL;
  753. PixelData src;
  754. /// First, convert the srcbox to a OpenGL compatible pixel format
  755. if(GLPixelUtil::getGLOriginFormat(src_orig.format) == 0)
  756. {
  757. /// Convert to buffer internal format
  758. data = new void*[PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), src.getDepth(), mFormat)];
  759. src = PixelData(src_orig.getWidth(), src_orig.getHeight(), src_orig.getDepth(), mFormat, data);
  760. PixelUtil::bulkPixelConversion(src_orig, src);
  761. }
  762. else
  763. {
  764. /// No conversion needed
  765. src = src_orig;
  766. }
  767. /// Create temporary texture to store source data
  768. GLuint id;
  769. GLenum target = (src.getDepth()!=1)?GL_TEXTURE_3D:GL_TEXTURE_2D;
  770. GLsizei width = GLPixelUtil::optionalPO2(src.getWidth());
  771. GLsizei height = GLPixelUtil::optionalPO2(src.getHeight());
  772. GLsizei depth = GLPixelUtil::optionalPO2(src.getDepth());
  773. GLenum format = GLPixelUtil::getClosestGLInternalFormat(src.format);
  774. /// Generate texture name
  775. glGenTextures(1, &id);
  776. /// Set texture type
  777. glBindTexture(target, id);
  778. /// Set automatic mipmap generation; nice for minimisation
  779. glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 1000 );
  780. glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE );
  781. /// Allocate texture memory
  782. if(target == GL_TEXTURE_3D)
  783. glTexImage3D(target, 0, format, width, height, depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  784. else
  785. glTexImage2D(target, 0, format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  786. /// GL texture buffer
  787. GLTextureBuffer tex(StringUtil::BLANK, target, id, 0, 0, (Usage)(TU_AUTOMIPMAP|HBU_STATIC_WRITE_ONLY), false, false, 0);
  788. /// Upload data to 0,0,0 in temporary texture
  789. Box tempTarget(0, 0, 0, src.getWidth(), src.getHeight(), src.getDepth());
  790. tex.upload(src, tempTarget);
  791. /// Blit
  792. blitFromTexture(&tex, tempTarget, dstBox);
  793. /// Delete temp texture
  794. glDeleteTextures(1, &id);
  795. if(data != NULL)
  796. delete[] data;
  797. }
  798. //-----------------------------------------------------------------------------
  799. RenderTexture *GLTextureBuffer::getRenderTarget(size_t zoffset)
  800. {
  801. assert(mUsage & TU_RENDERTARGET);
  802. assert(zoffset < mDepth);
  803. return mSliceTRT[zoffset];
  804. }
  805. //********* GLRenderBuffer
  806. //-----------------------------------------------------------------------------
  807. GLRenderBuffer::GLRenderBuffer(GLenum format, size_t width, size_t height, GLsizei numSamples):
  808. GLHardwarePixelBuffer(width, height, 1, GLPixelUtil::getClosestOGREFormat(format),HBU_WRITE_ONLY),
  809. mRenderbufferID(0)
  810. {
  811. mGLInternalFormat = format;
  812. /// Generate renderbuffer
  813. glGenRenderbuffersEXT(1, &mRenderbufferID);
  814. /// Bind it to FBO
  815. glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRenderbufferID);
  816. /// Allocate storage for depth buffer
  817. if (numSamples > 0)
  818. {
  819. glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT,
  820. numSamples, format, width, height);
  821. }
  822. else
  823. {
  824. glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, format,
  825. width, height);
  826. }
  827. }
  828. //-----------------------------------------------------------------------------
  829. GLRenderBuffer::~GLRenderBuffer()
  830. {
  831. /// Generate renderbuffer
  832. glDeleteRenderbuffersEXT(1, &mRenderbufferID);
  833. }
  834. //-----------------------------------------------------------------------------
  835. void GLRenderBuffer::bindToFramebuffer(GLenum attachment, size_t zoffset)
  836. {
  837. assert(zoffset < mDepth);
  838. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, attachment,
  839. GL_RENDERBUFFER_EXT, mRenderbufferID);
  840. }
  841. };