game/sdlpp/sdlpp_texture.cpp

81 lines
3.0 KiB
C++
Raw Normal View History

2020-11-21 19:57:40 +00:00
#include "sdlpp_texture.hpp"
namespace SDLPP {
Texture::Texture( std::shared_ptr< Renderer > &renderer,
const std::string &img_path, const std::string &color_key ) {
SDL_Surface *surface = IMG_Load( img_path.c_str() );
if ( surface == NULL ) {
std::cerr << "Unable to load image '" << img_path
<< "': IMG Error: " << IMG_GetError() << std::endl;
throw "IMG_Load error";
}
if ( !color_key.empty() ) {
2021-03-15 13:48:48 +00:00
auto color = getSDLColorHEX( color_key );
SDL_SetColorKey(
surface, SDL_TRUE,
SDL_MapRGB( surface->format, color.r, color.g, color.b ) );
2020-11-21 19:57:40 +00:00
}
setTextureFromSurface( renderer, surface );
}
Texture::Texture( std::shared_ptr< Renderer > &renderer, Font &font,
const std::string &text, const std::string &color,
const std::string &outline_color, const int outline_size ) {
if ( outline_size != -1 ) {
font.setOutline( outline_size );
}
int og_outline = 0;
SDL_Surface *bg_surface = NULL;
if ( ( og_outline = font.getOutline() ) != 0 ) {
bg_surface = TTF_RenderUTF8_Blended( font.getFont(), text.c_str(),
getSDLColorHEX( outline_color ) );
if ( bg_surface == NULL ) {
std::cerr << "Unable to render text '" << text
<< "': TTF Error: " << TTF_GetError() << std::endl;
throw "TTF_RenderUTF8_Shaded error";
}
font.setOutline( 0 );
}
SDL_Surface *surface = TTF_RenderUTF8_Blended( font.getFont(), text.c_str(),
getSDLColorHEX( color ) );
if ( surface == NULL ) {
std::cerr << "Unable to render text '" << text
<< "': TTF Error: " << TTF_GetError() << std::endl;
throw "TTF_RenderUTF8_Shaded error";
}
if ( og_outline != 0 ) {
SDL_Rect rect = { og_outline, og_outline, surface->w, surface->h };
SDL_SetSurfaceBlendMode( surface, SDL_BLENDMODE_BLEND );
SDL_BlitSurface( surface, NULL, bg_surface, &rect );
SDL_FreeSurface( surface );
surface = bg_surface;
bg_surface = NULL;
font.setOutline( og_outline );
}
setTextureFromSurface( renderer, surface );
}
Texture::~Texture() {
if ( texture != nullptr )
SDL_DestroyTexture( texture );
2020-11-21 19:57:40 +00:00
}
SDL_Texture *Texture::getTexturePtr() {
return texture;
}
void Texture::setTextureFromSurface( std::shared_ptr< Renderer > &renderer,
SDL_Surface *surface ) {
texture =
SDL_CreateTextureFromSurface( renderer->getRendererPtr(), surface );
if ( texture == NULL ) {
std::cerr << "Unable to create texture from surface! SDL Error: "
<< SDL_GetError() << std::endl;
throw "Texture error";
}
SDL_FreeSurface( surface );
}
2021-03-07 12:18:58 +00:00
void Texture::setAlpha( uint8_t alpha ) {
SDL_SetTextureBlendMode( texture, SDL_BLENDMODE_BLEND );
SDL_SetTextureAlphaMod( texture, alpha );
}
2020-11-21 19:57:40 +00:00
} // namespace SDLPP