99 lines
2.1 KiB
C++
99 lines
2.1 KiB
C++
#include "Sprite.hpp"
|
|
#include "Game.hpp"
|
|
|
|
Sprite::Sprite(Node *parent) : Node(parent, true) {}
|
|
|
|
Sprite::Sprite(Node *parent, std::string path) : Node(parent, true)
|
|
{
|
|
associate(path);
|
|
animation.play();
|
|
}
|
|
|
|
void Sprite::set_frame_length(float length)
|
|
{
|
|
animation.set_frame_length(length);
|
|
}
|
|
|
|
void Sprite::associate(std::string path)
|
|
{
|
|
if (fs::is_regular_file(path))
|
|
{
|
|
frame_paths.push_back(fs::path(path));
|
|
}
|
|
else if (fs::is_directory(path))
|
|
{
|
|
fs::directory_iterator directory(path);
|
|
std::vector<fs::path> paths;
|
|
std::copy(directory, fs::directory_iterator(), std::back_inserter(paths));
|
|
std::sort(paths.begin(), paths.end());
|
|
for (const fs::path &name : paths)
|
|
{
|
|
std::cout << "associating " << name << std::endl;
|
|
frame_paths.push_back(name);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
std::ostringstream message;
|
|
message << "invalid path " << path;
|
|
get_root()->print_error(message.str());
|
|
}
|
|
}
|
|
|
|
void Sprite::load()
|
|
{
|
|
for (const fs::path &path : frame_paths)
|
|
{
|
|
load_file(path);
|
|
}
|
|
}
|
|
|
|
void Sprite::load_file(fs::path path)
|
|
{
|
|
Game *game = get_root();
|
|
SDL_Texture *texture = IMG_LoadTexture(game->renderer, path.string().c_str());
|
|
if (not texture)
|
|
{
|
|
game->print_sdl_error("Could not load image");
|
|
}
|
|
else
|
|
{
|
|
add_frame(texture);
|
|
}
|
|
}
|
|
|
|
void Sprite::add_frame(SDL_Texture *texture)
|
|
{
|
|
frames.push_back(texture);
|
|
}
|
|
|
|
void Sprite::unload()
|
|
{
|
|
while (not frames.empty())
|
|
{
|
|
SDL_DestroyTexture(frames.back());
|
|
frames.pop_back();
|
|
}
|
|
}
|
|
|
|
void Sprite::advance_frame()
|
|
{
|
|
if (++frame_ii >= frames.size())
|
|
{
|
|
frame_ii = 0;
|
|
}
|
|
}
|
|
|
|
void Sprite::update()
|
|
{
|
|
if (active)
|
|
{
|
|
animation.update();
|
|
int w, h;
|
|
SDL_Texture *frame = frames[frame_ii];
|
|
SDL_QueryTexture(frame, NULL, NULL, &w, &h);
|
|
SDL_Rect frame_rect = {location.get_x(), location.get_y(), w, h};
|
|
SDL_RenderCopy(get_root()->renderer, frame, NULL, &frame_rect);
|
|
}
|
|
}
|