blob: fbf7ccf9de30dc4ee5d28c91387b0ece2678ef06 (
plain) (
tree)
|
|
#include "animation.h"
#include <string_view>
#include <fstream>
#include <stdexcept>
#include <string>
#include <regex>
#include <list>
#include "direction.h"
#include "util.h"
Animation::Animation(std::string_view path) {
std::ifstream datafile(path.data());
if (!datafile.is_open()) {
throw std::invalid_argument(std::string("Could not find sprite datafile: ") + path.data());
}
std::string animLine;
char ch;
int cellWidth;
int cellHeight;
datafile >> cellWidth;
datafile >> ch; //,
datafile >> cellHeight;
std::getline(datafile, animLine); // cell size
int framesPerRow;
datafile >> framesPerRow;
std::getline(datafile, animLine); // frames per row
int numFrames;
datafile >> numFrames;
std::getline(datafile, animLine); // frames
std::getline(datafile, animLine); // blank
for (int i=0; i<numFrames; i++) {
SDL_Rect srcRect;
srcRect.x = (i % framesPerRow) * cellWidth;
srcRect.y = (i / framesPerRow) * cellHeight;
srcRect.w = cellWidth;
srcRect.h = cellHeight;
frames_.push_back(srcRect);
}
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::string animName = m[1];
std::vector<int> anim;
auto framestrs = splitStr<std::list<std::string>>(m[3], ",");
for (const std::string& f : framestrs) {
anim.push_back(std::stoi(f));
}
int animId = animations_.size();
animations_.push_back(std::move(anim));
Direction dir = directionFromString(std::string(m[2]));
nameDirToAnim_[animName][dir] = animId;
}
updateAnim();
}
void Animation::setDirection(Direction dir) {
dir_ = dir;
updateAnim();
}
void Animation::setAnimation(std::string_view anim) {
animationName_ = anim;
updateAnim();
}
void Animation::update(int dt) {
animTimer_.accumulate(dt);
while (animTimer_.step()) {
animationFrame_++;
if (animationFrame_ >= animations_.at(animationId_).size()) {
animationFrame_ = 0;
}
}
}
void Animation::updateAnim() {
if (nameDirToAnim_.at(animationName_).at(dir_) != animationId_) {
animationId_ = nameDirToAnim_.at(animationName_).at(dir_);
animationFrame_ = 0;
}
}
|