diff --git a/assets/tilesets/terrain.json b/assets/tilesets/terrain.json new file mode 100644 index 0000000..fec51c9 --- /dev/null +++ b/assets/tilesets/terrain.json @@ -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 + } + ] +} diff --git a/src/rutile/core/resources/loaders/tile_set_loader.cppm b/src/rutile/core/resources/loaders/tile_set_loader.cppm index 48f7142..1d423a4 100644 --- a/src/rutile/core/resources/loaders/tile_set_loader.cppm +++ b/src/rutile/core/resources/loaders/tile_set_loader.cppm @@ -6,9 +6,11 @@ import std; import rutile.core.common; import rutile.core.resources.texture; 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 { @@ -38,20 +40,29 @@ export namespace rutile TileSet load_resource(const std::string& name) const { - return TileSet::create_from_texture( - texture_load_callback_(name), - // TODO: Load this from a JSON file - 32, - { - // Tile 0: No tile - {0, 0}, - // Tile 1: Actual first tile in the texture - {0, 0}, - {1, 0}, - {2, 0}, - {3, 0}, + try { + std::ifstream json_file(name); + json data = json::parse(json_file); + + // Texture path is relative to JSON file + fs::path texture_path = fs::path(name).replace_filename(data.at("texture")); + + std::vector tile_atlas_coords; + for (auto tile : data.at("tiles")) { + tile_atlas_coords.push_back({tile.at("x"), tile.at("y")}); } - ); + + 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()) + ); + } } }; } diff --git a/src/rutile/game/game.cppm b/src/rutile/game/game.cppm index 6d422db..ff6822a 100644 --- a/src/rutile/game/game.cppm +++ b/src/rutile/game/game.cppm @@ -40,7 +40,7 @@ export namespace rutile ) }, 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} } {