开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情
在cocos2dx中,使用图片资源,因为有搜索路径的存在,所以资源路径有很多种写法,比如有搜索路径res, 那么1.png、res/1.png的写法是等价的。
我们知道engine会缓存已经加载过的图片资源,当再次使用这个资源的时候,会从缓存中查找。
从缓存中查找的key,是资源的完整绝对路径,这样搜索路径导致的各种不同的资源路径写法,就不会出现从缓存中找不到的问题,也保证了同一个资源在这个engine中只存在一份。
下边是自己写的校验逻辑,查询纹理中是否存在相同路径的资源。
void TextureCache::checkRepeatTexture()
{
std::map< string, vector<string>> maps;
for (auto it = this->_textures.begin(); it != this->_textures.end(); it++)
{
string key = it->first;
TexInfo* info = it->second;
string fileFullPath = info->Tex->getPath();
if (!fileFullPath.empty())
{
if (maps.find(fileFullPath) == maps.end())
{
maps[fileFullPath] = { key };
}
else{
// repeat texture
maps[fileFullPath].push_back(key);
}
}
}
std::map< string, vector<string>> repeatInfo;
for (auto map : maps)
{
if (map.second.size() > 1)
{
repeatInfo[map.first] = map.second;
}
}
int size = repeatInfo.size();
if (size > 0)
{
cocos2d::log("\nrepead count: %d", size);
for (auto info : repeatInfo)
{
cocos2d::log("\n[%d] file:%s", info.second.size(), info.first.c_str());
for (auto item : info.second)
{
cocos2d::log("-> %s", item.c_str());
}
cocos2d::log("\n");
}
cocos2d::log("\n");
}
}
实际测试发现,纹理中并没有出现多个相同资源的情况。
纹理中有些并没有对应的本地资源,它是由内存生成的纹理,比如有一个2x2像素的白色图片,这个纹理就是engine自己生成的,并没有实际对应的本地资源。
engine支持的纹理格式有:RGBA8888、RGB888、RGB565、RGBA4444、RGB5A1、AI88、A8、I8、PVRTC4、PVRTC2、PVRTC2A、PVRTC4A、ETC、S3TC_DXT1、S3TC_DXT3、S3TC_DXT5、ATC_RGB、ATC_EXPLICIT_ALPHA、ATC_INTERPOLATED_ALPHA、ASTC4x4、ASTC5x5、ASTC6x6、ASTC8x5、ASTC8x6、ASTC8x8、ASTC10x5、ASTC_RGBA。
支持的格式非常多,其中ASTC是creator才支持的,移植到2dx的,经常使用的还是RGB、PVR,其他格式不经常使用。