Cocos2D-x , CCTextureCache的多线程加载原理和使用方法

本文介绍了一个在Cocos2d-x中实现纹理异步加载的方法,通过创建后台线程加载图片并将其转化为纹理,有效提升了游戏启动速度和资源加载效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在查阅资料学习的时候,看到一个texture的异步加载,觉得挺有用的所以将具体的原理和使用方法分享出来,后面大家根据浏览器的特性可以做相应修改移植。
void CCTextureCache::addImageAsync(const char *path, CCObject *target, SEL_CallFuncO selector)
{
CCAssert(path != NULL, “TextureCache: fileimage MUST not be NULL”);

CCTexture2D *texture = NULL;

// 优化

std::string pathKey = path;
CCFileUtils::ccRemoveHDSuffixFromFile(pathKey);

pathKey = CCFileUtils::fullPathFromRelativePath(pathKey.c_str());
texture = m_pTextures->objectForKey(pathKey);
//根据pathkey查看是否纹理已经加载过,如果已经有了,则不重复加载

std::string fullpath = pathKey;
if (texture != NULL)
{
if (target && selector)
{
(target->*selector)(texture);
}

return;
}
if (target)
{
target->retain();
}

// lazy init
static bool firstRun = true;
if (firstRun)
{
s_pAsyncStructQueue = new queue<asyncstruct>();
s_pImageQueue = new queue<imageinfo>();

pthread_mutex_init(&s_asyncStructQueueMutex, NULL);
sem_init(&s_sem, 0, 0);
pthread_mutex_init(&s_ImageInfoMutex, NULL);
pthread_create(&s_loadingThread, NULL, loadImage, NULL);
//创建新的线程,用于后台加载图片

//创建调度队列,用来根据已加载的图片进行纹理转换
CCScheduler::sharedScheduler()->scheduleSelector(schedule_selector(CCTextureCache::addImageAsyncCallBack), this, 0, false);
need_quit = false;
firstRun = false;
}

// 生成异步结构
AsyncStruct *data = new AsyncStruct();
data->filename = fullpath.c_str();
data->target = target;
data->selector = selector;

// 添加到队列异步结构
pthread_mutex_lock(&s_asyncStructQueueMutex);
s_pAsyncStructQueue->push(data); //将需要加载的图片放入队列中
pthread_mutex_unlock(&s_asyncStructQueueMutex);

sem_post(&s_sem);
}


从上述代码分析可以看出其过程:

1.创建线程,用于后台加载

2. 将对于需要加载的图片放入队列中
       3. callback函数设定,用于将加载完成的图片转为纹理,等待使用其调用是由CCTimer::update调用的。
       4. addImageAsyncCallBack函数在处理完纹理转换,还会调用addImageAsync传入的SEL_CallFuncO selector,实现用户加载图片纹理之后的具体处理。
使用例子:
CCTextureCache::sharedTextureCache()->addImageAsync(“Images/blocks.png”, this, callfuncO_selector(TextureCacheTest::loadingCallBack));
loadingCallBack函数就是使用异步加载完之后的用户可以自处理结果,比如初始化一个sprite,用这个纹理贴出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值