6.1 ResourceManager 与资源生命周期
OGRE 里的「资源」不是文件,而是一个运行时对象:纹理、网格、材质、骨架、GPU 程序,都是 Resource 的子类。资源系统要回答三个问题:资源有几个生命状态?谁负责创建具体类型的资源?多线程下加载如何不打架?这一节讲前两个,第三个在 6.3 与卷四的多线程加载里展开。
本章与站内既有内容的分工
helio 卷二的资产管线(helio-ed-asset)讲的是编辑器侧的资产导入、目录与依赖图;本系列 6.1~6.3 讲 OGRE 引擎运行时的资源生命周期、归档定位与资源组。前者偏编辑器工作流,后者偏引擎内核的资源管理机制。
Resource 的生命周期:六态状态机
OgreResource.h 用 LoadingState 枚举把资源的一生切成六态:
// OgreMain/include/OgreResource.h:LoadingState 枚举(v14.6.3 源码摘录,已删减)
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
};
三个关键设计点:
- PREPARED/PREPARING 独立成态:prepare 与 load 分离,把「从归档读到内存」和「解析成 GPU 资源」两件事拆开。prepare 适合后台线程做(读文件慢),load 必须在渲染上下文里做(建 GPU 对象)。
mLoadingState是std::atomic:多线程读状态无锁,配合 CAS 做有锁的过渡(见下)。- 状态数 = 生命周期步骤数:六态几乎一一对应「创建 → 准备中 → 已准备 → 加载中 → 已加载 → 卸载」。
加载骨架:钩子 + 纯虚
Resource 把加载流程定成骨架,具体资源填步骤。钩子是虚的(默认空),纯虚必须实现:
// OgreMain/include/OgreResource.h:加载钩子与纯虚(v14.6.3 源码摘录,已删减)
/** Internal hook to perform actions before the load process, but
after the resource has been marked as 'loading'.
*/
virtual void preLoadImpl(void) {}
/** Internal hook to perform actions after the load process, but
before the resource has been marked as fully loaded.
*/
virtual void postLoadImpl(void) {}
/** Internal implementation of the meat of the 'load' action, only called if this
resource is not being loaded from a ManualResourceLoader.
*/
virtual void loadImpl(void) = 0;
/** Internal implementation of the 'unload' action; called regardless of
whether this resource is being loaded from a ManualResourceLoader.
*/
virtual void unloadImpl(void) = 0;
load() 的实际执行顺序(OgreResource.cpp)是固定的:非手动加载时 prepareImpl() → preLoadImpl() → loadImpl() → postLoadImpl() → calculateSize()。具体资源只需实现 loadImpl(把数据解析成资源)、unloadImpl(释放);Mesh 解析顶点、Texture 上传 GPU,都藏在自己的 loadImpl 里。
load 的多线程守卫:CAS 状态机
Resource::load(bool background) 开头是一段无锁快检 + CAS 慢检的竞争处理。两线程同时 load 同一资源时,只有一个能把状态从 UNLOADED 换成 LOADING,另一个在 CAS 失败后自旋等 LOADING 结束:
// OgreMain/src/OgreResource.cpp:Resource::load 开头(v14.6.3 源码摘录,已删减)
bool keepChecking = true;
LoadingState old = LOADSTATE_UNLOADED;
while (keepChecking)
{
old = mLoadingState.load();
...
if (old!=LOADSTATE_UNLOADED && old!=LOADSTATE_PREPARED && old!=LOADSTATE_LOADING) return;
// atomically do slower check to make absolutely sure,
// and set the load state to LOADING
if (old==LOADSTATE_LOADING || !mLoadingState.compare_exchange_strong(old,LOADSTATE_LOADING))
{
while( mLoadingState.load() == LOADSTATE_LOADING )
{
OGRE_LOCK_AUTO_MUTEX;
}
...
return;
}
keepChecking = false;
}
成功抢到 LOADING 的线程执行加载主体,异常时回滚:mLoadingState.store(LOADSTATE_UNLOADED) 后 unloadImpl() 再 throw,保证失败不留下半加载状态。
ResourceManager:创建与查重
每个资源类型有一个专属 Manager(MeshManager、TextureManager、SkeletonManager……)。ResourceManager 基类管登记,子类管创建。登记靠三张表(OgreResourceManager.h):
// OgreMain/include/OgreResourceManager.h:三张查表(v14.6.3 源码摘录,已删减)
typedef std::unordered_map< String, ResourcePtr > ResourceMap;
typedef std::unordered_map< String, ResourceMap > ResourceWithGroupMap;
typedef std::map<ResourceHandle, ResourcePtr> ResourceHandleMap;
protected:
ResourceHandleMap mResourcesByHandle;
ResourceMap mResources;
ResourceWithGroupMap mResourcesWithGroup;
size_t mMemoryBudget; /// In bytes
std::atomic<ResourceHandle> mNextHandle;
mResourcesByHandle:handle → 资源(handle 是数值,查得快);mResources:名字 → 资源(默认组);mResourcesWithGroup:组 → 名字 → 资源(跨组的完整索引)。
createResource 的执行顺序是「子类造对象 → 父类登记 → 通知资源组」:
// OgreMain/src/OgreResourceManager.cpp:createResource(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));
...
addImpl(ret);
// Tell resource group manager
if(ret)
ResourceGroupManager::getSingleton()._notifyResourceCreated(ret);
return ret;
}
createImpl 是纯虚——MeshManager::createImpl 返回 Mesh,TextureManager::createImpl 返回 Texture。父类不知道也不关心具体类型,只负责分配递增 handle、登记三表、通知资源组。
createOrRetrieve:一次调用避免竞态
反复「先 getByName 再 create」有竞态:两线程都查到空、都去创建。createOrRetrieve 把「查 + 建」合成一个原子操作:
// OgreMain/src/OgreResourceManager.cpp:createOrRetrieve(v14.6.3 源码摘录,已删减)
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);
}
返回值是 pair<ResourcePtr, bool>:bool 告诉你这次到底新建了还是复用了旧的。加载资源的公开入口 load(name, group, ...) 内部就走 createOrRetrieve——「已存在就返回,不存在就建」,这是全引擎加载任何资源的标准姿势。
资源状态与加载分支
flowchart TD
A["未加载资源"] --> B{"prepare 或 load"}
B -->|"prepare"| C["PREPARING,执行 prepareImpl"]
C -->|"成功"| D["PREPARED"]
C -->|"异常"| A
B -->|"load"| E["LOADING"]
D --> E
E --> F["补 prepare,再执行 loadImpl 及前后钩子"]
F -->|"成功"| G["LOADED"]
F -->|"异常"| A
G --> H["UNLOADING,执行 unloadImpl"]
H --> A
状态竞争和失败回退
同一资源对象的加载由原子状态协调。prepare 已在进行时,load 需等准备阶段给出结果。load 成功后才交付已加载状态。资源准备或加载失败时,要沿异常分支检查状态和临时数据的回收。
磁盘网格样例通过未加载、已准备、已加载和卸载重载四个点。ResourceManager 的名称登记保持独立,卸载后仍可通过同一个资源对象重载。
状态由资源实例维护
flowchart TD
G["ResourceGroupManager 管理组"] -->|"查找和调度"| M["具体 ResourceManager"]
M -->|"按名称和组登记"| R["Resource 实例"]
C["宿主或后台队列"] -.->|"请求 prepare 或 load"| R
R --> S["原子加载状态"]
R --> P["子类 prepareImpl 和 loadImpl"]
P --> D["临时流、解析结果或硬件资源"]
S -.->|"成功后公布状态"| C
源码定位
OgreMain/include/OgreResource.h:LoadingState六态、loadImpl/unloadImpl纯虚、pre/post 钩子OgreMain/src/OgreResource.cpp:Resource::load的 CAS 状态机与异常回滚OgreMain/include/OgreResourceManager.h:createImpl纯虚、三张查表、createResource/createOrRetrieveOgreMain/src/OgreResourceManager.cpp:createResource与createOrRetrieve实现
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现六态状态机、幂等加载、handle 分配与 createOrRetrieve 先查后建。它与 src/06-1-resource-lifecycle.cpp 逐字节一致:
// file: src/06-1-resource-lifecycle.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/06-1-resource-lifecycle.cpp -o bin/06-1-resource-lifecycle && ./bin/06-1-resource-lifecycle
//
// 复现 OgreResource 的加载状态机与 OgreResourceManager 的创建/取回:
// LoadingState 六态;load() 幂等(已 LOADED 不再 loadImpl);
// createResource 分配 handle 并注册;createOrRetrieve 先查后建。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <map>
#include <stdexcept>
#include <string>
namespace ogre_repro {
// 对应 OgreResource.h 的 LoadingState 枚举(六态)
enum LoadingState {
LOADSTATE_UNLOADED,
LOADSTATE_LOADING,
LOADSTATE_LOADED,
LOADSTATE_UNLOADING,
LOADSTATE_PREPARED,
LOADSTATE_PREPARING
};
class ResourceManager;
// 对应 OgreResource:名字/handle/组/加载状态,纯虚 loadImpl/unloadImpl
class Resource {
public:
std::string mName;
uint64_t mHandle;
std::string mGroup;
LoadingState mLoadingState = LOADSTATE_UNLOADED;
ResourceManager* mCreator = nullptr;
int loadCalls = 0;
Resource(const std::string& n, uint64_t h, const std::string& g)
: mName(n), mHandle(h), mGroup(g) {}
virtual ~Resource() = default;
// 对应 Resource::loadImpl(void) = 0
virtual void loadImpl() = 0;
virtual void unloadImpl() = 0;
bool isLoaded() const { return mLoadingState == LOADSTATE_LOADED; }
// 简化 Resource::load:幂等守卫 + LOADING → loadImpl → LOADED
void load() {
if (isLoaded()) return; // 已加载直接返回(幂等)
if (mLoadingState != LOADSTATE_UNLOADED &&
mLoadingState != LOADSTATE_PREPARED)
return;
mLoadingState = LOADSTATE_LOADING;
try {
loadImpl();
mLoadingState = LOADSTATE_LOADED;
} catch (...) {
mLoadingState = LOADSTATE_UNLOADED; // 失败回滚
throw;
}
}
// 对应 Resource::unload
void unload() {
if (!isLoaded()) return;
unloadImpl();
mLoadingState = LOADSTATE_UNLOADED;
}
};
// 具体资源:对应 Texture/Mesh 等由 Manager 创建的具体类型
class MyResource : public Resource {
public:
using Resource::Resource;
void loadImpl() override { loadCalls++; }
void unloadImpl() override { loadCalls = 0; }
};
// 对应 OgreResourceManager:handle 分配、三表注册、createImpl 纯虚
class ResourceManager {
public:
uint64_t mNextHandle = 0;
std::map<std::string, Resource*> mResources;
std::map<uint64_t, Resource*> mResourcesByHandle;
virtual ~ResourceManager() {
for (auto& kv : mResources) delete kv.second;
}
// 对应 createImpl:子类决定具体资源类型
virtual Resource* createImpl(const std::string& name, uint64_t handle,
const std::string& group) = 0;
// 对应 createResource:createImpl + 注册
Resource* createResource(const std::string& name, const std::string& group) {
Resource* res = createImpl(name, mNextHandle++, group);
mResources[name] = res;
mResourcesByHandle[res->mHandle] = res;
return res;
}
Resource* getResourceByName(const std::string& name) const {
auto it = mResources.find(name);
return it == mResources.end() ? nullptr : it->second;
}
// 对应 createOrRetrieve:先查后建,一次调用避免竞态
Resource* createOrRetrieve(const std::string& name, const std::string& group,
bool& created) {
Resource* res = getResourceByName(name);
created = false;
if (!res) {
created = true;
res = createResource(name, group);
}
return res;
}
};
class MyManager : public ResourceManager {
public:
Resource* createImpl(const std::string& name, uint64_t handle,
const std::string& group) override {
return new MyResource(name, handle, group);
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
MyManager mgr;
// createResource:分配递增 handle 并注册两表
Resource* a = mgr.createResource("tree.mesh", "General");
Resource* b = mgr.createResource("rock.mesh", "General");
CHECK(a->mHandle == 0u);
CHECK(b->mHandle == 1u);
CHECK(a->mName == "tree.mesh");
CHECK(a->mGroup == "General");
CHECK_EQ(mgr.mResourcesByHandle.size(), 2u);
// 加载:UNLOADED → LOADING → LOADED
CHECK(!a->isLoaded());
a->load();
CHECK(a->isLoaded());
// 幂等:已加载再 load 不触发第二次 loadImpl
a->load();
CHECK_EQ(a->loadCalls, 1);
// getByName 取回
CHECK(mgr.getResourceByName("tree.mesh") == a);
CHECK(mgr.getResourceByName("nope.mesh") == nullptr);
// createOrRetrieve:已存在不重建
bool created = false;
Resource* a2 = mgr.createOrRetrieve("tree.mesh", "General", created);
CHECK(!created);
CHECK(a2 == a);
// createOrRetrieve:不存在则创建
Resource* c = mgr.createOrRetrieve("sky.mesh", "General", created);
CHECK(created);
CHECK(c->mHandle == 2u);
// unload:回 UNLOADED,再 load 重新计数
a->unload();
CHECK(!a->isLoaded());
a->load();
CHECK_EQ(a->loadCalls, 1);
return lab::report("06-1 资源系统:Resource 生命周期与创建");
}
本机实测(Apple clang 16,clang++ -std=c++20):编译通过,断言 16/16 通过。
小结
- Resource 生命周期是六态状态机,PREPARED 与 LOADED 分离「读入内存」与「建 GPU 资源」。
- 加载骨架 = 钩子(pre/post)+ 纯虚(loadImpl/unloadImpl),具体资源填步骤。
- ResourceManager 三表登记,createImpl 纯虚决定具体类型,createResource 分配 handle。
- createOrRetrieve 把「查 + 建」合成原子操作,杜绝先查后建竞态。
- CAS 状态机守卫多线程加载,失败回滚 UNLOADED 不留半态。
阅读导航:上一节:5.3 MovableObject 与附着 · 下一节:6.2 Archive 与资源定位 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。