cocos2d-x学习路径
在Cocos2d-x开发中,了解其如何查找图片是非常重要的。下面我们将深入探究Cocos2d-x查找图片的具体过程,并通过关键部分的源码来详细分析。
1. 获取完整路径
在Cocos2d-x中,获取图片完整路径的关键代码如下:
pathKey = CCFileUtils::sharedFileUtils()->fullPathForFilename(pathKey.c_str());
fullPathForFilename 函数的定义如下:
/**
* Returns the fullpath for a given filename.
* First it will try to get a new filename from the "filenameLookup" dictionary.
* If a new filename can't be found on the dictionary, it will use the original filename.
* Then it will try to obtain the full path of the filename using the CCFileUtils search rules: resolutions, and search paths.
* The file search is based on the array element order of search paths and resolution directories.
*
* For instance:
* .....
*
* @since v2.1
*/
virtual std::string fullPathForFilename(const char* pszFileName);
该函数的主要功能是根据给定的文件名返回其完整路径。具体查找过程如下:
查找步骤
- 判断绝对路径:首先判断传入的路径是否已经是绝对路径,如果是则直接返回该路径。
- 缓存查询:从缓存中查询是否存在该资源的路径缓存(以传递的关键字作为key)。如果之前已经加载过该资源,就可以直接从缓存中获取其完整路径。
- 文件名查找字典匹配:如果在缓存中找不到,则从文件名查找字典中进行匹配。
- 查询路径数组匹配:若在文件名查找字典中也未找到,则会从查询路径数组中逐个进行匹配查找。
在这个过程中,我们会发现 m_searchPathArray 里已经存在了一个该项目目录下的 Resource 文件夹路径。这显然是在初始化的时候设置了默认路径,接下来我们继续追踪这个默认路径的设置过程。
2. 默认路径的设置
CCFileUtils 初始化
CCFileUtils 在初始化的时候会将默认资源路径添加到数组中,代码如下:
bool CCFileUtils::init()
{
m_searchPathArray.push_back(m_strDefaultResRootPath);
m_searchResolutionsOrderArray.push_back("");
return true;
}
查找 m_strDefaultResRootPath 的赋值位置
我们需要查找 m_strDefaultResRootPath 是在哪里赋值的。以Win32项目为例,在 CCFileUtilsWin32.cpp 的子类构造函数中可以找到相关代码:
bool CCFileUtilsWin32::init()
{
_checkPath();
m_strDefaultResRootPath = s_pszResourcePath;
return CCFileUtils::init();
}
static void _checkPath()
{
if (! s_pszResourcePath[0])
{
WCHAR wszPath[MAX_PATH] = {0};
int nNum = WideCharToMultiByte(CP_ACP, 0, wszPath,
GetCurrentDirectoryW(sizeof(wszPath), wszPath),
s_pszResourcePath, MAX_PATH, NULL, NULL);
s_pszResourcePath[nNum] = '\\';
}
}
在Win32平台下,通过 GetCurrentDirectoryW 这个Win32 API函数来获取当前的工作目录。当然,在其他平台也会有对应平台的获取方式。
项目属性中的工作目录设置
打开项目属性管理器面板,在调试子面板中可以发现,通过Cocos2d-x模板生成的项目,默认将工作目录设置为了 $(ProjectDir)..\\Resources。所以在调试时,得到的工作目录便是这个 Resources 文件夹。
3. 解决图片查找问题
如果在开发过程中遇到图片无法正常加载的问题,解决的办法就是将图片拷贝到exe所在的文件目录下。因为exe所在的目录就是当前工作目录,这样就可以匹配上图片路径,从而正常加载图片。
通过以上的分析,我们详细了解了Cocos2d-x查找图片的机制,这对于我们在开发过程中处理资源加载问题具有重要的指导意义。