102 lines
1.8 KiB
C++
102 lines
1.8 KiB
C++
#include <SDL2/SDL_image.h>
|
|
#include <stdio.h>
|
|
#include <string>
|
|
#include "texture.h"
|
|
|
|
Texture::Texture(SDL_Renderer *renderer)
|
|
{
|
|
this->renderer = renderer;
|
|
texture = NULL;
|
|
width = 0;
|
|
height = 0;
|
|
}
|
|
|
|
Texture::Texture(SDL_Renderer *renderer, std::string filepath)
|
|
{
|
|
this->renderer = renderer;
|
|
texture = NULL;
|
|
width = 0;
|
|
height = 0;
|
|
loadFromFile(filepath);
|
|
}
|
|
|
|
Texture::~Texture()
|
|
{
|
|
free();
|
|
}
|
|
|
|
bool Texture::loadFromFile(std::string path)
|
|
{
|
|
// Get rid of preexisting texture
|
|
free();
|
|
|
|
// The final texture
|
|
SDL_Texture *newTexture = NULL;
|
|
|
|
// Load image at specified path
|
|
SDL_Surface *loadedSurface = IMG_Load(path.c_str());
|
|
if (loadedSurface == NULL)
|
|
{
|
|
printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
|
|
}
|
|
else
|
|
{
|
|
// Color key image
|
|
SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF));
|
|
|
|
// Create texture from surface pixels
|
|
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
|
|
if (newTexture == NULL)
|
|
{
|
|
printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
|
|
}
|
|
else
|
|
{
|
|
// Get image dimensions
|
|
width = loadedSurface->w;
|
|
height = loadedSurface->h;
|
|
}
|
|
|
|
// Get rid of old loaded surface
|
|
SDL_FreeSurface(loadedSurface);
|
|
}
|
|
|
|
// Return success
|
|
texture = newTexture;
|
|
return texture != NULL;
|
|
}
|
|
|
|
void Texture::free()
|
|
{
|
|
// Free texture if it exists
|
|
if (texture != NULL)
|
|
{
|
|
SDL_DestroyTexture(texture);
|
|
texture = NULL;
|
|
width = 0;
|
|
height = 0;
|
|
}
|
|
}
|
|
|
|
void Texture::render(SDL_Rect *src, SDL_Rect *dst)
|
|
{
|
|
// Render to screen
|
|
SDL_RenderCopy(renderer, texture, src, dst);
|
|
}
|
|
|
|
int Texture::getWidth()
|
|
{
|
|
return width;
|
|
}
|
|
|
|
int Texture::getHeight()
|
|
{
|
|
return height;
|
|
}
|
|
|
|
// Modulación de color
|
|
void Texture::setColor(int r, int g, int b)
|
|
{
|
|
SDL_SetTextureColorMod(texture, r, g, b);
|
|
}
|