分析cocos缓存管理的实现

前端之家收集整理的这篇文章主要介绍了分析cocos缓存管理的实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
今天看了一下cocos的缓存管理类,首先缓存管理类是一个单例对象,获得该对象的实例必须通过导演类Dirctor的Director::getInstance()->getTextureCache();其实这是一种挺不错的架构方式,通过一个在顶部的对象来获得引擎里面你需要的接口,这就屏蔽了实现的细节。题外话了,转入正题。cocos的纹理缓存管理包含了加载图片纹理的接口,删除纹理对象的接口,删除无用纹理对象的接口(纹理对象的引用计数值为1),获得纹理缓存大小的接口,重新加载纹理对象的接口。在加载纹理对象的接口当中包含了异步加载和普通加载。异步加载是使用了线程机制把图片放入缓存里面,然后在加载完成以后会调用用户传进来的函数,这个机制可以实现加载进度条的实现。在异步加载中loadimage是一直阻塞的(使用了条件变量),只有当需要加载图片或者是调用了导演类的purgeDirector的时候才会被唤醒。普通加载就是直接把纹理对象放入缓存里面。异步加载与普通加载的接口分别是addImageAsync,addImage,其中异步加载可以传用户自定义函数,但加载完成会回调该函数。其余的在下面的代码将详细的注释讲解: ”’c++ NS_CC_BEGIN //单例模式实现纹理缓存 TextureCache * TextureCache::getInstance() { return Director::getInstance()->getTextureCache(); } TextureCache::TextureCache()

_loadingThread(nullptr) @H_301_4@,_asyncStructQueue(nullptr) @H_301_4@,_imageInfoQueue(nullptr) @H_301_4@,_needQuit(false) @H_301_4@,_asyncRefCount(0) @H_301_4@ { @H_301_4@ } @H_301_4@ TextureCache::~TextureCache() @H_301_4@ { @H_301_4@ CCLOGINFO(“deallocing TextureCache: %p”,this); @H_301_4@ //在析构函数里面释放map里面保存的指针, @H_301_4@ //防止内存泄露 @H_301_4@ for( auto it=_textures.begin(); it!=_textures.end(); ++it) @H_301_4@ (it->second)->release(); @H_301_4@ CC_SAFE_DELETE(_loadingThread); @H_301_4@ } @H_301_4@ void TextureCache::destroyInstance() @H_301_4@ { @H_301_4@ } @H_301_4@ //获得纹理缓存的对象其实还是从导演类获得 @H_301_4@ TextureCache * TextureCache::sharedTextureCache() @H_301_4@ { @H_301_4@ return Director::getInstance()->getTextureCache(); @H_301_4@ } @H_301_4@ //已抛弃,使用destroyInstance @H_301_4@ void TextureCache::purgeSharedTextureCache() @H_301_4@ { @H_301_4@ } @H_301_4@ //获得缓存的大小 @H_301_4@ std::string TextureCache::getDescription() const @H_301_4@ { @H_301_4@ return StringUtils::format(“

if CC_ENABLE_CACHE_TEXTURE_DATA

// cache the texture file name
        VolatileTextureMgr::addImageTexture(texture,filename);

endif

//加入到map里面存储起来 @H_301_4@ // cache the texture. retain it,since it is added in the map @H_301_4@ _textures.insert( std::make_pair(filename,texture) ); @H_301_4@ texture->retain(); @H_301_4@ texture->autorelease(); @H_301_4@ } @H_301_4@ else @H_301_4@ { @H_301_4@ //已经在缓存里面,从map里面取出 @H_301_4@ auto it = _textures.find(asyncStruct->filename); @H_301_4@ if(it != _textures.end()) @H_301_4@ texture = it->second; @H_301_4@ } @H_301_4@ //表示图片已经加载成功,回调用户传进来的用户函数 @H_301_4@ if (asyncStruct->callback) @H_301_4@ { @H_301_4@ asyncStruct->callback(texture); @H_301_4@ } @H_301_4@ //如果image不为空则释放image对象 @H_301_4@ if(image) @H_301_4@ { @H_301_4@ image->release(); @H_301_4@ } @H_301_4@ delete asyncStruct; @H_301_4@ delete imageInfo; @H_301_4@ //已经加载的图片后则把引用计数减1 @H_301_4@ –_asyncRefCount; @H_301_4@ //当所有图片已经完成加载则停止执行计数器函数 @H_301_4@ if (0 == _asyncRefCount) @H_301_4@ { @H_301_4@ Director::getInstance()->getScheduler()->unschedule(schedule_selector(TextureCache::addImageAsyncCallBack),this); @H_301_4@ } @H_301_4@ } @H_301_4@ } @H_301_4@ //普通加载函数重路径加载 @H_301_4@ //判断图片是否在缓存里面,如果不在则重新 @H_301_4@ //生成纹理对象,并把纹理对象放入缓存里面,否则直接重缓存里面取出 @H_301_4@ Texture2D * TextureCache::addImage(const std::string &path) @H_301_4@ { @H_301_4@ Texture2D * texture = nullptr; @H_301_4@ Image* image = nullptr; @H_301_4@ // Split up directory and filename @H_301_4@ // MUTEX: @H_301_4@ // Needed since addImageAsync calls this method from a different thread @H_301_4@ std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path); @H_301_4@ if (fullpath.size() == 0) @H_301_4@ { @H_301_4@ return nullptr; @H_301_4@ } @H_301_4@ auto it = _textures.find(fullpath); @H_301_4@ if( it != _textures.end() ) @H_301_4@ texture = it->second; @H_301_4@ if (! texture) @H_301_4@ { @H_301_4@ // all images are handled by UIImage except PVR extension that is handled by our own handler @H_301_4@ do @H_301_4@ { @H_301_4@ image = new Image(); @H_301_4@ CC_BREAK_IF(nullptr == image); @H_301_4@ bool bRet = image->initWithImageFile(fullpath); @H_301_4@ CC_BREAK_IF(!bRet); @H_301_4@ texture = new Texture2D(); @H_301_4@ if( texture && texture->initWithImage(image) ) @H_301_4@ {

if CC_ENABLE_CACHE_TEXTURE_DATA

// cache the texture file name
            VolatileTextureMgr::addImageTexture(texture,fullpath);

endif

// texture already retained,no need to re-retain it
            _textures.insert( std::make_pair(fullpath,texture) );
        }
        else
        {
            CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache",path.c_str());
        }
    } while (0);
}
CC_SAFE_RELEASE(image);
return texture;

} @H_301_4@ //根据传进的Key值判断是否在缓存里面,在的话直接返回纹理对象 @H_301_4@ //否则重新生成纹理对象并放入缓存里面 @H_301_4@ Texture2D* TextureCache::addImage(Image *image,const std::string &key) @H_301_4@ { @H_301_4@ CCASSERT(image != nullptr,“TextureCache: image MUST not be nil”); @H_301_4@ Texture2D * texture = nullptr; @H_301_4@ do @H_301_4@ { @H_301_4@ auto it = _textures.find(key); @H_301_4@ if( it != _textures.end() ) { @H_301_4@ texture = it->second; @H_301_4@ break; @H_301_4@ } @H_301_4@ // prevents overloading the autorelease pool @H_301_4@ texture = new Texture2D(); @H_301_4@ texture->initWithImage(image); @H_301_4@ if(texture) @H_301_4@ { @H_301_4@ _textures.insert( std::make_pair(key,texture) ); @H_301_4@ texture->retain(); @H_301_4@ texture->autorelease(); @H_301_4@ } @H_301_4@ else @H_301_4@ { @H_301_4@ CCLOG(“cocos2d: Couldn’t add UIImage in TextureCache”); @H_301_4@ } @H_301_4@ } while (0);

if CC_ENABLE_CACHE_TEXTURE_DATA

VolatileTextureMgr::addImage(texture,image);

endif

return texture;

} @H_301_4@ //重新加载纹理成功返回true,否则false @H_301_4@ bool TextureCache::reloadTexture(const std::string& fileName) @H_301_4@ { @H_301_4@ Texture2D * texture = nullptr; @H_301_4@ std::string fullpath = FileUtils::getInstance()->fullPathForFilename(fileName); @H_301_4@ if (fullpath.size() == 0) @H_301_4@ { @H_301_4@ return false; @H_301_4@ } @H_301_4@ auto it = _textures.find(fullpath); @H_301_4@ if (it != _textures.end()) { @H_301_4@ texture = it->second; @H_301_4@ } @H_301_4@ //当传进来的路径的纹理不在缓存里面则调用addImage @H_301_4@ //放入缓存里面,否则重新生成纹理对象的图片信息 @H_301_4@ bool ret = false; @H_301_4@ if (! texture) { @H_301_4@ texture = this->addImage(fullpath); @H_301_4@ ret = (texture != nullptr); @H_301_4@ } @H_301_4@ else @H_301_4@ { @H_301_4@ do { @H_301_4@ Image* image = new Image(); @H_301_4@ CC_BREAK_IF(nullptr == image); @H_301_4@ bool bRet = image->initWithImageFile(fullpath); @H_301_4@ CC_BREAK_IF(!bRet);

ret = texture->initWithImage(image);
    } while (0);
}
return ret;

} @H_301_4@ // TextureCache - Remove @H_301_4@ //重缓存里面删除所有的纹理对象 @H_301_4@ void TextureCache::removeAllTextures() @H_301_4@ { @H_301_4@ for( auto it=_textures.begin(); it!=_textures.end(); ++it ) { @H_301_4@ (it->second)->release(); @H_301_4@ } @H_301_4@ _textures.clear(); @H_301_4@ } @H_301_4@ //根据纹理对象的引用计数值,当为1时删除该纹理对象 @H_301_4@ void TextureCache::removeUnusedTextures() @H_301_4@ { @H_301_4@ for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */) { @H_301_4@ Texture2D *tex = it->second; @H_301_4@ if( tex->getReferenceCount() == 1 ) { @H_301_4@ CCLOG(“cocos2d: TextureCache: removing unused texture: %s”,it->first.c_str()); @H_301_4@ tex->release(); @H_301_4@ _textures.erase(it++); @H_301_4@ } else { @H_301_4@ ++it; @H_301_4@ } @H_301_4@ } @H_301_4@ } @H_301_4@ //重存储缓存的map里面取出对于的纹理对象并释放该对象 @H_301_4@ void TextureCache::removeTexture(Texture2D* texture) @H_301_4@ { @H_301_4@ if( ! texture ) @H_301_4@ { @H_301_4@ return; @H_301_4@ } @H_301_4@ for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */ ) { @H_301_4@ if( it->second == texture ) { @H_301_4@ texture->release(); @H_301_4@ _textures.erase(it++); @H_301_4@ break; @H_301_4@ } else @H_301_4@ ++it; @H_301_4@ } @H_301_4@ } @H_301_4@ //根据Key值删除纹理对象 @H_301_4@ void TextureCache::removeTextureForKey(const std::string &textureKeyName) @H_301_4@ { @H_301_4@ std::string key = textureKeyName; @H_301_4@ auto it = _textures.find(key); @H_301_4@ //如果没有在缓存里面找到则重新获得该纹理对象的真实路径值在寻找一遍 @H_301_4@ if( it == _textures.end() ) { @H_301_4@ key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); @H_301_4@ it = _textures.find(key); @H_301_4@ } @H_301_4@ //如果寻找到该对象则删除,否则不做处理 @H_301_4@ if( it != _textures.end() ) { @H_301_4@ (it->second)->release(); @H_301_4@ _textures.erase(it); @H_301_4@ } @H_301_4@ } @H_301_4@ //根据Key获得纹理对象 @H_301_4@ Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const @H_301_4@ { @H_301_4@ std::string key = textureKeyName; @H_301_4@ auto it = _textures.find(key); @H_301_4@ //如果没有找到纹理对象,则取出纹理对象的路径,在寻找一遍 @H_301_4@ if( it == _textures.end() ) { @H_301_4@ key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); @H_301_4@ it = _textures.find(key); @H_301_4@ } @H_301_4@ //找到后则返回 @H_301_4@ if( it != _textures.end() ) @H_301_4@ return it->second; @H_301_4@ return nullptr; @H_301_4@ } @H_301_4@ //不做任何事情 @H_301_4@ void TextureCache::reloadAllTextures() @H_301_4@ { @H_301_4@ //will do nothing @H_301_4@ // #if CC_ENABLE_CACHE_TEXTURE_DATA @H_301_4@ // VolatileTextureMgr::reloadAllTextures(); @H_301_4@ // #endif @H_301_4@ } @H_301_4@ //由diretor调用线程loadiamg线程将会跑完 @H_301_4@ void TextureCache::waitForQuit() @H_301_4@ { @H_301_4@ // notify sub thread to quick @H_301_4@ _needQuit = true; @H_301_4@ _sleepCondition.notify_one(); @H_301_4@ if (_loadingThread) _loadingThread->join(); @H_301_4@ } @H_301_4@ //获得所有缓存的大小 @H_301_4@ std::string TextureCache::getCachedTextureInfo() const @H_301_4@ { @H_301_4@ std::string buffer; @H_301_4@ char buftmp[4096]; @H_301_4@ unsigned int count = 0; @H_301_4@ unsigned int totalBytes = 0; @H_301_4@ // 遍历map获得所有的缓存内存信息 @H_301_4@ for( auto it = _textures.begin(); it != _textures.end(); ++it ) { @H_301_4@ memset(buftmp,sizeof(buftmp)); @H_301_4@ Texture2D* tex = it->second; @H_301_4@ unsigned int bpp = tex->getBitsPerPixelForFormat(); @H_301_4@ // Each texture takes up width * height * bytesPerPixel bytes. @H_301_4@ auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; @H_301_4@ totalBytes += bytes; @H_301_4@ count++; @H_301_4@ snprintf(buftmp,sizeof(buftmp)-1,”\”%s\” rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n”,@H_301_4@ it->first.c_str(),@H_301_4@ (long)tex->getReferenceCount(),@H_301_4@ (long)tex->getName(),@H_301_4@ (long)tex->getPixelsWide(),@H_301_4@ (long)tex->getPixelsHigh(),@H_301_4@ (long)bpp,@H_301_4@ (long)bytes / 1024);

buffer += buftmp;
}
snprintf(buftmp,"TextureCache dumpDebugInfo: %ld textures,for %lu KB (%.2f MB)\n",(long)count,(long)totalBytes / 1024,totalBytes / (1024.0f*1024.0f));
buffer += buftmp;
return buffer;

} @H_301_4@ //这段代码是查阅了相关的资料得知android wp8在程序切入后台时会使得纹理失效,所以cocos在游戏切入后台时会把纹理缓存起来,在程序恢复时在重新加载内存。好像这样会出现游戏从后台恢复到前台会黑屏的现象,是因为后台纹理太多了,恢复纹理需要一定的时间,所以感觉就黑屏卡主的感觉。解决方案:参考http://www.jb51.cc/article/p-yldmzkog-kx.html

if CC_ENABLE_CACHE_TEXTURE_DATA

std::list VolatileTextureMgr::_textures;
bool VolatileTextureMgr::_isReloading = false;
VolatileTexture::VolatileTexture(Texture2D *t)

_texture(t) @H_301_4@,_cashedImageType(kInvalid) @H_301_4@,_textureData(nullptr) @H_301_4@,_pixelFormat(Texture2D::PixelFormat::RGBA8888) @H_301_4@,_fileName(“”) @H_301_4@,_text(“”) @H_301_4@,_uiImage(nullptr) @H_301_4@,_hasMipmaps(false) @H_301_4@ { @H_301_4@ _texParams.minFilter = GL_LINEAR; @H_301_4@ _texParams.magFilter = GL_LINEAR; @H_301_4@ _texParams.wrapS = GL_CLAMP_TO_EDGE; @H_301_4@ _texParams.wrapT = GL_CLAMP_TO_EDGE; @H_301_4@ } @H_301_4@ VolatileTexture::~VolatileTexture() @H_301_4@ { @H_301_4@ CC_SAFE_RELEASE(_uiImage); @H_301_4@ } @H_301_4@ //从图片中加载 @H_301_4@ void VolatileTextureMgr::addImageTexture(Texture2D *tt,const std::string& imageFileName) @H_301_4@ { @H_301_4@ if (_isReloading) @H_301_4@ { @H_301_4@ return; @H_301_4@ } @H_301_4@ VolatileTexture *vt = findVolotileTexture(tt); @H_301_4@ vt->_cashedImageType = VolatileTexture::kImageFile; @H_301_4@ vt->_fileName = imageFileName; @H_301_4@ vt->_pixelFormat = tt->getPixelFormat(); @H_301_4@ } @H_301_4@ //从纹理对象中加载 @H_301_4@ void VolatileTextureMgr::addImage(Texture2D *tt,Image *image) @H_301_4@ { @H_301_4@ VolatileTexture *vt = findVolotileTexture(tt); @H_301_4@ image->retain(); @H_301_4@ vt->_uiImage = image; @H_301_4@ vt->_cashedImageType = VolatileTexture::kImage; @H_301_4@ } @H_301_4@ //寻找该纹理对象是否在缓存里面如不在则重新生成VolatileTexture 对象并放入缓存里面 @H_301_4@ VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt) @H_301_4@ { @H_301_4@ VolatileTexture *vt = 0; @H_301_4@ auto i = _textures.begin(); @H_301_4@ while (i != _textures.end()) @H_301_4@ { @H_301_4@ VolatileTexture *v = *i++; @H_301_4@ if (v->_texture == tt) @H_301_4@ { @H_301_4@ vt = v; @H_301_4@ break; @H_301_4@ } @H_301_4@ }

if (! vt) @H_301_4@ { @H_301_4@ vt = new VolatileTexture(tt); @H_301_4@ _textures.push_back(vt); @H_301_4@ }

return vt; @H_301_4@ } @H_301_4@ //从纹理数据加载 @H_301_4@ void VolatileTextureMgr::addDataTexture(Texture2D tt,void data,int dataLen,Texture2D::PixelFormat pixelFormat,const Size& contentSize) @H_301_4@ { @H_301_4@ if (_isReloading) @H_301_4@ { @H_301_4@ return; @H_301_4@ } @H_301_4@ VolatileTexture *vt = findVolotileTexture(tt); @H_301_4@ vt->_cashedImageType = VolatileTexture::kImageData; @H_301_4@ vt->_textureData = data; @H_301_4@ vt->_dataLen = dataLen; @H_301_4@ vt->_pixelFormat = pixelFormat; @H_301_4@ vt->_textureSize = contentSize; @H_301_4@ } @H_301_4@ //加载字体纹理 @H_301_4@ void VolatileTextureMgr::addStringTexture(Texture2D tt,const char text,const FontDefinition& fontDefinition) @H_301_4@ { @H_301_4@ if (_isReloading) @H_301_4@ { @H_301_4@ return; @H_301_4@ } @H_301_4@ VolatileTexture *vt = findVolotileTexture(tt); @H_301_4@ vt->_cashedImageType = VolatileTexture::kString; @H_301_4@ vt->_text = text; @H_301_4@ vt->_fontDefinition = fontDefinition; @H_301_4@ } @H_301_4@ //设置多重纹理 @H_301_4@ void VolatileTextureMgr::setHasMipmaps(Texture2D *t,bool hasMipmaps) @H_301_4@ { @H_301_4@ VolatileTexture *vt = findVolotileTexture(t); @H_301_4@ vt->_hasMipmaps = hasMipmaps; @H_301_4@ } @H_301_4@ //设置纹理参数 @H_301_4@ void VolatileTextureMgr::setTexParameters(Texture2D *t,const Texture2D::TexParams &texParams) @H_301_4@ { @H_301_4@ VolatileTexture *vt = findVolotileTexture(t); @H_301_4@ if (texParams.minFilter != GL_NONE) @H_301_4@ vt->_texParams.minFilter = texParams.minFilter; @H_301_4@ if (texParams.magFilter != GL_NONE) @H_301_4@ vt->_texParams.magFilter = texParams.magFilter; @H_301_4@ if (texParams.wrapS != GL_NONE) @H_301_4@ vt->_texParams.wrapS = texParams.wrapS; @H_301_4@ if (texParams.wrapT != GL_NONE) @H_301_4@ vt->_texParams.wrapT = texParams.wrapT; @H_301_4@ } @H_301_4@ //从缓存表中删除该纹理对象 @H_301_4@ void VolatileTextureMgr::removeTexture(Texture2D *t) @H_301_4@ { @H_301_4@ auto i = _textures.begin(); @H_301_4@ while (i != _textures.end()) @H_301_4@ { @H_301_4@ VolatileTexture *vt = *i++; @H_301_4@ if (vt->_texture == t) @H_301_4@ { @H_301_4@ _textures.remove(vt); @H_301_4@ delete vt; @H_301_4@ break; @H_301_4@ } @H_301_4@ } @H_301_4@ } @H_301_4@ //重新载入所有的纹理对象 @H_301_4@ void VolatileTextureMgr::reloadAllTextures() @H_301_4@ { @H_301_4@ _isReloading = true; @H_301_4@ CCLOG(“reload all texture”); @H_301_4@ auto iter = _textures.begin(); @H_301_4@ while (iter != _textures.end()) @H_301_4@ { @H_301_4@ VolatileTexture *vt = *iter++; @H_301_4@ switch (vt->_cashedImageType) @H_301_4@ { @H_301_4@ case VolatileTexture::kImageFile: @H_301_4@ { @H_301_4@ Image* image = new Image();

Data data = FileUtils::getInstance()->getDataFromFile(vt->_fileName);

        if (image && image->initWithImageData(data.getBytes(),data.getSize()))
        {
            Texture2D::PixelFormat oldPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
            Texture2D::setDefaultAlphaPixelFormat(vt->_pixelFormat);
            vt->_texture->initWithImage(image);
            Texture2D::setDefaultAlphaPixelFormat(oldPixelFormat);
        }

        CC_SAFE_RELEASE(image);
    }
    break;
case VolatileTexture::kImageData:
    {
        vt->_texture->initWithData(vt->_textureData,vt->_dataLen,vt->_pixelFormat,vt->_textureSize.width,vt->_textureSize.height,vt->_textureSize);
    }
    break;
case VolatileTexture::kString:
    {
        vt->_texture->initWithString(vt->_text.c_str(),vt->_fontDefinition);
    }
    break;
case VolatileTexture::kImage:
    {
        vt->_texture->initWithImage(vt->_uiImage);
    }
    break;
default:
    break;
}
if (vt->_hasMipmaps) {
    vt->_texture->generateMipmap();
}
vt->_texture->setTexParameters(vt->_texParams);

} @H_301_4@ _isReloading = false; @H_301_4@ }

endif // CC_ENABLE_CACHE_TEXTURE_DATA

NS_CC_END @H_301_4@ “` @H_301_4@ 参考:http://www.jb51.cc/article/p-yldmzkog-kx.html

猜你在找的Cocos2d-x相关文章