CCTextureCache.cpp 27 KB

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