Passant std::cout a SDL_Log

This commit is contained in:
2025-03-27 19:57:30 +01:00
parent c6288918b2
commit 8afca398e9
27 changed files with 588 additions and 764 deletions

View File

@@ -1,11 +1,10 @@
#include "animated_sprite.h" #include "animated_sprite.h"
#include <stddef.h> // Para size_t #include <SDL3/SDL_log.h> // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic... #include <stddef.h> // Para size_t
#include <iostream> // Para cout, cerr #include <fstream> // Para basic_istream, basic_ifstream, basic_ios
#include <sstream> // Para basic_stringstream #include <sstream> // Para basic_stringstream
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para printWithDots
// Carga las animaciones en un vector(Animations) desde un fichero // Carga las animaciones en un vector(Animations) desde un fichero
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path) AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path)
@@ -13,11 +12,11 @@ AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path)
std::ifstream file(file_path); std::ifstream file(file_path);
if (!file) if (!file)
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Animation file loaded: %s", file_path.c_str());
std::vector<std::string> buffer; std::vector<std::string> buffer;
std::string line; std::string line;
@@ -52,7 +51,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const Animation
} }
} }
// Obtiene el indice de la animación a partir del nombre // Obtiene el índice de la animación a partir del nombre
int AnimatedSprite::getIndex(const std::string &name) int AnimatedSprite::getIndex(const std::string &name)
{ {
auto index = -1; auto index = -1;
@@ -65,7 +64,7 @@ int AnimatedSprite::getIndex(const std::string &name)
return index; return index;
} }
} }
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "** Warning: could not find \"%s\" animation", name.c_str());
return -1; return -1;
} }
@@ -169,7 +168,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
// Parsea el fichero para buscar variables y valores // Parsea el fichero para buscar variables y valores
if (line != "[animation]") if (line != "[animation]")
{ {
// Encuentra la posición del caracter '=' // Encuentra la posición del carácter '='
size_t pos = line.find("="); size_t pos = line.find("=");
// Procesa las dos subcadenas // Procesa las dos subcadenas
@@ -182,7 +181,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
else if (key == "frame_height") else if (key == "frame_height")
frame_height = value; frame_height = value;
else else
std::cout << "Warning: unknown parameter " << key << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: unknown parameter %s", key.c_str());
frames_per_row = texture_->getWidth() / frame_width; frames_per_row = texture_->getWidth() / frame_width;
const int w = texture_->getWidth() / frame_width; const int w = texture_->getWidth() / frame_width;
@@ -191,7 +190,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
} }
} }
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación // Si la línea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") if (line == "[animation]")
{ {
Animation animation; Animation animation;
@@ -220,7 +219,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
SDL_FRect rect = {0, 0, frame_width, frame_height}; SDL_FRect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ',')) while (getline(ss, tmp, ','))
{ {
// Comprueba que el tile no sea mayor que el maximo indice permitido // Comprueba que el tile no sea mayor que el máximo índice permitido
const int num_tile = std::stoi(tmp); const int num_tile = std::stoi(tmp);
if (num_tile <= max_tiles) if (num_tile <= max_tiles)
{ {
@@ -230,9 +229,8 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
} }
} }
} }
else else
std::cout << "Warning: unknown parameter " << key << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: unknown parameter %s", key.c_str());
} }
} while (line != "[/animation]"); } while (line != "[/animation]");
@@ -240,7 +238,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
animations_.emplace_back(animation); animations_.emplace_back(animation);
} }
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente // Una vez procesada la línea, aumenta el índice para pasar a la siguiente
index++; index++;
} }

View File

@@ -1,9 +1,9 @@
#include "asset.h" #include "asset.h"
#include <algorithm> // Para find_if, max #include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError
#include <fstream> // Para basic_ostream, operator<<, basic_ifstream, endl #include <algorithm> // Para find_if, max
#include <iostream> // Para cout #include <fstream> // Para basic_ifstream, ifstream
#include <string> // Para allocator, char_traits, string, operator+, oper... #include <string> // Para allocator, string, char_traits, operator+
#include "utils.h" // Para getFileName, printWithDots #include "utils.h" // Para getFileName
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Asset *Asset::asset_ = nullptr; Asset *Asset::asset_ = nullptr;
@@ -48,7 +48,7 @@ std::string Asset::get(const std::string &text) const
} }
else else
{ {
std::cout << "Warning: file " << text << " not found" << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found", text.c_str());
return ""; return "";
} }
} }
@@ -58,12 +58,9 @@ bool Asset::check() const
{ {
bool success = true; bool success = true;
std::cout << "\n** CHECKING FILES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES");
// std::cout << "Executable path is: " << executable_path_ << std::endl; // Comprueba la lista de ficheros clasificándolos por tipo
// std::cout << "Sample filepath: " << file_list_.back().file << std::endl;
// Comprueba la lista de ficheros clasificandolos por tipo
for (int type = 0; type < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type) for (int type = 0; type < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type)
{ {
// Comprueba si hay ficheros de ese tipo // Comprueba si hay ficheros de ese tipo
@@ -80,7 +77,7 @@ bool Asset::check() const
// Si hay ficheros de ese tipo, comprueba si existen // Si hay ficheros de ese tipo, comprueba si existen
if (any) if (any)
{ {
std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> %s FILES", getTypeName(static_cast<AssetType>(type)).c_str());
for (const auto &f : file_list_) for (const auto &f : file_list_)
{ {
@@ -90,12 +87,19 @@ bool Asset::check() const
} }
} }
if (success) if (success)
std::cout << " All files are OK." << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, " All files are OK.");
} }
} }
// Resultado // Resultado
std::cout << (success ? "\n** CHECKING FILES COMPLETED.\n" : "\n** CHECKING FILES FAILED.\n") << std::endl; if (success)
{
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES COMPLETED.\n");
}
else
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES FAILED.\n");
}
return success; return success;
} }
@@ -108,7 +112,9 @@ bool Asset::checkFile(const std::string &path) const
file.close(); file.close();
if (!success) if (!success)
printWithDots("Checking file : ", getFileName(path), "[ ERROR ]"); {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Checking file: %s [ ERROR ]", getFileName(path).c_str());
}
return success; return success;
} }
@@ -120,43 +126,24 @@ std::string Asset::getTypeName(AssetType type) const
{ {
case AssetType::BITMAP: case AssetType::BITMAP:
return "BITMAP"; return "BITMAP";
break;
case AssetType::MUSIC: case AssetType::MUSIC:
return "MUSIC"; return "MUSIC";
break;
case AssetType::SOUND: case AssetType::SOUND:
return "SOUND"; return "SOUND";
break;
case AssetType::FONT: case AssetType::FONT:
return "FONT"; return "FONT";
break;
case AssetType::LANG: case AssetType::LANG:
return "LANG"; return "LANG";
break;
case AssetType::DATA: case AssetType::DATA:
return "DATA"; return "DATA";
break;
case AssetType::ANIMATION: case AssetType::ANIMATION:
return "ANIMATION"; return "ANIMATION";
break;
case AssetType::PALETTE: case AssetType::PALETTE:
return "PALETTE"; return "PALETTE";
break;
case AssetType::ITEM: case AssetType::ITEM:
return "ITEM"; return "ITEM";
break;
default: default:
return "ERROR"; return "ERROR";
break;
} }
} }

View File

@@ -321,7 +321,7 @@ int BalloonManager::destroyAllBalloons()
balloon_deploy_counter_ = 300; balloon_deploy_counter_ = 300;
JA_PlaySound(Resource::get()->getSound("power_ball_explosion.wav")); JA_PlaySound(Resource::get()->getSound("power_ball_explosion.wav"));
Screen::get()->flash(flash_color, 3); Screen::get()->flash(FLASH_COLOR, 3);
Screen::get()->shake(); Screen::get()->shake();
return score; return score;

View File

@@ -46,7 +46,7 @@ Credits::Credits()
section::name = section::Name::CREDITS; section::name = section::Name::CREDITS;
balloon_manager_->setPlayArea(play_area_); balloon_manager_->setPlayArea(play_area_);
fade_in_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_in_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b);
fade_in_->setType(FadeType::FULLSCREEN); fade_in_->setType(FadeType::FULLSCREEN);
fade_in_->setPostDuration(50); fade_in_->setPostDuration(50);
fade_in_->setMode(FadeMode::IN); fade_in_->setMode(FadeMode::IN);
@@ -185,46 +185,46 @@ void Credits::fillTextTexture()
int y = (param.game.height - TEXTS_HEIGHT) / 2; int y = (param.game.height - TEXTS_HEIGHT) / 2;
y = 0; y = 0;
text->setPalette(1); text->setPalette(1);
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text->setPalette(0); text->setPalette(0);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
text->setPalette(1); text->setPalette(1);
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text->setPalette(0); text->setPalette(0);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
text->setPalette(1); text->setPalette(1);
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text->setPalette(0); text->setPalette(0);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
text->setPalette(1); text->setPalette(1);
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text->setPalette(0); text->setPalette(0);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_POST_TITLE; y += SPACE_POST_TITLE;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
// Mini logo // Mini logo
y += SPACE_PRE_TITLE; y += SPACE_PRE_TITLE;
mini_logo_rect_src_.y = y; mini_logo_rect_src_.y = y;
auto mini_logo_sprite = std::make_unique<Sprite>(Resource::get()->getTexture("logo_jailgames_mini.png")); auto mini_logo_sprite = std::make_unique<Sprite>(Resource::get()->getTexture("logo_jailgames_mini.png"));
mini_logo_sprite->setPosition(1 + param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, 1 + y); mini_logo_sprite->setPosition(1 + param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, 1 + y);
Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(shdw_txt_color.r, shdw_txt_color.g, shdw_txt_color.b); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(SHADOW_TEXT_COLOR.r, SHADOW_TEXT_COLOR.g, SHADOW_TEXT_COLOR.b);
mini_logo_sprite->render(); mini_logo_sprite->render();
mini_logo_sprite->setPosition(param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, y); mini_logo_sprite->setPosition(param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, y);
@@ -233,7 +233,7 @@ void Credits::fillTextTexture()
// Texto con el copyright // Texto con el copyright
y += mini_logo_sprite->getHeight() + 3; y += mini_logo_sprite->getHeight() + 3;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXT_COPYRIGHT, 1, no_color, 1, shdw_txt_color); text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXT_COPYRIGHT, 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
// Resetea el renderizador // Resetea el renderizador
SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr);

View File

@@ -1,15 +1,11 @@
// IWYU pragma: no_include <bits/chrono.h> // IWYU pragma: no_include <bits/chrono.h>
#include "director.h" #include "director.h"
#include <SDL3/SDL_audio.h> // Para SDL_AudioFormat #include <SDL3/SDL_audio.h> // Para SDL_AudioFormat
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_error.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton #include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
#include <SDL3/SDL_hints.h> // Para SDL_SetHint, SDL_HINT_RENDER_DRIVER #include <SDL3/SDL_init.h> // Para SDL_Init, SDL_Quit, SDL_INIT_AUDIO
#include <SDL3/SDL_init.h> // Para SDL_Init, SDL_Quit, SDL_INIT_VIDEO #include <SDL3/SDL_log.h> // Para SDL_Log, SDL_LogCategory, SDL_LogE...
#include <SDL3/SDL_log.h> // Para SDL_Log
#include <SDL3/SDL_mouse.h> // Para SDL_HideCursor
#include <SDL3/SDL_scancode.h> // Para SDL_Scancode #include <SDL3/SDL_scancode.h> // Para SDL_Scancode
#include <SDL3/SDL_stdinc.h> // Para SDL_free, SDL_PRIu32, Uint32
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG #include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <stdio.h> // Para printf, perror #include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU #include <sys/stat.h> // Para mkdir, stat, S_IRWXU
@@ -17,10 +13,9 @@
#include <algorithm> // Para min #include <algorithm> // Para min
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand #include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
#include <ctime> // Para time #include <ctime> // Para time
#include <iostream> // Para basic_ostream, operator<<, cout, endl
#include <memory> // Para make_unique, unique_ptr #include <memory> // Para make_unique, unique_ptr
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para operator+, char_traits, allocator #include <string> // Para operator+, allocator, char_traits
#include <vector> // Para vector #include <vector> // Para vector
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "credits.h" // Para Credits #include "credits.h" // Para Credits
@@ -35,8 +30,8 @@
#include "manage_hiscore_table.h" // Para ManageHiScoreTable #include "manage_hiscore_table.h" // Para ManageHiScoreTable
#include "notifier.h" // Para Notifier #include "notifier.h" // Para Notifier
#include "on_screen_help.h" // Para OnScreenHelp #include "on_screen_help.h" // Para OnScreenHelp
#include "options.h" // Para Options, options, GamepadOptions #include "options.h" // Para GamepadOptions, Options, options
#include "param.h" // Para Param, ParamGame, param, loadParam... #include "param.h" // Para loadParamsFromFile
#include "resource.h" // Para Resource #include "resource.h" // Para Resource
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "section.h" // Para Name, Options, name, options #include "section.h" // Para Name, Options, name, options
@@ -61,13 +56,7 @@ Director::Director(int argc, const char *argv[])
section::attract_mode = section::AttractMode::TITLE_TO_DEMO; section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
#endif #endif
#ifndef VERBOSE SDL_Log("Game start");
// Deshabilita todos los std::cout
std::ostream null_stream(nullptr);
orig_buf = std::cout.rdbuf(null_stream.rdbuf());
#endif
std::cout << "Game start" << std::endl;
// 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)));
@@ -85,7 +74,7 @@ Director::Director(int argc, const char *argv[])
Director::~Director() Director::~Director()
{ {
close(); close();
std::cout << "\nBye!" << std::endl; SDL_Log("\nBye!");
} }
// Inicializa todo // Inicializa todo
@@ -694,12 +683,7 @@ int Director::run()
break; break;
} }
std::cout << "\nGame end " << return_code << std::endl; SDL_Log("\nGame end %s", return_code.c_str());
#ifndef VERBOSE
// Habilita de nuevo los std::cout
std::cout.rdbuf(orig_buf);
#endif
return (section::options == section::Options::QUIT_WITH_CONTROLLER) ? 1 : 0; return (section::options == section::Options::QUIT_WITH_CONTROLLER) ? 1 : 0;
} }

View File

@@ -1,25 +1,14 @@
#pragma once #pragma once
#include <SDL3/SDL_render.h> // Para SDL_Renderer #include <string> // Para string
#include <SDL3/SDL_video.h> // Para SDL_Window
#include <string> // Para string
namespace lang namespace lang
{ {
enum class Code : int; enum class Code : int;
} // lines 9-9 } // lines 8-8
// Textos
constexpr char WINDOW_CAPTION[] = "Coffee Crisis Arcade Edition";
class Director class Director
{ {
private: private:
// Objetos y punteros
#ifndef VERBOSE
std::streambuf *orig_buf; // Puntero al buffer de flujo original para restaurar std::cout
#endif
// Variables // Variables
std::string executable_path_; // Path del ejecutable std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos std::string system_folder_; // Carpeta del sistema donde guardar datos

View File

@@ -64,14 +64,14 @@ Game::Game(int player_id, int current_stage, bool demo)
Scoreboard::init(); Scoreboard::init();
scoreboard_ = Scoreboard::get(); scoreboard_ = Scoreboard::get();
fade_in_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_in_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b);
fade_in_->setPreDuration(demo_.enabled ? 80 : 0); fade_in_->setPreDuration(demo_.enabled ? 80 : 0);
fade_in_->setPostDuration(0); fade_in_->setPostDuration(0);
fade_in_->setType(FadeType::RANDOM_SQUARE); fade_in_->setType(FadeType::RANDOM_SQUARE);
fade_in_->setMode(FadeMode::IN); fade_in_->setMode(FadeMode::IN);
fade_in_->activate(); fade_in_->activate();
fade_out_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_out_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b);
fade_out_->setPostDuration(param.fade.post_duration); fade_out_->setPostDuration(param.fade.post_duration);
fade_out_->setType(FadeType::VENETIAN); fade_out_->setType(FadeType::VENETIAN);
@@ -263,7 +263,7 @@ void Game::updateStage()
++Stage::number; ++Stage::number;
JA_PlaySound(Resource::get()->getSound("stage_change.wav")); JA_PlaySound(Resource::get()->getSound("stage_change.wav"));
balloon_manager_->resetBalloonSpeed(); balloon_manager_->resetBalloonSpeed();
screen_->flash(flash_color, 3); screen_->flash(FLASH_COLOR, 3);
screen_->shake(); screen_->shake();
// Escribe el texto por pantalla // Escribe el texto por pantalla
@@ -1691,7 +1691,7 @@ void Game::initDifficultyVars()
{ {
balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]); balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]);
difficulty_score_multiplier_ = 0.5f; difficulty_score_multiplier_ = 0.5f;
scoreboard_->setColor(scoreboard_easy_color); scoreboard_->setColor(SCOREBOARD_EASY_COLOR);
break; break;
} }
@@ -1699,7 +1699,7 @@ void Game::initDifficultyVars()
{ {
balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]); balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]);
difficulty_score_multiplier_ = 1.0f; difficulty_score_multiplier_ = 1.0f;
scoreboard_->setColor(scoreboard_normal_color); scoreboard_->setColor(SCOREBOARD_NORMAL_COLOR);
break; break;
} }
@@ -1707,7 +1707,7 @@ void Game::initDifficultyVars()
{ {
balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[4]); balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[4]);
difficulty_score_multiplier_ = 1.5f; difficulty_score_multiplier_ = 1.5f;
scoreboard_->setColor(scoreboard_hard_color); scoreboard_->setColor(SCOREBOARD_HARD_COLOR);
break; break;
} }

View File

@@ -1,14 +1,11 @@
#include "gif.h" #include "gif.h"
#include <iostream> // Para std::cout #include <SDL3/SDL_log.h> // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo
#include <cstring> // Para memcpy, size_t #include <cstring> // Para memcpy, size_t
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para allocator, char_traits, operator==, basic_string #include <string> // Para char_traits, operator==, basic_string, string
namespace GIF namespace GIF
{ {
// Función inline para reemplazar el macro READ.
// Actualiza el puntero 'buffer' tras copiar 'size' bytes a 'dst'.
inline void readBytes(const uint8_t *&buffer, void *dst, size_t size) inline void readBytes(const uint8_t *&buffer, void *dst, size_t size)
{ {
std::memcpy(dst, buffer, size); std::memcpy(dst, buffer, size);
@@ -17,9 +14,9 @@ namespace GIF
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)
{ {
// Verifica que el code_length tenga un rango razonable.
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);
throw std::runtime_error("Invalid LZW code length"); throw std::runtime_error("Invalid LZW code length");
} }
@@ -33,7 +30,6 @@ namespace GIF
int stop_code = clear_code + 1; int stop_code = clear_code + 1;
int match_len = 0; int match_len = 0;
// Inicializamos el diccionario con el tamaño correspondiente.
dictionary.resize(1 << (code_length + 1)); dictionary.resize(1 << (code_length + 1));
for (dictionary_ind = 0; dictionary_ind < (1 << code_length); dictionary_ind++) for (dictionary_ind = 0; dictionary_ind < (1 << code_length); dictionary_ind++)
{ {
@@ -41,17 +37,16 @@ namespace GIF
dictionary[dictionary_ind].prev = -1; dictionary[dictionary_ind].prev = -1;
dictionary[dictionary_ind].len = 1; dictionary[dictionary_ind].len = 1;
} }
dictionary_ind += 2; // Reservamos espacio para clear y stop codes dictionary_ind += 2;
// Bucle principal: procesar el stream comprimido.
while (input_length > 0) while (input_length > 0)
{ {
int code = 0; int code = 0;
// Lee (code_length + 1) bits para formar el código.
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");
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;
@@ -67,7 +62,6 @@ namespace GIF
if (code == clear_code) if (code == clear_code)
{ {
// Reinicia el diccionario.
code_length = reset_code_length; code_length = reset_code_length;
dictionary.resize(1 << (code_length + 1)); dictionary.resize(1 << (code_length + 1));
for (dictionary_ind = 0; dictionary_ind < (1 << code_length); dictionary_ind++) for (dictionary_ind = 0; dictionary_ind < (1 << code_length); dictionary_ind++)
@@ -89,8 +83,7 @@ namespace GIF
{ {
if (code > dictionary_ind) if (code > dictionary_ind)
{ {
std::cerr << "code = " << std::hex << code SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "LZW error: code (%d) exceeds dictionary_ind (%d)", code, dictionary_ind);
<< ", but dictionary_ind = " << dictionary_ind << std::endl;
throw std::runtime_error("LZW error: code exceeds dictionary_ind."); throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
} }
@@ -122,23 +115,20 @@ namespace GIF
prev = code; prev = code;
// Verifica que 'code' sea un índice válido antes de usarlo.
if (code < 0 || static_cast<size_t>(code) >= dictionary.size()) if (code < 0 || static_cast<size_t>(code) >= dictionary.size())
{ {
std::cerr << "Invalid LZW code " << code SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Invalid LZW code %d, dictionary size %lu", code, static_cast<unsigned long>(dictionary.size()));
<< ", dictionary size " << dictionary.size() << std::endl;
throw std::runtime_error("LZW error: invalid code encountered"); throw std::runtime_error("LZW error: invalid code encountered");
} }
int curCode = code; // Variable temporal para recorrer la cadena. int curCode = code;
match_len = dictionary[curCode].len; match_len = dictionary[curCode].len;
while (curCode != -1) while (curCode != -1)
{ {
// Se asume que dictionary[curCode].len > 0.
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)
{ {
std::cerr << "Internal error; self-reference detected." << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Internal error; self-reference detected.");
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;
@@ -165,7 +155,6 @@ namespace GIF
std::vector<uint8_t> Gif::processImageDescriptor(const uint8_t *&buffer, const std::vector<RGB> &gct, int resolution_bits) std::vector<uint8_t> Gif::processImageDescriptor(const uint8_t *&buffer, const std::vector<RGB> &gct, int resolution_bits)
{ {
ImageDescriptor image_descriptor; ImageDescriptor image_descriptor;
// Lee 9 bytes para el image descriptor.
readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor)); readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor));
uint8_t lzw_code_size; uint8_t lzw_code_size;
@@ -208,26 +197,27 @@ namespace GIF
std::vector<uint8_t> Gif::processGifStream(const uint8_t *buffer, uint16_t &w, uint16_t &h) std::vector<uint8_t> Gif::processGifStream(const uint8_t *buffer, uint16_t &w, uint16_t &h)
{ {
// Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a")
uint8_t header[6]; uint8_t header[6];
std::memcpy(header, buffer, 6); std::memcpy(header, buffer, 6);
buffer += 6; buffer += 6;
// Opcional: Validar header
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());
throw std::runtime_error("Formato de archivo GIF inválido."); throw std::runtime_error("Formato de archivo GIF inválido.");
} }
// Leer el Screen Descriptor (7 bytes, empaquetado sin padding) SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "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));
// Asigna ancho y alto
w = screen_descriptor.width; w = screen_descriptor.width;
h = screen_descriptor.height; h = screen_descriptor.height;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "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)
@@ -238,22 +228,18 @@ namespace GIF
buffer += 3 * global_color_table_size; buffer += 3 * global_color_table_size;
} }
// Supongamos que 'buffer' es el puntero actual y TRAILER es 0x3B
uint8_t block_type = *buffer++; uint8_t block_type = *buffer++;
while (block_type != TRAILER) while (block_type != TRAILER)
{ {
if (block_type == EXTENSION_INTRODUCER) // 0x21 if (block_type == EXTENSION_INTRODUCER)
{ {
// Se lee la etiqueta de extensión, la cual indica el tipo de extensión.
uint8_t extension_label = *buffer++; uint8_t extension_label = *buffer++;
switch (extension_label) switch (extension_label)
{ {
case GRAPHIC_CONTROL: // 0xF9 case GRAPHIC_CONTROL:
{ {
// Procesar Graphic Control Extension: uint8_t blockSize = *buffer++;
uint8_t blockSize = *buffer++; // Normalmente, blockSize == 4 buffer += blockSize;
buffer += blockSize; // Saltamos los 4 bytes del bloque fijo
// Saltar los sub-bloques
uint8_t subBlockSize = *buffer++; uint8_t subBlockSize = *buffer++;
while (subBlockSize != 0) while (subBlockSize != 0)
{ {
@@ -262,11 +248,10 @@ namespace GIF
} }
break; break;
} }
case APPLICATION_EXTENSION: // 0xFF case APPLICATION_EXTENSION:
case COMMENT_EXTENSION: // 0xFE case COMMENT_EXTENSION:
case PLAINTEXT_EXTENSION: // 0x01 case PLAINTEXT_EXTENSION:
{ {
// Para estas extensiones, saltamos el bloque fijo y los sub-bloques.
uint8_t blockSize = *buffer++; uint8_t blockSize = *buffer++;
buffer += blockSize; buffer += blockSize;
uint8_t subBlockSize = *buffer++; uint8_t subBlockSize = *buffer++;
@@ -279,7 +264,6 @@ namespace GIF
} }
default: default:
{ {
// Si la etiqueta de extensión es desconocida, saltarla también:
uint8_t blockSize = *buffer++; uint8_t blockSize = *buffer++;
buffer += blockSize; buffer += blockSize;
uint8_t subBlockSize = *buffer++; uint8_t subBlockSize = *buffer++;
@@ -294,17 +278,18 @@ namespace GIF
} }
else if (block_type == IMAGE_DESCRIPTOR) else if (block_type == IMAGE_DESCRIPTOR)
{ {
// Procesar el Image Descriptor y retornar los datos de imagen SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Procesando Image Descriptor...");
return processImageDescriptor(buffer, global_color_table, color_resolution_bits); return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
} }
else else
{ {
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unrecognized block type: 0x%X", block_type);
return std::vector<uint8_t>{}; return std::vector<uint8_t>{};
} }
block_type = *buffer++; block_type = *buffer++;
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "GIF procesado correctamente.");
return std::vector<uint8_t>{}; return std::vector<uint8_t>{};
} }

View File

@@ -1,7 +1,7 @@
#include "global_events.h" #include "global_events.h"
#include <iostream> // Para char_traits, basic_ostream, operator<<, cout, endl #include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory
#include "mouse.h" // Para handleEvent #include "mouse.h" // Para handleEvent
#include "section.h" // Para Name, Options, name, options #include "section.h" // Para Name, Options, name, options
namespace globalEvents namespace globalEvents
{ {
@@ -14,16 +14,20 @@ namespace globalEvents
section::name = section::Name::QUIT; section::name = section::Name::QUIT;
section::options = section::Options::QUIT_FROM_EVENT; section::options = section::Options::QUIT_FROM_EVENT;
return; return;
case SDL_EVENT_RENDER_DEVICE_RESET: case SDL_EVENT_RENDER_DEVICE_RESET:
case SDL_EVENT_RENDER_TARGETS_RESET: case SDL_EVENT_RENDER_TARGETS_RESET:
std::cout << "SDL_RENDER_TARGETS_RESET" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "SDL_RENDER_TARGETS_RESET");
break; break;
case SDL_EVENT_WINDOW_RESIZED: case SDL_EVENT_WINDOW_RESIZED:
std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "SDL_WINDOWEVENT_SIZE_CHANGED");
break; break;
default: default:
break; break;
} }
Mouse::handleEvent(event); Mouse::handleEvent(event);
} }
} }

View File

@@ -117,7 +117,7 @@ void HiScoreTable::render()
Screen::get()->start(); Screen::get()->start();
// Limpia la pantalla // Limpia la pantalla
Screen::get()->clean(bg_color); Screen::get()->clean(BG_COLOR);
// Pinta el fondo // Pinta el fondo
background_->render(); background_->render();
@@ -233,7 +233,7 @@ void HiScoreTable::createSprites()
// Crea los sprites para las entradas en la tabla de puntuaciones // Crea los sprites para las entradas en la tabla de puntuaciones
const int animation = rand() % 4; const int animation = rand() % 4;
const std::string sample_line(ENTRY_LENGHT + 3, ' '); const std::string sample_line(ENTRY_LENGHT + 3, ' ');
auto sample_entry = std::make_unique<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, orange_color, 1, shdw_txt_color)); auto sample_entry = std::make_unique<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR));
const auto entry_width = sample_entry->getWidth(); const auto entry_width = sample_entry->getWidth();
for (int i = 0; i < MAX_NAMES; ++i) for (int i = 0; i < MAX_NAMES; ++i)
{ {
@@ -248,7 +248,7 @@ void HiScoreTable::createSprites()
} }
const auto line = table_position + options.game.hi_score_table.at(i).name + dots + score + one_cc; const auto line = table_position + options.game.hi_score_table.at(i).name + dots + score + one_cc;
entry_names_.emplace_back(std::make_shared<PathSprite>(entry_text->writeDXToTexture(TEXT_SHADOW, line, 1, orange_color, 1, shdw_txt_color))); entry_names_.emplace_back(std::make_shared<PathSprite>(entry_text->writeDXToTexture(TEXT_SHADOW, line, 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR)));
const int default_pos_x = (backbuffer_width - entry_width) / 2; const int default_pos_x = (backbuffer_width - entry_width) / 2;
const int pos_x = (i < 9) ? default_pos_x : default_pos_x - entry_text->getCharacterSize(); const int pos_x = (i < 9) ? default_pos_x : default_pos_x - entry_text->getCharacterSize();
const int pos_y = (i * space_between_lines) + first_line + space_between_header; const int pos_y = (i * space_between_lines) + first_line + space_between_header;
@@ -324,7 +324,7 @@ void HiScoreTable::updateSprites()
// Inicializa el fade // Inicializa el fade
void HiScoreTable::initFade() void HiScoreTable::initFade()
{ {
fade_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b);
fade_->setType(FadeType::RANDOM_SQUARE); fade_->setType(FadeType::RANDOM_SQUARE);
fade_->setPostDuration(param.fade.post_duration); fade_->setPostDuration(param.fade.post_duration);
fade_->setMode(fade_mode_); fade_->setMode(fade_mode_);
@@ -346,7 +346,7 @@ void HiScoreTable::initBackground()
background_->setTransition(0.0f); background_->setTransition(0.0f);
background_->setSunProgression(1.0f); background_->setSunProgression(1.0f);
background_->setMoonProgression(0.0f); background_->setMoonProgression(0.0f);
background_fade_color_ = green_sky_color; background_fade_color_ = GREEN_SKY_COLOR;
break; break;
} }
@@ -356,7 +356,7 @@ void HiScoreTable::initBackground()
background_->setTransition(0.0f); background_->setTransition(0.0f);
background_->setSunProgression(0.65f); background_->setSunProgression(0.65f);
background_->setMoonProgression(0.0f); background_->setMoonProgression(0.0f);
background_fade_color_ = pink_sky_color; background_fade_color_ = PINK_SKY_COLOR;
break; break;
} }
@@ -366,7 +366,7 @@ void HiScoreTable::initBackground()
background_->setTransition(0.0f); background_->setTransition(0.0f);
background_->setSunProgression(0.0f); background_->setSunProgression(0.0f);
background_->setMoonProgression(0.0f); background_->setMoonProgression(0.0f);
background_fade_color_ = blue_sky_color; background_fade_color_ = BLUE_SKY_COLOR;
break; break;
} }

View File

@@ -1,9 +1,9 @@
#include "input.h" #include "input.h"
#include <SDL3/SDL.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_init.h> // Para SDL_INIT_GAMEPAD, SDL_InitSubSystem #include <SDL3/SDL_init.h> // Para SDL_INIT_GAMEPAD, SDL_InitSubSystem
#include <SDL3/SDL_keyboard.h> // Para SDL_GetKeyboardState #include <SDL3/SDL_keyboard.h> // Para SDL_GetKeyboardState
#include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_Log...
#include <algorithm> // Para find #include <algorithm> // Para find
#include <iostream> // Para basic_ostream, operator<<, basic_ostr...
#include <iterator> // Para distance #include <iterator> // Para distance
#include <unordered_map> // Para unordered_map, operator==, _Node_cons... #include <unordered_map> // Para unordered_map, operator==, _Node_cons...
#include <utility> // Para pair #include <utility> // Para pair
@@ -226,7 +226,7 @@ bool Input::discoverGameControllers()
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0)
{ {
std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: could not load %s file: %s", game_controller_db_path_.c_str(), SDL_GetError());
} }
SDL_GetJoysticks(&num_joysticks_); SDL_GetJoysticks(&num_joysticks_);
@@ -244,15 +244,15 @@ bool Input::discoverGameControllers()
} }
} }
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** LOOKING FOR GAME CONTROLLERS");
if (num_joysticks_ != num_gamepads_) if (num_joysticks_ != num_gamepads_)
{ {
std::cout << "Joysticks found: " << num_joysticks_ << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Joysticks found: %d", num_joysticks_);
std::cout << "Gamepads found : " << num_gamepads_ << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found : %d", num_gamepads_);
} }
else else
{ {
std::cout << "Gamepads found: " << num_gamepads_ << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found: %d", num_gamepads_);
} }
if (num_gamepads_ > 0) if (num_gamepads_ > 0)
@@ -267,19 +267,19 @@ bool Input::discoverGameControllers()
{ {
connected_controllers_.push_back(pad); connected_controllers_.push_back(pad);
const std::string name = SDL_GetGamepadNameForID(i); const std::string name = SDL_GetGamepadNameForID(i);
std::cout << "#" << i << ": " << name << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str());
controller_names_.push_back(name); controller_names_.push_back(name);
} }
else else
{ {
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GetError() = %s", SDL_GetError());
} }
} }
SDL_SetGamepadEventsEnabled(true); SDL_SetGamepadEventsEnabled(true);
} }
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** FINISHED LOOKING FOR GAME CONTROLLERS");
return found; return found;
} }
@@ -321,12 +321,12 @@ void Input::printBindings(InputDeviceToUse device, int controller_index) const
} }
// Muestra el nombre del mando // Muestra el nombre del mando
std::cout << "\n" + controller_names_.at(controller_index) << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n%s", controller_names_.at(controller_index).c_str());
// Muestra los botones asignados // Muestra los botones asignados
for (auto bi : button_inputs_) for (auto bi : button_inputs_)
{ {
std::cout << to_string(bi) << " : " << controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s : %d", to_string(bi).c_str(), controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button);
} }
} }
} }

View File

@@ -38,7 +38,7 @@ Instructions::Instructions()
view_ = param.game.game_area.rect; view_ = param.game.game_area.rect;
// Inicializa objetos // Inicializa objetos
fade_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b);
fade_->setType(FadeType::FULLSCREEN); fade_->setType(FadeType::FULLSCREEN);
fade_->setPostDuration(param.fade.post_duration); fade_->setPostDuration(param.fade.post_duration);
fade_->setMode(FadeMode::IN); fade_->setMode(FadeMode::IN);
@@ -147,24 +147,24 @@ void Instructions::fillTexture()
const int anchor_item = (param.game.width - (lenght + desp_x)) / 2; const int anchor_item = (param.game.width - (lenght + desp_x)) / 2;
// Escribe el texto de las instrucciones // Escribe el texto de las instrucciones
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, first_line, lang::getText(11), 1, orange_color, 1, shdw_txt_color); text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, first_line, lang::getText(11), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR);
const int anchor1 = first_line + space_post_header; const int anchor1 = first_line + space_post_header;
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 0, lang::getText(12), 1, no_color, 1, shdw_txt_color); text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 0, lang::getText(12), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 1, lang::getText(13), 1, no_color, 1, shdw_txt_color); text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 1, lang::getText(13), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 2, lang::getText(14), 1, no_color, 1, shdw_txt_color); text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 2, lang::getText(14), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 3, lang::getText(15), 1, no_color, 1, shdw_txt_color); text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 3, lang::getText(15), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR);
// Escribe el texto de los objetos y sus puntos // Escribe el texto de los objetos y sus puntos
const int anchor2 = anchor1 + space_pre_header + space_new_paragraph + space_between_lines * 3; const int anchor2 = anchor1 + space_pre_header + space_new_paragraph + space_between_lines * 3;
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor2, lang::getText(16), 1, orange_color, 1, shdw_txt_color); text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor2, lang::getText(16), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR);
const int anchor3 = anchor2 + space_post_header; const int anchor3 = anchor2 + space_post_header;
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 0, lang::getText(17), shdw_txt_color); text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 0, lang::getText(17), SHADOW_TEXT_COLOR);
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 1, lang::getText(18), shdw_txt_color); text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 1, lang::getText(18), SHADOW_TEXT_COLOR);
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 2, lang::getText(19), shdw_txt_color); text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 2, lang::getText(19), SHADOW_TEXT_COLOR);
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 3, lang::getText(20), shdw_txt_color); text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 3, lang::getText(20), SHADOW_TEXT_COLOR);
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 4, lang::getText(21), shdw_txt_color); text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 4, lang::getText(21), SHADOW_TEXT_COLOR);
// Deja el renderizador como estaba // Deja el renderizador como estaba
SDL_SetRenderTarget(renderer_, temp); SDL_SetRenderTarget(renderer_, temp);
@@ -242,7 +242,7 @@ void Instructions::render()
Screen::get()->start(); Screen::get()->start();
// Limpia la pantalla // Limpia la pantalla
Screen::get()->clean(bg_color); Screen::get()->clean(BG_COLOR);
// Dibuja el mosacico de fondo // Dibuja el mosacico de fondo
tiled_bg_->render(); tiled_bg_->render();

View File

@@ -260,7 +260,7 @@ void Intro::render()
Screen::get()->start(); Screen::get()->start();
// Limpia la pantalla // Limpia la pantalla
Screen::get()->clean(bg_color); Screen::get()->clean(BG_COLOR);
// Dibuja el fondo // Dibuja el fondo
tiled_bg_->render(); tiled_bg_->render();

View File

@@ -1,49 +1,53 @@
#ifndef JA_USESDLMIXER #ifndef JA_USESDLMIXER
#include "jail_audio.h" #include "jail_audio.h"
#include "stb_vorbis.c" #include <SDL3/SDL_iostream.h> // Para SDL_IOFromMem
#include <SDL3/SDL.h> #include <SDL3/SDL_log.h> // Para SDL_Log, SDL_SetLogPriority, SDL_LogC...
#include <stdio.h> #include <SDL3/SDL_timer.h> // Para SDL_GetTicks, SDL_AddTimer, SDL_Remov...
#include <stdint.h> // Para uint32_t, uint8_t
#include <stdio.h> // Para NULL, fseek, printf, fclose, fopen
#include <stdlib.h> // Para free, malloc
#include "stb_vorbis.c" // Para stb_vorbis_decode_memory
#define JA_MAX_SIMULTANEOUS_CHANNELS 5 #define JA_MAX_SIMULTANEOUS_CHANNELS 20
struct JA_Sound_t struct JA_Sound_t
{ {
SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 }; SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length { 0 }; Uint32 length{0};
Uint8 *buffer { NULL }; Uint8 *buffer{NULL};
}; };
struct JA_Channel_t struct JA_Channel_t
{ {
JA_Sound_t *sound { nullptr }; JA_Sound_t *sound{nullptr};
int pos { 0 }; int pos{0};
int times { 0 }; int times{0};
SDL_AudioStream *stream { nullptr }; SDL_AudioStream *stream{nullptr};
JA_Channel_state state { JA_CHANNEL_FREE }; JA_Channel_state state{JA_CHANNEL_FREE};
}; };
struct JA_Music_t struct JA_Music_t
{ {
SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 }; SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length { 0 }; Uint32 length{0};
Uint8 *buffer { nullptr }; Uint8 *buffer{nullptr};
int pos { 0 }; int pos{0};
int times { 0 }; int times{0};
SDL_AudioStream *stream { nullptr }; SDL_AudioStream *stream{nullptr};
JA_Music_state state { JA_MUSIC_INVALID }; JA_Music_state state{JA_MUSIC_INVALID};
}; };
JA_Music_t *current_music { nullptr }; JA_Music_t *current_music{nullptr};
JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
SDL_AudioSpec JA_audioSpec { SDL_AUDIO_S16, 2, 48000 }; SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000};
float JA_musicVolume { 1.0f }; float JA_musicVolume{1.0f};
float JA_soundVolume { 0.5f }; float JA_soundVolume{0.5f};
bool JA_musicEnabled { true }; bool JA_musicEnabled{true};
bool JA_soundEnabled { true }; bool JA_soundEnabled{true};
SDL_AudioDeviceID sdlAudioDevice { 0 }; SDL_AudioDeviceID sdlAudioDevice{0};
SDL_TimerID JA_timerID { 0 }; SDL_TimerID JA_timerID{0};
bool fading = false; bool fading = false;
int fade_start_time; int fade_start_time;
@@ -92,13 +96,17 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval)
{ {
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING)
{ {
if (fading) { if (fading)
{
int time = SDL_GetTicks(); int time = SDL_GetTicks();
if (time > (fade_start_time+fade_duration)) { if (time > (fade_start_time + fade_duration))
{
fading = false; fading = false;
JA_StopMusic(); JA_StopMusic();
return 30; return 30;
} else { }
else
{
const int time_passed = time - fade_start_time; const int time_passed = time - fade_start_time;
const float percent = (float)time_passed / (float)fade_duration; const float percent = (float)time_passed / (float)fade_duration;
SDL_SetAudioStreamGain(current_music->stream, 1.0 - percent); SDL_SetAudioStreamGain(current_music->stream, 1.0 - percent);
@@ -107,34 +115,38 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval)
if (current_music->times != 0) if (current_music->times != 0)
{ {
if (SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length/2)) { if (SDL_GetAudioStreamAvailable(current_music->stream) < static_cast<int>(current_music->length / 2))
{
SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length); SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length);
} }
if (current_music->times>0) current_music->times--; if (current_music->times > 0)
current_music->times--;
} }
else else
{ {
if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic(); if (SDL_GetAudioStreamAvailable(current_music->stream) == 0)
JA_StopMusic();
} }
} }
if (JA_soundEnabled) if (JA_soundEnabled)
{ {
for (int i=0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i)
if (channels[i].state == JA_CHANNEL_PLAYING) if (channels[i].state == JA_CHANNEL_PLAYING)
{ {
if (channels[i].times != 0) if (channels[i].times != 0)
{ {
if (SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length/2)) if (SDL_GetAudioStreamAvailable(channels[i].stream) < static_cast<int>(channels[i].sound->length / 2))
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length); SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length);
if (channels[i].times>0) channels[i].times--; if (channels[i].times > 0)
channels[i].times--;
} }
} }
else else
{ {
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i); if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0)
JA_StopChannel(i);
} }
} }
return 30; return 30;
@@ -142,28 +154,31 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval)
void JA_Init(const int freq, const SDL_AudioFormat format, const int channels) void JA_Init(const int freq, const SDL_AudioFormat format, const int channels)
{ {
#ifdef DEBUG #ifdef DEBUG
SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG); SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
#endif #endif
SDL_Log("Iniciant JailAudio..."); SDL_Log("Iniciant JailAudio...");
JA_audioSpec = {format, channels, freq }; JA_audioSpec = {format, channels, freq};
if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); if (!sdlAudioDevice)
SDL_CloseAudioDevice(sdlAudioDevice);
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec); sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
SDL_Log( (sdlAudioDevice==0) ? "Failed to initialize SDL audio!\n" : "OK!\n"); SDL_Log((sdlAudioDevice == 0) ? "Failed to initialize SDL audio!\n" : "OK!\n");
//SDL_PauseAudioDevice(sdlAudioDevice); // SDL_PauseAudioDevice(sdlAudioDevice);
JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr); JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr);
} }
void JA_Quit() void JA_Quit()
{ {
if (JA_timerID) SDL_RemoveTimer(JA_timerID); if (JA_timerID)
SDL_RemoveTimer(JA_timerID);
if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); if (!sdlAudioDevice)
SDL_CloseAudioDevice(sdlAudioDevice);
sdlAudioDevice = 0; sdlAudioDevice = 0;
} }
JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length) JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length)
{ {
JA_Music_t *music = new JA_Music_t(); JA_Music_t *music = new JA_Music_t();
@@ -174,7 +189,7 @@ JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length)
music->spec.channels = chan; music->spec.channels = chan;
music->spec.freq = samplerate; music->spec.freq = samplerate;
music->spec.format = SDL_AUDIO_S16; music->spec.format = SDL_AUDIO_S16;
music->buffer = (Uint8*)SDL_malloc(music->length); music->buffer = (Uint8 *)SDL_malloc(music->length);
SDL_memcpy(music->buffer, output, music->length); SDL_memcpy(music->buffer, output, music->length);
free(output); free(output);
music->pos = 0; music->pos = 0;
@@ -183,15 +198,16 @@ JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length)
return music; return music;
} }
JA_Music_t *JA_LoadMusic(const char* filename) JA_Music_t *JA_LoadMusic(const char *filename)
{ {
// [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid. // [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid.
FILE *f = fopen(filename, "rb"); FILE *f = fopen(filename, "rb");
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
long fsize = ftell(f); long fsize = ftell(f);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8*)malloc(fsize + 1); Uint8 *buffer = (Uint8 *)malloc(fsize + 1);
if (fread(buffer, fsize, 1, f)!=1) return NULL; if (fread(buffer, fsize, 1, f) != 1)
return NULL;
fclose(f); fclose(f);
JA_Music_t *music = JA_LoadMusic(buffer, fsize); JA_Music_t *music = JA_LoadMusic(buffer, fsize);
@@ -203,7 +219,8 @@ JA_Music_t *JA_LoadMusic(const char* filename)
void JA_PlayMusic(JA_Music_t *music, const int loop) void JA_PlayMusic(JA_Music_t *music, const int loop)
{ {
if (!JA_musicEnabled) return; if (!JA_musicEnabled)
return;
JA_StopMusic(); JA_StopMusic();
@@ -213,48 +230,58 @@ void JA_PlayMusic(JA_Music_t *music, const int loop)
current_music->times = loop; current_music->times = loop;
current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec); current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec);
if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n"); if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length))
printf("[ERROR] SDL_PutAudioStreamData failed!\n");
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n"); if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream))
//SDL_ResumeAudioStreamDevice(current_music->stream); printf("[ERROR] SDL_BindAudioStream failed!\n");
// SDL_ResumeAudioStreamDevice(current_music->stream);
} }
void JA_PauseMusic() void JA_PauseMusic()
{ {
if (!JA_musicEnabled) return; if (!JA_musicEnabled)
if (!current_music || current_music->state == JA_MUSIC_INVALID) return; return;
if (!current_music || current_music->state == JA_MUSIC_INVALID)
return;
current_music->state = JA_MUSIC_PAUSED; current_music->state = JA_MUSIC_PAUSED;
//SDL_PauseAudioStreamDevice(current_music->stream); // SDL_PauseAudioStreamDevice(current_music->stream);
SDL_UnbindAudioStream(current_music->stream); SDL_UnbindAudioStream(current_music->stream);
} }
void JA_ResumeMusic() void JA_ResumeMusic()
{ {
if (!JA_musicEnabled) return; if (!JA_musicEnabled)
if (!current_music || current_music->state == JA_MUSIC_INVALID) return; return;
if (!current_music || current_music->state == JA_MUSIC_INVALID)
return;
current_music->state = JA_MUSIC_PLAYING; current_music->state = JA_MUSIC_PLAYING;
//SDL_ResumeAudioStreamDevice(current_music->stream); // SDL_ResumeAudioStreamDevice(current_music->stream);
SDL_BindAudioStream(sdlAudioDevice, current_music->stream); SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
} }
void JA_StopMusic() void JA_StopMusic()
{ {
if (!JA_musicEnabled) return; if (!JA_musicEnabled)
if (!current_music || current_music->state == JA_MUSIC_INVALID) return; return;
if (!current_music || current_music->state == JA_MUSIC_INVALID)
return;
current_music->pos = 0; current_music->pos = 0;
current_music->state = JA_MUSIC_STOPPED; current_music->state = JA_MUSIC_STOPPED;
//SDL_PauseAudioStreamDevice(current_music->stream); // SDL_PauseAudioStreamDevice(current_music->stream);
SDL_DestroyAudioStream(current_music->stream); SDL_DestroyAudioStream(current_music->stream);
current_music->stream = nullptr; current_music->stream = nullptr;
} }
void JA_FadeOutMusic(const int milliseconds) void JA_FadeOutMusic(const int milliseconds)
{ {
if (!JA_musicEnabled) return; if (!JA_musicEnabled)
if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return; return;
if (current_music == NULL || current_music->state == JA_MUSIC_INVALID)
return;
fading = true; fading = true;
fade_start_time = SDL_GetTicks(); fade_start_time = SDL_GetTicks();
@@ -264,51 +291,55 @@ void JA_FadeOutMusic(const int milliseconds)
JA_Music_state JA_GetMusicState() JA_Music_state JA_GetMusicState()
{ {
if (!JA_musicEnabled) return JA_MUSIC_DISABLED; if (!JA_musicEnabled)
if (!current_music) return JA_MUSIC_INVALID; return JA_MUSIC_DISABLED;
if (!current_music)
return JA_MUSIC_INVALID;
return current_music->state; return current_music->state;
} }
void JA_DeleteMusic(JA_Music_t *music) void JA_DeleteMusic(JA_Music_t *music)
{ {
if (current_music == music) current_music = nullptr; if (current_music == music)
current_music = nullptr;
SDL_free(music->buffer); SDL_free(music->buffer);
if (music->stream) SDL_DestroyAudioStream(music->stream); if (music->stream)
SDL_DestroyAudioStream(music->stream);
delete music; delete music;
} }
float JA_SetMusicVolume(float volume) float JA_SetMusicVolume(float volume)
{ {
JA_musicVolume = SDL_clamp( volume, 0.0f, 1.0f ); JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f);
if (current_music) SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); if (current_music)
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
return JA_musicVolume; return JA_musicVolume;
} }
void JA_SetMusicPosition(float value) void JA_SetMusicPosition(float value)
{ {
if (!current_music) return; if (!current_music)
return;
current_music->pos = value * current_music->spec.freq; current_music->pos = value * current_music->spec.freq;
} }
float JA_GetMusicPosition() float JA_GetMusicPosition()
{ {
if (!current_music) return 0; if (!current_music)
return float(current_music->pos)/float(current_music->spec.freq); return 0;
return float(current_music->pos) / float(current_music->spec.freq);
} }
void JA_EnableMusic(const bool value) void JA_EnableMusic(const bool value)
{ {
if ( !value && current_music && (current_music->state==JA_MUSIC_PLAYING) ) JA_StopMusic(); if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING))
JA_StopMusic();
JA_musicEnabled = value; JA_musicEnabled = value;
} }
JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length)
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length)
{ {
JA_Sound_t *sound = new JA_Sound_t(); JA_Sound_t *sound = new JA_Sound_t();
sound->buffer = buffer; sound->buffer = buffer;
@@ -316,15 +347,15 @@ JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length)
return sound; return sound;
} }
JA_Sound_t *JA_LoadSound(uint8_t* buffer, uint32_t size) 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();
SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size),1, &sound->spec, &sound->buffer, &sound->length); SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length);
return sound; return sound;
} }
JA_Sound_t *JA_LoadSound(const char* filename) JA_Sound_t *JA_LoadSound(const char *filename)
{ {
JA_Sound_t *sound = new JA_Sound_t(); JA_Sound_t *sound = new JA_Sound_t();
SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length); SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length);
@@ -334,11 +365,16 @@ JA_Sound_t *JA_LoadSound(const char* filename)
int JA_PlaySound(JA_Sound_t *sound, const int loop) int JA_PlaySound(JA_Sound_t *sound, const int loop)
{ {
if (!JA_soundEnabled) return -1; if (!JA_soundEnabled)
return -1;
int channel = 0; int channel = 0;
while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; } while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE)
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) channel = 0; {
channel++;
}
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS)
channel = 0;
JA_StopChannel(channel); JA_StopChannel(channel);
channels[channel].sound = sound; channels[channel].sound = sound;
@@ -355,9 +391,11 @@ int JA_PlaySound(JA_Sound_t *sound, const int loop)
int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop) int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop)
{ {
if (!JA_soundEnabled) return -1; if (!JA_soundEnabled)
return -1;
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1; if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS)
return -1;
JA_StopChannel(channel); JA_StopChannel(channel);
channels[channel].sound = sound; channels[channel].sound = sound;
@@ -374,8 +412,10 @@ int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop)
void JA_DeleteSound(JA_Sound_t *sound) void JA_DeleteSound(JA_Sound_t *sound)
{ {
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
if (channels[i].sound == sound) JA_StopChannel(i); {
if (channels[i].sound == sound)
JA_StopChannel(i);
} }
SDL_free(sound->buffer); SDL_free(sound->buffer);
delete sound; delete sound;
@@ -383,7 +423,8 @@ void JA_DeleteSound(JA_Sound_t *sound)
void JA_PauseChannel(const int channel) void JA_PauseChannel(const int channel)
{ {
if (!JA_soundEnabled) return; if (!JA_soundEnabled)
return;
if (channel == -1) if (channel == -1)
{ {
@@ -391,7 +432,7 @@ void JA_PauseChannel(const int channel)
if (channels[i].state == JA_CHANNEL_PLAYING) if (channels[i].state == JA_CHANNEL_PLAYING)
{ {
channels[i].state = JA_CHANNEL_PAUSED; channels[i].state = JA_CHANNEL_PAUSED;
//SDL_PauseAudioStreamDevice(channels[i].stream); // SDL_PauseAudioStreamDevice(channels[i].stream);
SDL_UnbindAudioStream(channels[i].stream); SDL_UnbindAudioStream(channels[i].stream);
} }
} }
@@ -400,7 +441,7 @@ void JA_PauseChannel(const int channel)
if (channels[channel].state == JA_CHANNEL_PLAYING) if (channels[channel].state == JA_CHANNEL_PLAYING)
{ {
channels[channel].state = JA_CHANNEL_PAUSED; channels[channel].state = JA_CHANNEL_PAUSED;
//SDL_PauseAudioStreamDevice(channels[channel].stream); // SDL_PauseAudioStreamDevice(channels[channel].stream);
SDL_UnbindAudioStream(channels[channel].stream); SDL_UnbindAudioStream(channels[channel].stream);
} }
} }
@@ -408,7 +449,8 @@ void JA_PauseChannel(const int channel)
void JA_ResumeChannel(const int channel) void JA_ResumeChannel(const int channel)
{ {
if (!JA_soundEnabled) return; if (!JA_soundEnabled)
return;
if (channel == -1) if (channel == -1)
{ {
@@ -416,7 +458,7 @@ void JA_ResumeChannel(const int channel)
if (channels[i].state == JA_CHANNEL_PAUSED) if (channels[i].state == JA_CHANNEL_PAUSED)
{ {
channels[i].state = JA_CHANNEL_PLAYING; channels[i].state = JA_CHANNEL_PLAYING;
//SDL_ResumeAudioStreamDevice(channels[i].stream); // SDL_ResumeAudioStreamDevice(channels[i].stream);
SDL_BindAudioStream(sdlAudioDevice, channels[i].stream); SDL_BindAudioStream(sdlAudioDevice, channels[i].stream);
} }
} }
@@ -425,7 +467,7 @@ void JA_ResumeChannel(const int channel)
if (channels[channel].state == JA_CHANNEL_PAUSED) if (channels[channel].state == JA_CHANNEL_PAUSED)
{ {
channels[channel].state = JA_CHANNEL_PLAYING; channels[channel].state = JA_CHANNEL_PLAYING;
//SDL_ResumeAudioStreamDevice(channels[channel].stream); // SDL_ResumeAudioStreamDevice(channels[channel].stream);
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream); SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
} }
} }
@@ -433,12 +475,15 @@ void JA_ResumeChannel(const int channel)
void JA_StopChannel(const int channel) void JA_StopChannel(const int channel)
{ {
if (!JA_soundEnabled) return; if (!JA_soundEnabled)
return;
if (channel == -1) if (channel == -1)
{ {
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
if (channels[i].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[i].stream); {
if (channels[i].state != JA_CHANNEL_FREE)
SDL_DestroyAudioStream(channels[i].stream);
channels[channel].stream = nullptr; channels[channel].stream = nullptr;
channels[i].state = JA_CHANNEL_FREE; channels[i].state = JA_CHANNEL_FREE;
channels[i].pos = 0; channels[i].pos = 0;
@@ -447,7 +492,8 @@ void JA_StopChannel(const int channel)
} }
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
{ {
if (channels[channel].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[channel].stream); if (channels[channel].state != JA_CHANNEL_FREE)
SDL_DestroyAudioStream(channels[channel].stream);
channels[channel].stream = nullptr; channels[channel].stream = nullptr;
channels[channel].state = JA_CHANNEL_FREE; channels[channel].state = JA_CHANNEL_FREE;
channels[channel].pos = 0; channels[channel].pos = 0;
@@ -457,19 +503,21 @@ void JA_StopChannel(const int channel)
JA_Channel_state JA_GetChannelState(const int channel) JA_Channel_state JA_GetChannelState(const int channel)
{ {
if (!JA_soundEnabled) return JA_SOUND_DISABLED; if (!JA_soundEnabled)
return JA_SOUND_DISABLED;
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID; if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS)
return JA_CHANNEL_INVALID;
return channels[channel].state; return channels[channel].state;
} }
float JA_SetSoundVolume(float volume) float JA_SetSoundVolume(float volume)
{ {
JA_soundVolume = SDL_clamp( volume, 0.0f, 1.0f ); JA_soundVolume = SDL_clamp(volume, 0.0f, 1.0f);
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
if ( (channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED) ) if ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED))
SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume); SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume);
return JA_soundVolume; return JA_soundVolume;
@@ -479,7 +527,8 @@ void JA_EnableSound(const bool value)
{ {
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
{ {
if (channels[i].state == JA_CHANNEL_PLAYING) JA_StopChannel(i); if (channels[i].state == JA_CHANNEL_PLAYING)
JA_StopChannel(i);
} }
JA_soundEnabled = value; JA_soundEnabled = value;
} }

View File

@@ -1,8 +1,26 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
enum JA_Channel_state { JA_CHANNEL_INVALID, JA_CHANNEL_FREE, JA_CHANNEL_PLAYING, JA_CHANNEL_PAUSED, JA_SOUND_DISABLED }; #include <SDL3/SDL_audio.h> // Para SDL_AudioFormat
enum JA_Music_state { JA_MUSIC_INVALID, JA_MUSIC_PLAYING, JA_MUSIC_PAUSED, JA_MUSIC_STOPPED, JA_MUSIC_DISABLED }; #include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
struct JA_Music_t; // lines 8-8
struct JA_Sound_t; // lines 7-7
enum JA_Channel_state
{
JA_CHANNEL_INVALID,
JA_CHANNEL_FREE,
JA_CHANNEL_PLAYING,
JA_CHANNEL_PAUSED,
JA_SOUND_DISABLED
};
enum JA_Music_state
{
JA_MUSIC_INVALID,
JA_MUSIC_PLAYING,
JA_MUSIC_PAUSED,
JA_MUSIC_STOPPED,
JA_MUSIC_DISABLED
};
struct JA_Sound_t; struct JA_Sound_t;
struct JA_Music_t; struct JA_Music_t;
@@ -10,8 +28,8 @@ struct JA_Music_t;
void JA_Init(const int freq, const SDL_AudioFormat format, const int channels); void JA_Init(const int freq, const SDL_AudioFormat format, const int channels);
void JA_Quit(); void JA_Quit();
JA_Music_t *JA_LoadMusic(const char* filename); JA_Music_t *JA_LoadMusic(const char *filename);
JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length); JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length);
void JA_PlayMusic(JA_Music_t *music, const int loop = -1); void JA_PlayMusic(JA_Music_t *music, const int loop = -1);
void JA_PauseMusic(); void JA_PauseMusic();
void JA_ResumeMusic(); void JA_ResumeMusic();
@@ -24,9 +42,9 @@ void JA_SetMusicPosition(float value);
float JA_GetMusicPosition(); float JA_GetMusicPosition();
void JA_EnableMusic(const bool value); void JA_EnableMusic(const bool value);
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length); JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length);
JA_Sound_t *JA_LoadSound(Uint8* buffer, Uint32 length); JA_Sound_t *JA_LoadSound(Uint8 *buffer, Uint32 length);
JA_Sound_t *JA_LoadSound(const char* filename); JA_Sound_t *JA_LoadSound(const char *filename);
int JA_PlaySound(JA_Sound_t *sound, const int loop = 0); int JA_PlaySound(JA_Sound_t *sound, const int loop = 0);
int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0); int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0);
void JA_PauseChannel(const int channel); void JA_PauseChannel(const int channel);

View File

@@ -1,7 +1,7 @@
#include "jail_shader.h" #include "jail_shader.h"
#include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_LogWarn
#include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FPoint, SDL_Point
#include <cstring> // Para strncmp #include <cstring> // Para strncmp
#include <iostream> // Para basic_ostream, operator<<, endl, cout
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <vector> // Para vector #include <vector> // Para vector
@@ -71,6 +71,7 @@ namespace shader
{ {
if (source.empty()) if (source.empty())
{ {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "ERROR FATAL: El código fuente del shader está vacío.");
throw std::runtime_error("ERROR FATAL: El código fuente del shader está vacío."); throw std::runtime_error("ERROR FATAL: El código fuente del shader está vacío.");
} }
@@ -95,14 +96,14 @@ namespace shader
glGetShaderiv(resultado, GL_COMPILE_STATUS, &compiladoCorrectamente); glGetShaderiv(resultado, GL_COMPILE_STATUS, &compiladoCorrectamente);
if (compiladoCorrectamente != GL_TRUE) if (compiladoCorrectamente != GL_TRUE)
{ {
std::cout << "Error en la compilación del shader (" << resultado << ")!" << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error en la compilación del shader (%d)!", resultado);
GLint longitudLog; GLint longitudLog;
glGetShaderiv(resultado, GL_INFO_LOG_LENGTH, &longitudLog); glGetShaderiv(resultado, GL_INFO_LOG_LENGTH, &longitudLog);
if (longitudLog > 0) if (longitudLog > 0)
{ {
std::vector<GLchar> log(longitudLog); std::vector<GLchar> log(longitudLog);
glGetShaderInfoLog(resultado, longitudLog, &longitudLog, log.data()); glGetShaderInfoLog(resultado, longitudLog, &longitudLog, log.data());
std::cout << "Registro de compilación del shader: " << log.data() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Registro de compilación del shader: %s", log.data());
} }
glDeleteShader(resultado); glDeleteShader(resultado);
resultado = 0; resultado = 0;
@@ -134,8 +135,7 @@ namespace shader
{ {
std::vector<char> log(longitudLog); std::vector<char> log(longitudLog);
glGetProgramInfoLog(idPrograma, longitudLog, &longitudLog, log.data()); glGetProgramInfoLog(idPrograma, longitudLog, &longitudLog, log.data());
std::cout << "Registro de información del programa:" << std::endl SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Registro de información del programa:\n%s", log.data());
<< log.data() << std::endl;
} }
} }
if (idShaderVertice) if (idShaderVertice)
@@ -156,13 +156,7 @@ namespace shader
shader::backBuffer = texturaBackBuffer; shader::backBuffer = texturaBackBuffer;
SDL_GetWindowSize(ventana, &win_size.x, &win_size.y); SDL_GetWindowSize(ventana, &win_size.x, &win_size.y);
// int acceso;
SDL_GetTextureSize(texturaBackBuffer, &tex_size.x, &tex_size.y); SDL_GetTextureSize(texturaBackBuffer, &tex_size.x, &tex_size.y);
// SDL_QueryTexture(texturaBackBuffer, nullptr, &acceso, &tex_size.x, &tex_size.y);
/*if (acceso != SDL_TEXTUREACCESS_TARGET)
{
throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET.");
}*/
const auto RENDER_NAME = SDL_GetRendererName(renderer); const auto RENDER_NAME = SDL_GetRendererName(renderer);
@@ -172,7 +166,7 @@ namespace shader
#ifndef __APPLE__ #ifndef __APPLE__
if (!initGLExtensions()) if (!initGLExtensions())
{ {
std::cout << "ADVERTENCIA: No se han podido inicializar las extensiones de OpenGL." << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "ADVERTENCIA: No se han podido inicializar las extensiones de OpenGL.");
usingOpenGL = false; usingOpenGL = false;
return false; return false;
} }
@@ -182,7 +176,7 @@ namespace shader
} }
else else
{ {
std::cout << "ADVERTENCIA: El driver del renderer no es OpenGL." << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "ADVERTENCIA: El driver del renderer no es OpenGL.");
usingOpenGL = false; usingOpenGL = false;
return false; return false;
} }

View File

@@ -1,8 +1,8 @@
#include "manage_hiscore_table.h" #include "manage_hiscore_table.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_iostream.h> // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO #include <SDL3/SDL_iostream.h> // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO
#include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_Lo...
#include <algorithm> // Para find_if, sort #include <algorithm> // Para find_if, sort
#include <iostream> // Para basic_ostream, operator<<, cout, endl
#include <iterator> // Para distance #include <iterator> // Para distance
#include "utils.h" // Para getFileName #include "utils.h" // Para getFileName
@@ -116,12 +116,12 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
table_.push_back(entry); table_.push_back(entry);
} }
std::cout << "Reading file: " << getFileName(file_path) << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Reading file: %s", getFileName(file_path).c_str());
SDL_CloseIO(file); SDL_CloseIO(file);
} }
else else
{ {
std::cout << "Error: Unable to load " << getFileName(file_path) << " file! " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to load %s file! %s", getFileName(file_path).c_str(), SDL_GetError());
success = false; success = false;
} }
return success; return success;
@@ -157,12 +157,12 @@ bool ManageHiScoreTable::saveToFile(const std::string &file_path)
SDL_WriteIO(file, &occ_value, sizeof(int)); SDL_WriteIO(file, &occ_value, sizeof(int));
} }
std::cout << "Writing file: " << getFileName(file_path) << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file: %s", getFileName(file_path).c_str());
SDL_CloseIO(file); SDL_CloseIO(file);
} }
else else
{ {
std::cout << "Error: Unable to save " << getFileName(file_path) << " file! " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to save %s file! %s", getFileName(file_path).c_str(), SDL_GetError());
success = false; success = false;
} }
return success; return success;

View File

@@ -1,13 +1,13 @@
#include "options.h" #include "options.h"
#include <algorithm> // Para clamp #include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogInfo, SDL_LogWarn
#include <fstream> // Para basic_ostream, operator<<, basic_ostream::opera... #include <algorithm> // Para clamp
#include <iostream> // Para cout #include <fstream> // Para basic_ostream, operator<<, basic_ostream::...
#include <utility> // Para swap #include <utility> // Para swap
#include <vector> // Para vector #include <vector> // Para vector
#include "input.h" // Para InputDeviceToUse #include "input.h" // Para InputDeviceToUse
#include "lang.h" // Para Code #include "lang.h" // Para Code
#include "screen.h" // Para ScreenFilter #include "screen.h" // Para ScreenFilter
#include "utils.h" // Para boolToString, stringToBool, getFileName #include "utils.h" // Para boolToString, stringToBool, getFileName
// Variables // Variables
Options options; Options options;
@@ -65,28 +65,27 @@ bool loadOptionsFile(std::string file_path)
// Si el fichero se puede abrir // Si el fichero se puede abrir
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // Procesa el fichero línea a línea
std::cout << "Reading file: " << getFileName(file_path) << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Reading file: %s", getFileName(file_path).c_str());
std::string line; std::string line;
while (std::getline(file, line)) while (std::getline(file, line))
{ {
// Comprueba que la linea no sea un comentario // Comprueba que la línea no sea un comentario
if (line.substr(0, 1) != "#") if (line.substr(0, 1) != "#")
{ {
// Encuentra la posición del caracter '=' // Encuentra la posición del carácter '='
int pos = line.find("="); int pos = line.find("=");
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length()))) if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length())))
{ {
std::cout << "Warning: file " << getFileName(file_path) << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s", getFileName(file_path).c_str());
std::cout << "Unknown parameter " << line.substr(0, pos).c_str() << std::endl; SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unknown parameter: %s", line.substr(0, pos).c_str());
success = false; success = false;
} }
} }
} }
file.close(); file.close();
} }
// El fichero no existe // El fichero no existe
else else
{ {
@@ -112,11 +111,11 @@ bool saveOptionsFile(std::string file_path)
if (!file.good()) if (!file.good())
{ {
std::cout << getFileName(file_path) << " can't be opened" << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s can't be opened", getFileName(file_path).c_str());
return false; return false;
} }
std::cout << "Writing file: " << getFileName(file_path) << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file: %s", getFileName(file_path).c_str());
// Opciones de video // Opciones de video
file << "## VIDEO\n"; file << "## VIDEO\n";

View File

@@ -1,18 +1,88 @@
#include "param.h" #include "param.h"
#include <fstream> // Para char_traits, basic_ostream, basic_ifstream, basi... #include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_LogInfo
#include <iostream> // Para cout #include <fstream> // Para basic_istream, basic_ifstream, ifstream
#include <sstream> #include <sstream> // Para basic_istringstream
#include <string> #include <stdexcept> // Para runtime_error
#include <stdexcept> #include <string> // Para operator==, stoi, char_traits, string, ope...
#include "utils.h" // Para Param, ParamGame, Zone, ParamBalloon #include "utils.h" // Para Zone, Color, NotifyPosition, getFileName
Param param; Param param;
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value);
// Calcula variables a partir de otras variables // Calcula variables a partir de otras variables
void precalculateZones(); void precalculateZones()
{
// playArea
param.game.play_area.center_x = param.game.play_area.rect.w / 2;
param.game.play_area.first_quarter_x = param.game.play_area.rect.w / 4;
param.game.play_area.third_quarter_x = param.game.play_area.rect.w / 4 * 3;
param.game.play_area.center_y = param.game.play_area.rect.h / 2;
param.game.play_area.first_quarter_y = param.game.play_area.rect.h / 4;
param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3;
// gameArea
param.game.game_area.rect = {0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)};
param.game.game_area.center_x = param.game.game_area.rect.w / 2;
param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4;
param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3;
param.game.game_area.center_y = param.game.game_area.rect.h / 2;
param.game.game_area.first_quarter_y = param.game.game_area.rect.h / 4;
param.game.game_area.third_quarter_y = param.game.game_area.rect.h / 4 * 3;
}
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value)
{
// Indicador de éxito en la asignación
auto success = true;
// GAME
if (var == "game.width")
{
param.game.width = std::stoi(value);
}
else if (var == "game.height")
{
param.game.height = std::stoi(value);
}
else if (var == "game.item_size")
{
param.game.item_size = std::stoi(value);
}
else if (var == "game.coffee_machine_w")
{
param.game.coffee_machine_w = std::stoi(value);
}
else if (var == "game.coffee_machine_h")
{
param.game.coffee_machine_h = std::stoi(value);
}
else if (var == "game.play_area.rect.x")
{
param.game.play_area.rect.x = std::stoi(value);
}
else if (var == "game.play_area.rect.y")
{
param.game.play_area.rect.y = std::stoi(value);
}
else if (var == "game.play_area.rect.w")
{
param.game.play_area.rect.w = std::stoi(value);
}
else if (var == "game.play_area.rect.h")
{
param.game.play_area.rect.h = std::stoi(value);
}
else if (var == "game.enter_name_seconds")
{
param.game.enter_name_seconds = std::stoi(value);
}
else
{
success = false;
}
return success;
}
// Establece valores por defecto a las variables // Establece valores por defecto a las variables
void initParam() void initParam()
@@ -65,6 +135,7 @@ void initParam()
param.notification.color.b = 48; param.notification.color.b = 48;
} }
// Carga los parámetros desde un archivo
void loadParamsFromFile(const std::string &file_path) void loadParamsFromFile(const std::string &file_path)
{ {
// Inicializa los parámetros con valores por defecto // Inicializa los parámetros con valores por defecto
@@ -74,11 +145,11 @@ 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())
{ {
std::cerr << "Error: No se pudo abrir el archivo " << file_path << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo abrir el archivo %s", file_path.c_str());
throw std::runtime_error("No se pudo abrir el archivo: " + file_path); throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
} }
std::cout << "Reading file: " << getFileName(file_path) << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Leyendo archivo: %s", getFileName(file_path).c_str());
std::string line, param1, param2; std::string line, param1, param2;
while (std::getline(file, line)) while (std::getline(file, line))
@@ -94,7 +165,10 @@ void loadParamsFromFile(const std::string &file_path)
std::istringstream iss(line); std::istringstream iss(line);
if (iss >> param1 >> param2) if (iss >> param1 >> param2)
{ {
setParams(param1, param2); if (!setParams(param1, param2))
{
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Parámetro desconocido: %s", param1.c_str());
}
} }
} }
@@ -104,267 +178,3 @@ void loadParamsFromFile(const std::string &file_path)
// Realiza cálculos adicionales después de cargar los parámetros // Realiza cálculos adicionales después de cargar los parámetros
precalculateZones(); precalculateZones();
} }
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value)
{
// Indicador de éxito en la asignación
auto success = true;
// GAME
if (var == "game.width")
{
param.game.width = std::stoi(value);
}
else if (var == "game.height")
{
param.game.height = std::stoi(value);
}
else if (var == "game.item_size")
{
param.game.item_size = std::stoi(value);
}
else if (var == "game.coffee_machine_w")
{
param.game.coffee_machine_w = std::stoi(value);
}
else if (var == "game.coffee_machine_h")
{
param.game.coffee_machine_h = std::stoi(value);
}
else if (var == "game.play_area.rect.x")
{
param.game.play_area.rect.x = std::stoi(value);
}
else if (var == "game.play_area.rect.y")
{
param.game.play_area.rect.y = std::stoi(value);
}
else if (var == "game.play_area.rect.w")
{
param.game.play_area.rect.w = std::stoi(value);
}
else if (var == "game.play_area.rect.h")
{
param.game.play_area.rect.h = std::stoi(value);
}
else if (var == "game.enter_name_seconds")
{
param.game.enter_name_seconds = std::stoi(value);
}
// FADE
else if (var == "fade.num_squares_width")
{
param.fade.num_squares_width = std::stoi(value);
}
else if (var == "fade.num_squares_height")
{
param.fade.num_squares_height = std::stoi(value);
}
else if (var == "fade.random_squares_delay")
{
param.fade.random_squares_delay = std::stoi(value);
}
else if (var == "fade.random_squares_mult")
{
param.fade.random_squares_mult = std::stoi(value);
}
else if (var == "fade.post_duration")
{
param.fade.post_duration = std::stoi(value);
}
else if (var == "fade.venetian_size")
{
param.fade.venetian_size = std::stoi(value);
}
// SCOREBOARD
else if (var == "scoreboard.x")
{
param.scoreboard.x = std::stoi(value);
}
else if (var == "scoreboard.y")
{
param.scoreboard.y = std::stoi(value);
}
else if (var == "scoreboard.w")
{
param.scoreboard.w = std::stoi(value);
}
else if (var == "scoreboard.h")
{
param.scoreboard.h = std::stoi(value);
}
// TITLE
else if (var == "title.press_start_position")
{
param.title.press_start_position = std::stoi(value);
}
else if (var == "title.title_duration")
{
param.title.title_duration = std::stoi(value);
}
else if (var == "title.arcade_edition_position")
{
param.title.arcade_edition_position = std::stoi(value);
}
else if (var == "title.title_c_c_position")
{
param.title.title_c_c_position = std::stoi(value);
}
// BACKGROUND
else if (var == "background.attenuate_color.r")
{
param.background.attenuate_color.r = std::stoi(value);
}
else if (var == "background.attenuate_color.g")
{
param.background.attenuate_color.g = std::stoi(value);
}
else if (var == "background.attenuate_color.b")
{
param.background.attenuate_color.b = std::stoi(value);
}
else if (var == "background.attenuate_alpha")
{
param.background.attenuate_alpha = std::stoi(value);
}
// BALLOON
else if (var == "balloon_1.vel")
{
param.balloon.at(0).vel = std::stof(value);
}
else if (var == "balloon_1.grav")
{
param.balloon.at(0).grav = std::stof(value);
}
else if (var == "balloon_2.vel")
{
param.balloon.at(1).vel = std::stof(value);
}
else if (var == "balloon_2.grav")
{
param.balloon.at(1).grav = std::stof(value);
}
else if (var == "balloon_3.vel")
{
param.balloon.at(2).vel = std::stof(value);
}
else if (var == "balloon_3.grav")
{
param.balloon.at(2).grav = std::stof(value);
}
else if (var == "balloon_4.vel")
{
param.balloon.at(3).vel = std::stof(value);
}
else if (var == "balloon_4.grav")
{
param.balloon.at(3).grav = std::stof(value);
}
// NOTIFICACIONES
else if (var == "notification.pos_h")
{
if (value == "LEFT")
{
param.notification.pos_h = NotifyPosition::LEFT;
}
else if (value == "MIDDLE")
{
param.notification.pos_h = NotifyPosition::MIDDLE;
}
else
{
param.notification.pos_h = NotifyPosition::RIGHT;
}
}
else if (var == "notification.pos_v")
{
param.notification.pos_v = value == "TOP" ? NotifyPosition::TOP : NotifyPosition::BOTTOM;
}
else if (var == "notification.sound")
{
param.notification.sound = stringToBool(value);
}
else if (var == "notification.color.r")
{
param.notification.color.r = std::stoi(value);
}
else if (var == "notification.color.g")
{
param.notification.color.g = std::stoi(value);
}
else if (var == "notification.color.b")
{
param.notification.color.b = std::stoi(value);
}
// RESTO
else
{
success = false;
}
return success;
}
// Calcula variables a partir de otras variables
void precalculateZones()
{
// playArea
param.game.play_area.center_x = param.game.play_area.rect.w / 2;
param.game.play_area.first_quarter_x = param.game.play_area.rect.w / 4;
param.game.play_area.third_quarter_x = param.game.play_area.rect.w / 4 * 3;
param.game.play_area.center_y = param.game.play_area.rect.h / 2;
param.game.play_area.first_quarter_y = param.game.play_area.rect.h / 4;
param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3;
// gameArea
param.game.game_area.rect = {0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)};
param.game.game_area.center_x = param.game.game_area.rect.w / 2;
param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4;
param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3;
param.game.game_area.center_y = param.game.game_area.rect.h / 2;
param.game.game_area.first_quarter_y = param.game.game_area.rect.h / 4;
param.game.game_area.third_quarter_y = param.game.game_area.rect.h / 4 * 3;
}

View File

@@ -1,14 +1,14 @@
#include "resource.h" #include "resource.h"
#include <algorithm> // Para find_if #include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError
#include <iostream> // Para basic_ostream, operator<<, endl, cout, cerr #include <algorithm> // Para find_if
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic #include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic
#include "lang.h" // Para getText #include "lang.h" // Para getText
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "text.h" // Para Text, loadTextFile #include "text.h" // Para Text, loadTextFile
struct JA_Music_t; // lines 11-11 struct JA_Music_t; // lines 11-11
struct JA_Sound_t; // lines 12-12 struct JA_Sound_t; // lines 12-12
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Resource *Resource::resource_ = nullptr; Resource *Resource::resource_ = nullptr;
@@ -52,7 +52,7 @@ void Resource::clear()
// Carga todos los recursos // Carga todos los recursos
void Resource::load() void Resource::load()
{ {
std::cout << "** LOADING RESOURCES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** LOADING RESOURCES");
loadSounds(); loadSounds();
loadMusics(); loadMusics();
loadTextures(); loadTextures();
@@ -62,7 +62,7 @@ void Resource::load()
addPalettes(); addPalettes();
createText(); createText();
createTextures(); createTextures();
std::cout << "\n** RESOURCES LOADED" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** RESOURCES LOADED");
} }
// Recarga todos los recursos // Recarga todos los recursos
@@ -91,7 +91,7 @@ JA_Sound_t *Resource::getSound(const std::string &name)
return it->sound; return it->sound;
} }
std::cerr << "Error: Sonido no encontrado " << name << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Sonido no encontrado %s", name.c_str());
throw std::runtime_error("Sonido no encontrado: " + name); throw std::runtime_error("Sonido no encontrado: " + name);
} }
@@ -106,7 +106,7 @@ JA_Music_t *Resource::getMusic(const std::string &name)
return it->music; return it->music;
} }
std::cerr << "Error: Música no encontrada " << name << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Música no encontrada %s", name.c_str());
throw std::runtime_error("Música no encontrada: " + name); throw std::runtime_error("Música no encontrada: " + name);
} }
@@ -121,7 +121,7 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
return it->texture; return it->texture;
} }
std::cerr << "Error: Imagen no encontrada " << name << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Imagen no encontrada %s", name.c_str());
throw std::runtime_error("Imagen no encontrada: " + name); throw std::runtime_error("Imagen no encontrada: " + name);
} }
@@ -136,7 +136,7 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
return it->text_file; return it->text_file;
} }
std::cerr << "Error: TextFile no encontrado " << name << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: TextFile no encontrado %s", name.c_str());
throw std::runtime_error("TextFile no encontrado: " + name); throw std::runtime_error("TextFile no encontrado: " + name);
} }
@@ -151,7 +151,7 @@ std::shared_ptr<Text> Resource::getText(const std::string &name)
return it->text; return it->text;
} }
std::cerr << "Error: Text no encontrado " << name << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Text no encontrado %s", name.c_str());
throw std::runtime_error("Text no encontrado: " + name); throw std::runtime_error("Text no encontrado: " + name);
} }
@@ -166,7 +166,7 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
return it->animation; return it->animation;
} }
std::cerr << "Error: Animación no encontrada " << name << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Animación no encontrada %s", name.c_str());
throw std::runtime_error("Animación no encontrada: " + name); throw std::runtime_error("Animación no encontrada: " + name);
} }
@@ -179,7 +179,7 @@ DemoData &Resource::getDemoData(int index)
// Carga los sonidos // Carga los sonidos
void Resource::loadSounds() void Resource::loadSounds()
{ {
std::cout << "\n>> SOUND FILES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> SOUND FILES");
auto list = Asset::get()->getListByType(AssetType::SOUND); auto list = Asset::get()->getListByType(AssetType::SOUND);
sounds_.clear(); sounds_.clear();
@@ -187,14 +187,14 @@ void Resource::loadSounds()
{ {
auto name = getFileName(l); auto name = getFileName(l);
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str()))); sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str())));
printWithDots("Sound : ", name, "[ LOADED ]"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Sound : %s [ LOADED ]", name.c_str());
} }
} }
// Carga las musicas // Carga las músicas
void Resource::loadMusics() void Resource::loadMusics()
{ {
std::cout << "\n>> MUSIC FILES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> MUSIC FILES");
auto list = Asset::get()->getListByType(AssetType::MUSIC); auto list = Asset::get()->getListByType(AssetType::MUSIC);
musics_.clear(); musics_.clear();
@@ -202,14 +202,14 @@ void Resource::loadMusics()
{ {
auto name = getFileName(l); auto name = getFileName(l);
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str()))); musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str())));
printWithDots("Music : ", name, "[ LOADED ]"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Music : %s [ LOADED ]", name.c_str());
} }
} }
// Carga las texturas // Carga las texturas
void Resource::loadTextures() void Resource::loadTextures()
{ {
std::cout << "\n>> TEXTURES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> TEXTURES");
auto list = Asset::get()->getListByType(AssetType::BITMAP); auto list = Asset::get()->getListByType(AssetType::BITMAP);
textures_.clear(); textures_.clear();
@@ -217,13 +217,14 @@ void Resource::loadTextures()
{ {
auto name = getFileName(l); auto name = getFileName(l);
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l))); textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Texture : %s [ LOADED ]", name.c_str());
} }
} }
// Carga los ficheros de texto // Carga los ficheros de texto
void Resource::loadTextFiles() void Resource::loadTextFiles()
{ {
std::cout << "\n>> TEXT FILES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> TEXT FILES");
auto list = Asset::get()->getListByType(AssetType::FONT); auto list = Asset::get()->getListByType(AssetType::FONT);
text_files_.clear(); text_files_.clear();
@@ -231,13 +232,14 @@ void Resource::loadTextFiles()
{ {
auto name = getFileName(l); auto name = getFileName(l);
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l))); text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l)));
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "TextFile : %s [ LOADED ]", name.c_str());
} }
} }
// Carga las animaciones // Carga las animaciones
void Resource::loadAnimations() void Resource::loadAnimations()
{ {
std::cout << "\n>> ANIMATIONS" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> ANIMATIONS");
auto list = Asset::get()->getListByType(AssetType::ANIMATION); auto list = Asset::get()->getListByType(AssetType::ANIMATION);
animations_.clear(); animations_.clear();
@@ -245,22 +247,25 @@ void Resource::loadAnimations()
{ {
auto name = getFileName(l); auto name = getFileName(l);
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Animation : %s [ LOADED ]", name.c_str());
} }
} }
// Carga los datos para el modo demostración // Carga los datos para el modo demostración
void Resource::loadDemoData() void Resource::loadDemoData()
{ {
std::cout << "\n>> DEMO_FILES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> DEMO FILES");
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo1.bin"))); demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo1.bin")));
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo2.bin"))); demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo2.bin")));
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Demo data loaded.");
} }
// Añade paletas a las texturas // Añade paletas a las texturas
void Resource::addPalettes() void Resource::addPalettes()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> PALETTES");
// Jugador 1 // Jugador 1
std::cout << "\n>> PALETTES" << std::endl;
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif"));
@@ -282,43 +287,42 @@ void Resource::createTextures()
std::string name; std::string name;
std::string text; std::string text;
// Constructor
NameAndText(const std::string &name_init, const std::string &text_init) NameAndText(const std::string &name_init, const std::string &text_init)
: name(name_init), text(text_init) {} : name(name_init), text(text_init) {}
}; };
std::cout << "\n>> CREATING TEXTURES" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> CREATING TEXTURES");
// Tamaño normal // Tamaño normal
std::vector<NameAndText> strings = { std::vector<NameAndText> strings = {
NameAndText("game_text_1000_points", "1.000"), {"game_text_1000_points", "1.000"},
NameAndText("game_text_2500_points", "2.500"), {"game_text_2500_points", "2.500"},
NameAndText("game_text_5000_points", "5.000"), {"game_text_5000_points", "5.000"},
NameAndText("game_text_powerup", lang::getText(117)), {"game_text_powerup", lang::getText(117)},
NameAndText("game_text_one_hit", lang::getText(118)), {"game_text_one_hit", lang::getText(118)},
NameAndText("game_text_stop", lang::getText(119)), {"game_text_stop", lang::getText(119)},
NameAndText("game_text_1000000_points", lang::getText(76))}; {"game_text_1000000_points", lang::getText(76)}};
auto text = getText("04b_25"); auto text = getText("04b_25");
for (const auto &s : strings) for (const auto &s : strings)
{ {
textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2))); textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
printWithDots("Texture : ", s.name, "[ DONE ]"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Texture : %s [ DONE ]", s.name.c_str());
} }
// Tamaño doble // Tamaño doble
std::vector<NameAndText> strings2X = { std::vector<NameAndText> strings2X = {
NameAndText("game_text_100000_points", "100.000"), {"game_text_100000_points", "100.000"},
NameAndText("game_text_get_ready", lang::getText(75)), {"game_text_get_ready", lang::getText(75)},
NameAndText("game_text_last_stage", lang::getText(79)), {"game_text_last_stage", lang::getText(79)},
NameAndText("game_text_congratulations", lang::getText(50)), {"game_text_congratulations", lang::getText(50)},
NameAndText("game_text_game_over", "Game Over")}; {"game_text_game_over", "Game Over"}};
auto text2 = getText("04b_25_2x"); auto text2 = getText("04b_25_2x");
for (const auto &s : strings2X) for (const auto &s : strings2X)
{ {
textures_.emplace_back(ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4))); textures_.emplace_back(ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4)));
printWithDots("Texture : ", s.name, "[ DONE ]"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Texture : %s [ DONE ]", s.name.c_str());
} }
} }
@@ -326,16 +330,15 @@ void Resource::createText()
{ {
struct ResourceInfo struct ResourceInfo
{ {
std::string key; // Identificador del recurso std::string key;
std::string textureFile; // Nombre del archivo de textura std::string textureFile;
std::string textFile; // Nombre del archivo de texto std::string textFile;
// Constructor para facilitar la creación de objetos ResourceInfo
ResourceInfo(const std::string &k, const std::string &tFile, const std::string &txtFile) ResourceInfo(const std::string &k, const std::string &tFile, const std::string &txtFile)
: key(k), textureFile(tFile), textFile(txtFile) {} : key(k), textureFile(tFile), textFile(txtFile) {}
}; };
std::cout << "\n>> CREATING TEXT_OBJECTS" << std::endl; SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> CREATING TEXT OBJECTS");
std::vector<ResourceInfo> resources = { std::vector<ResourceInfo> resources = {
{"04b_25", "04b_25.png", "04b_25.txt"}, {"04b_25", "04b_25.png", "04b_25.txt"},
@@ -350,14 +353,13 @@ void Resource::createText()
texts_.emplace_back(ResourceText(resource.key, std::make_shared<Text>( texts_.emplace_back(ResourceText(resource.key, std::make_shared<Text>(
getTexture(resource.textureFile), getTexture(resource.textureFile),
getTextFile(resource.textFile)))); getTextFile(resource.textFile))));
printWithDots("Text : ", resource.key, "[ DONE ]"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Text : %s [ DONE ]", resource.key.c_str());
} }
} }
// Vacía el vector de sonidos // Vacía el vector de sonidos
void Resource::clearSounds() void Resource::clearSounds()
{ {
// Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t
for (auto &sound : sounds_) for (auto &sound : sounds_)
{ {
if (sound.sound) if (sound.sound)
@@ -366,13 +368,12 @@ void Resource::clearSounds()
sound.sound = nullptr; sound.sound = nullptr;
} }
} }
sounds_.clear(); // Limpia el vector después de liberar todos los recursos sounds_.clear();
} }
// Vacía el vector de musicas // Vacía el vector de músicas
void Resource::clearMusics() void Resource::clearMusics()
{ {
// Itera sobre el vector y libera los recursos asociados a cada JA_Music_t
for (auto &music : musics_) for (auto &music : musics_)
{ {
if (music.music) if (music.music)
@@ -381,5 +382,5 @@ void Resource::clearMusics()
music.music = nullptr; music.music = nullptr;
} }
} }
musics_.clear(); // Limpia el vector después de liberar todos los recursos musics_.clear();
} }

View File

@@ -269,7 +269,7 @@ void Scoreboard::fillPanelTextures()
for (size_t j = 0; j < MAX_NAME_LENGHT; ++j) for (size_t j = 0; j < MAX_NAME_LENGHT; ++j)
{ {
// Selecciona el color // Selecciona el color
const Color color = j < selector_pos_[i] ? orange_soft_color.lighten() : Color(0xFF, 0xFF, 0xEB); const Color color = j < selector_pos_[i] ? ORANGE_SOFT_COLOR.lighten() : Color(0xFF, 0xFF, 0xEB);
if (j != selector_pos_[i] || time_counter_ % 3 == 0) if (j != selector_pos_[i] || time_counter_ % 3 == 0)
{ {
@@ -439,14 +439,14 @@ void Scoreboard::createPanelTextures()
void Scoreboard::renderSeparator() void Scoreboard::renderSeparator()
{ {
// Dibuja la linea que separa el marcador de la zona de juego // Dibuja la linea que separa el marcador de la zona de juego
SDL_SetRenderDrawColor(renderer_, separator_color.r, separator_color.g, separator_color.b, 255); SDL_SetRenderDrawColor(renderer_, SEPARATOR_COLOR.r, SEPARATOR_COLOR.g, SEPARATOR_COLOR.b, 255);
SDL_RenderLine(renderer_, 0, 0, rect_.w, 0); SDL_RenderLine(renderer_, 0, 0, rect_.w, 0);
} }
// Inicializa el vector de colores para el nombre // Inicializa el vector de colores para el nombre
void Scoreboard::iniNameColors() void Scoreboard::iniNameColors()
{ {
Color color = green_color; Color color = GREEN_COLOR;
name_colors_.clear(); name_colors_.clear();
name_colors_.emplace_back(color.lighten(50)); name_colors_.emplace_back(color.lighten(50));

View File

@@ -1,21 +1,25 @@
#include "screen.h" #include "screen.h"
#include <SDL3/SDL.h> // Para SDL_PixelFormat #include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL_hints.h> // Para SDL_SetHint, SDL_HINT_RENDER_DRIVER
#include <SDL3/SDL_init.h> // Para SDL_Init, SDL_INIT_VIDEO #include <SDL3/SDL_init.h> // Para SDL_Init, SDL_INIT_VIDEO
#include <algorithm> // Para max, min #include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_L...
#include <fstream> // Para basic_ifstream, ifstream #include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat
#include <iterator> // Para istreambuf_iterator, operator== #include <SDL3/SDL_surface.h> // Para SDL_ScaleMode
#include <memory> // Para __shared_ptr_access, shared_ptr #include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <string> // Para string, operator+, to_string #include <algorithm> // Para min, max
#include "asset.h" // Para Asset #include <fstream> // Para basic_ifstream, ifstream
#include "jail_shader.h" // Para init, render #include <iterator> // Para istreambuf_iterator, operator==
#include "mouse.h" // Para updateCursorVisibility #include <memory> // Para __shared_ptr_access, shared_ptr
#include "notifier.h" // Para Notifier #include <string> // Para allocator, char_traits, operator+
#include "on_screen_help.h" // Para OnScreenHelp #include "asset.h" // Para Asset
#include "options.h" // Para Options, VideoOptions, options, WindowO... #include "jail_shader.h" // Para init, render
#include "resource.h" // Para Resource #include "mouse.h" // Para updateCursorVisibility
#include "text.h" // Para Text #include "notifier.h" // Para Notifier
#include "on_screen_help.h" // Para OnScreenHelp
#include "options.h" // Para Options, options, WindowOptions, Vid...
#include "resource.h" // Para Resource
#include "text.h" // Para Text
// [SINGLETON] // [SINGLETON]
Screen *Screen::screen_ = nullptr; Screen *Screen::screen_ = nullptr;
@@ -220,10 +224,10 @@ void Screen::renderInfo()
// FPS // FPS
const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS"; const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS";
text->writeColored(param.game.width - text->lenght(FPS_TEXT), 0, FPS_TEXT, orange_soft_color); text->writeColored(param.game.width - text->lenght(FPS_TEXT), 0, FPS_TEXT, ORANGE_SOFT_COLOR);
// Resolution // Resolution
text->writeColored(0, 0, options.video.info, orange_soft_color); text->writeColored(0, 0, options.video.info, ORANGE_SOFT_COLOR);
} }
} }

View File

@@ -1,8 +1,8 @@
#include "text.h" #include "text.h"
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND #include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888 #include <SDL3/SDL_pixels.h> // Para SDL_PixelFormat
#include <SDL3/SDL_rect.h> // Para SDL_FRect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_TEXTUREACCESS_TARGET #include <SDL3/SDL_render.h> // Para SDL_SetRenderTarget, SDL_GetRenderTa...
#include <stddef.h> // Para size_t #include <stddef.h> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic... #include <fstream> // Para basic_ifstream, basic_istream, basic...
#include <iostream> // Para cerr #include <iostream> // Para cerr

View File

@@ -1,14 +1,15 @@
#include "texture.h" #include "texture.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_surface.h> // Para SDL_CreateRGBSurfaceWithFormatFrom #include <SDL3/SDL_log.h> // Para SDL_LogError, SDL_LogCategory, SDL_Log...
#include <SDL3/SDL_surface.h> // Para SDL_CreateSurfaceFrom, SDL_DestroySurface
#include <stdint.h> // Para uint32_t #include <stdint.h> // Para uint32_t
#include <cstring> // Para memcpy, size_t #include <cstring> // Para memcpy, size_t
#include <fstream> // Para basic_ostream, operator<<, basic_ifstream #include <fstream> // Para basic_ifstream, basic_ios, ios, operator|
#include <iostream> // Para cerr, cout
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para char_traits, operator<<, operator+ #include <string> // Para operator+, char_traits, string, operat...
#include <vector> // Para vector #include <vector> // Para vector
#include "gif.h" // Para Gif #include "gif.h" // Para Gif
#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_a...
#include "utils.h" // Para getFileName, Color, printWithDots #include "utils.h" // Para getFileName, Color, printWithDots
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
@@ -67,7 +68,7 @@ bool Texture::loadFromFile(const std::string &file_path)
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format); unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
if (!data) if (!data)
{ {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", getFileName(file_path).c_str());
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} }
else else
@@ -89,11 +90,10 @@ bool Texture::loadFromFile(const std::string &file_path)
SDL_Texture *new_texture = nullptr; SDL_Texture *new_texture = nullptr;
// Carga la imagen desde una ruta específica // Carga la imagen desde una ruta específica
/*auto loaded_surface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast<void *>(data), width, height, depth, pitch, pixel_format);*/
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)
{ {
std::cout << "Unable to load image " << file_path << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load image %s", file_path.c_str());
} }
else else
{ {
@@ -101,7 +101,7 @@ bool Texture::loadFromFile(const std::string &file_path)
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface); new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
if (new_texture == nullptr) if (new_texture == nullptr)
{ {
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create texture from %s! SDL Error: %s", file_path.c_str(), SDL_GetError());
} }
else else
{ {
@@ -127,7 +127,7 @@ bool Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_Tex
texture_ = SDL_CreateTexture(renderer_, format, access, width, height); texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_) if (!texture_)
{ {
std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create blank texture! SDL Error: %s", SDL_GetError());
} }
else else
{ {
@@ -249,7 +249,7 @@ std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path)
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)
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
@@ -261,7 +261,7 @@ std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path)
std::vector<Uint8> buffer(size); std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size)) if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{ {
std::cerr << "Error al leer el fichero " << file_path << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al leer el fichero %s", file_path.c_str());
throw std::runtime_error("Error al leer el fichero: " + file_path); throw std::runtime_error("Error al leer el fichero: " + file_path);
} }
@@ -271,11 +271,11 @@ std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path)
std::vector<Uint8> rawPixels = gif.loadGif(buffer.data(), w, h); std::vector<Uint8> rawPixels = gif.loadGif(buffer.data(), w, h);
if (rawPixels.empty()) if (rawPixels.empty())
{ {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo cargar el GIF %s", file_path.c_str());
return nullptr; return nullptr;
} }
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>, // Si el constructor de Surface espera un std::shared_ptr<Uint8[]>:
// reservamos un bloque dinámico y copiamos los datos del vector.
size_t pixelCount = rawPixels.size(); size_t pixelCount = rawPixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixelCount], std::default_delete<Uint8[]>()); auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixelCount], std::default_delete<Uint8[]>());
std::memcpy(pixels.get(), rawPixels.data(), pixelCount); std::memcpy(pixels.get(), rawPixels.data(), pixelCount);
@@ -286,6 +286,7 @@ std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path)
width_ = w; width_ = w;
height_ = h; height_ = h;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "GIF %s cargado correctamente.", file_path.c_str());
return surface; return surface;
} }
@@ -325,8 +326,8 @@ std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
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)
{ {
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
else else
{ {
@@ -340,8 +341,8 @@ std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
std::vector<Uint8> buffer(size); std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size)) if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{ {
std::cerr << "Error: No se pudo leer completamente el fichero " << getFileName(file_path) << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo leer completamente el fichero %s", file_path.c_str());
throw std::runtime_error("Error al leer el fichero: " + getFileName(file_path)); throw std::runtime_error("Error al leer el fichero: " + file_path);
} }
// Usar la nueva función loadPalette, que devuelve un vector<uint32_t> // Usar la nueva función loadPalette, que devuelve un vector<uint32_t>
@@ -349,6 +350,7 @@ std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
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());
return palette; // Devuelve un vector vacío si no hay paleta return palette; // Devuelve un vector vacío si no hay paleta
} }
@@ -358,6 +360,7 @@ std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
palette.push_back((color << 8) | 0xFF); // Resultado: 0xRRGGBBAA palette.push_back((color << 8) | 0xFF); // Resultado: 0xRRGGBBAA
} }
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Paleta cargada correctamente desde %s", file_path.c_str());
return palette; return palette;
} }

View File

@@ -39,7 +39,7 @@ Title::Title()
// Configura objetos // Configura objetos
game_logo_->enable(); game_logo_->enable();
mini_logo_sprite_->setX(param.game.game_area.center_x - mini_logo_sprite_->getWidth() / 2); mini_logo_sprite_->setX(param.game.game_area.center_x - mini_logo_sprite_->getWidth() / 2);
fade_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b);
fade_->setType(FadeType::RANDOM_SQUARE); fade_->setType(FadeType::RANDOM_SQUARE);
fade_->setPostDuration(param.fade.post_duration); fade_->setPostDuration(param.fade.post_duration);
Resource::get()->getTexture("smb2.gif")->setPalette(1); Resource::get()->getTexture("smb2.gif")->setPalette(1);
@@ -87,7 +87,7 @@ void Title::render()
Screen::get()->start(); Screen::get()->start();
// Limpia la pantalla // Limpia la pantalla
Screen::get()->clean(bg_color); Screen::get()->clean(BG_COLOR);
// Dibuja el mosacico de fondo // Dibuja el mosacico de fondo
tiled_bg_->render(); tiled_bg_->render();
@@ -106,7 +106,7 @@ void Title::render()
mini_logo_sprite_->render(); mini_logo_sprite_->render();
// Texto con el copyright // Texto con el copyright
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, pos2, TEXT_COPYRIGHT, 1, no_color, 1, shadow); text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, pos2, TEXT_COPYRIGHT, 1, NO_COLOR, 1, shadow);
} }
if (state_ == TitleState::LOGO_FINISHED) if (state_ == TitleState::LOGO_FINISHED)
@@ -114,7 +114,7 @@ void Title::render()
// 'PRESS TO PLAY' // 'PRESS TO PLAY'
if (counter_ % 50 > 14 && !define_buttons_->isEnabled()) if (counter_ % 50 > 14 && !define_buttons_->isEnabled())
{ {
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, no_color, 1, shadow); text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, NO_COLOR, 1, shadow);
} }
} }
@@ -123,7 +123,7 @@ void Title::render()
// 'PRESS TO PLAY' // 'PRESS TO PLAY'
if (counter_ % 10 > 4 && !define_buttons_->isEnabled()) if (counter_ % 10 > 4 && !define_buttons_->isEnabled())
{ {
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, no_color, 1, shadow); text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, NO_COLOR, 1, shadow);
} }
} }

View File

@@ -1,36 +1,36 @@
#define _USE_MATH_DEFINES #define _USE_MATH_DEFINES
#include "utils.h" #include "utils.h"
#include <SDL3/SDL_iostream.h> // Para SDL_CloseIO, SDL_IOFromFile, SDL_ReadIO #include <SDL3/SDL_iostream.h> // Para SDL_CloseIO, SDL_IOFromFile, SDL_ReadIO
#include <SDL3/SDL_log.h> // Para SDL_LogCategory, SDL_LogError, SDL_Lo...
#include <stddef.h> // Para size_t #include <stddef.h> // Para size_t
#include <algorithm> // Para min, clamp, find_if_not, find, transform #include <algorithm> // Para min, clamp, find_if_not, find, transform
#include <cctype> // Para tolower, isspace #include <cctype> // Para tolower, isspace
#include <cmath> // Para pow, sin, M_PI, cos #include <cmath> // Para pow, sin, M_PI, cos
#include <compare> // Para operator< #include <compare> // Para operator<
#include <filesystem> // Para path #include <filesystem> // Para path
#include <iostream> // Para basic_ostream, cout, basic_ios, endl
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para basic_string, string, char_traits #include <string> // Para basic_string, string, operator==, ope...
#include "lang.h" // Para getText #include "lang.h" // Para getText
// Variables // Variables
Overrides overrides = Overrides(); Overrides overrides = Overrides();
// Colores // Colores
const Color bg_color = Color(0X27, 0X27, 0X36); const Color BG_COLOR = Color(0X27, 0X27, 0X36);
const Color no_color = Color(0XFF, 0XFF, 0XFF); const Color NO_COLOR = Color(0XFF, 0XFF, 0XFF);
const Color shdw_txt_color = Color(0X43, 0X43, 0X4F); const Color SHADOW_TEXT_COLOR = Color(0X43, 0X43, 0X4F);
const Color separator_color = Color(0X0D, 0X1A, 0X2B); const Color SEPARATOR_COLOR = Color(0X0D, 0X1A, 0X2B);
const Color scoreboard_easy_color = Color(0X4B, 0X69, 0X2F); const Color SCOREBOARD_EASY_COLOR = Color(0X4B, 0X69, 0X2F);
const Color scoreboard_normal_color = Color(0X2E, 0X3F, 0X47); const Color SCOREBOARD_NORMAL_COLOR = Color(0X2E, 0X3F, 0X47);
const Color scoreboard_hard_color = Color(0X76, 0X42, 0X8A); const Color SCOREBOARD_HARD_COLOR = Color(0X76, 0X42, 0X8A);
const Color flash_color = Color(0XFF, 0XFF, 0XFF); const Color FLASH_COLOR = Color(0XFF, 0XFF, 0XFF);
const Color fade_color = Color(0X27, 0X27, 0X36); const Color FADE_COLOR = Color(0X27, 0X27, 0X36);
const Color orange_color = Color(0XFF, 0X7A, 0X00); const Color ORANGE_COLOR = Color(0XFF, 0X7A, 0X00);
const Color orange_soft_color = Color(0XFF, 0XA0, 0X33); const Color ORANGE_SOFT_COLOR = Color(0XFF, 0XA0, 0X33);
const Color green_color = Color(0X5B, 0XEC, 0X95); const Color GREEN_COLOR = Color(0X5B, 0XEC, 0X95);
const Color blue_sky_color = Color(0X02, 0X88, 0XD1); const Color BLUE_SKY_COLOR = Color(0X02, 0X88, 0XD1);
const Color pink_sky_color = Color(0XFF, 0X6B, 0X97); const Color PINK_SKY_COLOR = Color(0XFF, 0X6B, 0X97);
const Color green_sky_color = Color(0X00, 0X79, 0X6B); const Color GREEN_SKY_COLOR = Color(0X00, 0X79, 0X6B);
// Obtiene un color del vector de colores imitando al Coche Fantástico // Obtiene un color del vector de colores imitando al Coche Fantástico
Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_) Color getColorLikeKnightRider(const std::vector<Color> &colors, int counter_)
@@ -299,17 +299,16 @@ bool stringInVector(const std::vector<std::string> &vec, const std::string &str)
return std::find(vec.begin(), vec.end(), str) != vec.end(); return std::find(vec.begin(), vec.end(), str) != vec.end();
} }
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos // Imprime por pantalla una línea de texto de tamaño fijo rellena con puntos
void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3) void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3)
{ {
std::cout.setf(std::ios::left, std::ios::adjustfield); std::string output = text1;
std::cout << text1; size_t dots_count = 50 - text1.length() - text3.length();
output.append(dots_count, '.');
output.append(text2);
output.append(text3);
std::cout.width(50 - text1.length() - text3.length()); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s", output.c_str());
std::cout.fill('.');
std::cout << text2;
std::cout << text3 << std::endl;
} }
// Carga el fichero de datos para la demo // Carga el fichero de datos para la demo
@@ -321,7 +320,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
auto file = SDL_IOFromFile(file_path.c_str(), "r+b"); auto file = SDL_IOFromFile(file_path.c_str(), "r+b");
if (!file) if (!file)
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
else else
@@ -357,21 +356,21 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd)
{ {
if (SDL_RWwrite(file, &data, sizeof(DemoKeys), 1) != 1) if (SDL_RWwrite(file, &data, sizeof(DemoKeys), 1) != 1)
{ {
std::cerr << "Error al escribir el fichero " << getFileName(file_path) << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al escribir el fichero %s", getFileName(file_path).c_str());
success = false; success = false;
break; break;
} }
} }
if (success) if (success)
{ {
std::cout << "Writing file " << getFileName(file_path).c_str() << std::endl; 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
{ {
std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl; SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to save %s file! %s", getFileName(file_path).c_str(), SDL_GetError());
success = false; success = false;
} }

View File

@@ -201,18 +201,18 @@ std::string getFileName(const std::string &path);
std::string getPath(const std::string &full_path); std::string getPath(const std::string &full_path);
// Colores // Colores
extern const Color bg_color; extern const Color BG_COLOR;
extern const Color no_color; extern const Color NO_COLOR;
extern const Color shdw_txt_color; extern const Color SHADOW_TEXT_COLOR;
extern const Color separator_color; extern const Color SEPARATOR_COLOR;
extern const Color scoreboard_easy_color; extern const Color SCOREBOARD_EASY_COLOR;
extern const Color scoreboard_normal_color; extern const Color SCOREBOARD_NORMAL_COLOR;
extern const Color scoreboard_hard_color; extern const Color SCOREBOARD_HARD_COLOR;
extern const Color flash_color; extern const Color FLASH_COLOR;
extern const Color fade_color; extern const Color FADE_COLOR;
extern const Color orange_color; extern const Color ORANGE_COLOR;
extern const Color orange_soft_color; extern const Color ORANGE_SOFT_COLOR;
extern const Color green_color; extern const Color GREEN_COLOR;
extern const Color blue_sky_color; extern const Color BLUE_SKY_COLOR;
extern const Color pink_sky_color; extern const Color PINK_SKY_COLOR;
extern const Color green_sky_color; extern const Color GREEN_SKY_COLOR;