93 lines
1.9 KiB
C++
93 lines
1.9 KiB
C++
/*
|
|
* LoadLevel.cpp
|
|
*
|
|
* Created on: Nov 11, 2016
|
|
* Author: tibi
|
|
*/
|
|
|
|
#include <model/Level.h>
|
|
|
|
#include <fstream>
|
|
#include <string>
|
|
#include <json.hpp>
|
|
|
|
using namespace farmlands::model;
|
|
using namespace nlohmann;
|
|
|
|
namespace farmlands {
|
|
namespace storage {
|
|
|
|
namespace {
|
|
|
|
void loadLevelCells(std::shared_ptr<Level> level, size_t layer, std::string cellsFileName)
|
|
{
|
|
char buffer[1024 * 10];
|
|
|
|
// Open file
|
|
std::ifstream in(cellsFileName);
|
|
if (!in)
|
|
throw 0; // TODO: replace with exception type
|
|
|
|
// Read CSV file line by line
|
|
for (size_t row = 0; row < level->rowCount(); row++)
|
|
{
|
|
in.getline(buffer, sizeof(buffer));
|
|
|
|
if (in.eof())
|
|
throw 0; // TODO: replace with exception type
|
|
|
|
// Separated by comma (or maybe semicolon)
|
|
char* nextNum = strtok(buffer, ",;");
|
|
for (size_t col = 0; col < level->columnCount() && nextNum != NULL; col++)
|
|
{
|
|
Cell cell = (Cell)strtol(nextNum, NULL, 10);
|
|
level->setCell(layer, row, col, cell);
|
|
|
|
nextNum = strtok(NULL, ",;");
|
|
}
|
|
}
|
|
|
|
in.close();
|
|
}
|
|
}
|
|
|
|
std::shared_ptr<Level> loadLevel(std::string fileName)
|
|
{
|
|
// Open file
|
|
std::ifstream levelIn(fileName);
|
|
if (!levelIn)
|
|
throw 0; // TODO: replace with exception type
|
|
|
|
// Parse file
|
|
json levelJs;
|
|
levelIn>>levelJs;
|
|
|
|
size_t layerCount = levelJs.value("layerCount", 0u);
|
|
size_t rowCount = levelJs.value("height", 0u);
|
|
size_t colCount = levelJs.value("width", 0u);
|
|
|
|
size_t cellWidth = levelJs.value("cellWidth", 0u);
|
|
size_t cellHeight = levelJs.value("cellHeight", 0u);
|
|
|
|
std::shared_ptr<Level> level(new Level(layerCount, rowCount, colCount));
|
|
|
|
// Read layers
|
|
json layersJs = levelJs["layers"];
|
|
size_t layer = 0;
|
|
|
|
for (auto it = layersJs.begin(); it != layersJs.end(); it++, layer++)
|
|
{
|
|
std::string cellsFileName = it->value("cellsFile", std::string());
|
|
loadLevelCells(level, layer, cellsFileName);
|
|
|
|
std::string textureFileName = it->value("textureFile", std::string());
|
|
}
|
|
return level;
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
|
|
|