cocos2d-x 3.0 取资源路径
在使用 cocos2d-x 3.0 开发项目时,可能会遇到这样的问题:项目在 VS 调试时能正常运行,但直接在生成目录执行 exe 文件却出现黑屏现象。经分析,这是由于资源文件加载问题导致的,程序找不到图片,所以才会黑屏。接下来,我们深入探讨 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文件夹路径,显然在初始化的时候设置了默认路径,下面我们继续追踪。
初始化默认资源路径
CCFileUtils 在初始化的时候会将默认资源路径 String 添加到数组中,代码如下:
bool CCFileUtils::init()
{
m_searchPathArray.push_back(m_strDefaultResRootPath);
m_searchResolutionsOrderArray.push_back("");
return true;
}
查找 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 平台,是通过 DWORD GetCurrentDirectoryW(DWORD nBufferLength, LPWSTR lpBuffer) 这个 win32 API 函数来获取当前的工作目录的,其他平台也会有对应的获取方式。
项目属性中的工作目录设置
打开项目属性管理器面板,进入调试子面板,会发现通过 cocos2d-x 模板生成的项目,默认将工作目录设置为了 $(ProjectDir)..\\Resources。所以在调试时,得到的工作目录便是这个 Resources 文件夹。
解决办法
综上所述,解决直接运行 exe 文件黑屏的办法是将图片拷贝到 exe 所在的文件目录下。因为 exe 所在的目录就是当前工作目录,这样程序就可以匹配到图片资源了。