CCRenderTexture.cpp 29 KB

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