feat: Sistema de pre-escalado de logos con stb_image_resize2

Implementa pre-escalado de alta calidad para eliminar artefactos de
escalado dinámico de SDL y mejorar la nitidez visual de los logos.

Características:
- 4 texturas pre-escaladas (2 logos × 2 resoluciones: base + nativa)
- Detección automática de resolución nativa del monitor
- Switching dinámico entre texturas al cambiar resolución (F4)
- Renderizado 1:1 sin escalado adicional (máxima calidad)
- Algoritmo Mitchell en espacio sRGB (balance calidad/velocidad)
- Todo en RAM, sin archivos temporales

Archivos nuevos:
- source/external/stb_image_resize2.h: Biblioteca de escalado stb
- source/logo_scaler.h/cpp: Clase helper para pre-escalado

Cambios en AppLogo:
- Reemplazadas shared_ptr<Texture> por SDL_Texture* raw pointers
- initialize(): Pre-escala logos a 2 resoluciones al inicio
- updateScreenSize(): Cambia entre texturas según resolución
- render(): Simplificado, siempre usa renderWithGeometry()
- ~AppLogo(): Libera 4 texturas SDL manualmente

El sistema detecta la resolución nativa al inicio y crea versiones
optimizadas. Al presionar F4, cambia automáticamente a la textura
nativa para calidad perfecta en fullscreen.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-18 10:36:26 +02:00
parent c91cb1ca56
commit ad3f5a00e4
5 changed files with 11063 additions and 150 deletions

View File

@@ -1,77 +1,194 @@
#include "app_logo.h" #include "app_logo.h"
#include <SDL3/SDL_render.h> // for SDL_SCALEMODE_LINEAR, SDL_RenderGeometry #include <SDL3/SDL_render.h> // for SDL_DestroyTexture, SDL_RenderGeometry, SDL_SetTextureAlphaMod
#include <cmath> // for powf, sinf, cosf #include <cmath> // for powf, sinf, cosf
#include <cstdlib> // for free()
#include <iostream> // for std::cout
#include "external/sprite.h" // for Sprite #include "logo_scaler.h" // for LogoScaler
#include "external/texture.h" // for Texture #include "defines.h" // for APPLOGO_HEIGHT_PERCENT, getResourcesDirectory
// ============================================================================
// Destructor - Liberar las 4 texturas SDL
// ============================================================================
AppLogo::~AppLogo() {
if (logo1_base_texture_) {
SDL_DestroyTexture(logo1_base_texture_);
logo1_base_texture_ = nullptr;
}
if (logo1_native_texture_) {
SDL_DestroyTexture(logo1_native_texture_);
logo1_native_texture_ = nullptr;
}
if (logo2_base_texture_) {
SDL_DestroyTexture(logo2_base_texture_);
logo2_base_texture_ = nullptr;
}
if (logo2_native_texture_) {
SDL_DestroyTexture(logo2_native_texture_);
logo2_native_texture_ = nullptr;
}
}
// ============================================================================
// Inicialización - Pre-escalar logos a 2 resoluciones (base y nativa)
// ============================================================================
bool AppLogo::initialize(SDL_Renderer* renderer, int screen_width, int screen_height) { bool AppLogo::initialize(SDL_Renderer* renderer, int screen_width, int screen_height) {
renderer_ = renderer; renderer_ = renderer;
base_screen_width_ = screen_width;
base_screen_height_ = screen_height;
screen_width_ = screen_width; screen_width_ = screen_width;
screen_height_ = screen_height; screen_height_ = screen_height;
std::string resources_dir = getResourcesDirectory(); std::string resources_dir = getResourcesDirectory();
// ======================================================================== // ========================================================================
// Cargar LOGO1 desde data/logo/logo.png // 1. Detectar resolución nativa del monitor
// ========================================================================
if (!LogoScaler::detectNativeResolution(native_screen_width_, native_screen_height_)) {
std::cout << "No se pudo detectar resolución nativa, usando solo base" << std::endl;
// Fallback: usar resolución base como nativa
native_screen_width_ = screen_width;
native_screen_height_ = screen_height;
}
// ========================================================================
// 2. Calcular alturas finales para ambas resoluciones
// ========================================================================
int logo_base_target_height = static_cast<int>(base_screen_height_ * APPLOGO_HEIGHT_PERCENT);
int logo_native_target_height = static_cast<int>(native_screen_height_ * APPLOGO_HEIGHT_PERCENT);
std::cout << "Pre-escalando logos:" << std::endl;
std::cout << " Base: " << base_screen_width_ << "x" << base_screen_height_
<< " (altura logo: " << logo_base_target_height << "px)" << std::endl;
std::cout << " Nativa: " << native_screen_width_ << "x" << native_screen_height_
<< " (altura logo: " << logo_native_target_height << "px)" << std::endl;
// ========================================================================
// 3. Cargar y escalar LOGO1 (data/logo/logo.png) a 2 versiones
// ======================================================================== // ========================================================================
std::string logo1_path = resources_dir + "/data/logo/logo.png"; std::string logo1_path = resources_dir + "/data/logo/logo.png";
logo1_texture_ = std::make_shared<Texture>(renderer, logo1_path);
if (logo1_texture_->getWidth() == 0 || logo1_texture_->getHeight() == 0) { // 3a. Versión BASE de logo1
// Error al cargar textura logo1 unsigned char* logo1_base_data = LogoScaler::loadAndScale(
logo1_path,
0, // width calculado automáticamente por aspect ratio
logo_base_target_height,
logo1_base_width_,
logo1_base_height_
);
if (logo1_base_data == nullptr) {
std::cout << "Error: No se pudo escalar logo1 (base)" << std::endl;
return false; return false;
} }
// Configurar filtrado LINEAR para suavizado logo1_base_texture_ = LogoScaler::createTextureFromBuffer(
logo1_texture_->setScaleMode(SDL_SCALEMODE_LINEAR); renderer, logo1_base_data, logo1_base_width_, logo1_base_height_
);
free(logo1_base_data); // Liberar buffer temporal
// Crear sprite con la textura if (logo1_base_texture_ == nullptr) {
logo1_sprite_ = std::make_unique<Sprite>(logo1_texture_); std::cout << "Error: No se pudo crear textura logo1 (base)" << std::endl;
return false;
}
// Configurar el clip para que use toda la textura // Habilitar alpha blending
float logo1_width = static_cast<float>(logo1_texture_->getWidth()); SDL_SetTextureBlendMode(logo1_base_texture_, SDL_BLENDMODE_BLEND);
float logo1_height = static_cast<float>(logo1_texture_->getHeight());
logo1_sprite_->setClip({0.0f, 0.0f, logo1_width, logo1_height}); // 3b. Versión NATIVA de logo1
unsigned char* logo1_native_data = LogoScaler::loadAndScale(
logo1_path,
0, // width calculado automáticamente
logo_native_target_height,
logo1_native_width_,
logo1_native_height_
);
if (logo1_native_data == nullptr) {
std::cout << "Error: No se pudo escalar logo1 (nativa)" << std::endl;
return false;
}
logo1_native_texture_ = LogoScaler::createTextureFromBuffer(
renderer, logo1_native_data, logo1_native_width_, logo1_native_height_
);
free(logo1_native_data);
if (logo1_native_texture_ == nullptr) {
std::cout << "Error: No se pudo crear textura logo1 (nativa)" << std::endl;
return false;
}
SDL_SetTextureBlendMode(logo1_native_texture_, SDL_BLENDMODE_BLEND);
// ======================================================================== // ========================================================================
// Cargar LOGO2 desde data/logo/logo2.png // 4. Cargar y escalar LOGO2 (data/logo/logo2.png) a 2 versiones
// ======================================================================== // ========================================================================
std::string logo2_path = resources_dir + "/data/logo/logo2.png"; std::string logo2_path = resources_dir + "/data/logo/logo2.png";
logo2_texture_ = std::make_shared<Texture>(renderer, logo2_path);
if (logo2_texture_->getWidth() == 0 || logo2_texture_->getHeight() == 0) { // 4a. Versión BASE de logo2
// Error al cargar textura logo2 unsigned char* logo2_base_data = LogoScaler::loadAndScale(
logo2_path,
0,
logo_base_target_height,
logo2_base_width_,
logo2_base_height_
);
if (logo2_base_data == nullptr) {
std::cout << "Error: No se pudo escalar logo2 (base)" << std::endl;
return false; return false;
} }
// Configurar filtrado LINEAR para suavizado logo2_base_texture_ = LogoScaler::createTextureFromBuffer(
logo2_texture_->setScaleMode(SDL_SCALEMODE_LINEAR); renderer, logo2_base_data, logo2_base_width_, logo2_base_height_
);
free(logo2_base_data);
// Crear sprite con la textura if (logo2_base_texture_ == nullptr) {
logo2_sprite_ = std::make_unique<Sprite>(logo2_texture_); std::cout << "Error: No se pudo crear textura logo2 (base)" << std::endl;
return false;
}
// Configurar el clip para que use toda la textura SDL_SetTextureBlendMode(logo2_base_texture_, SDL_BLENDMODE_BLEND);
float logo2_width = static_cast<float>(logo2_texture_->getWidth());
float logo2_height = static_cast<float>(logo2_texture_->getHeight()); // 4b. Versión NATIVA de logo2
logo2_sprite_->setClip({0.0f, 0.0f, logo2_width, logo2_height}); unsigned char* logo2_native_data = LogoScaler::loadAndScale(
logo2_path,
0,
logo_native_target_height,
logo2_native_width_,
logo2_native_height_
);
if (logo2_native_data == nullptr) {
std::cout << "Error: No se pudo escalar logo2 (nativa)" << std::endl;
return false;
}
logo2_native_texture_ = LogoScaler::createTextureFromBuffer(
renderer, logo2_native_data, logo2_native_width_, logo2_native_height_
);
free(logo2_native_data);
if (logo2_native_texture_ == nullptr) {
std::cout << "Error: No se pudo crear textura logo2 (nativa)" << std::endl;
return false;
}
SDL_SetTextureBlendMode(logo2_native_texture_, SDL_BLENDMODE_BLEND);
// ======================================================================== // ========================================================================
// Calcular tamaño base (asumimos mismo tamaño para ambos logos) // 5. Inicialmente usar texturas BASE (la resolución de inicio)
// El logo debe tener una altura de APPLOGO_HEIGHT_PERCENT (40%) de la pantalla
// ======================================================================== // ========================================================================
float target_height = screen_height_ * APPLOGO_HEIGHT_PERCENT; logo1_current_texture_ = logo1_base_texture_;
float scale = target_height / logo1_height; logo1_current_width_ = logo1_base_width_;
logo1_current_height_ = logo1_base_height_;
base_width_ = logo1_width * scale; logo2_current_texture_ = logo2_base_texture_;
base_height_ = target_height; // = logo1_height * scale logo2_current_width_ = logo2_base_width_;
logo2_current_height_ = logo2_base_height_;
// Aplicar escala inicial a ambos sprites
logo1_sprite_->setSize(base_width_, base_height_);
logo2_sprite_->setSize(base_width_, base_height_);
// Posicionar ambos logos en el centro del cuadrante inferior derecho (superpuestos)
updateLogoPosition();
std::cout << "Logos pre-escalados exitosamente (4 texturas creadas)" << std::endl;
return true; return true;
} }
@@ -340,60 +457,14 @@ void AppLogo::update(float delta_time, AppMode current_mode) {
} }
break; break;
} }
// Aplicar alpha a ambos logos (compartido - sincronizado)
if (logo1_texture_) {
logo1_texture_->setAlpha(current_alpha_);
}
if (logo2_texture_) {
logo2_texture_->setAlpha(current_alpha_);
}
// Aplicar escala animada INDEPENDIENTE a cada logo
if (logo1_sprite_) {
float scaled_width = base_width_ * logo1_scale_;
float scaled_height = base_height_ * logo1_scale_;
logo1_sprite_->setSize(scaled_width, scaled_height);
}
if (logo2_sprite_) {
float scaled_width = base_width_ * logo2_scale_;
float scaled_height = base_height_ * logo2_scale_;
logo2_sprite_->setSize(scaled_width, scaled_height);
}
// Recentrar ambos logos (están superpuestos, misma posición)
updateLogoPosition();
} }
void AppLogo::render() { void AppLogo::render() {
// Renderizar si NO está en estado HIDDEN (incluye FADE_IN, VISIBLE, FADE_OUT) // Renderizar si NO está en estado HIDDEN (incluye FADE_IN, VISIBLE, FADE_OUT)
if (state_ != AppLogoState::HIDDEN) { if (state_ != AppLogoState::HIDDEN) {
// Determinar animaciones actuales para cada logo // Renderizar LOGO1 primero (fondo), luego LOGO2 (encima)
AppLogoAnimationType logo1_anim = (state_ == AppLogoState::FADE_IN) ? logo1_entry_animation_ : logo1_exit_animation_;
AppLogoAnimationType logo2_anim = (state_ == AppLogoState::FADE_IN) ? logo2_entry_animation_ : logo2_exit_animation_;
// ====================================================================
// Renderizar LOGO1 primero (fondo)
// ====================================================================
if (logo1_anim != AppLogoAnimationType::ZOOM_ONLY) {
// Usar renderizado con geometría para deformaciones/rotación
renderWithGeometry(1); renderWithGeometry(1);
} else if (logo1_sprite_) {
// Usar renderizado simple con Sprite (solo ZOOM_ONLY)
logo1_sprite_->render();
}
// ====================================================================
// Renderizar LOGO2 después (encima de logo1)
// ====================================================================
if (logo2_anim != AppLogoAnimationType::ZOOM_ONLY) {
// Usar renderizado con geometría para deformaciones/rotación
renderWithGeometry(2); renderWithGeometry(2);
} else if (logo2_sprite_) {
// Usar renderizado simple con Sprite (solo ZOOM_ONLY)
logo2_sprite_->render();
}
} }
} }
@@ -401,59 +472,37 @@ void AppLogo::updateScreenSize(int screen_width, int screen_height) {
screen_width_ = screen_width; screen_width_ = screen_width;
screen_height_ = screen_height; screen_height_ = screen_height;
// Recalcular tamaño base para la nueva resolución (asumimos mismo tamaño para ambos logos) // ========================================================================
if (logo1_sprite_ && logo1_texture_) { // Detectar si coincide con resolución nativa o base, cambiar texturas
float logo_width = static_cast<float>(logo1_texture_->getWidth()); // ========================================================================
float logo_height = static_cast<float>(logo1_texture_->getHeight()); bool is_native = (screen_width == native_screen_width_ && screen_height == native_screen_height_);
// El logo debe tener una altura de APPLOGO_HEIGHT_PERCENT (40%) de la pantalla if (is_native) {
float target_height = screen_height_ * APPLOGO_HEIGHT_PERCENT; // Cambiar a texturas nativas (F4 fullscreen)
float scale = target_height / logo_height; logo1_current_texture_ = logo1_native_texture_;
logo1_current_width_ = logo1_native_width_;
logo1_current_height_ = logo1_native_height_;
// Recalcular tamaño base logo2_current_texture_ = logo2_native_texture_;
base_width_ = logo_width * scale; logo2_current_width_ = logo2_native_width_;
base_height_ = target_height; // = logo_height * scale logo2_current_height_ = logo2_native_height_;
// Aplicar escala actual a AMBOS logos (respeta la animación en curso) std::cout << "AppLogo: Cambiado a texturas NATIVAS" << std::endl;
if (logo1_sprite_) { } else {
float scaled_width = base_width_ * logo1_scale_; // Cambiar a texturas base (ventana redimensionable)
float scaled_height = base_height_ * logo1_scale_; logo1_current_texture_ = logo1_base_texture_;
logo1_sprite_->setSize(scaled_width, scaled_height); logo1_current_width_ = logo1_base_width_;
logo1_current_height_ = logo1_base_height_;
logo2_current_texture_ = logo2_base_texture_;
logo2_current_width_ = logo2_base_width_;
logo2_current_height_ = logo2_base_height_;
std::cout << "AppLogo: Cambiado a texturas BASE" << std::endl;
} }
if (logo2_sprite_) { // Nota: No es necesario recalcular escalas porque las texturas están pre-escaladas
float scaled_width = base_width_ * logo2_scale_; // al tamaño exacto de pantalla. Solo renderizamos al 100% (o con deformaciones de animación).
float scaled_height = base_height_ * logo2_scale_;
logo2_sprite_->setSize(scaled_width, scaled_height);
}
// Reposicionar ambos logos
updateLogoPosition();
}
}
void AppLogo::updateLogoPosition() {
// Calcular padding desde bordes derecho e inferior
float padding_x = screen_width_ * APPLOGO_PADDING_PERCENT;
float padding_y = screen_height_ * APPLOGO_PADDING_PERCENT;
// Posicionar LOGO1 (anclado a esquina inferior derecha con padding)
if (logo1_sprite_) {
float logo1_width = base_width_ * logo1_scale_;
float logo1_height = base_height_ * logo1_scale_;
float pos_x = screen_width_ - logo1_width - padding_x;
float pos_y = screen_height_ - logo1_height - padding_y;
logo1_sprite_->setPos({pos_x, pos_y});
}
// Posicionar LOGO2 (anclado a esquina inferior derecha con padding, superpuesto a logo1)
if (logo2_sprite_) {
float logo2_width = base_width_ * logo2_scale_;
float logo2_height = base_height_ * logo2_scale_;
float pos_x = screen_width_ - logo2_width - padding_x;
float pos_y = screen_height_ - logo2_height - padding_y;
logo2_sprite_->setPos({pos_x, pos_y});
}
} }
// ============================================================================ // ============================================================================
@@ -528,26 +577,31 @@ AppLogoAnimationType AppLogo::getRandomAnimation() {
} }
// ============================================================================ // ============================================================================
// Renderizado con geometría deformada (para animación ELASTIC_STICK) // Renderizado con geometría (para todos los logos, con deformaciones)
// ============================================================================ // ============================================================================
void AppLogo::renderWithGeometry(int logo_index) { void AppLogo::renderWithGeometry(int logo_index) {
if (!renderer_) return; if (!renderer_) return;
// Seleccionar variables según el logo_index (1 = logo1, 2 = logo2) // Seleccionar variables según el logo_index (1 = logo1, 2 = logo2)
std::shared_ptr<Texture> texture; SDL_Texture* texture;
int base_width, base_height;
float scale, squash_y, stretch_x, rotation; float scale, squash_y, stretch_x, rotation;
if (logo_index == 1) { if (logo_index == 1) {
if (!logo1_texture_) return; if (!logo1_current_texture_) return;
texture = logo1_texture_; texture = logo1_current_texture_;
base_width = logo1_current_width_;
base_height = logo1_current_height_;
scale = logo1_scale_; scale = logo1_scale_;
squash_y = logo1_squash_y_; squash_y = logo1_squash_y_;
stretch_x = logo1_stretch_x_; stretch_x = logo1_stretch_x_;
rotation = logo1_rotation_; rotation = logo1_rotation_;
} else if (logo_index == 2) { } else if (logo_index == 2) {
if (!logo2_texture_) return; if (!logo2_current_texture_) return;
texture = logo2_texture_; texture = logo2_current_texture_;
base_width = logo2_current_width_;
base_height = logo2_current_height_;
scale = logo2_scale_; scale = logo2_scale_;
squash_y = logo2_squash_y_; squash_y = logo2_squash_y_;
stretch_x = logo2_stretch_x_; stretch_x = logo2_stretch_x_;
@@ -556,9 +610,13 @@ void AppLogo::renderWithGeometry(int logo_index) {
return; // Índice inválido return; // Índice inválido
} }
// Aplicar alpha a la textura
SDL_SetTextureAlphaMod(texture, static_cast<Uint8>(current_alpha_));
// Calcular tamaño con escala y deformaciones aplicadas // Calcular tamaño con escala y deformaciones aplicadas
float width = base_width_ * scale * stretch_x; // (base_width y base_height ya están pre-escalados al tamaño correcto de pantalla)
float height = base_height_ * scale * squash_y; float width = base_width * scale * stretch_x;
float height = base_height * scale * squash_y;
// Calcular padding desde bordes derecho e inferior // Calcular padding desde bordes derecho e inferior
float padding_x = screen_width_ * APPLOGO_PADDING_PERCENT; float padding_x = screen_width_ * APPLOGO_PADDING_PERCENT;
@@ -631,5 +689,5 @@ void AppLogo::renderWithGeometry(int logo_index) {
int indices[6] = {0, 1, 2, 2, 3, 0}; int indices[6] = {0, 1, 2, 2, 3, 0};
// Renderizar con la textura del logo correspondiente // Renderizar con la textura del logo correspondiente
SDL_RenderGeometry(renderer_, texture->getSDLTexture(), vertices, 4, indices, 6); SDL_RenderGeometry(renderer_, texture, vertices, 4, indices, 6);
} }

View File

@@ -28,7 +28,7 @@ enum class AppLogoAnimationType {
class AppLogo { class AppLogo {
public: public:
AppLogo() = default; AppLogo() = default;
~AppLogo() = default; ~AppLogo(); // Necesario para liberar las 4 texturas SDL
// Inicializar textura y sprite del logo // Inicializar textura y sprite del logo
bool initialize(SDL_Renderer* renderer, int screen_width, int screen_height); bool initialize(SDL_Renderer* renderer, int screen_width, int screen_height);
@@ -43,13 +43,33 @@ class AppLogo {
void updateScreenSize(int screen_width, int screen_height); void updateScreenSize(int screen_width, int screen_height);
private: private:
// Texturas y sprites (x2 - logo1 y logo2 superpuestos) // ====================================================================
std::shared_ptr<Texture> logo1_texture_; // Textura del logo1 (data/logo/logo.png) // Texturas pre-escaladas (4 texturas: 2 logos × 2 resoluciones)
std::unique_ptr<Sprite> logo1_sprite_; // Sprite para renderizar logo1 // ====================================================================
std::shared_ptr<Texture> logo2_texture_; // Textura del logo2 (data/logo/logo2.png) SDL_Texture* logo1_base_texture_ = nullptr; // Logo1 para resolución base
std::unique_ptr<Sprite> logo2_sprite_; // Sprite para renderizar logo2 SDL_Texture* logo1_native_texture_ = nullptr; // Logo1 para resolución nativa (F4)
SDL_Texture* logo2_base_texture_ = nullptr; // Logo2 para resolución base
SDL_Texture* logo2_native_texture_ = nullptr; // Logo2 para resolución nativa (F4)
// Dimensiones pre-calculadas para cada textura
int logo1_base_width_ = 0, logo1_base_height_ = 0;
int logo1_native_width_ = 0, logo1_native_height_ = 0;
int logo2_base_width_ = 0, logo2_base_height_ = 0;
int logo2_native_width_ = 0, logo2_native_height_ = 0;
// Texturas actualmente en uso (apuntan a base o native según resolución)
SDL_Texture* logo1_current_texture_ = nullptr;
SDL_Texture* logo2_current_texture_ = nullptr;
int logo1_current_width_ = 0, logo1_current_height_ = 0;
int logo2_current_width_ = 0, logo2_current_height_ = 0;
// Resoluciones conocidas
int base_screen_width_ = 0, base_screen_height_ = 0; // Resolución inicial
int native_screen_width_ = 0, native_screen_height_ = 0; // Resolución nativa (F4)
// ====================================================================
// Variables COMPARTIDAS (sincronización de ambos logos) // Variables COMPARTIDAS (sincronización de ambos logos)
// ====================================================================
AppLogoState state_ = AppLogoState::HIDDEN; // Estado actual de la máquina de estados AppLogoState state_ = AppLogoState::HIDDEN; // Estado actual de la máquina de estados
float timer_ = 0.0f; // Contador de tiempo para estado actual float timer_ = 0.0f; // Contador de tiempo para estado actual
int current_alpha_ = 0; // Alpha actual (0-255) int current_alpha_ = 0; // Alpha actual (0-255)

10630
source/external/stb_image_resize2.h vendored Normal file

File diff suppressed because it is too large Load Diff

144
source/logo_scaler.cpp Normal file
View File

@@ -0,0 +1,144 @@
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "logo_scaler.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_log.h> // Para SDL_Log
#include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat
#include <SDL3/SDL_render.h> // Para SDL_CreateTexture
#include <SDL3/SDL_surface.h> // Para SDL_CreateSurfaceFrom
#include <SDL3/SDL_video.h> // Para SDL_GetDisplays
#include <cstdlib> // Para free()
#include <iostream> // Para std::cout
#include "external/stb_image.h" // Para stbi_load, stbi_image_free
#include "external/stb_image_resize2.h" // Para stbir_resize_uint8_srgb
// ============================================================================
// Detectar resolución nativa del monitor principal
// ============================================================================
bool LogoScaler::detectNativeResolution(int& native_width, int& native_height) {
int num_displays = 0;
SDL_DisplayID* displays = SDL_GetDisplays(&num_displays);
if (displays == nullptr || num_displays == 0) {
SDL_Log("Error al obtener displays: %s", SDL_GetError());
return false;
}
// Obtener resolución del display principal (displays[0])
const auto* dm = SDL_GetCurrentDisplayMode(displays[0]);
if (dm == nullptr) {
SDL_Log("Error al obtener modo del display: %s", SDL_GetError());
SDL_free(displays);
return false;
}
native_width = dm->w;
native_height = dm->h;
SDL_free(displays);
std::cout << "Resolución nativa detectada: " << native_width << "x" << native_height << std::endl;
return true;
}
// ============================================================================
// Cargar PNG y escalar al tamaño especificado
// ============================================================================
unsigned char* LogoScaler::loadAndScale(const std::string& path,
int target_width, int target_height,
int& out_width, int& out_height) {
// 1. Cargar imagen original con stb_image
int orig_width, orig_height, orig_channels;
unsigned char* orig_data = stbi_load(path.c_str(), &orig_width, &orig_height, &orig_channels, STBI_rgb_alpha);
if (orig_data == nullptr) {
SDL_Log("Error al cargar imagen %s: %s", path.c_str(), stbi_failure_reason());
return nullptr;
}
std::cout << "Imagen cargada: " << path << " (" << orig_width << "x" << orig_height << ")" << std::endl;
// 2. Calcular tamaño final manteniendo aspect ratio
// El alto está fijado por target_height (APPLOGO_HEIGHT_PERCENT)
// Calcular ancho proporcional al aspect ratio original
float aspect_ratio = static_cast<float>(orig_width) / static_cast<float>(orig_height);
out_width = static_cast<int>(target_height * aspect_ratio);
out_height = target_height;
std::cout << " Escalando a: " << out_width << "x" << out_height << std::endl;
// 3. Alocar buffer para imagen escalada (RGBA = 4 bytes por píxel)
unsigned char* scaled_data = static_cast<unsigned char*>(malloc(out_width * out_height * 4));
if (scaled_data == nullptr) {
SDL_Log("Error al alocar memoria para imagen escalada");
stbi_image_free(orig_data);
return nullptr;
}
// 4. Escalar con stb_image_resize2 (algoritmo Mitchell, espacio sRGB)
// La función devuelve el puntero de salida, o nullptr si falla
unsigned char* result = stbir_resize_uint8_srgb(
orig_data, orig_width, orig_height, 0, // Input
scaled_data, out_width, out_height, 0, // Output
STBIR_RGBA // Formato píxel
);
// Liberar imagen original (ya no la necesitamos)
stbi_image_free(orig_data);
if (result == nullptr) {
SDL_Log("Error al escalar imagen");
free(scaled_data);
return nullptr;
}
std::cout << " Escalado completado correctamente" << std::endl;
return scaled_data;
}
// ============================================================================
// Crear textura SDL desde buffer RGBA
// ============================================================================
SDL_Texture* LogoScaler::createTextureFromBuffer(SDL_Renderer* renderer,
unsigned char* data,
int width, int height) {
if (renderer == nullptr || data == nullptr || width <= 0 || height <= 0) {
SDL_Log("Parámetros inválidos para createTextureFromBuffer");
return nullptr;
}
// 1. Crear surface SDL desde buffer RGBA
int pitch = width * 4; // 4 bytes por píxel (RGBA)
SDL_PixelFormat pixel_format = SDL_PIXELFORMAT_RGBA32;
SDL_Surface* surface = SDL_CreateSurfaceFrom(
width, height,
pixel_format,
data,
pitch
);
if (surface == nullptr) {
SDL_Log("Error al crear surface: %s", SDL_GetError());
return nullptr;
}
// 2. Crear textura desde surface
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture == nullptr) {
SDL_Log("Error al crear textura: %s", SDL_GetError());
SDL_DestroySurface(surface);
return nullptr;
}
// 3. Liberar surface (la textura ya tiene los datos)
SDL_DestroySurface(surface);
return texture;
}

61
source/logo_scaler.h Normal file
View File

@@ -0,0 +1,61 @@
#pragma once
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_video.h> // Para SDL_DisplayID, SDL_GetDisplays
#include <string> // Para std::string
/**
* @brief Helper class para pre-escalar logos usando stb_image_resize2
*
* Proporciona funciones para:
* - Detectar resolución nativa del monitor
* - Cargar PNG y escalar a tamaño específico con algoritmos de alta calidad
* - Crear texturas SDL desde buffers escalados
*
* Usado por AppLogo para pre-generar versiones de logos al tamaño exacto
* de pantalla, eliminando el escalado dinámico de SDL y mejorando calidad visual.
*/
class LogoScaler {
public:
/**
* @brief Detecta la resolución nativa del monitor principal
*
* @param native_width [out] Ancho nativo del display en píxeles
* @param native_height [out] Alto nativo del display en píxeles
* @return true si se pudo detectar, false si hubo error
*/
static bool detectNativeResolution(int& native_width, int& native_height);
/**
* @brief Carga un PNG y lo escala al tamaño especificado
*
* Usa stb_image para cargar y stb_image_resize2 para escalar con
* algoritmo Mitchell (balance calidad/velocidad) en espacio sRGB.
*
* @param path Ruta al archivo PNG (ej: "data/logo/logo.png")
* @param target_width Ancho destino en píxeles
* @param target_height Alto destino en píxeles
* @param out_width [out] Ancho real de la imagen escalada
* @param out_height [out] Alto real de la imagen escalada
* @return Buffer RGBA (4 bytes por píxel) o nullptr si falla
* IMPORTANTE: El caller debe liberar con free() cuando termine
*/
static unsigned char* loadAndScale(const std::string& path,
int target_width, int target_height,
int& out_width, int& out_height);
/**
* @brief Crea una textura SDL desde un buffer RGBA
*
* @param renderer Renderizador SDL activo
* @param data Buffer RGBA (4 bytes por píxel)
* @param width Ancho del buffer en píxeles
* @param height Alto del buffer en píxeles
* @return Textura SDL creada o nullptr si falla
* IMPORTANTE: El caller debe destruir con SDL_DestroyTexture()
*/
static SDL_Texture* createTextureFromBuffer(SDL_Renderer* renderer,
unsigned char* data,
int width, int height);
};