CmGLPixelBuffer.cpp 28 KB

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