3.1 自定义资源类型
卷三讲过 Mesh、Material、Texture 这些资源类怎么被引擎使用,这一节换到自定义资源那一侧——如果我想让 OGRE 认识一种全新的资源,该实现什么。OGRE 的回答是两件套:一个 Resource 子类管「这个资源怎么从数据变成可用的对象」,一个 ResourceManager 子类管「这个资源怎么被创建、登记、按名查询」。资源加载的整个状态机就定义在 OgreResource.h 里,而管理器的核心逻辑定义在 OgreResourceManager.cpp 里。
先看状态机。OGRE 用一个六态枚举描述资源从出生到退役的全部加载阶段:
// OgreMain/include/OgreResource.h:LoadingState(v14.6.3 源码摘录,已删减)
/// Enum identifying the loading state of the resource
enum LoadingState
{
/// Not loaded
LOADSTATE_UNLOADED,
/// Loading is in progress
LOADSTATE_LOADING,
/// Fully loaded
LOADSTATE_LOADED,
/// Currently unloading
LOADSTATE_UNLOADING,
/// Fully prepared
LOADSTATE_PREPARED,
/// Preparing is in progress
LOADSTATE_PREPARING
};
六个状态可以画成两条轴:prepare 轴(UNLOADED → PREPARING → PREPARED)和 load 轴(PREPARED → LOADING → LOADED)。为什么拆两段?头文件里对 prepare 的注释解释得很清楚:prepare 允许后台线程做「不碰渲染系统」的加载工作,load 留到主渲染线程做「需要渲染系统」的最后一步。这样背景线程把耗时的大头干完,主线程只剩轻活,帧率不受影响。
本章与站内既有内容的分工
卷二/卷三的渲染章节从消费侧讲 Material、Texture、Mesh 怎么被场景使用;本卷第 3 章回到引擎内部分层,讲自定义资源/存档/编解码器三块扩展面。3.1 聚焦 Resource + ResourceManager 这个最小两件套——这是第 4 章脚本编译(用 ScriptCompilerManager 加载 .material 等脚本资源)和第 10 章后台加载的基础。
Resource 子类:状态机怎么推进
prepare 和 load 的虚方法声明带着完整的行为契约:
// OgreMain/include/OgreResource.h:prepare / load(v14.6.3 源码摘录,已删减)
virtual void prepare(bool backgroundThread = false);
/** Loads the resource, if it is not already.
If the resource is loaded from a file, loading is automatic. If not,
if for example this resource gained it's data from procedural calls
rather than loading from a file, then this resource will not reload
on it's own.
@param backgroundThread Indicates whether the caller of this method is
the background resource loading thread.
*/
virtual void load(bool backgroundThread = false);
prepare 与 load 都接受一个 backgroundThread 参数:为 true 时表示调用方是后台资源加载线程。头文件注释强调一个组合策略——后台线程调 prepare、主渲染循环稍后调 load,只要 prepare 保持线程安全,子类就可以任意地把加载工作拆到两个阶段之间。实践建议是「尽量在 prepare 里多做」,让主线程的 load 越短越好。
作为 Resource 子类,你真正必须实现的只有三件事:prepareImpl、loadImpl、unloadImpl。其中 loadImpl 是纯虚——每个资源类型的「解析逻辑」都不同(Mesh 读顶点/索引,Material 读渲染状态,你的自定义类型读你自己的数据格式),而状态推进是共用的,放在基类里。
ResourceManager 子类:句柄分配与登记
资源不会自己跑到引擎里,得有个管理器负责创建。管理器基类把「分配句柄、登记、去重」这些通用流程写好,只留一个 createImpl 纯虚方法让子类决定具体造哪种 Resource:
// OgreMain/src/OgreResourceManager.cpp:createResource / createOrRetrieve(v14.6.3 源码摘录,已删减)
ResourcePtr ResourceManager::createResource(const String& name, const String& group,
bool isManual, ManualResourceLoader* loader, const NameValuePairList* params)
{
OgreAssert(!name.empty(), "resource name must not be empty");
// Call creation implementation
ResourcePtr ret = ResourcePtr(
createImpl(name, getNextHandle(), group, isManual, loader, params));
if (params)
ret->setParameterList(*params);
addImpl(ret);
// Tell resource group manager
if(ret)
ResourceGroupManager::getSingleton()._notifyResourceCreated(ret);
return ret;
}
//-----------------------------------------------------------------------
ResourceManager::ResourceCreateOrRetrieveResult
ResourceManager::createOrRetrieve(
const String& name, const String& group,
bool isManual, ManualResourceLoader* loader,
const NameValuePairList* params)
{
// Lock for the whole get / insert
OGRE_LOCK_AUTO_MUTEX;
ResourcePtr res = getResourceByName(name, group);
bool created = false;
if (!res)
{
created = true;
res = createResource(name, group, isManual, loader, params);
}
return ResourceCreateOrRetrieveResult(res, created);
}
createResource 的流程可以拆成四步:
- 断言名字非空。
- 调
createImpl,并传入getNextHandle()分配的句柄。mNextHandle从 1 开始递增(构造函数mNextHandle(1),getNextHandle原子递增、不回滚——即便这次登记失败,句柄也消耗掉了)。 addImpl登记:按资源组放入mResources(全局池)或mResourcesWithGroup(分组池),用emplace处理同名冲突。- 通知
ResourceGroupManager资源已创建。
createOrRetrieve 是更常用的入口:先按名查,命中直接复用(created=false);查不到才 createResource(created=true)。它返回 (ResourcePtr, bool) 二元组,调用方据此决定是「刚创建的新资源」还是「复用已有资源」。
addImpl 的同名冲突处理值得注意:emplace 返回 {iterator, bool},如果已有同名资源且装了 ResourceLoadingListener,会回调 resourceCollision 让监听器决定保留旧的还是强制覆盖;不装监听器则旧资源静默胜出,新实例被 res.reset() 丢弃。
源码定位
OgreMain/include/OgreResource.h:LoadingState枚举(101-116)、mLoadingState原子字段(143)、prepare(257)、load(269)OgreMain/include/OgreResourceManager.h:createImpl纯虚(450-452)、createResource声明(123-125)、mNextHandle(35 区域)OgreMain/src/OgreResourceManager.cpp:ResourceManager()构造(34-39)、createResource(51-68)、createOrRetrieve(70-88)、addImpl(111-164)、getNextHandle(35)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面用纯 C++ 复现资源两件套:LoadingState 六态状态机、ResourceManager 的句柄分配与按名去重。它与 src/ogre-ext-03-1-custom-resource.cpp 逐字节一致:
// file: src/ogre-ext-03-1-custom-resource.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-03-1-custom-resource.cpp -o bin/ogre-ext-03-1-custom-resource && ./bin/ogre-ext-03-1-custom-resource
//
// 复现自定义资源类型机制(对应 OgreMain/include/OgreResource.h 101-116 的
// LoadingState 与 prepare/load 生命周期,OgreResourceManager.h 450-452 的
// createImpl 纯虚,OgreResourceManager.cpp 51-108 的 createResource/
// createOrRetrieve):Resource 子类实现 loadImpl 并维护 UNLOADED→PREPARED→
// LOADED 状态机;ResourceManager 用 getNextHandle 分配句柄、addImpl 登记并按名去重。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <map>
#include <string>
namespace ogre_repro {
using ResourceHandle = std::size_t;
// 对应 OgreResource.h 101-116 的 LoadingState 枚举
enum LoadingState : uint8_t {
LOADSTATE_UNLOADED,
LOADSTATE_LOADING,
LOADSTATE_LOADED,
LOADSTATE_UNLOADING,
LOADSTATE_PREPARED,
LOADSTATE_PREPARING
};
// 对应 OgreResource.h:最小 Resource,维护加载状态机
class Resource {
public:
Resource(const std::string& name, ResourceHandle handle)
: mName(name), mHandle(handle), mLoadingState(LOADSTATE_UNLOADED),
mSize(0) {}
void prepare() {
if (mLoadingState == LOADSTATE_UNLOADED) {
mLoadingState = LOADSTATE_PREPARING;
prepareImpl();
mLoadingState = LOADSTATE_PREPARED;
}
}
void load() {
if (mLoadingState == LOADSTATE_UNLOADED) prepare();
if (mLoadingState == LOADSTATE_PREPARED) {
mLoadingState = LOADSTATE_LOADING;
loadImpl();
mLoadingState = LOADSTATE_LOADED;
}
}
void unload() {
if (mLoadingState == LOADSTATE_LOADED) {
unloadImpl();
mLoadingState = LOADSTATE_UNLOADED;
}
}
bool isPrepared() const { return mLoadingState == LOADSTATE_PREPARED; }
bool isLoaded() const { return mLoadingState == LOADSTATE_LOADED; }
LoadingState getLoadingState() const { return mLoadingState; }
const std::string& getName() const { return mName; }
ResourceHandle getHandle() const { return mHandle; }
std::size_t getSize() const { return mSize; }
protected:
virtual void prepareImpl() {} // prepare 阶段统计字节
virtual void loadImpl() = 0; // 子类必须实现
virtual void unloadImpl() {}
std::string mName;
ResourceHandle mHandle;
LoadingState mLoadingState;
std::size_t mSize;
};
// 一个真实的 Resource 子类:prepare 读入统计,load 标记解析完成
class MeshResource : public Resource {
public:
MeshResource(const std::string& name, ResourceHandle handle)
: Resource(name, handle) {}
void prepareImpl() override { mSize = 4096; }
void loadImpl() override { mParsed = true; }
bool mParsed = false;
};
// 对应 OgreResourceManager.h 450-452 的 createImpl 与 OgreResourceManager.cpp
// 51-108 的 createResource:分配句柄、登记去重、按名查询
class ResourceManager {
public:
virtual ~ResourceManager() {}
virtual Resource* createImpl(const std::string& name, ResourceHandle handle) = 0;
Resource* createResource(const std::string& name) {
ResourceHandle handle = getNextHandle();
Resource* res = createImpl(name, handle);
if (!addImpl(res)) return nullptr; // 名称冲突被拒绝
return res;
}
Resource* createOrRetrieve(const std::string& name) {
Resource* res = getResourceByName(name);
if (res) return res;
return createResource(name);
}
Resource* getResourceByName(const std::string& name) {
auto it = mResources.find(name);
return it == mResources.end() ? nullptr : it->second;
}
bool addImpl(Resource* res) {
if (mResources.count(res->getName())) return false;
mResources.emplace(res->getName(), res);
mHandles.emplace(res->getHandle(), res);
return true;
}
ResourceHandle getNextHandle() { return mNextHandle++; }
std::map<std::string, Resource*> mResources;
std::map<ResourceHandle, Resource*> mHandles;
ResourceHandle mNextHandle = 1; // 对应 OgreResourceManager.cpp 35 mNextHandle(1)
};
// 具体管理器:创建 MeshResource 实例
class MeshManager : public ResourceManager {
public:
Resource* createImpl(const std::string& name, ResourceHandle handle) override {
return new MeshResource(name, handle);
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
MeshManager mgr;
// createResource:句柄从 1 开始,初始状态 UNLOADED
Resource* a = mgr.createResource("tree.mesh");
CHECK(a != nullptr);
CHECK_EQ(a->getHandle(), ResourceHandle(1));
CHECK_EQ(a->getLoadingState(), LOADSTATE_UNLOADED);
// 第二个资源句柄递增
Resource* b = mgr.createResource("rock.mesh");
CHECK_EQ(b->getHandle(), ResourceHandle(2));
// 同名重复创建:addImpl 拒绝,返回 nullptr
CHECK(mgr.createResource("tree.mesh") == nullptr);
// createOrRetrieve:已存在则复用,不分配新句柄
Resource* c = mgr.createOrRetrieve("tree.mesh");
CHECK(c == a);
CHECK_EQ(c->getHandle(), ResourceHandle(1));
// 首次 createOrRetrieve:创建并分配句柄;注意上一次失败的重复创建已
// 消耗了句柄 3(getNextHandle 是原子递增、不回滚,OGRE 同此语义)
Resource* d = mgr.createOrRetrieve("grass.mesh");
CHECK_EQ(d->getHandle(), ResourceHandle(4));
// prepare:UNLOADED → PREPARING → PREPARED,并统计字节
CHECK(!a->isPrepared());
a->prepare();
CHECK(a->isPrepared());
CHECK_EQ(a->getSize(), size_t(4096));
// load:PREPARED → LOADING → LOADED,子类 loadImpl 生效
CHECK(!a->isLoaded());
a->load();
CHECK(a->isLoaded());
CHECK(static_cast<MeshResource*>(a)->mParsed);
// 已加载再 load:幂等,状态保持 LOADED
a->load();
CHECK_EQ(a->getLoadingState(), LOADSTATE_LOADED);
// unload 回到 UNLOADED,可再次 load
a->unload();
CHECK_EQ(a->getLoadingState(), LOADSTATE_UNLOADED);
a->load();
CHECK(a->isLoaded());
return lab::report("3.1 自定义资源类型");
}
本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译通过(零警告),断言 17/17 通过。
小结
Resource用六态LoadingState描述生命周期,prepare与load各沿一条轴推进。prepare适合后台线程、load适合主渲染线程,注释建议尽量在prepare里多做。- 子类必须实现
loadImpl,prepareImpl/unloadImpl可按需覆盖。 ResourceManager只留createImpl纯虚,句柄分配、登记、去重全在基类完成。getNextHandle原子递增不回滚,失败创建也消耗句柄;createOrRetrieve先查后建。
阅读导航:上一节:2.3 对象工厂 · 下一节:3.2 自定义存档 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。