blob: 7fbd19e9686a969954907b5c26cbe6b134076471 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
/** ---------------------------------------------------------------------------
* @file: spritesheet.cpp
*
* Copyright (c) 2017 Yann Herklotz Grave <ymherklotz@gmail.com>
* MIT License, see LICENSE file for more details.
* ----------------------------------------------------------------------------
*/
/// @file
#include "spritesheet.h"
#include <rapidjson/document.h>
#include <yage/core/imageloader.h>
#include <cassert>
#include <fstream>
#include <sstream>
#include <stdexcept>
using rapidjson::Document;
using yage::details::Coordinate;
using yage::details::SpriteMap;
namespace yage
{
SpriteSheet::SpriteSheet(std::string pngFileName, std::string jsonFileName)
{
int jsonWidth, jsonHeight;
fileLocations_ =
parseJson(jsonWidth, jsonHeight, fileContent(jsonFileName));
texture_ = ImageLoader::loadPng(pngFileName);
if (texture_.width != jsonWidth)
throw std::runtime_error("JSON width does not match texture width");
if (texture_.height != jsonHeight)
throw std::runtime_error("JSON height does not match texture height");
}
std::string SpriteSheet::fileContent(std::string jsonFileName) const
{
std::ifstream inputFile(jsonFileName);
std::stringstream stream;
stream << inputFile.rdbuf();
return stream.str();
}
SpriteMap SpriteSheet::parseJson(int &width, int &height,
std::string jsonContent) const
{
SpriteMap spriteMap;
Document jsonAtlas;
jsonAtlas.Parse(jsonContent.c_str());
width = jsonAtlas["width"].GetInt();
height = jsonAtlas["height"].GetInt();
for (auto &texture : jsonAtlas["sprites"].GetObject()) {
Coordinate coord;
for (auto &value : texture.value.GetObject()) {
std::string keyName{value.value.GetString()};
int keyValue{value.value.GetInt()};
if (keyName == "x") {
coord.x = keyValue;
} else if (keyName == "y") {
coord.y = keyValue;
} else if (keyName == "width") {
coord.width = keyValue;
} else if (keyName == "height") {
coord.height = keyValue;
} else {
throw std::runtime_error("JSON key incorrect: " + keyName);
}
}
spriteMap[texture.name.GetString()] = coord;
}
return spriteMap;
}
} // namespace yage
|