#include "sprite.h" #include #include #include #include #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 frames; auto framestrs = splitStr>(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])); stateDirToAnim_[m[1]][dir] = animId; } updateAnimation(); } void Sprite::setDirection(Direction dir) { if (curDir_ != dir) { curDir_ = dir; updateAnimation(); } } void Sprite::setState(std::string state) { if (state_ != state) { state_ = state; updateAnimation(); } } void Sprite::updateAnimation() { curAnim_ = stateDirToAnim_[state_][curDir_]; curFrame_ = 0; } void Sprite::tickAnim() { curFrame_++; if (curFrame_ >= animations_[curAnim_].size()) { curFrame_ = 0; } }