This commit is contained in:
2025-10-27 18:35:53 +01:00
parent b1dca32a5b
commit 3179a08dac
63 changed files with 686 additions and 693 deletions

View File

@@ -27,7 +27,7 @@ inline void initializeDictionary(std::vector<DictionaryEntry>& dictionary, int c
}
// Lee los próximos bits del stream de entrada para formar un código
inline int readNextCode(const uint8_t*& input, int& input_length, unsigned int& mask, int code_length) {
inline auto readNextCode(const uint8_t*& input, int& input_length, unsigned int& mask, int code_length) -> int {
int code = 0;
for (int i = 0; i < (code_length + 1); i++) {
if (input_length <= 0) {
@@ -46,7 +46,7 @@ inline int readNextCode(const uint8_t*& input, int& input_length, unsigned int&
}
// Encuentra el primer byte de una cadena del diccionario
inline uint8_t findFirstByte(const std::vector<DictionaryEntry>& dictionary, int code) {
inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int code) -> uint8_t {
int ptr = code;
while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev;
@@ -76,13 +76,13 @@ inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& di
}
// Escribe la cadena decodificada al buffer de salida
inline int writeDecodedString(const std::vector<DictionaryEntry>& dictionary, int code, uint8_t*& out) {
inline auto writeDecodedString(const std::vector<DictionaryEntry>& dictionary, int code, uint8_t*& out) -> int {
int cur_code = code;
int match_len = dictionary[cur_code].len;
while (cur_code != -1) {
out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
if (dictionary[cur_code].prev == cur_code) {
std::cerr << "Internal error; self-reference detected." << std::endl;
std::cerr << "Internal error; self-reference detected." << '\n';
throw std::runtime_error("Internal error in decompress: self-reference");
}
cur_code = dictionary[cur_code].prev;
@@ -127,7 +127,7 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
if (prev > -1 && code_length < 12) {
if (code > dictionary_ind) {
std::cerr << "code = " << std::hex << code
<< ", but dictionary_ind = " << dictionary_ind << std::endl;
<< ", but dictionary_ind = " << dictionary_ind << '\n';
throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
}
@@ -139,7 +139,7 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
// Verifica que 'code' sea un índice válido antes de usarlo.
if (code < 0 || static_cast<size_t>(code) >= dictionary.size()) {
std::cerr << "Invalid LZW code " << code
<< ", dictionary size " << dictionary.size() << std::endl;
<< ", dictionary size " << dictionary.size() << '\n';
throw std::runtime_error("LZW error: invalid code encountered");
}
@@ -147,7 +147,7 @@ void Gif::decompress(int code_length, const uint8_t* input, int input_length, ui
}
}
std::vector<uint8_t> Gif::readSubBlocks(const uint8_t*& buffer) {
auto Gif::readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t> {
std::vector<uint8_t> data;
uint8_t block_size = *buffer;
buffer++;
@@ -160,7 +160,7 @@ std::vector<uint8_t> Gif::readSubBlocks(const uint8_t*& buffer) {
return data;
}
std::vector<uint8_t> Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) {
auto Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t> {
ImageDescriptor image_descriptor;
// Lee 9 bytes para el image descriptor.
readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor));
@@ -176,7 +176,7 @@ std::vector<uint8_t> Gif::processImageDescriptor(const uint8_t*& buffer, const s
return uncompressed_data;
}
std::vector<uint32_t> Gif::loadPalette(const uint8_t* buffer) {
auto Gif::loadPalette(const uint8_t* buffer) -> std::vector<uint32_t> {
uint8_t header[6];
std::memcpy(header, buffer, 6);
buffer += 6;
@@ -200,7 +200,7 @@ std::vector<uint32_t> Gif::loadPalette(const uint8_t* buffer) {
return global_color_table;
}
std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) {
auto Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
// Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a")
uint8_t header[6];
std::memcpy(header, buffer, 6);
@@ -280,7 +280,7 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
// Procesar el Image Descriptor y retornar los datos de imagen
return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
} else {
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << std::endl;
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << '\n';
return std::vector<uint8_t>{};
}
block_type = *buffer++;
@@ -289,7 +289,7 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t* buffer, uint16_t& w, u
return std::vector<uint8_t>{};
}
std::vector<uint8_t> Gif::loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) {
auto Gif::loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
return processGifStream(buffer, w, h);
}

View File

@@ -72,21 +72,21 @@ class Gif {
// Carga la paleta (global color table) a partir de un buffer,
// retornándola en un vector de uint32_t (cada color se compone de R, G, B).
static std::vector<uint32_t> loadPalette(const uint8_t* buffer);
static auto loadPalette(const uint8_t* buffer) -> std::vector<uint32_t>;
// Carga el stream GIF; devuelve un vector con los datos de imagen sin comprimir y
// asigna el ancho y alto mediante referencias.
static std::vector<uint8_t> loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h);
static auto loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
private:
// Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>.
static std::vector<uint8_t> readSubBlocks(const uint8_t*& buffer);
static auto readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t>;
// Procesa el Image Descriptor y retorna el vector de datos sin comprimir.
static std::vector<uint8_t> processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits);
static auto processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t>;
// Procesa el stream completo del GIF y devuelve los datos sin comprimir.
static std::vector<uint8_t> processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h);
static auto processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
};
} // namespace GIF

View File

@@ -14,7 +14,7 @@ OpenGLShader::~OpenGLShader() {
}
#ifndef __APPLE__
bool OpenGLShader::initGLExtensions() {
auto OpenGLShader::initGLExtensions() -> bool {
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
@@ -61,7 +61,7 @@ void OpenGLShader::checkGLError(const char* operation) {
}
}
GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type) {
auto OpenGLShader::compileShader(const std::string& source, GLenum shader_type) -> GLuint {
if (source.empty()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"ERROR: El código fuente del shader está vacío");
@@ -104,7 +104,7 @@ GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type
return shader_id;
}
GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) {
auto OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint {
GLuint program = glCreateProgram();
if (program == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
@@ -196,7 +196,7 @@ void OpenGLShader::createQuadGeometry() {
checkGLError("glBufferData(EBO)");
// Atributo 0: Posición (2 floats)
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)nullptr);
glEnableVertexAttribArray(0);
checkGLError("glVertexAttribPointer(position)");
@@ -210,7 +210,7 @@ void OpenGLShader::createQuadGeometry() {
glBindVertexArray(0);
}
GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
auto OpenGLShader::getTextureID(SDL_Texture* texture) -> GLuint {
if (texture == nullptr) {
return 1;
}
@@ -238,10 +238,10 @@ GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
return texture_id;
}
bool OpenGLShader::init(SDL_Window* window,
auto OpenGLShader::init(SDL_Window* window,
SDL_Texture* texture,
const std::string& vertex_source,
const std::string& fragment_source) {
const std::string& fragment_source) -> bool {
window_ = window;
back_buffer_ = texture;
renderer_ = SDL_GetRenderer(window);
@@ -432,7 +432,7 @@ void OpenGLShader::render() {
// Dibujar quad usando VAO
glBindVertexArray(vao_);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
checkGLError("glDrawElements");
// Presentar

View File

@@ -23,23 +23,23 @@ class OpenGLShader : public ShaderBackend {
OpenGLShader() = default;
~OpenGLShader() override;
bool init(SDL_Window* window,
auto init(SDL_Window* window,
SDL_Texture* texture,
const std::string& vertex_source,
const std::string& fragment_source) override;
const std::string& fragment_source) -> bool override;
void render() override;
void setTextureSize(float width, float height) override;
void cleanup() final;
bool isHardwareAccelerated() const override { return is_initialized_; }
[[nodiscard]] auto isHardwareAccelerated() const -> bool override { return is_initialized_; }
private:
// Funciones auxiliares
bool initGLExtensions();
GLuint compileShader(const std::string& source, GLenum shader_type);
GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader);
auto initGLExtensions() -> bool;
auto compileShader(const std::string& source, GLenum shader_type) -> GLuint;
auto linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint;
void createQuadGeometry();
static GLuint getTextureID(SDL_Texture* texture);
static auto getTextureID(SDL_Texture* texture) -> GLuint;
static void checkGLError(const char* operation);
// Estado SDL

View File

@@ -1,11 +1,11 @@
#pragma once
#include <SDL3/SDL.h>
#include <stddef.h> // Para size_t
#include <memory> // Para shared_ptr, __shared_ptr_access
#include <string> // Para string
#include <vector> // Para vector
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, __shared_ptr_access
#include <string> // Para string
#include <vector> // Para vector
#include "utils/utils.hpp" // Para Color
class Surface;
@@ -32,15 +32,14 @@ class Screen {
};
struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frame_count; // Número acumulado de frames en el intervalo.
int last_value; // Número de frames calculado en el último segundo.
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
int frame_count{0}; // Número acumulado de frames en el intervalo.
int last_value{0}; // Número de frames calculado en el último segundo.
// Constructor para inicializar la estructura.
FPS()
: ticks(0),
frame_count(0),
last_value(0) {}
{}
// Incrementador que se llama en cada frame.
void increment() {
@@ -48,7 +47,7 @@ class Screen {
}
// Método para calcular y devolver el valor de FPS.
int calculate(Uint32 current_ticks) {
auto calculate(Uint32 current_ticks) -> int {
if (current_ticks - ticks >= 1000) // Si ha pasado un segundo o más.
{
last_value = frame_count; // Actualizamos el valor del último FPS.
@@ -114,7 +113,7 @@ class Screen {
void renderOverlays();
// Localiza la paleta dentro del vector de paletas
size_t findPalette(const std::string& name);
auto findPalette(const std::string& name) -> size_t;
void initShaders(); // Inicializa los shaders
void loadShaders(); // Carga el contenido del archivo GLSL
@@ -136,7 +135,7 @@ class Screen {
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static Screen* get();
static auto get() -> Screen*;
// Limpia el renderer
void clearRenderer(Color color = {0x00, 0x00, 0x00});
@@ -163,10 +162,10 @@ class Screen {
void toggleIntegerScale();
// Reduce el tamaño de la ventana
bool decWindowZoom();
auto decWindowZoom() -> bool;
// Aumenta el tamaño de la ventana
bool incWindowZoom();
auto incWindowZoom() -> bool;
// Cambia el color del borde
void setBorderColor(Uint8 color);
@@ -209,7 +208,7 @@ class Screen {
void toggleDebugInfo();
// Getters
SDL_Renderer* getRenderer();
std::shared_ptr<Surface> getRendererSurface();
std::shared_ptr<Surface> getBorderSurface();
auto getRenderer() -> SDL_Renderer*;
auto getRendererSurface() -> std::shared_ptr<Surface>;
auto getBorderSurface() -> std::shared_ptr<Surface>;
};

View File

@@ -24,10 +24,10 @@ class ShaderBackend {
* @param fragment_source Código fuente del fragment shader
* @return true si la inicialización fue exitosa
*/
virtual bool init(SDL_Window* window,
virtual auto init(SDL_Window* window,
SDL_Texture* texture,
const std::string& vertex_source,
const std::string& fragment_source) = 0;
const std::string& fragment_source) -> bool = 0;
/**
* @brief Renderiza la textura con los shaders aplicados
@@ -50,7 +50,7 @@ class ShaderBackend {
* @brief Verifica si el backend está usando aceleración por hardware
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
*/
virtual bool isHardwareAccelerated() const = 0;
[[nodiscard]] virtual auto isHardwareAccelerated() const -> bool = 0;
};
} // namespace Rendering

View File

@@ -18,7 +18,7 @@
#include "core/rendering/screen.hpp" // Para Screen
// Carga una paleta desde un archivo .gif
Palette loadPalette(const std::string& file_path) {
auto loadPalette(const std::string& file_path) -> Palette {
// Abrir el archivo en modo binario
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
@@ -51,7 +51,7 @@ Palette loadPalette(const std::string& file_path) {
}
// Carga una paleta desde un archivo .pal
Palette readPalFile(const std::string& file_path) {
auto readPalFile(const std::string& file_path) -> Palette {
Palette palette{};
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)
@@ -107,11 +107,11 @@ Surface::Surface(const std::string& file_path)
}
// Carga una superficie desde un archivo
SurfaceData Surface::loadSurface(const std::string& file_path) {
auto Surface::loadSurface(const std::string& file_path) -> SurfaceData {
// Abrir el archivo usando std::ifstream para manejo automático del recurso
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
std::cerr << "Error opening file: " << file_path << std::endl;
std::cerr << "Error opening file: " << file_path << '\n';
throw std::runtime_error("Error opening file");
}
@@ -122,7 +122,7 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
// Leer el contenido del archivo en un buffer
std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) {
std::cerr << "Error reading file: " << file_path << std::endl;
std::cerr << "Error reading file: " << file_path << '\n';
throw std::runtime_error("Error reading file");
}
@@ -131,7 +131,7 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
Uint16 h = 0;
std::vector<Uint8> raw_pixels = GIF::Gif::loadGif(buffer.data(), w, h);
if (raw_pixels.empty()) {
std::cerr << "Error loading GIF from file: " << file_path << std::endl;
std::cerr << "Error loading GIF from file: " << file_path << '\n';
throw std::runtime_error("Error loading GIF");
}
@@ -143,7 +143,7 @@ SurfaceData Surface::loadSurface(const std::string& file_path) {
// Crear y devolver directamente el objeto SurfaceData
printWithDots("Surface : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
return SurfaceData(w, h, pixels);
return {static_cast<float>(w), static_cast<float>(h), pixels};
}
// Carga una paleta desde un archivo
@@ -179,7 +179,7 @@ void Surface::putPixel(int x, int y, Uint8 color) {
}
// Obtiene el color de un pixel de la surface_data
Uint8 Surface::getPixel(int x, int y) { return surface_data_->data.get()[x + (y * static_cast<int>(surface_data_->width))]; }
auto Surface::getPixel(int x, int y) -> Uint8 { return surface_data_->data.get()[x + (y * static_cast<int>(surface_data_->width))]; }
// Dibuja un rectangulo relleno
void Surface::fillRect(const SDL_FRect* rect, Uint8 color) {
@@ -527,7 +527,7 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR
}
// Realiza un efecto de fundido en la paleta principal
bool Surface::fadePalette() {
auto Surface::fadePalette() -> bool {
// Verificar que el tamaño mínimo de palette_ sea adecuado
static constexpr int PALETTE_SIZE = 19;
if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) {
@@ -547,7 +547,7 @@ bool Surface::fadePalette() {
}
// Realiza un efecto de fundido en la paleta secundaria
bool Surface::fadeSubPalette(Uint32 delay) {
auto Surface::fadeSubPalette(Uint32 delay) -> bool {
// Variable estática para almacenar el último tick
static Uint32 last_tick_ = 0;

View File

@@ -15,10 +15,10 @@ using Palette = std::array<Uint32, 256>;
using SubPalette = std::array<Uint8, 256>;
// Carga una paleta desde un archivo .gif
Palette loadPalette(const std::string& file_path);
auto loadPalette(const std::string& file_path) -> Palette;
// Carga una paleta desde un archivo .pal
Palette readPalFile(const std::string& file_path);
auto readPalFile(const std::string& file_path) -> Palette;
struct SurfaceData {
std::shared_ptr<Uint8[]> data; // Usa std::shared_ptr para gestión automática
@@ -47,11 +47,11 @@ struct SurfaceData {
SurfaceData(SurfaceData&& other) noexcept = default;
// Operador de movimiento
SurfaceData& operator=(SurfaceData&& other) noexcept = default;
auto operator=(SurfaceData&& other) noexcept -> SurfaceData& = default;
// Evita copias accidentales
SurfaceData(const SurfaceData&) = delete;
SurfaceData& operator=(const SurfaceData&) = delete;
auto operator=(const SurfaceData&) -> SurfaceData& = delete;
};
class Surface {
@@ -70,7 +70,7 @@ class Surface {
~Surface() = default;
// Carga una SurfaceData desde un archivo
static SurfaceData loadSurface(const std::string& file_path);
static auto loadSurface(const std::string& file_path) -> SurfaceData;
// Carga una paleta desde un archivo
void loadPalette(const std::string& file_path);
@@ -95,14 +95,14 @@ class Surface {
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect);
// Realiza un efecto de fundido en las paletas
bool fadePalette();
bool fadeSubPalette(Uint32 delay = 0);
auto fadePalette() -> bool;
auto fadeSubPalette(Uint32 delay = 0) -> bool;
// Pone un pixel en la SurfaceData
void putPixel(int x, int y, Uint8 color);
// Obtiene el color de un pixel de la surface_data
Uint8 getPixel(int x, int y);
auto getPixel(int x, int y) -> Uint8;
// Dibuja un rectangulo relleno
void fillRect(const SDL_FRect* rect, Uint8 color);
@@ -114,15 +114,15 @@ class Surface {
void drawLine(float x1, float y1, float x2, float y2, Uint8 color);
// Metodos para gestionar surface_data_
std::shared_ptr<SurfaceData> getSurfaceData() const { return surface_data_; }
void setSurfaceData(std::shared_ptr<SurfaceData> new_data) { surface_data_ = new_data; }
[[nodiscard]] auto getSurfaceData() const -> std::shared_ptr<SurfaceData> { return surface_data_; }
void setSurfaceData(std::shared_ptr<SurfaceData> new_data) { surface_data_ = std::move(new_data); }
// Obtien ancho y alto
float getWidth() const { return surface_data_->width; }
float getHeight() const { return surface_data_->height; }
[[nodiscard]] auto getWidth() const -> float { return surface_data_->width; }
[[nodiscard]] auto getHeight() const -> float { return surface_data_->height; }
// Color transparente
Uint8 getTransparentColor() const { return transparent_color_; }
[[nodiscard]] auto getTransparentColor() const -> Uint8 { return transparent_color_; }
void setTransparentColor(Uint8 color = 255) { transparent_color_ = color; }
// Paleta

View File

@@ -1,20 +1,20 @@
#include "core/rendering/surface_animated_sprite.hpp"
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include <stdexcept> // Para runtime_error
#include <utility>
#include "core/rendering/surface.hpp" // Para Surface
#include "utils/utils.hpp" // Para printWithDots
// Carga las animaciones en un vector(Animations) desde un fichero
Animations loadAnimationsFromFile(const std::string& file_path) {
auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
std::ifstream file(file_path);
if (!file) {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
std::cerr << "Error: Fichero no encontrado " << file_path << '\n';
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
@@ -33,7 +33,7 @@ Animations loadAnimationsFromFile(const std::string& file_path) {
// Constructor
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
: SurfaceMovingSprite(surface) {
: SurfaceMovingSprite(std::move(surface)) {
// Carga las animaciones
if (!file_path.empty()) {
Animations v = loadAnimationsFromFile(file_path);
@@ -43,14 +43,14 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, c
// Constructor
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations)
: SurfaceMovingSprite(surface) {
: SurfaceMovingSprite(std::move(surface)) {
if (!animations.empty()) {
setAnimations(animations);
}
}
// Obtiene el indice de la animación a partir del nombre
int SurfaceAnimatedSprite::getIndex(const std::string& name) {
auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int {
auto index = -1;
for (const auto& a : animations_) {
@@ -59,7 +59,7 @@ int SurfaceAnimatedSprite::getIndex(const std::string& name) {
return index;
}
}
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << '\n';
return -1;
}
@@ -94,7 +94,7 @@ void SurfaceAnimatedSprite::animate() {
}
// Comprueba si ha terminado la animación
bool SurfaceAnimatedSprite::animationIsCompleted() {
auto SurfaceAnimatedSprite::animationIsCompleted() -> bool {
return animations_[current_animation_].completed;
}
@@ -136,8 +136,8 @@ void SurfaceAnimatedSprite::resetAnimation() {
}
// Helper: Parsea los parámetros de configuración globales (frame_width, frame_height)
bool parseGlobalParameter(const std::string& line, float& frame_width, float& frame_height) {
size_t pos = line.find("=");
auto parseGlobalParameter(const std::string& line, float& frame_width, float& frame_height) -> bool {
size_t pos = line.find('=');
if (pos == std::string::npos) {
return false;
}
@@ -154,7 +154,7 @@ bool parseGlobalParameter(const std::string& line, float& frame_width, float& fr
return true;
}
std::cout << "Warning: unknown parameter " << key << std::endl;
std::cout << "Warning: unknown parameter " << key << '\n';
return false;
}
@@ -177,10 +177,7 @@ void parseAnimationFrames(const std::string& value, AnimationData& animation,
}
// Helper: Parsea un parámetro de animación individual
bool parseAnimationParameter(const std::string& key, const std::string& value,
AnimationData& animation,
float frame_width, float frame_height,
int frames_per_row, int max_tiles) {
auto parseAnimationParameter(const std::string& key, const std::string& value, AnimationData& animation, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> bool {
if (key == "name") {
animation.name = value;
return true;
@@ -198,21 +195,19 @@ bool parseAnimationParameter(const std::string& key, const std::string& value,
return true;
}
std::cout << "Warning: unknown parameter " << key << std::endl;
std::cout << "Warning: unknown parameter " << key << '\n';
return false;
}
// Helper: Parsea una animación completa
AnimationData parseAnimation(const Animations& animations, size_t& index,
float frame_width, float frame_height,
int frames_per_row, int max_tiles) {
auto parseAnimation(const Animations& animations, size_t& index, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> AnimationData {
AnimationData animation;
std::string line;
do {
index++;
line = animations.at(index);
size_t pos = line.find("=");
size_t pos = line.find('=');
if (pos != std::string::npos) {
std::string key = line.substr(0, pos);
@@ -234,7 +229,7 @@ void SurfaceAnimatedSprite::setAnimations(const Animations& animations) {
size_t index = 0;
while (index < animations.size()) {
std::string line = animations.at(index);
const std::string& line = animations.at(index);
// Parsea el fichero para buscar variables y valores
if (line != "[animation]") {

View File

@@ -4,6 +4,7 @@
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <utility>
#include <vector> // Para vector
#include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite
@@ -12,24 +13,21 @@ class Surface; // lines 9-9
struct AnimationData {
std::string name; // Nombre de la animacion
std::vector<SDL_FRect> frames; // Cada uno de los frames que componen la animación
int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación
int current_frame; // Frame actual
int counter; // Contador para las animaciones
int speed{5}; // Velocidad de la animación
int loop{0}; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed{false}; // Indica si ha finalizado la animación
int current_frame{0}; // Frame actual
int counter{0}; // Contador para las animaciones
AnimationData()
: speed(5),
loop(0),
completed(false),
current_frame(0),
counter(0) {}
{}
};
using Animations = std::vector<std::string>;
// Carga las animaciones en un vector(Animations) desde un fichero
Animations loadAnimationsFromFile(const std::string& file_path);
auto loadAnimationsFromFile(const std::string& file_path) -> Animations;
class SurfaceAnimatedSprite : public SurfaceMovingSprite {
protected:
@@ -48,19 +46,19 @@ class SurfaceAnimatedSprite : public SurfaceMovingSprite {
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path);
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations);
explicit SurfaceAnimatedSprite(std::shared_ptr<Surface> surface)
: SurfaceMovingSprite(surface) {}
: SurfaceMovingSprite(std::move(surface)) {}
// Destructor
virtual ~SurfaceAnimatedSprite() override = default;
~SurfaceAnimatedSprite() override = default;
// Actualiza las variables del objeto
void update() override;
// Comprueba si ha terminado la animación
bool animationIsCompleted();
auto animationIsCompleted() -> bool;
// Obtiene el indice de la animación a partir del nombre
int getIndex(const std::string& name);
auto getIndex(const std::string& name) -> int;
// Establece la animacion actual
void setCurrentAnimation(const std::string& name = "default");
@@ -73,5 +71,5 @@ class SurfaceAnimatedSprite : public SurfaceMovingSprite {
void setCurrentAnimationFrame(int num);
// Obtiene el numero de frames de la animación actual
int getCurrentAnimationSize() { return static_cast<int>(animations_[current_animation_].frames.size()); }
auto getCurrentAnimationSize() -> int { return static_cast<int>(animations_[current_animation_].frames.size()); }
};

View File

@@ -1,22 +1,24 @@
#include "core/rendering/surface_moving_sprite.hpp"
#include <utility>
#include "core/rendering/surface.hpp" // Para Surface
// Constructor
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos, SDL_FlipMode flip)
: SurfaceSprite(surface, pos),
: SurfaceSprite(std::move(surface), pos),
x_(pos.x),
y_(pos.y),
flip_(flip) { SurfaceSprite::pos_ = pos; }
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos)
: SurfaceSprite(surface, pos),
: SurfaceSprite(std::move(surface), pos),
x_(pos.x),
y_(pos.y),
flip_(SDL_FLIP_NONE) { SurfaceSprite::pos_ = pos; }
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface)
: SurfaceSprite(surface),
: SurfaceSprite(std::move(surface)),
x_(0.0F),
y_(0.0F),
flip_(SDL_FLIP_NONE) { SurfaceSprite::clear(); }

View File

@@ -32,7 +32,7 @@ class SurfaceMovingSprite : public SurfaceSprite {
explicit SurfaceMovingSprite(std::shared_ptr<Surface> surface);
// Destructor
virtual ~SurfaceMovingSprite() override = default;
~SurfaceMovingSprite() override = default;
// Actualiza las variables internas del objeto
virtual void update();
@@ -45,12 +45,12 @@ class SurfaceMovingSprite : public SurfaceSprite {
void render(Uint8 source_color, Uint8 target_color) override;
// Obtiene la variable
float getPosX() const { return x_; }
float getPosY() const { return y_; }
float getVelX() const { return vx_; }
float getVelY() const { return vy_; }
float getAccelX() const { return ax_; }
float getAccelY() const { return ay_; }
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
[[nodiscard]] auto getVelX() const -> float { return vx_; }
[[nodiscard]] auto getVelY() const -> float { return vy_; }
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
// Establece la variable
void setVelX(float value) { vx_ = value; }
@@ -65,7 +65,7 @@ class SurfaceMovingSprite : public SurfaceSprite {
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
// Obtiene el valor de la variable
SDL_FlipMode getFlip() { return flip_; }
auto getFlip() -> SDL_FlipMode { return flip_; }
// Establece la posición y_ el tamaño del objeto
void setPos(SDL_FRect rect);

View File

@@ -1,20 +1,22 @@
#include "core/rendering/surface_sprite.hpp"
#include <utility>
#include "core/rendering/surface.hpp" // Para Surface
// Constructor
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, float x, float y, float w, float h)
: surface_(surface),
: surface_(std::move(std::move(surface))),
pos_((SDL_FRect){x, y, w, h}),
clip_((SDL_FRect){0.0F, 0.0F, pos_.w, pos_.h}) {}
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, SDL_FRect rect)
: surface_(surface),
: surface_(std::move(std::move(surface))),
pos_(rect),
clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface)
: surface_(surface),
: surface_(std::move(std::move(surface))),
pos_((SDL_FRect){0.0F, 0.0F, surface_->getWidth(), surface_->getHeight()}),
clip_(pos_) {}
@@ -41,6 +43,6 @@ void SurfaceSprite::setPosition(SDL_FPoint p) {
// Reinicia las variables a cero
void SurfaceSprite::clear() {
pos_ = {0, 0, 0, 0};
clip_ = {0, 0, 0, 0};
pos_ = {.x = 0, .y = 0, .w = 0, .h = 0};
clip_ = {.x = 0, .y = 0, .w = 0, .h = 0};
}

View File

@@ -3,7 +3,8 @@
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
class Surface; // lines 5-5
#include <utility>
class Surface; // lines 5-5
// Clase SurfaceSprite
class SurfaceSprite {
@@ -30,14 +31,14 @@ class SurfaceSprite {
virtual void clear();
// Obtiene la posición y el tamaño
float getX() const { return pos_.x; }
float getY() const { return pos_.y; }
float getWidth() const { return pos_.w; }
float getHeight() const { return pos_.h; }
[[nodiscard]] auto getX() const -> float { return pos_.x; }
[[nodiscard]] auto getY() const -> float { return pos_.y; }
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
// Devuelve el rectangulo donde está el sprite
SDL_FRect getPosition() const { return pos_; }
SDL_FRect& getRect() { return pos_; }
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
auto getRect() -> SDL_FRect& { return pos_; }
// Establece la posición y el tamaño
void setX(float x) { pos_.x = x; }
@@ -55,15 +56,15 @@ class SurfaceSprite {
void incY(float value) { pos_.y += value; }
// Obtiene el rectangulo que se dibuja de la surface
SDL_FRect getClip() const { return clip_; }
[[nodiscard]] auto getClip() const -> SDL_FRect { return clip_; }
// Establece el rectangulo que se dibuja de la surface
void setClip(SDL_FRect rect) { clip_ = rect; }
void setClip(float x, float y, float w, float h) { clip_ = (SDL_FRect){x, y, w, h}; }
// Obtiene un puntero a la surface
std::shared_ptr<Surface> getSurface() const { return surface_; }
[[nodiscard]] auto getSurface() const -> std::shared_ptr<Surface> { return surface_; }
// Establece la surface a utilizar
void setSurface(std::shared_ptr<Surface> surface) { surface_ = surface; }
void setSurface(std::shared_ptr<Surface> surface) { surface_ = std::move(surface); }
};

View File

@@ -1,8 +1,8 @@
#include "core/rendering/text.hpp"
#include <SDL3/SDL.h>
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
#include <iostream> // Para cerr
#include <stdexcept> // Para runtime_error
@@ -13,14 +13,14 @@
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
// Llena una estructuta TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile> {
auto tf = std::make_shared<TextFile>();
// Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; ++i) {
tf->offset[i].x = 0;
tf->offset[i].y = 0;
tf->offset[i].w = 0;
for (auto& i : tf->offset) {
i.x = 0;
i.y = 0;
i.w = 0;
tf->box_width = 0;
tf->box_height = 0;
}
@@ -61,7 +61,7 @@ std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
// El fichero no se puede abrir
else {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
}
@@ -75,7 +75,7 @@ std::shared_ptr<TextFile> loadTextFile(const std::string& file_path) {
}
// Constructor
Text::Text(std::shared_ptr<Surface> surface, const std::string& text_file) {
Text::Text(const std::shared_ptr<Surface>& surface, const std::string& text_file) {
// Carga los offsets desde el fichero
auto tf = loadTextFile(text_file);
@@ -96,7 +96,7 @@ Text::Text(std::shared_ptr<Surface> surface, const std::string& text_file) {
}
// Constructor
Text::Text(std::shared_ptr<Surface> surface, std::shared_ptr<TextFile> text_file) {
Text::Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<TextFile>& text_file) {
// Inicializa variables desde la estructura
box_height_ = text_file->box_height;
box_width_ = text_file->box_width;
@@ -132,7 +132,7 @@ void Text::write(int x, int y, const std::string& text, int kerning, int lenght)
}
// Escribe el texto en una surface
std::shared_ptr<Surface> Text::writeToSurface(const std::string& text, int zoom, int kerning) {
auto Text::writeToSurface(const std::string& text, int zoom, int kerning) -> std::shared_ptr<Surface> {
auto width = lenght(text, kerning) * zoom;
auto height = box_height_ * zoom;
auto surface = std::make_shared<Surface>(width, height);
@@ -146,7 +146,7 @@ std::shared_ptr<Surface> Text::writeToSurface(const std::string& text, int zoom,
}
// Escribe el texto con extras en una surface
std::shared_ptr<Surface> Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
auto Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) -> std::shared_ptr<Surface> {
auto width = Text::lenght(text, kerning) + shadow_distance;
auto height = box_height_ + shadow_distance;
auto surface = std::make_shared<Surface>(width, height);
@@ -223,7 +223,7 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerni
}
// Obtiene la longitud en pixels de una cadena
int Text::lenght(const std::string& text, int kerning) const {
auto Text::lenght(const std::string& text, int kerning) const -> int {
int shift = 0;
for (size_t i = 0; i < text.length(); ++i) {
shift += (offset_[static_cast<int>(text[i])].w + kerning);
@@ -234,7 +234,7 @@ int Text::lenght(const std::string& text, int kerning) const {
}
// Devuelve el valor de la variable
int Text::getCharacterSize() const {
auto Text::getCharacterSize() const -> int {
return box_width_;
}

View File

@@ -24,7 +24,7 @@ struct TextFile {
};
// Llena una estructuta TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string& file_path);
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile>;
// Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text {
@@ -40,8 +40,8 @@ class Text {
public:
// Constructor
Text(std::shared_ptr<Surface> surface, const std::string& text_file);
Text(std::shared_ptr<Surface> surface, std::shared_ptr<TextFile> text_file);
Text(const std::shared_ptr<Surface>& surface, const std::string& text_file);
Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<TextFile>& text_file);
// Destructor
~Text() = default;
@@ -50,10 +50,10 @@ class Text {
void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1);
// Escribe el texto en una textura
std::shared_ptr<Surface> writeToSurface(const std::string& text, int zoom = 1, int kerning = 1);
auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Surface>;
// Escribe el texto con extras en una textura
std::shared_ptr<Surface> writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1);
auto writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1) -> std::shared_ptr<Surface>;
// Escribe el texto con colores
void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1);
@@ -68,10 +68,10 @@ class Text {
void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1);
// Obtiene la longitud en pixels de una cadena
int lenght(const std::string& text, int kerning = 1) const;
[[nodiscard]] auto lenght(const std::string& text, int kerning = 1) const -> int;
// Devuelve el valor de la variable
int getCharacterSize() const;
[[nodiscard]] auto getCharacterSize() const -> int;
// Establece si se usa un tamaño fijo de letra
void setFixedWidth(bool value);

View File

@@ -6,7 +6,8 @@
#include <iostream> // Para basic_ostream, operator<<, endl, cout
#include <stdexcept> // Para runtime_error
#include <string> // Para char_traits, operator<<, string, opera...
#include <vector> // Para vector
#include <utility>
#include <vector> // Para vector
#include "utils/utils.hpp" // Para getFileName, Color, printWithDots
@@ -14,13 +15,13 @@
#include "external/stb_image.h" // para stbi_failure_reason, stbi_image_free
// Constructor
Texture::Texture(SDL_Renderer* renderer, const std::string& path)
Texture::Texture(SDL_Renderer* renderer, std::string path)
: renderer_(renderer),
path_(path) {
path_(std::move(path)) {
// Carga el fichero en la textura
if (!path_.empty()) {
// Obtiene la extensión
const std::string EXTENSION = path_.substr(path_.find_last_of(".") + 1);
const std::string EXTENSION = path_.substr(path_.find_last_of('.') + 1);
// .png
if (EXTENSION == "png") {
@@ -36,7 +37,7 @@ Texture::~Texture() {
}
// Carga una imagen desde un fichero
bool Texture::loadFromFile(const std::string& file_path) {
auto Texture::loadFromFile(const std::string& file_path) -> bool {
if (file_path.empty()) {
return false;
}
@@ -47,7 +48,7 @@ bool Texture::loadFromFile(const std::string& file_path) {
int orig_format;
unsigned char* data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
if (data == nullptr) {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
}
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
@@ -67,12 +68,12 @@ bool Texture::loadFromFile(const std::string& file_path) {
// Carga la imagen desde una ruta específica
auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch);
if (loaded_surface == nullptr) {
std::cout << "Unable to load image " << file_path << std::endl;
std::cout << "Unable to load image " << file_path << '\n';
} else {
// Crea la textura desde los pixels de la surface
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (new_texture == nullptr) {
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << '\n';
} else {
// Obtiene las dimensiones de la imagen
width_ = loaded_surface->w;
@@ -153,10 +154,10 @@ void Texture::render(float x, float y, SDL_FRect* clip, float zoom_w, float zoom
void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); }
// Recarga la textura
bool Texture::reLoad() { return loadFromFile(path_); }
auto Texture::reLoad() -> bool { return loadFromFile(path_); }
// Obtiene la textura
SDL_Texture* Texture::getSDLTexture() { return texture_; }
auto Texture::getSDLTexture() -> SDL_Texture* { return texture_; }
// Obtiene el renderizador
SDL_Renderer* Texture::getRenderer() { return renderer_; }
auto Texture::getRenderer() -> SDL_Renderer* { return renderer_; }

View File

@@ -23,13 +23,13 @@ class Texture {
public:
// Constructor
explicit Texture(SDL_Renderer* renderer, const std::string& path = std::string());
explicit Texture(SDL_Renderer* renderer, std::string path = std::string());
// Destructor
~Texture();
// Carga una imagen desde un fichero
bool loadFromFile(const std::string& path);
auto loadFromFile(const std::string& path) -> bool;
// Crea una textura en blanco
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool;
@@ -51,17 +51,17 @@ class Texture {
void setAsRenderTarget(SDL_Renderer* renderer);
// Obtiene el ancho de la imagen
int getWidth() const { return width_; }
[[nodiscard]] auto getWidth() const -> int { return width_; }
// Obtiene el alto de la imagen
int getHeight() const { return height_; }
[[nodiscard]] auto getHeight() const -> int { return height_; }
// Recarga la textura
bool reLoad();
auto reLoad() -> bool;
// Obtiene la textura
SDL_Texture* getSDLTexture();
auto getSDLTexture() -> SDL_Texture*;
// Obtiene el renderizador
SDL_Renderer* getRenderer();
auto getRenderer() -> SDL_Renderer*;
};