summaryrefslogtreecommitdiff
path: root/src/sets/tileset.hpp
blob: 0415969f357bacc5a269551be5af18ef57bcb3c1 (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
#pragma once
#include <SFML/Graphics/Texture.hpp>
#include <algorithm>

#include "../utils/string.hpp"
#include "entryset.hpp"

#define TILE_WIDTH 16
#define TILE_HEIGHT 16

namespace silly::editor {
  enum TilesetTileType { TILE_FLOOR = 0, TILE_WALL };
  struct TilesetTile {
      int id;
      sf::Texture texture;
      std::string path, name, extension;
      TilesetTileType type;
  };

  class TileSet : public EntrySet<TilesetTile, TilesetTileType> {
    public:
      void add_entry(const std::string &path, TilesetTileType type) override {
        TilesetTile tile;
        tile.type = type;
        tile.path = path;
        tile.id = this->entries.size();

        if (!tile.texture.loadFromFile(path)) {
          // TODO: add logging here
          return;
        }

        // parsing name and extension
#ifdef WIN32
        char delim = '\\';
#else
        char delim = '/';
#endif
        auto path_parts = utils::split_text(path, delim);

        std::string name_with_extension = path_parts[path_parts.size() - 1];
        auto nwe_parts = utils::split_text(name_with_extension, '.');

        tile.extension = nwe_parts[nwe_parts.size() - 1];
        tile.name = name_with_extension.substr(
            0, name_with_extension.length() - tile.extension.length() - 1);

        this->entries.push_back(std::make_shared<TilesetTile>(tile));
      }

      void remove_entry(const TilesetTile &entry) override {
        this->entries.resize(std::distance(
            this->entries.begin(),
            std::remove_if(this->entries.begin(), this->entries.end(),
                           [&entry](const std::shared_ptr<TilesetTile> &t) {
                             return t.get()->id == entry.id;
                           })));
      }

      void clear() { this->entries.clear(); }

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

        oss << "[tileset]\n"
            << "# id;type;name.extension\n";

        for (auto it = this->entries.begin(); it != this->entries.end(); ++it) {
          TilesetTile *t = it->get();
          oss << std::to_string(t->id) << ";" << std::to_string(t->type) << ";"
              << t->name << "." << t->extension << "\n";
        }

        return oss.str();
      }
  };
}