Saving & Loading for Hexwave.

Hello! Today we're going to be talking about how Saving & Loading works in Hexwave! If you don't know, Hexwave is my Interactive Film Engine (in C++) that I'm working on as part of my University assignment (and I'll continue to work on after).

 

Hexwave originally used CSV (comma separated values) to save projects, like so:

ahhhh,woah!,1
test,testing!,1
teste,testing again,1

Whilst this worked for initial testing, I very quickly realised that it would break if people tried to use commas (I could fix that by using " ", but I wanted to move away from CSV) so I decided I needed to rewrite it to use JSON. I'm very familiar with JSON as I PR Review for D++ (which is a Discord Bot library) so we deal with JSON from Discord's API. It's also extremely common for storing data (if you're not using a database) so it's just the most logical option. If you're not familiar with JSON, it looks something like this:

{
    "testing":
    {
        "name": "hello world",
        "age": 19
    }

}

It's a much better way of storing data and, like I said, I have experience with JSON in C++, so I'm confident in using it. I used a JSON library by nholmann for this. We use the same library in D++ so I'm extremely familiar with it, along with it being one of the best JSON libraries for C++.

 

So, how do we go about saving projects with JSON? Well, we want to be able to gather the information of a video struct and turn it into a JSON object, so we can easily make a function called "json to_json() const" in our video struct which, as you may have guess, returns a JSON object. Then, in our declaration of "to_json", we do:

json j;

j["id"] = id;
j["name"] = name;
j["length"] = length;

return j;

This lets us easily loop through a videos array, do "vid.to_json()", and then append that to a "json::array()" called "videos". Then we apply a similar logic for the options, options get a "to_json()" function, which gets called when a video is getting turned into a JSON object. This means we get a lovely project file that is a lot more readable for people to even edit by hand!

 

Now, let's talk about loading projects! Nholmann json comes with a function called "json::parse()" and we can directly get the entire text of our file with "std::ifstream" and pipe it straight into "json::parse()", creating a JSON object from our file data! From there, it's as easy as just looping through the "videos" array like so:

json j = json::parse(project_file);

for (const auto& vid : j["videos"]) {

    // get data from vid and add it to the videos array.

}

From here, we can take the values from the "vid" object and create a new video object with our data!


And that is how I did saving and loading for Hexwave!


I hope you enjoyed this post!

Comments

Popular posts from this blog

The idea behind making Hexwave.

Making Hexwave work on Steam Deck!