summary refs log tree commit diff stats
path: root/src/sprite.cpp
blob: cc196ae7ef152cb9fafa191a6078b9cfeb57291c (plain) (blame)
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
#include "sprite.h"
#include <SDL_image.h>
#include <fstream>
#include <list>
#include <regex>
#include "util.h"

Sprite::Sprite(std::string_view filename, Renderer& renderer) {
  std::ifstream datafile(filename.data());
  if (!datafile.is_open()) {
    throw std::invalid_argument(std::string("Could not find sprite datafile: ") + std::string(filename));
  }

  char ch;

  std::string imagename;
  datafile >> imagename;
  textureId_ = renderer.loadImageFromFile(imagename);

  datafile >> size_.w();
  datafile >> ch; //,
  datafile >> size_.h();

  std::string animLine;
  std::getline(datafile, animLine); // blank
  while (std::getline(datafile, animLine)) {
    std::regex re(R"(([a-z]+)\[([a-z_]+)\]: ([0-9,]+))");
    std::smatch m;
    std::regex_match(animLine, m, re);

    std::vector<int> frames;
    auto framestrs = splitStr<std::list<std::string>>(m[3], ",");
    for (const std::string& f : framestrs) {
      frames.push_back(std::stoi(f));
    }

    int animId = animations_.size();
    animations_.push_back(std::move(frames));

    Direction dir = directionFromString(std::string(m[2]));

    if (m[1] == "still") {
      stillAnims_[dir] = animId;
    } else {
      walkingAnims_[dir] = animId;
    }
  }

  updateAnimation();
}

void Sprite::setDirection(Direction dir) {
  if (curDir_ != dir) {
    curDir_ = dir;
    updateAnimation();
  }
}

void Sprite::setWalking(bool walking) {
  if (isWalking_ != walking) {
    isWalking_ = walking;
    updateAnimation();
  }
}

void Sprite::updateAnimation() {
  if (isWalking_) {
    curAnim_ = walkingAnims_[curDir_];
  } else {
    curAnim_ = stillAnims_[curDir_];
  }
  curFrame_ = 0;
}

void Sprite::tickAnim() {
  curFrame_++;
  if (curFrame_ >= animations_[curAnim_].size()) {
    curFrame_ = 0;
  }
}