#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 line; std::string imagename; datafile >> imagename; textureId_ = renderer.loadImageFromFile(imagename); std::string framefilename; datafile >> framefilename; std::ifstream framefile(framefilename); if (!framefile.is_open()) { throw std::invalid_argument("Could not find frame datafile: " + framefilename); } vec2i cellSize; framefile >> cellSize.w(); framefile >> ch; //, framefile >> cellSize.h(); std::getline(framefile, line); // cell size int framesPerRow; framefile >> framesPerRow; std::getline(framefile, line); // frames per row int numFrames; framefile >> numFrames; std::getline(framefile, line); // frames std::getline(framefile, line); // blank for (int i=0; i> f.size.w(); framefile >> ch; //, framefile >> f.size.h(); framefile >> ch; //, framefile >> f.center.x(); framefile >> ch; //, framefile >> f.center.y(); std::getline(framefile, line); // blank f.srcRect.x = (i % framesPerRow) * cellSize.w(); f.srcRect.y = (i / framesPerRow) * cellSize.h(); f.srcRect.w = f.size.w(); f.srcRect.h = f.size.h(); frames_.push_back(std::move(f)); } 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; } }