summaryrefslogtreecommitdiff
path: root/src/package.cpp
blob: d07fa9f485251b3dcf2f9962fc9e54ffc19e78f8 (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
85
86
87
#include "package.hpp"

#include <algorithm>
#include <filesystem>
#include <fstream>

namespace silly::editor {
  TileSet &LevelPackage::get_tileset() { return this->tileset; }

  void LevelPackage::add_level(TileLevel level) {
    this->levels.push_back(level);
  }

  TileLevel &LevelPackage::get_current_level() {
    return this->levels.at(this->currentLevelIndex);
  }

  void LevelPackage::move_to_level_index(int index) {
    this->currentLevelIndex = std::min(index, (int)this->levels.size() - 1);
  }

  const int LevelPackage::get_current_level_index() const {
    return this->currentLevelIndex;
  }

  const std::vector<TileLevel> &LevelPackage::get_levels() const {
    return this->levels;
  }

  const std::string &LevelPackage::get_name() const { return this->name; }

  void LevelPackage::set_name(const std::string &name) { this->name = name; }

  void LevelPackage::clear() {
    this->name = "";
    this->currentLevelIndex = 0;
    this->levels.clear();
    this->tileset.clear();
  }

  std::string LevelPackage::export_to_string() const {
    std::ostringstream oss;

    // package data
    oss << "[package]\n"
        << "# name;version\n"
        << name << ";"
        << "0\n";

    // tileset data
    oss << this->tileset.export_to_string() << "\n";

    // level data
    for (auto it = this->levels.begin(); it != this->levels.end(); ++it) {
      oss << it->export_to_string() << "\n";
    }

    return oss.str();
  }

  void LevelPackage::save(LevelPackageFormat format,
                          std::string &file_path) const {
    if (format != PACKAGE_TXT) {
      return;
    }

    // writing package file
    std::stringstream pkg_file_path;

    pkg_file_path << file_path << "/" << this->name << ".txt";

    std::string package = this->export_to_string();

    std::ofstream ifs(pkg_file_path.str());
    ifs << package;
    ifs.close();

    // copying resource files
    for (auto it = this->tileset.get_entries().begin();
         it != this->tileset.get_entries().end(); ++it) {
      TilesetTile *t = it->get();
      std::string old_path = t->path;
      std::string new_path = file_path + "/" + t->name + "." + t->extension;
      std::filesystem::copy_file(old_path, new_path);
    }
  }
}