使用yaml-cpp库进行序列化设置¶
YAML处理¶
- 加码和解码Vec3,vec4
namespace YAML {
template<>
struct convert<glm::vec3>
{
static Node encode(const glm::vec3& rhs)
{
Node node;
node.push_back(rhs.x);
node.push_back(rhs.y);
node.push_back(rhs.z);
return node;
}
static bool decode(const Node& node, glm::vec3& rhs)
{
if (!node.IsSequence() || node.size() != 3)
return false;
rhs.x = node[0].as<float>();
rhs.y = node[1].as<float>();
rhs.z = node[2].as<float>();
return true;
}
};
template<>
struct convert<glm::vec4>
{
static Node encode(const glm::vec4& rhs)
{
Node node;
node.push_back(rhs.x);
node.push_back(rhs.y);
node.push_back(rhs.z);
node.push_back(rhs.w);
return node;
}
static bool decode(const Node& node, glm::vec4& rhs)
{
if (!node.IsSequence() || node.size() != 4)
return false;
rhs.x = node[0].as<float>();
rhs.y = node[1].as<float>();
rhs.z = node[2].as<float>();
rhs.w = node[3].as<float>();
return true;
}
};
}
Serializer序列化器设置¶
序列化器本身对应一个scene
+ 老规矩,给Scene加个友元friend class SceneSerializer
+ 提供一个SerializeEntity,序列化所有的组件
+ 对每个component(Tag,Transform,Camera,SpriteRenderer)进行序列化
- 构造:初始化scene
* 序列化:初始化场景信息,再遍历注册表初始化entity
* 反序列化:读取yaml信息创建对应的scene的所有实体,并以此根据细节信息给对应的entity赋值。
* 运行时序列化和反序列化(暂时没做)
#pragma once
#include "Scene.h"
namespace CryDust {
class SceneSerializer
{
public:
SceneSerializer(const Ref<Scene>& scene);
void Serialize(const std::string& filepath);
void SerializeRuntime(const std::string& filepath);
bool Deserialize(const std::string& filepath);
bool DeserializeRuntime(const std::string& filepath);
private:
Ref<Scene> m_Scene;
};
}
EditorLayer¶
开始菜单上加点按钮
if (ImGui::MenuItem("Serialize"))
{
SceneSerializer serializer(m_ActiveScene);
serializer.Serialize("assets/scenes/Example.crydust");
}
if (ImGui::MenuItem("Deserialize"))
{
SceneSerializer serializer(m_ActiveScene);
serializer.Deserialize("assets/scenes/Example.crydust");
}
yaml-cpp¶
记得定义一个宏
#define YAML_CPP_STATIC_DEFINE