Files
dl_old/dl/render/dl_model_cache.h
2026-04-18 17:33:12 +08:00

118 lines
2.1 KiB
C++

/**
* @file dl_model_cache.h
* @brief 用于保存模型文件信息,检查修改,加快加载
*
*
* @version 1.0
* @author lveyou
* @date 22-04-21
*/
#pragma once
#include <cstdint>
#include <vector>
#include <string>
#include <unordered_map>
#include "memory/dl_stream_input.h"
#include "memory/dl_stream_output.h"
namespace dl
{
//版本,不同则重新生成(修改ModelObject代码也需要更新)
constexpr uint32_t VERSION_MODEL_CACHE = 2;
//模型缓存文件
class ModelCache
{
public:
struct Node
{
uint32_t _crc32;// 文件效验值
time_t _t; // 修改时间戳
std::vector<std::string> _allSub;//子模型缓存路径
void Load(StreamInput& s)
{
s.Read(&_crc32);
s.Read(&_t);
s.Read(&_allSub);
}
void Save(StreamOutput& s)
{
s.Write(&_crc32);
s.Write(&_t);
s.Write(&_allSub);
}
};
Node* Get(std::string_view path_name)
{
auto iter = _allModel.find(std::string{ path_name });
if (iter == _allModel.end())
return nullptr;
return &iter->second;
}
Node* Add(std::string_view path_name)
{
auto p = _allModel.insert(std::make_pair(path_name, Node()));
if (p.second)
{
return &p.first->second;
}
return nullptr;
}
void Load(std::string_view path_name)
{
StreamInput s;
if (!s.LoadFromFile(path_name))
return;
uint32_t version;
s.Read(&version);
if (version != VERSION_MODEL_CACHE)
return;
size_t size;
s.Read64(&size);
for (size_t i = 0; i < size; ++i)
{
std::string name;
Node node;
s.Read(&name);
node.Load(s);
if (IsVaild(node))
_allModel[name] = node;
}
}
void Save(std::string_view path_name)
{
StreamOutput s;
s.Write(&VERSION_MODEL_CACHE);
size_t size = _allModel.size();
s.Write64(&size);
for (auto& iter : _allModel)
{
s.Write(&iter.first);
iter.second.Save(s);
}
s.Save(path_name);
}
bool Empty() { return _allModel.empty(); }
bool IsVaild(const Node& node)
{
for (auto& iter : node._allSub)
{
if (!File::IsExist(iter))
return false;
}
return true;
}
private:
//所有模型 文件名 -> node
std::unordered_map<std::string, Node> _allModel;
};
}