summaryrefslogtreecommitdiff
path: root/core/src/cpp/sprite.cpp
blob: afd633da2e86b98df5dfeaf444850b53a5e55b93 (plain)
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
#include "sprite.h"

#include <iostream>

#include <SDL_render.h>
#include <SDL_surface.h>

Sprite::Sprite(
    SDL_Renderer* renderer,
    const std::string& filename,
    const int width
)
    : width{width}
{
    SDL_Surface* surface =
        SDL_LoadBMP((std::string(RESOURCES_DIR) + filename).c_str());

    if (!surface)
    {
        std::cerr << "Error in SDL_LoadBMP: " << SDL_GetError() << std::endl;
        return;
    }

    if (!(surface->w % width) && surface->w / width)
    {  // image width must be a multiple of sprite width
        height = surface->h;
        nframes = surface->w / width;
        texture = SDL_CreateTextureFromSurface(renderer, surface);
    }
    else
    {
        std::cerr << "Incorrect sprite size" << std::endl;
    }

    SDL_FreeSurface(surface);
}

Sprite::~Sprite()
{
    if (texture)
    {
        SDL_DestroyTexture(texture);
    }
}

SDL_Rect Sprite::rect(const int idx) const
{
    return {idx * width, 0, width, height};
}