eliminat molt de ruido de la consola de log

This commit is contained in:
2026-04-14 13:04:24 +02:00
parent f5da35bfb2
commit cf7ea6cc9c
27 changed files with 144 additions and 383 deletions

View File

@@ -5,13 +5,13 @@
#include <algorithm> // Para min #include <algorithm> // Para min
#include <cstddef> // Para size_t #include <cstddef> // Para size_t
#include <fstream> // Para basic_istream, basic_ifstream, istream, basic_ios, ifstream, istringstream, stringstream #include <fstream> // Para basic_istream, basic_ifstream, istream, basic_ios, ifstream, istringstream, stringstream
#include <iostream> // Para std::cout
#include <sstream> // Para basic_istringstream, basic_stringstream #include <sstream> // Para basic_istringstream, basic_stringstream
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <utility> // Para move, pair #include <utility> // Para move, pair
#include "resource_helper.hpp" // Para loadFile #include "resource_helper.hpp" // Para loadFile
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
#include "ui/logger.hpp" // Para dots
// Carga las animaciones en un vector(Animations) desde un fichero // Carga las animaciones en un vector(Animations) desde un fichero
auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer { auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer {
@@ -31,15 +31,13 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe
if (!using_resource_data) { if (!using_resource_data) {
file.open(file_path); file.open(file_path);
if (!file) { if (!file) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); std::cout << "Error: Fichero no encontrado " << file_path << '\n';
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
} }
std::istream& input_stream = using_resource_data ? stream : static_cast<std::istream&>(file); std::istream& input_stream = using_resource_data ? stream : static_cast<std::istream&>(file);
Logger::dots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
std::vector<std::string> buffer; std::vector<std::string> buffer;
std::string line; std::string line;
while (std::getline(input_stream, line)) { while (std::getline(input_stream, line)) {
@@ -82,7 +80,7 @@ auto AnimatedSprite::getAnimationIndex(const std::string& name) -> int {
} }
// Si no se encuentra, muestra una advertencia y devuelve -1 // Si no se encuentra, muestra una advertencia y devuelve -1
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "** Warning: could not find \"%s\" animation", name.c_str()); std::cout << "** Warning: could not find \"" << name << "\" animation" << '\n';
return -1; return -1;
} }
@@ -219,7 +217,7 @@ void AnimatedSprite::processConfigLine(const std::string& line, AnimationConfig&
config.frame_height = value; config.frame_height = value;
updateFrameCalculations(config); updateFrameCalculations(config);
} else { } else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: unknown parameter %s", key.c_str()); std::cout << "Warning: unknown parameter " << key << '\n';
} }
} }
@@ -275,7 +273,7 @@ void AnimatedSprite::processAnimationParameter(const std::string& line, Animatio
} else if (key == "frames") { } else if (key == "frames") {
parseFramesParameter(value, animation, config); parseFramesParameter(value, animation, config);
} else { } else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: unknown parameter %s", key.c_str()); std::cout << "Warning: unknown parameter " << key << '\n';
} }
} }

View File

@@ -12,7 +12,6 @@
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include "resource_helper.hpp" // Para loadFile #include "resource_helper.hpp" // Para loadFile
#include "ui/logger.hpp" // Para info, section, CYAN
#include "utils.hpp" // Para getFileName #include "utils.hpp" // Para getFileName
// Singleton // Singleton
@@ -37,9 +36,7 @@ void Asset::addToMap(const std::string& file_path, Type type, bool required, boo
// Verificar si ya existe el archivo // Verificar si ya existe el archivo
if (file_list_.contains(filename)) { if (file_list_.contains(filename)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, std::cout << "Warning: Asset '" << filename << "' already exists, overwriting" << '\n';
"Warning: Asset '%s' already exists, overwriting",
filename.c_str());
} }
file_list_.emplace(filename, Item{std::move(full_path), type, required}); file_list_.emplace(filename, Item{std::move(full_path), type, required});
@@ -54,9 +51,7 @@ void Asset::add(const std::string& file_path, Type type, bool required, bool abs
void Asset::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) { void Asset::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) {
std::ifstream file(config_file_path); std::ifstream file(config_file_path);
if (!file.is_open()) { if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, std::cout << "Error: Cannot open config file: " << config_file_path << '\n';
"Error: Cannot open config file: %s",
config_file_path.c_str());
return; return;
} }
@@ -89,9 +84,7 @@ void Asset::loadFromFile(const std::string& config_file_path, const std::string&
// Verificar que tenemos al menos tipo y ruta // Verificar que tenemos al menos tipo y ruta
if (parts.size() < 2) { if (parts.size() < 2) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, std::cout << "Warning: Malformed line " << line_number << " in config file (insufficient fields)" << '\n';
"Warning: Malformed line %d in config file (insufficient fields)",
line_number);
continue; continue;
} }
@@ -118,14 +111,10 @@ void Asset::loadFromFile(const std::string& config_file_path, const std::string&
addToMap(path, type, required, absolute); addToMap(path, type, required, absolute);
} catch (const std::exception& e) { } catch (const std::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, std::cout << "Error parsing line " << line_number << " in config file: " << e.what() << '\n';
"Error parsing line %d in config file: %s",
line_number,
e.what());
} }
} }
std::cout << "Loaded " << file_list_.size() << " assets from config file" << '\n';
file.close(); file.close();
} }
@@ -136,7 +125,7 @@ auto Asset::getPath(const std::string& filename) const -> std::string {
return it->second.file; return it->second.file;
} }
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found", filename.c_str()); std::cout << "Warning: file " << filename << " not found" << '\n';
return ""; return "";
} }
@@ -147,7 +136,7 @@ auto Asset::loadData(const std::string& filename) const -> std::vector<uint8_t>
return ResourceHelper::loadFile(it->second.file); return ResourceHelper::loadFile(it->second.file);
} }
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found for data loading", filename.c_str()); std::cout << "Warning: file " << filename << " not found for data loading" << '\n';
return {}; return {};
} }
@@ -160,9 +149,6 @@ auto Asset::exists(const std::string& filename) const -> bool {
auto Asset::check() const -> bool { auto Asset::check() const -> bool {
bool success = true; bool success = true;
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES");
Logger::section("CHECKING FILES", Logger::CYAN);
// Agrupar por tipo para mostrar organizado // Agrupar por tipo para mostrar organizado
std::unordered_map<Type, std::vector<const Item*>> by_type; std::unordered_map<Type, std::vector<const Item*>> by_type;
@@ -177,19 +163,11 @@ auto Asset::check() const -> bool {
Type asset_type = static_cast<Type>(type); Type asset_type = static_cast<Type>(type);
if (by_type.contains(asset_type)) { if (by_type.contains(asset_type)) {
Logger::info(getTypeName(asset_type) + " FILES");
bool type_success = true;
for (const auto* item : by_type[asset_type]) { for (const auto* item : by_type[asset_type]) {
if (!checkFile(item->file)) { if (!checkFile(item->file)) {
success = false; success = false;
type_success = false;
} }
} }
if (type_success) {
Logger::info("All files are OK.\n");
}
} }
} }
return success; return success;
@@ -215,9 +193,7 @@ auto Asset::checkFile(const std::string& path) const -> bool {
file.close(); file.close();
if (!success) { if (!success) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, std::cout << "Error: Could not open file: " << path << '\n';
"Error: Could not open file: %s",
path.c_str());
} }
return success; return success;

View File

@@ -3,6 +3,7 @@
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_G... #include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_G...
#include <algorithm> // Para clamp #include <algorithm> // Para clamp
#include <iostream> // Para std::cout
// Implementación de stb_vorbis (debe estar ANTES de incluir jail_audio.hpp). // Implementación de stb_vorbis (debe estar ANTES de incluir jail_audio.hpp).
// clang-format off // clang-format off
@@ -21,7 +22,6 @@
#include "external/jail_audio.hpp" // Para JA_FadeOutMusic, JA_Init, JA_PauseM... #include "external/jail_audio.hpp" // Para JA_FadeOutMusic, JA_Init, JA_PauseM...
#include "options.hpp" // Para AudioOptions, audio, MusicOptions #include "options.hpp" // Para AudioOptions, audio, MusicOptions
#include "resource.hpp" // Para Resource #include "resource.hpp" // Para Resource
#include "ui/logger.hpp" // Para logger
// Singleton // Singleton
Audio* Audio::instance = nullptr; Audio* Audio::instance = nullptr;
@@ -154,11 +154,9 @@ void Audio::enable(bool value) {
// Inicializa SDL Audio // Inicializa SDL Audio
void Audio::initSDLAudio() { void Audio::initSDLAudio() {
if (!SDL_Init(SDL_INIT_AUDIO)) { if (!SDL_Init(SDL_INIT_AUDIO)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_AUDIO could not initialize! SDL Error: %s", SDL_GetError()); std::cout << "SDL_AUDIO could not initialize! SDL Error: " << SDL_GetError() << '\n';
} else { } else {
JA_Init(FREQUENCY, SDL_AUDIO_S16LE, 2); JA_Init(FREQUENCY, SDL_AUDIO_S16LE, 2);
enable(Options::audio.enabled); enable(Options::audio.enabled);
Logger::info("Audio system initialized successfully");
} }
} }

View File

@@ -2,11 +2,11 @@
#include <SDL3/SDL.h> // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO #include <SDL3/SDL.h> // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO
#include <iostream> // Para std::cout
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include "resource_helper.hpp" // Para ResourceHelper #include "resource_helper.hpp" // Para ResourceHelper
#include "ui/logger.hpp" #include "utils.hpp" // Para getFileName
#include "utils.hpp" // Para printWithDots, getFileName
// Carga el fichero de datos para la demo // Carga el fichero de datos para la demo
auto loadDemoDataFromFile(const std::string& file_path) -> DemoData { auto loadDemoDataFromFile(const std::string& file_path) -> DemoData {
@@ -24,10 +24,9 @@ auto loadDemoDataFromFile(const std::string& file_path) -> DemoData {
} }
if (file == nullptr) { if (file == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); std::cout << "Error: Fichero no encontrado " << file_path << '\n';
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
Logger::dots("DemoData : ", getFileName(file_path), "[ LOADED ]");
// Lee todos los datos del fichero y los deja en el destino // Lee todos los datos del fichero y los deja en el destino
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) { for (int i = 0; i < TOTAL_DEMO_DATA; ++i) {
@@ -52,18 +51,15 @@ bool saveDemoFile(const std::string& file_path, const DemoData& dd) {
// Guarda los datos // Guarda los datos
for (const auto& data : dd) { for (const auto& data : dd) {
if (SDL_WriteIO(file, &data, sizeof(DemoKeys)) != sizeof(DemoKeys)) { if (SDL_WriteIO(file, &data, sizeof(DemoKeys)) != sizeof(DemoKeys)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al escribir el fichero %s", getFileName(file_path).c_str()); std::cout << "Error al escribir el fichero " << getFileName(file_path) << '\n';
success = false; success = false;
break; break;
} }
} }
if (success) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file %s", getFileName(file_path).c_str());
}
// Cierra el fichero // Cierra el fichero
SDL_CloseIO(file); SDL_CloseIO(file);
} else { } else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to save %s file! %s", getFileName(file_path).c_str(), SDL_GetError()); std::cout << "Error: Unable to save " << getFileName(file_path) << " file! " << SDL_GetError() << '\n';
success = false; success = false;
} }

View File

@@ -36,7 +36,6 @@
#include "sections/title.hpp" // Para Title #include "sections/title.hpp" // Para Title
#include "shutdown.hpp" // Para resultToString, shutdownSystem, ShutdownResult #include "shutdown.hpp" // Para resultToString, shutdownSystem, ShutdownResult
#include "system_utils.hpp" // Para createApplicationFolder, resultToString, Result #include "system_utils.hpp" // Para createApplicationFolder, resultToString, Result
#include "ui/logger.hpp" // Para section, put
#include "ui/notifier.hpp" // Para Notifier #include "ui/notifier.hpp" // Para Notifier
#include "ui/service_menu.hpp" // Para ServiceMenu #include "ui/service_menu.hpp" // Para ServiceMenu
#include "utils.hpp" // Para Overrides, overrides #include "utils.hpp" // Para Overrides, overrides
@@ -49,11 +48,11 @@ Director::Director(int argc, std::span<char*> argv) {
SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
SDL_SetLogPriority(SDL_LOG_CATEGORY_TEST, SDL_LOG_PRIORITY_ERROR); SDL_SetLogPriority(SDL_LOG_CATEGORY_TEST, SDL_LOG_PRIORITY_ERROR);
Logger::put("Game start\n");
// Inicia la semilla aleatoria usando el tiempo actual en segundos // Inicia la semilla aleatoria usando el tiempo actual en segundos
std::srand(static_cast<unsigned int>(std::time(nullptr))); std::srand(static_cast<unsigned int>(std::time(nullptr)));
std::cout << "Game start\n";
// Comprueba los parametros del programa // Comprueba los parametros del programa
checkProgramArguments(argc, argv); checkProgramArguments(argc, argv);
@@ -80,7 +79,6 @@ Director::~Director() {
// que close() destruye a continuación. // que close() destruye a continuación.
resetActiveSection(); resetActiveSection();
close(); close();
Logger::put("\nBye!");
} }
// Inicializa todo // Inicializa todo
@@ -106,10 +104,8 @@ void Director::init() {
loadAssets(); // Crea el índice de archivos loadAssets(); // Crea el índice de archivos
Logger::section("INIT INPUT");
Input::init(Asset::get()->getPath("gamecontrollerdb.txt"), Asset::get()->getPath("controllers.json")); // Carga configuración de controles Input::init(Asset::get()->getPath("gamecontrollerdb.txt"), Asset::get()->getPath("controllers.json")); // Carga configuración de controles
Logger::section("INIT CONFIG");
Options::setConfigFile(Asset::get()->getPath("config.yaml")); // Establece el fichero de configuración Options::setConfigFile(Asset::get()->getPath("config.yaml")); // Establece el fichero de configuración
Options::setControllersFile(Asset::get()->getPath("controllers.json")); // Establece el fichero de configuración de mandos Options::setControllersFile(Asset::get()->getPath("controllers.json")); // Establece el fichero de configuración de mandos
Options::setPostFXFile(Asset::get()->getPath("postfx.yaml")); // Establece el fichero de presets PostFX Options::setPostFXFile(Asset::get()->getPath("postfx.yaml")); // Establece el fichero de presets PostFX
@@ -123,13 +119,10 @@ void Director::init() {
// Inicialización de subsistemas principales // Inicialización de subsistemas principales
Lang::setLanguage(Options::settings.language); // Carga el archivo de idioma Lang::setLanguage(Options::settings.language); // Carga el archivo de idioma
Logger::section("INIT VIDEO");
Screen::init(); // Inicializa la pantalla y el sistema de renderizado Screen::init(); // Inicializa la pantalla y el sistema de renderizado
Logger::section("INIT AUDIO");
Audio::init(); // Activa el sistema de audio Audio::init(); // Activa el sistema de audio
Logger::section("INIT RESOURCES");
#ifdef _DEBUG #ifdef _DEBUG
Resource::init(debug_config.resource_loading == "lazy" ? Resource::LoadingMode::LAZY_LOAD : Resource::LoadingMode::PRELOAD); Resource::init(debug_config.resource_loading == "lazy" ? Resource::LoadingMode::LAZY_LOAD : Resource::LoadingMode::PRELOAD);
#else #else
@@ -138,8 +131,6 @@ void Director::init() {
ServiceMenu::init(); // Inicializa el menú de servicio ServiceMenu::init(); // Inicializa el menú de servicio
Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones
Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones
Logger::section("GAME LOG");
} }
// Cierra todo y libera recursos del sistema y de los singletons // Cierra todo y libera recursos del sistema y de los singletons
@@ -156,6 +147,8 @@ void Director::close() {
Screen::destroy(); // Libera el sistema de pantalla y renderizado Screen::destroy(); // Libera el sistema de pantalla y renderizado
Asset::destroy(); // Libera el gestor de archivos Asset::destroy(); // Libera el gestor de archivos
std::cout << "\nBye!\n";
// Libera todos los recursos de SDL // Libera todos los recursos de SDL
SDL_Quit(); SDL_Quit();
@@ -200,8 +193,6 @@ void Director::loadAssets() {
std::string config_path = executable_path_ + PREFIX + "/config/assets.txt"; std::string config_path = executable_path_ + PREFIX + "/config/assets.txt";
Asset::get()->loadFromFile(config_path, PREFIX, system_folder_); Asset::get()->loadFromFile(config_path, PREFIX, system_folder_);
Logger::put("Assets configuration loaded successfully");
// Si falta algun fichero, sale del programa // Si falta algun fichero, sale del programa
if (!Asset::get()->check()) { if (!Asset::get()->check()) {
throw std::runtime_error("Falta algun fichero"); throw std::runtime_error("Falta algun fichero");
@@ -255,7 +246,6 @@ void Director::loadDebugConfig() {
out << "show_render_info: true\n"; out << "show_render_info: true\n";
out << "resource_loading: preload\n"; out << "resource_loading: preload\n";
out.close(); out.close();
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Debug config created: %s", DEBUG_FILE.c_str());
} }
// Usar defaults de DebugConfig // Usar defaults de DebugConfig
} else { } else {
@@ -288,9 +278,8 @@ void Director::loadDebugConfig() {
debug_config.resource_loading = yaml["resource_loading"].get_value<std::string>(); debug_config.resource_loading = yaml["resource_loading"].get_value<std::string>();
} catch (...) {} } catch (...) {}
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Debug config loaded: section=%s options=%s stage=%d", debug_config.initial_section.c_str(), debug_config.initial_options.c_str(), debug_config.initial_stage);
} catch (...) { } catch (...) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Error parsing debug.yaml, using defaults"); std::cout << "Error parsing debug.yaml, using defaults" << '\n';
} }
} }

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo #include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo
#include <cstring> // Para memcpy, size_t #include <cstring> // Para memcpy, size_t
#include <iostream> // Para std::cout
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para char_traits, operator==, basic_string, string #include <string> // Para char_traits, operator==, basic_string, string
@@ -13,7 +14,7 @@ inline void readBytes(const uint8_t *&buffer, void *dst, size_t size) {
void Gif::decompress(int code_length, const uint8_t *input, int input_length, uint8_t *out) { void Gif::decompress(int code_length, const uint8_t *input, int input_length, uint8_t *out) {
if (code_length < 2 || code_length > 12) { if (code_length < 2 || code_length > 12) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Invalid LZW code length: %d", code_length); std::cout << "Invalid LZW code length: " << code_length << '\n';
throw std::runtime_error("Invalid LZW code length"); throw std::runtime_error("Invalid LZW code length");
} }
@@ -39,7 +40,7 @@ void Gif::decompress(int code_length, const uint8_t *input, int input_length, ui
int code = 0; int code = 0;
for (i = 0; i < (code_length + 1); i++) { for (i = 0; i < (code_length + 1); i++) {
if (input_length <= 0) { if (input_length <= 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unexpected end of input in decompress"); std::cout << "Unexpected end of input in decompress" << '\n';
throw std::runtime_error("Unexpected end of input in decompress"); throw std::runtime_error("Unexpected end of input in decompress");
} }
bit = ((*input & mask) != 0) ? 1 : 0; bit = ((*input & mask) != 0) ? 1 : 0;
@@ -69,7 +70,7 @@ void Gif::decompress(int code_length, const uint8_t *input, int input_length, ui
if (prev > -1 && code_length < 12) { if (prev > -1 && code_length < 12) {
if (code > dictionary_ind) { if (code > dictionary_ind) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "LZW error: code (%d) exceeds dictionary_ind (%d)", code, dictionary_ind); std::cout << "LZW error: code (" << code << ") exceeds dictionary_ind (" << dictionary_ind << ")" << '\n';
throw std::runtime_error("LZW error: code exceeds dictionary_ind."); throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
} }
@@ -98,7 +99,7 @@ void Gif::decompress(int code_length, const uint8_t *input, int input_length, ui
prev = code; prev = code;
if (code < 0 || static_cast<size_t>(code) >= dictionary.size()) { if (code < 0 || static_cast<size_t>(code) >= dictionary.size()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Invalid LZW code %d, dictionary size %lu", code, static_cast<unsigned long>(dictionary.size())); std::cout << "Invalid LZW code " << code << ", dictionary size " << static_cast<unsigned long>(dictionary.size()) << '\n';
throw std::runtime_error("LZW error: invalid code encountered"); throw std::runtime_error("LZW error: invalid code encountered");
} }
@@ -107,7 +108,7 @@ void Gif::decompress(int code_length, const uint8_t *input, int input_length, ui
while (curCode != -1) { while (curCode != -1) {
out[dictionary[curCode].len - 1] = dictionary[curCode].byte; out[dictionary[curCode].len - 1] = dictionary[curCode].byte;
if (dictionary[curCode].prev == curCode) { if (dictionary[curCode].prev == curCode) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Internal error; self-reference detected."); std::cout << "Internal error; self-reference detected." << '\n';
throw std::runtime_error("Internal error in decompress: self-reference"); throw std::runtime_error("Internal error in decompress: self-reference");
} }
curCode = dictionary[curCode].prev; curCode = dictionary[curCode].prev;
@@ -175,20 +176,16 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t *buffer, uint16_t &w, u
std::string headerStr(reinterpret_cast<char *>(header), 6); std::string headerStr(reinterpret_cast<char *>(header), 6);
if (headerStr != "GIF87a" && headerStr != "GIF89a") { if (headerStr != "GIF87a" && headerStr != "GIF89a") {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Formato de archivo GIF inválido: %s", headerStr.c_str()); std::cout << "Formato de archivo GIF inválido: " << headerStr << '\n';
throw std::runtime_error("Formato de archivo GIF inválido."); throw std::runtime_error("Formato de archivo GIF inválido.");
} }
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "Procesando GIF con cabecera: %s", headerStr.c_str());
ScreenDescriptor screen_descriptor; ScreenDescriptor screen_descriptor;
readBytes(buffer, &screen_descriptor, sizeof(ScreenDescriptor)); readBytes(buffer, &screen_descriptor, sizeof(ScreenDescriptor));
w = screen_descriptor.width; w = screen_descriptor.width;
h = screen_descriptor.height; h = screen_descriptor.height;
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "Resolución del GIF: %dx%d", w, h);
int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1; int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
std::vector<RGB> global_color_table; std::vector<RGB> global_color_table;
if (screen_descriptor.fields & 0x80) { if (screen_descriptor.fields & 0x80) {
@@ -239,13 +236,12 @@ std::vector<uint8_t> Gif::processGifStream(const uint8_t *buffer, uint16_t &w, u
} else if (block_type == IMAGE_DESCRIPTOR) { } else if (block_type == IMAGE_DESCRIPTOR) {
return processImageDescriptor(buffer, global_color_table, color_resolution_bits); return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
} else { } else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unrecognized block type: 0x%X", block_type); std::cout << "Unrecognized block type: 0x" << std::hex << static_cast<int>(block_type) << std::dec << '\n';
return std::vector<uint8_t>{}; return std::vector<uint8_t>{};
} }
block_type = *buffer++; block_type = *buffer++;
} }
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "GIF procesado correctamente.");
return std::vector<uint8_t>{}; return std::vector<uint8_t>{};
} }

View File

@@ -7,6 +7,8 @@
#include <stdlib.h> // Para free, malloc #include <stdlib.h> // Para free, malloc
#include <string.h> // Para strcpy, strlen #include <string.h> // Para strcpy, strlen
#include <iostream> // Para std::cout
#define STB_VORBIS_HEADER_ONLY #define STB_VORBIS_HEADER_ONLY
#include "external/stb_vorbis.h" // Para stb_vorbis_decode_memory #include "external/stb_vorbis.h" // Para stb_vorbis_decode_memory
@@ -179,7 +181,7 @@ inline void JA_Init(const int freq, const SDL_AudioFormat format, const int num_
JA_audioSpec = {format, num_channels, freq}; JA_audioSpec = {format, num_channels, freq};
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); // Corregido: !sdlAudioDevice -> sdlAudioDevice if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); // Corregido: !sdlAudioDevice -> sdlAudioDevice
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec); sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
if (sdlAudioDevice == 0) SDL_Log("Failed to initialize SDL audio!"); if (sdlAudioDevice == 0) std::cout << "Failed to initialize SDL audio!" << '\n';
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE; for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE;
for (int i = 0; i < JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5f; for (int i = 0; i < JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5f;
} }
@@ -204,7 +206,7 @@ inline JA_Music_t* JA_LoadMusic(const Uint8* buffer, Uint32 length) {
stb_vorbis* vorbis = stb_vorbis_open_memory(ogg_copy, static_cast<int>(length), &error, nullptr); stb_vorbis* vorbis = stb_vorbis_open_memory(ogg_copy, static_cast<int>(length), &error, nullptr);
if (!vorbis) { if (!vorbis) {
SDL_free(ogg_copy); SDL_free(ogg_copy);
SDL_Log("JA_LoadMusic: stb_vorbis_open_memory failed (error %d)", error); std::cout << "JA_LoadMusic: stb_vorbis_open_memory failed (error " << error << ")" << '\n';
return nullptr; return nullptr;
} }
@@ -269,7 +271,7 @@ inline void JA_PlayMusic(JA_Music_t* music, const int loop = -1) {
current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec); current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec);
if (!current_music->stream) { if (!current_music->stream) {
SDL_Log("Failed to create audio stream!"); std::cout << "Failed to create audio stream!" << '\n';
current_music->state = JA_MUSIC_STOPPED; current_music->state = JA_MUSIC_STOPPED;
return; return;
} }
@@ -386,7 +388,7 @@ inline JA_Sound_t* JA_NewSound(Uint8* buffer, Uint32 length) {
inline JA_Sound_t* JA_LoadSound(uint8_t* buffer, uint32_t size) { inline JA_Sound_t* JA_LoadSound(uint8_t* buffer, uint32_t size) {
JA_Sound_t* sound = new JA_Sound_t(); JA_Sound_t* sound = new JA_Sound_t();
if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length)) { if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length)) {
SDL_Log("Failed to load WAV from memory: %s", SDL_GetError()); std::cout << "Failed to load WAV from memory: " << SDL_GetError() << '\n';
delete sound; delete sound;
return nullptr; return nullptr;
} }
@@ -396,7 +398,7 @@ inline JA_Sound_t* JA_LoadSound(uint8_t* buffer, uint32_t size) {
inline JA_Sound_t* JA_LoadSound(const char* filename) { inline JA_Sound_t* JA_LoadSound(const char* filename) {
JA_Sound_t* sound = new JA_Sound_t(); JA_Sound_t* sound = new JA_Sound_t();
if (!SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length)) { if (!SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length)) {
SDL_Log("Failed to load WAV file: %s", SDL_GetError()); std::cout << "Failed to load WAV file: " << SDL_GetError() << '\n';
delete sound; delete sound;
return nullptr; return nullptr;
} }
@@ -430,7 +432,7 @@ inline int JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec); channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec);
if (!channels[channel].stream) { if (!channels[channel].stream) {
SDL_Log("Failed to create audio stream for sound!"); std::cout << "Failed to create audio stream for sound!" << '\n';
channels[channel].state = JA_CHANNEL_FREE; channels[channel].state = JA_CHANNEL_FREE;
return -1; return -1;
} }

View File

@@ -3,6 +3,7 @@
#include <SDL3/SDL.h> // Para SDL_EventType, SDL_Event, SDL_LogInfo, SDL_LogCategory #include <SDL3/SDL.h> // Para SDL_EventType, SDL_Event, SDL_LogInfo, SDL_LogCategory
#include <cstddef> // Para size_t #include <cstddef> // Para size_t
#include <iostream> // Para std::cout
#include <string> // Para allocator, operator+, string #include <string> // Para allocator, operator+, string
#include <vector> // Para vector #include <vector> // Para vector
@@ -50,7 +51,7 @@ namespace GlobalEvents {
case SDL_EVENT_RENDER_DEVICE_RESET: case SDL_EVENT_RENDER_DEVICE_RESET:
case SDL_EVENT_RENDER_TARGETS_RESET: case SDL_EVENT_RENDER_TARGETS_RESET:
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "SDL_RENDER_TARGETS_RESET"); std::cout << "SDL_RENDER_TARGETS_RESET" << '\n';
break; break;
case SDL_EVENT_WINDOW_RESIZED: case SDL_EVENT_WINDOW_RESIZED:

View File

@@ -8,7 +8,6 @@
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator #include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
#include <utility> // Para pair, move #include <utility> // Para pair, move
#include "ui/logger.hpp" // Para info
// Singleton // Singleton
Input* Input::instance = nullptr; Input* Input::instance = nullptr;
@@ -322,12 +321,11 @@ void Input::discoverGamepads() {
void Input::initSDLGamePad() { void Input::initSDLGamePad() {
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) { if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError()); std::cout << "SDL_GAMEPAD could not initialize! SDL Error: " << SDL_GetError() << '\n';
} else { } else {
addGamepadMappingsFromFile(); addGamepadMappingsFromFile();
loadGamepadConfigs(); loadGamepadConfigs();
discoverGamepads(); discoverGamepads();
Logger::info("Input System initialized successfully");
} }
} }
} }

View File

@@ -5,11 +5,12 @@
#include <algorithm> // Para __sort_fn, sort #include <algorithm> // Para __sort_fn, sort
#include <array> // Para array #include <array> // Para array
#include <functional> // Para identity #include <functional> // Para identity
#include <iomanip> // Para std::setw, std::setfill
#include <iostream> // Para std::cout
#include <iterator> // Para distance #include <iterator> // Para distance
#include <ranges> // Para __find_if_fn, find_if #include <ranges> // Para __find_if_fn, find_if
#include <utility> // Para move #include <utility> // Para move
#include "ui/logger.hpp" // Para info
#include "utils.hpp" // Para getFileName #include "utils.hpp" // Para getFileName
// Resetea la tabla a los valores por defecto // Resetea la tabla a los valores por defecto
@@ -105,7 +106,7 @@ auto ManageHiScoreTable::loadFromFile(const std::string& file_path) -> bool {
auto* file = SDL_IOFromFile(file_path.c_str(), "rb"); auto* file = SDL_IOFromFile(file_path.c_str(), "rb");
if (file == nullptr) { if (file == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to load %s file! %s", getFileName(file_path).c_str(), SDL_GetError()); std::cout << "Error: Unable to load " << getFileName(file_path) << " file! " << SDL_GetError() << '\n';
clear(); clear();
return false; return false;
} }
@@ -152,9 +153,8 @@ auto ManageHiScoreTable::loadFromFile(const std::string& file_path) -> bool {
// Si todo fue bien, actualizar la tabla; si no, usar valores por defecto // Si todo fue bien, actualizar la tabla; si no, usar valores por defecto
if (success) { if (success) {
table_ = std::move(temp_table); table_ = std::move(temp_table);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\nReading file: %s (loaded %d entries successfully)", getFileName(file_path).c_str(), table_size);
} else { } else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "File %s is corrupted - loading default values", getFileName(file_path).c_str()); std::cout << "File " << getFileName(file_path) << " is corrupted - loading default values" << '\n';
clear(); clear();
} }
@@ -166,7 +166,7 @@ auto ManageHiScoreTable::loadFromFile(const std::string& file_path) -> bool {
auto ManageHiScoreTable::validateMagicNumber(SDL_IOStream* file, const std::string& file_path) -> bool { auto ManageHiScoreTable::validateMagicNumber(SDL_IOStream* file, const std::string& file_path) -> bool {
std::array<char, 4> magic; std::array<char, 4> magic;
if (SDL_ReadIO(file, magic.data(), 4) != 4 || magic[0] != 'C' || magic[1] != 'C' || magic[2] != 'A' || magic[3] != 'E') { if (SDL_ReadIO(file, magic.data(), 4) != 4 || magic[0] != 'C' || magic[1] != 'C' || magic[2] != 'A' || magic[3] != 'E') {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid magic number in %s - file may be corrupted or old format", getFileName(file_path).c_str()); std::cout << "Error: Invalid magic number in " << getFileName(file_path) << " - file may be corrupted or old format" << '\n';
return false; return false;
} }
return true; return true;
@@ -175,12 +175,12 @@ auto ManageHiScoreTable::validateMagicNumber(SDL_IOStream* file, const std::stri
auto ManageHiScoreTable::validateVersion(SDL_IOStream* file, const std::string& file_path) -> bool { auto ManageHiScoreTable::validateVersion(SDL_IOStream* file, const std::string& file_path) -> bool {
int version = 0; int version = 0;
if (SDL_ReadIO(file, &version, sizeof(int)) != sizeof(int)) { if (SDL_ReadIO(file, &version, sizeof(int)) != sizeof(int)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read version in %s", getFileName(file_path).c_str()); std::cout << "Error: Cannot read version in " << getFileName(file_path) << '\n';
return false; return false;
} }
if (version != FILE_VERSION) { if (version != FILE_VERSION) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unsupported file version %d in %s (expected %d)", version, getFileName(file_path).c_str(), FILE_VERSION); std::cout << "Error: Unsupported file version " << version << " in " << getFileName(file_path) << " (expected " << FILE_VERSION << ")" << '\n';
return false; return false;
} }
return true; return true;
@@ -188,12 +188,12 @@ auto ManageHiScoreTable::validateVersion(SDL_IOStream* file, const std::string&
auto ManageHiScoreTable::readTableSize(SDL_IOStream* file, const std::string& file_path, int& table_size) -> bool { auto ManageHiScoreTable::readTableSize(SDL_IOStream* file, const std::string& file_path, int& table_size) -> bool {
if (SDL_ReadIO(file, &table_size, sizeof(int)) != sizeof(int)) { if (SDL_ReadIO(file, &table_size, sizeof(int)) != sizeof(int)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read table size in %s", getFileName(file_path).c_str()); std::cout << "Error: Cannot read table size in " << getFileName(file_path) << '\n';
return false; return false;
} }
if (table_size < 0 || table_size > MAX_TABLE_SIZE) { if (table_size < 0 || table_size > MAX_TABLE_SIZE) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid table size %d in %s (expected 0-%d)", table_size, getFileName(file_path).c_str(), MAX_TABLE_SIZE); std::cout << "Error: Invalid table size " << table_size << " in " << getFileName(file_path) << " (expected 0-" << MAX_TABLE_SIZE << ")" << '\n';
return false; return false;
} }
return true; return true;
@@ -202,31 +202,31 @@ auto ManageHiScoreTable::readTableSize(SDL_IOStream* file, const std::string& fi
auto ManageHiScoreTable::readEntry(SDL_IOStream* file, const std::string& file_path, int index, HiScoreEntry& entry) -> bool { auto ManageHiScoreTable::readEntry(SDL_IOStream* file, const std::string& file_path, int index, HiScoreEntry& entry) -> bool {
// Leer y validar puntuación // Leer y validar puntuación
if (SDL_ReadIO(file, &entry.score, sizeof(int)) != sizeof(int)) { if (SDL_ReadIO(file, &entry.score, sizeof(int)) != sizeof(int)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read score for entry %d in %s", index, getFileName(file_path).c_str()); std::cout << "Error: Cannot read score for entry " << index << " in " << getFileName(file_path) << '\n';
return false; return false;
} }
if (entry.score < 0 || entry.score > MAX_SCORE) { if (entry.score < 0 || entry.score > MAX_SCORE) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid score %d for entry %d in %s", entry.score, index, getFileName(file_path).c_str()); std::cout << "Error: Invalid score " << entry.score << " for entry " << index << " in " << getFileName(file_path) << '\n';
return false; return false;
} }
// Leer y validar tamaño del nombre // Leer y validar tamaño del nombre
int name_size = 0; int name_size = 0;
if (SDL_ReadIO(file, &name_size, sizeof(int)) != sizeof(int)) { if (SDL_ReadIO(file, &name_size, sizeof(int)) != sizeof(int)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read name size for entry %d in %s", index, getFileName(file_path).c_str()); std::cout << "Error: Cannot read name size for entry " << index << " in " << getFileName(file_path) << '\n';
return false; return false;
} }
if (name_size < 0 || name_size > MAX_NAME_SIZE) { if (name_size < 0 || name_size > MAX_NAME_SIZE) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid name size %d for entry %d in %s", name_size, index, getFileName(file_path).c_str()); std::cout << "Error: Invalid name size " << name_size << " for entry " << index << " in " << getFileName(file_path) << '\n';
return false; return false;
} }
// Leer el nombre // Leer el nombre
std::vector<char> name_buffer(name_size + 1); std::vector<char> name_buffer(name_size + 1);
if (SDL_ReadIO(file, name_buffer.data(), name_size) != static_cast<size_t>(name_size)) { if (SDL_ReadIO(file, name_buffer.data(), name_size) != static_cast<size_t>(name_size)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read name for entry %d in %s", index, getFileName(file_path).c_str()); std::cout << "Error: Cannot read name for entry " << index << " in " << getFileName(file_path) << '\n';
return false; return false;
} }
name_buffer[name_size] = '\0'; name_buffer[name_size] = '\0';
@@ -235,7 +235,7 @@ auto ManageHiScoreTable::readEntry(SDL_IOStream* file, const std::string& file_p
// Leer one_credit_complete // Leer one_credit_complete
int occ_value = 0; int occ_value = 0;
if (SDL_ReadIO(file, &occ_value, sizeof(int)) != sizeof(int)) { if (SDL_ReadIO(file, &occ_value, sizeof(int)) != sizeof(int)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read one_credit_complete for entry %d in %s", index, getFileName(file_path).c_str()); std::cout << "Error: Cannot read one_credit_complete for entry " << index << " in " << getFileName(file_path) << '\n';
return false; return false;
} }
entry.one_credit_complete = (occ_value != 0); entry.one_credit_complete = (occ_value != 0);
@@ -246,13 +246,13 @@ auto ManageHiScoreTable::readEntry(SDL_IOStream* file, const std::string& file_p
auto ManageHiScoreTable::verifyChecksum(SDL_IOStream* file, const std::string& file_path, const Table& temp_table) -> bool { auto ManageHiScoreTable::verifyChecksum(SDL_IOStream* file, const std::string& file_path, const Table& temp_table) -> bool {
unsigned int stored_checksum = 0; unsigned int stored_checksum = 0;
if (SDL_ReadIO(file, &stored_checksum, sizeof(unsigned int)) != sizeof(unsigned int)) { if (SDL_ReadIO(file, &stored_checksum, sizeof(unsigned int)) != sizeof(unsigned int)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot read checksum in %s", getFileName(file_path).c_str()); std::cout << "Error: Cannot read checksum in " << getFileName(file_path) << '\n';
return false; return false;
} }
unsigned int calculated_checksum = calculateChecksum(temp_table); unsigned int calculated_checksum = calculateChecksum(temp_table);
if (stored_checksum != calculated_checksum) { if (stored_checksum != calculated_checksum) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Checksum mismatch in %s (stored: 0x%08X, calculated: 0x%08X) - file is corrupted", getFileName(file_path).c_str(), stored_checksum, calculated_checksum); std::cout << "Error: Checksum mismatch in " << getFileName(file_path) << " (stored: 0x" << std::hex << std::setw(8) << std::setfill('0') << stored_checksum << ", calculated: 0x" << std::setw(8) << std::setfill('0') << calculated_checksum << std::dec << ") - file is corrupted" << '\n';
return false; return false;
} }
return true; return true;
@@ -317,11 +317,9 @@ auto ManageHiScoreTable::saveToFile(const std::string& file_path) -> bool {
unsigned int checksum = calculateChecksum(table_); unsigned int checksum = calculateChecksum(table_);
SDL_WriteIO(file, &checksum, sizeof(unsigned int)); SDL_WriteIO(file, &checksum, sizeof(unsigned int));
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file: %s", getFileName(file_path).c_str());
Logger::info("Writing file: " + getFileName(file_path));
SDL_CloseIO(file); SDL_CloseIO(file);
} else { } else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to save %s file! %s", getFileName(file_path).c_str(), SDL_GetError()); std::cout << "Error: Unable to save " << getFileName(file_path) << " file! " << SDL_GetError() << '\n';
success = false; success = false;
} }
return success; return success;

View File

@@ -5,6 +5,7 @@
#include <algorithm> // Para clamp #include <algorithm> // Para clamp
#include <cstddef> // Para size_t #include <cstddef> // Para size_t
#include <fstream> // Para ifstream, ofstream #include <fstream> // Para ifstream, ofstream
#include <iostream> // Para std::cout
#include <string> // Para string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector
@@ -12,7 +13,6 @@
#include "external/fkyaml_node.hpp" // Para fkyaml::node #include "external/fkyaml_node.hpp" // Para fkyaml::node
#include "input.hpp" // Para Input #include "input.hpp" // Para Input
#include "lang.hpp" // Para getText, Code #include "lang.hpp" // Para getText, Code
#include "ui/logger.hpp" // Para info
#include "utils.hpp" // Para boolToString, getFileName #include "utils.hpp" // Para boolToString, getFileName
namespace Options { namespace Options {
@@ -63,7 +63,6 @@ namespace Options {
std::ifstream file(postfx_file_path); std::ifstream file(postfx_file_path);
if (!file.good()) { if (!file.good()) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "PostFX file not found, creating default: %s", postfx_file_path.c_str());
return savePostFXToFile(); return savePostFXToFile();
} }
@@ -110,11 +109,10 @@ namespace Options {
video.shader.current_postfx_preset = 0; video.shader.current_postfx_preset = 0;
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "PostFX file loaded: %zu preset(s)", postfx_presets.size());
return true; return true;
} catch (const fkyaml::exception& e) { } catch (const fkyaml::exception& e) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Error parsing PostFX YAML: %s. Recreating defaults.", e.what()); std::cout << "Error parsing PostFX YAML: " << e.what() << ". Recreating defaults." << '\n';
return savePostFXToFile(); return savePostFXToFile();
} }
} }
@@ -127,7 +125,7 @@ namespace Options {
std::ofstream file(postfx_file_path); std::ofstream file(postfx_file_path);
if (!file.is_open()) { if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s can't be opened for writing", postfx_file_path.c_str()); std::cout << "Error: " << postfx_file_path << " can't be opened for writing" << '\n';
return false; return false;
} }
@@ -200,8 +198,6 @@ namespace Options {
file.close(); file.close();
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "PostFX file created with defaults: %s", postfx_file_path.c_str());
// Cargar los presets recién escritos // Cargar los presets recién escritos
postfx_presets.clear(); postfx_presets.clear();
postfx_presets.push_back({"CRT", 0.15F, 0.7F, 0.2F, 0.5F, 0.1F, 0.0F, 0.0F, 0.0F}); postfx_presets.push_back({"CRT", 0.15F, 0.7F, 0.2F, 0.5F, 0.1F, 0.0F, 0.0F, 0.0F});
@@ -247,7 +243,7 @@ namespace Options {
if (crtpi_file_path.empty()) { return false; } if (crtpi_file_path.empty()) { return false; }
std::ofstream file(crtpi_file_path); std::ofstream file(crtpi_file_path);
if (!file.is_open()) { if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s can't be opened for writing", crtpi_file_path.c_str()); std::cout << "Error: " << crtpi_file_path << " can't be opened for writing" << '\n';
return false; return false;
} }
file << "# Coffee Crisis Arcade Edition - CrtPi Shader Presets\n"; file << "# Coffee Crisis Arcade Edition - CrtPi Shader Presets\n";
@@ -266,7 +262,6 @@ namespace Options {
file << " - name: \"Sharp\"\n scanline_weight: 6.0\n scanline_gap_brightness: 0.12\n bloom_factor: 3.5\n input_gamma: 2.4\n output_gamma: 2.2\n mask_brightness: 0.80\n curvature_x: 0.05\n curvature_y: 0.10\n mask_type: 2\n enable_scanlines: true\n enable_multisample: false\n enable_gamma: true\n enable_curvature: false\n enable_sharper: true\n"; file << " - name: \"Sharp\"\n scanline_weight: 6.0\n scanline_gap_brightness: 0.12\n bloom_factor: 3.5\n input_gamma: 2.4\n output_gamma: 2.2\n mask_brightness: 0.80\n curvature_x: 0.05\n curvature_y: 0.10\n mask_type: 2\n enable_scanlines: true\n enable_multisample: false\n enable_gamma: true\n enable_curvature: false\n enable_sharper: true\n";
file << " - name: \"Minimal\"\n scanline_weight: 8.0\n scanline_gap_brightness: 0.05\n bloom_factor: 2.0\n input_gamma: 2.4\n output_gamma: 2.2\n mask_brightness: 1.00\n curvature_x: 0.0\n curvature_y: 0.0\n mask_type: 0\n enable_scanlines: true\n enable_multisample: false\n enable_gamma: false\n enable_curvature: false\n enable_sharper: false\n"; file << " - name: \"Minimal\"\n scanline_weight: 8.0\n scanline_gap_brightness: 0.05\n bloom_factor: 2.0\n input_gamma: 2.4\n output_gamma: 2.2\n mask_brightness: 1.00\n curvature_x: 0.0\n curvature_y: 0.0\n mask_type: 0\n enable_scanlines: true\n enable_multisample: false\n enable_gamma: false\n enable_curvature: false\n enable_sharper: false\n";
file.close(); file.close();
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "CrtPi file created with defaults: %s", crtpi_file_path.c_str());
populateDefaultCrtPiPresets(); populateDefaultCrtPiPresets();
return true; return true;
} }
@@ -277,7 +272,6 @@ namespace Options {
std::ifstream file(crtpi_file_path); std::ifstream file(crtpi_file_path);
if (!file.good()) { if (!file.good()) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "CrtPi file not found, creating default: %s", crtpi_file_path.c_str());
return saveCrtPiDefaults(); return saveCrtPiDefaults();
} }
@@ -330,11 +324,10 @@ namespace Options {
video.shader.current_crtpi_preset = 0; video.shader.current_crtpi_preset = 0;
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "CrtPi file loaded: %zu preset(s)", crtpi_presets.size());
return true; return true;
} catch (const fkyaml::exception& e) { } catch (const fkyaml::exception& e) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Error parsing CrtPi YAML: %s. Recreating defaults.", e.what()); std::cout << "Error parsing CrtPi YAML: " << e.what() << ". Recreating defaults." << '\n';
return saveCrtPiDefaults(); return saveCrtPiDefaults();
} }
} }
@@ -581,12 +574,10 @@ namespace Options {
std::ifstream file(settings.config_file); std::ifstream file(settings.config_file);
if (!file.is_open()) { if (!file.is_open()) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Config file not found. Creating default settings.");
saveToFile(); saveToFile();
return true; return true;
} }
Logger::info("Reading file: " + getFileName(settings.config_file));
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close(); file.close();
@@ -601,7 +592,7 @@ namespace Options {
} catch (...) {} } catch (...) {}
} }
if (file_version != Settings::CURRENT_CONFIG_VERSION) { if (file_version != Settings::CURRENT_CONFIG_VERSION) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Config version %d != expected %d. Recreating defaults.", file_version, Settings::CURRENT_CONFIG_VERSION); std::cout << "Config version " << file_version << " != expected " << Settings::CURRENT_CONFIG_VERSION << ". Recreating defaults." << '\n';
init(); init();
saveToFile(); saveToFile();
return true; return true;
@@ -615,7 +606,7 @@ namespace Options {
loadKeyboardFromYaml(yaml); loadKeyboardFromYaml(yaml);
} catch (const fkyaml::exception& e) { } catch (const fkyaml::exception& e) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Error parsing YAML config: %s. Using defaults.", e.what()); std::cout << "Error parsing YAML config: " << e.what() << ". Using defaults." << '\n';
init(); init();
saveToFile(); saveToFile();
return true; return true;
@@ -630,12 +621,10 @@ namespace Options {
std::ofstream file(settings.config_file); std::ofstream file(settings.config_file);
if (!file.good()) { if (!file.good()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s can't be opened", getFileName(settings.config_file).c_str()); std::cout << "Error: " << getFileName(settings.config_file) << " can't be opened" << '\n';
return false; return false;
} }
Logger::info("Writing file: " + getFileName(settings.config_file));
applyPendingChanges(); applyPendingChanges();
file << "# Coffee Crisis Arcade Edition - Configuration File\n"; file << "# Coffee Crisis Arcade Edition - Configuration File\n";

View File

@@ -4,6 +4,7 @@
#include <fstream> // Para basic_istream, basic_ifstream, ifstream, istringstream #include <fstream> // Para basic_istream, basic_ifstream, ifstream, istringstream
#include <functional> // Para function #include <functional> // Para function
#include <iostream> // Para std::cout
#include <sstream> // Para basic_istringstream #include <sstream> // Para basic_istringstream
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para string, basic_string, stoi, stof, hash, allocator, operator==, char_traits, operator+, operator>>, getline #include <string> // Para string, basic_string, stoi, stof, hash, allocator, operator==, char_traits, operator+, operator>>, getline
@@ -11,7 +12,6 @@
#include <utility> // Para pair #include <utility> // Para pair
#include "color.hpp" // Para Color #include "color.hpp" // Para Color
#include "ui/logger.hpp" // Para info, YELLOW
#include "ui/notifier.hpp" // Para Notifier #include "ui/notifier.hpp" // Para Notifier
#include "utils.hpp" // Para Zone, stringToBool, getFileName #include "utils.hpp" // Para Zone, stringToBool, getFileName
@@ -50,13 +50,10 @@ void loadParamsFromFile(const std::string& file_path) {
std::ifstream file(file_path); std::ifstream file(file_path);
if (!file.is_open()) { if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo abrir el archivo %s", file_path.c_str()); std::cout << "Error: No se pudo abrir el archivo " << file_path << '\n';
throw std::runtime_error("No se pudo abrir el archivo: " + file_path); throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
} }
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\nReading file: %s", getFileName(file_path).c_str());
Logger::info("Reading file: " + getFileName(file_path));
std::string line; std::string line;
std::string param_name; std::string param_name;
std::string param_value; std::string param_value;
@@ -72,7 +69,7 @@ void loadParamsFromFile(const std::string& file_path) {
std::istringstream iss(line); std::istringstream iss(line);
if (iss >> param_name >> param_value) { if (iss >> param_name >> param_value) {
if (!setParams(param_name, param_value)) { if (!setParams(param_name, param_value)) {
Logger::info("WARNING: Parámetro desconocido: " + param_name, Logger::YELLOW); std::cout << "WARNING: Parámetro desconocido: " << param_name << '\n';
} }
} }
} }
@@ -208,7 +205,7 @@ namespace {
static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = { static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = {
{"balloon.color[0]", [validate_balloon_color](const std::string& v) -> void { {"balloon.color[0]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'blue' por defecto.", v.c_str()); std::cout << "Color de globo inválido '" << v << "'. Usando 'blue' por defecto." << '\n';
param.balloon.color.at(0) = "blue"; param.balloon.color.at(0) = "blue";
} else { } else {
param.balloon.color.at(0) = v; param.balloon.color.at(0) = v;
@@ -216,7 +213,7 @@ namespace {
}}, }},
{"balloon.color[1]", [validate_balloon_color](const std::string& v) -> void { {"balloon.color[1]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'orange' por defecto.", v.c_str()); std::cout << "Color de globo inválido '" << v << "'. Usando 'orange' por defecto." << '\n';
param.balloon.color.at(1) = "orange"; param.balloon.color.at(1) = "orange";
} else { } else {
param.balloon.color.at(1) = v; param.balloon.color.at(1) = v;
@@ -224,7 +221,7 @@ namespace {
}}, }},
{"balloon.color[2]", [validate_balloon_color](const std::string& v) -> void { {"balloon.color[2]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'red' por defecto.", v.c_str()); std::cout << "Color de globo inválido '" << v << "'. Usando 'red' por defecto." << '\n';
param.balloon.color.at(2) = "red"; param.balloon.color.at(2) = "red";
} else { } else {
param.balloon.color.at(2) = v; param.balloon.color.at(2) = v;
@@ -232,7 +229,7 @@ namespace {
}}, }},
{"balloon.color[3]", [validate_balloon_color](const std::string& v) -> void { {"balloon.color[3]", [validate_balloon_color](const std::string& v) -> void {
if (!validate_balloon_color(v)) { if (!validate_balloon_color(v)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'green' por defecto.", v.c_str()); std::cout << "Color de globo inválido '" << v << "'. Usando 'green' por defecto." << '\n';
param.balloon.color.at(3) = "green"; param.balloon.color.at(3) = "green";
} else { } else {
param.balloon.color.at(3) = v; param.balloon.color.at(3) = v;

View File

@@ -5,6 +5,7 @@
#include <algorithm> // std::min, std::max, std::floor #include <algorithm> // std::min, std::max, std::floor
#include <cmath> // std::floor, std::ceil #include <cmath> // std::floor, std::ceil
#include <cstring> // memcpy, strlen #include <cstring> // memcpy, strlen
#include <iostream> // Para std::cout
#ifndef __APPLE__ #ifndef __APPLE__
#include "rendering/sdl3gpu/crtpi_frag_spv.h" #include "rendering/sdl3gpu/crtpi_frag_spv.h"
@@ -377,7 +378,7 @@ namespace Rendering {
// 1. GPU disabled by config // 1. GPU disabled by config
if (preferred_driver_ == "none") { if (preferred_driver_ == "none") {
SDL_Log("SDL3GPUShader: GPU disabled by config, using SDL_Renderer fallback"); std::cout << "SDL3GPUShader: GPU disabled by config, using SDL_Renderer fallback" << '\n';
driver_name_ = ""; driver_name_ = "";
return false; return false;
} }
@@ -392,18 +393,18 @@ namespace Rendering {
const char* preferred = preferred_driver_.empty() ? nullptr : preferred_driver_.c_str(); const char* preferred = preferred_driver_.empty() ? nullptr : preferred_driver_.c_str();
device_ = SDL_CreateGPUDevice(PREFERRED, false, preferred); device_ = SDL_CreateGPUDevice(PREFERRED, false, preferred);
if (device_ == nullptr && preferred != nullptr) { if (device_ == nullptr && preferred != nullptr) {
SDL_Log("SDL3GPUShader: driver '%s' not available, falling back to auto", preferred); std::cout << "SDL3GPUShader: driver '" << preferred << "' not available, falling back to auto" << '\n';
device_ = SDL_CreateGPUDevice(PREFERRED, false, nullptr); device_ = SDL_CreateGPUDevice(PREFERRED, false, nullptr);
} }
if (device_ == nullptr) { if (device_ == nullptr) {
SDL_Log("SDL3GPUShader: SDL_CreateGPUDevice failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: SDL_CreateGPUDevice failed: " << SDL_GetError() << '\n';
return false; return false;
} }
driver_name_ = SDL_GetGPUDeviceDriver(device_); driver_name_ = SDL_GetGPUDeviceDriver(device_);
SDL_Log("SDL3GPUShader: driver = %s", driver_name_.c_str()); std::cout << "SDL3GPUShader: driver = " << driver_name_ << '\n';
if (!SDL_ClaimWindowForGPUDevice(device_, window_)) { if (!SDL_ClaimWindowForGPUDevice(device_, window_)) {
SDL_Log("SDL3GPUShader: SDL_ClaimWindowForGPUDevice failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: SDL_ClaimWindowForGPUDevice failed: " << SDL_GetError() << '\n';
SDL_DestroyGPUDevice(device_); SDL_DestroyGPUDevice(device_);
device_ = nullptr; device_ = nullptr;
return false; return false;
@@ -422,7 +423,7 @@ namespace Rendering {
tex_info.num_levels = 1; tex_info.num_levels = 1;
scene_texture_ = SDL_CreateGPUTexture(device_, &tex_info); scene_texture_ = SDL_CreateGPUTexture(device_, &tex_info);
if (scene_texture_ == nullptr) { if (scene_texture_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create scene texture: %s", SDL_GetError()); std::cout << "SDL3GPUShader: failed to create scene texture: " << SDL_GetError() << '\n';
cleanup(); cleanup();
return false; return false;
} }
@@ -435,7 +436,7 @@ namespace Rendering {
tb_info.size = static_cast<Uint32>(game_width_ * game_height_ * 4); tb_info.size = static_cast<Uint32>(game_width_ * game_height_ * 4);
upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info); upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info);
if (upload_buffer_ == nullptr) { if (upload_buffer_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create upload buffer: %s", SDL_GetError()); std::cout << "SDL3GPUShader: failed to create upload buffer: " << SDL_GetError() << '\n';
cleanup(); cleanup();
return false; return false;
} }
@@ -450,7 +451,7 @@ namespace Rendering {
samp_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; samp_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
sampler_ = SDL_CreateGPUSampler(device_, &samp_info); sampler_ = SDL_CreateGPUSampler(device_, &samp_info);
if (sampler_ == nullptr) { if (sampler_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create sampler: %s", SDL_GetError()); std::cout << "SDL3GPUShader: failed to create sampler: " << SDL_GetError() << '\n';
cleanup(); cleanup();
return false; return false;
} }
@@ -464,7 +465,7 @@ namespace Rendering {
lsamp_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; lsamp_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
linear_sampler_ = SDL_CreateGPUSampler(device_, &lsamp_info); linear_sampler_ = SDL_CreateGPUSampler(device_, &lsamp_info);
if (linear_sampler_ == nullptr) { if (linear_sampler_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create linear sampler: %s", SDL_GetError()); std::cout << "SDL3GPUShader: failed to create linear sampler: " << SDL_GetError() << '\n';
cleanup(); cleanup();
return false; return false;
} }
@@ -480,7 +481,7 @@ namespace Rendering {
} }
is_initialized_ = true; is_initialized_ = true;
SDL_Log("SDL3GPUShader: initialized OK (%dx%d)", game_width_, game_height_); std::cout << "SDL3GPUShader: initialized OK (" << game_width_ << "x" << game_height_ << ")" << '\n';
return true; return true;
} }
@@ -500,7 +501,7 @@ namespace Rendering {
#endif #endif
if ((vert == nullptr) || (frag == nullptr)) { if ((vert == nullptr) || (frag == nullptr)) {
SDL_Log("SDL3GPUShader: failed to compile PostFX shaders"); std::cout << "SDL3GPUShader: failed to compile PostFX shaders" << '\n';
if (vert != nullptr) { SDL_ReleaseGPUShader(device_, vert); } if (vert != nullptr) { SDL_ReleaseGPUShader(device_, vert); }
if (frag != nullptr) { SDL_ReleaseGPUShader(device_, frag); } if (frag != nullptr) { SDL_ReleaseGPUShader(device_, frag); }
return false; return false;
@@ -529,7 +530,7 @@ namespace Rendering {
SDL_ReleaseGPUShader(device_, frag); SDL_ReleaseGPUShader(device_, frag);
if (pipeline_ == nullptr) { if (pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: PostFX pipeline creation failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: PostFX pipeline creation failed: " << SDL_GetError() << '\n';
return false; return false;
} }
@@ -565,7 +566,7 @@ namespace Rendering {
SDL_ReleaseGPUShader(device_, ufrag); SDL_ReleaseGPUShader(device_, ufrag);
if (upscale_pipeline_ == nullptr) { if (upscale_pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: upscale pipeline creation failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: upscale pipeline creation failed: " << SDL_GetError() << '\n';
return false; return false;
} }
@@ -601,7 +602,7 @@ namespace Rendering {
SDL_ReleaseGPUShader(device_, offrag); SDL_ReleaseGPUShader(device_, offrag);
if (postfx_offscreen_pipeline_ == nullptr) { if (postfx_offscreen_pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: PostFX offscreen pipeline creation failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: PostFX offscreen pipeline creation failed: " << SDL_GetError() << '\n';
return false; return false;
} }
@@ -637,7 +638,7 @@ namespace Rendering {
SDL_ReleaseGPUShader(device_, dfrag); SDL_ReleaseGPUShader(device_, dfrag);
if (downscale_pipeline_ == nullptr) { if (downscale_pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: downscale pipeline creation failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: downscale pipeline creation failed: " << SDL_GetError() << '\n';
return false; return false;
} }
@@ -683,7 +684,7 @@ namespace Rendering {
SDL_ReleaseGPUShader(device_, frag); SDL_ReleaseGPUShader(device_, frag);
if (crtpi_pipeline_ == nullptr) { if (crtpi_pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: CrtPi pipeline creation failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: CrtPi pipeline creation failed: " << SDL_GetError() << '\n';
return false; return false;
} }
return true; return true;
@@ -697,7 +698,7 @@ namespace Rendering {
void* mapped = SDL_MapGPUTransferBuffer(device_, upload_buffer_, false); void* mapped = SDL_MapGPUTransferBuffer(device_, upload_buffer_, false);
if (mapped == nullptr) { if (mapped == nullptr) {
SDL_Log("SDL3GPUShader: SDL_MapGPUTransferBuffer failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: SDL_MapGPUTransferBuffer failed: " << SDL_GetError() << '\n';
return; return;
} }
@@ -726,7 +727,7 @@ namespace Rendering {
SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(device_); SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(device_);
if (cmd == nullptr) { if (cmd == nullptr) {
SDL_Log("SDL3GPUShader: SDL_AcquireGPUCommandBuffer failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: SDL_AcquireGPUCommandBuffer failed: " << SDL_GetError() << '\n';
return; return;
} }
@@ -773,7 +774,7 @@ namespace Rendering {
Uint32 sw = 0; Uint32 sw = 0;
Uint32 sh = 0; Uint32 sh = 0;
if (!SDL_AcquireGPUSwapchainTexture(cmd, window_, &swapchain, &sw, &sh)) { if (!SDL_AcquireGPUSwapchainTexture(cmd, window_, &swapchain, &sw, &sh)) {
SDL_Log("SDL3GPUShader: SDL_AcquireGPUSwapchainTexture failed: %s", SDL_GetError()); std::cout << "SDL3GPUShader: SDL_AcquireGPUSwapchainTexture failed: " << SDL_GetError() << '\n';
SDL_SubmitGPUCommandBuffer(cmd); SDL_SubmitGPUCommandBuffer(cmd);
return; return;
} }
@@ -998,7 +999,7 @@ namespace Rendering {
info.num_uniform_buffers = num_uniform_buffers; info.num_uniform_buffers = num_uniform_buffers;
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info); SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info);
if (shader == nullptr) { if (shader == nullptr) {
SDL_Log("SDL3GPUShader: MSL shader '%s' failed: %s", entrypoint, SDL_GetError()); std::cout << "SDL3GPUShader: MSL shader '" << entrypoint << "' failed: " << SDL_GetError() << '\n';
} }
return shader; return shader;
} }
@@ -1020,7 +1021,7 @@ namespace Rendering {
info.num_uniform_buffers = num_uniform_buffers; info.num_uniform_buffers = num_uniform_buffers;
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info); SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info);
if (shader == nullptr) { if (shader == nullptr) {
SDL_Log("SDL3GPUShader: SPIRV shader '%s' failed: %s", entrypoint, SDL_GetError()); std::cout << "SDL3GPUShader: SPIRV shader '" << entrypoint << "' failed: " << SDL_GetError() << '\n';
} }
return shader; return shader;
} }
@@ -1135,7 +1136,7 @@ namespace Rendering {
tex_info.num_levels = 1; tex_info.num_levels = 1;
scene_texture_ = SDL_CreateGPUTexture(device_, &tex_info); scene_texture_ = SDL_CreateGPUTexture(device_, &tex_info);
if (scene_texture_ == nullptr) { if (scene_texture_ == nullptr) {
SDL_Log("SDL3GPUShader: reinit — failed to create scene texture: %s", SDL_GetError()); std::cout << "SDL3GPUShader: reinit — failed to create scene texture: " << SDL_GetError() << '\n';
return false; return false;
} }
@@ -1144,13 +1145,13 @@ namespace Rendering {
tb_info.size = static_cast<Uint32>(game_width_ * game_height_ * 4); tb_info.size = static_cast<Uint32>(game_width_ * game_height_ * 4);
upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info); upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info);
if (upload_buffer_ == nullptr) { if (upload_buffer_ == nullptr) {
SDL_Log("SDL3GPUShader: reinit — failed to create upload buffer: %s", SDL_GetError()); std::cout << "SDL3GPUShader: reinit — failed to create upload buffer: " << SDL_GetError() << '\n';
SDL_ReleaseGPUTexture(device_, scene_texture_); SDL_ReleaseGPUTexture(device_, scene_texture_);
scene_texture_ = nullptr; scene_texture_ = nullptr;
return false; return false;
} }
SDL_Log("SDL3GPUShader: reinit — scene %dx%d, SS %s", game_width_, game_height_, oversample_ > 1 ? "on" : "off"); std::cout << "SDL3GPUShader: reinit — scene " << game_width_ << "x" << game_height_ << ", SS " << (oversample_ > 1 ? "on" : "off") << '\n';
return true; return true;
} }
@@ -1185,20 +1186,20 @@ namespace Rendering {
scaled_texture_ = SDL_CreateGPUTexture(device_, &info); scaled_texture_ = SDL_CreateGPUTexture(device_, &info);
if (scaled_texture_ == nullptr) { if (scaled_texture_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create scaled texture %dx%d: %s", W, H, SDL_GetError()); std::cout << "SDL3GPUShader: failed to create scaled texture " << W << "x" << H << ": " << SDL_GetError() << '\n';
return false; return false;
} }
postfx_texture_ = SDL_CreateGPUTexture(device_, &info); postfx_texture_ = SDL_CreateGPUTexture(device_, &info);
if (postfx_texture_ == nullptr) { if (postfx_texture_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create postfx texture %dx%d: %s", W, H, SDL_GetError()); std::cout << "SDL3GPUShader: failed to create postfx texture " << W << "x" << H << ": " << SDL_GetError() << '\n';
SDL_ReleaseGPUTexture(device_, scaled_texture_); SDL_ReleaseGPUTexture(device_, scaled_texture_);
scaled_texture_ = nullptr; scaled_texture_ = nullptr;
return false; return false;
} }
ss_factor_ = factor; ss_factor_ = factor;
SDL_Log("SDL3GPUShader: scaled+postfx textures %dx%d (factor %dx)", W, H, factor); std::cout << "SDL3GPUShader: scaled+postfx textures " << W << "x" << H << " (factor " << factor << "x)" << '\n';
return true; return true;
} }

View File

@@ -7,6 +7,7 @@
#include <exception> // Para exception #include <exception> // Para exception
#include <filesystem> // Para exists, path, remove #include <filesystem> // Para exists, path, remove
#include <fstream> // Para basic_ofstream, basic_ios, basic_ostream::write, ios, ofstream #include <fstream> // Para basic_ofstream, basic_ios, basic_ostream::write, ios, ofstream
#include <iostream> // Para std::cout
#include <ranges> // Para __find_if_fn, find_if, __find_fn, find #include <ranges> // Para __find_if_fn, find_if, __find_fn, find
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <utility> // Para move #include <utility> // Para move
@@ -19,7 +20,6 @@
#include "resource_helper.hpp" // Para loadFile #include "resource_helper.hpp" // Para loadFile
#include "screen.hpp" // Para Screen #include "screen.hpp" // Para Screen
#include "text.hpp" // Para Text #include "text.hpp" // Para Text
#include "ui/logger.hpp" // Para info, CR, dots
#include "utils.hpp" // Para getFileName #include "utils.hpp" // Para getFileName
#include "version.h" // Para APP_NAME, GIT_HASH #include "version.h" // Para APP_NAME, GIT_HASH
@@ -80,21 +80,16 @@ Resource::~Resource() {
// Carga los recursos esenciales que siempre se necesitan (modo lazy) // Carga los recursos esenciales que siempre se necesitan (modo lazy)
void Resource::loadEssentialResources() { void Resource::loadEssentialResources() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading essential resources for lazy mode");
// Cargar recursos de texto básicos que se usan para crear texturas // Cargar recursos de texto básicos que se usan para crear texturas
loadTextFilesQuiet(); // <- VERSIÓN SILENCIOSA loadTextFilesQuiet(); // <- VERSIÓN SILENCIOSA
loadEssentialTextures(); // Ya es silenciosa loadEssentialTextures(); // Ya es silenciosa
createText(); // Crear objetos de texto createText(); // Crear objetos de texto
createTextTextures(); // Crear texturas generadas (game_text_xxx) createTextTextures(); // Crear texturas generadas (game_text_xxx)
createPlayerTextures(); // Crea las texturas de jugadores con todas sus variantes de paleta createPlayerTextures(); // Crea las texturas de jugadores con todas sus variantes de paleta
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Essential resources loaded");
} }
// Carga los ficheros de texto del juego (versión silenciosa) // Carga los ficheros de texto del juego (versión silenciosa)
void Resource::loadTextFilesQuiet() { void Resource::loadTextFilesQuiet() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXT FILES (quiet load)");
auto list = Asset::get()->getListByType(Asset::Type::FONT); auto list = Asset::get()->getListByType(Asset::Type::FONT);
for (const auto& l : list) { for (const auto& l : list) {
@@ -103,7 +98,6 @@ void Resource::loadTextFilesQuiet() {
auto it = std::ranges::find_if(text_files_, [&name](const auto& t) -> auto { return t.name == name; }); auto it = std::ranges::find_if(text_files_, [&name](const auto& t) -> auto { return t.name == name; });
if (it != text_files_.end()) { if (it != text_files_.end()) {
it->text_file = Text::loadFile(l); it->text_file = Text::loadFile(l);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Text file loaded: %s", name.c_str());
} }
} }
} }
@@ -141,8 +135,6 @@ void Resource::loadEssentialTextures() {
// Inicializa las listas de recursos sin cargar el contenido (modo lazy) // Inicializa las listas de recursos sin cargar el contenido (modo lazy)
void Resource::initResourceLists() { void Resource::initResourceLists() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Initializing resource lists for lazy loading");
// Inicializa lista de sonidos // Inicializa lista de sonidos
auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND); auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND);
sounds_.clear(); sounds_.clear();
@@ -200,8 +192,6 @@ void Resource::initResourceLists() {
for (const auto& text_name : TEXT_OBJECTS) { for (const auto& text_name : TEXT_OBJECTS) {
texts_.emplace_back(text_name); // Constructor con nullptr por defecto texts_.emplace_back(text_name); // Constructor con nullptr por defecto
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Resource lists initialized for lazy loading");
} }
// Obtiene el sonido a partir de un nombre (con carga perezosa) // Obtiene el sonido a partir de un nombre (con carga perezosa)
@@ -216,7 +206,7 @@ auto Resource::getSound(const std::string& name) -> JA_Sound_t* {
return it->sound; return it->sound;
} }
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Sonido no encontrado %s", name.c_str()); std::cout << "Error: Sonido no encontrado " << name << '\n';
throw std::runtime_error("Sonido no encontrado: " + name); throw std::runtime_error("Sonido no encontrado: " + name);
} }
@@ -232,7 +222,7 @@ auto Resource::getMusic(const std::string& name) -> JA_Music_t* {
return it->music; return it->music;
} }
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Música no encontrada %s", name.c_str()); std::cout << "Error: Música no encontrada " << name << '\n';
throw std::runtime_error("Música no encontrada: " + name); throw std::runtime_error("Música no encontrada: " + name);
} }
@@ -248,7 +238,7 @@ auto Resource::getTexture(const std::string& name) -> std::shared_ptr<Texture> {
return it->texture; return it->texture;
} }
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Imagen no encontrada %s", name.c_str()); std::cout << "Error: Imagen no encontrada " << name << '\n';
throw std::runtime_error("Imagen no encontrada: " + name); throw std::runtime_error("Imagen no encontrada: " + name);
} }
@@ -264,7 +254,7 @@ auto Resource::getTextFile(const std::string& name) -> std::shared_ptr<Text::Fil
return it->text_file; return it->text_file;
} }
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: TextFile no encontrado %s", name.c_str()); std::cout << "Error: TextFile no encontrado " << name << '\n';
throw std::runtime_error("TextFile no encontrado: " + name); throw std::runtime_error("TextFile no encontrado: " + name);
} }
@@ -280,7 +270,7 @@ auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> {
return it->text; return it->text;
} }
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Text no encontrado %s", name.c_str()); std::cout << "Error: Text no encontrado " << name << '\n';
throw std::runtime_error("Text no encontrado: " + name); throw std::runtime_error("Text no encontrado: " + name);
} }
@@ -296,14 +286,14 @@ auto Resource::getAnimation(const std::string& name) -> AnimationsFileBuffer& {
return it->animation; return it->animation;
} }
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Animación no encontrada %s", name.c_str()); std::cout << "Error: Animación no encontrada " << name << '\n';
throw std::runtime_error("Animación no encontrada: " + name); throw std::runtime_error("Animación no encontrada: " + name);
} }
// Obtiene el fichero con los datos para el modo demostración a partir de un índice // Obtiene el fichero con los datos para el modo demostración a partir de un índice
auto Resource::getDemoData(int index) -> DemoData& { auto Resource::getDemoData(int index) -> DemoData& {
if (index < 0 || std::cmp_greater_equal(index, demos_.size())) { if (index < 0 || std::cmp_greater_equal(index, demos_.size())) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Index %d out of range for demo data (size: %d)", index, static_cast<int>(demos_.size())); std::cout << "Index " << index << " out of range for demo data (size: " << static_cast<int>(demos_.size()) << ")" << '\n';
static DemoData empty_demo_; static DemoData empty_demo_;
return empty_demo_; return empty_demo_;
} }
@@ -313,7 +303,6 @@ auto Resource::getDemoData(int index) -> DemoData& {
// --- Métodos de carga perezosa --- // --- Métodos de carga perezosa ---
auto Resource::loadSoundLazy(const std::string& name) -> JA_Sound_t* { auto Resource::loadSoundLazy(const std::string& name) -> JA_Sound_t* {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading sound lazily: %s", name.c_str());
auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND); auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND);
for (const auto& file : sound_list) { for (const auto& file : sound_list) {
if (getFileName(file) == name) { if (getFileName(file) == name) {
@@ -329,7 +318,6 @@ auto Resource::loadSoundLazy(const std::string& name) -> JA_Sound_t* {
} }
auto Resource::loadMusicLazy(const std::string& name) -> JA_Music_t* { auto Resource::loadMusicLazy(const std::string& name) -> JA_Music_t* {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading music lazily: %s", name.c_str());
auto music_list = Asset::get()->getListByType(Asset::Type::MUSIC); auto music_list = Asset::get()->getListByType(Asset::Type::MUSIC);
for (const auto& file : music_list) { for (const auto& file : music_list) {
if (getFileName(file) == name) { if (getFileName(file) == name) {
@@ -345,7 +333,6 @@ auto Resource::loadMusicLazy(const std::string& name) -> JA_Music_t* {
} }
auto Resource::loadTextureLazy(const std::string& name) -> std::shared_ptr<Texture> { auto Resource::loadTextureLazy(const std::string& name) -> std::shared_ptr<Texture> {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading texture lazily: %s", name.c_str());
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP); auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
for (const auto& file : texture_list) { for (const auto& file : texture_list) {
if (getFileName(file) == name) { if (getFileName(file) == name) {
@@ -356,7 +343,6 @@ auto Resource::loadTextureLazy(const std::string& name) -> std::shared_ptr<Textu
} }
auto Resource::loadTextFileLazy(const std::string& name) -> std::shared_ptr<Text::File> { auto Resource::loadTextFileLazy(const std::string& name) -> std::shared_ptr<Text::File> {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading text file lazily: %s", name.c_str());
auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT); auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
for (const auto& file : text_file_list) { for (const auto& file : text_file_list) {
if (getFileName(file) == name) { if (getFileName(file) == name) {
@@ -367,8 +353,6 @@ auto Resource::loadTextFileLazy(const std::string& name) -> std::shared_ptr<Text
} }
auto Resource::loadTextLazy(const std::string& name) -> std::shared_ptr<Text> { auto Resource::loadTextLazy(const std::string& name) -> std::shared_ptr<Text> {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading text object lazily: %s", name.c_str());
// Mapeo de objetos de texto a sus recursos // Mapeo de objetos de texto a sus recursos
struct TextMapping { struct TextMapping {
std::string key; std::string key;
@@ -406,7 +390,6 @@ auto Resource::loadTextLazy(const std::string& name) -> std::shared_ptr<Text> {
} }
auto Resource::loadAnimationLazy(const std::string& name) -> AnimationsFileBuffer { auto Resource::loadAnimationLazy(const std::string& name) -> AnimationsFileBuffer {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Loading animation lazily: %s", name.c_str());
auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION); auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
for (const auto& file : animation_list) { for (const auto& file : animation_list) {
if (getFileName(file) == name) { if (getFileName(file) == name) {
@@ -470,7 +453,6 @@ void Resource::loadSounds() {
auto list = Asset::get()->getListByType(Asset::Type::SOUND); auto list = Asset::get()->getListByType(Asset::Type::SOUND);
sounds_.clear(); sounds_.clear();
int failed = 0;
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
updateLoadingProgress(name); updateLoadingProgress(name);
@@ -482,12 +464,10 @@ void Resource::loadSounds() {
sound = JA_LoadSound(l.c_str()); sound = JA_LoadSound(l.c_str());
} }
if (sound == nullptr) { if (sound == nullptr) {
Logger::error(" Sound load failed: " + name); std::cout << "Sound load failed: " << name << '\n';
++failed;
} }
sounds_.emplace_back(name, sound); sounds_.emplace_back(name, sound);
} }
Logger::info("Sounds loaded: " + std::to_string(list.size() - failed) + "/" + std::to_string(list.size()));
} }
// Carga las músicas del juego // Carga las músicas del juego
@@ -495,7 +475,6 @@ void Resource::loadMusics() {
auto list = Asset::get()->getListByType(Asset::Type::MUSIC); auto list = Asset::get()->getListByType(Asset::Type::MUSIC);
musics_.clear(); musics_.clear();
int failed = 0;
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
updateLoadingProgress(name); updateLoadingProgress(name);
@@ -507,12 +486,10 @@ void Resource::loadMusics() {
music = JA_LoadMusic(l.c_str()); music = JA_LoadMusic(l.c_str());
} }
if (music == nullptr) { if (music == nullptr) {
Logger::error(" Music load failed: " + name); std::cout << "Music load failed: " << name << '\n';
++failed;
} }
musics_.emplace_back(name, music); musics_.emplace_back(name, music);
} }
Logger::info("Musics loaded: " + std::to_string(list.size() - failed) + "/" + std::to_string(list.size()));
} }
// Carga las texturas del juego // Carga las texturas del juego
@@ -525,7 +502,6 @@ void Resource::loadTextures() {
updateLoadingProgress(name); updateLoadingProgress(name);
textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)); textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l));
} }
Logger::info("Textures loaded: " + std::to_string(list.size()));
} }
// Carga los ficheros de texto del juego // Carga los ficheros de texto del juego
@@ -538,7 +514,6 @@ void Resource::loadTextFiles() {
updateLoadingProgress(name); updateLoadingProgress(name);
text_files_.emplace_back(name, Text::loadFile(l)); text_files_.emplace_back(name, Text::loadFile(l));
} }
Logger::info("Text files loaded: " + std::to_string(list.size()));
} }
// Carga las animaciones del juego // Carga las animaciones del juego
@@ -551,7 +526,6 @@ void Resource::loadAnimations() {
updateLoadingProgress(name); updateLoadingProgress(name);
animations_.emplace_back(name, loadAnimationsFromFile(l)); animations_.emplace_back(name, loadAnimationsFromFile(l));
} }
Logger::info("Animations loaded: " + std::to_string(list.size()));
} }
// Carga los datos para el modo demostración // Carga los datos para el modo demostración
@@ -564,7 +538,6 @@ void Resource::loadDemoData() {
updateLoadingProgress(name); updateLoadingProgress(name);
demos_.emplace_back(loadDemoDataFromFile(l)); demos_.emplace_back(loadDemoDataFromFile(l));
} }
Logger::info("Demo files loaded: " + std::to_string(list.size()));
} }
// Crea las texturas de jugadores con todas sus variantes de paleta // Crea las texturas de jugadores con todas sus variantes de paleta
@@ -641,7 +614,6 @@ void Resource::createPlayerTextures() {
textures_.emplace_back(texture_name, texture); textures_.emplace_back(texture_name, texture);
} }
} }
Logger::info("Player textures created: " + std::to_string(players.size() * 4));
} }
// Crea texturas a partir de textos para mostrar puntuaciones y mensajes // Crea texturas a partir de textos para mostrar puntuaciones y mensajes
@@ -683,8 +655,6 @@ void Resource::createTextTextures() {
for (const auto& s : strings2) { for (const auto& s : strings2) {
textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color)); textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
} }
Logger::info("Text textures created: " + std::to_string(strings1.size() + strings2.size()));
} }
// Crea los objetos de texto a partir de los archivos de textura y texto // Crea los objetos de texto a partir de los archivos de textura y texto
@@ -728,7 +698,6 @@ void Resource::createText() {
texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file))); texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file)));
} }
} }
Logger::info("Text objects created: " + std::to_string(resources.size()));
} }
// Vacía el vector de sonidos y libera la memoria asociada // Vacía el vector de sonidos y libera la memoria asociada
@@ -847,7 +816,6 @@ void Resource::renderProgress() {
// Carga los datos para el modo demostración (sin mostrar progreso) // Carga los datos para el modo demostración (sin mostrar progreso)
void Resource::loadDemoDataQuiet() { void Resource::loadDemoDataQuiet() {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES (quiet load)");
auto list = Asset::get()->getListByType(Asset::Type::DEMODATA); auto list = Asset::get()->getListByType(Asset::Type::DEMODATA);
demos_.clear(); demos_.clear();

View File

@@ -33,8 +33,6 @@ auto ResourceLoader::initialize(const std::string& pack_file, bool enable_fallba
if (std::filesystem::exists(pack_file)) { if (std::filesystem::exists(pack_file)) {
resource_pack_ = new ResourcePack(); resource_pack_ = new ResourcePack();
if (resource_pack_->loadPack(pack_file)) { if (resource_pack_->loadPack(pack_file)) {
std::cout << "Resource pack loaded successfully: " << pack_file << '\n';
std::cout << "Resources available: " << resource_pack_->getResourceCount() << '\n';
return true; return true;
} }
delete resource_pack_; delete resource_pack_;
@@ -43,7 +41,6 @@ auto ResourceLoader::initialize(const std::string& pack_file, bool enable_fallba
} }
if (fallback_to_files_) { if (fallback_to_files_) {
std::cout << "Using fallback mode: loading resources from data/ directory" << '\n';
return true; return true;
} }

View File

@@ -4,6 +4,7 @@
#include <algorithm> // Para min, max #include <algorithm> // Para min, max
#include <cstring> // Para memcpy #include <cstring> // Para memcpy
#include <iostream> // Para std::cout
#include <memory> // Para allocator, shared_ptr, unique_ptr, __shared_ptr_access, make_shared, make_unique #include <memory> // Para allocator, shared_ptr, unique_ptr, __shared_ptr_access, make_shared, make_unique
#include <string> // Para basic_string, operator+, char_traits, to_string, string #include <string> // Para basic_string, operator+, char_traits, to_string, string
#include <vector> // Para vector #include <vector> // Para vector
@@ -17,7 +18,6 @@
#include "resource.hpp" // Para Resource #include "resource.hpp" // Para Resource
#include "text.hpp" // Para Text #include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
#include "ui/logger.hpp" // Para info
#include "ui/notifier.hpp" // Para Notifier #include "ui/notifier.hpp" // Para Notifier
#include "ui/service_menu.hpp" // Para ServiceMenu #include "ui/service_menu.hpp" // Para ServiceMenu
#include "utils.hpp" // Para toLower #include "utils.hpp" // Para toLower
@@ -290,7 +290,7 @@ void Screen::initShaders() {
#ifndef NO_SHADERS #ifndef NO_SHADERS
auto* self = Screen::get(); auto* self = Screen::get();
if (self == nullptr) { if (self == nullptr) {
SDL_Log("Screen::initShaders: instance is null, skipping"); std::cout << "Screen::initShaders: instance is null, skipping" << '\n';
return; return;
} }
if (!self->shader_backend_) { if (!self->shader_backend_) {
@@ -301,7 +301,7 @@ void Screen::initShaders() {
} }
if (!self->shader_backend_->isHardwareAccelerated()) { if (!self->shader_backend_->isHardwareAccelerated()) {
const bool ok = self->shader_backend_->init(self->window_, self->game_canvas_, "", ""); const bool ok = self->shader_backend_->init(self->window_, self->game_canvas_, "", "");
SDL_Log("Screen::initShaders: SDL3GPUShader::init() = %s", ok ? "OK" : "FAILED"); std::cout << "Screen::initShaders: SDL3GPUShader::init() = " << (ok ? "OK" : "FAILED") << '\n';
} }
if (self->shader_backend_ && self->shader_backend_->isHardwareAccelerated()) { if (self->shader_backend_ && self->shader_backend_->isHardwareAccelerated()) {
self->shader_backend_->setLinearUpscale(Options::video.supersampling.linear_upscale); self->shader_backend_->setLinearUpscale(Options::video.supersampling.linear_upscale);
@@ -371,9 +371,7 @@ void Screen::renderAttenuate() {
auto Screen::initSDLVideo() -> bool { auto Screen::initSDLVideo() -> bool {
// Inicializar SDL // Inicializar SDL
if (!SDL_Init(SDL_INIT_VIDEO)) { if (!SDL_Init(SDL_INIT_VIDEO)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, std::cout << "FATAL: Failed to initialize SDL_VIDEO! SDL Error: " << SDL_GetError() << '\n';
"FATAL: Failed to initialize SDL_VIDEO! SDL Error: %s",
SDL_GetError());
return false; return false;
} }
@@ -383,8 +381,7 @@ auto Screen::initSDLVideo() -> bool {
// Configurar hint para renderizado // Configurar hint para renderizado
#ifdef __APPLE__ #ifdef __APPLE__
if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal")) { if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal")) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, std::cout << "Warning: Failed to set Metal hint!" << '\n';
"Warning: Failed to set Metal hint!");
} }
#endif #endif
@@ -405,9 +402,7 @@ auto Screen::initSDLVideo() -> bool {
window_flags); window_flags);
if (window_ == nullptr) { if (window_ == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, std::cout << "FATAL: Failed to create window! SDL Error: " << SDL_GetError() << '\n';
"FATAL: Failed to create window! SDL Error: %s",
SDL_GetError());
SDL_Quit(); SDL_Quit();
return false; return false;
} }
@@ -415,9 +410,7 @@ auto Screen::initSDLVideo() -> bool {
// Crear renderer // Crear renderer
renderer_ = SDL_CreateRenderer(window_, nullptr); renderer_ = SDL_CreateRenderer(window_, nullptr);
if (renderer_ == nullptr) { if (renderer_ == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, std::cout << "FATAL: Failed to create renderer! SDL Error: " << SDL_GetError() << '\n';
"FATAL: Failed to create renderer! SDL Error: %s",
SDL_GetError());
SDL_DestroyWindow(window_); SDL_DestroyWindow(window_);
window_ = nullptr; window_ = nullptr;
SDL_Quit(); SDL_Quit();
@@ -429,24 +422,14 @@ auto Screen::initSDLVideo() -> bool {
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
SDL_SetRenderVSync(renderer_, Options::video.vsync ? 1 : SDL_RENDERER_VSYNC_DISABLED); SDL_SetRenderVSync(renderer_, Options::video.vsync ? 1 : SDL_RENDERER_VSYNC_DISABLED);
Logger::info("Video system initialized successfully");
return true; return true;
} }
// Obtiene información sobre la pantalla // Obtiene información sobre la pantalla
void Screen::getDisplayInfo() { void Screen::getDisplayInfo() {
int i;
int num_displays = 0; int num_displays = 0;
SDL_DisplayID* displays = SDL_GetDisplays(&num_displays); SDL_DisplayID* displays = SDL_GetDisplays(&num_displays);
if (displays != nullptr) { if (displays != nullptr) {
for (i = 0; i < num_displays; ++i) {
SDL_DisplayID instance_id = displays[i];
const char* name = SDL_GetDisplayName(instance_id);
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Display %" SDL_PRIu32 ": %s", instance_id, (name != nullptr) ? name : "Unknown");
Logger::info(std::string("Display ") + std::to_string(instance_id) + ": " + (name != nullptr ? name : "Unknown"));
}
const auto* dm = SDL_GetCurrentDisplayMode(displays[0]); const auto* dm = SDL_GetCurrentDisplayMode(displays[0]);
// Guarda información del monitor en display_monitor_ // Guarda información del monitor en display_monitor_
@@ -465,13 +448,6 @@ void Screen::getDisplayInfo() {
std::to_string(dm->h) + " @ " + std::to_string(dm->h) + " @ " +
std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz"; std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz";
// Muestra información sobre el tamaño de la pantalla y de la ventana de juego
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Current display mode: %dx%d @ %dHz", static_cast<int>(dm->w), static_cast<int>(dm->h), static_cast<int>(dm->refresh_rate));
Logger::info("Current display mode: " + Options::video.info);
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Window resolution: %dx%d x%d", static_cast<int>(param.game.width), static_cast<int>(param.game.height), Options::window.zoom);
Logger::info("Window resolution: " + std::to_string(static_cast<int>(param.game.width)) + "x" + std::to_string(static_cast<int>(param.game.height)) + "x" + std::to_string(Options::window.zoom));
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla // Calcula el máximo factor de zoom que se puede aplicar a la pantalla
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS) / param.game.height); const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS) / param.game.height);
@@ -563,11 +539,7 @@ void Screen::applyCurrentPostFXPreset() {
p.curvature = preset.curvature; p.curvature = preset.curvature;
p.bleeding = preset.bleeding; p.bleeding = preset.bleeding;
p.flicker = preset.flicker; p.flicker = preset.flicker;
SDL_Log("Screen::applyCurrentPostFXPreset: preset='%s' scan=%.2f vign=%.2f chroma=%.2f", std::cout << "Screen::applyCurrentPostFXPreset: preset='" << preset.name << "' scan=" << p.scanlines << " vign=" << p.vignette << " chroma=" << p.chroma << '\n';
preset.name.c_str(),
p.scanlines,
p.vignette,
p.chroma);
} }
shader_backend_->setPostFXParams(p); shader_backend_->setPostFXParams(p);
} }
@@ -594,7 +566,7 @@ void Screen::applyCurrentCrtPiPreset() {
.enable_sharper = preset.enable_sharper, .enable_sharper = preset.enable_sharper,
}; };
shader_backend_->setCrtPiParams(p); shader_backend_->setCrtPiParams(p);
SDL_Log("Screen::applyCurrentCrtPiPreset: preset='%s'", preset.name.c_str()); std::cout << "Screen::applyCurrentCrtPiPreset: preset='" << preset.name << "'" << '\n';
} }
} }

View File

@@ -28,7 +28,6 @@
#include "text.hpp" // Para Text #include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode #include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
#include "ui/logger.hpp" // Para section
#include "ui/service_menu.hpp" // Para ServiceMenu #include "ui/service_menu.hpp" // Para ServiceMenu
#include "utils.hpp" // Para Zone #include "utils.hpp" // Para Zone
@@ -49,8 +48,6 @@ Credits::Credits()
initVars(); initVars();
startCredits(); startCredits();
Logger::section("CREDITS");
// Inicializa el timer de delta time para el primer frame del callback // Inicializa el timer de delta time para el primer frame del callback
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();
} }

View File

@@ -41,7 +41,6 @@
#include "smart_sprite.hpp" // Para SmartSprite #include "smart_sprite.hpp" // Para SmartSprite
#include "stage.hpp" // Para StageManager, StageData #include "stage.hpp" // Para StageManager, StageData
#include "tabe.hpp" // Para Tabe #include "tabe.hpp" // Para Tabe
#include "ui/logger.hpp" // Para section
#include "text.hpp" // Para Text #include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
#include "ui/service_menu.hpp" // Para ServiceMenu #include "ui/service_menu.hpp" // Para ServiceMenu
@@ -133,8 +132,6 @@ Game::Game(Player::Id player_id, int current_stage, bool demo_enabled)
setState(State::PLAYING); setState(State::PLAYING);
#endif #endif
Logger::section(demo_.enabled ? "GAME (DEMO)" : "GAME");
// Inicializa el timer de delta time para el primer frame del callback // Inicializa el timer de delta time para el primer frame del callback
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();
} }

View File

@@ -23,7 +23,6 @@
#include "resource.hpp" // Para Resource #include "resource.hpp" // Para Resource
#include "screen.hpp" // Para Screen #include "screen.hpp" // Para Screen
#include "section.hpp" // Para Name, name, Options, options #include "section.hpp" // Para Name, name, Options, options
#include "ui/logger.hpp" // Para section
#include "sprite.hpp" // Para Sprite #include "sprite.hpp" // Para Sprite
#include "text.hpp" // Para Text, Text::SHADOW, Text::COLOR #include "text.hpp" // Para Text, Text::SHADOW, Text::COLOR
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
@@ -47,8 +46,6 @@ HiScoreTable::HiScoreTable()
iniEntryColors(); iniEntryColors();
createSprites(); createSprites();
Logger::section("HI-SCORE TABLE");
// Inicializa el timer de delta time y arranca la música // Inicializa el timer de delta time y arranca la música
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();
Audio::get()->playMusic("title.ogg"); Audio::get()->playMusic("title.ogg");

View File

@@ -23,7 +23,6 @@
#include "sprite.hpp" // Para Sprite #include "sprite.hpp" // Para Sprite
#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW #include "text.hpp" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode #include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
#include "ui/logger.hpp" // Para section
#include "utils.hpp" #include "utils.hpp"
// Constructor // Constructor
@@ -59,8 +58,6 @@ Instructions::Instructions()
// Inicializa los sprites de los items // Inicializa los sprites de los items
iniSprites(); iniSprites();
Logger::section("INSTRUCTIONS");
// Inicializa el timer de delta time y arranca la música // Inicializa el timer de delta time y arranca la música
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();
Audio::get()->playMusic("title.ogg"); Audio::get()->playMusic("title.ogg");

View File

@@ -20,7 +20,6 @@
#include "text.hpp" // Para Text #include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode #include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
#include "ui/logger.hpp" // Para section
#include "utils.hpp" // Para easeOutBounce #include "utils.hpp" // Para easeOutBounce
#include "writer.hpp" // Para Writer #include "writer.hpp" // Para Writer
@@ -41,8 +40,6 @@ Intro::Intro()
tiled_bg_->setSpeed(TILED_BG_SPEED); tiled_bg_->setSpeed(TILED_BG_SPEED);
tiled_bg_->setColor(bg_color_); tiled_bg_->setColor(bg_color_);
Logger::section("INTRO");
// Inicializa el timer de delta time y arranca la música // Inicializa el timer de delta time y arranca la música
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();
Audio::get()->playMusic("intro.ogg", 0); Audio::get()->playMusic("intro.ogg", 0);

View File

@@ -9,7 +9,6 @@
#include "audio.hpp" // Para Audio #include "audio.hpp" // Para Audio
#include "color.hpp" // Para Color #include "color.hpp" // Para Color
#include "global_events.hpp" // Para handle #include "global_events.hpp" // Para handle
#include "ui/logger.hpp" // Para section
#include "global_inputs.hpp" // Para check #include "global_inputs.hpp" // Para check
#include "input.hpp" // Para Input #include "input.hpp" // Para Input
#include "param.hpp" // Para Param, ParamGame, param #include "param.hpp" // Para Param, ParamGame, param
@@ -48,8 +47,6 @@ Logo::Logo()
jail_sprite_.push_back(std::move(temp)); jail_sprite_.push_back(std::move(temp));
} }
Logger::section("LOGO");
// Inicializa el timer de delta time para el primer frame del callback // Inicializa el timer de delta time para el primer frame del callback
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();

View File

@@ -24,7 +24,6 @@
#include "sprite.hpp" // Para Sprite #include "sprite.hpp" // Para Sprite
#include "text.hpp" // Para Text #include "text.hpp" // Para Text
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode #include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
#include "ui/logger.hpp" // Para section
#include "ui/notifier.hpp" // Para Notifier #include "ui/notifier.hpp" // Para Notifier
#include "ui/service_menu.hpp" // Para ServiceMenu #include "ui/service_menu.hpp" // Para ServiceMenu
#include "utils.hpp" // Para Zone, BLOCK #include "utils.hpp" // Para Zone, BLOCK
@@ -61,8 +60,6 @@ Title::Title()
mini_logo_sprite_->setY(anchor_.mini_logo); mini_logo_sprite_->setY(anchor_.mini_logo);
anchor_.copyright_text = anchor_.mini_logo + mini_logo_sprite_->getHeight() + COPYRIGHT_TEXT_SPACING; anchor_.copyright_text = anchor_.mini_logo + mini_logo_sprite_->getHeight() + COPYRIGHT_TEXT_SPACING;
Logger::section("TITLE");
// Inicializa el timer de delta time para el primer frame del callback // Inicializa el timer de delta time para el primer frame del callback
last_time_ = SDL_GetTicks(); last_time_ = SDL_GetTicks();
} }

View File

@@ -15,7 +15,6 @@
#include "screen.hpp" // Para Screen #include "screen.hpp" // Para Screen
#include "sprite.hpp" // Para Sprite #include "sprite.hpp" // Para Sprite
#include "texture.hpp" // Para Texture #include "texture.hpp" // Para Texture
#include "ui/logger.hpp" // Para dots
#include "utils.hpp" // Para getFileName #include "utils.hpp" // Para getFileName
// Constructor // Constructor
@@ -432,7 +431,6 @@ auto Text::loadFile(const std::string& file_path) -> std::shared_ptr<Text::File>
line_read++; line_read++;
}; };
Logger::dots("Text File : ", getFileName(file_path), "[ LOADED ]");
// Cierra el fichero si se usó // Cierra el fichero si se usó
if (!using_resource_data && file.is_open()) { if (!using_resource_data && file.is_open()) {
file.close(); file.close();

View File

@@ -6,17 +6,17 @@
#include <cstdint> // Para uint32_t #include <cstdint> // Para uint32_t
#include <cstring> // Para memcpy #include <cstring> // Para memcpy
#include <fstream> // Para basic_ifstream, basic_istream, basic_ios #include <fstream> // Para basic_ifstream, basic_istream, basic_ios
#include <iostream> // Para std::cout
#include <sstream> // Para basic_istringstream #include <sstream> // Para basic_istringstream
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para basic_string, char_traits, operator+, string #include <string> // Para basic_string, char_traits, operator+, string
#include <utility> #include <utility>
#include <vector> // Para vector #include <vector> // Para vector
#include "color.hpp" // Para getFileName, Color, printWithDots #include "color.hpp" // Para getFileName, Color
#include "external/gif.hpp" // Para Gif #include "external/gif.hpp" // Para Gif
#include "resource_helper.hpp" // Para ResourceHelper #include "resource_helper.hpp" // Para ResourceHelper
#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha #include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha
#include "ui/logger.hpp"
#include "utils.hpp" #include "utils.hpp"
// Constructor // Constructor
@@ -39,7 +39,7 @@ Texture::Texture(SDL_Renderer* renderer, std::string path)
surface_ = loadSurface(path_); surface_ = loadSurface(path_);
// Añade la propia paleta del fichero a la lista // Añade la propia paleta del fichero a la lista
addPaletteFromGifFile(path_, true); // Usar modo silencioso addPaletteFromGifFile(path_);
// Crea la textura, establece el BlendMode y copia la surface a la textura // Crea la textura, establece el BlendMode y copia la surface a la textura
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
@@ -80,10 +80,9 @@ auto Texture::loadFromFile(const std::string& file_path) -> bool {
} }
if (data == nullptr) { if (data == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", getFileName(file_path).c_str()); std::cout << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} }
Logger::dots("Texture : ", getFileName(file_path), "[ LOADED ]");
int pitch; int pitch;
SDL_PixelFormat pixel_format; SDL_PixelFormat pixel_format;
@@ -99,12 +98,12 @@ auto Texture::loadFromFile(const std::string& file_path) -> bool {
// Carga la imagen desde una ruta específica // Carga la imagen desde una ruta específica
auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch); auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch);
if (loaded_surface == nullptr) { if (loaded_surface == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load image %s", file_path.c_str()); std::cout << "Unable to load image " << file_path << '\n';
} else { } else {
// Crea la textura desde los pixels de la surface // Crea la textura desde los pixels de la surface
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface); new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (new_texture == nullptr) { if (new_texture == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create texture from %s! SDL Error: %s", file_path.c_str(), SDL_GetError()); std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << '\n';
} else { } else {
// Obtiene las dimensiones de la imagen // Obtiene las dimensiones de la imagen
width_ = loaded_surface->w; width_ = loaded_surface->w;
@@ -126,7 +125,7 @@ auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_Tex
// Crea una textura sin inicializar // Crea una textura sin inicializar
texture_ = SDL_CreateTexture(renderer_, format, access, width, height); texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (texture_ == nullptr) { if (texture_ == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create blank texture! SDL Error: %s", SDL_GetError()); std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << '\n';
} else { } else {
width_ = width; width_ = width;
height_ = height; height_ = height;
@@ -236,7 +235,7 @@ auto Texture::loadSurface(const std::string& file_path) -> std::shared_ptr<Surfa
// Fallback a filesystem directo // Fallback a filesystem directo
std::ifstream file(file_path, std::ios::binary | std::ios::ate); std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file) { if (!file) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); std::cout << "Error: Fichero no encontrado " << file_path << '\n';
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
@@ -247,7 +246,7 @@ auto Texture::loadSurface(const std::string& file_path) -> std::shared_ptr<Surfa
// Leer el contenido del archivo en un buffer // Leer el contenido del archivo en un buffer
buffer.resize(size); buffer.resize(size);
if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) { if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al leer el fichero %s", file_path.c_str()); std::cout << "Error al leer el fichero " << file_path << '\n';
throw std::runtime_error("Error al leer el fichero: " + file_path); throw std::runtime_error("Error al leer el fichero: " + file_path);
} }
} }
@@ -258,7 +257,7 @@ auto Texture::loadSurface(const std::string& file_path) -> std::shared_ptr<Surfa
Uint16 h = 0; Uint16 h = 0;
std::vector<Uint8> raw_pixels = gif.loadGif(buffer.data(), w, h); std::vector<Uint8> raw_pixels = gif.loadGif(buffer.data(), w, h);
if (raw_pixels.empty()) { if (raw_pixels.empty()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo cargar el GIF %s", file_path.c_str()); std::cout << "Error: No se pudo cargar el GIF " << file_path << '\n';
return nullptr; return nullptr;
} }
@@ -273,7 +272,6 @@ auto Texture::loadSurface(const std::string& file_path) -> std::shared_ptr<Surfa
width_ = w; width_ = w;
height_ = h; height_ = h;
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "GIF %s cargado correctamente.", file_path.c_str());
return surface; return surface;
} }
@@ -302,7 +300,7 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color) {
} }
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
auto Texture::loadPaletteFromFile(const std::string& file_path, bool quiet) -> Palette { auto Texture::loadPaletteFromFile(const std::string& file_path) -> Palette {
Palette palette; Palette palette;
std::vector<Uint8> buffer; std::vector<Uint8> buffer;
@@ -315,7 +313,7 @@ auto Texture::loadPaletteFromFile(const std::string& file_path, bool quiet) -> P
// Fallback a filesystem directo // Fallback a filesystem directo
std::ifstream file(file_path, std::ios::binary | std::ios::ate); std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file) { if (!file) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); std::cout << "Error: Fichero no encontrado " << file_path << '\n';
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
@@ -325,20 +323,16 @@ auto Texture::loadPaletteFromFile(const std::string& file_path, bool quiet) -> P
buffer.resize(size); buffer.resize(size);
if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) { if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo leer completamente el fichero %s", file_path.c_str()); std::cout << "Error: No se pudo leer completamente el fichero " << file_path << '\n';
throw std::runtime_error("Error al leer el fichero: " + file_path); throw std::runtime_error("Error al leer el fichero: " + file_path);
} }
} }
if (!quiet) {
Logger::dots("Palette : ", getFileName(file_path), "[ LOADED ]");
}
// Usar la nueva función loadPalette, que devuelve un vector<uint32_t> // Usar la nueva función loadPalette, que devuelve un vector<uint32_t>
GIF::Gif gif; GIF::Gif gif;
std::vector<uint32_t> pal = gif.loadPalette(buffer.data()); std::vector<uint32_t> pal = gif.loadPalette(buffer.data());
if (pal.empty()) { if (pal.empty()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Advertencia: No se encontró paleta en el archivo %s", file_path.c_str()); std::cout << "Advertencia: No se encontró paleta en el archivo " << file_path << '\n';
return palette; // Devuelve un vector vacío si no hay paleta return palette; // Devuelve un vector vacío si no hay paleta
} }
@@ -347,19 +341,18 @@ auto Texture::loadPaletteFromFile(const std::string& file_path, bool quiet) -> P
palette[i] = (pal[i] << 8) | 0xFF; // Resultado: 0xRRGGBBAA palette[i] = (pal[i] << 8) | 0xFF; // Resultado: 0xRRGGBBAA
} }
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "Paleta cargada correctamente desde %s", file_path.c_str());
return palette; return palette;
} }
// Añade una paleta a la lista // Añade una paleta a la lista
void Texture::addPaletteFromGifFile(const std::string& path, bool quiet) { void Texture::addPaletteFromGifFile(const std::string& path) {
palettes_.emplace_back(loadPaletteFromFile(path, quiet)); palettes_.emplace_back(loadPaletteFromFile(path));
setPaletteColor(palettes_.size() - 1, 0, 0x00000000); setPaletteColor(palettes_.size() - 1, 0, 0x00000000);
} }
// Añade una paleta a la lista // Añade una paleta a la lista
void Texture::addPaletteFromPalFile(const std::string& path) { void Texture::addPaletteFromPalFile(const std::string& path) {
palettes_.emplace_back(readPalFile(path, true)); // Usar modo silencioso palettes_.emplace_back(readPalFile(path));
setPaletteColor(palettes_.size() - 1, 0, 0x00000000); setPaletteColor(palettes_.size() - 1, 0, 0x00000000);
} }
@@ -375,7 +368,7 @@ void Texture::setPalette(size_t palette) {
auto Texture::getRenderer() -> SDL_Renderer* { return renderer_; } auto Texture::getRenderer() -> SDL_Renderer* { return renderer_; }
// Carga una paleta desde un archivo .pal // Carga una paleta desde un archivo .pal
auto Texture::readPalFile(const std::string& file_path, bool quiet) -> Palette { auto Texture::readPalFile(const std::string& file_path) -> Palette {
Palette palette{}; Palette palette{};
palette.fill(0); // Inicializar todo con 0 (transparente por defecto) palette.fill(0); // Inicializar todo con 0 (transparente por defecto)

View File

@@ -49,7 +49,7 @@ class Texture {
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
// --- Paletas --- // --- Paletas ---
void addPaletteFromGifFile(const std::string& path, bool quiet = false); // Añade una paleta a la lista void addPaletteFromGifFile(const std::string& path); // Añade una paleta a la lista
void addPaletteFromPalFile(const std::string& path); // Añade una paleta a la lista void addPaletteFromPalFile(const std::string& path); // Añade una paleta a la lista
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
void setPalette(size_t palette); // Cambia la paleta de la textura void setPalette(size_t palette); // Cambia la paleta de la textura
@@ -76,8 +76,8 @@ class Texture {
// --- Métodos internos --- // --- Métodos internos ---
auto loadSurface(const std::string& file_path) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif auto loadSurface(const std::string& file_path) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
void flipSurface(); // Vuelca la surface en la textura void flipSurface(); // Vuelca la surface en la textura
static auto loadPaletteFromFile(const std::string& file_path, bool quiet = false) -> Palette; // Carga una paleta desde un fichero static auto loadPaletteFromFile(const std::string& file_path) -> Palette; // Carga una paleta desde un fichero
void unloadTexture(); // Libera la memoria de la textura void unloadTexture(); // Libera la memoria de la textura
void unloadSurface(); // Libera la surface actual void unloadSurface(); // Libera la surface actual
static auto readPalFile(const std::string& file_path, bool quiet = false) -> Palette; // Carga una paleta desde un archivo .pal static auto readPalFile(const std::string& file_path) -> Palette; // Carga una paleta desde un archivo .pal
}; };

View File

@@ -1,85 +0,0 @@
#pragma once
#include <iostream>
#include <string>
namespace Logger {
// Colores ANSI
inline constexpr const char* RESET = "\033[0m";
inline constexpr const char* RED = "\033[31m";
inline constexpr const char* GREEN = "\033[32m";
inline constexpr const char* YELLOW = "\033[33m";
inline constexpr const char* BLUE = "\033[34m";
inline constexpr const char* MAGENTA = "\033[35m";
inline constexpr const char* CYAN = "\033[36m";
inline constexpr const char* WHITE = "\033[37m";
// Ancho total global para alineación
inline constexpr size_t TOTAL_WIDTH = 52;
// Sección
inline void section(const std::string& title, const std::string& color = CYAN) {
std::cout << "\n"
<< color
<< "========================================\n"
<< " " << title << "\n"
<< "========================================"
<< RESET << "\n";
}
// Info
inline void info(const std::string& msg, const std::string& color = WHITE) {
std::cout << " " << color << msg << RESET << "\n";
}
// Put
inline void put(const std::string& msg, const std::string& color = WHITE) {
std::cout << color << msg << RESET << "\n";
}
// Error
inline void error(const std::string& msg) {
std::cout << RED << msg << RESET << "\n";
}
// CR
inline void cr() {
std::cout << "\n";
}
// Dots genérico
inline void dots(const std::string& prefix,
const std::string& middle,
const std::string& suffix,
const std::string& suffix_color = GREEN) {
size_t field_width = TOTAL_WIDTH > (prefix.size() + suffix.size())
? TOTAL_WIDTH - prefix.size() - suffix.size()
: 0;
std::string field_text;
if (middle.size() < field_width) {
field_text = middle + std::string(field_width - middle.size(), '.');
} else {
field_text = middle.substr(0, field_width);
}
std::cout << " " << prefix << field_text
<< suffix_color << suffix << RESET
<< "\n";
}
// Status con true/false, usando dots y sufijos fijos
inline void status(const std::string& name, bool ok) {
// Ambos sufijos tienen 9 caracteres → alineación perfecta
constexpr const char* OK_LABEL = "[ OK ]";
constexpr const char* ERROR_LABEL = "[ ERROR ]";
if (ok) {
dots(" ", name, OK_LABEL, GREEN);
} else {
dots(" ", name, ERROR_LABEL, RED);
}
}
} // namespace Logger