clang-format

This commit is contained in:
2026-03-21 23:19:15 +01:00
parent 55b58ded70
commit 366c00fd22
68 changed files with 5585 additions and 5603 deletions

View File

@@ -5,93 +5,93 @@
// --- Clase Audio: gestor de audio (singleton) ---
class Audio {
public:
// --- Enums ---
enum class Group : int {
ALL = -1, // Todos los grupos
GAME = 0, // Sonidos del juego
INTERFACE = 1 // Sonidos de la interfaz
};
public:
// --- Enums ---
enum class Group : int {
ALL = -1, // Todos los grupos
GAME = 0, // Sonidos del juego
INTERFACE = 1 // Sonidos de la interfaz
};
enum class MusicState {
PLAYING, // Reproduciendo música
PAUSED, // Música pausada
STOPPED, // Música detenida
};
enum class MusicState {
PLAYING, // Reproduciendo música
PAUSED, // Música pausada
STOPPED, // Música detenida
};
// --- Constantes ---
static constexpr float MAX_VOLUME = 1.0F; // Volumen máximo
static constexpr float MIN_VOLUME = 0.0F; // Volumen mínimo
static constexpr int FREQUENCY = 48000; // Frecuencia de audio
// --- Constantes ---
static constexpr float MAX_VOLUME = 1.0F; // Volumen máximo
static constexpr float MIN_VOLUME = 0.0F; // Volumen mínimo
static constexpr int FREQUENCY = 48000; // Frecuencia de audio
// --- Singleton ---
static void init(); // Inicializa el objeto Audio
static void destroy(); // Libera el objeto Audio
static auto get() -> Audio*; // Obtiene el puntero al objeto Audio
Audio(const Audio&) = delete; // Evitar copia
auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación
// --- Singleton ---
static void init(); // Inicializa el objeto Audio
static void destroy(); // Libera el objeto Audio
static auto get() -> Audio*; // Obtiene el puntero al objeto Audio
Audio(const Audio&) = delete; // Evitar copia
auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación
static void update(); // Actualización del sistema de audio
static void update(); // Actualización del sistema de audio
// --- Control de música ---
void playMusic(const std::string& name, int loop = -1); // Reproducir música en bucle
void pauseMusic(); // Pausar reproducción de música
void resumeMusic(); // Continua la música pausada
void stopMusic(); // Detener completamente la música
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
// --- Control de música ---
void playMusic(const std::string& name, int loop = -1); // Reproducir música en bucle
void pauseMusic(); // Pausar reproducción de música
void resumeMusic(); // Continua la música pausada
void stopMusic(); // Detener completamente la música
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
// --- Control de sonidos ---
void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual por nombre
void playSound(struct JA_Sound_t* sound, Group group = Group::GAME) const; // Reproducir sonido puntual por puntero
void stopAllSounds() const; // Detener todos los sonidos
// --- Control de sonidos ---
void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual por nombre
void playSound(struct JA_Sound_t* sound, Group group = Group::GAME) const; // Reproducir sonido puntual por puntero
void stopAllSounds() const; // Detener todos los sonidos
// --- Control de volumen ---
void setSoundVolume(float volume, Group group = Group::ALL) const; // Ajustar volumen de efectos
void setMusicVolume(float volume) const; // Ajustar volumen de música
// --- Control de volumen ---
void setSoundVolume(float volume, Group group = Group::ALL) const; // Ajustar volumen de efectos
void setMusicVolume(float volume) const; // Ajustar volumen de música
// --- Configuración general ---
void enable(bool value); // Establecer estado general
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general
void applySettings(); // Aplica la configuración
// --- Configuración general ---
void enable(bool value); // Establecer estado general
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general
void applySettings(); // Aplica la configuración
// --- Configuración de sonidos ---
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos
// --- Configuración de sonidos ---
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos
// --- Configuración de música ---
void enableMusic() { music_enabled_ = true; } // Habilitar música
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música
// --- Configuración de música ---
void enableMusic() { music_enabled_ = true; } // Habilitar música
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música
// --- Consultas de estado ---
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto isSoundEnabled() const -> bool { return sound_enabled_; }
[[nodiscard]] auto isMusicEnabled() const -> bool { return music_enabled_; }
[[nodiscard]] auto getMusicState() const -> MusicState { return music_.state; }
[[nodiscard]] static auto getRealMusicState() -> MusicState;
[[nodiscard]] auto getCurrentMusicName() const -> const std::string& { return music_.name; }
// --- Consultas de estado ---
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto isSoundEnabled() const -> bool { return sound_enabled_; }
[[nodiscard]] auto isMusicEnabled() const -> bool { return music_enabled_; }
[[nodiscard]] auto getMusicState() const -> MusicState { return music_.state; }
[[nodiscard]] static auto getRealMusicState() -> MusicState;
[[nodiscard]] auto getCurrentMusicName() const -> const std::string& { return music_.name; }
private:
// --- Tipos anidados ---
struct Music {
MusicState state{MusicState::STOPPED}; // Estado actual de la música
std::string name; // Última pista de música reproducida
bool loop{false}; // Indica si se reproduce en bucle
};
private:
// --- Tipos anidados ---
struct Music {
MusicState state{MusicState::STOPPED}; // Estado actual de la música
std::string name; // Última pista de música reproducida
bool loop{false}; // Indica si se reproduce en bucle
};
// --- Métodos ---
Audio(); // Constructor privado
~Audio(); // Destructor privado
void initSDLAudio(); // Inicializa SDL Audio
// --- Métodos ---
Audio(); // Constructor privado
~Audio(); // Destructor privado
void initSDLAudio(); // Inicializa SDL Audio
// --- Variables miembro ---
static Audio* instance; // Instancia única de Audio
// --- Variables miembro ---
static Audio* instance; // Instancia única de Audio
Music music_; // Estado de la música
bool enabled_{true}; // Estado general del audio
bool sound_enabled_{true}; // Estado de los efectos de sonido
bool music_enabled_{true}; // Estado de la música
Music music_; // Estado de la música
bool enabled_{true}; // Estado general del audio
bool sound_enabled_{true}; // Estado de los efectos de sonido
bool music_enabled_{true}; // Estado de la música
};

View File

@@ -27,30 +27,30 @@ enum JA_Music_state { JA_MUSIC_INVALID,
#define JA_MAX_GROUPS 2
struct JA_Sound_t {
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0};
Uint8* buffer{NULL};
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0};
Uint8* buffer{NULL};
};
struct JA_Channel_t {
JA_Sound_t* sound{nullptr};
int pos{0};
int times{0};
int group{0};
SDL_AudioStream* stream{nullptr};
JA_Channel_state state{JA_CHANNEL_FREE};
JA_Sound_t* sound{nullptr};
int pos{0};
int times{0};
int group{0};
SDL_AudioStream* stream{nullptr};
JA_Channel_state state{JA_CHANNEL_FREE};
};
struct JA_Music_t {
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0};
Uint8* buffer{nullptr};
char* filename{nullptr};
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0};
Uint8* buffer{nullptr};
char* filename{nullptr};
int pos{0};
int times{0};
SDL_AudioStream* stream{nullptr};
JA_Music_state state{JA_MUSIC_INVALID};
int pos{0};
int times{0};
SDL_AudioStream* stream{nullptr};
JA_Music_state state{JA_MUSIC_INVALID};
};
// --- Internal Global State ---

View File

@@ -18,117 +18,117 @@
namespace GlobalInputs {
// Funciones internas
namespace {
void handleQuit() {
// En la escena GAME el comportamiento es siempre el mismo (con o sin modo kiosko)
if (SceneManager::current == SceneManager::Scene::GAME) {
const std::string CODE = "PRESS AGAIN TO RETURN TO MENU";
if (stringInVector(Notifier::get()->getCodes(), CODE)) {
SceneManager::current = SceneManager::Scene::TITLE;
} else {
Notifier::get()->show({CODE}, Notifier::Style::DEFAULT, -1, true, CODE);
// Funciones internas
namespace {
void handleQuit() {
// En la escena GAME el comportamiento es siempre el mismo (con o sin modo kiosko)
if (SceneManager::current == SceneManager::Scene::GAME) {
const std::string CODE = "PRESS AGAIN TO RETURN TO MENU";
if (stringInVector(Notifier::get()->getCodes(), CODE)) {
SceneManager::current = SceneManager::Scene::TITLE;
} else {
Notifier::get()->show({CODE}, Notifier::Style::DEFAULT, -1, true, CODE);
}
return;
}
// En modo kiosko, fuera de GAME: mostrar el texto del kiosko y no salir nunca
if (Options::kiosk.enabled) {
const std::string KIOSK_CODE = "KIOSK_EXIT";
if (!stringInVector(Notifier::get()->getCodes(), KIOSK_CODE)) {
Notifier::get()->show({Options::kiosk.text}, Notifier::Style::DEFAULT, -1, true, KIOSK_CODE);
}
// Segunda pulsación: notificación ya activa → no hacer nada
return;
}
// Comportamiento normal fuera del modo kiosko
const std::string CODE = "PRESS AGAIN TO EXIT";
if (stringInVector(Notifier::get()->getCodes(), CODE)) {
SceneManager::current = SceneManager::Scene::QUIT;
} else {
Notifier::get()->show({CODE}, Notifier::Style::DEFAULT, -1, true, CODE);
}
}
return;
}
// En modo kiosko, fuera de GAME: mostrar el texto del kiosko y no salir nunca
if (Options::kiosk.enabled) {
const std::string KIOSK_CODE = "KIOSK_EXIT";
if (!stringInVector(Notifier::get()->getCodes(), KIOSK_CODE)) {
Notifier::get()->show({Options::kiosk.text}, Notifier::Style::DEFAULT, -1, true, KIOSK_CODE);
void handleSkipSection() {
switch (SceneManager::current) {
case SceneManager::Scene::LOGO:
case SceneManager::Scene::LOADING_SCREEN:
case SceneManager::Scene::CREDITS:
case SceneManager::Scene::DEMO:
case SceneManager::Scene::GAME_OVER:
case SceneManager::Scene::ENDING:
case SceneManager::Scene::ENDING2:
SceneManager::current = SceneManager::Scene::TITLE;
SceneManager::options = SceneManager::Options::NONE;
break;
default:
break;
}
}
// Segunda pulsación: notificación ya activa → no hacer nada
return;
}
// Comportamiento normal fuera del modo kiosko
const std::string CODE = "PRESS AGAIN TO EXIT";
if (stringInVector(Notifier::get()->getCodes(), CODE)) {
SceneManager::current = SceneManager::Scene::QUIT;
} else {
Notifier::get()->show({CODE}, Notifier::Style::DEFAULT, -1, true, CODE);
}
}
void handleToggleBorder() {
Screen::get()->toggleBorder();
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")});
}
void handleSkipSection() {
switch (SceneManager::current) {
case SceneManager::Scene::LOGO:
case SceneManager::Scene::LOADING_SCREEN:
case SceneManager::Scene::CREDITS:
case SceneManager::Scene::DEMO:
case SceneManager::Scene::GAME_OVER:
case SceneManager::Scene::ENDING:
case SceneManager::Scene::ENDING2:
SceneManager::current = SceneManager::Scene::TITLE;
SceneManager::options = SceneManager::Options::NONE;
break;
void handleToggleVideoMode() {
Screen::get()->toggleVideoMode();
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")});
}
default:
break;
}
}
void handleDecWindowZoom() {
if (Screen::get()->decWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)});
}
}
void handleToggleBorder() {
Screen::get()->toggleBorder();
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")});
}
void handleIncWindowZoom() {
if (Screen::get()->incWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)});
}
}
void handleToggleVideoMode() {
Screen::get()->toggleVideoMode();
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")});
}
void handleTogglePostFX() {
Screen::get()->togglePostFX();
Notifier::get()->show({"POSTFX " + std::string(Options::video.postfx ? "ENABLED" : "DISABLED")});
}
void handleDecWindowZoom() {
if (Screen::get()->decWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)});
}
}
void handleNextPostFXPreset() {
if (!Options::postfx_presets.empty()) {
Options::current_postfx_preset = (Options::current_postfx_preset + 1) % static_cast<int>(Options::postfx_presets.size());
Screen::get()->reloadPostFX();
Notifier::get()->show({"POSTFX " + Options::postfx_presets[static_cast<size_t>(Options::current_postfx_preset)].name});
}
}
void handleIncWindowZoom() {
if (Screen::get()->incWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)});
}
}
void handleNextPalette() {
Screen::get()->nextPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette});
}
void handleTogglePostFX() {
Screen::get()->togglePostFX();
Notifier::get()->show({"POSTFX " + std::string(Options::video.postfx ? "ENABLED" : "DISABLED")});
}
void handlePreviousPalette() {
Screen::get()->previousPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette});
}
void handleNextPostFXPreset() {
if (!Options::postfx_presets.empty()) {
Options::current_postfx_preset = (Options::current_postfx_preset + 1) % static_cast<int>(Options::postfx_presets.size());
Screen::get()->reloadPostFX();
Notifier::get()->show({"POSTFX " + Options::postfx_presets[static_cast<size_t>(Options::current_postfx_preset)].name});
}
}
void handleToggleIntegerScale() {
Screen::get()->toggleIntegerScale();
Screen::get()->setVideoMode(Options::video.fullscreen);
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")});
}
void handleNextPalette() {
Screen::get()->nextPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette});
}
void handlePreviousPalette() {
Screen::get()->previousPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette});
}
void handleToggleIntegerScale() {
Screen::get()->toggleIntegerScale();
Screen::get()->setVideoMode(Options::video.fullscreen);
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")});
}
void handleToggleVSync() {
Screen::get()->toggleVSync();
Notifier::get()->show({"V-SYNC " + std::string(Options::video.vertical_sync ? "ENABLED" : "DISABLED")});
}
void handleToggleVSync() {
Screen::get()->toggleVSync();
Notifier::get()->show({"V-SYNC " + std::string(Options::video.vertical_sync ? "ENABLED" : "DISABLED")});
}
#ifdef _DEBUG
void handleShowDebugInfo() {
Screen::get()->toggleDebugInfo();
}
void handleShowDebugInfo() {
Screen::get()->toggleDebugInfo();
}
/*
void handleToggleDebug() {
@@ -138,138 +138,138 @@ void handleToggleDebug() {
*/
#endif
// Detecta qué acción global ha sido presionada (si alguna)
auto getPressedAction() -> InputAction {
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::EXIT;
}
if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::ACCEPT;
}
if (Input::get()->checkAction(InputAction::TOGGLE_BORDER, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_BORDER;
}
if (!Options::kiosk.enabled) {
if (Input::get()->checkAction(InputAction::TOGGLE_FULLSCREEN, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_FULLSCREEN;
// Detecta qué acción global ha sido presionada (si alguna)
auto getPressedAction() -> InputAction {
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::EXIT;
}
if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::ACCEPT;
}
if (Input::get()->checkAction(InputAction::TOGGLE_BORDER, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_BORDER;
}
if (!Options::kiosk.enabled) {
if (Input::get()->checkAction(InputAction::TOGGLE_FULLSCREEN, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_FULLSCREEN;
}
if (Input::get()->checkAction(InputAction::WINDOW_DEC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::WINDOW_DEC_ZOOM;
}
if (Input::get()->checkAction(InputAction::WINDOW_INC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::WINDOW_INC_ZOOM;
}
}
if (Input::get()->checkAction(InputAction::TOGGLE_POSTFX, Input::DO_NOT_ALLOW_REPEAT)) {
if (Options::video.postfx && ((SDL_GetModState() & SDL_KMOD_SHIFT) != 0U)) {
return InputAction::NEXT_POSTFX_PRESET;
}
return InputAction::TOGGLE_POSTFX;
}
if (Input::get()->checkAction(InputAction::NEXT_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::NEXT_PALETTE;
}
if (Input::get()->checkAction(InputAction::PREVIOUS_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::PREVIOUS_PALETTE;
}
if (Input::get()->checkAction(InputAction::TOGGLE_INTEGER_SCALE, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_INTEGER_SCALE;
}
if (Input::get()->checkAction(InputAction::TOGGLE_VSYNC, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_VSYNC;
}
if (Input::get()->checkAction(InputAction::TOGGLE_DEBUG, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_DEBUG;
}
if (Input::get()->checkAction(InputAction::SHOW_DEBUG_INFO, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::SHOW_DEBUG_INFO;
}
return InputAction::NONE;
}
if (Input::get()->checkAction(InputAction::WINDOW_DEC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::WINDOW_DEC_ZOOM;
} // namespace
// Funciones públicas
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void handle() {
// Salida de administrador en modo kiosko (Ctrl+Shift+Alt+Q)
if (Options::kiosk.enabled) {
SDL_Keymod mod = SDL_GetModState();
const bool* ks = SDL_GetKeyboardState(nullptr);
if (((mod & SDL_KMOD_CTRL) != 0U) && ((mod & SDL_KMOD_SHIFT) != 0U) && ((mod & SDL_KMOD_ALT) != 0U) && ks[SDL_SCANCODE_Q]) {
SceneManager::current = SceneManager::Scene::QUIT;
return;
}
}
if (Input::get()->checkAction(InputAction::WINDOW_INC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::WINDOW_INC_ZOOM;
}
}
if (Input::get()->checkAction(InputAction::TOGGLE_POSTFX, Input::DO_NOT_ALLOW_REPEAT)) {
if (Options::video.postfx && ((SDL_GetModState() & SDL_KMOD_SHIFT) != 0U)) {
return InputAction::NEXT_POSTFX_PRESET;
}
return InputAction::TOGGLE_POSTFX;
}
if (Input::get()->checkAction(InputAction::NEXT_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::NEXT_PALETTE;
}
if (Input::get()->checkAction(InputAction::PREVIOUS_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::PREVIOUS_PALETTE;
}
if (Input::get()->checkAction(InputAction::TOGGLE_INTEGER_SCALE, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_INTEGER_SCALE;
}
if (Input::get()->checkAction(InputAction::TOGGLE_VSYNC, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_VSYNC;
}
if (Input::get()->checkAction(InputAction::TOGGLE_DEBUG, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::TOGGLE_DEBUG;
}
if (Input::get()->checkAction(InputAction::SHOW_DEBUG_INFO, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::SHOW_DEBUG_INFO;
}
return InputAction::NONE;
}
} // namespace
// Detectar qué acción global está siendo presionada
InputAction action = getPressedAction();
// Funciones públicas
// Ejecutar el handler correspondiente usando switch statement
switch (action) {
case InputAction::EXIT:
handleQuit();
break;
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void handle() {
// Salida de administrador en modo kiosko (Ctrl+Shift+Alt+Q)
if (Options::kiosk.enabled) {
SDL_Keymod mod = SDL_GetModState();
const bool* ks = SDL_GetKeyboardState(nullptr);
if (((mod & SDL_KMOD_CTRL) != 0U) && ((mod & SDL_KMOD_SHIFT) != 0U) && ((mod & SDL_KMOD_ALT) != 0U) && ks[SDL_SCANCODE_Q]) {
SceneManager::current = SceneManager::Scene::QUIT;
return;
}
}
case InputAction::ACCEPT:
handleSkipSection();
break;
// Detectar qué acción global está siendo presionada
InputAction action = getPressedAction();
case InputAction::TOGGLE_BORDER:
handleToggleBorder();
break;
// Ejecutar el handler correspondiente usando switch statement
switch (action) {
case InputAction::EXIT:
handleQuit();
break;
case InputAction::TOGGLE_FULLSCREEN:
handleToggleVideoMode();
break;
case InputAction::ACCEPT:
handleSkipSection();
break;
case InputAction::WINDOW_DEC_ZOOM:
handleDecWindowZoom();
break;
case InputAction::TOGGLE_BORDER:
handleToggleBorder();
break;
case InputAction::WINDOW_INC_ZOOM:
handleIncWindowZoom();
break;
case InputAction::TOGGLE_FULLSCREEN:
handleToggleVideoMode();
break;
case InputAction::TOGGLE_POSTFX:
handleTogglePostFX();
break;
case InputAction::WINDOW_DEC_ZOOM:
handleDecWindowZoom();
break;
case InputAction::NEXT_POSTFX_PRESET:
handleNextPostFXPreset();
break;
case InputAction::WINDOW_INC_ZOOM:
handleIncWindowZoom();
break;
case InputAction::NEXT_PALETTE:
handleNextPalette();
break;
case InputAction::TOGGLE_POSTFX:
handleTogglePostFX();
break;
case InputAction::PREVIOUS_PALETTE:
handlePreviousPalette();
break;
case InputAction::NEXT_POSTFX_PRESET:
handleNextPostFXPreset();
break;
case InputAction::TOGGLE_INTEGER_SCALE:
handleToggleIntegerScale();
break;
case InputAction::NEXT_PALETTE:
handleNextPalette();
break;
case InputAction::TOGGLE_VSYNC:
handleToggleVSync();
break;
case InputAction::PREVIOUS_PALETTE:
handlePreviousPalette();
break;
case InputAction::TOGGLE_INTEGER_SCALE:
handleToggleIntegerScale();
break;
case InputAction::TOGGLE_VSYNC:
handleToggleVSync();
break;
case InputAction::TOGGLE_DEBUG:
// handleToggleDebug();
break;
case InputAction::TOGGLE_DEBUG:
// handleToggleDebug();
break;
#ifdef _DEBUG
case InputAction::SHOW_DEBUG_INFO:
handleShowDebugInfo();
break;
case InputAction::SHOW_DEBUG_INFO:
handleShowDebugInfo();
break;
#endif
case InputAction::NONE:
default:
// No se presionó ninguna acción global
break;
case InputAction::NONE:
default:
// No se presionó ninguna acción global
break;
}
}
}
} // namespace GlobalInputs

View File

@@ -1,6 +1,6 @@
#pragma once
namespace GlobalInputs {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void handle();
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void handle();
} // namespace GlobalInputs

View File

@@ -13,128 +13,128 @@
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
class Input {
public:
// --- Constantes ---
static constexpr bool ALLOW_REPEAT = true; // Permite repetición
static constexpr bool DO_NOT_ALLOW_REPEAT = false; // No permite repetición
static constexpr bool CHECK_KEYBOARD = true; // Comprueba teclado
static constexpr bool DO_NOT_CHECK_KEYBOARD = false; // No comprueba teclado
static constexpr int TRIGGER_L2_AS_BUTTON = 100; // L2 como botón
static constexpr int TRIGGER_R2_AS_BUTTON = 101; // R2 como botón
public:
// --- Constantes ---
static constexpr bool ALLOW_REPEAT = true; // Permite repetición
static constexpr bool DO_NOT_ALLOW_REPEAT = false; // No permite repetición
static constexpr bool CHECK_KEYBOARD = true; // Comprueba teclado
static constexpr bool DO_NOT_CHECK_KEYBOARD = false; // No comprueba teclado
static constexpr int TRIGGER_L2_AS_BUTTON = 100; // L2 como botón
static constexpr int TRIGGER_R2_AS_BUTTON = 101; // R2 como botón
// --- Tipos ---
using Action = InputAction; // Alias para mantener compatibilidad
// --- Tipos ---
using Action = InputAction; // Alias para mantener compatibilidad
// --- Estructuras ---
struct KeyState {
Uint8 scancode{0}; // Scancode asociado
bool is_held{false}; // Está pulsada ahora mismo
bool just_pressed{false}; // Se acaba de pulsar en este fotograma
};
// --- Estructuras ---
struct KeyState {
Uint8 scancode{0}; // Scancode asociado
bool is_held{false}; // Está pulsada ahora mismo
bool just_pressed{false}; // Se acaba de pulsar en este fotograma
};
struct ButtonState {
int button{static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)}; // GameControllerButton asociado
bool is_held{false}; // Está pulsada ahora mismo
bool just_pressed{false}; // Se acaba de pulsar en este fotograma
bool axis_active{false}; // Estado del eje
bool trigger_active{false}; // Estado del trigger como botón digital
};
struct ButtonState {
int button{static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)}; // GameControllerButton asociado
bool is_held{false}; // Está pulsada ahora mismo
bool just_pressed{false}; // Se acaba de pulsar en este fotograma
bool axis_active{false}; // Estado del eje
bool trigger_active{false}; // Estado del trigger como botón digital
};
struct Keyboard {
std::unordered_map<Action, KeyState> bindings; // Mapa de acciones a estados de tecla
};
struct Keyboard {
std::unordered_map<Action, KeyState> bindings; // Mapa de acciones a estados de tecla
};
struct Gamepad {
SDL_Gamepad* pad{nullptr}; // Puntero al gamepad SDL
SDL_JoystickID instance_id{0}; // ID de instancia del joystick
std::string name; // Nombre del gamepad
std::string path; // Ruta del dispositivo
std::unordered_map<Action, ButtonState> bindings; // Mapa de acciones a estados de botón
struct Gamepad {
SDL_Gamepad* pad{nullptr}; // Puntero al gamepad SDL
SDL_JoystickID instance_id{0}; // ID de instancia del joystick
std::string name; // Nombre del gamepad
std::string path; // Ruta del dispositivo
std::unordered_map<Action, ButtonState> bindings; // Mapa de acciones a estados de botón
explicit Gamepad(SDL_Gamepad* gamepad)
: pad(gamepad),
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
name(std::string(SDL_GetGamepadName(gamepad))),
path(std::string(SDL_GetGamepadPath(pad))),
bindings{
// Movimiento del jugador
{Action::LEFT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT)}},
{Action::RIGHT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT)}},
{Action::JUMP, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_WEST)}}} {}
explicit Gamepad(SDL_Gamepad* gamepad)
: pad(gamepad),
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
name(std::string(SDL_GetGamepadName(gamepad))),
path(std::string(SDL_GetGamepadPath(pad))),
bindings{
// Movimiento del jugador
{Action::LEFT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT)}},
{Action::RIGHT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT)}},
{Action::JUMP, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_WEST)}}} {}
~Gamepad() {
if (pad != nullptr) {
SDL_CloseGamepad(pad);
}
}
~Gamepad() {
if (pad != nullptr) {
SDL_CloseGamepad(pad);
}
}
// Reasigna un botón a una acción
void rebindAction(Action action, SDL_GamepadButton new_button) {
bindings[action].button = static_cast<int>(new_button);
}
};
// Reasigna un botón a una acción
void rebindAction(Action action, SDL_GamepadButton new_button) {
bindings[action].button = static_cast<int>(new_button);
}
};
// --- Tipos ---
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
// --- Tipos ---
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
// --- Singleton ---
static void init(const std::string& game_controller_db_path);
static void destroy();
static auto get() -> Input*;
// --- Singleton ---
static void init(const std::string& game_controller_db_path);
static void destroy();
static auto get() -> Input*;
// --- Actualización del sistema ---
void update(); // Actualiza estados de entrada
// --- Actualización del sistema ---
void update(); // Actualiza estados de entrada
// --- Configuración de controles ---
void bindKey(Action action, SDL_Scancode code);
void applyKeyboardBindingsFromOptions();
void applyGamepadBindingsFromOptions();
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button);
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source);
// --- Configuración de controles ---
void bindKey(Action action, SDL_Scancode code);
void applyKeyboardBindingsFromOptions();
void applyGamepadBindingsFromOptions();
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button);
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source);
// --- Consulta de entrada ---
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
void resetInputStates();
// --- Consulta de entrada ---
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
void resetInputStates();
// --- Gestión de gamepads ---
[[nodiscard]] auto gameControllerFound() const -> bool;
[[nodiscard]] auto getNumGamepads() const -> int;
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
auto getGamepads() const -> const Gamepads& { return gamepads_; }
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
auto getControllerNames() const -> std::vector<std::string>;
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
void printConnectedGamepads() const;
// --- Gestión de gamepads ---
[[nodiscard]] auto gameControllerFound() const -> bool;
[[nodiscard]] auto getNumGamepads() const -> int;
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
auto getGamepads() const -> const Gamepads& { return gamepads_; }
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
auto getControllerNames() const -> std::vector<std::string>;
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
void printConnectedGamepads() const;
// --- Eventos ---
auto handleEvent(const SDL_Event& event) -> std::string;
// --- Eventos ---
auto handleEvent(const SDL_Event& event) -> std::string;
private:
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD = 30000; // Umbral para ejes analógicos
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (50% del rango)
static constexpr std::array<Action, 1> BUTTON_INPUTS = {Action::JUMP}; // Inputs que usan botones
private:
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD = 30000; // Umbral para ejes analógicos
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (50% del rango)
static constexpr std::array<Action, 1> BUTTON_INPUTS = {Action::JUMP}; // Inputs que usan botones
// --- Métodos ---
explicit Input(std::string game_controller_db_path);
~Input() = default;
// --- Métodos ---
explicit Input(std::string game_controller_db_path);
~Input() = default;
void initSDLGamePad();
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
auto addGamepad(int device_index) -> std::string;
auto removeGamepad(SDL_JoystickID id) -> std::string;
void addGamepadMappingsFromFile();
void discoverGamepads();
void initSDLGamePad();
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
auto addGamepad(int device_index) -> std::string;
auto removeGamepad(SDL_JoystickID id) -> std::string;
void addGamepadMappingsFromFile();
void discoverGamepads();
// --- Variables miembro ---
static Input* instance; // Instancia única del singleton
// --- Variables miembro ---
static Input* instance; // Instancia única del singleton
Gamepads gamepads_; // Lista de gamepads conectados
Keyboard keyboard_{}; // Estado del teclado
std::string gamepad_mappings_file_; // Ruta al archivo de mappings
Gamepads gamepads_; // Lista de gamepads conectados
Keyboard keyboard_{}; // Estado del teclado
std::string gamepad_mappings_file_; // Ruta al archivo de mappings
};

View File

@@ -1,25 +1,25 @@
#include "core/input/mouse.hpp"
namespace Mouse {
Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor
Uint32 last_mouse_move_time = 0; // Última vez que el ratón se movió
bool cursor_visible = true; // Estado del cursor
Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor
Uint32 last_mouse_move_time = 0; // Última vez que el ratón se movió
bool cursor_visible = true; // Estado del cursor
void handleEvent(const SDL_Event& event) {
if (event.type == SDL_EVENT_MOUSE_MOTION) {
last_mouse_move_time = SDL_GetTicks();
if (!cursor_visible) {
SDL_ShowCursor();
cursor_visible = true;
void handleEvent(const SDL_Event& event) {
if (event.type == SDL_EVENT_MOUSE_MOTION) {
last_mouse_move_time = SDL_GetTicks();
if (!cursor_visible) {
SDL_ShowCursor();
cursor_visible = true;
}
}
}
}
void updateCursorVisibility() {
Uint32 current_time = SDL_GetTicks();
if (cursor_visible && (current_time - last_mouse_move_time > cursor_hide_time)) {
SDL_HideCursor();
cursor_visible = false;
void updateCursorVisibility() {
Uint32 current_time = SDL_GetTicks();
if (cursor_visible && (current_time - last_mouse_move_time > cursor_hide_time)) {
SDL_HideCursor();
cursor_visible = false;
}
}
}
} // namespace Mouse

View File

@@ -3,10 +3,10 @@
#include <SDL3/SDL.h>
namespace Mouse {
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor
extern Uint32 last_mouse_move_time; // Última vez que el ratón se movió
extern bool cursor_visible; // Estado del cursor
extern Uint32 cursor_hide_time; // Tiempo en milisegundos para ocultar el cursor
extern Uint32 last_mouse_move_time; // Última vez que el ratón se movió
extern bool cursor_visible; // Estado del cursor
void handleEvent(const SDL_Event& event);
void updateCursorVisibility();
void handleEvent(const SDL_Event& event);
void updateCursorVisibility();
} // namespace Mouse

View File

@@ -7,289 +7,289 @@
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) {
std::memcpy(dst, buffer, size);
buffer += size;
}
// Inicializa el diccionario LZW con los valores iniciales
inline void initializeDictionary(std::vector<DictionaryEntry>& dictionary, int code_length, int& dictionary_ind) {
int size = 1 << code_length;
dictionary.resize(1 << (code_length + 1));
for (dictionary_ind = 0; dictionary_ind < size; dictionary_ind++) {
dictionary[dictionary_ind].byte = static_cast<uint8_t>(dictionary_ind);
dictionary[dictionary_ind].prev = -1;
dictionary[dictionary_ind].len = 1;
}
dictionary_ind += 2; // Reservamos espacio para clear y stop codes
}
// Lee los próximos bits del stream de entrada para formar un código
inline auto readNextCode(const uint8_t*& input, int& input_length, unsigned int& mask, int code_length) -> int {
int code = 0;
for (int i = 0; i < (code_length + 1); i++) {
if (input_length <= 0) {
throw std::runtime_error("Unexpected end of input in decompress");
}
int bit = ((*input & mask) != 0) ? 1 : 0;
mask <<= 1;
if (mask == 0x100) {
mask = 0x01;
input++;
input_length--;
}
code |= (bit << i);
}
return code;
}
// Encuentra el primer byte de una cadena del diccionario
inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int code) -> uint8_t {
int ptr = code;
while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev;
}
return dictionary[ptr].byte;
}
// Agrega una nueva entrada al diccionario
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind, int& code_length, int prev, int code) {
uint8_t first_byte;
if (code == dictionary_ind) {
first_byte = findFirstByte(dictionary, prev);
} else {
first_byte = findFirstByte(dictionary, code);
// 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) {
std::memcpy(dst, buffer, size);
buffer += size;
}
dictionary[dictionary_ind].byte = first_byte;
dictionary[dictionary_ind].prev = prev;
dictionary[dictionary_ind].len = dictionary[prev].len + 1;
dictionary_ind++;
if ((dictionary_ind == (1 << (code_length + 1))) && (code_length < 11)) {
code_length++;
// Inicializa el diccionario LZW con los valores iniciales
inline void initializeDictionary(std::vector<DictionaryEntry>& dictionary, int code_length, int& dictionary_ind) {
int size = 1 << code_length;
dictionary.resize(1 << (code_length + 1));
}
}
// Escribe la cadena decodificada al buffer de salida
inline auto writeDecodedString(const std::vector<DictionaryEntry>& dictionary, int code, uint8_t*& out) -> int {
int cur_code = code;
int match_len = dictionary[cur_code].len;
while (cur_code != -1) {
out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
if (dictionary[cur_code].prev == cur_code) {
std::cerr << "Internal error; self-reference detected." << '\n';
throw std::runtime_error("Internal error in decompress: self-reference");
for (dictionary_ind = 0; dictionary_ind < size; dictionary_ind++) {
dictionary[dictionary_ind].byte = static_cast<uint8_t>(dictionary_ind);
dictionary[dictionary_ind].prev = -1;
dictionary[dictionary_ind].len = 1;
}
cur_code = dictionary[cur_code].prev;
}
out += match_len;
return match_len;
}
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) {
throw std::runtime_error("Invalid LZW code length");
dictionary_ind += 2; // Reservamos espacio para clear y stop codes
}
int prev = -1;
std::vector<DictionaryEntry> dictionary;
int dictionary_ind;
unsigned int mask = 0x01;
int reset_code_length = code_length;
int clear_code = 1 << code_length;
int stop_code = clear_code + 1;
// Inicializamos el diccionario con el tamaño correspondiente.
initializeDictionary(dictionary, code_length, dictionary_ind);
// Bucle principal: procesar el stream comprimido.
while (input_length > 0) {
int code = readNextCode(input, input_length, mask, code_length);
if (code == clear_code) {
// Reinicia el diccionario.
code_length = reset_code_length;
initializeDictionary(dictionary, code_length, dictionary_ind);
prev = -1;
continue;
}
if (code == stop_code) {
break;
}
if (prev > -1 && code_length < 12) {
if (code > dictionary_ind) {
std::cerr << "code = " << std::hex << code
<< ", but dictionary_ind = " << dictionary_ind << '\n';
throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
// Lee los próximos bits del stream de entrada para formar un código
inline auto readNextCode(const uint8_t*& input, int& input_length, unsigned int& mask, int code_length) -> int {
int code = 0;
for (int i = 0; i < (code_length + 1); i++) {
if (input_length <= 0) {
throw std::runtime_error("Unexpected end of input in decompress");
}
addDictionaryEntry(dictionary, dictionary_ind, code_length, 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()) {
std::cerr << "Invalid LZW code " << code
<< ", dictionary size " << dictionary.size() << '\n';
throw std::runtime_error("LZW error: invalid code encountered");
}
writeDecodedString(dictionary, code, out);
}
}
auto Gif::readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t> {
std::vector<uint8_t> data;
uint8_t block_size = *buffer;
buffer++;
while (block_size != 0) {
data.insert(data.end(), buffer, buffer + block_size);
buffer += block_size;
block_size = *buffer;
buffer++;
}
return data;
}
auto Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t> {
ImageDescriptor image_descriptor;
// Lee 9 bytes para el image descriptor.
readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor));
uint8_t lzw_code_size;
readBytes(buffer, &lzw_code_size, sizeof(uint8_t));
std::vector<uint8_t> compressed_data = readSubBlocks(buffer);
int uncompressed_data_length = image_descriptor.image_width * image_descriptor.image_height;
std::vector<uint8_t> uncompressed_data(uncompressed_data_length);
decompress(lzw_code_size, compressed_data.data(), static_cast<int>(compressed_data.size()), uncompressed_data.data());
return uncompressed_data;
}
auto Gif::loadPalette(const uint8_t* buffer) -> std::vector<uint32_t> {
uint8_t header[6];
std::memcpy(header, buffer, 6);
buffer += 6;
ScreenDescriptor screen_descriptor;
std::memcpy(&screen_descriptor, buffer, sizeof(ScreenDescriptor));
buffer += sizeof(ScreenDescriptor);
std::vector<uint32_t> global_color_table;
if ((screen_descriptor.fields & 0x80) != 0) {
int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
global_color_table.resize(global_color_table_size);
for (int i = 0; i < global_color_table_size; ++i) {
uint8_t r = buffer[0];
uint8_t g = buffer[1];
uint8_t b = buffer[2];
global_color_table[i] = (r << 16) | (g << 8) | b;
buffer += 3;
}
}
return global_color_table;
}
auto Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
// Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a")
uint8_t header[6];
std::memcpy(header, buffer, 6);
buffer += 6;
// Opcional: Validar header
std::string header_str(reinterpret_cast<char*>(header), 6);
if (header_str != "GIF87a" && header_str != "GIF89a") {
throw std::runtime_error("Formato de archivo GIF inválido.");
}
// Leer el Screen Descriptor (7 bytes, empaquetado sin padding)
ScreenDescriptor screen_descriptor;
readBytes(buffer, &screen_descriptor, sizeof(ScreenDescriptor));
// Asigna ancho y alto
w = screen_descriptor.width;
h = screen_descriptor.height;
int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
std::vector<RGB> global_color_table;
if ((screen_descriptor.fields & 0x80) != 0) {
int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
global_color_table.resize(global_color_table_size);
std::memcpy(global_color_table.data(), 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++;
while (block_type != TRAILER) {
if (block_type == EXTENSION_INTRODUCER) // 0x21
{
// Se lee la etiqueta de extensión, la cual indica el tipo de extensión.
uint8_t extension_label = *buffer++;
switch (extension_label) {
case GRAPHIC_CONTROL: // 0xF9
{
// Procesar Graphic Control Extension:
uint8_t block_size = *buffer++; // Normalmente, blockSize == 4
buffer += block_size; // Saltamos los 4 bytes del bloque fijo
// Saltar los sub-bloques
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
case APPLICATION_EXTENSION: // 0xFF
case COMMENT_EXTENSION: // 0xFE
case PLAINTEXT_EXTENSION: // 0x01
{
// Para estas extensiones, saltamos el bloque fijo y los sub-bloques.
uint8_t block_size = *buffer++;
buffer += block_size;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
default: {
// Si la etiqueta de extensión es desconocida, saltarla también:
uint8_t block_size = *buffer++;
buffer += block_size;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
int bit = ((*input & mask) != 0) ? 1 : 0;
mask <<= 1;
if (mask == 0x100) {
mask = 0x01;
input++;
input_length--;
}
} else if (block_type == IMAGE_DESCRIPTOR) {
// Procesar el Image Descriptor y retornar los datos de imagen
return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
code |= (bit << i);
}
return code;
}
// Encuentra el primer byte de una cadena del diccionario
inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int code) -> uint8_t {
int ptr = code;
while (dictionary[ptr].prev != -1) {
ptr = dictionary[ptr].prev;
}
return dictionary[ptr].byte;
}
// Agrega una nueva entrada al diccionario
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind, int& code_length, int prev, int code) {
uint8_t first_byte;
if (code == dictionary_ind) {
first_byte = findFirstByte(dictionary, prev);
} else {
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << '\n';
return std::vector<uint8_t>{};
first_byte = findFirstByte(dictionary, code);
}
dictionary[dictionary_ind].byte = first_byte;
dictionary[dictionary_ind].prev = prev;
dictionary[dictionary_ind].len = dictionary[prev].len + 1;
dictionary_ind++;
if ((dictionary_ind == (1 << (code_length + 1))) && (code_length < 11)) {
code_length++;
dictionary.resize(1 << (code_length + 1));
}
block_type = *buffer++;
}
return std::vector<uint8_t>{};
}
// Escribe la cadena decodificada al buffer de salida
inline auto writeDecodedString(const std::vector<DictionaryEntry>& dictionary, int code, uint8_t*& out) -> int {
int cur_code = code;
int match_len = dictionary[cur_code].len;
while (cur_code != -1) {
out[dictionary[cur_code].len - 1] = dictionary[cur_code].byte;
if (dictionary[cur_code].prev == cur_code) {
std::cerr << "Internal error; self-reference detected." << '\n';
throw std::runtime_error("Internal error in decompress: self-reference");
}
cur_code = dictionary[cur_code].prev;
}
out += match_len;
return match_len;
}
auto Gif::loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
return processGifStream(buffer, w, h);
}
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) {
throw std::runtime_error("Invalid LZW code length");
}
int prev = -1;
std::vector<DictionaryEntry> dictionary;
int dictionary_ind;
unsigned int mask = 0x01;
int reset_code_length = code_length;
int clear_code = 1 << code_length;
int stop_code = clear_code + 1;
// Inicializamos el diccionario con el tamaño correspondiente.
initializeDictionary(dictionary, code_length, dictionary_ind);
// Bucle principal: procesar el stream comprimido.
while (input_length > 0) {
int code = readNextCode(input, input_length, mask, code_length);
if (code == clear_code) {
// Reinicia el diccionario.
code_length = reset_code_length;
initializeDictionary(dictionary, code_length, dictionary_ind);
prev = -1;
continue;
}
if (code == stop_code) {
break;
}
if (prev > -1 && code_length < 12) {
if (code > dictionary_ind) {
std::cerr << "code = " << std::hex << code
<< ", but dictionary_ind = " << dictionary_ind << '\n';
throw std::runtime_error("LZW error: code exceeds dictionary_ind.");
}
addDictionaryEntry(dictionary, dictionary_ind, code_length, 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()) {
std::cerr << "Invalid LZW code " << code
<< ", dictionary size " << dictionary.size() << '\n';
throw std::runtime_error("LZW error: invalid code encountered");
}
writeDecodedString(dictionary, code, out);
}
}
auto Gif::readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t> {
std::vector<uint8_t> data;
uint8_t block_size = *buffer;
buffer++;
while (block_size != 0) {
data.insert(data.end(), buffer, buffer + block_size);
buffer += block_size;
block_size = *buffer;
buffer++;
}
return data;
}
auto Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t> {
ImageDescriptor image_descriptor;
// Lee 9 bytes para el image descriptor.
readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor));
uint8_t lzw_code_size;
readBytes(buffer, &lzw_code_size, sizeof(uint8_t));
std::vector<uint8_t> compressed_data = readSubBlocks(buffer);
int uncompressed_data_length = image_descriptor.image_width * image_descriptor.image_height;
std::vector<uint8_t> uncompressed_data(uncompressed_data_length);
decompress(lzw_code_size, compressed_data.data(), static_cast<int>(compressed_data.size()), uncompressed_data.data());
return uncompressed_data;
}
auto Gif::loadPalette(const uint8_t* buffer) -> std::vector<uint32_t> {
uint8_t header[6];
std::memcpy(header, buffer, 6);
buffer += 6;
ScreenDescriptor screen_descriptor;
std::memcpy(&screen_descriptor, buffer, sizeof(ScreenDescriptor));
buffer += sizeof(ScreenDescriptor);
std::vector<uint32_t> global_color_table;
if ((screen_descriptor.fields & 0x80) != 0) {
int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
global_color_table.resize(global_color_table_size);
for (int i = 0; i < global_color_table_size; ++i) {
uint8_t r = buffer[0];
uint8_t g = buffer[1];
uint8_t b = buffer[2];
global_color_table[i] = (r << 16) | (g << 8) | b;
buffer += 3;
}
}
return global_color_table;
}
auto Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
// Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a")
uint8_t header[6];
std::memcpy(header, buffer, 6);
buffer += 6;
// Opcional: Validar header
std::string header_str(reinterpret_cast<char*>(header), 6);
if (header_str != "GIF87a" && header_str != "GIF89a") {
throw std::runtime_error("Formato de archivo GIF inválido.");
}
// Leer el Screen Descriptor (7 bytes, empaquetado sin padding)
ScreenDescriptor screen_descriptor;
readBytes(buffer, &screen_descriptor, sizeof(ScreenDescriptor));
// Asigna ancho y alto
w = screen_descriptor.width;
h = screen_descriptor.height;
int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
std::vector<RGB> global_color_table;
if ((screen_descriptor.fields & 0x80) != 0) {
int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
global_color_table.resize(global_color_table_size);
std::memcpy(global_color_table.data(), 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++;
while (block_type != TRAILER) {
if (block_type == EXTENSION_INTRODUCER) // 0x21
{
// Se lee la etiqueta de extensión, la cual indica el tipo de extensión.
uint8_t extension_label = *buffer++;
switch (extension_label) {
case GRAPHIC_CONTROL: // 0xF9
{
// Procesar Graphic Control Extension:
uint8_t block_size = *buffer++; // Normalmente, blockSize == 4
buffer += block_size; // Saltamos los 4 bytes del bloque fijo
// Saltar los sub-bloques
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
case APPLICATION_EXTENSION: // 0xFF
case COMMENT_EXTENSION: // 0xFE
case PLAINTEXT_EXTENSION: // 0x01
{
// Para estas extensiones, saltamos el bloque fijo y los sub-bloques.
uint8_t block_size = *buffer++;
buffer += block_size;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
default: {
// Si la etiqueta de extensión es desconocida, saltarla también:
uint8_t block_size = *buffer++;
buffer += block_size;
uint8_t sub_block_size = *buffer++;
while (sub_block_size != 0) {
buffer += sub_block_size;
sub_block_size = *buffer++;
}
break;
}
}
} else if (block_type == IMAGE_DESCRIPTOR) {
// Procesar el Image Descriptor y retornar los datos de imagen
return processImageDescriptor(buffer, global_color_table, color_resolution_bits);
} else {
std::cerr << "Unrecognized block type " << std::hex << static_cast<int>(block_type) << '\n';
return std::vector<uint8_t>{};
}
block_type = *buffer++;
}
return std::vector<uint8_t>{};
}
auto Gif::loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t> {
return processGifStream(buffer, w, h);
}
} // namespace GIF

View File

@@ -5,67 +5,67 @@
namespace GIF {
// Constantes definidas con constexpr, en lugar de macros
constexpr uint8_t EXTENSION_INTRODUCER = 0x21;
constexpr uint8_t IMAGE_DESCRIPTOR = 0x2C;
constexpr uint8_t TRAILER = 0x3B;
constexpr uint8_t GRAPHIC_CONTROL = 0xF9;
constexpr uint8_t APPLICATION_EXTENSION = 0xFF;
constexpr uint8_t COMMENT_EXTENSION = 0xFE;
constexpr uint8_t PLAINTEXT_EXTENSION = 0x01;
// Constantes definidas con constexpr, en lugar de macros
constexpr uint8_t EXTENSION_INTRODUCER = 0x21;
constexpr uint8_t IMAGE_DESCRIPTOR = 0x2C;
constexpr uint8_t TRAILER = 0x3B;
constexpr uint8_t GRAPHIC_CONTROL = 0xF9;
constexpr uint8_t APPLICATION_EXTENSION = 0xFF;
constexpr uint8_t COMMENT_EXTENSION = 0xFE;
constexpr uint8_t PLAINTEXT_EXTENSION = 0x01;
#pragma pack(push, 1)
struct ScreenDescriptor {
struct ScreenDescriptor {
uint16_t width;
uint16_t height;
uint8_t fields;
uint8_t background_color_index;
uint8_t pixel_aspect_ratio;
};
};
struct RGB {
struct RGB {
uint8_t r, g, b;
};
};
struct ImageDescriptor {
struct ImageDescriptor {
uint16_t image_left_position;
uint16_t image_top_position;
uint16_t image_width;
uint16_t image_height;
uint8_t fields;
};
};
#pragma pack(pop)
struct DictionaryEntry {
struct DictionaryEntry {
uint8_t byte;
int prev;
int len;
};
};
struct Extension {
struct Extension {
uint8_t extension_code;
uint8_t block_size;
};
};
struct GraphicControlExtension {
struct GraphicControlExtension {
uint8_t fields;
uint16_t delay_time;
uint8_t transparent_color_index;
};
};
struct ApplicationExtension {
struct ApplicationExtension {
uint8_t application_id[8];
uint8_t version[3];
};
};
struct PlaintextExtension {
struct PlaintextExtension {
uint16_t left, top, width, height;
uint8_t cell_width, cell_height;
uint8_t foreground_color, background_color;
};
};
class Gif {
public:
class Gif {
public:
// Descompone (uncompress) el bloque comprimido usando LZW.
// Este método puede lanzar std::runtime_error en caso de error.
static void decompress(int code_length, const uint8_t* input, int input_length, uint8_t* out);
@@ -78,7 +78,7 @@ class Gif {
// asigna el ancho y alto mediante referencias.
static auto loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
private:
private:
// Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>.
static auto readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t>;
@@ -87,6 +87,6 @@ class Gif {
// Procesa el stream completo del GIF y devuelve los datos sin comprimir.
static auto processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
};
};
} // namespace GIF

View File

@@ -8,35 +8,35 @@ class Surface;
// Efecto de revelado pixel a pixel por filas, de arriba a abajo.
// Cada fila se revela en num_steps pasos, con píxeles en orden aleatorio u ordenado (bisección).
class PixelReveal {
public:
// Modo de revelado: aleatorio por fila o en orden de bisección (dithering ordenado 1D)
enum class RevealMode { RANDOM,
ORDERED };
public:
// Modo de revelado: aleatorio por fila o en orden de bisección (dithering ordenado 1D)
enum class RevealMode { RANDOM,
ORDERED };
// Constructor
PixelReveal(int width, int height, float pixels_per_second, float step_duration, int num_steps = 4, bool reverse = false, RevealMode mode = RevealMode::RANDOM);
// Constructor
PixelReveal(int width, int height, float pixels_per_second, float step_duration, int num_steps = 4, bool reverse = false, RevealMode mode = RevealMode::RANDOM);
// Destructor definido en el .cpp para que unique_ptr<Surface> funcione con forward declaration
~PixelReveal();
// Destructor definido en el .cpp para que unique_ptr<Surface> funcione con forward declaration
~PixelReveal();
// Actualiza el estado del revelado según el tiempo transcurrido
void update(float time_active);
// Actualiza el estado del revelado según el tiempo transcurrido
void update(float time_active);
// Dibuja la máscara de revelado en la posición indicada
void render(int dst_x, int dst_y) const;
// Dibuja la máscara de revelado en la posición indicada
void render(int dst_x, int dst_y) const;
// Indica si el revelado ha completado todas las filas
[[nodiscard]] auto isComplete() const -> bool;
// Indica si el revelado ha completado todas las filas
[[nodiscard]] auto isComplete() const -> bool;
private:
std::shared_ptr<Surface> cover_surface_; // Máscara negra que se va haciendo transparente
std::vector<std::vector<int>> reveal_order_; // Orden de columnas por fila (aleatorio u ordenado por bisección)
std::vector<int> row_step_; // Paso actual de revelado por fila (0..num_steps_)
int width_;
int height_;
float pixels_per_second_; // Filas reveladas por segundo
float step_duration_; // Segundos por paso dentro de una fila
int num_steps_; // Número de pasos de revelado por fila
bool reverse_; // Si true: transparente → negro (ocultar); si false: negro → transparente (revelar)
RevealMode mode_; // Modo de revelado: aleatorio u ordenado por bisección
private:
std::shared_ptr<Surface> cover_surface_; // Máscara negra que se va haciendo transparente
std::vector<std::vector<int>> reveal_order_; // Orden de columnas por fila (aleatorio u ordenado por bisección)
std::vector<int> row_step_; // Paso actual de revelado por fila (0..num_steps_)
int width_;
int height_;
float pixels_per_second_; // Filas reveladas por segundo
float step_duration_; // Segundos por paso dentro de una fila
int num_steps_; // Número de pasos de revelado por fila
bool reverse_; // Si true: transparente → negro (ocultar); si false: negro → transparente (revelar)
RevealMode mode_; // Modo de revelado: aleatorio u ordenado por bisección
};

View File

@@ -12,154 +12,154 @@
class Surface;
class Text;
namespace Rendering {
class ShaderBackend;
class ShaderBackend;
}
class Screen {
public:
// Tipos de filtro
enum class Filter : Uint32 {
NEAREST = 0,
LINEAR = 1,
};
public:
// Tipos de filtro
enum class Filter : Uint32 {
NEAREST = 0,
LINEAR = 1,
};
// Singleton
static void init(); // Crea el singleton
static void destroy(); // Destruye el singleton
static auto get() -> Screen*; // Obtiene el singleton
// Singleton
static void init(); // Crea el singleton
static void destroy(); // Destruye el singleton
static auto get() -> Screen*; // Obtiene el singleton
// Renderizado
void clearRenderer(Color color = {0x00, 0x00, 0x00}); // Limpia el renderer
void clearSurface(Uint8 index); // Limpia la game_surface_
void start(); // Prepara para empezar a dibujar en la textura de juego
void render(); // Vuelca el contenido del renderizador en pantalla
void update(float delta_time); // Actualiza la lógica de la clase
// Renderizado
void clearRenderer(Color color = {0x00, 0x00, 0x00}); // Limpia el renderer
void clearSurface(Uint8 index); // Limpia la game_surface_
void start(); // Prepara para empezar a dibujar en la textura de juego
void render(); // Vuelca el contenido del renderizador en pantalla
void update(float delta_time); // Actualiza la lógica de la clase
// Video y ventana
void setVideoMode(bool mode); // Establece el modo de video
void toggleVideoMode(); // Cambia entre pantalla completa y ventana
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
auto decWindowZoom() -> bool; // Reduce el tamaño de la ventana
auto incWindowZoom() -> bool; // Aumenta el tamaño de la ventana
void show(); // Muestra la ventana
void hide(); // Oculta la ventana
// Video y ventana
void setVideoMode(bool mode); // Establece el modo de video
void toggleVideoMode(); // Cambia entre pantalla completa y ventana
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
auto decWindowZoom() -> bool; // Reduce el tamaño de la ventana
auto incWindowZoom() -> bool; // Aumenta el tamaño de la ventana
void show(); // Muestra la ventana
void hide(); // Oculta la ventana
// Borde
void setBorderColor(Uint8 color); // Cambia el color del borde
static void setBorderWidth(int width); // Establece el ancho del borde
static void setBorderHeight(int height); // Establece el alto del borde
static void setBorderEnabled(bool value); // Establece si se ha de ver el borde
void toggleBorder(); // Cambia entre borde visible y no visible
// Borde
void setBorderColor(Uint8 color); // Cambia el color del borde
static void setBorderWidth(int width); // Establece el ancho del borde
static void setBorderHeight(int height); // Establece el alto del borde
static void setBorderEnabled(bool value); // Establece si se ha de ver el borde
void toggleBorder(); // Cambia entre borde visible y no visible
// Paletas y PostFX
void nextPalette(); // Cambia a la siguiente paleta
void previousPalette(); // Cambia a la paleta anterior
void setPalete(); // Establece la paleta actual
void togglePostFX(); // Cambia el estado del PostFX
void reloadPostFX(); // Recarga el shader del preset actual sin toggle
// Paletas y PostFX
void nextPalette(); // Cambia a la siguiente paleta
void previousPalette(); // Cambia a la paleta anterior
void setPalete(); // Establece la paleta actual
void togglePostFX(); // Cambia el estado del PostFX
void reloadPostFX(); // Recarga el shader del preset actual sin toggle
// Surfaces y notificaciones
void setRendererSurface(const std::shared_ptr<Surface>& surface = nullptr); // Establece el renderizador para las surfaces
void setNotificationsEnabled(bool value); // Establece la visibilidad de las notificaciones
void toggleDebugInfo(); // Activa o desactiva la información de debug
// Surfaces y notificaciones
void setRendererSurface(const std::shared_ptr<Surface>& surface = nullptr); // Establece el renderizador para las surfaces
void setNotificationsEnabled(bool value); // Establece la visibilidad de las notificaciones
void toggleDebugInfo(); // Activa o desactiva la información de debug
// Getters
auto getRenderer() -> SDL_Renderer*;
auto getRendererSurface() -> std::shared_ptr<Surface>;
auto getBorderSurface() -> std::shared_ptr<Surface>;
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; }
[[nodiscard]] auto getGameSurfaceDstRect() const -> SDL_FRect { return game_surface_dstrect_; }
// Getters
auto getRenderer() -> SDL_Renderer*;
auto getRendererSurface() -> std::shared_ptr<Surface>;
auto getBorderSurface() -> std::shared_ptr<Surface>;
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; }
[[nodiscard]] auto getGameSurfaceDstRect() const -> SDL_FRect { return game_surface_dstrect_; }
private:
// Estructuras
struct DisplayMonitor {
std::string name;
int width{0};
int height{0};
int refresh_rate{0};
};
private:
// Estructuras
struct DisplayMonitor {
std::string name;
int width{0};
int height{0};
int refresh_rate{0};
};
struct FPS {
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar
int frame_count{0}; // Número acumulado de frames en el intervalo
int last_value{0}; // Número de frames calculado en el último segundo
struct FPS {
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar
int frame_count{0}; // Número acumulado de frames en el intervalo
int last_value{0}; // Número de frames calculado en el último segundo
void increment() {
frame_count++;
}
void increment() {
frame_count++;
}
auto calculate(Uint32 current_ticks) -> int {
if (current_ticks - ticks >= 1000) {
last_value = frame_count;
frame_count = 0;
ticks = current_ticks;
}
return last_value;
}
};
auto calculate(Uint32 current_ticks) -> int {
if (current_ticks - ticks >= 1000) {
last_value = frame_count;
frame_count = 0;
ticks = current_ticks;
}
return last_value;
}
};
// Constantes
static constexpr int WINDOWS_DECORATIONS = 35; // Decoraciones de la ventana
// Constantes
static constexpr int WINDOWS_DECORATIONS = 35; // Decoraciones de la ventana
// Singleton
static Screen* screen;
// Singleton
static Screen* screen;
// Métodos privados
void renderNotifications() const; // Dibuja las notificaciones
void adjustWindowSize(); // Calcula el tamaño de la ventana
void adjustRenderLogicalSize(); // Ajusta el tamaño lógico del renderizador
void processPaletteList(); // Extrae los nombres de las paletas
void surfaceToTexture(); // Copia la surface a la textura
void textureToRenderer(); // Copia la textura al renderizador
void renderOverlays(); // Renderiza todos los overlays
auto findPalette(const std::string& name) -> size_t; // Localiza la paleta dentro del vector de paletas
void initShaders(); // Inicializa los shaders
void applyCurrentPostFXPreset(); // Aplica los parámetros del preset actual al backend
void renderInfo() const; // Muestra información por pantalla
void getDisplayInfo(); // Obtiene información sobre la pantalla
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
void createText(); // Crea el objeto de texto
// Métodos privados
void renderNotifications() const; // Dibuja las notificaciones
void adjustWindowSize(); // Calcula el tamaño de la ventana
void adjustRenderLogicalSize(); // Ajusta el tamaño lógico del renderizador
void processPaletteList(); // Extrae los nombres de las paletas
void surfaceToTexture(); // Copia la surface a la textura
void textureToRenderer(); // Copia la textura al renderizador
void renderOverlays(); // Renderiza todos los overlays
auto findPalette(const std::string& name) -> size_t; // Localiza la paleta dentro del vector de paletas
void initShaders(); // Inicializa los shaders
void applyCurrentPostFXPreset(); // Aplica los parámetros del preset actual al backend
void renderInfo() const; // Muestra información por pantalla
void getDisplayInfo(); // Obtiene información sobre la pantalla
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
void createText(); // Crea el objeto de texto
// Constructor y destructor
Screen();
~Screen();
// Constructor y destructor
Screen();
~Screen();
// Objetos SDL
SDL_Window* window_{nullptr}; // Ventana de la aplicación
SDL_Renderer* renderer_{nullptr}; // Renderizador de la ventana
SDL_Texture* game_texture_{nullptr}; // Textura donde se dibuja el juego
SDL_Texture* border_texture_{nullptr}; // Textura donde se dibuja el borde del juego
// Objetos SDL
SDL_Window* window_{nullptr}; // Ventana de la aplicación
SDL_Renderer* renderer_{nullptr}; // Renderizador de la ventana
SDL_Texture* game_texture_{nullptr}; // Textura donde se dibuja el juego
SDL_Texture* border_texture_{nullptr}; // Textura donde se dibuja el borde del juego
// Surfaces y renderizado
std::shared_ptr<Surface> game_surface_; // Surface principal del juego
std::shared_ptr<Surface> border_surface_; // Surface para el borde de la pantalla
std::shared_ptr<std::shared_ptr<Surface>> renderer_surface_; // Puntero a la Surface activa
std::unique_ptr<Rendering::ShaderBackend> shader_backend_; // Backend de shaders (OpenGL/Metal/Vulkan)
std::shared_ptr<Text> text_; // Objeto para escribir texto
// Surfaces y renderizado
std::shared_ptr<Surface> game_surface_; // Surface principal del juego
std::shared_ptr<Surface> border_surface_; // Surface para el borde de la pantalla
std::shared_ptr<std::shared_ptr<Surface>> renderer_surface_; // Puntero a la Surface activa
std::unique_ptr<Rendering::ShaderBackend> shader_backend_; // Backend de shaders (OpenGL/Metal/Vulkan)
std::shared_ptr<Text> text_; // Objeto para escribir texto
// Configuración de ventana y pantalla
int window_width_{0}; // Ancho de la pantalla o ventana
int window_height_{0}; // Alto de la pantalla o ventana
SDL_FRect game_surface_dstrect_; // Coordenadas donde se dibuja la textura del juego
// Configuración de ventana y pantalla
int window_width_{0}; // Ancho de la pantalla o ventana
int window_height_{0}; // Alto de la pantalla o ventana
SDL_FRect game_surface_dstrect_; // Coordenadas donde se dibuja la textura del juego
// Paletas y colores
Uint8 border_color_{0}; // Color del borde
std::vector<std::string> palettes_; // Listado de ficheros de paleta disponibles
Uint8 current_palette_{0}; // Índice para el vector de paletas
// Paletas y colores
Uint8 border_color_{0}; // Color del borde
std::vector<std::string> palettes_; // Listado de ficheros de paleta disponibles
Uint8 current_palette_{0}; // Índice para el vector de paletas
// Estado y configuración
bool notifications_enabled_{false}; // Indica si se muestran las notificaciones
FPS fps_; // Gestor de frames por segundo
DisplayMonitor display_monitor_; // Información de la pantalla
// Estado y configuración
bool notifications_enabled_{false}; // Indica si se muestran las notificaciones
FPS fps_; // Gestor de frames por segundo
DisplayMonitor display_monitor_; // Información de la pantalla
// Shaders
std::string info_resolution_; // Texto con la información de la pantalla
std::vector<Uint32> pixel_buffer_; // Buffer intermedio para SDL3GPU path (surface → ARGB)
// Shaders
std::string info_resolution_; // Texto con la información de la pantalla
std::vector<Uint32> pixel_buffer_; // Buffer intermedio para SDL3GPU path (surface → ARGB)
#ifdef _DEBUG
bool show_debug_info_{true}; // Indica si ha de mostrar la información de debug
bool show_debug_info_{true}; // Indica si ha de mostrar la información de debug
#else
bool show_debug_info_{false}; // Indica si ha de mostrar la información de debug
bool show_debug_info_{false}; // Indica si ha de mostrar la información de debug
#endif
};

View File

@@ -162,395 +162,395 @@ fragment float4 postfx_fs(PostVOut in [[stage_in]],
namespace Rendering {
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
SDL3GPUShader::~SDL3GPUShader() {
destroy();
}
// ---------------------------------------------------------------------------
// init
// ---------------------------------------------------------------------------
auto SDL3GPUShader::init(SDL_Window* window,
SDL_Texture* texture,
const std::string& /*vertex_source*/,
const std::string& /*fragment_source*/) -> bool {
// Si ya estaba inicializado (p.ej. al cambiar borde), liberar recursos
// de textura/pipeline pero mantener el device vivo para evitar conflictos
// con SDL_Renderer en Windows/Vulkan.
if (is_initialized_) {
cleanup();
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
SDL3GPUShader::~SDL3GPUShader() {
destroy();
}
window_ = window;
// ---------------------------------------------------------------------------
// init
// ---------------------------------------------------------------------------
auto SDL3GPUShader::init(SDL_Window* window,
SDL_Texture* texture,
const std::string& /*vertex_source*/,
const std::string& /*fragment_source*/) -> bool {
// Si ya estaba inicializado (p.ej. al cambiar borde), liberar recursos
// de textura/pipeline pero mantener el device vivo para evitar conflictos
// con SDL_Renderer en Windows/Vulkan.
if (is_initialized_) {
cleanup();
}
// Dimensions from the SDL_Texture placeholder
float fw = 0.0F;
float fh = 0.0F;
SDL_GetTextureSize(texture, &fw, &fh);
tex_width_ = static_cast<int>(fw);
tex_height_ = static_cast<int>(fh);
uniforms_.screen_height = fh; // Altura lógica del juego (no el swapchain físico)
window_ = window;
// ----------------------------------------------------------------
// 1. Create GPU device (solo si no existe ya)
// ----------------------------------------------------------------
if (device_ == nullptr) {
#ifdef __APPLE__
const SDL_GPUShaderFormat PREFERRED = SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_METALLIB;
#else
const SDL_GPUShaderFormat PREFERRED = SDL_GPU_SHADERFORMAT_SPIRV;
#endif
device_ = SDL_CreateGPUDevice(PREFERRED, false, nullptr);
// Dimensions from the SDL_Texture placeholder
float fw = 0.0F;
float fh = 0.0F;
SDL_GetTextureSize(texture, &fw, &fh);
tex_width_ = static_cast<int>(fw);
tex_height_ = static_cast<int>(fh);
uniforms_.screen_height = fh; // Altura lógica del juego (no el swapchain físico)
// ----------------------------------------------------------------
// 1. Create GPU device (solo si no existe ya)
// ----------------------------------------------------------------
if (device_ == nullptr) {
SDL_Log("SDL3GPUShader: SDL_CreateGPUDevice failed: %s", SDL_GetError());
#ifdef __APPLE__
const SDL_GPUShaderFormat PREFERRED = SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_METALLIB;
#else
const SDL_GPUShaderFormat PREFERRED = SDL_GPU_SHADERFORMAT_SPIRV;
#endif
device_ = SDL_CreateGPUDevice(PREFERRED, false, nullptr);
if (device_ == nullptr) {
SDL_Log("SDL3GPUShader: SDL_CreateGPUDevice failed: %s", SDL_GetError());
return false;
}
SDL_Log("SDL3GPUShader: driver = %s", SDL_GetGPUDeviceDriver(device_));
// ----------------------------------------------------------------
// 2. Claim window (una sola vez — no liberar hasta destroy())
// ----------------------------------------------------------------
if (!SDL_ClaimWindowForGPUDevice(device_, window_)) {
SDL_Log("SDL3GPUShader: SDL_ClaimWindowForGPUDevice failed: %s", SDL_GetError());
SDL_DestroyGPUDevice(device_);
device_ = nullptr;
return false;
}
SDL_SetGPUSwapchainParameters(device_, window_, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, vsync_ ? SDL_GPU_PRESENTMODE_VSYNC : SDL_GPU_PRESENTMODE_IMMEDIATE);
}
// ----------------------------------------------------------------
// 3. Create scene texture (upload target + sampler source)
// Format: B8G8R8A8_UNORM matches SDL ARGB8888 byte layout on LE
// ----------------------------------------------------------------
SDL_GPUTextureCreateInfo tex_info = {};
tex_info.type = SDL_GPU_TEXTURETYPE_2D;
tex_info.format = SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM;
tex_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER;
tex_info.width = static_cast<Uint32>(tex_width_);
tex_info.height = static_cast<Uint32>(tex_height_);
tex_info.layer_count_or_depth = 1;
tex_info.num_levels = 1;
scene_texture_ = SDL_CreateGPUTexture(device_, &tex_info);
if (scene_texture_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create scene texture: %s", SDL_GetError());
cleanup();
return false;
}
SDL_Log("SDL3GPUShader: driver = %s", SDL_GetGPUDeviceDriver(device_));
// ----------------------------------------------------------------
// 2. Claim window (una sola vez — no liberar hasta destroy())
// 4. Create upload transfer buffer (CPU → GPU, size = w*h*4 bytes)
// ----------------------------------------------------------------
if (!SDL_ClaimWindowForGPUDevice(device_, window_)) {
SDL_Log("SDL3GPUShader: SDL_ClaimWindowForGPUDevice failed: %s", SDL_GetError());
SDL_GPUTransferBufferCreateInfo tb_info = {};
tb_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
tb_info.size = static_cast<Uint32>(tex_width_ * tex_height_ * 4);
upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info);
if (upload_buffer_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create upload buffer: %s", SDL_GetError());
cleanup();
return false;
}
// ----------------------------------------------------------------
// 5. Create nearest-neighbour sampler (retro pixel art)
// ----------------------------------------------------------------
SDL_GPUSamplerCreateInfo samp_info = {};
samp_info.min_filter = SDL_GPU_FILTER_NEAREST;
samp_info.mag_filter = SDL_GPU_FILTER_NEAREST;
samp_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
samp_info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
samp_info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
samp_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
sampler_ = SDL_CreateGPUSampler(device_, &samp_info);
if (sampler_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create sampler: %s", SDL_GetError());
cleanup();
return false;
}
// ----------------------------------------------------------------
// 6. Create PostFX graphics pipeline
// ----------------------------------------------------------------
if (!createPipeline()) {
cleanup();
return false;
}
is_initialized_ = true;
SDL_Log("SDL3GPUShader: initialized OK (%dx%d)", tex_width_, tex_height_);
return true;
}
// ---------------------------------------------------------------------------
// createPipeline
// ---------------------------------------------------------------------------
auto SDL3GPUShader::createPipeline() -> bool {
const SDL_GPUTextureFormat SWAPCHAIN_FMT = SDL_GetGPUSwapchainTextureFormat(device_, window_);
#ifdef __APPLE__
SDL_GPUShader* vert = createShaderMSL(device_, POSTFX_VERT_MSL, "postfx_vs", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
SDL_GPUShader* frag = createShaderMSL(device_, POSTFX_FRAG_MSL, "postfx_fs", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 1);
#else
SDL_GPUShader* vert = createShaderSPIRV(device_, kpostfx_vert_spv, kpostfx_vert_spv_size, "main", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
SDL_GPUShader* frag = createShaderSPIRV(device_, kpostfx_frag_spv, kpostfx_frag_spv_size, "main", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 1);
#endif
if ((vert == nullptr) || (frag == nullptr)) {
SDL_Log("SDL3GPUShader: failed to compile PostFX shaders");
if (vert != nullptr) { SDL_ReleaseGPUShader(device_, vert); }
if (frag != nullptr) { SDL_ReleaseGPUShader(device_, frag); }
return false;
}
SDL_GPUColorTargetBlendState no_blend = {};
no_blend.enable_blend = false;
no_blend.enable_color_write_mask = false;
SDL_GPUColorTargetDescription color_target = {};
color_target.format = SWAPCHAIN_FMT;
color_target.blend_state = no_blend;
SDL_GPUVertexInputState no_input = {};
SDL_GPUGraphicsPipelineCreateInfo pipe_info = {};
pipe_info.vertex_shader = vert;
pipe_info.fragment_shader = frag;
pipe_info.vertex_input_state = no_input;
pipe_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
pipe_info.target_info.num_color_targets = 1;
pipe_info.target_info.color_target_descriptions = &color_target;
pipeline_ = SDL_CreateGPUGraphicsPipeline(device_, &pipe_info);
SDL_ReleaseGPUShader(device_, vert);
SDL_ReleaseGPUShader(device_, frag);
if (pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: pipeline creation failed: %s", SDL_GetError());
return false;
}
return true;
}
// ---------------------------------------------------------------------------
// uploadPixels — copies ARGB8888 CPU pixels into the GPU transfer buffer
// ---------------------------------------------------------------------------
void SDL3GPUShader::uploadPixels(const Uint32* pixels, int width, int height) {
if (!is_initialized_ || (upload_buffer_ == nullptr)) { return; }
void* mapped = SDL_MapGPUTransferBuffer(device_, upload_buffer_, false);
if (mapped == nullptr) {
SDL_Log("SDL3GPUShader: SDL_MapGPUTransferBuffer failed: %s", SDL_GetError());
return;
}
std::memcpy(mapped, pixels, static_cast<size_t>(width * height * 4));
SDL_UnmapGPUTransferBuffer(device_, upload_buffer_);
}
// ---------------------------------------------------------------------------
// render — upload scene texture + PostFX pass → swapchain
// ---------------------------------------------------------------------------
void SDL3GPUShader::render() {
if (!is_initialized_) { return; }
SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(device_);
if (cmd == nullptr) {
SDL_Log("SDL3GPUShader: SDL_AcquireGPUCommandBuffer failed: %s", SDL_GetError());
return;
}
// ---- Copy pass: transfer buffer → scene texture ----
SDL_GPUCopyPass* copy = SDL_BeginGPUCopyPass(cmd);
if (copy != nullptr) {
SDL_GPUTextureTransferInfo src = {};
src.transfer_buffer = upload_buffer_;
src.offset = 0;
src.pixels_per_row = static_cast<Uint32>(tex_width_);
src.rows_per_layer = static_cast<Uint32>(tex_height_);
SDL_GPUTextureRegion dst = {};
dst.texture = scene_texture_;
dst.w = static_cast<Uint32>(tex_width_);
dst.h = static_cast<Uint32>(tex_height_);
dst.d = 1;
SDL_UploadToGPUTexture(copy, &src, &dst, false);
SDL_EndGPUCopyPass(copy);
}
// ---- Acquire swapchain texture ----
SDL_GPUTexture* swapchain = nullptr;
Uint32 sw = 0;
Uint32 sh = 0;
if (!SDL_AcquireGPUSwapchainTexture(cmd, window_, &swapchain, &sw, &sh)) {
SDL_Log("SDL3GPUShader: SDL_AcquireGPUSwapchainTexture failed: %s", SDL_GetError());
SDL_SubmitGPUCommandBuffer(cmd);
return;
}
if (swapchain == nullptr) {
// Window minimized — skip frame
SDL_SubmitGPUCommandBuffer(cmd);
return;
}
// ---- Render pass: PostFX → swapchain ----
SDL_GPUColorTargetInfo color_target = {};
color_target.texture = swapchain;
color_target.load_op = SDL_GPU_LOADOP_CLEAR;
color_target.store_op = SDL_GPU_STOREOP_STORE;
color_target.clear_color = {.r = 0.0F, .g = 0.0F, .b = 0.0F, .a = 1.0F};
SDL_GPURenderPass* pass = SDL_BeginGPURenderPass(cmd, &color_target, 1, nullptr);
if (pass != nullptr) {
SDL_BindGPUGraphicsPipeline(pass, pipeline_);
// Calcular viewport para mantener relación de aspecto (letterbox o integer scale)
float vx = 0.0F;
float vy = 0.0F;
float vw = 0.0F;
float vh = 0.0F;
if (integer_scale_) {
const int SCALE = std::max(1, std::min(static_cast<int>(sw) / tex_width_, static_cast<int>(sh) / tex_height_));
vw = static_cast<float>(tex_width_ * SCALE);
vh = static_cast<float>(tex_height_ * SCALE);
} else {
const float SCALE = std::min(
static_cast<float>(sw) / static_cast<float>(tex_width_),
static_cast<float>(sh) / static_cast<float>(tex_height_));
vw = static_cast<float>(tex_width_) * SCALE;
vh = static_cast<float>(tex_height_) * SCALE;
}
vx = std::floor((static_cast<float>(sw) - vw) * 0.5F);
vy = std::floor((static_cast<float>(sh) - vh) * 0.5F);
SDL_GPUViewport vp = {vx, vy, vw, vh, 0.0F, 1.0F};
SDL_SetGPUViewport(pass, &vp);
SDL_GPUTextureSamplerBinding binding = {};
binding.texture = scene_texture_;
binding.sampler = sampler_;
SDL_BindGPUFragmentSamplers(pass, 0, &binding, 1);
SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms_, sizeof(PostFXUniforms));
SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0);
SDL_EndGPURenderPass(pass);
}
SDL_SubmitGPUCommandBuffer(cmd);
}
// ---------------------------------------------------------------------------
// cleanup — libera pipeline/texturas/buffer pero mantiene device + swapchain
// ---------------------------------------------------------------------------
void SDL3GPUShader::cleanup() {
is_initialized_ = false;
if (device_ != nullptr) {
SDL_WaitForGPUIdle(device_);
if (pipeline_ != nullptr) {
SDL_ReleaseGPUGraphicsPipeline(device_, pipeline_);
pipeline_ = nullptr;
}
if (scene_texture_ != nullptr) {
SDL_ReleaseGPUTexture(device_, scene_texture_);
scene_texture_ = nullptr;
}
if (upload_buffer_ != nullptr) {
SDL_ReleaseGPUTransferBuffer(device_, upload_buffer_);
upload_buffer_ = nullptr;
}
if (sampler_ != nullptr) {
SDL_ReleaseGPUSampler(device_, sampler_);
sampler_ = nullptr;
}
// device_ y el claim de la ventana se mantienen vivos
}
}
// ---------------------------------------------------------------------------
// destroy — limpieza completa incluyendo device y swapchain (solo al cerrar)
// ---------------------------------------------------------------------------
void SDL3GPUShader::destroy() {
cleanup();
if (device_ != nullptr) {
if (window_ != nullptr) {
SDL_ReleaseWindowFromGPUDevice(device_, window_);
}
SDL_DestroyGPUDevice(device_);
device_ = nullptr;
return false;
}
SDL_SetGPUSwapchainParameters(device_, window_, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, vsync_ ? SDL_GPU_PRESENTMODE_VSYNC : SDL_GPU_PRESENTMODE_IMMEDIATE);
window_ = nullptr;
}
// ----------------------------------------------------------------
// 3. Create scene texture (upload target + sampler source)
// Format: B8G8R8A8_UNORM matches SDL ARGB8888 byte layout on LE
// ----------------------------------------------------------------
SDL_GPUTextureCreateInfo tex_info = {};
tex_info.type = SDL_GPU_TEXTURETYPE_2D;
tex_info.format = SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM;
tex_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER;
tex_info.width = static_cast<Uint32>(tex_width_);
tex_info.height = static_cast<Uint32>(tex_height_);
tex_info.layer_count_or_depth = 1;
tex_info.num_levels = 1;
scene_texture_ = SDL_CreateGPUTexture(device_, &tex_info);
if (scene_texture_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create scene texture: %s", SDL_GetError());
cleanup();
return false;
}
// ----------------------------------------------------------------
// 4. Create upload transfer buffer (CPU → GPU, size = w*h*4 bytes)
// ----------------------------------------------------------------
SDL_GPUTransferBufferCreateInfo tb_info = {};
tb_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
tb_info.size = static_cast<Uint32>(tex_width_ * tex_height_ * 4);
upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info);
if (upload_buffer_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create upload buffer: %s", SDL_GetError());
cleanup();
return false;
}
// ----------------------------------------------------------------
// 5. Create nearest-neighbour sampler (retro pixel art)
// ----------------------------------------------------------------
SDL_GPUSamplerCreateInfo samp_info = {};
samp_info.min_filter = SDL_GPU_FILTER_NEAREST;
samp_info.mag_filter = SDL_GPU_FILTER_NEAREST;
samp_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
samp_info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
samp_info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
samp_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
sampler_ = SDL_CreateGPUSampler(device_, &samp_info);
if (sampler_ == nullptr) {
SDL_Log("SDL3GPUShader: failed to create sampler: %s", SDL_GetError());
cleanup();
return false;
}
// ----------------------------------------------------------------
// 6. Create PostFX graphics pipeline
// ----------------------------------------------------------------
if (!createPipeline()) {
cleanup();
return false;
}
is_initialized_ = true;
SDL_Log("SDL3GPUShader: initialized OK (%dx%d)", tex_width_, tex_height_);
return true;
}
// ---------------------------------------------------------------------------
// createPipeline
// ---------------------------------------------------------------------------
auto SDL3GPUShader::createPipeline() -> bool {
const SDL_GPUTextureFormat SWAPCHAIN_FMT = SDL_GetGPUSwapchainTextureFormat(device_, window_);
#ifdef __APPLE__
SDL_GPUShader* vert = createShaderMSL(device_, POSTFX_VERT_MSL, "postfx_vs", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
SDL_GPUShader* frag = createShaderMSL(device_, POSTFX_FRAG_MSL, "postfx_fs", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 1);
#else
SDL_GPUShader* vert = createShaderSPIRV(device_, kpostfx_vert_spv, kpostfx_vert_spv_size, "main", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
SDL_GPUShader* frag = createShaderSPIRV(device_, kpostfx_frag_spv, kpostfx_frag_spv_size, "main", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 1);
#endif
if ((vert == nullptr) || (frag == nullptr)) {
SDL_Log("SDL3GPUShader: failed to compile PostFX shaders");
if (vert != nullptr) { SDL_ReleaseGPUShader(device_, vert); }
if (frag != nullptr) { SDL_ReleaseGPUShader(device_, frag); }
return false;
}
SDL_GPUColorTargetBlendState no_blend = {};
no_blend.enable_blend = false;
no_blend.enable_color_write_mask = false;
SDL_GPUColorTargetDescription color_target = {};
color_target.format = SWAPCHAIN_FMT;
color_target.blend_state = no_blend;
SDL_GPUVertexInputState no_input = {};
SDL_GPUGraphicsPipelineCreateInfo pipe_info = {};
pipe_info.vertex_shader = vert;
pipe_info.fragment_shader = frag;
pipe_info.vertex_input_state = no_input;
pipe_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
pipe_info.target_info.num_color_targets = 1;
pipe_info.target_info.color_target_descriptions = &color_target;
pipeline_ = SDL_CreateGPUGraphicsPipeline(device_, &pipe_info);
SDL_ReleaseGPUShader(device_, vert);
SDL_ReleaseGPUShader(device_, frag);
if (pipeline_ == nullptr) {
SDL_Log("SDL3GPUShader: pipeline creation failed: %s", SDL_GetError());
return false;
}
return true;
}
// ---------------------------------------------------------------------------
// uploadPixels — copies ARGB8888 CPU pixels into the GPU transfer buffer
// ---------------------------------------------------------------------------
void SDL3GPUShader::uploadPixels(const Uint32* pixels, int width, int height) {
if (!is_initialized_ || (upload_buffer_ == nullptr)) { return; }
void* mapped = SDL_MapGPUTransferBuffer(device_, upload_buffer_, false);
if (mapped == nullptr) {
SDL_Log("SDL3GPUShader: SDL_MapGPUTransferBuffer failed: %s", SDL_GetError());
return;
}
std::memcpy(mapped, pixels, static_cast<size_t>(width * height * 4));
SDL_UnmapGPUTransferBuffer(device_, upload_buffer_);
}
// ---------------------------------------------------------------------------
// render — upload scene texture + PostFX pass → swapchain
// ---------------------------------------------------------------------------
void SDL3GPUShader::render() {
if (!is_initialized_) { return; }
SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(device_);
if (cmd == nullptr) {
SDL_Log("SDL3GPUShader: SDL_AcquireGPUCommandBuffer failed: %s", SDL_GetError());
return;
}
// ---- Copy pass: transfer buffer → scene texture ----
SDL_GPUCopyPass* copy = SDL_BeginGPUCopyPass(cmd);
if (copy != nullptr) {
SDL_GPUTextureTransferInfo src = {};
src.transfer_buffer = upload_buffer_;
src.offset = 0;
src.pixels_per_row = static_cast<Uint32>(tex_width_);
src.rows_per_layer = static_cast<Uint32>(tex_height_);
SDL_GPUTextureRegion dst = {};
dst.texture = scene_texture_;
dst.w = static_cast<Uint32>(tex_width_);
dst.h = static_cast<Uint32>(tex_height_);
dst.d = 1;
SDL_UploadToGPUTexture(copy, &src, &dst, false);
SDL_EndGPUCopyPass(copy);
}
// ---- Acquire swapchain texture ----
SDL_GPUTexture* swapchain = nullptr;
Uint32 sw = 0;
Uint32 sh = 0;
if (!SDL_AcquireGPUSwapchainTexture(cmd, window_, &swapchain, &sw, &sh)) {
SDL_Log("SDL3GPUShader: SDL_AcquireGPUSwapchainTexture failed: %s", SDL_GetError());
SDL_SubmitGPUCommandBuffer(cmd);
return;
}
if (swapchain == nullptr) {
// Window minimized — skip frame
SDL_SubmitGPUCommandBuffer(cmd);
return;
}
// ---- Render pass: PostFX → swapchain ----
SDL_GPUColorTargetInfo color_target = {};
color_target.texture = swapchain;
color_target.load_op = SDL_GPU_LOADOP_CLEAR;
color_target.store_op = SDL_GPU_STOREOP_STORE;
color_target.clear_color = {.r = 0.0F, .g = 0.0F, .b = 0.0F, .a = 1.0F};
SDL_GPURenderPass* pass = SDL_BeginGPURenderPass(cmd, &color_target, 1, nullptr);
if (pass != nullptr) {
SDL_BindGPUGraphicsPipeline(pass, pipeline_);
// Calcular viewport para mantener relación de aspecto (letterbox o integer scale)
float vx = 0.0F;
float vy = 0.0F;
float vw = 0.0F;
float vh = 0.0F;
if (integer_scale_) {
const int SCALE = std::max(1, std::min(static_cast<int>(sw) / tex_width_, static_cast<int>(sh) / tex_height_));
vw = static_cast<float>(tex_width_ * SCALE);
vh = static_cast<float>(tex_height_ * SCALE);
} else {
const float SCALE = std::min(
static_cast<float>(sw) / static_cast<float>(tex_width_),
static_cast<float>(sh) / static_cast<float>(tex_height_));
vw = static_cast<float>(tex_width_) * SCALE;
vh = static_cast<float>(tex_height_) * SCALE;
// ---------------------------------------------------------------------------
// Shader creation helpers
// ---------------------------------------------------------------------------
auto SDL3GPUShader::createShaderMSL(SDL_GPUDevice* device,
const char* msl_source,
const char* entrypoint,
SDL_GPUShaderStage stage,
Uint32 num_samplers,
Uint32 num_uniform_buffers) -> SDL_GPUShader* {
SDL_GPUShaderCreateInfo info = {};
info.code = reinterpret_cast<const Uint8*>(msl_source);
info.code_size = std::strlen(msl_source) + 1;
info.entrypoint = entrypoint;
info.format = SDL_GPU_SHADERFORMAT_MSL;
info.stage = stage;
info.num_samplers = num_samplers;
info.num_uniform_buffers = num_uniform_buffers;
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info);
if (shader == nullptr) {
SDL_Log("SDL3GPUShader: MSL shader '%s' failed: %s", entrypoint, SDL_GetError());
}
vx = std::floor((static_cast<float>(sw) - vw) * 0.5F);
vy = std::floor((static_cast<float>(sh) - vh) * 0.5F);
SDL_GPUViewport vp = {vx, vy, vw, vh, 0.0F, 1.0F};
SDL_SetGPUViewport(pass, &vp);
SDL_GPUTextureSamplerBinding binding = {};
binding.texture = scene_texture_;
binding.sampler = sampler_;
SDL_BindGPUFragmentSamplers(pass, 0, &binding, 1);
SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms_, sizeof(PostFXUniforms));
SDL_DrawGPUPrimitives(pass, 3, 1, 0, 0);
SDL_EndGPURenderPass(pass);
return shader;
}
SDL_SubmitGPUCommandBuffer(cmd);
}
// ---------------------------------------------------------------------------
// cleanup — libera pipeline/texturas/buffer pero mantiene device + swapchain
// ---------------------------------------------------------------------------
void SDL3GPUShader::cleanup() {
is_initialized_ = false;
if (device_ != nullptr) {
SDL_WaitForGPUIdle(device_);
if (pipeline_ != nullptr) {
SDL_ReleaseGPUGraphicsPipeline(device_, pipeline_);
pipeline_ = nullptr;
auto SDL3GPUShader::createShaderSPIRV(SDL_GPUDevice* device,
const uint8_t* spv_code,
size_t spv_size,
const char* entrypoint,
SDL_GPUShaderStage stage,
Uint32 num_samplers,
Uint32 num_uniform_buffers) -> SDL_GPUShader* {
SDL_GPUShaderCreateInfo info = {};
info.code = spv_code;
info.code_size = spv_size;
info.entrypoint = entrypoint;
info.format = SDL_GPU_SHADERFORMAT_SPIRV;
info.stage = stage;
info.num_samplers = num_samplers;
info.num_uniform_buffers = num_uniform_buffers;
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info);
if (shader == nullptr) {
SDL_Log("SDL3GPUShader: SPIRV shader '%s' failed: %s", entrypoint, SDL_GetError());
}
if (scene_texture_ != nullptr) {
SDL_ReleaseGPUTexture(device_, scene_texture_);
scene_texture_ = nullptr;
return shader;
}
void SDL3GPUShader::setPostFXParams(const PostFXParams& p) {
uniforms_.vignette_strength = p.vignette;
uniforms_.scanline_strength = p.scanlines;
uniforms_.chroma_strength = p.chroma;
uniforms_.mask_strength = p.mask;
uniforms_.gamma_strength = p.gamma;
uniforms_.curvature = p.curvature;
uniforms_.bleeding = p.bleeding;
}
void SDL3GPUShader::setVSync(bool vsync) {
vsync_ = vsync;
if (device_ != nullptr && window_ != nullptr) {
SDL_SetGPUSwapchainParameters(device_, window_, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, vsync_ ? SDL_GPU_PRESENTMODE_VSYNC : SDL_GPU_PRESENTMODE_IMMEDIATE);
}
if (upload_buffer_ != nullptr) {
SDL_ReleaseGPUTransferBuffer(device_, upload_buffer_);
upload_buffer_ = nullptr;
}
if (sampler_ != nullptr) {
SDL_ReleaseGPUSampler(device_, sampler_);
sampler_ = nullptr;
}
// device_ y el claim de la ventana se mantienen vivos
}
}
// ---------------------------------------------------------------------------
// destroy — limpieza completa incluyendo device y swapchain (solo al cerrar)
// ---------------------------------------------------------------------------
void SDL3GPUShader::destroy() {
cleanup();
if (device_ != nullptr) {
if (window_ != nullptr) {
SDL_ReleaseWindowFromGPUDevice(device_, window_);
}
SDL_DestroyGPUDevice(device_);
device_ = nullptr;
void SDL3GPUShader::setScaleMode(bool integer_scale) {
integer_scale_ = integer_scale;
}
window_ = nullptr;
}
// ---------------------------------------------------------------------------
// Shader creation helpers
// ---------------------------------------------------------------------------
auto SDL3GPUShader::createShaderMSL(SDL_GPUDevice* device,
const char* msl_source,
const char* entrypoint,
SDL_GPUShaderStage stage,
Uint32 num_samplers,
Uint32 num_uniform_buffers) -> SDL_GPUShader* {
SDL_GPUShaderCreateInfo info = {};
info.code = reinterpret_cast<const Uint8*>(msl_source);
info.code_size = std::strlen(msl_source) + 1;
info.entrypoint = entrypoint;
info.format = SDL_GPU_SHADERFORMAT_MSL;
info.stage = stage;
info.num_samplers = num_samplers;
info.num_uniform_buffers = num_uniform_buffers;
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info);
if (shader == nullptr) {
SDL_Log("SDL3GPUShader: MSL shader '%s' failed: %s", entrypoint, SDL_GetError());
}
return shader;
}
auto SDL3GPUShader::createShaderSPIRV(SDL_GPUDevice* device,
const uint8_t* spv_code,
size_t spv_size,
const char* entrypoint,
SDL_GPUShaderStage stage,
Uint32 num_samplers,
Uint32 num_uniform_buffers) -> SDL_GPUShader* {
SDL_GPUShaderCreateInfo info = {};
info.code = spv_code;
info.code_size = spv_size;
info.entrypoint = entrypoint;
info.format = SDL_GPU_SHADERFORMAT_SPIRV;
info.stage = stage;
info.num_samplers = num_samplers;
info.num_uniform_buffers = num_uniform_buffers;
SDL_GPUShader* shader = SDL_CreateGPUShader(device, &info);
if (shader == nullptr) {
SDL_Log("SDL3GPUShader: SPIRV shader '%s' failed: %s", entrypoint, SDL_GetError());
}
return shader;
}
void SDL3GPUShader::setPostFXParams(const PostFXParams& p) {
uniforms_.vignette_strength = p.vignette;
uniforms_.scanline_strength = p.scanlines;
uniforms_.chroma_strength = p.chroma;
uniforms_.mask_strength = p.mask;
uniforms_.gamma_strength = p.gamma;
uniforms_.curvature = p.curvature;
uniforms_.bleeding = p.bleeding;
}
void SDL3GPUShader::setVSync(bool vsync) {
vsync_ = vsync;
if (device_ != nullptr && window_ != nullptr) {
SDL_SetGPUSwapchainParameters(device_, window_, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, vsync_ ? SDL_GPU_PRESENTMODE_VSYNC : SDL_GPU_PRESENTMODE_IMMEDIATE);
}
}
void SDL3GPUShader::setScaleMode(bool integer_scale) {
integer_scale_ = integer_scale;
}
} // namespace Rendering

View File

@@ -9,27 +9,27 @@
// Must match the MSL struct and GLSL uniform block layout.
// 8 floats = 32 bytes — meets Metal/Vulkan 16-byte alignment requirement.
struct PostFXUniforms {
float vignette_strength; // 0 = none, ~0.8 = subtle
float chroma_strength; // 0 = off, ~0.2 = subtle chromatic aberration
float scanline_strength; // 0 = off, 1 = full
float screen_height; // logical height in pixels (for resolution-independent scanlines)
float mask_strength; // 0 = off, 1 = full phosphor dot mask
float gamma_strength; // 0 = off, 1 = full gamma 2.4/2.2 correction
float curvature; // 0 = flat, 1 = max barrel distortion
float bleeding; // 0 = off, 1 = max NTSC chrominance bleeding
float vignette_strength; // 0 = none, ~0.8 = subtle
float chroma_strength; // 0 = off, ~0.2 = subtle chromatic aberration
float scanline_strength; // 0 = off, 1 = full
float screen_height; // logical height in pixels (for resolution-independent scanlines)
float mask_strength; // 0 = off, 1 = full phosphor dot mask
float gamma_strength; // 0 = off, 1 = full gamma 2.4/2.2 correction
float curvature; // 0 = flat, 1 = max barrel distortion
float bleeding; // 0 = off, 1 = max NTSC chrominance bleeding
};
namespace Rendering {
/**
* @brief Backend de shaders usando SDL3 GPU API (Metal en macOS, Vulkan/SPIR-V en Win/Linux)
*
* Reemplaza el backend OpenGL para que los shaders PostFX funcionen en macOS.
* Pipeline: Surface pixels (CPU) → SDL_GPUTransferBuffer → SDL_GPUTexture (scene)
* → PostFX render pass → swapchain → present
*/
class SDL3GPUShader : public ShaderBackend {
public:
/**
* @brief Backend de shaders usando SDL3 GPU API (Metal en macOS, Vulkan/SPIR-V en Win/Linux)
*
* Reemplaza el backend OpenGL para que los shaders PostFX funcionen en macOS.
* Pipeline: Surface pixels (CPU) → SDL_GPUTransferBuffer → SDL_GPUTexture (scene)
* → PostFX render pass → swapchain → present
*/
class SDL3GPUShader : public ShaderBackend {
public:
SDL3GPUShader() = default;
~SDL3GPUShader() override;
@@ -41,7 +41,7 @@ class SDL3GPUShader : public ShaderBackend {
void render() override;
void setTextureSize(float width, float height) override {}
void cleanup() final; // Libera pipeline/texturas pero mantiene el device vivo
void destroy(); // Limpieza completa (device + swapchain); llamar solo al cerrar
void destroy(); // Limpieza completa (device + swapchain); llamar solo al cerrar
[[nodiscard]] auto isHardwareAccelerated() const -> bool override { return is_initialized_; }
// Sube píxeles ARGB8888 desde CPU; llamado antes de render()
@@ -56,7 +56,7 @@ class SDL3GPUShader : public ShaderBackend {
// Activa/desactiva escalado entero (integer scale)
void setScaleMode(bool integer_scale) override;
private:
private:
static auto createShaderMSL(SDL_GPUDevice* device,
const char* msl_source,
const char* entrypoint,
@@ -88,6 +88,6 @@ class SDL3GPUShader : public ShaderBackend {
bool is_initialized_ = false;
bool vsync_ = true;
bool integer_scale_ = false;
};
};
} // namespace Rendering

View File

@@ -6,11 +6,11 @@
namespace Rendering {
/**
* @brief Parámetros de intensidad de los efectos PostFX
* Definido a nivel de namespace para facilitar el uso desde subclases y screen.cpp
*/
struct PostFXParams {
/**
* @brief Parámetros de intensidad de los efectos PostFX
* Definido a nivel de namespace para facilitar el uso desde subclases y screen.cpp
*/
struct PostFXParams {
float vignette = 0.0F; // Intensidad de la viñeta
float scanlines = 0.0F; // Intensidad de las scanlines
float chroma = 0.0F; // Aberración cromática
@@ -18,16 +18,16 @@ struct PostFXParams {
float gamma = 0.0F; // Corrección gamma (blend 0=off, 1=full)
float curvature = 0.0F; // Curvatura barrel CRT
float bleeding = 0.0F; // Sangrado de color NTSC
};
};
/**
* @brief Interfaz abstracta para backends de renderizado con shaders
*
* Esta interfaz define el contrato que todos los backends de shaders
* deben cumplir (OpenGL, Metal, Vulkan, etc.)
*/
class ShaderBackend {
public:
/**
* @brief Interfaz abstracta para backends de renderizado con shaders
*
* Esta interfaz define el contrato que todos los backends de shaders
* deben cumplir (OpenGL, Metal, Vulkan, etc.)
*/
class ShaderBackend {
public:
virtual ~ShaderBackend() = default;
/**
@@ -87,6 +87,6 @@ class ShaderBackend {
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
*/
[[nodiscard]] virtual auto isHardwareAccelerated() const -> bool = 0;
};
};
} // namespace Rendering

View File

@@ -21,129 +21,129 @@ auto loadPalette(const std::string& file_path) -> Palette;
auto readPalFile(const std::string& file_path) -> Palette;
struct SurfaceData {
std::shared_ptr<Uint8[]> data; // Usa std::shared_ptr para gestión automática
float width; // Ancho de la imagen
float height; // Alto de la imagen
std::shared_ptr<Uint8[]> data; // Usa std::shared_ptr para gestión automática
float width; // Ancho de la imagen
float height; // Alto de la imagen
// Constructor por defecto
SurfaceData()
: data(nullptr),
width(0),
height(0) {}
// Constructor por defecto
SurfaceData()
: data(nullptr),
width(0),
height(0) {}
// Constructor que inicializa dimensiones y asigna memoria
SurfaceData(float w, float h)
: data(std::shared_ptr<Uint8[]>(new Uint8[static_cast<size_t>(w * h)](), std::default_delete<Uint8[]>())),
width(w),
height(h) {}
// Constructor que inicializa dimensiones y asigna memoria
SurfaceData(float w, float h)
: data(std::shared_ptr<Uint8[]>(new Uint8[static_cast<size_t>(w * h)](), std::default_delete<Uint8[]>())),
width(w),
height(h) {}
// Constructor para inicializar directamente con datos
SurfaceData(float w, float h, std::shared_ptr<Uint8[]> pixels)
: data(std::move(pixels)),
width(w),
height(h) {}
// Constructor para inicializar directamente con datos
SurfaceData(float w, float h, std::shared_ptr<Uint8[]> pixels)
: data(std::move(pixels)),
width(w),
height(h) {}
// Constructor de movimiento
SurfaceData(SurfaceData&& other) noexcept = default;
// Constructor de movimiento
SurfaceData(SurfaceData&& other) noexcept = default;
// Operador de movimiento
auto operator=(SurfaceData&& other) noexcept -> SurfaceData& = default;
// Operador de movimiento
auto operator=(SurfaceData&& other) noexcept -> SurfaceData& = default;
// Evita copias accidentales
SurfaceData(const SurfaceData&) = delete;
auto operator=(const SurfaceData&) -> SurfaceData& = delete;
// Evita copias accidentales
SurfaceData(const SurfaceData&) = delete;
auto operator=(const SurfaceData&) -> SurfaceData& = delete;
};
class Surface {
private:
std::shared_ptr<SurfaceData> surface_data_; // Datos a dibujar
Palette palette_; // Paleta para volcar la SurfaceData a una Textura
SubPalette sub_palette_; // Paleta para reindexar colores
int transparent_color_; // Indice de la paleta que se omite en la copia de datos
private:
std::shared_ptr<SurfaceData> surface_data_; // Datos a dibujar
Palette palette_; // Paleta para volcar la SurfaceData a una Textura
SubPalette sub_palette_; // Paleta para reindexar colores
int transparent_color_; // Indice de la paleta que se omite en la copia de datos
public:
// Constructor
Surface(int w, int h);
explicit Surface(const std::string& file_path);
public:
// Constructor
Surface(int w, int h);
explicit Surface(const std::string& file_path);
// Destructor
~Surface() = default;
// Destructor
~Surface() = default;
// Carga una SurfaceData desde un archivo
static auto loadSurface(const std::string& file_path) -> SurfaceData;
// Carga una SurfaceData desde un archivo
static auto loadSurface(const std::string& file_path) -> SurfaceData;
// Carga una paleta desde un archivo
void loadPalette(const std::string& file_path);
void loadPalette(const Palette& palette);
// Carga una paleta desde un archivo
void loadPalette(const std::string& file_path);
void loadPalette(const Palette& palette);
// Copia una región de la SurfaceData de origen a la SurfaceData de destino
void render(float dx, float dy, float sx, float sy, float w, float h);
void render(int x, int y, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
void render(SDL_FRect* src_rect = nullptr, SDL_FRect* dst_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
// Copia una región de la SurfaceData de origen a la SurfaceData de destino
void render(float dx, float dy, float sx, float sy, float w, float h);
void render(int x, int y, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
void render(SDL_FRect* src_rect = nullptr, SDL_FRect* dst_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
// Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro
void renderWithColorReplace(int x, int y, Uint8 source_color = 0, Uint8 target_color = 0, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
// Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro
void renderWithColorReplace(int x, int y, Uint8 source_color = 0, Uint8 target_color = 0, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE);
// Render amb dissolució als cantons superior/inferior (hash 2D, sense parpelleig)
void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, SDL_FRect* src_rect = nullptr);
// Render amb dissolució als cantons superior/inferior (hash 2D, sense parpelleig)
void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, SDL_FRect* src_rect = nullptr);
// Idem però reemplaçant un color índex (per a sprites sobre fons del mateix color)
void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect = nullptr);
// Idem però reemplaçant un color índex (per a sprites sobre fons del mateix color)
void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect = nullptr);
// Establece un color en la paleta
void setColor(int index, Uint32 color);
// Establece un color en la paleta
void setColor(int index, Uint32 color);
// Rellena la SurfaceData con un color
void clear(Uint8 color);
// Rellena la SurfaceData con un color
void clear(Uint8 color);
// Vuelca la SurfaceData a una textura
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture);
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect);
// Vuelca la SurfaceData a una textura
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture);
void copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect);
// Realiza un efecto de fundido en las paletas
auto fadePalette() -> bool;
auto fadeSubPalette(Uint32 delay = 0) -> bool;
// Realiza un efecto de fundido en las paletas
auto fadePalette() -> bool;
auto fadeSubPalette(Uint32 delay = 0) -> bool;
// Vuelca los píxeles como ARGB8888 a un buffer externo (sin SDL_Texture)
void toARGBBuffer(Uint32* buffer) const;
// Vuelca los píxeles como ARGB8888 a un buffer externo (sin SDL_Texture)
void toARGBBuffer(Uint32* buffer) const;
// Pone un pixel en la SurfaceData
void putPixel(int x, int y, Uint8 color);
// Pone un pixel en la SurfaceData
void putPixel(int x, int y, Uint8 color);
// Obtiene el color de un pixel de la surface_data
auto getPixel(int x, int y) -> Uint8;
// Obtiene el color de un pixel de la surface_data
auto getPixel(int x, int y) -> Uint8;
// Dibuja un rectangulo relleno
void fillRect(const SDL_FRect* rect, Uint8 color);
// Dibuja un rectangulo relleno
void fillRect(const SDL_FRect* rect, Uint8 color);
// Dibuja el borde de un rectangulo
void drawRectBorder(const SDL_FRect* rect, Uint8 color);
// Dibuja el borde de un rectangulo
void drawRectBorder(const SDL_FRect* rect, Uint8 color);
// Dibuja una linea
void drawLine(float x1, float y1, float x2, float y2, Uint8 color);
// Dibuja una linea
void drawLine(float x1, float y1, float x2, float y2, Uint8 color);
// Metodos para gestionar surface_data_
[[nodiscard]] auto getSurfaceData() const -> std::shared_ptr<SurfaceData> { return surface_data_; }
void setSurfaceData(std::shared_ptr<SurfaceData> new_data) { surface_data_ = std::move(new_data); }
// Metodos para gestionar surface_data_
[[nodiscard]] auto getSurfaceData() const -> std::shared_ptr<SurfaceData> { return surface_data_; }
void setSurfaceData(std::shared_ptr<SurfaceData> new_data) { surface_data_ = std::move(new_data); }
// Obtien ancho y alto
[[nodiscard]] auto getWidth() const -> float { return surface_data_->width; }
[[nodiscard]] auto getHeight() const -> float { return surface_data_->height; }
// Obtien ancho y alto
[[nodiscard]] auto getWidth() const -> float { return surface_data_->width; }
[[nodiscard]] auto getHeight() const -> float { return surface_data_->height; }
// Color transparente
[[nodiscard]] auto getTransparentColor() const -> Uint8 { return transparent_color_; }
void setTransparentColor(Uint8 color = 255) { transparent_color_ = color; }
// Color transparente
[[nodiscard]] auto getTransparentColor() const -> Uint8 { return transparent_color_; }
void setTransparentColor(Uint8 color = 255) { transparent_color_ = color; }
// Paleta
void setPalette(const std::array<Uint32, 256>& palette) { palette_ = palette; }
// Paleta
void setPalette(const std::array<Uint32, 256>& palette) { palette_ = palette; }
// Inicializa la sub paleta
static void initializeSubPalette(SubPalette& palette) { std::iota(palette.begin(), palette.end(), 0); }
// Inicializa la sub paleta
static void initializeSubPalette(SubPalette& palette) { std::iota(palette.begin(), palette.end(), 0); }
private:
// Helper para calcular coordenadas con flip
static void calculateFlippedCoords(int ix, int iy, float sx, float sy, float w, float h, SDL_FlipMode flip, int& src_x, int& src_y);
private:
// Helper para calcular coordenadas con flip
static void calculateFlippedCoords(int ix, int iy, float sx, float sy, float w, float h, SDL_FlipMode flip, int& src_x, int& src_y);
// Helper para copiar un pixel si no es transparente
void copyPixelIfNotTransparent(Uint8* dest_data, int dest_x, int dest_y, int dest_width, int src_x, int src_y) const;
// Helper para copiar un pixel si no es transparente
void copyPixelIfNotTransparent(Uint8* dest_data, int dest_x, int dest_y, int dest_width, int src_x, int src_y) const;
};

View File

@@ -13,50 +13,50 @@
class Surface;
class SurfaceAnimatedSprite : public SurfaceMovingSprite {
public:
using Animations = std::vector<std::string>; // Tipo para lista de animaciones
public:
using Animations = std::vector<std::string>; // Tipo para lista de animaciones
// Estructura pública de datos de animación
struct AnimationData {
std::string name; // Nombre de la animacion
std::vector<SDL_FRect> frames; // Cada uno de los frames que componen la animación
float speed{0.083F}; // Velocidad de la animación (segundos por frame)
int loop{0}; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed{false}; // Indica si ha finalizado la animación
int current_frame{0}; // Frame actual
float accumulated_time{0.0F}; // Tiempo acumulado para las animaciones (time-based)
};
// Estructura pública de datos de animación
struct AnimationData {
std::string name; // Nombre de la animacion
std::vector<SDL_FRect> frames; // Cada uno de los frames que componen la animación
float speed{0.083F}; // Velocidad de la animación (segundos por frame)
int loop{0}; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed{false}; // Indica si ha finalizado la animación
int current_frame{0}; // Frame actual
float accumulated_time{0.0F}; // Tiempo acumulado para las animaciones (time-based)
};
// Métodos estáticos
static auto loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr<Surface>& surface, float& frame_width, float& frame_height) -> std::vector<AnimationData>; // Carga las animaciones desde fichero YAML
// Métodos estáticos
static auto loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr<Surface>& surface, float& frame_width, float& frame_height) -> std::vector<AnimationData>; // Carga las animaciones desde fichero YAML
// Constructores
explicit SurfaceAnimatedSprite(const AnimationResource& cached_data); // Constructor con datos pre-cargados del cache
// Constructores
explicit SurfaceAnimatedSprite(const AnimationResource& cached_data); // Constructor con datos pre-cargados del cache
~SurfaceAnimatedSprite() override = default; // Destructor
~SurfaceAnimatedSprite() override = default; // Destructor
void update(float delta_time) override; // Actualiza las variables del objeto (time-based)
void update(float delta_time) override; // Actualiza las variables del objeto (time-based)
// Consultas de estado
auto animationIsCompleted() -> bool; // Comprueba si ha terminado la animación
auto getIndex(const std::string& name) -> int; // Obtiene el índice de la animación por nombre
auto getCurrentAnimationSize() -> int { return static_cast<int>(animations_[current_animation_].frames.size()); } // Número de frames de la animación actual
// Consultas de estado
auto animationIsCompleted() -> bool; // Comprueba si ha terminado la animación
auto getIndex(const std::string& name) -> int; // Obtiene el índice de la animación por nombre
auto getCurrentAnimationSize() -> int { return static_cast<int>(animations_[current_animation_].frames.size()); } // Número de frames de la animación actual
// Modificadores de animación
void setCurrentAnimation(const std::string& name = "default"); // Establece la animación actual por nombre
void setCurrentAnimation(int index = 0); // Establece la animación actual por índice
void resetAnimation(); // Reinicia la animación
void setCurrentAnimationFrame(int num); // Establece el frame actual de la animación
// Modificadores de animación
void setCurrentAnimation(const std::string& name = "default"); // Establece la animación actual por nombre
void setCurrentAnimation(int index = 0); // Establece la animación actual por índice
void resetAnimation(); // Reinicia la animación
void setCurrentAnimationFrame(int num); // Establece el frame actual de la animación
protected:
// Constructor per a ús de subclasses que gestionen la surface directament (sense YAML)
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, SDL_FRect pos);
protected:
// Constructor per a ús de subclasses que gestionen la surface directament (sense YAML)
SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, SDL_FRect pos);
// Métodos protegidos
void animate(float delta_time); // Calcula el frame correspondiente a la animación actual (time-based)
// Métodos protegidos
void animate(float delta_time); // Calcula el frame correspondiente a la animación actual (time-based)
private:
// Variables miembro
std::vector<AnimationData> animations_; // Vector con las diferentes animaciones
int current_animation_{0}; // Animación activa
private:
// Variables miembro
std::vector<AnimationData> animations_; // Vector con las diferentes animaciones
int current_animation_{0}; // Animación activa
};

View File

@@ -16,47 +16,47 @@ enum class DissolveDirection { NONE,
// Sprite que pot dissoldre's o generar-se de forma aleatòria en X mil·lisegons.
// progress_ va de 0.0 (totalment visible) a 1.0 (totalment invisible).
class SurfaceDissolveSprite : public SurfaceAnimatedSprite {
public:
explicit SurfaceDissolveSprite(const AnimationResource& data);
SurfaceDissolveSprite(std::shared_ptr<Surface> surface, SDL_FRect pos);
~SurfaceDissolveSprite() override = default;
public:
explicit SurfaceDissolveSprite(const AnimationResource& data);
SurfaceDissolveSprite(std::shared_ptr<Surface> surface, SDL_FRect pos);
~SurfaceDissolveSprite() override = default;
void update(float delta_time) override;
void render() override;
void update(float delta_time) override;
void render() override;
// Progrés manual [0.0 = totalment visible, 1.0 = totalment invisible]
void setProgress(float progress);
[[nodiscard]] auto getProgress() const -> float { return progress_; }
// Progrés manual [0.0 = totalment visible, 1.0 = totalment invisible]
void setProgress(float progress);
[[nodiscard]] auto getProgress() const -> float { return progress_; }
// Inicia una dissolució temporal (visible → invisible en duration_ms)
void startDissolve(float duration_ms, DissolveDirection dir = DissolveDirection::NONE);
// Inicia una dissolució temporal (visible → invisible en duration_ms)
void startDissolve(float duration_ms, DissolveDirection dir = DissolveDirection::NONE);
// Inicia una generació temporal (invisible → visible en duration_ms)
void startGenerate(float duration_ms, DissolveDirection dir = DissolveDirection::NONE);
// Inicia una generació temporal (invisible → visible en duration_ms)
void startGenerate(float duration_ms, DissolveDirection dir = DissolveDirection::NONE);
void stopTransition();
[[nodiscard]] auto isTransitionDone() const -> bool;
void stopTransition();
[[nodiscard]] auto isTransitionDone() const -> bool;
// Substitució de color: en reconstruir, substitueix source per target
void setColorReplace(Uint8 source, Uint8 target);
// Substitució de color: en reconstruir, substitueix source per target
void setColorReplace(Uint8 source, Uint8 target);
private:
enum class TransitionMode { NONE,
DISSOLVING,
GENERATING };
private:
enum class TransitionMode { NONE,
DISSOLVING,
GENERATING };
std::shared_ptr<Surface> surface_display_; // Superfície amb els píxels filtrats
std::shared_ptr<Surface> surface_display_; // Superfície amb els píxels filtrats
float progress_{0.0F}; // [0=visible, 1=invisible]
DissolveDirection direction_{DissolveDirection::NONE};
TransitionMode transition_mode_{TransitionMode::NONE};
float transition_duration_{0.0F};
float transition_elapsed_{0.0F};
SDL_FRect prev_clip_{0, 0, 0, 0};
bool needs_rebuild_{false};
Uint8 source_color_{255}; // 255 = transparent = sense replace per defecte
Uint8 target_color_{0};
float progress_{0.0F}; // [0=visible, 1=invisible]
DissolveDirection direction_{DissolveDirection::NONE};
TransitionMode transition_mode_{TransitionMode::NONE};
float transition_duration_{0.0F};
float transition_elapsed_{0.0F};
SDL_FRect prev_clip_{0, 0, 0, 0};
bool needs_rebuild_{false};
Uint8 source_color_{255}; // 255 = transparent = sense replace per defecte
Uint8 target_color_{0};
void rebuildDisplaySurface();
[[nodiscard]] static auto computePixelRank(int col, int row, int frame_h, DissolveDirection dir) -> float;
void rebuildDisplaySurface();
[[nodiscard]] static auto computePixelRank(int col, int row, int frame_h, DissolveDirection dir) -> float;
};

View File

@@ -9,69 +9,69 @@ class Surface; // lines 8-8
// Clase SMovingSprite. Añade movimiento y flip al sprite
class SurfaceMovingSprite : public SurfaceSprite {
public:
// Constructores
SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos, SDL_FlipMode flip);
SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos);
explicit SurfaceMovingSprite();
explicit SurfaceMovingSprite(std::shared_ptr<Surface> surface);
~SurfaceMovingSprite() override = default;
public:
// Constructores
SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos, SDL_FlipMode flip);
SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos);
explicit SurfaceMovingSprite();
explicit SurfaceMovingSprite(std::shared_ptr<Surface> surface);
~SurfaceMovingSprite() override = default;
// Actualización y renderizado
void update(float delta_time) override; // Actualiza variables internas (time-based)
void render() override; // Muestra el sprite por pantalla
void render(Uint8 source_color, Uint8 target_color) override; // Renderiza con reemplazo de color
// Actualización y renderizado
void update(float delta_time) override; // Actualiza variables internas (time-based)
void render() override; // Muestra el sprite por pantalla
void render(Uint8 source_color, Uint8 target_color) override; // Renderiza con reemplazo de color
// Gestión de estado
void clear() override; // Reinicia todas las variables a cero
// Gestión de estado
void clear() override; // Reinicia todas las variables a cero
// Getters de posición
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
// Getters de posición
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
// Getters de velocidad
[[nodiscard]] auto getVelX() const -> float { return vx_; }
[[nodiscard]] auto getVelY() const -> float { return vy_; }
// Getters de velocidad
[[nodiscard]] auto getVelX() const -> float { return vx_; }
[[nodiscard]] auto getVelY() const -> float { return vy_; }
// Getters de aceleración
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
// Getters de aceleración
[[nodiscard]] auto getAccelX() const -> float { return ax_; }
[[nodiscard]] auto getAccelY() const -> float { return ay_; }
// Setters de posición
void setPos(SDL_FRect rect); // Establece posición y tamaño del objeto
void setPos(float x, float y); // Establece posición x, y
void setPosX(float value); // Establece posición X
void setPosY(float value); // Establece posición Y
// Setters de posición
void setPos(SDL_FRect rect); // Establece posición y tamaño del objeto
void setPos(float x, float y); // Establece posición x, y
void setPosX(float value); // Establece posición X
void setPosY(float value); // Establece posición Y
// Setters de velocidad
void setVelX(float value) { vx_ = value; }
void setVelY(float value) { vy_ = value; }
// Setters de velocidad
void setVelX(float value) { vx_ = value; }
void setVelY(float value) { vy_ = value; }
// Setters de aceleración
void setAccelX(float value) { ax_ = value; }
void setAccelY(float value) { ay_ = value; }
// Setters de aceleración
void setAccelX(float value) { ax_ = value; }
void setAccelY(float value) { ay_ = value; }
// Gestión de flip (volteo horizontal)
void setFlip(SDL_FlipMode flip) { flip_ = flip; } // Establece modo de flip
auto getFlip() -> SDL_FlipMode { return flip_; } // Obtiene modo de flip
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; } // Alterna flip horizontal
// Gestión de flip (volteo horizontal)
void setFlip(SDL_FlipMode flip) { flip_ = flip; } // Establece modo de flip
auto getFlip() -> SDL_FlipMode { return flip_; } // Obtiene modo de flip
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; } // Alterna flip horizontal
protected:
// Métodos protegidos
void move(float delta_time); // Mueve el sprite (time-based)
protected:
// Métodos protegidos
void move(float delta_time); // Mueve el sprite (time-based)
// Variables miembro - Posición
float x_{0.0F}; // Posición en el eje X
float y_{0.0F}; // Posición en el eje Y
// Variables miembro - Posición
float x_{0.0F}; // Posición en el eje X
float y_{0.0F}; // Posición en el eje Y
// Variables miembro - Velocidad (pixels/segundo)
float vx_{0.0F}; // Velocidad en el eje X
float vy_{0.0F}; // Velocidad en el eje Y
// Variables miembro - Velocidad (pixels/segundo)
float vx_{0.0F}; // Velocidad en el eje X
float vy_{0.0F}; // Velocidad en el eje Y
// Variables miembro - Aceleración (pixels/segundo²)
float ax_{0.0F}; // Aceleración en el eje X
float ay_{0.0F}; // Aceleración en el eje Y
// Variables miembro - Aceleración (pixels/segundo²)
float ax_{0.0F}; // Aceleración en el eje X
float ay_{0.0F}; // Aceleración en el eje Y
// Variables miembro - Renderizado
SDL_FlipMode flip_{SDL_FLIP_NONE}; // Modo de volteo del sprite
// Variables miembro - Renderizado
SDL_FlipMode flip_{SDL_FLIP_NONE}; // Modo de volteo del sprite
};

View File

@@ -8,55 +8,55 @@ class Surface; // lines 5-5
// Clase SurfaceSprite
class SurfaceSprite {
public:
// Constructores
SurfaceSprite(std::shared_ptr<Surface>, float x, float y, float w, float h);
SurfaceSprite(std::shared_ptr<Surface>, SDL_FRect rect);
SurfaceSprite();
explicit SurfaceSprite(std::shared_ptr<Surface>);
public:
// Constructores
SurfaceSprite(std::shared_ptr<Surface>, float x, float y, float w, float h);
SurfaceSprite(std::shared_ptr<Surface>, SDL_FRect rect);
SurfaceSprite();
explicit SurfaceSprite(std::shared_ptr<Surface>);
// Destructor
virtual ~SurfaceSprite() = default;
// Destructor
virtual ~SurfaceSprite() = default;
// Actualización y renderizado
virtual void update(float delta_time); // Actualiza el estado del sprite (time-based)
virtual void render(); // Muestra el sprite por pantalla
virtual void render(Uint8 source_color, Uint8 target_color); // Renderiza con reemplazo de color
virtual void renderWithVerticalFade(int fade_h, int canvas_height); // Renderiza amb dissolució vertical (hash 2D, sense parpelleig)
virtual void renderWithVerticalFade(int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color); // Idem amb reemplaç de color
// Actualización y renderizado
virtual void update(float delta_time); // Actualiza el estado del sprite (time-based)
virtual void render(); // Muestra el sprite por pantalla
virtual void render(Uint8 source_color, Uint8 target_color); // Renderiza con reemplazo de color
virtual void renderWithVerticalFade(int fade_h, int canvas_height); // Renderiza amb dissolució vertical (hash 2D, sense parpelleig)
virtual void renderWithVerticalFade(int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color); // Idem amb reemplaç de color
// Gestión de estado
virtual void clear(); // Reinicia las variables a cero
// Gestión de estado
virtual void clear(); // Reinicia las variables a cero
// Obtención de propiedades
[[nodiscard]] auto getX() const -> float { return pos_.x; }
[[nodiscard]] auto getY() const -> float { return pos_.y; }
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
[[nodiscard]] auto getClip() const -> SDL_FRect { return clip_; }
[[nodiscard]] auto getSurface() const -> std::shared_ptr<Surface> { return surface_; }
auto getRect() -> SDL_FRect& { return pos_; }
// Obtención de propiedades
[[nodiscard]] auto getX() const -> float { return pos_.x; }
[[nodiscard]] auto getY() const -> float { return pos_.y; }
[[nodiscard]] auto getWidth() const -> float { return pos_.w; }
[[nodiscard]] auto getHeight() const -> float { return pos_.h; }
[[nodiscard]] auto getPosition() const -> SDL_FRect { return pos_; }
[[nodiscard]] auto getClip() const -> SDL_FRect { return clip_; }
[[nodiscard]] auto getSurface() const -> std::shared_ptr<Surface> { return surface_; }
auto getRect() -> SDL_FRect& { return pos_; }
// Modificación de posición y tamaño
void setX(float x) { pos_.x = x; }
void setY(float y) { pos_.y = y; }
void setWidth(float w) { pos_.w = w; }
void setHeight(float h) { pos_.h = h; }
void setPosition(float x, float y);
void setPosition(SDL_FPoint p);
void setPosition(SDL_FRect r) { pos_ = r; }
void incX(float value) { pos_.x += value; }
void incY(float value) { pos_.y += value; }
// Modificación de posición y tamaño
void setX(float x) { pos_.x = x; }
void setY(float y) { pos_.y = y; }
void setWidth(float w) { pos_.w = w; }
void setHeight(float h) { pos_.h = h; }
void setPosition(float x, float y);
void setPosition(SDL_FPoint p);
void setPosition(SDL_FRect r) { pos_ = r; }
void incX(float value) { pos_.x += value; }
void incY(float value) { pos_.y += value; }
// Modificación de clip y surface
void setClip(SDL_FRect rect) { clip_ = rect; }
void setClip(float x, float y, float w, float h) { clip_ = SDL_FRect{x, y, w, h}; }
void setSurface(std::shared_ptr<Surface> surface) { surface_ = std::move(surface); }
// Modificación de clip y surface
void setClip(SDL_FRect rect) { clip_ = rect; }
void setClip(float x, float y, float w, float h) { clip_ = SDL_FRect{x, y, w, h}; }
void setSurface(std::shared_ptr<Surface> surface) { surface_ = std::move(surface); }
protected:
// Variables miembro
std::shared_ptr<Surface> surface_{nullptr}; // Surface donde estan todos los dibujos del sprite
SDL_FRect pos_{0.0F, 0.0F, 0.0F, 0.0F}; // Posición y tamaño donde dibujar el sprite
SDL_FRect clip_{0.0F, 0.0F, 0.0F, 0.0F}; // Rectangulo de origen de la surface que se dibujará en pantalla
protected:
// Variables miembro
std::shared_ptr<Surface> surface_{nullptr}; // Surface donde estan todos los dibujos del sprite
SDL_FRect pos_{0.0F, 0.0F, 0.0F, 0.0F}; // Posición y tamaño donde dibujar el sprite
SDL_FRect clip_{0.0F, 0.0F, 0.0F, 0.0F}; // Rectangulo de origen de la surface que se dibujará en pantalla
};

View File

@@ -11,54 +11,54 @@ class Surface; // lines 8-8
// Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text {
public:
// Tipos anidados públicos
struct Offset {
int x{0}, y{0}, w{0};
};
public:
// Tipos anidados públicos
struct Offset {
int x{0}, y{0}, w{0};
};
struct File {
int box_width{0}; // Anchura de la caja de cada caracter en el png
int box_height{0}; // Altura de la caja de cada caracter en el png
std::array<Offset, 128> offset{}; // Vector con las posiciones y ancho de cada letra
};
struct File {
int box_width{0}; // Anchura de la caja de cada caracter en el png
int box_height{0}; // Altura de la caja de cada caracter en el png
std::array<Offset, 128> offset{}; // Vector con las posiciones y ancho de cada letra
};
// Constructor
Text(const std::shared_ptr<Surface>& surface, const std::string& text_file);
Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<File>& text_file);
// Constructor
Text(const std::shared_ptr<Surface>& surface, const std::string& text_file);
Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<File>& text_file);
// Destructor
~Text() = default;
// Destructor
~Text() = default;
// Constantes de flags para writeDX
static constexpr int COLOR_FLAG = 1;
static constexpr int SHADOW_FLAG = 2;
static constexpr int CENTER_FLAG = 4;
static constexpr int STROKE_FLAG = 8;
// Constantes de flags para writeDX
static constexpr int COLOR_FLAG = 1;
static constexpr int SHADOW_FLAG = 2;
static constexpr int CENTER_FLAG = 4;
static constexpr int STROKE_FLAG = 8;
void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string& text, Uint8 color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1); // Escribe texto con extras
void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string& text, Uint8 color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1); // Escribe texto con extras
auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Surface>; // Escribe el texto en una textura
auto writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1) -> std::shared_ptr<Surface>; // Escribe el texto con extras en una textura
auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Surface>; // Escribe el texto en una textura
auto writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1) -> std::shared_ptr<Surface>; // Escribe el texto con extras en una textura
[[nodiscard]] auto length(const std::string& text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena
[[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño del caracter
[[nodiscard]] auto length(const std::string& text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena
[[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño del caracter
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
static auto loadTextFile(const std::string& file_path) -> std::shared_ptr<File>; // Método de utilidad para cargar ficheros de texto
static auto loadTextFile(const std::string& file_path) -> std::shared_ptr<File>; // Método de utilidad para cargar ficheros de texto
private:
// Objetos y punteros
std::unique_ptr<SurfaceSprite> sprite_ = nullptr; // Objeto con los graficos para el texto
private:
// Objetos y punteros
std::unique_ptr<SurfaceSprite> sprite_ = nullptr; // Objeto con los graficos para el texto
// Variables
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
int box_height_ = 0; // Altura de la caja de cada caracter en el png
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
std::array<Offset, 128> offset_{}; // Vector con las posiciones y ancho de cada letra
// Variables
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
int box_height_ = 0; // Altura de la caja de cada caracter en el png
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
std::array<Offset, 128> offset_{}; // Vector con las posiciones y ancho de cada letra
};

View File

@@ -7,37 +7,37 @@
struct Color; // lines 11-11
class Texture {
public:
explicit Texture(SDL_Renderer* renderer, std::string path = std::string()); // Constructor
~Texture(); // Destructor
public:
explicit Texture(SDL_Renderer* renderer, std::string path = std::string()); // Constructor
~Texture(); // Destructor
auto loadFromFile(const std::string& path) -> bool; // Carga una imagen desde un fichero
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
auto reLoad() -> bool; // Recarga la textura
auto loadFromFile(const std::string& path) -> bool; // Carga una imagen desde un fichero
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
auto reLoad() -> bool; // Recarga la textura
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulacion
void setColor(Color color); // Establece el color para la modulacion
void setBlendMode(SDL_BlendMode blending); // Establece el blending
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
void setAsRenderTarget(SDL_Renderer* renderer); // Establece la textura como objetivo de renderizado
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulacion
void setColor(Color color); // Establece el color para la modulacion
void setBlendMode(SDL_BlendMode blending); // Establece el blending
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
void setAsRenderTarget(SDL_Renderer* renderer); // Establece la textura como objetivo de renderizado
void render(float x, float y, SDL_FRect* clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint* center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
void render(float x, float y, SDL_FRect* clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint* center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
[[nodiscard]] auto getWidth() const -> int { return width_; } // Obtiene el ancho de la imagen
[[nodiscard]] auto getHeight() const -> int { return height_; } // Obtiene el alto de la imagen
auto getSDLTexture() -> SDL_Texture*; // Obtiene la textura
auto getRenderer() -> SDL_Renderer*; // Obtiene el renderizador
[[nodiscard]] auto getWidth() const -> int { return width_; } // Obtiene el ancho de la imagen
[[nodiscard]] auto getHeight() const -> int { return height_; } // Obtiene el alto de la imagen
auto getSDLTexture() -> SDL_Texture*; // Obtiene la textura
auto getRenderer() -> SDL_Renderer*; // Obtiene el renderizador
private:
void unloadTexture(); // Libera la memoria de la textura
private:
void unloadTexture(); // Libera la memoria de la textura
// Objetos y punteros
SDL_Renderer* renderer_; // Renderizador donde dibujar la textura
SDL_Texture* texture_ = nullptr; // La textura
// Objetos y punteros
SDL_Renderer* renderer_; // Renderizador donde dibujar la textura
SDL_Texture* texture_ = nullptr; // La textura
// Variables
std::string path_; // Ruta de la imagen de la textura
float width_ = 0.0F; // Ancho de la imagen
float height_ = 0.0F; // Alto de la imagen
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
// Variables
std::string path_; // Ruta de la imagen de la textura
float width_ = 0.0F; // Ancho de la imagen
float height_ = 0.0F; // Alto de la imagen
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
};

View File

@@ -24,478 +24,478 @@ struct JA_Sound_t; // lines 18-18
namespace Resource {
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Cache* Cache::cache = nullptr;
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Cache* Cache::cache = nullptr;
// [SINGLETON] Crearemos el objeto cache con esta función estática
void Cache::init() { Cache::cache = new Cache(); }
// [SINGLETON] Crearemos el objeto cache con esta función estática
void Cache::init() { Cache::cache = new Cache(); }
// [SINGLETON] Destruiremos el objeto cache con esta función estática
void Cache::destroy() { delete Cache::cache; }
// [SINGLETON] Destruiremos el objeto cache con esta función estática
void Cache::destroy() { delete Cache::cache; }
// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él
auto Cache::get() -> Cache* { return Cache::cache; }
// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él
auto Cache::get() -> Cache* { return Cache::cache; }
// Constructor
Cache::Cache()
: loading_text_(Screen::get()->getText()) {
load();
}
// Vacia todos los vectores de recursos
void Cache::clear() {
clearSounds();
clearMusics();
surfaces_.clear();
palettes_.clear();
text_files_.clear();
texts_.clear();
animations_.clear();
}
// Carga todos los recursos
void Cache::load() {
calculateTotal();
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
std::cout << "\n** LOADING RESOURCES" << '\n';
loadSounds();
loadMusics();
loadSurfaces();
loadPalettes();
loadTextFiles();
loadAnimations();
loadRooms();
createText();
std::cout << "\n** RESOURCES LOADED" << '\n';
}
// Recarga todos los recursos
void Cache::reload() {
clear();
load();
}
// Obtiene el sonido a partir de un nombre
auto Cache::getSound(const std::string& name) -> JA_Sound_t* {
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; });
if (it != sounds_.end()) {
return it->sound;
// Constructor
Cache::Cache()
: loading_text_(Screen::get()->getText()) {
load();
}
std::cerr << "Error: Sonido no encontrado " << name << '\n';
throw std::runtime_error("Sonido no encontrado: " + name);
}
// Obtiene la música a partir de un nombre
auto Cache::getMusic(const std::string& name) -> JA_Music_t* {
auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; });
if (it != musics_.end()) {
return it->music;
// Vacia todos los vectores de recursos
void Cache::clear() {
clearSounds();
clearMusics();
surfaces_.clear();
palettes_.clear();
text_files_.clear();
texts_.clear();
animations_.clear();
}
std::cerr << "Error: Música no encontrada " << name << '\n';
throw std::runtime_error("Música no encontrada: " + name);
}
// Obtiene la surface a partir de un nombre
auto Cache::getSurface(const std::string& name) -> std::shared_ptr<Surface> {
auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) { return t.name == name; });
if (it != surfaces_.end()) {
return it->surface;
// Carga todos los recursos
void Cache::load() {
calculateTotal();
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
std::cout << "\n** LOADING RESOURCES" << '\n';
loadSounds();
loadMusics();
loadSurfaces();
loadPalettes();
loadTextFiles();
loadAnimations();
loadRooms();
createText();
std::cout << "\n** RESOURCES LOADED" << '\n';
}
std::cerr << "Error: Imagen no encontrada " << name << '\n';
throw std::runtime_error("Imagen no encontrada: " + name);
}
// Obtiene la paleta a partir de un nombre
auto Cache::getPalette(const std::string& name) -> Palette {
auto it = std::ranges::find_if(palettes_, [&name](const auto& t) { return t.name == name; });
if (it != palettes_.end()) {
return it->palette;
// Recarga todos los recursos
void Cache::reload() {
clear();
load();
}
std::cerr << "Error: Paleta no encontrada " << name << '\n';
throw std::runtime_error("Paleta no encontrada: " + name);
}
// Obtiene el sonido a partir de un nombre
auto Cache::getSound(const std::string& name) -> JA_Sound_t* {
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; });
// Obtiene el fichero de texto a partir de un nombre
auto Cache::getTextFile(const std::string& name) -> std::shared_ptr<Text::File> {
auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; });
if (it != text_files_.end()) {
return it->text_file;
}
std::cerr << "Error: TextFile no encontrado " << name << '\n';
throw std::runtime_error("TextFile no encontrado: " + name);
}
// Obtiene el objeto de texto a partir de un nombre
auto Cache::getText(const std::string& name) -> std::shared_ptr<Text> {
auto it = std::ranges::find_if(texts_, [&name](const auto& t) { return t.name == name; });
if (it != texts_.end()) {
return it->text;
}
std::cerr << "Error: Text no encontrado " << name << '\n';
throw std::runtime_error("Texto no encontrado: " + name);
}
// Obtiene los datos de animación parseados a partir de un nombre
auto Cache::getAnimationData(const std::string& name) -> const AnimationResource& {
auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; });
if (it != animations_.end()) {
return *it;
}
std::cerr << "Error: Animación no encontrada " << name << '\n';
throw std::runtime_error("Animación no encontrada: " + name);
}
// Obtiene la habitación a partir de un nombre
auto Cache::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; });
if (it != rooms_.end()) {
return it->room;
}
std::cerr << "Error: Habitación no encontrada " << name << '\n';
throw std::runtime_error("Habitación no encontrada: " + name);
}
// Obtiene todas las habitaciones
auto Cache::getRooms() -> std::vector<RoomResource>& {
return rooms_;
}
// Helper para lanzar errores de carga con formato consistente
[[noreturn]] void Cache::throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e) {
std::cerr << "\n[ ERROR ] Failed to load " << asset_type << ": " << getFileName(file_path) << '\n';
std::cerr << "[ ERROR ] Path: " << file_path << '\n';
std::cerr << "[ ERROR ] Reason: " << e.what() << '\n';
std::cerr << "[ ERROR ] Check config/assets.yaml configuration\n";
throw;
}
// Carga los sonidos
void Cache::loadSounds() {
std::cout << "\n>> SOUND FILES" << '\n';
auto list = List::get()->getListByType(List::Type::SOUND);
sounds_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
JA_Sound_t* sound = nullptr;
// Try loading from resource pack first
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
sound = JA_LoadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
// Fallback to file path if memory loading failed
if (sound == nullptr) {
sound = JA_LoadSound(l.c_str());
}
if (sound == nullptr) {
throw std::runtime_error("Failed to decode audio file");
}
sounds_.emplace_back(SoundResource{.name = name, .sound = sound});
printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("SOUND", l, e);
if (it != sounds_.end()) {
return it->sound;
}
std::cerr << "Error: Sonido no encontrado " << name << '\n';
throw std::runtime_error("Sonido no encontrado: " + name);
}
}
// Carga las musicas
void Cache::loadMusics() {
std::cout << "\n>> MUSIC FILES" << '\n';
auto list = List::get()->getListByType(List::Type::MUSIC);
musics_.clear();
// Obtiene la música a partir de un nombre
auto Cache::getMusic(const std::string& name) -> JA_Music_t* {
auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; });
for (const auto& l : list) {
try {
auto name = getFileName(l);
JA_Music_t* music = nullptr;
// Try loading from resource pack first
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
music = JA_LoadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
// Fallback to file path if memory loading failed
if (music == nullptr) {
music = JA_LoadMusic(l.c_str());
}
if (music == nullptr) {
throw std::runtime_error("Failed to decode music file");
}
musics_.emplace_back(MusicResource{.name = name, .music = music});
printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress(1);
} catch (const std::exception& e) {
throwLoadError("MUSIC", l, e);
if (it != musics_.end()) {
return it->music;
}
std::cerr << "Error: Música no encontrada " << name << '\n';
throw std::runtime_error("Música no encontrada: " + name);
}
}
// Carga las texturas
void Cache::loadSurfaces() {
std::cout << "\n>> SURFACES" << '\n';
auto list = List::get()->getListByType(List::Type::BITMAP);
surfaces_.clear();
// Obtiene la surface a partir de un nombre
auto Cache::getSurface(const std::string& name) -> std::shared_ptr<Surface> {
auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) { return t.name == name; });
for (const auto& l : list) {
try {
auto name = getFileName(l);
surfaces_.emplace_back(SurfaceResource{.name = name, .surface = std::make_shared<Surface>(l)});
surfaces_.back().surface->setTransparentColor(0);
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("BITMAP", l, e);
if (it != surfaces_.end()) {
return it->surface;
}
std::cerr << "Error: Imagen no encontrada " << name << '\n';
throw std::runtime_error("Imagen no encontrada: " + name);
}
// Obtiene la paleta a partir de un nombre
auto Cache::getPalette(const std::string& name) -> Palette {
auto it = std::ranges::find_if(palettes_, [&name](const auto& t) { return t.name == name; });
if (it != palettes_.end()) {
return it->palette;
}
std::cerr << "Error: Paleta no encontrada " << name << '\n';
throw std::runtime_error("Paleta no encontrada: " + name);
}
// Obtiene el fichero de texto a partir de un nombre
auto Cache::getTextFile(const std::string& name) -> std::shared_ptr<Text::File> {
auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; });
if (it != text_files_.end()) {
return it->text_file;
}
std::cerr << "Error: TextFile no encontrado " << name << '\n';
throw std::runtime_error("TextFile no encontrado: " + name);
}
// Obtiene el objeto de texto a partir de un nombre
auto Cache::getText(const std::string& name) -> std::shared_ptr<Text> {
auto it = std::ranges::find_if(texts_, [&name](const auto& t) { return t.name == name; });
if (it != texts_.end()) {
return it->text;
}
std::cerr << "Error: Text no encontrado " << name << '\n';
throw std::runtime_error("Texto no encontrado: " + name);
}
// Obtiene los datos de animación parseados a partir de un nombre
auto Cache::getAnimationData(const std::string& name) -> const AnimationResource& {
auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; });
if (it != animations_.end()) {
return *it;
}
std::cerr << "Error: Animación no encontrada " << name << '\n';
throw std::runtime_error("Animación no encontrada: " + name);
}
// Obtiene la habitación a partir de un nombre
auto Cache::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; });
if (it != rooms_.end()) {
return it->room;
}
std::cerr << "Error: Habitación no encontrada " << name << '\n';
throw std::runtime_error("Habitación no encontrada: " + name);
}
// Obtiene todas las habitaciones
auto Cache::getRooms() -> std::vector<RoomResource>& {
return rooms_;
}
// Helper para lanzar errores de carga con formato consistente
[[noreturn]] void Cache::throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e) {
std::cerr << "\n[ ERROR ] Failed to load " << asset_type << ": " << getFileName(file_path) << '\n';
std::cerr << "[ ERROR ] Path: " << file_path << '\n';
std::cerr << "[ ERROR ] Reason: " << e.what() << '\n';
std::cerr << "[ ERROR ] Check config/assets.yaml configuration\n";
throw;
}
// Carga los sonidos
void Cache::loadSounds() {
std::cout << "\n>> SOUND FILES" << '\n';
auto list = List::get()->getListByType(List::Type::SOUND);
sounds_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
JA_Sound_t* sound = nullptr;
// Try loading from resource pack first
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
sound = JA_LoadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
// Fallback to file path if memory loading failed
if (sound == nullptr) {
sound = JA_LoadSound(l.c_str());
}
if (sound == nullptr) {
throw std::runtime_error("Failed to decode audio file");
}
sounds_.emplace_back(SoundResource{.name = name, .sound = sound});
printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("SOUND", l, e);
}
}
}
// Reconfigura el color transparente de algunas surfaces
getSurface("loading_screen_color.gif")->setTransparentColor();
getSurface("ending1.gif")->setTransparentColor();
getSurface("ending2.gif")->setTransparentColor();
getSurface("ending3.gif")->setTransparentColor();
getSurface("ending4.gif")->setTransparentColor();
getSurface("ending5.gif")->setTransparentColor();
getSurface("standard.gif")->setTransparentColor(16);
}
// Carga las musicas
void Cache::loadMusics() {
std::cout << "\n>> MUSIC FILES" << '\n';
auto list = List::get()->getListByType(List::Type::MUSIC);
musics_.clear();
// Carga las paletas
void Cache::loadPalettes() {
std::cout << "\n>> PALETTES" << '\n';
auto list = List::get()->getListByType(List::Type::PALETTE);
palettes_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
JA_Music_t* music = nullptr;
for (const auto& l : list) {
try {
auto name = getFileName(l);
palettes_.emplace_back(ResourcePalette{.name = name, .palette = readPalFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("PALETTE", l, e);
}
}
}
// Try loading from resource pack first
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
music = JA_LoadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
// Carga los ficheros de texto
void Cache::loadTextFiles() {
std::cout << "\n>> TEXT FILES" << '\n';
auto list = List::get()->getListByType(List::Type::FONT);
text_files_.clear();
// Fallback to file path if memory loading failed
if (music == nullptr) {
music = JA_LoadMusic(l.c_str());
}
for (const auto& l : list) {
try {
auto name = getFileName(l);
text_files_.emplace_back(TextFileResource{.name = name, .text_file = Text::loadTextFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("FONT", l, e);
}
}
}
if (music == nullptr) {
throw std::runtime_error("Failed to decode music file");
}
// Carga las animaciones
void Cache::loadAnimations() {
std::cout << "\n>> ANIMATIONS" << '\n';
auto list = List::get()->getListByType(List::Type::ANIMATION);
animations_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
// Cargar bytes del archivo YAML sin parsear (carga lazy)
auto yaml_bytes = Helper::loadFile(l);
if (yaml_bytes.empty()) {
throw std::runtime_error("File is empty or could not be loaded");
musics_.emplace_back(MusicResource{.name = name, .music = music});
printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress(1);
} catch (const std::exception& e) {
throwLoadError("MUSIC", l, e);
}
animations_.emplace_back(AnimationResource{.name = name, .yaml_data = yaml_bytes});
printWithDots("Animation : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ANIMATION", l, e);
}
}
}
// Carga las habitaciones desde archivos YAML
void Cache::loadRooms() {
std::cout << "\n>> ROOMS" << '\n';
auto list = List::get()->getListByType(List::Type::ROOM);
rooms_.clear();
// Carga las texturas
void Cache::loadSurfaces() {
std::cout << "\n>> SURFACES" << '\n';
auto list = List::get()->getListByType(List::Type::BITMAP);
surfaces_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
rooms_.emplace_back(RoomResource{.name = name, .room = std::make_shared<Room::Data>(Room::loadYAML(l))});
printWithDots("Room : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ROOM", l, e);
for (const auto& l : list) {
try {
auto name = getFileName(l);
surfaces_.emplace_back(SurfaceResource{.name = name, .surface = std::make_shared<Surface>(l)});
surfaces_.back().surface->setTransparentColor(0);
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("BITMAP", l, e);
}
}
// Reconfigura el color transparente de algunas surfaces
getSurface("loading_screen_color.gif")->setTransparentColor();
getSurface("ending1.gif")->setTransparentColor();
getSurface("ending2.gif")->setTransparentColor();
getSurface("ending3.gif")->setTransparentColor();
getSurface("ending4.gif")->setTransparentColor();
getSurface("ending5.gif")->setTransparentColor();
getSurface("standard.gif")->setTransparentColor(16);
}
// Carga las paletas
void Cache::loadPalettes() {
std::cout << "\n>> PALETTES" << '\n';
auto list = List::get()->getListByType(List::Type::PALETTE);
palettes_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
palettes_.emplace_back(ResourcePalette{.name = name, .palette = readPalFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("PALETTE", l, e);
}
}
}
}
void Cache::createText() {
struct ResourceInfo {
// Carga los ficheros de texto
void Cache::loadTextFiles() {
std::cout << "\n>> TEXT FILES" << '\n';
auto list = List::get()->getListByType(List::Type::FONT);
text_files_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
text_files_.emplace_back(TextFileResource{.name = name, .text_file = Text::loadTextFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("FONT", l, e);
}
}
}
// Carga las animaciones
void Cache::loadAnimations() {
std::cout << "\n>> ANIMATIONS" << '\n';
auto list = List::get()->getListByType(List::Type::ANIMATION);
animations_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
// Cargar bytes del archivo YAML sin parsear (carga lazy)
auto yaml_bytes = Helper::loadFile(l);
if (yaml_bytes.empty()) {
throw std::runtime_error("File is empty or could not be loaded");
}
animations_.emplace_back(AnimationResource{.name = name, .yaml_data = yaml_bytes});
printWithDots("Animation : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ANIMATION", l, e);
}
}
}
// Carga las habitaciones desde archivos YAML
void Cache::loadRooms() {
std::cout << "\n>> ROOMS" << '\n';
auto list = List::get()->getListByType(List::Type::ROOM);
rooms_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
rooms_.emplace_back(RoomResource{.name = name, .room = std::make_shared<Room::Data>(Room::loadYAML(l))});
printWithDots("Room : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ROOM", l, e);
}
}
}
void Cache::createText() {
struct ResourceInfo {
std::string key; // Identificador del recurso
std::string texture_file; // Nombre del archivo de textura
std::string text_file; // Nombre del archivo de texto
};
};
std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n';
std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n';
std::vector<ResourceInfo> resources = {
{.key = "aseprite", .texture_file = "aseprite.gif", .text_file = "aseprite.txt"},
{.key = "gauntlet", .texture_file = "gauntlet.gif", .text_file = "gauntlet.txt"},
{.key = "smb2", .texture_file = "smb2.gif", .text_file = "smb2.txt"},
{.key = "subatomic", .texture_file = "subatomic.gif", .text_file = "subatomic.txt"},
{.key = "8bithud", .texture_file = "8bithud.gif", .text_file = "8bithud.txt"}};
std::vector<ResourceInfo> resources = {
{.key = "aseprite", .texture_file = "aseprite.gif", .text_file = "aseprite.txt"},
{.key = "gauntlet", .texture_file = "gauntlet.gif", .text_file = "gauntlet.txt"},
{.key = "smb2", .texture_file = "smb2.gif", .text_file = "smb2.txt"},
{.key = "subatomic", .texture_file = "subatomic.gif", .text_file = "subatomic.txt"},
{.key = "8bithud", .texture_file = "8bithud.gif", .text_file = "8bithud.txt"}};
for (const auto& res_info : resources) {
texts_.emplace_back(TextResource{.name = res_info.key, .text = std::make_shared<Text>(getSurface(res_info.texture_file), getTextFile(res_info.text_file))});
printWithDots("Text : ", res_info.key, "[ DONE ]");
}
}
// Vacía el vector de sonidos
void Cache::clearSounds() {
// Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t
for (auto& sound : sounds_) {
if (sound.sound != nullptr) {
JA_DeleteSound(sound.sound);
sound.sound = nullptr;
for (const auto& res_info : resources) {
texts_.emplace_back(TextResource{.name = res_info.key, .text = std::make_shared<Text>(getSurface(res_info.texture_file), getTextFile(res_info.text_file))});
printWithDots("Text : ", res_info.key, "[ DONE ]");
}
}
sounds_.clear(); // Limpia el vector después de liberar todos los recursos
}
// Vacía el vector de musicas
void Cache::clearMusics() {
// Itera sobre el vector y libera los recursos asociados a cada JA_Music_t
for (auto& music : musics_) {
if (music.music != nullptr) {
JA_DeleteMusic(music.music);
music.music = nullptr;
// Vacía el vector de sonidos
void Cache::clearSounds() {
// Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t
for (auto& sound : sounds_) {
if (sound.sound != nullptr) {
JA_DeleteSound(sound.sound);
sound.sound = nullptr;
}
}
}
musics_.clear(); // Limpia el vector después de liberar todos los recursos
}
// Calcula el numero de recursos para cargar
void Cache::calculateTotal() {
std::vector<List::Type> asset_types = {
List::Type::SOUND,
List::Type::MUSIC,
List::Type::BITMAP,
List::Type::PALETTE,
List::Type::FONT,
List::Type::ANIMATION,
List::Type::ROOM};
int total = 0;
for (const auto& asset_type : asset_types) {
auto list = List::get()->getListByType(asset_type);
total += list.size();
sounds_.clear(); // Limpia el vector después de liberar todos los recursos
}
count_ = ResourceCount{.total = total, .loaded = 0};
}
// Vacía el vector de musicas
void Cache::clearMusics() {
// Itera sobre el vector y libera los recursos asociados a cada JA_Music_t
for (auto& music : musics_) {
if (music.music != nullptr) {
JA_DeleteMusic(music.music);
music.music = nullptr;
}
}
musics_.clear(); // Limpia el vector después de liberar todos los recursos
}
// Muestra el progreso de carga
void Cache::renderProgress() {
constexpr float X_PADDING = 60.0F;
constexpr float Y_PADDING = 10.0F;
constexpr float BAR_HEIGHT = 5.0F;
// Calcula el numero de recursos para cargar
void Cache::calculateTotal() {
std::vector<List::Type> asset_types = {
List::Type::SOUND,
List::Type::MUSIC,
List::Type::BITMAP,
List::Type::PALETTE,
List::Type::FONT,
List::Type::ANIMATION,
List::Type::ROOM};
const float BAR_POSITION = Options::game.height - BAR_HEIGHT - Y_PADDING;
Screen::get()->start();
Screen::get()->clearSurface(static_cast<Uint8>(PaletteColor::BLACK));
int total = 0;
for (const auto& asset_type : asset_types) {
auto list = List::get()->getListByType(asset_type);
total += list.size();
}
auto surface = Screen::get()->getRendererSurface();
const auto LOADING_TEXT_COLOR = static_cast<Uint8>(PaletteColor::BRIGHT_WHITE);
const auto BAR_COLOR = static_cast<Uint8>(PaletteColor::WHITE);
const int TEXT_HEIGHT = loading_text_->getCharacterSize();
const int CENTER_X = Options::game.width / 2;
const int CENTER_Y = Options::game.height / 2;
count_ = ResourceCount{.total = total, .loaded = 0};
}
// Draw APP_NAME centered above center
const std::string APP_NAME = spaceBetweenLetters(Version::APP_NAME);
loading_text_->writeColored(
CENTER_X - (loading_text_->length(APP_NAME) / 2),
CENTER_Y - TEXT_HEIGHT,
APP_NAME,
LOADING_TEXT_COLOR);
// Muestra el progreso de carga
void Cache::renderProgress() {
constexpr float X_PADDING = 60.0F;
constexpr float Y_PADDING = 10.0F;
constexpr float BAR_HEIGHT = 5.0F;
// Draw VERSION centered below center
const std::string VERSION_TEXT = "ver. " + std::string(Texts::VERSION) + " (" + std::string(Version::GIT_HASH) + ")";
loading_text_->writeColored(
CENTER_X - (loading_text_->length(VERSION_TEXT) / 2),
CENTER_Y + TEXT_HEIGHT,
VERSION_TEXT,
LOADING_TEXT_COLOR);
const float BAR_POSITION = Options::game.height - BAR_HEIGHT - Y_PADDING;
Screen::get()->start();
Screen::get()->clearSurface(static_cast<Uint8>(PaletteColor::BLACK));
// Draw progress bar border
const float WIRED_BAR_WIDTH = Options::game.width - (X_PADDING * 2);
SDL_FRect rect_wired = {X_PADDING, BAR_POSITION, WIRED_BAR_WIDTH, BAR_HEIGHT};
surface->drawRectBorder(&rect_wired, BAR_COLOR);
auto surface = Screen::get()->getRendererSurface();
const auto LOADING_TEXT_COLOR = static_cast<Uint8>(PaletteColor::BRIGHT_WHITE);
const auto BAR_COLOR = static_cast<Uint8>(PaletteColor::WHITE);
const int TEXT_HEIGHT = loading_text_->getCharacterSize();
const int CENTER_X = Options::game.width / 2;
const int CENTER_Y = Options::game.height / 2;
// Draw progress bar fill
const float FULL_BAR_WIDTH = WIRED_BAR_WIDTH * count_.getPercentage();
SDL_FRect rect_full = {X_PADDING, BAR_POSITION, FULL_BAR_WIDTH, BAR_HEIGHT};
surface->fillRect(&rect_full, BAR_COLOR);
// Draw APP_NAME centered above center
const std::string APP_NAME = spaceBetweenLetters(Version::APP_NAME);
loading_text_->writeColored(
CENTER_X - (loading_text_->length(APP_NAME) / 2),
CENTER_Y - TEXT_HEIGHT,
APP_NAME,
LOADING_TEXT_COLOR);
Screen::get()->render();
}
// Draw VERSION centered below center
const std::string VERSION_TEXT = "ver. " + std::string(Texts::VERSION) + " (" + std::string(Version::GIT_HASH) + ")";
loading_text_->writeColored(
CENTER_X - (loading_text_->length(VERSION_TEXT) / 2),
CENTER_Y + TEXT_HEIGHT,
VERSION_TEXT,
LOADING_TEXT_COLOR);
// Comprueba los eventos de la pantalla de carga
void Cache::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_QUIT:
exit(0);
break;
case SDL_EVENT_KEY_DOWN:
if (event.key.key == SDLK_ESCAPE) {
// Draw progress bar border
const float WIRED_BAR_WIDTH = Options::game.width - (X_PADDING * 2);
SDL_FRect rect_wired = {X_PADDING, BAR_POSITION, WIRED_BAR_WIDTH, BAR_HEIGHT};
surface->drawRectBorder(&rect_wired, BAR_COLOR);
// Draw progress bar fill
const float FULL_BAR_WIDTH = WIRED_BAR_WIDTH * count_.getPercentage();
SDL_FRect rect_full = {X_PADDING, BAR_POSITION, FULL_BAR_WIDTH, BAR_HEIGHT};
surface->fillRect(&rect_full, BAR_COLOR);
Screen::get()->render();
}
// Comprueba los eventos de la pantalla de carga
void Cache::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_QUIT:
exit(0);
}
break;
break;
case SDL_EVENT_KEY_DOWN:
if (event.key.key == SDLK_ESCAPE) {
exit(0);
}
break;
}
}
}
}
// Actualiza el progreso de carga
void Cache::updateLoadingProgress(int steps) {
count_.add(1);
if (count_.loaded % steps == 0 || count_.loaded == count_.total) {
renderProgress();
// Actualiza el progreso de carga
void Cache::updateLoadingProgress(int steps) {
count_.add(1);
if (count_.loaded % steps == 0 || count_.loaded == count_.total) {
renderProgress();
}
checkEvents();
}
checkEvents();
}
} // namespace Resource

View File

@@ -9,8 +9,8 @@
namespace Resource {
class Cache {
public:
class Cache {
public:
static void init(); // Inicialización singleton
static void destroy(); // Destrucción singleton
static auto get() -> Cache*; // Acceso al singleton
@@ -27,21 +27,21 @@ class Cache {
void reload(); // Recarga todos los recursos
private:
private:
// Estructura para llevar la cuenta de los recursos cargados
struct ResourceCount {
int total{0}; // Número total de recursos
int loaded{0}; // Número de recursos cargados
int total{0}; // Número total de recursos
int loaded{0}; // Número de recursos cargados
// Añade una cantidad a los recursos cargados
void add(int amount) {
loaded += amount;
}
// Añade una cantidad a los recursos cargados
void add(int amount) {
loaded += amount;
}
// Obtiene el porcentaje de recursos cargados
[[nodiscard]] auto getPercentage() const -> float {
return static_cast<float>(loaded) / static_cast<float>(total);
}
// Obtiene el porcentaje de recursos cargados
[[nodiscard]] auto getPercentage() const -> float {
return static_cast<float>(loaded) / static_cast<float>(total);
}
};
// Métodos de carga de recursos
@@ -88,6 +88,6 @@ class Cache {
ResourceCount count_{}; // Contador de recursos
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
};
};
} // namespace Resource

View File

@@ -12,171 +12,171 @@
namespace Resource::Helper {
static bool resource_system_initialized = false;
static bool resource_system_initialized = false;
// Initialize the resource system
auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback)
-> bool {
if (resource_system_initialized) {
std::cout << "ResourceHelper: Already initialized\n";
return true;
}
std::cout << "ResourceHelper: Initializing with pack: " << pack_file << '\n';
std::cout << "ResourceHelper: Fallback enabled: " << (enable_fallback ? "Yes" : "No")
<< '\n';
bool success = Loader::get().initialize(pack_file, enable_fallback);
if (success) {
resource_system_initialized = true;
std::cout << "ResourceHelper: Initialization successful\n";
} else {
std::cerr << "ResourceHelper: Initialization failed\n";
}
return success;
}
// Shutdown the resource system
void shutdownResourceSystem() {
if (resource_system_initialized) {
Loader::get().shutdown();
resource_system_initialized = false;
std::cout << "ResourceHelper: Shutdown complete\n";
}
}
// Load a file
auto loadFile(const std::string& filepath) -> std::vector<uint8_t> {
if (!resource_system_initialized) {
std::cerr << "ResourceHelper: System not initialized, loading from filesystem\n";
// Fallback to direct filesystem access
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
return {};
// Initialize the resource system
auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback)
-> bool {
if (resource_system_initialized) {
std::cout << "ResourceHelper: Already initialized\n";
return true;
}
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> data(file_size);
file.read(reinterpret_cast<char*>(data.data()), file_size);
return data;
std::cout << "ResourceHelper: Initializing with pack: " << pack_file << '\n';
std::cout << "ResourceHelper: Fallback enabled: " << (enable_fallback ? "Yes" : "No")
<< '\n';
bool success = Loader::get().initialize(pack_file, enable_fallback);
if (success) {
resource_system_initialized = true;
std::cout << "ResourceHelper: Initialization successful\n";
} else {
std::cerr << "ResourceHelper: Initialization failed\n";
}
return success;
}
// Determine if we should use the pack
if (shouldUseResourcePack(filepath)) {
// Convert to pack path
std::string pack_path = getPackPath(filepath);
// Shutdown the resource system
void shutdownResourceSystem() {
if (resource_system_initialized) {
Loader::get().shutdown();
resource_system_initialized = false;
std::cout << "ResourceHelper: Shutdown complete\n";
}
}
// Try to load from pack
auto data = Loader::get().loadResource(pack_path);
if (!data.empty()) {
// Load a file
auto loadFile(const std::string& filepath) -> std::vector<uint8_t> {
if (!resource_system_initialized) {
std::cerr << "ResourceHelper: System not initialized, loading from filesystem\n";
// Fallback to direct filesystem access
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
return {};
}
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> data(file_size);
file.read(reinterpret_cast<char*>(data.data()), file_size);
return data;
}
// If pack loading failed, try filesystem as fallback
std::cerr << "ResourceHelper: Pack failed for " << pack_path
<< ", trying filesystem\n";
// Determine if we should use the pack
if (shouldUseResourcePack(filepath)) {
// Convert to pack path
std::string pack_path = getPackPath(filepath);
// Try to load from pack
auto data = Loader::get().loadResource(pack_path);
if (!data.empty()) {
return data;
}
// If pack loading failed, try filesystem as fallback
std::cerr << "ResourceHelper: Pack failed for " << pack_path
<< ", trying filesystem\n";
}
// Load from filesystem
return Loader::get().loadResource(filepath);
}
// Load from filesystem
return Loader::get().loadResource(filepath);
}
// Check if a file exists
auto fileExists(const std::string& filepath) -> bool {
if (!resource_system_initialized) {
return std::filesystem::exists(filepath);
}
// Check if a file exists
auto fileExists(const std::string& filepath) -> bool {
if (!resource_system_initialized) {
// Check pack if appropriate
if (shouldUseResourcePack(filepath)) {
std::string pack_path = getPackPath(filepath);
if (Loader::get().resourceExists(pack_path)) {
return true;
}
}
// Check filesystem
return std::filesystem::exists(filepath);
}
// Check pack if appropriate
if (shouldUseResourcePack(filepath)) {
std::string pack_path = getPackPath(filepath);
if (Loader::get().resourceExists(pack_path)) {
// Convert asset path to pack path
auto getPackPath(const std::string& asset_path) -> std::string {
std::string path = asset_path;
// Convert backslashes to forward slashes
std::ranges::replace(path, '\\', '/');
// If it's an absolute path containing "/data/", extract everything after "/data/"
// This handles paths like: /Users/sergio/.../data/palette/file.pal -> palette/file.pal
size_t data_pos = path.find("/data/");
if (data_pos != std::string::npos) {
return path.substr(data_pos + 6); // +6 to skip "/data/"
}
// Remove leading slashes
while (!path.empty() && path[0] == '/') {
path = path.substr(1);
}
// Remove "./" prefix if present
if (path.starts_with("./")) {
path = path.substr(2);
}
// Remove "../" prefixes (for macOS bundle paths in development)
while (path.starts_with("../")) {
path = path.substr(3);
}
// Remove "Resources/" prefix if present (for macOS bundle)
const std::string RESOURCES_PREFIX = "Resources/";
if (path.starts_with(RESOURCES_PREFIX)) {
path = path.substr(RESOURCES_PREFIX.length());
}
// Remove "data/" prefix if present
const std::string DATA_PREFIX = "data/";
if (path.starts_with(DATA_PREFIX)) {
path = path.substr(DATA_PREFIX.length());
}
return path;
}
// Check if file should use resource pack
auto shouldUseResourcePack(const std::string& filepath) -> bool {
std::string path = filepath;
std::ranges::replace(path, '\\', '/');
// Don't use pack for most config files (except config/assets.yaml which is loaded
// directly via Loader::loadAssetsConfig() in release builds)
if (path.find("config/") != std::string::npos) {
return false;
}
// Use pack for data files
if (path.find("data/") != std::string::npos) {
return true;
}
}
// Check filesystem
return std::filesystem::exists(filepath);
}
// Check if it looks like a data file (has common extensions)
if (path.find(".ogg") != std::string::npos || path.find(".wav") != std::string::npos ||
path.find(".gif") != std::string::npos || path.find(".png") != std::string::npos ||
path.find(".pal") != std::string::npos || path.find(".yaml") != std::string::npos ||
path.find(".txt") != std::string::npos || path.find(".glsl") != std::string::npos) {
return true;
}
// Convert asset path to pack path
auto getPackPath(const std::string& asset_path) -> std::string {
std::string path = asset_path;
// Convert backslashes to forward slashes
std::ranges::replace(path, '\\', '/');
// If it's an absolute path containing "/data/", extract everything after "/data/"
// This handles paths like: /Users/sergio/.../data/palette/file.pal -> palette/file.pal
size_t data_pos = path.find("/data/");
if (data_pos != std::string::npos) {
return path.substr(data_pos + 6); // +6 to skip "/data/"
}
// Remove leading slashes
while (!path.empty() && path[0] == '/') {
path = path.substr(1);
}
// Remove "./" prefix if present
if (path.starts_with("./")) {
path = path.substr(2);
}
// Remove "../" prefixes (for macOS bundle paths in development)
while (path.starts_with("../")) {
path = path.substr(3);
}
// Remove "Resources/" prefix if present (for macOS bundle)
const std::string RESOURCES_PREFIX = "Resources/";
if (path.starts_with(RESOURCES_PREFIX)) {
path = path.substr(RESOURCES_PREFIX.length());
}
// Remove "data/" prefix if present
const std::string DATA_PREFIX = "data/";
if (path.starts_with(DATA_PREFIX)) {
path = path.substr(DATA_PREFIX.length());
}
return path;
}
// Check if file should use resource pack
auto shouldUseResourcePack(const std::string& filepath) -> bool {
std::string path = filepath;
std::ranges::replace(path, '\\', '/');
// Don't use pack for most config files (except config/assets.yaml which is loaded
// directly via Loader::loadAssetsConfig() in release builds)
if (path.find("config/") != std::string::npos) {
return false;
}
// Use pack for data files
if (path.find("data/") != std::string::npos) {
return true;
// Check if pack is loaded
auto isPackLoaded() -> bool {
if (!resource_system_initialized) {
return false;
}
return Loader::get().isPackLoaded();
}
// Check if it looks like a data file (has common extensions)
if (path.find(".ogg") != std::string::npos || path.find(".wav") != std::string::npos ||
path.find(".gif") != std::string::npos || path.find(".png") != std::string::npos ||
path.find(".pal") != std::string::npos || path.find(".yaml") != std::string::npos ||
path.find(".txt") != std::string::npos || path.find(".glsl") != std::string::npos) {
return true;
}
return false;
}
// Check if pack is loaded
auto isPackLoaded() -> bool {
if (!resource_system_initialized) {
return false;
}
return Loader::get().isPackLoaded();
}
} // namespace Resource::Helper

View File

@@ -9,30 +9,30 @@
namespace Resource::Helper {
// Initialize the resource system
// pack_file: Path to resources.pack
// enable_fallback: Allow loading from filesystem if pack not available
auto initializeResourceSystem(const std::string& pack_file = "resources.pack",
bool enable_fallback = true) -> bool;
// Initialize the resource system
// pack_file: Path to resources.pack
// enable_fallback: Allow loading from filesystem if pack not available
auto initializeResourceSystem(const std::string& pack_file = "resources.pack",
bool enable_fallback = true) -> bool;
// Shutdown the resource system
void shutdownResourceSystem();
// Shutdown the resource system
void shutdownResourceSystem();
// Load a file (tries pack first, then filesystem if fallback enabled)
auto loadFile(const std::string& filepath) -> std::vector<uint8_t>;
// Load a file (tries pack first, then filesystem if fallback enabled)
auto loadFile(const std::string& filepath) -> std::vector<uint8_t>;
// Check if a file exists
auto fileExists(const std::string& filepath) -> bool;
// Check if a file exists
auto fileExists(const std::string& filepath) -> bool;
// Convert an asset path to a pack path
// Example: "data/music/title.ogg" -> "music/title.ogg"
auto getPackPath(const std::string& asset_path) -> std::string;
// Convert an asset path to a pack path
// Example: "data/music/title.ogg" -> "music/title.ogg"
auto getPackPath(const std::string& asset_path) -> std::string;
// Check if a file should use the resource pack
// Returns false for config/ files (always from filesystem)
auto shouldUseResourcePack(const std::string& filepath) -> bool;
// Check if a file should use the resource pack
// Returns false for config/ files (always from filesystem)
auto shouldUseResourcePack(const std::string& filepath) -> bool;
// Check if pack is loaded
auto isPackLoaded() -> bool;
// Check if pack is loaded
auto isPackLoaded() -> bool;
} // namespace Resource::Helper

View File

@@ -16,305 +16,305 @@
namespace Resource {
// Singleton
List* List::instance = nullptr;
// Singleton
List* List::instance = nullptr;
void List::init(const std::string& executable_path) {
List::instance = new List(executable_path);
}
void List::destroy() {
delete List::instance;
}
auto List::get() -> List* {
return List::instance;
}
// Añade un elemento al mapa (función auxiliar)
void List::addToMap(const std::string& file_path, Type type, bool required, bool absolute) {
std::string full_path = absolute ? file_path : executable_path_ + file_path;
std::string filename = getFileName(full_path);
// Verificar si ya existe el archivo
if (file_list_.find(filename) != file_list_.end()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset '%s' already exists, overwriting",
filename.c_str());
void List::init(const std::string& executable_path) {
List::instance = new List(executable_path);
}
file_list_.emplace(filename, Item{std::move(full_path), type, required});
}
// Añade un elemento a la lista
void List::add(const std::string& file_path, Type type, bool required, bool absolute) {
addToMap(file_path, type, required, absolute);
}
// Carga recursos desde un archivo de configuración con soporte para variables
void List::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) {
std::ifstream file(config_file_path);
if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error: Cannot open config file: %s",
config_file_path.c_str());
return;
void List::destroy() {
delete List::instance;
}
// Read entire file into string
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
auto List::get() -> List* {
return List::instance;
}
// Parse using loadFromString
loadFromString(buffer.str(), prefix, system_folder);
}
// Añade un elemento al mapa (función auxiliar)
void List::addToMap(const std::string& file_path, Type type, bool required, bool absolute) {
std::string full_path = absolute ? file_path : executable_path_ + file_path;
std::string filename = getFileName(full_path);
// Carga recursos desde un string de configuración (para release con pack)
void List::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) {
try {
// Parsear YAML
auto yaml = fkyaml::node::deserialize(config_content);
// Verificar si ya existe el archivo
if (file_list_.find(filename) != file_list_.end()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset '%s' already exists, overwriting",
filename.c_str());
}
// Verificar estructura básica
if (!yaml.contains("assets")) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid assets.yaml format - missing 'assets' key");
file_list_.emplace(filename, Item{std::move(full_path), type, required});
}
// Añade un elemento a la lista
void List::add(const std::string& file_path, Type type, bool required, bool absolute) {
addToMap(file_path, type, required, absolute);
}
// Carga recursos desde un archivo de configuración con soporte para variables
void List::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) {
std::ifstream file(config_file_path);
if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error: Cannot open config file: %s",
config_file_path.c_str());
return;
}
const auto& assets = yaml["assets"];
// Iterar sobre cada categoría (fonts, palettes, etc.)
for (auto it = assets.begin(); it != assets.end(); ++it) {
const std::string& category = it.key().get_value<std::string>();
const auto& category_assets = it.value();
// Verificar que es un array
if (!category_assets.is_sequence()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Category '%s' is not a sequence, skipping",
category.c_str());
continue;
}
// Procesar cada asset en la categoría
for (const auto& asset : category_assets) {
try {
// Verificar campos obligatorios
if (!asset.contains("type") || !asset.contains("path")) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset in category '%s' missing 'type' or 'path', skipping",
category.c_str());
continue;
}
// Extraer campos
auto type_str = asset["type"].get_value<std::string>();
auto path = asset["path"].get_value<std::string>();
// Valores por defecto
bool required = true;
bool absolute = false;
// Campos opcionales
if (asset.contains("required")) {
required = asset["required"].get_value<bool>();
}
if (asset.contains("absolute")) {
absolute = asset["absolute"].get_value<bool>();
}
// Reemplazar variables en la ruta
path = replaceVariables(path, prefix, system_folder);
// Parsear el tipo de asset
Type type = parseAssetType(type_str);
// Añadir al mapa
addToMap(path, type, required, absolute);
} catch (const std::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error parsing asset in category '%s': %s",
category.c_str(),
e.what());
}
}
}
std::cout << "Loaded " << file_list_.size() << " assets from YAML config" << '\n';
} catch (const fkyaml::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"YAML parsing error: %s",
e.what());
} catch (const std::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error loading assets: %s",
e.what());
}
}
// Devuelve la ruta completa a un fichero (búsqueda O(1))
auto List::get(const std::string& filename) const -> std::string {
auto it = file_list_.find(filename);
if (it != file_list_.end()) {
return it->second.file;
}
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found", filename.c_str());
return "";
}
// Carga datos del archivo
auto List::loadData(const std::string& filename) const -> std::vector<uint8_t> {
auto it = file_list_.find(filename);
if (it != file_list_.end()) {
std::ifstream file(it->second.file, std::ios::binary);
if (!file.is_open()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Could not open file %s for data loading",
filename.c_str());
return {};
}
// Obtener tamaño del archivo
file.seekg(0, std::ios::end);
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
// Leer datos
std::vector<uint8_t> data(size);
file.read(reinterpret_cast<char*>(data.data()), size);
// Read entire file into string
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
return data;
// Parse using loadFromString
loadFromString(buffer.str(), prefix, system_folder);
}
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found for data loading", filename.c_str());
return {};
}
// Carga recursos desde un string de configuración (para release con pack)
void List::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) {
try {
// Parsear YAML
auto yaml = fkyaml::node::deserialize(config_content);
// Verifica si un recurso existe
auto List::exists(const std::string& filename) const -> bool {
return file_list_.find(filename) != file_list_.end();
}
// Verificar estructura básica
if (!yaml.contains("assets")) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid assets.yaml format - missing 'assets' key");
return;
}
// Parsea string a Type
auto List::parseAssetType(const std::string& type_str) -> Type {
if (type_str == "DATA") {
return Type::DATA;
}
if (type_str == "BITMAP") {
return Type::BITMAP;
}
if (type_str == "ANIMATION") {
return Type::ANIMATION;
}
if (type_str == "MUSIC") {
return Type::MUSIC;
}
if (type_str == "SOUND") {
return Type::SOUND;
}
if (type_str == "FONT") {
return Type::FONT;
}
if (type_str == "ROOM") {
return Type::ROOM;
}
if (type_str == "TILEMAP") {
// TILEMAP está obsoleto, ahora todo es ROOM (.yaml unificado)
return Type::ROOM;
}
if (type_str == "PALETTE") {
return Type::PALETTE;
}
const auto& assets = yaml["assets"];
throw std::runtime_error("Unknown asset type: " + type_str);
}
// Iterar sobre cada categoría (fonts, palettes, etc.)
for (auto it = assets.begin(); it != assets.end(); ++it) {
const std::string& category = it.key().get_value<std::string>();
const auto& category_assets = it.value();
// Devuelve el nombre del tipo de recurso
auto List::getTypeName(Type type) -> std::string {
switch (type) {
case Type::DATA:
return "DATA";
case Type::BITMAP:
return "BITMAP";
case Type::ANIMATION:
return "ANIMATION";
case Type::MUSIC:
return "MUSIC";
case Type::SOUND:
return "SOUND";
case Type::FONT:
return "FONT";
case Type::ROOM:
return "ROOM";
case Type::PALETTE:
return "PALETTE";
default:
return "ERROR";
}
}
// Verificar que es un array
if (!category_assets.is_sequence()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Category '%s' is not a sequence, skipping",
category.c_str());
continue;
}
// Devuelve la lista de recursos de un tipo
auto List::getListByType(Type type) const -> std::vector<std::string> {
std::vector<std::string> list;
// Procesar cada asset en la categoría
for (const auto& asset : category_assets) {
try {
// Verificar campos obligatorios
if (!asset.contains("type") || !asset.contains("path")) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Asset in category '%s' missing 'type' or 'path', skipping",
category.c_str());
continue;
}
for (const auto& [filename, item] : file_list_) {
if (item.type == type) {
list.push_back(item.file);
// Extraer campos
auto type_str = asset["type"].get_value<std::string>();
auto path = asset["path"].get_value<std::string>();
// Valores por defecto
bool required = true;
bool absolute = false;
// Campos opcionales
if (asset.contains("required")) {
required = asset["required"].get_value<bool>();
}
if (asset.contains("absolute")) {
absolute = asset["absolute"].get_value<bool>();
}
// Reemplazar variables en la ruta
path = replaceVariables(path, prefix, system_folder);
// Parsear el tipo de asset
Type type = parseAssetType(type_str);
// Añadir al mapa
addToMap(path, type, required, absolute);
} catch (const std::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error parsing asset in category '%s': %s",
category.c_str(),
e.what());
}
}
}
std::cout << "Loaded " << file_list_.size() << " assets from YAML config" << '\n';
} catch (const fkyaml::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"YAML parsing error: %s",
e.what());
} catch (const std::exception& e) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Error loading assets: %s",
e.what());
}
}
// Ordenar alfabéticamente para garantizar orden consistente
std::ranges::sort(list);
// Devuelve la ruta completa a un fichero (búsqueda O(1))
auto List::get(const std::string& filename) const -> std::string {
auto it = file_list_.find(filename);
if (it != file_list_.end()) {
return it->second.file;
}
return list;
}
// Reemplaza variables en las rutas
auto List::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string {
std::string result = path;
// Reemplazar ${PREFIX}
size_t pos = 0;
while ((pos = result.find("${PREFIX}", pos)) != std::string::npos) {
result.replace(pos, 9, prefix); // 9 = longitud de "${PREFIX}"
pos += prefix.length();
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found", filename.c_str());
return "";
}
// Reemplazar ${SYSTEM_FOLDER}
pos = 0;
while ((pos = result.find("${SYSTEM_FOLDER}", pos)) != std::string::npos) {
result.replace(pos, 16, system_folder); // 16 = longitud de "${SYSTEM_FOLDER}"
pos += system_folder.length();
// Carga datos del archivo
auto List::loadData(const std::string& filename) const -> std::vector<uint8_t> {
auto it = file_list_.find(filename);
if (it != file_list_.end()) {
std::ifstream file(it->second.file, std::ios::binary);
if (!file.is_open()) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Warning: Could not open file %s for data loading",
filename.c_str());
return {};
}
// Obtener tamaño del archivo
file.seekg(0, std::ios::end);
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
// Leer datos
std::vector<uint8_t> data(size);
file.read(reinterpret_cast<char*>(data.data()), size);
file.close();
return data;
}
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found for data loading", filename.c_str());
return {};
}
return result;
}
// Parsea las opciones de una línea de configuración
auto List::parseOptions(const std::string& options, bool& required, bool& absolute) -> void {
if (options.empty()) {
return;
// Verifica si un recurso existe
auto List::exists(const std::string& filename) const -> bool {
return file_list_.find(filename) != file_list_.end();
}
std::istringstream iss(options);
std::string option;
// Parsea string a Type
auto List::parseAssetType(const std::string& type_str) -> Type {
if (type_str == "DATA") {
return Type::DATA;
}
if (type_str == "BITMAP") {
return Type::BITMAP;
}
if (type_str == "ANIMATION") {
return Type::ANIMATION;
}
if (type_str == "MUSIC") {
return Type::MUSIC;
}
if (type_str == "SOUND") {
return Type::SOUND;
}
if (type_str == "FONT") {
return Type::FONT;
}
if (type_str == "ROOM") {
return Type::ROOM;
}
if (type_str == "TILEMAP") {
// TILEMAP está obsoleto, ahora todo es ROOM (.yaml unificado)
return Type::ROOM;
}
if (type_str == "PALETTE") {
return Type::PALETTE;
}
while (std::getline(iss, option, ',')) {
// Eliminar espacios
option.erase(0, option.find_first_not_of(" \t"));
option.erase(option.find_last_not_of(" \t") + 1);
throw std::runtime_error("Unknown asset type: " + type_str);
}
if (option == "optional") {
required = false;
} else if (option == "absolute") {
absolute = true;
// Devuelve el nombre del tipo de recurso
auto List::getTypeName(Type type) -> std::string {
switch (type) {
case Type::DATA:
return "DATA";
case Type::BITMAP:
return "BITMAP";
case Type::ANIMATION:
return "ANIMATION";
case Type::MUSIC:
return "MUSIC";
case Type::SOUND:
return "SOUND";
case Type::FONT:
return "FONT";
case Type::ROOM:
return "ROOM";
case Type::PALETTE:
return "PALETTE";
default:
return "ERROR";
}
}
// Devuelve la lista de recursos de un tipo
auto List::getListByType(Type type) const -> std::vector<std::string> {
std::vector<std::string> list;
for (const auto& [filename, item] : file_list_) {
if (item.type == type) {
list.push_back(item.file);
}
}
// Ordenar alfabéticamente para garantizar orden consistente
std::ranges::sort(list);
return list;
}
// Reemplaza variables en las rutas
auto List::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string {
std::string result = path;
// Reemplazar ${PREFIX}
size_t pos = 0;
while ((pos = result.find("${PREFIX}", pos)) != std::string::npos) {
result.replace(pos, 9, prefix); // 9 = longitud de "${PREFIX}"
pos += prefix.length();
}
// Reemplazar ${SYSTEM_FOLDER}
pos = 0;
while ((pos = result.find("${SYSTEM_FOLDER}", pos)) != std::string::npos) {
result.replace(pos, 16, system_folder); // 16 = longitud de "${SYSTEM_FOLDER}"
pos += system_folder.length();
}
return result;
}
// Parsea las opciones de una línea de configuración
auto List::parseOptions(const std::string& options, bool& required, bool& absolute) -> void {
if (options.empty()) {
return;
}
std::istringstream iss(options);
std::string option;
while (std::getline(iss, option, ',')) {
// Eliminar espacios
option.erase(0, option.find_first_not_of(" \t"));
option.erase(option.find_last_not_of(" \t") + 1);
if (option == "optional") {
required = false;
} else if (option == "absolute") {
absolute = true;
}
}
}
}
} // namespace Resource

View File

@@ -8,9 +8,9 @@
namespace Resource {
// --- Clase List: gestor optimizado de recursos (singleton) ---
class List {
public:
// --- Clase List: gestor optimizado de recursos (singleton) ---
class List {
public:
// --- Enums ---
enum class Type : int {
DATA, // Datos
@@ -40,17 +40,17 @@ class List {
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
[[nodiscard]] auto exists(const std::string& filename) const -> bool; // Verifica si un asset existe
private:
private:
// --- Estructuras privadas ---
struct Item {
std::string file; // Ruta completa del archivo
Type type; // Tipo de recurso
bool required; // Indica si el archivo es obligatorio
std::string file; // Ruta completa del archivo
Type type; // Tipo de recurso
bool required; // Indica si el archivo es obligatorio
Item(std::string path, Type asset_type, bool is_required)
: file(std::move(path)),
type(asset_type),
required(is_required) {}
Item(std::string path, Type asset_type, bool is_required)
: file(std::move(path)),
type(asset_type),
required(is_required) {}
};
// --- Variables internas ---
@@ -71,6 +71,6 @@ class List {
// --- Instancia singleton ---
static List* instance; // Instancia única de List
};
};
} // namespace Resource

View File

@@ -9,191 +9,191 @@
namespace Resource {
// Get singleton instance
auto Loader::get() -> Loader& {
static Loader instance_;
return instance_;
}
// Get singleton instance
auto Loader::get() -> Loader& {
static Loader instance_;
return instance_;
}
// Initialize with a pack file
auto Loader::initialize(const std::string& pack_file, bool enable_fallback)
-> bool {
if (initialized_) {
std::cout << "Loader: Already initialized\n";
// Initialize with a pack file
auto Loader::initialize(const std::string& pack_file, bool enable_fallback)
-> bool {
if (initialized_) {
std::cout << "Loader: Already initialized\n";
return true;
}
fallback_to_files_ = enable_fallback;
// Try to load the pack file
if (!pack_file.empty() && fileExistsOnFilesystem(pack_file)) {
std::cout << "Loader: Loading pack file: " << pack_file << '\n';
resource_pack_ = std::make_unique<Pack>();
if (resource_pack_->loadPack(pack_file)) {
std::cout << "Loader: Pack loaded successfully\n";
initialized_ = true;
return true;
}
std::cerr << "Loader: Failed to load pack file\n";
resource_pack_.reset();
} else {
std::cout << "Loader: Pack file not found: " << pack_file << '\n';
}
// If pack loading failed and fallback is disabled, fail
if (!fallback_to_files_) {
std::cerr << "Loader: Pack required but not found (fallback disabled)\n";
return false;
}
// Otherwise, fallback to filesystem
std::cout << "Loader: Using filesystem fallback\n";
initialized_ = true;
return true;
}
fallback_to_files_ = enable_fallback;
// Try to load the pack file
if (!pack_file.empty() && fileExistsOnFilesystem(pack_file)) {
std::cout << "Loader: Loading pack file: " << pack_file << '\n';
resource_pack_ = std::make_unique<Pack>();
if (resource_pack_->loadPack(pack_file)) {
std::cout << "Loader: Pack loaded successfully\n";
initialized_ = true;
return true;
// Load a resource
auto Loader::loadResource(const std::string& filename) -> std::vector<uint8_t> {
if (!initialized_) {
std::cerr << "Loader: Not initialized\n";
return {};
}
std::cerr << "Loader: Failed to load pack file\n";
resource_pack_.reset();
} else {
std::cout << "Loader: Pack file not found: " << pack_file << '\n';
}
// If pack loading failed and fallback is disabled, fail
if (!fallback_to_files_) {
std::cerr << "Loader: Pack required but not found (fallback disabled)\n";
return false;
}
// Otherwise, fallback to filesystem
std::cout << "Loader: Using filesystem fallback\n";
initialized_ = true;
return true;
}
// Load a resource
auto Loader::loadResource(const std::string& filename) -> std::vector<uint8_t> {
if (!initialized_) {
std::cerr << "Loader: Not initialized\n";
return {};
}
// Try pack first if available
if (resource_pack_ && resource_pack_->isLoaded()) {
if (resource_pack_->hasResource(filename)) {
auto data = resource_pack_->getResource(filename);
if (!data.empty()) {
return data;
// Try pack first if available
if (resource_pack_ && resource_pack_->isLoaded()) {
if (resource_pack_->hasResource(filename)) {
auto data = resource_pack_->getResource(filename);
if (!data.empty()) {
return data;
}
std::cerr << "Loader: Failed to extract from pack: " << filename
<< '\n';
}
std::cerr << "Loader: Failed to extract from pack: " << filename
<< '\n';
}
}
// Fallback to filesystem if enabled
if (fallback_to_files_) {
return loadFromFilesystem(filename);
}
std::cerr << "Loader: Resource not found: " << filename << '\n';
return {};
}
// Check if a resource exists
auto Loader::resourceExists(const std::string& filename) -> bool {
if (!initialized_) {
return false;
}
// Check pack first
if (resource_pack_ && resource_pack_->isLoaded()) {
if (resource_pack_->hasResource(filename)) {
return true;
// Fallback to filesystem if enabled
if (fallback_to_files_) {
return loadFromFilesystem(filename);
}
}
// Check filesystem if fallback enabled
if (fallback_to_files_) {
return fileExistsOnFilesystem(filename);
}
return false;
}
// Check if pack is loaded
auto Loader::isPackLoaded() const -> bool {
return resource_pack_ && resource_pack_->isLoaded();
}
// Get pack statistics
auto Loader::getPackResourceCount() const -> size_t {
if (resource_pack_ && resource_pack_->isLoaded()) {
return resource_pack_->getResourceCount();
}
return 0;
}
// Cleanup
void Loader::shutdown() {
resource_pack_.reset();
initialized_ = false;
std::cout << "Loader: Shutdown complete\n";
}
// Load from filesystem
auto Loader::loadFromFilesystem(const std::string& filepath)
-> std::vector<uint8_t> {
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
std::cerr << "Loader: Resource not found: " << filename << '\n';
return {};
}
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
// Check if a resource exists
auto Loader::resourceExists(const std::string& filename) -> bool {
if (!initialized_) {
return false;
}
std::vector<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
std::cerr << "Loader: Failed to read file: " << filepath << '\n';
return {};
}
// Check pack first
if (resource_pack_ && resource_pack_->isLoaded()) {
if (resource_pack_->hasResource(filename)) {
return true;
}
}
return data;
}
// Check filesystem if fallback enabled
if (fallback_to_files_) {
return fileExistsOnFilesystem(filename);
}
// Check if file exists on filesystem
auto Loader::fileExistsOnFilesystem(const std::string& filepath) -> bool {
return std::filesystem::exists(filepath);
}
// Validate pack integrity
auto Loader::validatePack() const -> bool {
if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) {
std::cerr << "Loader: Cannot validate - pack not loaded\n";
return false;
}
// Calculate pack checksum
uint32_t checksum = resource_pack_->calculatePackChecksum();
if (checksum == 0) {
std::cerr << "Loader: Pack checksum is zero (invalid)\n";
return false;
// Check if pack is loaded
auto Loader::isPackLoaded() const -> bool {
return resource_pack_ && resource_pack_->isLoaded();
}
std::cout << "Loader: Pack checksum: 0x" << std::hex << checksum << std::dec
<< '\n';
std::cout << "Loader: Pack validation successful\n";
return true;
}
// Load assets.yaml from pack
auto Loader::loadAssetsConfig() const -> std::string {
if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) {
std::cerr << "Loader: Cannot load assets config - pack not loaded\n";
return "";
// Get pack statistics
auto Loader::getPackResourceCount() const -> size_t {
if (resource_pack_ && resource_pack_->isLoaded()) {
return resource_pack_->getResourceCount();
}
return 0;
}
// Try to load config/assets.yaml from pack
std::string config_path = "config/assets.yaml";
if (!resource_pack_->hasResource(config_path)) {
std::cerr << "Loader: assets.yaml not found in pack: " << config_path << '\n';
return "";
// Cleanup
void Loader::shutdown() {
resource_pack_.reset();
initialized_ = false;
std::cout << "Loader: Shutdown complete\n";
}
auto data = resource_pack_->getResource(config_path);
if (data.empty()) {
std::cerr << "Loader: Failed to load assets.yaml from pack\n";
return "";
// Load from filesystem
auto Loader::loadFromFilesystem(const std::string& filepath)
-> std::vector<uint8_t> {
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
return {};
}
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
std::cerr << "Loader: Failed to read file: " << filepath << '\n';
return {};
}
return data;
}
// Convert bytes to string
std::string config_content(data.begin(), data.end());
std::cout << "Loader: Loaded assets.yaml from pack (" << data.size()
<< " bytes)\n";
// Check if file exists on filesystem
auto Loader::fileExistsOnFilesystem(const std::string& filepath) -> bool {
return std::filesystem::exists(filepath);
}
return config_content;
}
// Validate pack integrity
auto Loader::validatePack() const -> bool {
if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) {
std::cerr << "Loader: Cannot validate - pack not loaded\n";
return false;
}
// Calculate pack checksum
uint32_t checksum = resource_pack_->calculatePackChecksum();
if (checksum == 0) {
std::cerr << "Loader: Pack checksum is zero (invalid)\n";
return false;
}
std::cout << "Loader: Pack checksum: 0x" << std::hex << checksum << std::dec
<< '\n';
std::cout << "Loader: Pack validation successful\n";
return true;
}
// Load assets.yaml from pack
auto Loader::loadAssetsConfig() const -> std::string {
if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) {
std::cerr << "Loader: Cannot load assets config - pack not loaded\n";
return "";
}
// Try to load config/assets.yaml from pack
std::string config_path = "config/assets.yaml";
if (!resource_pack_->hasResource(config_path)) {
std::cerr << "Loader: assets.yaml not found in pack: " << config_path << '\n';
return "";
}
auto data = resource_pack_->getResource(config_path);
if (data.empty()) {
std::cerr << "Loader: Failed to load assets.yaml from pack\n";
return "";
}
// Convert bytes to string
std::string config_content(data.begin(), data.end());
std::cout << "Loader: Loaded assets.yaml from pack (" << data.size()
<< " bytes)\n";
return config_content;
}
} // namespace Resource

View File

@@ -11,9 +11,9 @@
namespace Resource {
// Singleton class for loading resources from pack or filesystem
class Loader {
public:
// Singleton class for loading resources from pack or filesystem
class Loader {
public:
static auto get() -> Loader&; // Singleton instance access
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool; // Initialize loader with pack file
@@ -33,7 +33,7 @@ class Loader {
Loader(Loader&&) = delete;
auto operator=(Loader&&) -> Loader& = delete;
private:
private:
Loader() = default;
~Loader() = default;
@@ -43,6 +43,6 @@ class Loader {
std::unique_ptr<Pack> resource_pack_; // Member variables
bool fallback_to_files_{true};
bool initialized_{false};
};
};
} // namespace Resource

View File

@@ -12,292 +12,292 @@
namespace Resource {
// Calculate CRC32 checksum for data verification
auto Pack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t {
uint32_t checksum = 0x12345678;
for (unsigned char byte : data) {
checksum = ((checksum << 5) + checksum) + byte;
}
return checksum;
}
// XOR encryption (symmetric - same function for encrypt/decrypt)
void Pack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
if (key.empty()) {
return;
}
for (size_t i = 0; i < data.size(); ++i) {
data[i] ^= key[i % key.length()];
}
}
void Pack::decryptData(std::vector<uint8_t>& data, const std::string& key) {
// XOR is symmetric
encryptData(data, key);
}
// Read entire file into memory
auto Pack::readFile(const std::string& filepath) -> std::vector<uint8_t> {
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
std::cerr << "ResourcePack: Failed to open file: " << filepath << '\n';
return {};
// Calculate CRC32 checksum for data verification
auto Pack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t {
uint32_t checksum = 0x12345678;
for (unsigned char byte : data) {
checksum = ((checksum << 5) + checksum) + byte;
}
return checksum;
}
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
std::cerr << "ResourcePack: Failed to read file: " << filepath << '\n';
return {};
// XOR encryption (symmetric - same function for encrypt/decrypt)
void Pack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
if (key.empty()) {
return;
}
for (size_t i = 0; i < data.size(); ++i) {
data[i] ^= key[i % key.length()];
}
}
return data;
}
// Add a single file to the pack
auto Pack::addFile(const std::string& filepath, const std::string& pack_name)
-> bool {
auto file_data = readFile(filepath);
if (file_data.empty()) {
return false;
void Pack::decryptData(std::vector<uint8_t>& data, const std::string& key) {
// XOR is symmetric
encryptData(data, key);
}
ResourceEntry entry{
.filename = pack_name,
.offset = data_.size(),
.size = file_data.size(),
.checksum = calculateChecksum(file_data)};
// Append file data to the data block
data_.insert(data_.end(), file_data.begin(), file_data.end());
resources_[pack_name] = entry;
std::cout << "Added: " << pack_name << " (" << file_data.size() << " bytes)\n";
return true;
}
// Add all files from a directory recursively
auto Pack::addDirectory(const std::string& dir_path,
const std::string& base_path) -> bool {
namespace fs = std::filesystem;
if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
std::cerr << "ResourcePack: Directory not found: " << dir_path << '\n';
return false;
}
std::string current_base = base_path.empty() ? "" : base_path + "/";
for (const auto& entry : fs::recursive_directory_iterator(dir_path)) {
if (!entry.is_regular_file()) {
continue;
// Read entire file into memory
auto Pack::readFile(const std::string& filepath) -> std::vector<uint8_t> {
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
std::cerr << "ResourcePack: Failed to open file: " << filepath << '\n';
return {};
}
std::string full_path = entry.path().string();
std::string relative_path = entry.path().lexically_relative(dir_path).string();
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
// Convert backslashes to forward slashes (Windows compatibility)
std::ranges::replace(relative_path, '\\', '/');
// Skip development files
if (relative_path.find(".world") != std::string::npos ||
relative_path.find(".tsx") != std::string::npos) {
std::cout << "Skipping development file: " << relative_path << '\n';
continue;
std::vector<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
std::cerr << "ResourcePack: Failed to read file: " << filepath << '\n';
return {};
}
std::string pack_name = current_base + relative_path;
addFile(full_path, pack_name);
return data;
}
return true;
}
// Add a single file to the pack
auto Pack::addFile(const std::string& filepath, const std::string& pack_name)
-> bool {
auto file_data = readFile(filepath);
if (file_data.empty()) {
return false;
}
// Save the pack to a file
auto Pack::savePack(const std::string& pack_file) -> bool {
std::ofstream file(pack_file, std::ios::binary);
if (!file) {
std::cerr << "ResourcePack: Failed to create pack file: " << pack_file << '\n';
return false;
ResourceEntry entry{
.filename = pack_name,
.offset = data_.size(),
.size = file_data.size(),
.checksum = calculateChecksum(file_data)};
// Append file data to the data block
data_.insert(data_.end(), file_data.begin(), file_data.end());
resources_[pack_name] = entry;
std::cout << "Added: " << pack_name << " (" << file_data.size() << " bytes)\n";
return true;
}
// Write header
file.write(MAGIC_HEADER.data(), MAGIC_HEADER.size());
file.write(reinterpret_cast<const char*>(&VERSION), sizeof(VERSION));
// Add all files from a directory recursively
auto Pack::addDirectory(const std::string& dir_path,
const std::string& base_path) -> bool {
namespace fs = std::filesystem;
// Write resource count
auto resource_count = static_cast<uint32_t>(resources_.size());
file.write(reinterpret_cast<const char*>(&resource_count), sizeof(resource_count));
if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
std::cerr << "ResourcePack: Directory not found: " << dir_path << '\n';
return false;
}
// Write resource entries
for (const auto& [name, entry] : resources_) {
// Write filename length and name
auto name_len = static_cast<uint32_t>(entry.filename.length());
file.write(reinterpret_cast<const char*>(&name_len), sizeof(name_len));
file.write(entry.filename.c_str(), name_len);
std::string current_base = base_path.empty() ? "" : base_path + "/";
// Write offset, size, checksum
file.write(reinterpret_cast<const char*>(&entry.offset), sizeof(entry.offset));
file.write(reinterpret_cast<const char*>(&entry.size), sizeof(entry.size));
file.write(reinterpret_cast<const char*>(&entry.checksum), sizeof(entry.checksum));
for (const auto& entry : fs::recursive_directory_iterator(dir_path)) {
if (!entry.is_regular_file()) {
continue;
}
std::string full_path = entry.path().string();
std::string relative_path = entry.path().lexically_relative(dir_path).string();
// Convert backslashes to forward slashes (Windows compatibility)
std::ranges::replace(relative_path, '\\', '/');
// Skip development files
if (relative_path.find(".world") != std::string::npos ||
relative_path.find(".tsx") != std::string::npos) {
std::cout << "Skipping development file: " << relative_path << '\n';
continue;
}
std::string pack_name = current_base + relative_path;
addFile(full_path, pack_name);
}
return true;
}
// Encrypt data
std::vector<uint8_t> encrypted_data = data_;
encryptData(encrypted_data, DEFAULT_ENCRYPT_KEY);
// Save the pack to a file
auto Pack::savePack(const std::string& pack_file) -> bool {
std::ofstream file(pack_file, std::ios::binary);
if (!file) {
std::cerr << "ResourcePack: Failed to create pack file: " << pack_file << '\n';
return false;
}
// Write encrypted data size and data
uint64_t data_size = encrypted_data.size();
file.write(reinterpret_cast<const char*>(&data_size), sizeof(data_size));
file.write(reinterpret_cast<const char*>(encrypted_data.data()), data_size);
// Write header
file.write(MAGIC_HEADER.data(), MAGIC_HEADER.size());
file.write(reinterpret_cast<const char*>(&VERSION), sizeof(VERSION));
std::cout << "\nPack saved successfully: " << pack_file << '\n';
std::cout << "Resources: " << resource_count << '\n';
std::cout << "Total size: " << data_size << " bytes\n";
// Write resource count
auto resource_count = static_cast<uint32_t>(resources_.size());
file.write(reinterpret_cast<const char*>(&resource_count), sizeof(resource_count));
return true;
}
// Write resource entries
for (const auto& [name, entry] : resources_) {
// Write filename length and name
auto name_len = static_cast<uint32_t>(entry.filename.length());
file.write(reinterpret_cast<const char*>(&name_len), sizeof(name_len));
file.write(entry.filename.c_str(), name_len);
// Load a pack from a file
auto Pack::loadPack(const std::string& pack_file) -> bool {
std::ifstream file(pack_file, std::ios::binary);
if (!file) {
std::cerr << "ResourcePack: Failed to open pack file: " << pack_file << '\n';
return false;
// Write offset, size, checksum
file.write(reinterpret_cast<const char*>(&entry.offset), sizeof(entry.offset));
file.write(reinterpret_cast<const char*>(&entry.size), sizeof(entry.size));
file.write(reinterpret_cast<const char*>(&entry.checksum), sizeof(entry.checksum));
}
// Encrypt data
std::vector<uint8_t> encrypted_data = data_;
encryptData(encrypted_data, DEFAULT_ENCRYPT_KEY);
// Write encrypted data size and data
uint64_t data_size = encrypted_data.size();
file.write(reinterpret_cast<const char*>(&data_size), sizeof(data_size));
file.write(reinterpret_cast<const char*>(encrypted_data.data()), data_size);
std::cout << "\nPack saved successfully: " << pack_file << '\n';
std::cout << "Resources: " << resource_count << '\n';
std::cout << "Total size: " << data_size << " bytes\n";
return true;
}
// Read and verify header
std::array<char, 4> header{};
file.read(header.data(), header.size());
if (header != MAGIC_HEADER) {
std::cerr << "ResourcePack: Invalid pack header\n";
return false;
// Load a pack from a file
auto Pack::loadPack(const std::string& pack_file) -> bool {
std::ifstream file(pack_file, std::ios::binary);
if (!file) {
std::cerr << "ResourcePack: Failed to open pack file: " << pack_file << '\n';
return false;
}
// Read and verify header
std::array<char, 4> header{};
file.read(header.data(), header.size());
if (header != MAGIC_HEADER) {
std::cerr << "ResourcePack: Invalid pack header\n";
return false;
}
// Read and verify version
uint32_t version = 0;
file.read(reinterpret_cast<char*>(&version), sizeof(version));
if (version != VERSION) {
std::cerr << "ResourcePack: Unsupported pack version: " << version << '\n';
return false;
}
// Read resource count
uint32_t resource_count = 0;
file.read(reinterpret_cast<char*>(&resource_count), sizeof(resource_count));
// Read resource entries
resources_.clear();
for (uint32_t i = 0; i < resource_count; ++i) {
// Read filename
uint32_t name_len = 0;
file.read(reinterpret_cast<char*>(&name_len), sizeof(name_len));
std::string filename(name_len, '\0');
file.read(filename.data(), name_len);
// Read entry data
ResourceEntry entry{};
entry.filename = filename;
file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset));
file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));
file.read(reinterpret_cast<char*>(&entry.checksum), sizeof(entry.checksum));
resources_[filename] = entry;
}
// Read encrypted data
uint64_t data_size = 0;
file.read(reinterpret_cast<char*>(&data_size), sizeof(data_size));
data_.resize(data_size);
file.read(reinterpret_cast<char*>(data_.data()), data_size);
// Decrypt data
decryptData(data_, DEFAULT_ENCRYPT_KEY);
loaded_ = true;
std::cout << "ResourcePack loaded: " << pack_file << '\n';
std::cout << "Resources: " << resource_count << '\n';
std::cout << "Data size: " << data_size << " bytes\n";
return true;
}
// Read and verify version
uint32_t version = 0;
file.read(reinterpret_cast<char*>(&version), sizeof(version));
if (version != VERSION) {
std::cerr << "ResourcePack: Unsupported pack version: " << version << '\n';
return false;
// Get a resource by name
auto Pack::getResource(const std::string& filename) -> std::vector<uint8_t> {
auto it = resources_.find(filename);
if (it == resources_.end()) {
return {};
}
const ResourceEntry& entry = it->second;
// Extract data slice
if (entry.offset + entry.size > data_.size()) {
std::cerr << "ResourcePack: Invalid offset/size for: " << filename << '\n';
return {};
}
std::vector<uint8_t> result(data_.begin() + entry.offset,
data_.begin() + entry.offset + entry.size);
// Verify checksum
uint32_t checksum = calculateChecksum(result);
if (checksum != entry.checksum) {
std::cerr << "ResourcePack: Checksum mismatch for: " << filename << '\n';
std::cerr << " Expected: 0x" << std::hex << entry.checksum << '\n';
std::cerr << " Got: 0x" << std::hex << checksum << std::dec << '\n';
}
return result;
}
// Read resource count
uint32_t resource_count = 0;
file.read(reinterpret_cast<char*>(&resource_count), sizeof(resource_count));
// Read resource entries
resources_.clear();
for (uint32_t i = 0; i < resource_count; ++i) {
// Read filename
uint32_t name_len = 0;
file.read(reinterpret_cast<char*>(&name_len), sizeof(name_len));
std::string filename(name_len, '\0');
file.read(filename.data(), name_len);
// Read entry data
ResourceEntry entry{};
entry.filename = filename;
file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset));
file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));
file.read(reinterpret_cast<char*>(&entry.checksum), sizeof(entry.checksum));
resources_[filename] = entry;
// Check if a resource exists
auto Pack::hasResource(const std::string& filename) const -> bool {
return resources_.find(filename) != resources_.end();
}
// Read encrypted data
uint64_t data_size = 0;
file.read(reinterpret_cast<char*>(&data_size), sizeof(data_size));
data_.resize(data_size);
file.read(reinterpret_cast<char*>(data_.data()), data_size);
// Decrypt data
decryptData(data_, DEFAULT_ENCRYPT_KEY);
loaded_ = true;
std::cout << "ResourcePack loaded: " << pack_file << '\n';
std::cout << "Resources: " << resource_count << '\n';
std::cout << "Data size: " << data_size << " bytes\n";
return true;
}
// Get a resource by name
auto Pack::getResource(const std::string& filename) -> std::vector<uint8_t> {
auto it = resources_.find(filename);
if (it == resources_.end()) {
return {};
// Get list of all resources
auto Pack::getResourceList() const -> std::vector<std::string> {
std::vector<std::string> list;
list.reserve(resources_.size());
for (const auto& [name, entry] : resources_) {
list.push_back(name);
}
std::ranges::sort(list);
return list;
}
const ResourceEntry& entry = it->second;
// Calculate overall pack checksum for validation
auto Pack::calculatePackChecksum() const -> uint32_t {
if (!loaded_ || data_.empty()) {
return 0;
}
// Extract data slice
if (entry.offset + entry.size > data_.size()) {
std::cerr << "ResourcePack: Invalid offset/size for: " << filename << '\n';
return {};
// Combine checksums of all resources for a global checksum
uint32_t global_checksum = 0x87654321;
// Sort resources by name for deterministic checksum
std::vector<std::string> sorted_names;
sorted_names.reserve(resources_.size());
for (const auto& [name, entry] : resources_) {
sorted_names.push_back(name);
}
std::ranges::sort(sorted_names);
// Combine individual checksums
for (const auto& name : sorted_names) {
const auto& entry = resources_.at(name);
global_checksum = ((global_checksum << 5) + global_checksum) + entry.checksum;
global_checksum = ((global_checksum << 5) + global_checksum) + entry.size;
}
return global_checksum;
}
std::vector<uint8_t> result(data_.begin() + entry.offset,
data_.begin() + entry.offset + entry.size);
// Verify checksum
uint32_t checksum = calculateChecksum(result);
if (checksum != entry.checksum) {
std::cerr << "ResourcePack: Checksum mismatch for: " << filename << '\n';
std::cerr << " Expected: 0x" << std::hex << entry.checksum << '\n';
std::cerr << " Got: 0x" << std::hex << checksum << std::dec << '\n';
}
return result;
}
// Check if a resource exists
auto Pack::hasResource(const std::string& filename) const -> bool {
return resources_.find(filename) != resources_.end();
}
// Get list of all resources
auto Pack::getResourceList() const -> std::vector<std::string> {
std::vector<std::string> list;
list.reserve(resources_.size());
for (const auto& [name, entry] : resources_) {
list.push_back(name);
}
std::ranges::sort(list);
return list;
}
// Calculate overall pack checksum for validation
auto Pack::calculatePackChecksum() const -> uint32_t {
if (!loaded_ || data_.empty()) {
return 0;
}
// Combine checksums of all resources for a global checksum
uint32_t global_checksum = 0x87654321;
// Sort resources by name for deterministic checksum
std::vector<std::string> sorted_names;
sorted_names.reserve(resources_.size());
for (const auto& [name, entry] : resources_) {
sorted_names.push_back(name);
}
std::ranges::sort(sorted_names);
// Combine individual checksums
for (const auto& name : sorted_names) {
const auto& entry = resources_.at(name);
global_checksum = ((global_checksum << 5) + global_checksum) + entry.checksum;
global_checksum = ((global_checksum << 5) + global_checksum) + entry.size;
}
return global_checksum;
}
} // namespace Resource

View File

@@ -11,20 +11,20 @@
namespace Resource {
// Entry metadata for each resource in the pack
struct ResourceEntry {
// Entry metadata for each resource in the pack
struct ResourceEntry {
std::string filename; // Relative path within pack
uint64_t offset{0}; // Byte offset in data block
uint64_t size{0}; // Size in bytes
uint32_t checksum{0}; // CRC32 checksum for verification
};
};
// Resource pack file format
// Header: "JDDI" (4 bytes) + Version (4 bytes)
// Metadata: Count + array of ResourceEntry
// Data: Encrypted data block
class Pack {
public:
// Resource pack file format
// Header: "JDDI" (4 bytes) + Version (4 bytes)
// Metadata: Count + array of ResourceEntry
// Data: Encrypted data block
class Pack {
public:
Pack() = default;
~Pack() = default;
@@ -48,7 +48,7 @@ class Pack {
auto getDataSize() const -> size_t { return data_.size(); }
auto calculatePackChecksum() const -> uint32_t; // Validation
private:
private:
static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'}; // Pack format constants
static constexpr uint32_t VERSION = 1;
static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024";
@@ -63,6 +63,6 @@ class Pack {
std::unordered_map<std::string, ResourceEntry> resources_; // Member variables
std::vector<uint8_t> data_; // Encrypted data block
bool loaded_{false};
};
};
} // namespace Resource

View File

@@ -15,48 +15,48 @@ struct JA_Sound_t;
// Estructura para almacenar ficheros de sonido y su nombre
struct SoundResource {
std::string name; // Nombre del sonido
JA_Sound_t* sound{nullptr}; // Objeto con el sonido
std::string name; // Nombre del sonido
JA_Sound_t* sound{nullptr}; // Objeto con el sonido
};
// Estructura para almacenar ficheros musicales y su nombre
struct MusicResource {
std::string name; // Nombre de la musica
JA_Music_t* music{nullptr}; // Objeto con la música
std::string name; // Nombre de la musica
JA_Music_t* music{nullptr}; // Objeto con la música
};
// Estructura para almacenar objetos Surface y su nombre
struct SurfaceResource {
std::string name; // Nombre de la surface
std::shared_ptr<Surface> surface; // Objeto con la surface
std::string name; // Nombre de la surface
std::shared_ptr<Surface> surface; // Objeto con la surface
};
// Estructura para almacenar objetos Palette y su nombre
struct ResourcePalette {
std::string name; // Nombre de la surface
Palette palette{}; // Paleta
std::string name; // Nombre de la surface
Palette palette{}; // Paleta
};
// Estructura para almacenar ficheros TextFile y su nombre
struct TextFileResource {
std::string name; // Nombre del fichero
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto
std::string name; // Nombre del fichero
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto
};
// Estructura para almacenar objetos Text y su nombre
struct TextResource {
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto
std::string name; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto
};
// Estructura para almacenar ficheros animaciones y su nombre
struct AnimationResource {
std::string name; // Nombre del fichero
std::vector<uint8_t> yaml_data; // Bytes del archivo YAML sin parsear
std::string name; // Nombre del fichero
std::vector<uint8_t> yaml_data; // Bytes del archivo YAML sin parsear
};
// Estructura para almacenar habitaciones y su nombre
struct RoomResource {
std::string name; // Nombre de la habitación
std::shared_ptr<Room::Data> room; // Habitación
std::string name; // Nombre de la habitación
std::shared_ptr<Room::Data> room; // Habitación
};

View File

@@ -9,36 +9,36 @@
// Clase Debug
class Debug {
public:
static void init(); // [SINGLETON] Crearemos el objeto con esta función estática
static void destroy(); // [SINGLETON] Destruiremos el objeto con esta función estática
static auto get() -> Debug*; // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
public:
static void init(); // [SINGLETON] Crearemos el objeto con esta función estática
static void destroy(); // [SINGLETON] Destruiremos el objeto con esta función estática
static auto get() -> Debug*; // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
void render(); // Dibuja en pantalla
void render(); // Dibuja en pantalla
void setPos(SDL_FPoint p); // Establece la posición donde se colocará la información de debug
void setPos(SDL_FPoint p); // Establece la posición donde se colocará la información de debug
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; } // Obtiene si el debug está activo
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; } // Obtiene si el debug está activo
void add(const std::string& text) { slot_.push_back(text); } // Añade texto al slot de debug
void clear() { slot_.clear(); } // Limpia el slot de debug
void addToLog(const std::string& text) { log_.push_back(text); } // Añade texto al log
void clearLog() { log_.clear(); } // Limpia el log
void setEnabled(bool value) { enabled_ = value; } // Establece si el debug está activo
void toggleEnabled() { enabled_ = !enabled_; } // Alterna el estado del debug
void add(const std::string& text) { slot_.push_back(text); } // Añade texto al slot de debug
void clear() { slot_.clear(); } // Limpia el slot de debug
void addToLog(const std::string& text) { log_.push_back(text); } // Añade texto al log
void clearLog() { log_.clear(); } // Limpia el log
void setEnabled(bool value) { enabled_ = value; } // Establece si el debug está activo
void toggleEnabled() { enabled_ = !enabled_; } // Alterna el estado del debug
private:
static Debug* debug; // [SINGLETON] Objeto privado
private:
static Debug* debug; // [SINGLETON] Objeto privado
Debug() = default; // Constructor
~Debug() = default; // Destructor
Debug() = default; // Constructor
~Debug() = default; // Destructor
// Variables
std::vector<std::string> slot_; // Vector con los textos a escribir
std::vector<std::string> log_; // Vector con los textos a escribir
int x_ = 0; // Posicion donde escribir el texto de debug
int y_ = 0; // Posición donde escribir el texto de debug
bool enabled_ = false; // Indica si esta activo el modo debug
// Variables
std::vector<std::string> slot_; // Vector con los textos a escribir
std::vector<std::string> log_; // Vector con los textos a escribir
int x_ = 0; // Posicion donde escribir el texto de debug
int y_ = 0; // Posición donde escribir el texto de debug
bool enabled_ = false; // Indica si esta activo el modo debug
};
#endif // _DEBUG

View File

@@ -6,27 +6,27 @@
#include <vector> // Para vector
class Director {
public:
explicit Director(std::vector<std::string> const& args); // Constructor
~Director(); // Destructor
static auto run() -> int; // Bucle principal
public:
explicit Director(std::vector<std::string> const& args); // Constructor
~Director(); // Destructor
static auto run() -> int; // Bucle principal
private:
// --- Variables ---
std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos
static auto checkProgramArguments(std::vector<std::string> const& args) -> std::string; // Comprueba los parametros del programa
private:
// --- Variables ---
std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos
static auto checkProgramArguments(std::vector<std::string> const& args) -> std::string; // Comprueba los parametros del programa
// --- Funciones ---
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
void setFileList(); // Carga la configuración de assets desde assets.yaml
static void runLogo(); // Ejecuta la seccion de juego con el logo
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
static void runTitle(); // Ejecuta la seccion de juego con el titulo y los menus
static void runCredits(); // Ejecuta la seccion de los creditos del juego
static void runDemo(); // Ejecuta la seccion de la demo, donde se ven pantallas del juego
static void runEnding(); // Ejecuta la seccion del final del juego
static void runEnding2(); // Ejecuta la seccion del final del juego
static void runGameOver(); // Ejecuta la seccion del final de la partida
static void runGame(); // Ejecuta la seccion de juego donde se juega
// --- Funciones ---
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
void setFileList(); // Carga la configuración de assets desde assets.yaml
static void runLogo(); // Ejecuta la seccion de juego con el logo
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
static void runTitle(); // Ejecuta la seccion de juego con el titulo y los menus
static void runCredits(); // Ejecuta la seccion de los creditos del juego
static void runDemo(); // Ejecuta la seccion de la demo, donde se ven pantallas del juego
static void runEnding(); // Ejecuta la seccion del final del juego
static void runEnding2(); // Ejecuta la seccion del final del juego
static void runGameOver(); // Ejecuta la seccion del final de la partida
static void runGame(); // Ejecuta la seccion de juego donde se juega
};

View File

@@ -5,18 +5,18 @@
#include "game/scene_manager.hpp" // Para SceneManager
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void handle(const SDL_Event& event) {
// Evento de salida de la aplicación
if (event.type == SDL_EVENT_QUIT) {
SceneManager::current = SceneManager::Scene::QUIT;
return;
}
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void handle(const SDL_Event& event) {
// Evento de salida de la aplicación
if (event.type == SDL_EVENT_QUIT) {
SceneManager::current = SceneManager::Scene::QUIT;
return;
}
if (event.type == SDL_EVENT_RENDER_DEVICE_RESET || event.type == SDL_EVENT_RENDER_TARGETS_RESET) {
// reLoadTextures();
}
if (event.type == SDL_EVENT_RENDER_DEVICE_RESET || event.type == SDL_EVENT_RENDER_TARGETS_RESET) {
// reLoadTextures();
}
Mouse::handleEvent(event);
}
Mouse::handleEvent(event);
}
} // namespace GlobalEvents

View File

@@ -3,6 +3,6 @@
#include <SDL3/SDL.h>
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void handle(const SDL_Event& event);
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void handle(const SDL_Event& event);
} // namespace GlobalEvents