neteja cppcheck (105 → 0)

This commit is contained in:
2026-05-16 19:35:23 +02:00
parent c9d16959d0
commit fcd2718794
48 changed files with 293 additions and 486 deletions
+3 -3
View File
@@ -265,13 +265,13 @@ inline JA_Music_t* JA_LoadMusic(const Uint8* buffer, Uint32 length) {
auto* music = new JA_Music_t();
music->ogg_data.assign(buffer, buffer + length);
int error = 0;
int err_code = 0;
music->vorbis = stb_vorbis_open_memory(music->ogg_data.data(),
static_cast<int>(length),
&error,
&err_code,
nullptr);
if (!music->vorbis) {
std::cout << "JA_LoadMusic: stb_vorbis_open_memory failed (error " << error << ")" << '\n';
std::cout << "JA_LoadMusic: stb_vorbis_open_memory failed (error " << err_code << ")" << '\n';
delete music;
return nullptr;
}
+5 -5
View File
@@ -1,6 +1,7 @@
#include "core/input/define_buttons.hpp"
#include <algorithm> // Para __all_of_fn, all_of
#include <algorithm> // Para __all_of_fn, all_of, ranges::transform
#include <iterator> // Para back_inserter
#include <memory> // Para unique_ptr, allocator, shared_ptr, operator==, make_unique
#include "core/input/input.hpp" // Para Input
@@ -16,10 +17,9 @@ DefineButtons::DefineButtons()
: input_(Input::get()) {
clearButtons();
auto gamepads = input_->getGamepads();
for (const auto& gamepad : gamepads) {
controller_names_.emplace_back(Input::getControllerName(gamepad));
}
const auto gamepads = input_->getGamepads();
controller_names_.reserve(gamepads.size());
std::ranges::transform(gamepads, std::back_inserter(controller_names_), Input::getControllerName);
// Crear la ventana de mensaje
WindowMessage::Config config(param.service_menu.window_message);
+24 -70
View File
@@ -118,53 +118,22 @@ auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const s
// Comprueba si hay almenos una acción activa
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
const auto JUST_PRESSED = [](const auto& pair) { return pair.second.just_pressed; };
// --- Comprobación del Teclado ---
if (check_keyboard) {
for (const auto& pair : keyboard_.bindings) {
// Simplemente leemos el estado pre-calculado por Input::update().
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
if (pair.second.just_pressed) {
return true; // Se encontró una acción recién pulsada.
}
}
if (check_keyboard && std::ranges::any_of(keyboard_.bindings, JUST_PRESSED)) {
return true;
}
// --- Comprobación del Mando ---
// Comprobamos si hay mandos y si el índice solicitado es válido.
if (gamepad != nullptr) {
// Iteramos sobre todas las acciones, no sobre el número de mandos.
for (const auto& pair : gamepad->bindings) {
// Leemos el estado pre-calculado para el mando y la acción específicos.
if (pair.second.just_pressed) {
return true; // Se encontró una acción recién pulsada en el mando.
}
}
}
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
return false;
return gamepad != nullptr && std::ranges::any_of(gamepad->bindings, JUST_PRESSED);
}
// Comprueba si hay algún botón pulsado
auto Input::checkAnyButton(bool repeat) -> bool {
// Solo comprueba los botones definidos previamente
for (auto bi : BUTTON_INPUTS) {
// Comprueba el teclado
if (checkAction(bi, repeat, CHECK_KEYBOARD)) {
return true;
}
// Comprueba los mandos
for (const auto& gamepad : gamepads_) {
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
return true;
}
}
}
return false;
return std::ranges::any_of(BUTTON_INPUTS, [this, repeat](auto bi) {
if (checkAction(bi, repeat, CHECK_KEYBOARD)) { return true; }
return std::ranges::any_of(gamepads_, [this, bi, repeat](const auto& gamepad) {
return checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad);
});
});
}
// Comprueba si hay algun mando conectado
@@ -178,9 +147,8 @@ auto Input::getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::s
// Obtiene la lista de nombres de mandos
auto Input::getControllerNames() const -> std::vector<std::string> {
std::vector<std::string> names;
for (const auto& gamepad : gamepads_) {
names.push_back(gamepad->name);
}
names.reserve(gamepads_.size());
std::ranges::transform(gamepads_, std::back_inserter(names), [](const auto& gamepad) { return gamepad->name; });
return names;
}
@@ -189,21 +157,15 @@ auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
// Obtiene el gamepad a partir de un event.id
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
for (const auto& gamepad : gamepads_) {
if (gamepad->instance_id == id) {
return gamepad;
}
}
return nullptr;
const auto it = std::ranges::find_if(gamepads_,
[id](const auto& gamepad) { return gamepad->instance_id == id; });
return it != gamepads_.end() ? *it : nullptr;
}
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
for (const auto& gamepad : gamepads_) {
if (gamepad && gamepad->name == name) {
return gamepad;
}
}
return nullptr;
const auto it = std::ranges::find_if(gamepads_,
[&name](const auto& gamepad) { return gamepad && gamepad->name == name; });
return it != gamepads_.end() ? *it : nullptr;
}
// Obtiene el SDL_GamepadButton asignado a un action
@@ -359,7 +321,7 @@ void Input::resetInputStates() {
key.second.just_pressed = false;
}
// Resetear todos los ControllerBindings.active a false
for (auto& gamepad : gamepads_) {
for (const auto& gamepad : gamepads_) {
for (auto& binding : gamepad->bindings) {
binding.second.is_held = false;
binding.second.just_pressed = false;
@@ -568,19 +530,11 @@ auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::
}
// Buscar por nombre
for (const auto& gamepad : gamepads_) {
if (gamepad && gamepad->name == gamepad_name) {
return gamepad;
}
}
auto by_name = std::ranges::find_if(gamepads_,
[&gamepad_name](const auto& gamepad) { return gamepad && gamepad->name == gamepad_name; });
if (by_name != gamepads_.end()) { return *by_name; }
// Si no se encuentra por nombre, devolver el primer gamepad válido
for (const auto& gamepad : gamepads_) {
if (gamepad) {
return gamepad;
}
}
// Si llegamos aquí, no hay gamepads válidos
return nullptr;
auto first_valid = std::ranges::find_if(gamepads_, [](const auto& gamepad) { return gamepad != nullptr; });
return first_valid != gamepads_.end() ? *first_valid : nullptr;
}
+4 -4
View File
@@ -32,7 +32,7 @@ class Input {
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
explicit KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
: scancode(scancode),
is_held(is_held),
just_pressed(just_pressed) {}
@@ -45,7 +45,7 @@ class Input {
bool axis_active; // Estado del eje
bool trigger_active{false}; // Estado del trigger como botón digital
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
explicit ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn),
is_held(is_held),
just_pressed(just_pressed),
@@ -115,7 +115,7 @@ class Input {
return s;
}
Gamepad(SDL_Gamepad* gamepad)
explicit Gamepad(SDL_Gamepad* gamepad)
: pad(gamepad),
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
name(trimName(SDL_GetGamepadName(gamepad))),
@@ -148,7 +148,7 @@ class Input {
// Reasigna un botón a una acción
void rebindAction(Action action, SDL_GamepadButton new_button) {
bindings[action] = static_cast<int>(new_button);
bindings[action] = ButtonState{static_cast<int>(new_button)};
}
};
+13 -24
View File
@@ -1,9 +1,11 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <utility>
#include <vector>
// --- Clase PauseManager: maneja el sistema de pausa del juego ---
class PauseManager {
@@ -48,7 +50,7 @@ class PauseManager {
// --- Métodos principales ---
void setFlag(Source source, bool enable) { // Establece/quita una fuente de pausa específica
bool was_paused = isPaused();
const bool WAS_PAUSED = isPaused();
if (enable) {
flags_ |= source;
@@ -56,7 +58,8 @@ class PauseManager {
flags_ &= ~source; // Ahora funciona: Source &= uint8_t
}
if (was_paused != isPaused()) {
// cppcheck-suppress knownConditionTrueFalse // false-positive: flags_ ha estat modificat entre les dues crides a isPaused()
if (WAS_PAUSED != isPaused()) {
notifyPauseChanged();
}
}
@@ -88,30 +91,16 @@ class PauseManager {
return "Active";
}
std::vector<std::string> parts;
if (hasFlag(Source::PLAYER)) { parts.emplace_back("Player"); }
if (hasFlag(Source::SERVICE_MENU)) { parts.emplace_back("ServiceMenu"); }
if (hasFlag(Source::FOCUS_LOST)) { parts.emplace_back("FocusLoss"); }
std::string result = "Paused by: ";
bool first = true;
if (hasFlag(Source::PLAYER)) {
if (!first) {
result += ", ";
}
result += "Player";
first = false;
for (size_t i = 0; i < parts.size(); ++i) {
if (i > 0) { result += ", "; }
result += parts[i];
}
if (hasFlag(Source::SERVICE_MENU)) {
if (!first) {
result += ", ";
}
result += "ServiceMenu";
first = false;
}
if (hasFlag(Source::FOCUS_LOST)) {
if (!first) {
result += ", ";
}
result += "FocusLoss";
}
return result;
}
void setCallback(std::function<void(bool)> callback) { // Permite cambiar el callback en runtime
+14 -28
View File
@@ -1,5 +1,6 @@
#include "core/locale/lang.hpp"
#include <algorithm> // Para ranges::find_if
#include <cstddef> // Para size_t
#include <exception> // Para exception
#include <fstream> // Para basic_ifstream, basic_istream, ifstream
@@ -80,35 +81,23 @@ namespace Lang {
// Obtiene un idioma del vector de idiomas a partir de un código
auto getLanguage(Code code) -> Language {
for (const auto& lang : languages) {
if (lang.code == code) {
return lang;
}
}
// Si no se encuentra, devuelve el primero por defecto
return languages[0];
const auto it = std::ranges::find_if(languages,
[code](const auto& lang) { return lang.code == code; });
return it != languages.end() ? *it : languages[0];
}
// Devuelve el código de un idioma a partir de un nombre
auto getCodeFromName(const std::string& name) -> Code {
for (const auto& lang : languages) {
if (lang.name == name) {
return lang.code;
}
}
// Si no se encuentra, devuelve el primero por defecto
return languages[0].code;
const auto it = std::ranges::find_if(languages,
[&name](const auto& lang) { return lang.name == name; });
return it != languages.end() ? it->code : languages[0].code;
}
// Devuelve el nombre de un idioma a partir de un código
auto getNameFromCode(Code code) -> std::string {
for (const auto& lang : languages) {
if (lang.code == code) {
return lang.name;
}
}
// Si no se encuentra, devuelve el nombre del primer idioma por defecto
return languages[0].name;
const auto it = std::ranges::find_if(languages,
[code](const auto& lang) { return lang.code == code; });
return it != languages.end() ? it->name : languages[0].name;
}
// Actualiza los nombres de los idiomas
@@ -155,13 +144,10 @@ namespace Lang {
// Obtiene una fichero a partir de un lang::Code
auto getLanguageFileName(Lang::Code code) -> std::string {
for (const auto& lang : languages) {
if (lang.code == code) {
return Asset::get()->getPath(lang.file_name);
}
}
// Si no se encuentra, devuelve el fichero del primer idioma por defecto
return Asset::get()->getPath(languages[0].file_name);
const auto it = std::ranges::find_if(languages,
[code](const auto& lang) { return lang.code == code; });
const auto& file = (it != languages.end()) ? it->file_name : languages[0].file_name;
return Asset::get()->getPath(file);
}
// Establece el idioma
+4 -5
View File
@@ -562,14 +562,13 @@ void Background::createMoonPath() {
const int FREEZE_START_INDEX = static_cast<int>(NUM_STEPS * (1.0F - FREEZE_PERCENTAGE));
for (int i = 0; i < NUM_STEPS; ++i) {
double theta = i * STEP;
float x = CENTER_X + (RADIUS * cos(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
if (i >= FREEZE_START_INDEX && !moon_path_.empty()) {
moon_path_.push_back(moon_path_.back()); // Repite el último punto válido
} else {
moon_path_.push_back({.x = x, .y = y});
const double THETA = i * STEP;
const float X = CENTER_X + (RADIUS * cos(THETA));
const float Y = CENTER_Y - (RADIUS * sin(THETA));
moon_path_.push_back({.x = X, .y = Y});
}
}
}
+2 -2
View File
@@ -28,8 +28,8 @@ class Background {
using ProgressCallback = std::function<void(float)>; // Callback para sincronización
// --- Constructor y destructor ---
Background(float total_progress_to_complete = 6100.0F); // Constructor principal
~Background(); // Destructor
explicit Background(float total_progress_to_complete = 6100.0F); // Constructor principal
~Background(); // Destructor
// --- Métodos principales ---
void update(float delta_time); // Actualiza la lógica del objeto
+1 -1
View File
@@ -66,7 +66,7 @@ class Screen {
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
// --- Display Monitor getters ---
[[nodiscard]] auto getDisplayMonitorName() const -> std::string { return display_monitor_.name; }
[[nodiscard]] auto getDisplayMonitorName() const -> const std::string& { return display_monitor_.name; }
[[nodiscard]] auto getDisplayMonitorWidth() const -> int { return display_monitor_.width; }
[[nodiscard]] auto getDisplayMonitorHeight() const -> int { return display_monitor_.height; }
[[nodiscard]] auto getDisplayMonitorRefreshRate() const -> int { return display_monitor_.refresh_rate; }
+6 -6
View File
@@ -25,12 +25,12 @@ enum class PathCentered { // Centrado del recorrido
// --- Estructuras ---
struct Path { // Define un recorrido para el sprite
float start_pos; // Posición inicial
float end_pos; // Posición final
PathType type; // Tipo de movimiento (horizontal/vertical)
float fixed_pos; // Posición fija en el eje contrario
float duration_s; // Duración de la animación en segundos
float waiting_time_s; // Tiempo de espera una vez en el destino
float start_pos = 0.0F; // Posición inicial
float end_pos = 0.0F; // Posición final
PathType type = PathType::HORIZONTAL; // Tipo de movimiento (horizontal/vertical)
float fixed_pos = 0.0F; // Posición fija en el eje contrario
float duration_s = 0.0F; // Duración de la animación en segundos
float waiting_time_s = 0.0F; // Tiempo de espera una vez en el destino
std::function<double(double)> easing_function; // Función de easing
float elapsed_time = 0.0F; // Tiempo transcurrido
float waiting_elapsed = 0.0F; // Tiempo de espera transcurrido
+1 -2
View File
@@ -403,9 +403,8 @@ auto Text::loadFile(const std::string& file_path) -> std::shared_ptr<Text::File>
file.open(file_path);
}
std::istream& input_stream = using_resource_data ? stream : static_cast<std::istream&>(file);
if ((using_resource_data && stream.good()) || (!using_resource_data && file.is_open() && file.good())) {
std::istream& input_stream = using_resource_data ? stream : static_cast<std::istream&>(file);
std::string buffer;
// Lee los dos primeros valores del fichero
+1 -1
View File
@@ -39,7 +39,7 @@ class Text {
int kerning;
// Constructor con argumentos por defecto
Style(Uint8 flags = 0,
explicit Style(Uint8 flags = 0,
Color text = Color(),
Color shadow = Color(),
Uint8 distance = 1,
+54 -73
View File
@@ -2,12 +2,14 @@
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError, SDL_SetRenderDrawColor, SDL_EventType, SDL_PollEvent, SDL_RenderFillRect, SDL_RenderRect, SDLK_ESCAPE, SDL_Event
#include <algorithm> // Para ranges::transform, ranges::find_if
#include <array> // Para array
#include <cstdlib> // Para exit
#include <exception> // Para exception
#include <filesystem> // Para exists, path, remove
#include <fstream> // Para basic_ofstream, basic_ios, basic_ostream::write, ios, ofstream
#include <iostream> // Para std::cout
#include <iterator> // Para back_inserter
#include <ranges> // Para __find_if_fn, find_if, __find_fn, find
#include <stdexcept> // Para runtime_error
#include <utility> // Para move
@@ -138,40 +140,37 @@ void Resource::loadEssentialTextures() {
// Inicializa las listas de recursos sin cargar el contenido (modo lazy)
void Resource::initResourceLists() {
const auto file_to_name = [](const auto& file) { return getFileName(file); };
// Inicializa lista de sonidos
auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND);
const auto sound_list = Asset::get()->getListByType(Asset::Type::SOUND);
sounds_.clear();
for (const auto& file : sound_list) {
sounds_.emplace_back(getFileName(file));
}
sounds_.reserve(sound_list.size());
std::ranges::transform(sound_list, std::back_inserter(sounds_), [&](const auto& file) { return ResourceSound(file_to_name(file)); });
// Inicializa lista de músicas
auto music_list = Asset::get()->getListByType(Asset::Type::MUSIC);
const auto music_list = Asset::get()->getListByType(Asset::Type::MUSIC);
musics_.clear();
for (const auto& file : music_list) {
musics_.emplace_back(getFileName(file));
}
musics_.reserve(music_list.size());
std::ranges::transform(music_list, std::back_inserter(musics_), [&](const auto& file) { return ResourceMusic(file_to_name(file)); });
// Inicializa lista de texturas
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
const auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
textures_.clear();
for (const auto& file : texture_list) {
textures_.emplace_back(getFileName(file));
}
textures_.reserve(texture_list.size());
std::ranges::transform(texture_list, std::back_inserter(textures_), [&](const auto& file) { return ResourceTexture(file_to_name(file)); });
// Inicializa lista de ficheros de texto
auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
const auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
text_files_.clear();
for (const auto& file : text_file_list) {
text_files_.emplace_back(getFileName(file));
}
text_files_.reserve(text_file_list.size());
std::ranges::transform(text_file_list, std::back_inserter(text_files_), [&](const auto& file) { return ResourceTextFile(file_to_name(file)); });
// Inicializa lista de animaciones
auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
const auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
animations_.clear();
for (const auto& file : animation_list) {
animations_.emplace_back(getFileName(file));
}
animations_.reserve(animation_list.size());
std::ranges::transform(animation_list, std::back_inserter(animations_), [&](const auto& file) { return ResourceAnimation(file_to_name(file)); });
// Los demos se cargan directamente sin mostrar progreso (son pocos y pequeños)
loadDemoDataQuiet();
@@ -192,9 +191,8 @@ void Resource::initResourceLists() {
"smb2_grad"};
texts_.clear();
for (const auto& text_name : TEXT_OBJECTS) {
texts_.emplace_back(text_name); // Constructor con nullptr por defecto
}
texts_.reserve(TEXT_OBJECTS.size());
std::ranges::transform(TEXT_OBJECTS, std::back_inserter(texts_), [](const auto& text_name) { return ResourceText(text_name); });
}
// Obtiene el sonido a partir de un nombre (con carga perezosa)
@@ -336,23 +334,17 @@ auto Resource::loadMusicLazy(const std::string& name) -> JA_Music_t* {
}
auto Resource::loadTextureLazy(const std::string& name) -> std::shared_ptr<Texture> {
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
for (const auto& file : texture_list) {
if (getFileName(file) == name) {
return std::make_shared<Texture>(Screen::get()->getRenderer(), file);
}
}
return nullptr;
const auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
const auto it = std::ranges::find_if(texture_list,
[&name](const auto& file) { return getFileName(file) == name; });
return it != texture_list.end() ? std::make_shared<Texture>(Screen::get()->getRenderer(), *it) : nullptr;
}
auto Resource::loadTextFileLazy(const std::string& name) -> std::shared_ptr<Text::File> {
auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
for (const auto& file : text_file_list) {
if (getFileName(file) == name) {
return Text::loadFile(file);
}
}
return nullptr;
const auto text_file_list = Asset::get()->getListByType(Asset::Type::FONT);
const auto it = std::ranges::find_if(text_file_list,
[&name](const auto& file) { return getFileName(file) == name; });
return it != text_file_list.end() ? Text::loadFile(*it) : nullptr;
}
auto Resource::loadTextLazy(const std::string& name) -> std::shared_ptr<Text> {
@@ -377,27 +369,22 @@ auto Resource::loadTextLazy(const std::string& name) -> std::shared_ptr<Text> {
{.key = "smb2", .texture_file = "smb2.png", .text_file = "smb2.txt"},
{.key = "smb2_grad", .texture_file = "smb2_grad.png", .text_file = "smb2.txt"}};
for (const auto& mapping : TEXT_MAPPINGS) {
if (mapping.key == name) {
// Cargar las dependencias automáticamente
auto texture = getTexture(mapping.texture_file); // Esto cargará la textura si no está cargada
auto text_file = getTextFile(mapping.text_file); // Esto cargará el archivo de texto si no está cargado
if (texture && text_file) {
return std::make_shared<Text>(texture, text_file);
}
}
const auto it = std::ranges::find_if(TEXT_MAPPINGS,
[&name](const auto& mapping) { return mapping.key == name; });
if (it == TEXT_MAPPINGS.end()) {
return nullptr;
}
return nullptr;
auto texture = getTexture(it->texture_file); // Esto cargará la textura si no está cargada
auto text_file = getTextFile(it->text_file); // Esto cargará el archivo de texto si no está cargado
return (texture && text_file) ? std::make_shared<Text>(texture, text_file) : nullptr;
}
auto Resource::loadAnimationLazy(const std::string& name) -> AnimationsFileBuffer {
auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
for (const auto& file : animation_list) {
if (getFileName(file) == name) {
return loadAnimationsFromFile(file);
}
const auto animation_list = Asset::get()->getListByType(Asset::Type::ANIMATION);
const auto it = std::ranges::find_if(animation_list,
[&name](const auto& file) { return getFileName(file) == name; });
if (it != animation_list.end()) {
return loadAnimationsFromFile(*it);
}
// Si no se encuentra, retorna vector vacío
return AnimationsFileBuffer{};
@@ -640,14 +627,10 @@ void Resource::createPlayerTextures() {
const auto& player = players[player_idx]; // Obtenemos el jugador actual
// Encontrar el archivo original de la textura
std::string texture_file_path;
auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
for (const auto& file : texture_list) {
if (getFileName(file) == player.base_texture) {
texture_file_path = file;
break;
}
}
const auto texture_list = Asset::get()->getListByType(Asset::Type::BITMAP);
const auto it = std::ranges::find_if(texture_list,
[&player](const auto& file) { return getFileName(file) == player.base_texture; });
const std::string texture_file_path = (it != texture_list.end()) ? *it : std::string{};
// Crear las 4 texturas con sus respectivas paletas
for (int palette_idx = 0; palette_idx < 4; ++palette_idx) {
@@ -720,9 +703,9 @@ void Resource::createTextTextures() {
{"game_text_1000000_points", Lang::getText("[GAME_TEXT] 8")}};
auto text1 = getText("04b_25_enhanced");
for (const auto& s : strings1) {
textures_.emplace_back(s.name, text1->writeDXToTexture(Text::STROKE, s.text, -2, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
}
std::ranges::transform(strings1, std::back_inserter(textures_), [&](const auto& s) {
return ResourceTexture(s.name, text1->writeDXToTexture(Text::STROKE, s.text, -2, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
});
// Texturas de tamaño doble
std::vector<NameAndText> strings2 = {
@@ -734,9 +717,9 @@ void Resource::createTextTextures() {
{"game_text_game_over", "Game Over"}};
auto text2 = getText("04b_25_2x_enhanced");
for (const auto& s : strings2) {
textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
}
std::ranges::transform(strings2, std::back_inserter(textures_), [&](const auto& s) {
return ResourceTexture(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
});
}
// Crea los objetos de texto a partir de los archivos de textura y texto
@@ -897,12 +880,10 @@ void Resource::renderProgress() {
// Carga los datos para el modo demostración (sin mostrar progreso)
void Resource::loadDemoDataQuiet() {
auto list = Asset::get()->getListByType(Asset::Type::DEMODATA);
const auto list = Asset::get()->getListByType(Asset::Type::DEMODATA);
demos_.clear();
for (const auto& l : list) {
demos_.emplace_back(loadDemoDataFromFile(l));
}
demos_.reserve(list.size());
std::ranges::transform(list, std::back_inserter(demos_), [this](const auto& l) { return loadDemoDataFromFile(l); });
}
// Inicializa los rectangulos que definen la barra de progreso
+7 -7
View File
@@ -60,7 +60,7 @@ class Resource {
std::string name; // Nombre del sonido
JA_Sound_t* sound; // Objeto con el sonido
ResourceSound(std::string name, JA_Sound_t* sound = nullptr)
explicit ResourceSound(std::string name, JA_Sound_t* sound = nullptr)
: name(std::move(name)),
sound(sound) {}
};
@@ -69,7 +69,7 @@ class Resource {
std::string name; // Nombre de la música
JA_Music_t* music; // Objeto con la música
ResourceMusic(std::string name, JA_Music_t* music = nullptr)
explicit ResourceMusic(std::string name, JA_Music_t* music = nullptr)
: name(std::move(name)),
music(music) {}
};
@@ -78,7 +78,7 @@ class Resource {
std::string name; // Nombre de la textura
std::shared_ptr<Texture> texture; // Objeto con la textura
ResourceTexture(std::string name, std::shared_ptr<Texture> texture = nullptr)
explicit ResourceTexture(std::string name, std::shared_ptr<Texture> texture = nullptr)
: name(std::move(name)),
texture(std::move(texture)) {}
};
@@ -87,7 +87,7 @@ class Resource {
std::string name; // Nombre del fichero
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto
ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file = nullptr)
explicit ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file = nullptr)
: name(std::move(name)),
text_file(std::move(text_file)) {}
};
@@ -96,7 +96,7 @@ class Resource {
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto de texto
ResourceText(std::string name, std::shared_ptr<Text> text = nullptr)
explicit ResourceText(std::string name, std::shared_ptr<Text> text = nullptr)
: name(std::move(name)),
text(std::move(text)) {}
};
@@ -105,7 +105,7 @@ class Resource {
std::string name; // Nombre de la animación
AnimationsFileBuffer animation; // Objeto con las animaciones
ResourceAnimation(std::string name, AnimationsFileBuffer animation = {})
explicit ResourceAnimation(std::string name, AnimationsFileBuffer animation = {})
: name(std::move(name)),
animation(std::move(animation)) {}
};
@@ -116,7 +116,7 @@ class Resource {
size_t loaded{0}; // Número de recursos cargados
ResourceCount() = default;
ResourceCount(size_t total)
explicit ResourceCount(size_t total)
: total(total) {}
void add(size_t amount) { loaded += amount; }
+3 -25
View File
@@ -1,10 +1,8 @@
#pragma once
#include <cstdint> // Para uint8_t
#include <filesystem> // Para remove, path
#include <fstream> // Para basic_ofstream, basic_ios, basic_ostream::write, ios, ofstream
#include <string> // Para string, basic_string, hash, operator+, to_string, __str_hash_base
#include <vector> // Para vector
#include <cstdint> // Para uint8_t
#include <string> // Para string
#include <vector> // Para vector
// Helper functions para integrar ResourceLoader con el sistema existente
namespace ResourceHelper {
@@ -22,24 +20,4 @@ namespace ResourceHelper {
// Convierte ruta Asset a ruta relativa para ResourceLoader
auto getPackPath(const std::string& asset_path) -> std::string;
// Wrappea la carga de archivos para mantener compatibilidad
template <typename T>
auto loadResourceFile(const std::string& asset_path, T* (*loader_func)(const char*)) -> T* {
auto data = loadFile(asset_path);
if (data.empty()) {
return loader_func(asset_path.c_str());
}
// Crear archivo temporal para funciones que esperan path
std::string temp_path = "/tmp/ccae_" + std::to_string(std::hash<std::string>{}(asset_path));
std::ofstream temp_file(temp_path, std::ios::binary);
temp_file.write(reinterpret_cast<const char*>(data.data()), data.size());
temp_file.close();
T* result = loader_func(temp_path.c_str());
std::filesystem::remove(temp_path);
return result;
}
} // namespace ResourceHelper
+10 -17
View File
@@ -1,10 +1,11 @@
#include "core/resources/resource_pack.hpp"
#include <algorithm> // Para replace
#include <algorithm> // Para replace, ranges::all_of
#include <array> // Para array
#include <filesystem> // Para path, recursive_directory_iterator, directory_entry, exists, relative
#include <fstream> // Para basic_ifstream, basic_ostream, basic_ofstream, operator<<, basic_ios, basic_istream::read, basic_ostream::write, endl, ios, basic_istream, ifstream, operator|, basic_istream::seekg, basic_istream::tellg, ofstream, streamsize
#include <iostream> // Para cerr
#include <numeric> // Para accumulate
#include <utility> // Para pair
const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCAE_RESOURCES__2024";
@@ -17,11 +18,7 @@ ResourcePack::~ResourcePack() {
}
auto ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t {
uint32_t checksum = 0x12345678;
for (unsigned char i : data) {
checksum = ((checksum << 5) + checksum) + i;
}
return checksum;
return std::accumulate(data.begin(), data.end(), static_cast<uint32_t>(0x12345678), [](uint32_t checksum, unsigned char i) { return ((checksum << 5) + checksum) + i; });
}
void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
@@ -162,20 +159,16 @@ auto ResourcePack::addDirectory(const std::string& directory) -> bool {
return false; // NOLINT(readability-simplify-boolean-expr)
}
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) {
if (entry.is_regular_file()) {
return std::ranges::all_of(std::filesystem::recursive_directory_iterator(directory),
[this, &directory](const auto& entry) {
if (!entry.is_regular_file()) {
return true;
}
std::string filepath = entry.path().string();
std::string filename = std::filesystem::relative(entry.path(), directory).string();
std::ranges::replace(filename, '\\', '/');
if (!addFile(filename, filepath)) {
return false;
}
}
}
return true;
return addFile(filename, filepath);
});
}
auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8_t> {
+1 -1
View File
@@ -520,7 +520,7 @@ auto Director::iterate() -> SDL_AppResult {
}
// Procesa un evento SDL (llamado desde SDL_AppEvent)
auto Director::handleEvent(SDL_Event& event) -> SDL_AppResult {
auto Director::handleEvent(const SDL_Event& event) -> SDL_AppResult {
// Eventos globales (SDL_EVENT_QUIT, resize, render target reset, hotplug, service menu, ratón)
GlobalEvents::handle(event);
+2 -2
View File
@@ -29,8 +29,8 @@ class Director {
~Director();
// --- Callbacks para SDL_MAIN_USE_CALLBACKS ---
auto iterate() -> SDL_AppResult; // Avanza un frame de la sección activa
auto handleEvent(SDL_Event& event) -> SDL_AppResult; // Procesa un evento SDL
auto iterate() -> SDL_AppResult; // Avanza un frame de la sección activa
auto handleEvent(const SDL_Event& event) -> SDL_AppResult; // Procesa un evento SDL
// --- Debug config (accesible desde otras clases) ---
struct DebugConfig {