I'm trying to use yaml-cpp to serialize(and de-serialize) "scene" data for my game engine. The problem is, YAML::LoadFile seems to change a scene data file when loading multiple files.
Let's say I have 2 files, A.yaml and B.yaml.
A.yaml:
-entity1
-entity2
-entity3
B.yaml:
-entity1
-entity2
-entity3
After adding 2 more entities and saving it, I can see that B have chaged properly.
B.yaml after chage:
-entity1
-entity2
-entity3
-entity4
-entity5
But if I load A and load B again in a same runtime, the file B returns to it's original state! (B.yaml at first). If I save B and restart my engine, then loading files multiple time has no effect on the file B.
Here's my code for loading and saving.
class scene_data {
public:
void save(const std::filesystem::path &) const;
void load(const std::filesystem::path &);
std::vector<entity_data> entities() const;
void add_entity();
void delete_entity(const entity_data &);
private:
std::vector<entity_data> _entities;
};
void scene_data::save(const std::filesystem::path &path) const {
YAML::Emitter em;
em << YAML::BeginMap << YAML::Key << "entities";
em << YAML::BeginSeq;
for (const auto &e: _entities) {
e.serialize(em);//Each entity write themselves in emitter
}
em << YAML::EndSeq;
em << YAML::EndMap;
std::ofstream filepath(path);
filepath << em.c_str();//I've heard that the ofstream doesn't need to be closed manually.
}
void scene_data::load(const std::filesystem::path &path) {
auto root = YAML::LoadFile(path.string());
if (auto ett_node = root["entities"]) {
std::vector<entity_data> new_entities;
for (const auto &ett: ett_node) {
new_entities.push_back(entity_data(ett));//entity_data constructor takes yaml node
}
_entities = new_entities;
}
}
Would there be some rules on using YAML::LoadFile?