summaryrefslogtreecommitdiff
path: root/core/src/cpp/sprite.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'core/src/cpp/sprite.cpp')
-rw-r--r--core/src/cpp/sprite.cpp49
1 files changed, 49 insertions, 0 deletions
diff --git a/core/src/cpp/sprite.cpp b/core/src/cpp/sprite.cpp
new file mode 100644
index 0000000..afd633d
--- /dev/null
+++ b/core/src/cpp/sprite.cpp
@@ -0,0 +1,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};
+}