YoggieEngine/Editor/src/SceneSerializer.h

109 lines
2.6 KiB
C
Raw Normal View History

#pragma once
#include <yaml-cpp/yaml.h>
#include <string>
#include <filesystem>
#include <fstream>
void WriteFile(std::string& emitter, std::filesystem::path path)
{
std::cout << "Writing Scene file to: " << path.u8string() << std::endl;
std::ofstream sceneFile;
sceneFile.open(path.u8string());
sceneFile << emitter.c_str();
sceneFile.close();
}
YAML::Emitter& operator<< (YAML::Emitter& emitter, glm::vec3& vector) {
emitter << YAML::Flow << YAML::BeginSeq << vector.x << vector.y << vector.x << YAML::EndSeq;
return emitter;
}
void Serialize(YAML::Emitter& emitter, TransformComponent& transform)
{
emitter << YAML::BeginMap;
emitter << YAML::Key << "Transform" << YAML::Value << YAML::Flow << YAML::BeginSeq;
emitter << YAML::Key << "Position";
emitter << YAML::Value << transform.Position;
emitter << YAML::Key << "Rotation";
emitter << YAML::Value << transform.Rotation;
emitter << YAML::Key << "Scale";
emitter << YAML::Value << transform.Scale;
emitter << YAML::EndSeq << YAML::EndMap;
}
void Serialize(YAML::Emitter& emitter, IdentifierComponent& identifier)
{
emitter << YAML::BeginMap;
emitter << YAML::Key << "Ident";
emitter << YAML::Value << identifier.name;
emitter << YAML::EndMap;
}
void Serialize(YAML::Emitter& emitter, LightComponent& light)
{
emitter << YAML::BeginMap << "Light";
emitter << YAML::Key << "strength";
emitter << YAML::Value << light.Strength;
emitter << YAML::Key << "Color";
emitter << YAML::Value << light.Color;
emitter << YAML::EndMap;
}
std::string Serialize( Scene& scene) {
YAML::Emitter sceneYAML;
sceneYAML << "YOGGIE_SCENE_FILE" ;
scene.getReg().each([&scene, &sceneYAML](auto enttNumber) {
Entity entity = Entity(enttNumber, &scene);
Serialize(sceneYAML, entity.GetComponent<IdentifierComponent>());
Serialize(sceneYAML, entity.GetComponent<TransformComponent>());
if (entity.HasComponent<LightComponent>()) {
Serialize(sceneYAML, entity.GetComponent<LightComponent>());
}
});
return std::string(sceneYAML.c_str());
}
void Parse(std::string& YAML) {
std::vector<YAML::Node> nodes = YAML::LoadAll(YAML);
for(YAML::Node node : nodes)
{
std::cout << node.Type() << std::endl;
}
}
void SaveScene(std::filesystem::path path, Scene& scene) {
std::string YAMLString = Serialize(scene);
WriteFile(YAMLString, path);
}
void LoadScene(std::filesystem::path path, Scene& scene)
{
std::ifstream sceneFile;
std::string YAMLScene;
sceneFile.open(path.u8string());
std::stringstream sstream;
sstream << sceneFile.rdbuf();
YAMLScene = sstream.str();
sceneFile.close();
Parse(YAMLScene);
}