Implement loading tile sets from JSON files

This commit is contained in:
Lexi / Zoe 2026-06-25 23:33:14 +02:00
parent 718679c13b
commit b4635cdb99
Signed by: binaryDiv
GPG key ID: F8D4956E224DA232
3 changed files with 53 additions and 16 deletions

View file

@ -0,0 +1,26 @@
{
"texture": "terrain.png",
"tile_size": 32,
"tiles": [
{
"x": 0,
"y": 0
},
{
"x": 0,
"y": 0
},
{
"x": 1,
"y": 0
},
{
"x": 2,
"y": 0
},
{
"x": 3,
"y": 0
}
]
}

View file

@ -6,9 +6,11 @@ import std;
import rutile.core.common; import rutile.core.common;
import rutile.core.resources.texture; import rutile.core.resources.texture;
import rutile.core.resources.tile_set; import rutile.core.resources.tile_set;
// import vendor.nlohmann.json; import wrappers.sdl;
import vendor.nlohmann.json;
// using json = nlohmann::json; namespace fs = std::filesystem;
using json = nlohmann::json;
namespace rutile namespace rutile
{ {
@ -38,20 +40,29 @@ export namespace rutile
TileSet load_resource(const std::string& name) const TileSet load_resource(const std::string& name) const
{ {
return TileSet::create_from_texture( try {
texture_load_callback_(name), std::ifstream json_file(name);
// TODO: Load this from a JSON file json data = json::parse(json_file);
32,
{ // Texture path is relative to JSON file
// Tile 0: No tile fs::path texture_path = fs::path(name).replace_filename(data.at("texture"));
{0, 0},
// Tile 1: Actual first tile in the texture std::vector<sdl::Point> tile_atlas_coords;
{0, 0}, for (auto tile : data.at("tiles")) {
{1, 0}, tile_atlas_coords.push_back({tile.at("x"), tile.at("y")});
{2, 0},
{3, 0},
} }
return TileSet::create_from_texture(
texture_load_callback_(texture_path),
data.at("tile_size"),
tile_atlas_coords
); );
} }
catch (const json::exception& e) {
throw std::runtime_error(
std::format("Error loading tile set from \"{}\": {}", name, e.what())
);
}
}
}; };
} }

View file

@ -40,7 +40,7 @@ export namespace rutile
) )
}, },
tile_map_{ tile_map_{
engine_.get_resource_server().load_tile_set("assets/tilesets/terrain.png"), engine_.get_resource_server().load_tile_set("assets/tilesets/terrain.json"),
32, 16, 12, {50, 50} 32, 16, 12, {50, 50}
} }
{ {