CCRenderTexture.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /****************************************************************************
  2. Copyright (c) 2009 Jason Booth
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2013-2017 Chukong Technologies Inc.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #include "2d/CCRenderTexture.h"
  23. #include "base/ccUtils.h"
  24. #include "platform/CCFileUtils.h"
  25. #include "base/CCEventType.h"
  26. #include "base/CCConfiguration.h"
  27. #include "base/CCDirector.h"
  28. #include "base/CCEventListenerCustom.h"
  29. #include "base/CCEventDispatcher.h"
  30. #include "renderer/CCRenderer.h"
  31. #include "2d/CCCamera.h"
  32. #include "renderer/CCTextureCache.h"
  33. NS_CC_BEGIN
  34. // implementation RenderTexture
  35. RenderTexture::RenderTexture()
  36. : _keepMatrix(false)
  37. , _rtTextureRect(Rect::ZERO)
  38. , _fullRect(Rect::ZERO)
  39. , _fullviewPort(Rect::ZERO)
  40. , _FBO(0)
  41. , _depthRenderBuffer(0)
  42. , _stencilRenderBuffer(0)
  43. , _oldFBO(0)
  44. , _texture(0)
  45. , _textureCopy(0)
  46. , _UITextureImage(nullptr)
  47. , _pixelFormat(Texture2D::PixelFormat::RGBA8888)
  48. , _clearFlags(0)
  49. , _clearColor(Color4F(0,0,0,0))
  50. , _clearDepth(0.0f)
  51. , _clearStencil(0)
  52. , _autoDraw(false)
  53. , _sprite(nullptr)
  54. , _saveFileCallback(nullptr)
  55. {
  56. #if CC_ENABLE_CACHE_TEXTURE_DATA
  57. // Listen this event to save render texture before come to background.
  58. // Then it can be restored after coming to foreground on Android.
  59. auto toBackgroundListener = EventListenerCustom::create(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(RenderTexture::listenToBackground, this));
  60. _eventDispatcher->addEventListenerWithSceneGraphPriority(toBackgroundListener, this);
  61. auto toForegroundListener = EventListenerCustom::create(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(RenderTexture::listenToForeground, this));
  62. _eventDispatcher->addEventListenerWithSceneGraphPriority(toForegroundListener, this);
  63. #endif
  64. }
  65. RenderTexture::~RenderTexture()
  66. {
  67. CC_SAFE_RELEASE(_sprite);
  68. CC_SAFE_RELEASE(_textureCopy);
  69. glDeleteFramebuffers(1, &_FBO);
  70. if (_depthRenderBuffer)
  71. {
  72. glDeleteRenderbuffers(1, &_depthRenderBuffer);
  73. }
  74. if (_stencilRenderBuffer)
  75. {
  76. glDeleteRenderbuffers(1, &_stencilRenderBuffer);
  77. }
  78. CC_SAFE_DELETE(_UITextureImage);
  79. }
  80. void RenderTexture::listenToBackground(EventCustom* /*event*/)
  81. {
  82. // We have not found a way to dispatch the enter background message before the texture data are destroyed.
  83. // So we disable this pair of message handler at present.
  84. #if CC_ENABLE_CACHE_TEXTURE_DATA
  85. CC_SAFE_DELETE(_UITextureImage);
  86. // to get the rendered texture data
  87. _UITextureImage = newImage(false);
  88. if (_UITextureImage)
  89. {
  90. const Size& s = _texture->getContentSizeInPixels();
  91. VolatileTextureMgr::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
  92. if ( _textureCopy )
  93. {
  94. VolatileTextureMgr::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
  95. }
  96. }
  97. else
  98. {
  99. CCLOG("Cache rendertexture failed!");
  100. }
  101. glDeleteFramebuffers(1, &_FBO);
  102. _FBO = 0;
  103. #endif
  104. }
  105. void RenderTexture::listenToForeground(EventCustom* /*event*/)
  106. {
  107. #if CC_ENABLE_CACHE_TEXTURE_DATA
  108. // -- regenerate frame buffer object and attach the texture
  109. glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
  110. glGenFramebuffers(1, &_FBO);
  111. glBindFramebuffer(GL_FRAMEBUFFER, _FBO);
  112. _texture->setAliasTexParameters();
  113. if ( _textureCopy )
  114. {
  115. _textureCopy->setAliasTexParameters();
  116. }
  117. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
  118. glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
  119. #endif
  120. }
  121. RenderTexture * RenderTexture::create(int w, int h, Texture2D::PixelFormat eFormat)
  122. {
  123. RenderTexture *ret = new (std::nothrow) RenderTexture();
  124. if(ret && ret->initWithWidthAndHeight(w, h, eFormat))
  125. {
  126. ret->autorelease();
  127. return ret;
  128. }
  129. CC_SAFE_DELETE(ret);
  130. return nullptr;
  131. }
  132. RenderTexture * RenderTexture::create(int w ,int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat)
  133. {
  134. RenderTexture *ret = new (std::nothrow) RenderTexture();
  135. if(ret && ret->initWithWidthAndHeight(w, h, eFormat, uDepthStencilFormat))
  136. {
  137. ret->autorelease();
  138. return ret;
  139. }
  140. CC_SAFE_DELETE(ret);
  141. return nullptr;
  142. }
  143. RenderTexture * RenderTexture::create(int w, int h)
  144. {
  145. RenderTexture *ret = new (std::nothrow) RenderTexture();
  146. if(ret && ret->initWithWidthAndHeight(w, h, Texture2D::PixelFormat::RGBA8888, 0))
  147. {
  148. ret->autorelease();
  149. return ret;
  150. }
  151. CC_SAFE_DELETE(ret);
  152. return nullptr;
  153. }
  154. bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat)
  155. {
  156. return initWithWidthAndHeight(w, h, eFormat, 0);
  157. }
  158. bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat format, GLuint depthStencilFormat)
  159. {
  160. CCASSERT(format != Texture2D::PixelFormat::A8, "only RGB and RGBA formats are valid for a render texture");
  161. bool ret = false;
  162. void *data = nullptr;
  163. do
  164. {
  165. _fullRect = _rtTextureRect = Rect(0,0,w,h);
  166. //Size size = Director::getInstance()->getWinSizeInPixels();
  167. //_fullviewPort = Rect(0,0,size.width,size.height);
  168. w = (int)(w * CC_CONTENT_SCALE_FACTOR());
  169. h = (int)(h * CC_CONTENT_SCALE_FACTOR());
  170. _fullviewPort = Rect(0,0,w,h);
  171. glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
  172. // textures must be power of two squared
  173. int powW = 0;
  174. int powH = 0;
  175. if (Configuration::getInstance()->supportsNPOT())
  176. {
  177. powW = w;
  178. powH = h;
  179. }
  180. else
  181. {
  182. powW = ccNextPOT(w);
  183. powH = ccNextPOT(h);
  184. }
  185. auto dataLen = powW * powH * 4;
  186. data = malloc(dataLen);
  187. CC_BREAK_IF(! data);
  188. memset(data, 0, dataLen);
  189. _pixelFormat = format;
  190. _texture = new (std::nothrow) Texture2D();
  191. if (_texture)
  192. {
  193. _texture->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
  194. }
  195. else
  196. {
  197. break;
  198. }
  199. GLint oldRBO;
  200. glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
  201. if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
  202. {
  203. _textureCopy = new (std::nothrow) Texture2D();
  204. if (_textureCopy)
  205. {
  206. _textureCopy->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
  207. }
  208. else
  209. {
  210. break;
  211. }
  212. }
  213. // generate FBO
  214. glGenFramebuffers(1, &_FBO);
  215. glBindFramebuffer(GL_FRAMEBUFFER, _FBO);
  216. // associate texture with FBO
  217. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
  218. if (depthStencilFormat != 0)
  219. {
  220. #if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  221. if(Configuration::getInstance()->supportsOESPackedDepthStencil())
  222. {
  223. //create and attach depth buffer
  224. glGenRenderbuffers(1, &_depthRenderBuffer);
  225. glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBuffer);
  226. glRenderbufferStorage(GL_RENDERBUFFER, depthStencilFormat, (GLsizei)powW, (GLsizei)powH);
  227. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBuffer);
  228. // if depth format is the one with stencil part, bind same render buffer as stencil attachment
  229. if (depthStencilFormat == GL_DEPTH24_STENCIL8)
  230. {
  231. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBuffer);
  232. }
  233. }
  234. else
  235. {
  236. glGenRenderbuffers(1, &_depthRenderBuffer);
  237. glGenRenderbuffers(1, &_stencilRenderBuffer);
  238. glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBuffer);
  239. if(Configuration::getInstance()->supportsOESDepth24())
  240. {
  241. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24_OES, (GLsizei)powW, (GLsizei)powH);
  242. }
  243. else
  244. {
  245. glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, (GLsizei)powW, (GLsizei)powH);
  246. }
  247. glBindRenderbuffer(GL_RENDERBUFFER, _stencilRenderBuffer);
  248. glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, (GLsizei)powW, (GLsizei)powH);
  249. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBuffer);
  250. glFramebufferRenderbuffer(GL_FRAMEBUFFER,
  251. GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _stencilRenderBuffer);
  252. }
  253. #else
  254. //create and attach depth buffer
  255. glGenRenderbuffers(1, &_depthRenderBuffer);
  256. glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBuffer);
  257. glRenderbufferStorage(GL_RENDERBUFFER, depthStencilFormat, (GLsizei)powW, (GLsizei)powH);
  258. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBuffer);
  259. // if depth format is the one with stencil part, bind same render buffer as stencil attachment
  260. if (depthStencilFormat == GL_DEPTH24_STENCIL8)
  261. {
  262. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBuffer);
  263. }
  264. #endif
  265. }
  266. // check if it worked (probably worth doing :) )
  267. CCASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");
  268. _texture->setAliasTexParameters();
  269. // retained
  270. setSprite(Sprite::createWithTexture(_texture));
  271. _texture->release();
  272. _sprite->setFlippedY(true);
  273. _sprite->setBlendFunc( BlendFunc::ALPHA_PREMULTIPLIED );
  274. _sprite->setOpacityModifyRGB(true);
  275. glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
  276. glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
  277. // Disabled by default.
  278. _autoDraw = false;
  279. // add sprite for backward compatibility
  280. addChild(_sprite);
  281. ret = true;
  282. } while (0);
  283. CC_SAFE_FREE(data);
  284. return ret;
  285. }
  286. void RenderTexture::setSprite(Sprite* sprite)
  287. {
  288. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  289. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  290. if (sEngine)
  291. {
  292. if (sprite)
  293. sEngine->retainScriptObject(this, sprite);
  294. if (_sprite)
  295. sEngine->releaseScriptObject(this, _sprite);
  296. }
  297. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  298. CC_SAFE_RETAIN(sprite);
  299. CC_SAFE_RELEASE(_sprite);
  300. _sprite = sprite;
  301. }
  302. void RenderTexture::setKeepMatrix(bool keepMatrix)
  303. {
  304. _keepMatrix = keepMatrix;
  305. }
  306. void RenderTexture::setVirtualViewport(const Vec2& rtBegin, const Rect& fullRect, const Rect& fullViewport)
  307. {
  308. _rtTextureRect.origin.x = rtBegin.x;
  309. _rtTextureRect.origin.y = rtBegin.y;
  310. _fullRect = fullRect;
  311. _fullviewPort = fullViewport;
  312. }
  313. void RenderTexture::beginWithClear(float r, float g, float b, float a)
  314. {
  315. beginWithClear(r, g, b, a, 0, 0, GL_COLOR_BUFFER_BIT);
  316. }
  317. void RenderTexture::beginWithClear(float r, float g, float b, float a, float depthValue)
  318. {
  319. beginWithClear(r, g, b, a, depthValue, 0, GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  320. }
  321. void RenderTexture::beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue)
  322. {
  323. beginWithClear(r, g, b, a, depthValue, stencilValue, GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
  324. }
  325. void RenderTexture::beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue, GLbitfield flags)
  326. {
  327. setClearColor(Color4F(r, g, b, a));
  328. setClearDepth(depthValue);
  329. setClearStencil(stencilValue);
  330. setClearFlags(flags);
  331. this->begin();
  332. //clear screen
  333. _beginWithClearCommand.init(_globalZOrder);
  334. _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
  335. Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand);
  336. }
  337. //TODO: find a better way to clear the screen, there is no need to rebind render buffer there.
  338. void RenderTexture::clear(float r, float g, float b, float a)
  339. {
  340. this->beginWithClear(r, g, b, a);
  341. this->end();
  342. }
  343. void RenderTexture::clearDepth(float depthValue)
  344. {
  345. setClearDepth(depthValue);
  346. this->begin();
  347. _clearDepthCommand.init(_globalZOrder);
  348. _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this);
  349. Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand);
  350. this->end();
  351. }
  352. void RenderTexture::clearStencil(int stencilValue)
  353. {
  354. // save old stencil value
  355. int stencilClearValue;
  356. glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &stencilClearValue);
  357. glClearStencil(stencilValue);
  358. glClear(GL_STENCIL_BUFFER_BIT);
  359. // restore clear color
  360. glClearStencil(stencilClearValue);
  361. }
  362. void RenderTexture::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
  363. {
  364. // override visit.
  365. // Don't call visit on its children
  366. if (!_visible)
  367. {
  368. return;
  369. }
  370. uint32_t flags = processParentFlags(parentTransform, parentFlags);
  371. Director* director = Director::getInstance();
  372. // IMPORTANT:
  373. // To ease the migration to v3.0, we still support the Mat4 stack,
  374. // but it is deprecated and your code should not rely on it
  375. director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  376. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
  377. _sprite->visit(renderer, _modelViewTransform, flags);
  378. if (isVisitableByVisitingCamera())
  379. {
  380. draw(renderer, _modelViewTransform, flags);
  381. }
  382. director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  383. // FIX ME: Why need to set _orderOfArrival to 0??
  384. // Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
  385. // setOrderOfArrival(0);
  386. }
  387. bool RenderTexture::saveToFile(const std::string& filename, bool isRGBA, std::function<void (RenderTexture*, const std::string&)> callback)
  388. {
  389. std::string basename(filename);
  390. std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower);
  391. if (basename.find(".png") != std::string::npos)
  392. {
  393. return saveToFile(filename, Image::Format::PNG, isRGBA, callback);
  394. }
  395. else if (basename.find(".jpg") != std::string::npos)
  396. {
  397. if (isRGBA) CCLOG("RGBA is not supported for JPG format.");
  398. return saveToFile(filename, Image::Format::JPG, false, callback);
  399. }
  400. else
  401. {
  402. CCLOG("Only PNG and JPG format are supported now!");
  403. }
  404. return saveToFile(filename, Image::Format::JPG, false, callback);
  405. }
  406. bool RenderTexture::saveToFile(const std::string& fileName, Image::Format format, bool isRGBA, std::function<void (RenderTexture*, const std::string&)> callback)
  407. {
  408. CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
  409. "the image can only be saved as JPG or PNG format");
  410. if (isRGBA && format == Image::Format::JPG) CCLOG("RGBA is not supported for JPG format");
  411. _saveFileCallback = callback;
  412. std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName;
  413. _saveToFileCommand.init(_globalZOrder);
  414. _saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA);
  415. Director::getInstance()->getRenderer()->addCommand(&_saveToFileCommand);
  416. return true;
  417. }
  418. void RenderTexture::onSaveToFile(const std::string& filename, bool isRGBA)
  419. {
  420. Image *image = newImage(true);
  421. if (image)
  422. {
  423. image->saveToFile(filename, !isRGBA);
  424. }
  425. if(_saveFileCallback)
  426. {
  427. _saveFileCallback(this, filename);
  428. }
  429. CC_SAFE_DELETE(image);
  430. }
  431. /* get buffer as Image */
  432. Image* RenderTexture::newImage(bool flipImage)
  433. {
  434. CCASSERT(_pixelFormat == Texture2D::PixelFormat::RGBA8888, "only RGBA8888 can be saved as image");
  435. if (nullptr == _texture)
  436. {
  437. return nullptr;
  438. }
  439. const Size& s = _texture->getContentSizeInPixels();
  440. // to get the image size to save
  441. // if the saving image domain exceeds the buffer texture domain,
  442. // it should be cut
  443. int savedBufferWidth = (int)s.width;
  444. int savedBufferHeight = (int)s.height;
  445. GLubyte *buffer = nullptr;
  446. GLubyte *tempData = nullptr;
  447. Image *image = new (std::nothrow) Image();
  448. do
  449. {
  450. CC_BREAK_IF(! (buffer = new (std::nothrow) GLubyte[savedBufferWidth * savedBufferHeight * 4]));
  451. if(! (tempData = new (std::nothrow) GLubyte[savedBufferWidth * savedBufferHeight * 4]))
  452. {
  453. delete[] buffer;
  454. buffer = nullptr;
  455. break;
  456. }
  457. glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
  458. glBindFramebuffer(GL_FRAMEBUFFER, _FBO);
  459. // TODO: move this to configuration, so we don't check it every time
  460. /* Certain Qualcomm Adreno GPU's will retain data in memory after a frame buffer switch which corrupts the render to the texture. The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture. Create a temporary texture to overcome this. At the end of RenderTexture::begin(), switch the attached texture to the second one, call glClear, and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers.
  461. */
  462. if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
  463. {
  464. // -- bind a temporary texture so we can clear the render buffer without losing our texture
  465. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureCopy->getName(), 0);
  466. CHECK_GL_ERROR_DEBUG();
  467. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  468. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
  469. }
  470. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  471. glReadPixels(0,0,savedBufferWidth, savedBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, tempData);
  472. glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
  473. if ( flipImage ) // -- flip is only required when saving image to file
  474. {
  475. // to get the actual texture data
  476. // #640 the image read from rendertexture is dirty
  477. for (int i = 0; i < savedBufferHeight; ++i)
  478. {
  479. memcpy(&buffer[i * savedBufferWidth * 4],
  480. &tempData[(savedBufferHeight - i - 1) * savedBufferWidth * 4],
  481. savedBufferWidth * 4);
  482. }
  483. image->initWithRawData(buffer, savedBufferWidth * savedBufferHeight * 4, savedBufferWidth, savedBufferHeight, 8);
  484. }
  485. else
  486. {
  487. image->initWithRawData(tempData, savedBufferWidth * savedBufferHeight * 4, savedBufferWidth, savedBufferHeight, 8);
  488. }
  489. } while (0);
  490. CC_SAFE_DELETE_ARRAY(buffer);
  491. CC_SAFE_DELETE_ARRAY(tempData);
  492. return image;
  493. }
  494. void RenderTexture::onBegin()
  495. {
  496. //
  497. Director *director = Director::getInstance();
  498. _oldProjMatrix = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
  499. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, _projectionMatrix);
  500. _oldTransMatrix = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  501. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _transformMatrix);
  502. if(!_keepMatrix)
  503. {
  504. director->setProjection(director->getProjection());
  505. const Size& texSize = _texture->getContentSizeInPixels();
  506. // Calculate the adjustment ratios based on the old and new projections
  507. Size size = director->getWinSizeInPixels();
  508. float widthRatio = size.width / texSize.width;
  509. float heightRatio = size.height / texSize.height;
  510. Mat4 orthoMatrix;
  511. Mat4::createOrthographicOffCenter((float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1, 1, &orthoMatrix);
  512. director->multiplyMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, orthoMatrix);
  513. }
  514. //calculate viewport
  515. {
  516. Rect viewport;
  517. viewport.size.width = _fullviewPort.size.width;
  518. viewport.size.height = _fullviewPort.size.height;
  519. float viewPortRectWidthRatio = float(viewport.size.width)/_fullRect.size.width;
  520. float viewPortRectHeightRatio = float(viewport.size.height)/_fullRect.size.height;
  521. viewport.origin.x = (_fullRect.origin.x - _rtTextureRect.origin.x) * viewPortRectWidthRatio;
  522. viewport.origin.y = (_fullRect.origin.y - _rtTextureRect.origin.y) * viewPortRectHeightRatio;
  523. //glViewport(_fullviewPort.origin.x, _fullviewPort.origin.y, (GLsizei)_fullviewPort.size.width, (GLsizei)_fullviewPort.size.height);
  524. glViewport(viewport.origin.x, viewport.origin.y, (GLsizei)viewport.size.width, (GLsizei)viewport.size.height);
  525. }
  526. // Adjust the orthographic projection and viewport
  527. glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
  528. glBindFramebuffer(GL_FRAMEBUFFER, _FBO);
  529. // TODO: move this to configuration, so we don't check it every time
  530. /* Certain Qualcomm Adreno GPU's will retain data in memory after a frame buffer switch which corrupts the render to the texture. The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture. Create a temporary texture to overcome this. At the end of RenderTexture::begin(), switch the attached texture to the second one, call glClear, and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers.
  531. */
  532. if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
  533. {
  534. // -- bind a temporary texture so we can clear the render buffer without losing our texture
  535. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureCopy->getName(), 0);
  536. CHECK_GL_ERROR_DEBUG();
  537. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  538. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
  539. }
  540. }
  541. void RenderTexture::onEnd()
  542. {
  543. Director *director = Director::getInstance();
  544. glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
  545. // restore viewport
  546. director->setViewport();
  547. const auto& vp = Camera::getDefaultViewport();
  548. glViewport(vp._left, vp._bottom, vp._width, vp._height);
  549. //
  550. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, _oldProjMatrix);
  551. director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _oldTransMatrix);
  552. }
  553. void RenderTexture::onClear()
  554. {
  555. // save clear color
  556. GLfloat oldClearColor[4] = {0.0f};
  557. GLfloat oldDepthClearValue = 0.0f;
  558. GLint oldStencilClearValue = 0;
  559. GLboolean oldDepthWrite = GL_FALSE;
  560. // backup and set
  561. if (_clearFlags & GL_COLOR_BUFFER_BIT)
  562. {
  563. glGetFloatv(GL_COLOR_CLEAR_VALUE, oldClearColor);
  564. glClearColor(_clearColor.r, _clearColor.g, _clearColor.b, _clearColor.a);
  565. }
  566. if (_clearFlags & GL_DEPTH_BUFFER_BIT)
  567. {
  568. glGetFloatv(GL_DEPTH_CLEAR_VALUE, &oldDepthClearValue);
  569. glClearDepth(_clearDepth);
  570. glGetBooleanv(GL_DEPTH_WRITEMASK, &oldDepthWrite);
  571. glDepthMask(GL_TRUE);
  572. }
  573. if (_clearFlags & GL_STENCIL_BUFFER_BIT)
  574. {
  575. glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &oldStencilClearValue);
  576. glClearStencil(_clearStencil);
  577. }
  578. // clear
  579. glClear(_clearFlags);
  580. // restore
  581. if (_clearFlags & GL_COLOR_BUFFER_BIT)
  582. {
  583. glClearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]);
  584. }
  585. if (_clearFlags & GL_DEPTH_BUFFER_BIT)
  586. {
  587. glClearDepth(oldDepthClearValue);
  588. glDepthMask(oldDepthWrite);
  589. }
  590. if (_clearFlags & GL_STENCIL_BUFFER_BIT)
  591. {
  592. glClearStencil(oldStencilClearValue);
  593. }
  594. }
  595. void RenderTexture::onClearDepth()
  596. {
  597. //! save old depth value
  598. GLfloat depthClearValue;
  599. glGetFloatv(GL_DEPTH_CLEAR_VALUE, &depthClearValue);
  600. glClearDepth(_clearDepth);
  601. glClear(GL_DEPTH_BUFFER_BIT);
  602. // restore clear color
  603. glClearDepth(depthClearValue);
  604. }
  605. void RenderTexture::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
  606. {
  607. if (_autoDraw)
  608. {
  609. //Begin will create a render group using new render target
  610. begin();
  611. //clear screen
  612. _clearCommand.init(_globalZOrder);
  613. _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
  614. renderer->addCommand(&_clearCommand);
  615. //! make sure all children are drawn
  616. sortAllChildren();
  617. for(const auto &child: _children)
  618. {
  619. if (child != _sprite)
  620. child->visit(renderer, transform, flags);
  621. }
  622. //End will pop the current render group
  623. end();
  624. }
  625. }
  626. void RenderTexture::begin()
  627. {
  628. Director* director = Director::getInstance();
  629. CCASSERT(nullptr != director, "Director is null when setting matrix stack");
  630. director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
  631. _projectionMatrix = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
  632. director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  633. _transformMatrix = director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  634. if(!_keepMatrix)
  635. {
  636. director->setProjection(director->getProjection());
  637. const Size& texSize = _texture->getContentSizeInPixels();
  638. // Calculate the adjustment ratios based on the old and new projections
  639. Size size = director->getWinSizeInPixels();
  640. float widthRatio = size.width / texSize.width;
  641. float heightRatio = size.height / texSize.height;
  642. Mat4 orthoMatrix;
  643. Mat4::createOrthographicOffCenter((float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1, 1, &orthoMatrix);
  644. director->multiplyMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION, orthoMatrix);
  645. }
  646. _groupCommand.init(_globalZOrder);
  647. Renderer *renderer = Director::getInstance()->getRenderer();
  648. renderer->addCommand(&_groupCommand);
  649. renderer->pushGroup(_groupCommand.getRenderQueueID());
  650. _beginCommand.init(_globalZOrder);
  651. _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this);
  652. Director::getInstance()->getRenderer()->addCommand(&_beginCommand);
  653. }
  654. void RenderTexture::end()
  655. {
  656. _endCommand.init(_globalZOrder);
  657. _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this);
  658. Director* director = Director::getInstance();
  659. CCASSERT(nullptr != director, "Director is null when setting matrix stack");
  660. Renderer *renderer = director->getRenderer();
  661. renderer->addCommand(&_endCommand);
  662. renderer->popGroup();
  663. director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
  664. director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
  665. }
  666. NS_CC_END