CCTextureCache.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2017 Chukong Technologies Inc.
  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 "renderer/CCTextureCache.h"
  24. #include <errno.h>
  25. #include <stack>
  26. #include <cctype>
  27. #include <list>
  28. #include "renderer/CCTexture2D.h"
  29. #include "base/ccMacros.h"
  30. #include "base/ccUTF8.h"
  31. #include "base/CCDirector.h"
  32. #include "base/CCScheduler.h"
  33. #include "platform/CCFileUtils.h"
  34. #include "base/ccUtils.h"
  35. #include "base/CCNinePatchImageParser.h"
  36. using namespace std;
  37. NS_CC_BEGIN
  38. std::string TextureCache::s_etc1AlphaFileSuffix = "@alpha";
  39. // implementation TextureCache
  40. void TextureCache::setETC1AlphaFileSuffix(const std::string& suffix)
  41. {
  42. s_etc1AlphaFileSuffix = suffix;
  43. }
  44. std::string TextureCache::getETC1AlphaFileSuffix()
  45. {
  46. return s_etc1AlphaFileSuffix;
  47. }
  48. TextureCache * TextureCache::getInstance()
  49. {
  50. return Director::getInstance()->getTextureCache();
  51. }
  52. TextureCache::TextureCache()
  53. : _loadingThread(nullptr)
  54. , _needQuit(false)
  55. , _asyncRefCount(0)
  56. {
  57. }
  58. TextureCache::~TextureCache()
  59. {
  60. CCLOGINFO("deallocing TextureCache: %p", this);
  61. for (auto& texture : _textures)
  62. texture.second->release();
  63. CC_SAFE_DELETE(_loadingThread);
  64. }
  65. void TextureCache::destroyInstance()
  66. {
  67. }
  68. TextureCache * TextureCache::sharedTextureCache()
  69. {
  70. return Director::getInstance()->getTextureCache();
  71. }
  72. void TextureCache::purgeSharedTextureCache()
  73. {
  74. }
  75. std::string TextureCache::getDescription() const
  76. {
  77. return StringUtils::format("<TextureCache | Number of textures = %d>", static_cast<int>(_textures.size()));
  78. }
  79. struct TextureCache::AsyncStruct
  80. {
  81. public:
  82. AsyncStruct
  83. ( const std::string& fn,const std::function<void(Texture2D*)>& f,
  84. const std::string& key )
  85. : filename(fn), callback(f),callbackKey( key ),
  86. pixelFormat(Texture2D::getDefaultAlphaPixelFormat()),
  87. loadSuccess(false)
  88. {}
  89. std::string filename;
  90. std::function<void(Texture2D*)> callback;
  91. std::string callbackKey;
  92. Image image;
  93. Image imageAlpha;
  94. Texture2D::PixelFormat pixelFormat;
  95. bool loadSuccess;
  96. };
  97. /**
  98. The addImageAsync logic follow the steps:
  99. - find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread)
  100. - get AsyncStruct from _requestQueue, load res and fill image data to AsyncStruct.image, then add AsyncStruct to _responseQueue (Load thread)
  101. - on schedule callback, get AsyncStruct from _responseQueue, convert image to texture, then delete AsyncStruct (GL thread)
  102. the Critical Area include these members:
  103. - _requestQueue: locked by _requestMutex
  104. - _responseQueue: locked by _responseMutex
  105. the object's life time:
  106. - AsyncStruct: construct and destruct in GL thread
  107. - image data: new in Load thread, delete in GL thread(by Image instance)
  108. Note:
  109. - all AsyncStruct referenced in _asyncStructQueue, for unbind function use.
  110. How to deal add image many times?
  111. - At first, this situation is abnormal, we only ensure the logic is correct.
  112. - If the image has been loaded, the after load image call will return immediately.
  113. - If the image request is in queue already, there will be more than one request in queue,
  114. - In addImageAsyncCallback, will deduplicate the request to ensure only create one texture.
  115. Does process all response in addImageAsyncCallback consume more time?
  116. - Convert image to texture faster than load image from disk, so this isn't a
  117. problem.
  118. Call unbindImageAsync(path) to prevent the call to the callback when the
  119. texture is loaded.
  120. */
  121. void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback)
  122. {
  123. addImageAsync( path, callback, path );
  124. }
  125. /**
  126. The addImageAsync logic follow the steps:
  127. - find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread)
  128. - get AsyncStruct from _requestQueue, load res and fill image data to AsyncStruct.image, then add AsyncStruct to _responseQueue (Load thread)
  129. - on schedule callback, get AsyncStruct from _responseQueue, convert image to texture, then delete AsyncStruct (GL thread)
  130. the Critical Area include these members:
  131. - _requestQueue: locked by _requestMutex
  132. - _responseQueue: locked by _responseMutex
  133. the object's life time:
  134. - AsyncStruct: construct and destruct in GL thread
  135. - image data: new in Load thread, delete in GL thread(by Image instance)
  136. Note:
  137. - all AsyncStruct referenced in _asyncStructQueue, for unbind function use.
  138. How to deal add image many times?
  139. - At first, this situation is abnormal, we only ensure the logic is correct.
  140. - If the image has been loaded, the after load image call will return immediately.
  141. - If the image request is in queue already, there will be more than one request in queue,
  142. - In addImageAsyncCallback, will deduplicate the request to ensure only create one texture.
  143. Does process all response in addImageAsyncCallback consume more time?
  144. - Convert image to texture faster than load image from disk, so this isn't a
  145. problem.
  146. The callbackKey allows to unbind the callback in cases where the loading of
  147. path is requested by several sources simultaneously. Each source can then
  148. unbind the callback independently as needed whilst a call to
  149. unbindImageAsync(path) would be ambiguous.
  150. */
  151. void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback, const std::string& callbackKey)
  152. {
  153. Texture2D *texture = nullptr;
  154. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
  155. auto it = _textures.find(fullpath);
  156. if (it != _textures.end())
  157. texture = it->second;
  158. if (texture != nullptr)
  159. {
  160. if (callback) callback(texture);
  161. return;
  162. }
  163. // check if file exists
  164. if (fullpath.empty() || !FileUtils::getInstance()->isFileExist(fullpath)) {
  165. if (callback) callback(nullptr);
  166. return;
  167. }
  168. // lazy init
  169. if (_loadingThread == nullptr)
  170. {
  171. // create a new thread to load images
  172. _loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
  173. _needQuit = false;
  174. }
  175. if (0 == _asyncRefCount)
  176. {
  177. Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false);
  178. }
  179. ++_asyncRefCount;
  180. // generate async struct
  181. AsyncStruct *data =
  182. new (std::nothrow) AsyncStruct(fullpath, callback, callbackKey);
  183. // add async struct into queue
  184. _asyncStructQueue.push_back(data);
  185. _requestMutex.lock();
  186. _requestQueue.push_back(data);
  187. _requestMutex.unlock();
  188. _sleepCondition.notify_one();
  189. }
  190. void TextureCache::unbindImageAsync(const std::string& callbackKey)
  191. {
  192. if (_asyncStructQueue.empty())
  193. {
  194. return;
  195. }
  196. for (auto& asyncStruct : _asyncStructQueue)
  197. {
  198. if (asyncStruct->callbackKey == callbackKey)
  199. {
  200. asyncStruct->callback = nullptr;
  201. }
  202. }
  203. }
  204. void TextureCache::unbindAllImageAsync()
  205. {
  206. if (_asyncStructQueue.empty())
  207. {
  208. return;
  209. }
  210. for (auto& asyncStruct : _asyncStructQueue)
  211. {
  212. asyncStruct->callback = nullptr;
  213. }
  214. }
  215. void TextureCache::loadImage()
  216. {
  217. AsyncStruct *asyncStruct = nullptr;
  218. std::mutex signalMutex;
  219. std::unique_lock<std::mutex> signal(signalMutex);
  220. while (!_needQuit)
  221. {
  222. // pop an AsyncStruct from request queue
  223. _requestMutex.lock();
  224. if (_requestQueue.empty())
  225. {
  226. asyncStruct = nullptr;
  227. }
  228. else
  229. {
  230. asyncStruct = _requestQueue.front();
  231. _requestQueue.pop_front();
  232. }
  233. _requestMutex.unlock();
  234. if (nullptr == asyncStruct) {
  235. _sleepCondition.wait(signal);
  236. continue;
  237. }
  238. // load image
  239. asyncStruct->loadSuccess = asyncStruct->image.initWithImageFileThreadSafe(asyncStruct->filename);
  240. // ETC1 ALPHA supports.
  241. if (asyncStruct->loadSuccess && asyncStruct->image.getFileType() == Image::Format::ETC && !s_etc1AlphaFileSuffix.empty())
  242. { // check whether alpha texture exists & load it
  243. auto alphaFile = asyncStruct->filename + s_etc1AlphaFileSuffix;
  244. if (FileUtils::getInstance()->isFileExist(alphaFile))
  245. asyncStruct->imageAlpha.initWithImageFileThreadSafe(alphaFile);
  246. }
  247. // push the asyncStruct to response queue
  248. _responseMutex.lock();
  249. _responseQueue.push_back(asyncStruct);
  250. _responseMutex.unlock();
  251. }
  252. }
  253. void TextureCache::addImageAsyncCallBack(float /*dt*/)
  254. {
  255. Texture2D *texture = nullptr;
  256. AsyncStruct *asyncStruct = nullptr;
  257. while (true)
  258. {
  259. // pop an AsyncStruct from response queue
  260. _responseMutex.lock();
  261. if (_responseQueue.empty())
  262. {
  263. asyncStruct = nullptr;
  264. }
  265. else
  266. {
  267. asyncStruct = _responseQueue.front();
  268. _responseQueue.pop_front();
  269. // the asyncStruct's sequence order in _asyncStructQueue must equal to the order in _responseQueue
  270. CC_ASSERT(asyncStruct == _asyncStructQueue.front());
  271. _asyncStructQueue.pop_front();
  272. }
  273. _responseMutex.unlock();
  274. if (nullptr == asyncStruct) {
  275. break;
  276. }
  277. // check the image has been convert to texture or not
  278. auto it = _textures.find(asyncStruct->filename);
  279. if (it != _textures.end())
  280. {
  281. texture = it->second;
  282. }
  283. else
  284. {
  285. // convert image to texture
  286. if (asyncStruct->loadSuccess)
  287. {
  288. Image* image = &(asyncStruct->image);
  289. // generate texture in render thread
  290. texture = new (std::nothrow) Texture2D();
  291. texture->initWithImage(image, asyncStruct->pixelFormat);
  292. //parse 9-patch info
  293. this->parseNinePatchImage(image, texture, asyncStruct->filename);
  294. #if CC_ENABLE_CACHE_TEXTURE_DATA
  295. // cache the texture file name
  296. VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename);
  297. #endif
  298. // cache the texture. retain it, since it is added in the map
  299. _textures.emplace(asyncStruct->filename, texture);
  300. texture->retain();
  301. texture->autorelease();
  302. // ETC1 ALPHA supports.
  303. if (asyncStruct->imageAlpha.getFileType() == Image::Format::ETC) {
  304. auto alphaTexture = new(std::nothrow) Texture2D();
  305. if(alphaTexture != nullptr && alphaTexture->initWithImage(&asyncStruct->imageAlpha, asyncStruct->pixelFormat)) {
  306. texture->setAlphaTexture(alphaTexture);
  307. }
  308. CC_SAFE_RELEASE(alphaTexture);
  309. }
  310. }
  311. else {
  312. texture = nullptr;
  313. CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str());
  314. }
  315. }
  316. // call callback function
  317. if (asyncStruct->callback)
  318. {
  319. (asyncStruct->callback)(texture);
  320. }
  321. // release the asyncStruct
  322. delete asyncStruct;
  323. --_asyncRefCount;
  324. }
  325. if (0 == _asyncRefCount)
  326. {
  327. Director::getInstance()->getScheduler()->unschedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this);
  328. }
  329. }
  330. Texture2D * TextureCache::addImage(const std::string &path)
  331. {
  332. Texture2D * texture = nullptr;
  333. Image* image = nullptr;
  334. // Split up directory and filename
  335. // MUTEX:
  336. // Needed since addImageAsync calls this method from a different thread
  337. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
  338. if (fullpath.size() == 0)
  339. {
  340. return nullptr;
  341. }
  342. auto it = _textures.find(fullpath);
  343. if (it != _textures.end())
  344. texture = it->second;
  345. if (!texture)
  346. {
  347. // all images are handled by UIImage except PVR extension that is handled by our own handler
  348. do
  349. {
  350. image = new (std::nothrow) Image();
  351. CC_BREAK_IF(nullptr == image);
  352. bool bRet = image->initWithImageFile(fullpath);
  353. CC_BREAK_IF(!bRet);
  354. texture = new (std::nothrow) Texture2D();
  355. if (texture && texture->initWithImage(image))
  356. {
  357. #if CC_ENABLE_CACHE_TEXTURE_DATA
  358. // cache the texture file name
  359. VolatileTextureMgr::addImageTexture(texture, fullpath);
  360. #endif
  361. // texture already retained, no need to re-retain it
  362. _textures.emplace(fullpath, texture);
  363. //-- ANDROID ETC1 ALPHA SUPPORTS.
  364. std::string alphaFullPath = path + s_etc1AlphaFileSuffix;
  365. if (image->getFileType() == Image::Format::ETC && !s_etc1AlphaFileSuffix.empty() && FileUtils::getInstance()->isFileExist(alphaFullPath))
  366. {
  367. Image alphaImage;
  368. if (alphaImage.initWithImageFile(alphaFullPath))
  369. {
  370. Texture2D *pAlphaTexture = new(std::nothrow) Texture2D;
  371. if(pAlphaTexture != nullptr && pAlphaTexture->initWithImage(&alphaImage)) {
  372. texture->setAlphaTexture(pAlphaTexture);
  373. }
  374. CC_SAFE_RELEASE(pAlphaTexture);
  375. }
  376. }
  377. //parse 9-patch info
  378. this->parseNinePatchImage(image, texture, path);
  379. }
  380. else
  381. {
  382. CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str());
  383. CC_SAFE_RELEASE(texture);
  384. texture = nullptr;
  385. }
  386. } while (0);
  387. }
  388. CC_SAFE_RELEASE(image);
  389. return texture;
  390. }
  391. void TextureCache::parseNinePatchImage(cocos2d::Image *image, cocos2d::Texture2D *texture, const std::string& path)
  392. {
  393. if (NinePatchImageParser::isNinePatchImage(path))
  394. {
  395. Rect frameRect = Rect(0, 0, image->getWidth(), image->getHeight());
  396. NinePatchImageParser parser(image, frameRect, false);
  397. texture->addSpriteFrameCapInset(nullptr, parser.parseCapInset());
  398. }
  399. }
  400. Texture2D* TextureCache::addImage(Image *image, const std::string &key)
  401. {
  402. CCASSERT(image != nullptr, "TextureCache: image MUST not be nil");
  403. CCASSERT(image->getData() != nullptr, "TextureCache: image MUST not be nil");
  404. Texture2D * texture = nullptr;
  405. do
  406. {
  407. auto it = _textures.find(key);
  408. if (it != _textures.end()) {
  409. texture = it->second;
  410. break;
  411. }
  412. texture = new (std::nothrow) Texture2D();
  413. if (texture)
  414. {
  415. if (texture->initWithImage(image))
  416. {
  417. _textures.emplace(key, texture);
  418. }
  419. else
  420. {
  421. CC_SAFE_RELEASE(texture);
  422. texture = nullptr;
  423. CCLOG("cocos2d: initWithImage failed!");
  424. }
  425. }
  426. else
  427. {
  428. CCLOG("cocos2d: Allocating memory for Texture2D failed!");
  429. }
  430. } while (0);
  431. #if CC_ENABLE_CACHE_TEXTURE_DATA
  432. VolatileTextureMgr::addImage(texture, image);
  433. #endif
  434. return texture;
  435. }
  436. bool TextureCache::reloadTexture(const std::string& fileName)
  437. {
  438. Texture2D * texture = nullptr;
  439. Image * image = nullptr;
  440. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(fileName);
  441. if (fullpath.size() == 0)
  442. {
  443. return false;
  444. }
  445. auto it = _textures.find(fullpath);
  446. if (it != _textures.end()) {
  447. texture = it->second;
  448. }
  449. bool ret = false;
  450. if (!texture) {
  451. texture = this->addImage(fullpath);
  452. ret = (texture != nullptr);
  453. }
  454. else
  455. {
  456. do {
  457. image = new (std::nothrow) Image();
  458. CC_BREAK_IF(nullptr == image);
  459. bool bRet = image->initWithImageFile(fullpath);
  460. CC_BREAK_IF(!bRet);
  461. ret = texture->initWithImage(image);
  462. } while (0);
  463. }
  464. CC_SAFE_RELEASE(image);
  465. return ret;
  466. }
  467. // TextureCache - Remove
  468. void TextureCache::removeAllTextures()
  469. {
  470. for (auto& texture : _textures) {
  471. texture.second->release();
  472. }
  473. _textures.clear();
  474. }
  475. void TextureCache::removeUnusedTextures()
  476. {
  477. for (auto it = _textures.cbegin(); it != _textures.cend(); /* nothing */) {
  478. Texture2D *tex = it->second;
  479. if (tex->getReferenceCount() == 1) {
  480. CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str());
  481. tex->release();
  482. it = _textures.erase(it);
  483. }
  484. else {
  485. ++it;
  486. }
  487. }
  488. }
  489. void TextureCache::removeTexture(Texture2D* texture)
  490. {
  491. if (!texture)
  492. {
  493. return;
  494. }
  495. for (auto it = _textures.cbegin(); it != _textures.cend(); /* nothing */) {
  496. if (it->second == texture) {
  497. it->second->release();
  498. it = _textures.erase(it);
  499. break;
  500. }
  501. else
  502. ++it;
  503. }
  504. }
  505. void TextureCache::removeTextureForKey(const std::string &textureKeyName)
  506. {
  507. std::string key = textureKeyName;
  508. auto it = _textures.find(key);
  509. if (it == _textures.end()) {
  510. key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
  511. it = _textures.find(key);
  512. }
  513. if (it != _textures.end()) {
  514. it->second->release();
  515. _textures.erase(it);
  516. }
  517. }
  518. Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const
  519. {
  520. std::string key = textureKeyName;
  521. auto it = _textures.find(key);
  522. if (it == _textures.end()) {
  523. key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
  524. it = _textures.find(key);
  525. }
  526. if (it != _textures.end())
  527. return it->second;
  528. return nullptr;
  529. }
  530. void TextureCache::reloadAllTextures()
  531. {
  532. //will do nothing
  533. // #if CC_ENABLE_CACHE_TEXTURE_DATA
  534. // VolatileTextureMgr::reloadAllTextures();
  535. // #endif
  536. }
  537. std::string TextureCache::getTextureFilePath(cocos2d::Texture2D* texture) const
  538. {
  539. for (auto& item : _textures)
  540. {
  541. if (item.second == texture)
  542. {
  543. return item.first;
  544. break;
  545. }
  546. }
  547. return "";
  548. }
  549. void TextureCache::waitForQuit()
  550. {
  551. // notify sub thread to quick
  552. _needQuit = true;
  553. _sleepCondition.notify_one();
  554. if (_loadingThread) _loadingThread->join();
  555. }
  556. std::string TextureCache::getCachedTextureInfo() const
  557. {
  558. std::string buffer;
  559. char buftmp[4096];
  560. unsigned int count = 0;
  561. unsigned int totalBytes = 0;
  562. for (auto& texture : _textures) {
  563. memset(buftmp, 0, sizeof(buftmp));
  564. Texture2D* tex = texture.second;
  565. unsigned int bpp = tex->getBitsPerPixelForFormat();
  566. // Each texture takes up width * height * bytesPerPixel bytes.
  567. auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
  568. totalBytes += bytes;
  569. count++;
  570. snprintf(buftmp, sizeof(buftmp) - 1, "\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
  571. texture.first.c_str(),
  572. (long)tex->getReferenceCount(),
  573. (long)tex->getName(),
  574. (long)tex->getPixelsWide(),
  575. (long)tex->getPixelsHigh(),
  576. (long)bpp,
  577. (long)bytes / 1024);
  578. buffer += buftmp;
  579. }
  580. snprintf(buftmp, sizeof(buftmp) - 1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
  581. buffer += buftmp;
  582. return buffer;
  583. }
  584. void TextureCache::renameTextureWithKey(const std::string& srcName, const std::string& dstName)
  585. {
  586. std::string key = srcName;
  587. auto it = _textures.find(key);
  588. if (it == _textures.end()) {
  589. key = FileUtils::getInstance()->fullPathForFilename(srcName);
  590. it = _textures.find(key);
  591. }
  592. if (it != _textures.end()) {
  593. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(dstName);
  594. Texture2D* tex = it->second;
  595. Image* image = new (std::nothrow) Image();
  596. if (image)
  597. {
  598. bool ret = image->initWithImageFile(dstName);
  599. if (ret)
  600. {
  601. tex->initWithImage(image);
  602. _textures.emplace(fullpath, tex);
  603. _textures.erase(it);
  604. }
  605. CC_SAFE_DELETE(image);
  606. }
  607. }
  608. }
  609. #if CC_ENABLE_CACHE_TEXTURE_DATA
  610. std::list<VolatileTexture*> VolatileTextureMgr::_textures;
  611. bool VolatileTextureMgr::_isReloading = false;
  612. VolatileTexture::VolatileTexture(Texture2D *t)
  613. : _texture(t)
  614. , _uiImage(nullptr)
  615. , _cashedImageType(kInvalid)
  616. , _textureData(nullptr)
  617. , _pixelFormat(Texture2D::PixelFormat::RGBA8888)
  618. , _fileName("")
  619. , _hasMipmaps(false)
  620. , _text("")
  621. {
  622. _texParams.minFilter = GL_LINEAR;
  623. _texParams.magFilter = GL_LINEAR;
  624. _texParams.wrapS = GL_CLAMP_TO_EDGE;
  625. _texParams.wrapT = GL_CLAMP_TO_EDGE;
  626. }
  627. VolatileTexture::~VolatileTexture()
  628. {
  629. CC_SAFE_RELEASE(_uiImage);
  630. }
  631. void VolatileTextureMgr::addImageTexture(Texture2D *tt, const std::string& imageFileName)
  632. {
  633. if (_isReloading)
  634. {
  635. return;
  636. }
  637. VolatileTexture *vt = findVolotileTexture(tt);
  638. vt->_cashedImageType = VolatileTexture::kImageFile;
  639. vt->_fileName = imageFileName;
  640. vt->_pixelFormat = tt->getPixelFormat();
  641. }
  642. void VolatileTextureMgr::addImage(Texture2D *tt, Image *image)
  643. {
  644. if (tt == nullptr || image == nullptr)
  645. return;
  646. VolatileTexture *vt = findVolotileTexture(tt);
  647. image->retain();
  648. vt->_uiImage = image;
  649. vt->_cashedImageType = VolatileTexture::kImage;
  650. }
  651. VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt)
  652. {
  653. VolatileTexture *vt = nullptr;
  654. for (const auto& texture : _textures)
  655. {
  656. VolatileTexture *v = texture;
  657. if (v->_texture == tt)
  658. {
  659. vt = v;
  660. break;
  661. }
  662. }
  663. if (!vt)
  664. {
  665. vt = new (std::nothrow) VolatileTexture(tt);
  666. _textures.push_back(vt);
  667. }
  668. return vt;
  669. }
  670. void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize)
  671. {
  672. if (_isReloading)
  673. {
  674. return;
  675. }
  676. VolatileTexture *vt = findVolotileTexture(tt);
  677. vt->_cashedImageType = VolatileTexture::kImageData;
  678. vt->_textureData = data;
  679. vt->_dataLen = dataLen;
  680. vt->_pixelFormat = pixelFormat;
  681. vt->_textureSize = contentSize;
  682. }
  683. void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition)
  684. {
  685. if (_isReloading)
  686. {
  687. return;
  688. }
  689. VolatileTexture *vt = findVolotileTexture(tt);
  690. vt->_cashedImageType = VolatileTexture::kString;
  691. vt->_text = text;
  692. vt->_fontDefinition = fontDefinition;
  693. }
  694. void VolatileTextureMgr::setHasMipmaps(Texture2D *t, bool hasMipmaps)
  695. {
  696. VolatileTexture *vt = findVolotileTexture(t);
  697. vt->_hasMipmaps = hasMipmaps;
  698. }
  699. void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams)
  700. {
  701. VolatileTexture *vt = findVolotileTexture(t);
  702. if (texParams.minFilter != GL_NONE)
  703. vt->_texParams.minFilter = texParams.minFilter;
  704. if (texParams.magFilter != GL_NONE)
  705. vt->_texParams.magFilter = texParams.magFilter;
  706. if (texParams.wrapS != GL_NONE)
  707. vt->_texParams.wrapS = texParams.wrapS;
  708. if (texParams.wrapT != GL_NONE)
  709. vt->_texParams.wrapT = texParams.wrapT;
  710. }
  711. void VolatileTextureMgr::removeTexture(Texture2D *t)
  712. {
  713. for (auto& item : _textures)
  714. {
  715. VolatileTexture *vt = item;
  716. if (vt->_texture == t)
  717. {
  718. _textures.remove(vt);
  719. delete vt;
  720. break;
  721. }
  722. }
  723. }
  724. void VolatileTextureMgr::reloadAllTextures()
  725. {
  726. _isReloading = true;
  727. // we need to release all of the glTextures to avoid collisions of texture id's when reloading the textures onto the GPU
  728. for (auto& item : _textures)
  729. {
  730. item->_texture->releaseGLTexture();
  731. }
  732. CCLOG("reload all texture");
  733. for (auto& texture : _textures)
  734. {
  735. VolatileTexture *vt = texture;
  736. switch (vt->_cashedImageType)
  737. {
  738. case VolatileTexture::kImageFile:
  739. {
  740. reloadTexture(vt->_texture, vt->_fileName, vt->_pixelFormat);
  741. // etc1 support check whether alpha texture exists & load it
  742. auto alphaFile = vt->_fileName + TextureCache::getETC1AlphaFileSuffix();
  743. reloadTexture(vt->_texture->getAlphaTexture(), alphaFile, vt->_pixelFormat);
  744. }
  745. break;
  746. case VolatileTexture::kImageData:
  747. {
  748. vt->_texture->initWithData(vt->_textureData,
  749. vt->_dataLen,
  750. vt->_pixelFormat,
  751. vt->_textureSize.width,
  752. vt->_textureSize.height,
  753. vt->_textureSize);
  754. }
  755. break;
  756. case VolatileTexture::kString:
  757. {
  758. vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition);
  759. }
  760. break;
  761. case VolatileTexture::kImage:
  762. {
  763. vt->_texture->initWithImage(vt->_uiImage);
  764. }
  765. break;
  766. default:
  767. break;
  768. }
  769. if (vt->_hasMipmaps) {
  770. vt->_texture->generateMipmap();
  771. }
  772. vt->_texture->setTexParameters(vt->_texParams);
  773. }
  774. _isReloading = false;
  775. }
  776. void VolatileTextureMgr::reloadTexture(Texture2D* texture, const std::string& filename, Texture2D::PixelFormat pixelFormat)
  777. {
  778. if (!texture)
  779. return;
  780. Image* image = new (std::nothrow) Image();
  781. Data data = FileUtils::getInstance()->getDataFromFile(filename);
  782. if (image && image->initWithImageData(data.getBytes(), data.getSize()))
  783. texture->initWithImage(image, pixelFormat);
  784. CC_SAFE_RELEASE(image);
  785. }
  786. #endif // CC_ENABLE_CACHE_TEXTURE_DATA
  787. NS_CC_END