121 lines
2.6 KiB
C++
121 lines
2.6 KiB
C++
#include "KTexture.h"
|
|
|
|
namespace KapitanGame {
|
|
KTexture::KTexture()
|
|
{
|
|
//Initialize
|
|
Texture = nullptr;
|
|
Width = 0;
|
|
Height = 0;
|
|
}
|
|
|
|
KTexture::KTexture(KTexture&& other) noexcept
|
|
: Texture(other.Texture),
|
|
Width(other.Width),
|
|
Height(other.Height) {
|
|
}
|
|
|
|
KTexture& KTexture::operator=(const KTexture& other) {
|
|
if (this == &other)
|
|
return *this;
|
|
Texture = other.Texture;
|
|
Width = other.Width;
|
|
Height = other.Height;
|
|
return *this;
|
|
}
|
|
|
|
KTexture& KTexture::operator=(KTexture&& other) noexcept {
|
|
if (this == &other)
|
|
return *this;
|
|
Texture = other.Texture;
|
|
Width = other.Width;
|
|
Height = other.Height;
|
|
return *this;
|
|
}
|
|
|
|
KTexture::~KTexture()
|
|
{
|
|
//Deallocate
|
|
Free();
|
|
|
|
}
|
|
bool KTexture::LoadFromFile(const std::string& path, SDL_Renderer* renderer)
|
|
{
|
|
//Get rid of preexisting texture
|
|
Free();
|
|
//The final texture
|
|
SDL_Texture* newTexture = nullptr;
|
|
|
|
//Load image at specified path
|
|
SDL_Surface* loadedSurface = SDL_LoadBMP(path.c_str());
|
|
if (loadedSurface == nullptr)
|
|
{
|
|
printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), SDL_GetError());
|
|
}
|
|
else
|
|
{
|
|
//Color key image
|
|
SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0xFF, 0, 0));
|
|
//Create texture from surface pixels
|
|
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
|
|
if (newTexture == nullptr)
|
|
{
|
|
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 != nullptr;
|
|
}
|
|
|
|
void KTexture::Free()
|
|
{
|
|
//Free texture if it exists
|
|
if (Texture != nullptr)
|
|
{
|
|
SDL_DestroyTexture(Texture);
|
|
Texture = nullptr;
|
|
Width = 0;
|
|
Height = 0;
|
|
}
|
|
}
|
|
|
|
void KTexture::Render(SDL_Renderer* renderer, const int x, const int y, SDL_Rect* clip, const float scale) const
|
|
{
|
|
//Set rendering space and render to screen
|
|
SDL_Rect renderQuad = {
|
|
static_cast<int>(static_cast<float>(x) * scale), static_cast<int>(static_cast<float>(y) * scale),
|
|
static_cast<int>(static_cast<float>(Width) * scale), static_cast<int>(static_cast<float>(Height) * scale)
|
|
};
|
|
|
|
//Set clip rendering dimensions
|
|
if (clip != nullptr)
|
|
{
|
|
renderQuad.w = clip->w;
|
|
renderQuad.h = clip->h;
|
|
}
|
|
|
|
//Render to screen
|
|
SDL_RenderCopy(renderer, Texture, clip, &renderQuad);
|
|
}
|
|
|
|
int KTexture::GetWidth() const
|
|
{
|
|
return Width;
|
|
}
|
|
|
|
int KTexture::GetHeight() const
|
|
{
|
|
return Height;
|
|
}
|
|
} |