primer commit
This commit is contained in:
183
source/core/audio/audio.cpp
Normal file
183
source/core/audio/audio.cpp
Normal file
@@ -0,0 +1,183 @@
|
||||
#include "audio.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_G...
|
||||
|
||||
#include <algorithm> // Para clamp
|
||||
#include <iostream> // Para std::cout
|
||||
|
||||
// Implementación de stb_vorbis (debe estar ANTES de incluir jail_audio.hpp)
|
||||
// clang-format off
|
||||
#undef STB_VORBIS_HEADER_ONLY
|
||||
#include "external/stb_vorbis.h"
|
||||
// clang-format on
|
||||
|
||||
#include "core/audio/jail_audio.hpp" // Para JA_FadeOutMusic, JA_Init, JA_PauseM...
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "game/options.hpp" // Para AudioOptions, audio, MusicOptions
|
||||
|
||||
// Singleton
|
||||
Audio* Audio::instance = nullptr;
|
||||
|
||||
// Inicializa la instancia única del singleton
|
||||
void Audio::init() { Audio::instance = new Audio(); }
|
||||
|
||||
// Libera la instancia
|
||||
void Audio::destroy() { delete Audio::instance; }
|
||||
|
||||
// Obtiene la instancia
|
||||
auto Audio::get() -> Audio* { return Audio::instance; }
|
||||
|
||||
// Constructor
|
||||
Audio::Audio() { initSDLAudio(); }
|
||||
|
||||
// Destructor
|
||||
Audio::~Audio() {
|
||||
JA_Quit();
|
||||
}
|
||||
|
||||
// Método principal
|
||||
void Audio::update() {
|
||||
JA_Update();
|
||||
}
|
||||
|
||||
// Reproduce la música
|
||||
void Audio::playMusic(const std::string& name, const int loop) {
|
||||
bool new_loop = (loop != 0);
|
||||
|
||||
// Si ya está sonando exactamente la misma pista y mismo modo loop, no hacemos nada
|
||||
if (music_.state == MusicState::PLAYING && music_.name == name && music_.loop == new_loop) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Intentar obtener recurso; si falla, no tocar estado
|
||||
auto* resource = Resource::Cache::get()->getMusic(name);
|
||||
if (resource == nullptr) {
|
||||
// manejo de error opcional
|
||||
return;
|
||||
}
|
||||
|
||||
// Si hay algo reproduciéndose, detenerlo primero (si el backend lo requiere)
|
||||
if (music_.state == MusicState::PLAYING) {
|
||||
JA_StopMusic(); // sustituir por la función de stop real del API si tiene otro nombre
|
||||
}
|
||||
|
||||
// Llamada al motor para reproducir la nueva pista
|
||||
JA_PlayMusic(resource, loop);
|
||||
|
||||
// Actualizar estado y metadatos después de iniciar con éxito
|
||||
music_.name = name;
|
||||
music_.loop = new_loop;
|
||||
music_.state = MusicState::PLAYING;
|
||||
}
|
||||
|
||||
// Pausa la música
|
||||
void Audio::pauseMusic() {
|
||||
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
||||
JA_PauseMusic();
|
||||
music_.state = MusicState::PAUSED;
|
||||
}
|
||||
}
|
||||
|
||||
// Continua la música pausada
|
||||
void Audio::resumeMusic() {
|
||||
if (music_enabled_ && music_.state == MusicState::PAUSED) {
|
||||
JA_ResumeMusic();
|
||||
music_.state = MusicState::PLAYING;
|
||||
}
|
||||
}
|
||||
|
||||
// Detiene la música
|
||||
void Audio::stopMusic() {
|
||||
if (music_enabled_) {
|
||||
JA_StopMusic();
|
||||
music_.state = MusicState::STOPPED;
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduce un sonido por nombre
|
||||
void Audio::playSound(const std::string& name, Group group) const {
|
||||
if (sound_enabled_) {
|
||||
JA_PlaySound(Resource::Cache::get()->getSound(name), 0, static_cast<int>(group));
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduce un sonido por puntero directo
|
||||
void Audio::playSound(JA_Sound_t* sound, Group group) const {
|
||||
if (sound_enabled_) {
|
||||
JA_PlaySound(sound, 0, static_cast<int>(group));
|
||||
}
|
||||
}
|
||||
|
||||
// Detiene todos los sonidos
|
||||
void Audio::stopAllSounds() const {
|
||||
if (sound_enabled_) {
|
||||
JA_StopChannel(-1);
|
||||
}
|
||||
}
|
||||
|
||||
// Realiza un fundido de salida de la música
|
||||
void Audio::fadeOutMusic(int milliseconds) const {
|
||||
if (music_enabled_ && getRealMusicState() == MusicState::PLAYING) {
|
||||
JA_FadeOutMusic(milliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
// Consulta directamente el estado real de la música en jailaudio
|
||||
auto Audio::getRealMusicState() -> MusicState {
|
||||
JA_Music_state ja_state = JA_GetMusicState();
|
||||
switch (ja_state) {
|
||||
case JA_MUSIC_PLAYING:
|
||||
return MusicState::PLAYING;
|
||||
case JA_MUSIC_PAUSED:
|
||||
return MusicState::PAUSED;
|
||||
case JA_MUSIC_STOPPED:
|
||||
case JA_MUSIC_INVALID:
|
||||
case JA_MUSIC_DISABLED:
|
||||
default:
|
||||
return MusicState::STOPPED;
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el volumen de los sonidos
|
||||
void Audio::setSoundVolume(float sound_volume, Group group) const {
|
||||
if (sound_enabled_) {
|
||||
sound_volume = std::clamp(sound_volume, MIN_VOLUME, MAX_VOLUME);
|
||||
const float CONVERTED_VOLUME = sound_volume * Options::audio.volume;
|
||||
JA_SetSoundVolume(CONVERTED_VOLUME, static_cast<int>(group));
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el volumen de la música
|
||||
void Audio::setMusicVolume(float music_volume) const {
|
||||
if (music_enabled_) {
|
||||
music_volume = std::clamp(music_volume, MIN_VOLUME, MAX_VOLUME);
|
||||
const float CONVERTED_VOLUME = music_volume * Options::audio.volume;
|
||||
JA_SetMusicVolume(CONVERTED_VOLUME);
|
||||
}
|
||||
}
|
||||
|
||||
// Aplica la configuración
|
||||
void Audio::applySettings() {
|
||||
enable(Options::audio.enabled);
|
||||
}
|
||||
|
||||
// Establecer estado general
|
||||
void Audio::enable(bool value) {
|
||||
enabled_ = value;
|
||||
|
||||
setSoundVolume(enabled_ ? Options::audio.sound.volume : MIN_VOLUME);
|
||||
setMusicVolume(enabled_ ? Options::audio.music.volume : MIN_VOLUME);
|
||||
}
|
||||
|
||||
// Inicializa SDL Audio
|
||||
void Audio::initSDLAudio() {
|
||||
if (!SDL_Init(SDL_INIT_AUDIO)) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_AUDIO could not initialize! SDL Error: %s", SDL_GetError());
|
||||
} else {
|
||||
JA_Init(FREQUENCY, SDL_AUDIO_S16LE, 2);
|
||||
enable(Options::audio.enabled);
|
||||
|
||||
std::cout << "\n** AUDIO SYSTEM **\n";
|
||||
std::cout << "Audio system initialized successfully\n";
|
||||
}
|
||||
}
|
||||
97
source/core/audio/audio.hpp
Normal file
97
source/core/audio/audio.hpp
Normal file
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <string> // Para string
|
||||
#include <utility> // Para move
|
||||
|
||||
// --- 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
|
||||
};
|
||||
|
||||
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
|
||||
|
||||
// --- 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
|
||||
|
||||
// --- 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 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 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
|
||||
|
||||
// --- 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
|
||||
};
|
||||
|
||||
// --- Métodos ---
|
||||
Audio(); // Constructor privado
|
||||
~Audio(); // Destructor privado
|
||||
void initSDLAudio(); // Inicializa SDL 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
|
||||
};
|
||||
482
source/core/audio/jail_audio.hpp
Normal file
482
source/core/audio/jail_audio.hpp
Normal file
@@ -0,0 +1,482 @@
|
||||
#pragma once
|
||||
|
||||
// --- Includes ---
|
||||
#include <SDL3/SDL.h>
|
||||
#include <stdint.h> // Para uint32_t, uint8_t
|
||||
#include <stdio.h> // Para NULL, fseek, printf, fclose, fopen, fread, ftell, FILE, SEEK_END, SEEK_SET
|
||||
#include <stdlib.h> // Para free, malloc
|
||||
#include <string.h> // Para strcpy, strlen
|
||||
|
||||
#define STB_VORBIS_HEADER_ONLY
|
||||
#include "external/stb_vorbis.h" // Para stb_vorbis_decode_memory
|
||||
|
||||
// --- Public Enums ---
|
||||
enum JA_Channel_state { JA_CHANNEL_INVALID,
|
||||
JA_CHANNEL_FREE,
|
||||
JA_CHANNEL_PLAYING,
|
||||
JA_CHANNEL_PAUSED,
|
||||
JA_SOUND_DISABLED };
|
||||
enum JA_Music_state { JA_MUSIC_INVALID,
|
||||
JA_MUSIC_PLAYING,
|
||||
JA_MUSIC_PAUSED,
|
||||
JA_MUSIC_STOPPED,
|
||||
JA_MUSIC_DISABLED };
|
||||
|
||||
// --- Struct Definitions ---
|
||||
#define JA_MAX_SIMULTANEOUS_CHANNELS 20
|
||||
#define JA_MAX_GROUPS 2
|
||||
|
||||
struct JA_Sound_t {
|
||||
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};
|
||||
};
|
||||
|
||||
struct JA_Music_t {
|
||||
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};
|
||||
};
|
||||
|
||||
// --- Internal Global State ---
|
||||
// Marcado 'inline' (C++17) para asegurar una única instancia.
|
||||
|
||||
inline JA_Music_t* current_music{nullptr};
|
||||
inline JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
|
||||
|
||||
inline SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000};
|
||||
inline float JA_musicVolume{1.0f};
|
||||
inline float JA_soundVolume[JA_MAX_GROUPS];
|
||||
inline bool JA_musicEnabled{true};
|
||||
inline bool JA_soundEnabled{true};
|
||||
inline SDL_AudioDeviceID sdlAudioDevice{0};
|
||||
|
||||
inline bool fading{false};
|
||||
inline int fade_start_time{0};
|
||||
inline int fade_duration{0};
|
||||
inline float fade_initial_volume{0.0f}; // Corregido de 'int' a 'float'
|
||||
|
||||
// --- Forward Declarations ---
|
||||
inline void JA_StopMusic();
|
||||
inline void JA_StopChannel(const int channel);
|
||||
inline int JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop = 0, const int group = 0);
|
||||
|
||||
// --- Core Functions ---
|
||||
|
||||
inline void JA_Update() {
|
||||
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) {
|
||||
if (fading) {
|
||||
int time = SDL_GetTicks();
|
||||
if (time > (fade_start_time + fade_duration)) {
|
||||
fading = false;
|
||||
JA_StopMusic();
|
||||
return;
|
||||
} else {
|
||||
const int time_passed = time - fade_start_time;
|
||||
const float percent = (float)time_passed / (float)fade_duration;
|
||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume * (1.0 - percent));
|
||||
}
|
||||
}
|
||||
|
||||
if (current_music->times != 0) {
|
||||
if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length / 2)) {
|
||||
SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length);
|
||||
}
|
||||
if (current_music->times > 0) current_music->times--;
|
||||
} else {
|
||||
if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic();
|
||||
}
|
||||
}
|
||||
|
||||
if (JA_soundEnabled) {
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i)
|
||||
if (channels[i].state == JA_CHANNEL_PLAYING) {
|
||||
if (channels[i].times != 0) {
|
||||
if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length / 2)) {
|
||||
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length);
|
||||
if (channels[i].times > 0) channels[i].times--;
|
||||
}
|
||||
} else {
|
||||
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels) {
|
||||
#ifdef _DEBUG
|
||||
SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
|
||||
#endif
|
||||
|
||||
JA_audioSpec = {format, num_channels, freq};
|
||||
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); // Corregido: !sdlAudioDevice -> sdlAudioDevice
|
||||
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
|
||||
if (sdlAudioDevice == 0) SDL_Log("Failed to initialize SDL audio!");
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE;
|
||||
for (int i = 0; i < JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5f;
|
||||
}
|
||||
|
||||
inline void JA_Quit() {
|
||||
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); // Corregido: !sdlAudioDevice -> sdlAudioDevice
|
||||
sdlAudioDevice = 0;
|
||||
}
|
||||
|
||||
// --- Music Functions ---
|
||||
|
||||
inline JA_Music_t* JA_LoadMusic(const Uint8* buffer, Uint32 length) {
|
||||
JA_Music_t* music = new JA_Music_t();
|
||||
|
||||
int chan, samplerate;
|
||||
short* output;
|
||||
music->length = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &output) * chan * 2;
|
||||
|
||||
music->spec.channels = chan;
|
||||
music->spec.freq = samplerate;
|
||||
music->spec.format = SDL_AUDIO_S16;
|
||||
music->buffer = static_cast<Uint8*>(SDL_malloc(music->length));
|
||||
SDL_memcpy(music->buffer, output, music->length);
|
||||
free(output);
|
||||
music->pos = 0;
|
||||
music->state = JA_MUSIC_STOPPED;
|
||||
|
||||
return music;
|
||||
}
|
||||
|
||||
inline JA_Music_t* JA_LoadMusic(const char* filename) {
|
||||
// [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid.
|
||||
FILE* f = fopen(filename, "rb");
|
||||
if (!f) return NULL; // Añadida comprobación de apertura
|
||||
fseek(f, 0, SEEK_END);
|
||||
long fsize = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
auto* buffer = static_cast<Uint8*>(malloc(fsize + 1));
|
||||
if (!buffer) { // Añadida comprobación de malloc
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
if (fread(buffer, fsize, 1, f) != 1) {
|
||||
fclose(f);
|
||||
free(buffer);
|
||||
return NULL;
|
||||
}
|
||||
fclose(f);
|
||||
|
||||
JA_Music_t* music = JA_LoadMusic(buffer, fsize);
|
||||
if (music) { // Comprobar que JA_LoadMusic tuvo éxito
|
||||
music->filename = static_cast<char*>(malloc(strlen(filename) + 1));
|
||||
if (music->filename) {
|
||||
strcpy(music->filename, filename);
|
||||
}
|
||||
}
|
||||
|
||||
free(buffer);
|
||||
|
||||
return music;
|
||||
}
|
||||
|
||||
inline void JA_PlayMusic(JA_Music_t* music, const int loop = -1) {
|
||||
if (!JA_musicEnabled || !music) return; // Añadida comprobación de music
|
||||
|
||||
JA_StopMusic();
|
||||
|
||||
current_music = music;
|
||||
current_music->pos = 0;
|
||||
current_music->state = JA_MUSIC_PLAYING;
|
||||
current_music->times = loop;
|
||||
|
||||
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec);
|
||||
if (!current_music->stream) { // Comprobar creación de stream
|
||||
SDL_Log("Failed to create audio stream!");
|
||||
current_music->state = JA_MUSIC_STOPPED;
|
||||
return;
|
||||
}
|
||||
if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n");
|
||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
||||
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n");
|
||||
}
|
||||
|
||||
inline char* JA_GetMusicFilename(const JA_Music_t* music = nullptr) {
|
||||
if (!music) music = current_music;
|
||||
if (!music) return nullptr; // Añadida comprobación
|
||||
return music->filename;
|
||||
}
|
||||
|
||||
inline void JA_PauseMusic() {
|
||||
if (!JA_musicEnabled) return;
|
||||
if (!current_music || current_music->state != JA_MUSIC_PLAYING) return; // Comprobación mejorada
|
||||
|
||||
current_music->state = JA_MUSIC_PAUSED;
|
||||
SDL_UnbindAudioStream(current_music->stream);
|
||||
}
|
||||
|
||||
inline void JA_ResumeMusic() {
|
||||
if (!JA_musicEnabled) return;
|
||||
if (!current_music || current_music->state != JA_MUSIC_PAUSED) return; // Comprobación mejorada
|
||||
|
||||
current_music->state = JA_MUSIC_PLAYING;
|
||||
SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
|
||||
}
|
||||
|
||||
inline void JA_StopMusic() {
|
||||
if (!current_music || current_music->state == JA_MUSIC_INVALID || current_music->state == JA_MUSIC_STOPPED) return;
|
||||
|
||||
current_music->pos = 0;
|
||||
current_music->state = JA_MUSIC_STOPPED;
|
||||
if (current_music->stream) {
|
||||
SDL_DestroyAudioStream(current_music->stream);
|
||||
current_music->stream = nullptr;
|
||||
}
|
||||
// No liberamos filename aquí, se debería liberar en JA_DeleteMusic
|
||||
}
|
||||
|
||||
inline void JA_FadeOutMusic(const int milliseconds) {
|
||||
if (!JA_musicEnabled) return;
|
||||
if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return;
|
||||
|
||||
fading = true;
|
||||
fade_start_time = SDL_GetTicks();
|
||||
fade_duration = milliseconds;
|
||||
fade_initial_volume = JA_musicVolume;
|
||||
}
|
||||
|
||||
inline JA_Music_state JA_GetMusicState() {
|
||||
if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
|
||||
if (!current_music) return JA_MUSIC_INVALID;
|
||||
|
||||
return current_music->state;
|
||||
}
|
||||
|
||||
inline void JA_DeleteMusic(JA_Music_t* music) {
|
||||
if (!music) return;
|
||||
if (current_music == music) {
|
||||
JA_StopMusic();
|
||||
current_music = nullptr;
|
||||
}
|
||||
SDL_free(music->buffer);
|
||||
if (music->stream) SDL_DestroyAudioStream(music->stream);
|
||||
free(music->filename); // filename se libera aquí
|
||||
delete music;
|
||||
}
|
||||
|
||||
inline float JA_SetMusicVolume(float volume) {
|
||||
JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f);
|
||||
if (current_music && current_music->stream) {
|
||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
||||
}
|
||||
return JA_musicVolume;
|
||||
}
|
||||
|
||||
inline void JA_SetMusicPosition(float value) {
|
||||
if (!current_music) return;
|
||||
current_music->pos = value * current_music->spec.freq;
|
||||
// Nota: Esta implementación de 'pos' no parece usarse en JA_Update para
|
||||
// el streaming. El streaming siempre parece empezar desde el principio.
|
||||
}
|
||||
|
||||
inline float JA_GetMusicPosition() {
|
||||
if (!current_music) return 0;
|
||||
return float(current_music->pos) / float(current_music->spec.freq);
|
||||
// Nota: Ver `JA_SetMusicPosition`
|
||||
}
|
||||
|
||||
inline void JA_EnableMusic(const bool value) {
|
||||
if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) JA_StopMusic();
|
||||
|
||||
JA_musicEnabled = value;
|
||||
}
|
||||
|
||||
// --- Sound Functions ---
|
||||
|
||||
inline JA_Sound_t* JA_NewSound(Uint8* buffer, Uint32 length) {
|
||||
JA_Sound_t* sound = new JA_Sound_t();
|
||||
sound->buffer = buffer;
|
||||
sound->length = length;
|
||||
// Nota: spec se queda con los valores por defecto.
|
||||
return sound;
|
||||
}
|
||||
|
||||
inline JA_Sound_t* JA_LoadSound(uint8_t* buffer, uint32_t size) {
|
||||
JA_Sound_t* sound = new JA_Sound_t();
|
||||
if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length)) {
|
||||
SDL_Log("Failed to load WAV from memory: %s", SDL_GetError());
|
||||
delete sound;
|
||||
return nullptr;
|
||||
}
|
||||
return sound;
|
||||
}
|
||||
|
||||
inline JA_Sound_t* JA_LoadSound(const char* filename) {
|
||||
JA_Sound_t* sound = new JA_Sound_t();
|
||||
if (!SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length)) {
|
||||
SDL_Log("Failed to load WAV file: %s", SDL_GetError());
|
||||
delete sound;
|
||||
return nullptr;
|
||||
}
|
||||
return sound;
|
||||
}
|
||||
|
||||
inline int JA_PlaySound(JA_Sound_t* sound, const int loop = 0, const int group = 0) {
|
||||
if (!JA_soundEnabled || !sound) return -1;
|
||||
|
||||
int channel = 0;
|
||||
while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; }
|
||||
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||
// No hay canal libre, reemplazamos el primero
|
||||
channel = 0;
|
||||
}
|
||||
|
||||
return JA_PlaySoundOnChannel(sound, channel, loop, group);
|
||||
}
|
||||
|
||||
inline int JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop, const int group) {
|
||||
if (!JA_soundEnabled || !sound) return -1;
|
||||
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1;
|
||||
|
||||
JA_StopChannel(channel); // Detiene y limpia el canal si estaba en uso
|
||||
|
||||
channels[channel].sound = sound;
|
||||
channels[channel].times = loop;
|
||||
channels[channel].pos = 0;
|
||||
channels[channel].group = group; // Asignar grupo
|
||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
||||
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec);
|
||||
|
||||
if (!channels[channel].stream) {
|
||||
SDL_Log("Failed to create audio stream for sound!");
|
||||
channels[channel].state = JA_CHANNEL_FREE;
|
||||
return -1;
|
||||
}
|
||||
|
||||
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer, channels[channel].sound->length);
|
||||
SDL_SetAudioStreamGain(channels[channel].stream, JA_soundVolume[group]);
|
||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
inline void JA_DeleteSound(JA_Sound_t* sound) {
|
||||
if (!sound) return;
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||
if (channels[i].sound == sound) JA_StopChannel(i);
|
||||
}
|
||||
SDL_free(sound->buffer);
|
||||
delete sound;
|
||||
}
|
||||
|
||||
inline void JA_PauseChannel(const int channel) {
|
||||
if (!JA_soundEnabled) return;
|
||||
|
||||
if (channel == -1) {
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
||||
if (channels[i].state == JA_CHANNEL_PLAYING) {
|
||||
channels[i].state = JA_CHANNEL_PAUSED;
|
||||
SDL_UnbindAudioStream(channels[i].stream);
|
||||
}
|
||||
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||
if (channels[channel].state == JA_CHANNEL_PLAYING) {
|
||||
channels[channel].state = JA_CHANNEL_PAUSED;
|
||||
SDL_UnbindAudioStream(channels[channel].stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void JA_ResumeChannel(const int channel) {
|
||||
if (!JA_soundEnabled) return;
|
||||
|
||||
if (channel == -1) {
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
||||
if (channels[i].state == JA_CHANNEL_PAUSED) {
|
||||
channels[i].state = JA_CHANNEL_PLAYING;
|
||||
SDL_BindAudioStream(sdlAudioDevice, channels[i].stream);
|
||||
}
|
||||
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||
if (channels[channel].state == JA_CHANNEL_PAUSED) {
|
||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void JA_StopChannel(const int channel) {
|
||||
if (channel == -1) {
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||
if (channels[i].state != JA_CHANNEL_FREE) {
|
||||
if (channels[i].stream) SDL_DestroyAudioStream(channels[i].stream);
|
||||
channels[i].stream = nullptr;
|
||||
channels[i].state = JA_CHANNEL_FREE;
|
||||
channels[i].pos = 0;
|
||||
channels[i].sound = NULL;
|
||||
}
|
||||
}
|
||||
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||
if (channels[channel].state != JA_CHANNEL_FREE) {
|
||||
if (channels[channel].stream) SDL_DestroyAudioStream(channels[channel].stream);
|
||||
channels[channel].stream = nullptr;
|
||||
channels[channel].state = JA_CHANNEL_FREE;
|
||||
channels[channel].pos = 0;
|
||||
channels[channel].sound = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline JA_Channel_state JA_GetChannelState(const int channel) {
|
||||
if (!JA_soundEnabled) return JA_SOUND_DISABLED;
|
||||
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID;
|
||||
|
||||
return channels[channel].state;
|
||||
}
|
||||
|
||||
inline float JA_SetSoundVolume(float volume, const int group = -1) // -1 para todos los grupos
|
||||
{
|
||||
const float v = SDL_clamp(volume, 0.0f, 1.0f);
|
||||
|
||||
if (group == -1) {
|
||||
for (int i = 0; i < JA_MAX_GROUPS; ++i) {
|
||||
JA_soundVolume[i] = v;
|
||||
}
|
||||
} else if (group >= 0 && group < JA_MAX_GROUPS) {
|
||||
JA_soundVolume[group] = v;
|
||||
} else {
|
||||
return v; // Grupo inválido
|
||||
}
|
||||
|
||||
// Aplicar volumen a canales activos
|
||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||
if ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) {
|
||||
if (group == -1 || channels[i].group == group) {
|
||||
if (channels[i].stream) {
|
||||
SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[channels[i].group]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
inline void JA_EnableSound(const bool value) {
|
||||
if (!value) {
|
||||
JA_StopChannel(-1); // Detener todos los canales
|
||||
}
|
||||
JA_soundEnabled = value;
|
||||
}
|
||||
|
||||
inline float JA_SetVolume(float volume) {
|
||||
float v = JA_SetMusicVolume(volume);
|
||||
JA_SetSoundVolume(v, -1); // Aplicar a todos los grupos de sonido
|
||||
return v;
|
||||
}
|
||||
230
source/core/input/global_inputs.cpp
Normal file
230
source/core/input/global_inputs.cpp
Normal file
@@ -0,0 +1,230 @@
|
||||
#include "core/input/global_inputs.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string> // Para allocator, operator+, char_traits, string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
|
||||
#include "game/scene_manager.hpp" // Para SceneManager
|
||||
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText
|
||||
#include "utils/utils.hpp" // Para stringInVector
|
||||
|
||||
#ifdef _DEBUG
|
||||
#include "core/system/debug.hpp" // Para Debug
|
||||
#endif
|
||||
|
||||
namespace GlobalInputs {
|
||||
|
||||
// Funciones internas
|
||||
namespace {
|
||||
void handleQuit() {
|
||||
const std::string CODE = SceneManager::current == SceneManager::Scene::GAME ? "PRESS AGAIN TO RETURN TO MENU" : "PRESS AGAIN TO EXIT";
|
||||
auto code_found = stringInVector(Notifier::get()->getCodes(), CODE);
|
||||
if (code_found) {
|
||||
// Si la notificación de salir está activa, cambia de sección
|
||||
switch (SceneManager::current) {
|
||||
case SceneManager::Scene::GAME:
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
break;
|
||||
default:
|
||||
SceneManager::current = SceneManager::Scene::QUIT;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Si la notificación de salir no está activa, muestra la notificación
|
||||
Notifier::get()->show({CODE}, Notifier::Style::DEFAULT, -1, true, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
void handleSkipSection() {
|
||||
switch (SceneManager::current) {
|
||||
case SceneManager::Scene::LOGO:
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void handleToggleBorder() {
|
||||
Screen::get()->toggleBorder();
|
||||
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")});
|
||||
}
|
||||
|
||||
void handleToggleVideoMode() {
|
||||
Screen::get()->toggleVideoMode();
|
||||
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")});
|
||||
}
|
||||
|
||||
void handleDecWindowZoom() {
|
||||
if (Screen::get()->decWindowZoom()) {
|
||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)});
|
||||
}
|
||||
}
|
||||
|
||||
void handleIncWindowZoom() {
|
||||
if (Screen::get()->incWindowZoom()) {
|
||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)});
|
||||
}
|
||||
}
|
||||
|
||||
void handleToggleShaders() {
|
||||
Screen::get()->toggleShaders();
|
||||
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "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")});
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
void handleShowDebugInfo() {
|
||||
Screen::get()->toggleDebugInfo();
|
||||
}
|
||||
|
||||
/*
|
||||
void handleToggleDebug() {
|
||||
Debug::get()->toggleEnabled();
|
||||
Notifier::get()->show({"DEBUG " + std::string(Debug::get()->isEnabled() ? "ENABLED" : "DISABLED")}, Notifier::TextAlign::CENTER);
|
||||
}
|
||||
*/
|
||||
#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 (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_SHADERS, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
return InputAction::TOGGLE_SHADERS;
|
||||
}
|
||||
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
|
||||
|
||||
// Funciones públicas
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
void handle() {
|
||||
// Detectar qué acción global está siendo presionada
|
||||
InputAction action = getPressedAction();
|
||||
|
||||
// Ejecutar el handler correspondiente usando switch statement
|
||||
switch (action) {
|
||||
case InputAction::EXIT:
|
||||
handleQuit();
|
||||
break;
|
||||
|
||||
case InputAction::ACCEPT:
|
||||
handleSkipSection();
|
||||
break;
|
||||
|
||||
case InputAction::TOGGLE_BORDER:
|
||||
handleToggleBorder();
|
||||
break;
|
||||
|
||||
case InputAction::TOGGLE_FULLSCREEN:
|
||||
handleToggleVideoMode();
|
||||
break;
|
||||
|
||||
case InputAction::WINDOW_DEC_ZOOM:
|
||||
handleDecWindowZoom();
|
||||
break;
|
||||
|
||||
case InputAction::WINDOW_INC_ZOOM:
|
||||
handleIncWindowZoom();
|
||||
break;
|
||||
|
||||
case InputAction::TOGGLE_SHADERS:
|
||||
handleToggleShaders();
|
||||
break;
|
||||
|
||||
case InputAction::NEXT_PALETTE:
|
||||
handleNextPalette();
|
||||
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;
|
||||
|
||||
#ifdef _DEBUG
|
||||
case InputAction::SHOW_DEBUG_INFO:
|
||||
handleShowDebugInfo();
|
||||
break;
|
||||
#endif
|
||||
|
||||
case InputAction::NONE:
|
||||
default:
|
||||
// No se presionó ninguna acción global
|
||||
break;
|
||||
}
|
||||
}
|
||||
} // namespace GlobalInputs
|
||||
6
source/core/input/global_inputs.hpp
Normal file
6
source/core/input/global_inputs.hpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
namespace GlobalInputs {
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
void handle();
|
||||
} // namespace GlobalInputs
|
||||
477
source/core/input/input.cpp
Normal file
477
source/core/input/input.cpp
Normal file
@@ -0,0 +1,477 @@
|
||||
#include "core/input/input.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetGamepadAxis, SDL_GamepadAxis, SDL_GamepadButton, SDL_GetError, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogError, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, Sint16, SDL_Gamepad, SDL_LogCategory, SDL_Scancode
|
||||
|
||||
#include <iostream> // Para basic_ostream, operator<<, cout, cerr
|
||||
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
|
||||
#include <ranges> // Para __find_if_fn, find_if
|
||||
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
|
||||
#include <utility> // Para pair, move
|
||||
|
||||
#include "game/options.hpp" // Para Options::controls
|
||||
|
||||
// Singleton
|
||||
Input* Input::instance = nullptr;
|
||||
|
||||
// Inicializa la instancia única del singleton
|
||||
void Input::init(const std::string& game_controller_db_path) {
|
||||
Input::instance = new Input(game_controller_db_path);
|
||||
}
|
||||
|
||||
// Libera la instancia
|
||||
void Input::destroy() { delete Input::instance; }
|
||||
|
||||
// Obtiene la instancia
|
||||
auto Input::get() -> Input* { return Input::instance; }
|
||||
|
||||
// Constructor
|
||||
Input::Input(std::string game_controller_db_path)
|
||||
: gamepad_mappings_file_(std::move(game_controller_db_path)) {
|
||||
// Inicializar bindings del teclado
|
||||
keyboard_.bindings = {
|
||||
// Movimiento del jugador
|
||||
{Action::LEFT, KeyState{.scancode = SDL_SCANCODE_LEFT}},
|
||||
{Action::RIGHT, KeyState{.scancode = SDL_SCANCODE_RIGHT}},
|
||||
{Action::JUMP, KeyState{.scancode = SDL_SCANCODE_UP}},
|
||||
|
||||
// Inputs de control
|
||||
{Action::ACCEPT, KeyState{.scancode = SDL_SCANCODE_RETURN}},
|
||||
{Action::CANCEL, KeyState{.scancode = SDL_SCANCODE_ESCAPE}},
|
||||
{Action::EXIT, KeyState{.scancode = SDL_SCANCODE_ESCAPE}},
|
||||
|
||||
// Inputs de sistema
|
||||
{Action::WINDOW_DEC_ZOOM, KeyState{.scancode = SDL_SCANCODE_F1}},
|
||||
{Action::WINDOW_INC_ZOOM, KeyState{.scancode = SDL_SCANCODE_F2}},
|
||||
{Action::TOGGLE_FULLSCREEN, KeyState{.scancode = SDL_SCANCODE_F3}},
|
||||
{Action::TOGGLE_SHADERS, KeyState{.scancode = SDL_SCANCODE_F4}},
|
||||
{Action::NEXT_PALETTE, KeyState{.scancode = SDL_SCANCODE_F5}},
|
||||
{Action::PREVIOUS_PALETTE, KeyState{.scancode = SDL_SCANCODE_F6}},
|
||||
{Action::TOGGLE_INTEGER_SCALE, KeyState{.scancode = SDL_SCANCODE_F7}},
|
||||
{Action::TOGGLE_MUSIC, KeyState{.scancode = SDL_SCANCODE_F8}},
|
||||
{Action::TOGGLE_BORDER, KeyState{.scancode = SDL_SCANCODE_F9}},
|
||||
{Action::TOGGLE_VSYNC, KeyState{.scancode = SDL_SCANCODE_F10}},
|
||||
{Action::PAUSE, KeyState{.scancode = SDL_SCANCODE_F11}},
|
||||
{Action::TOGGLE_DEBUG, KeyState{.scancode = SDL_SCANCODE_F12}}};
|
||||
|
||||
initSDLGamePad(); // Inicializa el subsistema SDL_INIT_GAMEPAD
|
||||
}
|
||||
|
||||
// Asigna inputs a teclas
|
||||
void Input::bindKey(Action action, SDL_Scancode code) {
|
||||
keyboard_.bindings[action].scancode = code;
|
||||
}
|
||||
|
||||
// Aplica las teclas configuradas desde Options
|
||||
void Input::applyKeyboardBindingsFromOptions() {
|
||||
bindKey(Action::LEFT, Options::keyboard_controls.key_left);
|
||||
bindKey(Action::RIGHT, Options::keyboard_controls.key_right);
|
||||
bindKey(Action::JUMP, Options::keyboard_controls.key_jump);
|
||||
}
|
||||
|
||||
// Aplica configuración de botones del gamepad desde Options al primer gamepad conectado
|
||||
void Input::applyGamepadBindingsFromOptions() {
|
||||
// Si no hay gamepads conectados, no hay nada que hacer
|
||||
if (gamepads_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Obtener el primer gamepad conectado
|
||||
const auto& gamepad = gamepads_[0];
|
||||
|
||||
// Aplicar bindings desde Options
|
||||
// Los valores pueden ser:
|
||||
// - 0-20+: Botones SDL_GamepadButton (DPAD, face buttons, shoulders)
|
||||
// - 100: L2 trigger
|
||||
// - 101: R2 trigger
|
||||
// - 200+: Ejes del stick analógico
|
||||
gamepad->bindings[Action::LEFT].button = Options::gamepad_controls.button_left;
|
||||
gamepad->bindings[Action::RIGHT].button = Options::gamepad_controls.button_right;
|
||||
gamepad->bindings[Action::JUMP].button = Options::gamepad_controls.button_jump;
|
||||
}
|
||||
|
||||
// Asigna inputs a botones del mando
|
||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button) {
|
||||
if (gamepad != nullptr) {
|
||||
gamepad->bindings[action].button = button;
|
||||
}
|
||||
}
|
||||
|
||||
// Asigna inputs a botones del mando
|
||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source) {
|
||||
if (gamepad != nullptr) {
|
||||
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si alguna acción está activa
|
||||
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||
bool success_keyboard = false;
|
||||
bool success_controller = false;
|
||||
|
||||
if (check_keyboard) {
|
||||
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||
success_keyboard = keyboard_.bindings[action].is_held;
|
||||
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||
success_keyboard = keyboard_.bindings[action].just_pressed;
|
||||
}
|
||||
}
|
||||
|
||||
// Si gamepad es nullptr pero hay mandos conectados, usar el primero
|
||||
std::shared_ptr<Gamepad> active_gamepad = gamepad;
|
||||
if (active_gamepad == nullptr && !gamepads_.empty()) {
|
||||
active_gamepad = gamepads_[0];
|
||||
}
|
||||
|
||||
if (active_gamepad != nullptr) {
|
||||
success_controller = checkAxisInput(action, active_gamepad, repeat);
|
||||
|
||||
if (!success_controller) {
|
||||
success_controller = checkTriggerInput(action, active_gamepad, repeat);
|
||||
}
|
||||
|
||||
if (!success_controller) {
|
||||
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||
success_controller = active_gamepad->bindings[action].is_held;
|
||||
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||
success_controller = active_gamepad->bindings[action].just_pressed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (success_keyboard || success_controller);
|
||||
}
|
||||
|
||||
// Comprueba si hay almenos una acción activa
|
||||
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
||||
|
||||
// --- Comprobación del Teclado ---
|
||||
if (check_keyboard) {
|
||||
for (const auto& pair : keyboard_.bindings) {
|
||||
// Simplemente leemos el estado pre-calculado por Input::update().
|
||||
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
|
||||
if (pair.second.just_pressed) {
|
||||
return true; // Se encontró una acción recién pulsada.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si gamepad es nullptr pero hay mandos conectados, usar el primero
|
||||
std::shared_ptr<Gamepad> active_gamepad = gamepad;
|
||||
if (active_gamepad == nullptr && !gamepads_.empty()) {
|
||||
active_gamepad = gamepads_[0];
|
||||
}
|
||||
|
||||
// --- Comprobación del Mando ---
|
||||
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
||||
if (active_gamepad != nullptr) {
|
||||
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
||||
for (const auto& pair : active_gamepad->bindings) {
|
||||
// Leemos el estado pre-calculado para el mando y la acción específicos.
|
||||
if (pair.second.just_pressed) {
|
||||
return true; // Se encontró una acción recién pulsada en el mando.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si hay algún botón pulsado
|
||||
auto Input::checkAnyButton(bool repeat) -> bool {
|
||||
// Solo comprueba los botones definidos previamente
|
||||
for (auto bi : BUTTON_INPUTS) {
|
||||
// Comprueba el teclado
|
||||
if (checkAction(bi, repeat, CHECK_KEYBOARD)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Comprueba los mandos
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si hay algun mando conectado
|
||||
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
|
||||
|
||||
// Obten el nombre de un mando de juego
|
||||
auto Input::getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string {
|
||||
return gamepad == nullptr ? std::string() : gamepad->name;
|
||||
}
|
||||
|
||||
// Obtiene la lista de nombres de mandos
|
||||
auto Input::getControllerNames() const -> std::vector<std::string> {
|
||||
std::vector<std::string> names;
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
names.push_back(gamepad->name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
// Obten el número de mandos conectados
|
||||
auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
|
||||
|
||||
// Obtiene el gamepad a partir de un event.id
|
||||
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (gamepad->instance_id == id) {
|
||||
return gamepad;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (gamepad && gamepad->name == name) {
|
||||
return gamepad;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Obtiene el SDL_GamepadButton asignado a un action
|
||||
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
|
||||
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
|
||||
}
|
||||
|
||||
// Comprueba el eje del mando
|
||||
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||
// Obtener el binding configurado para esta acción
|
||||
auto& binding = gamepad->bindings[action];
|
||||
|
||||
// Solo revisar ejes si el binding está configurado como eje (valores 200+)
|
||||
// 200 = Left stick izquierda, 201 = Left stick derecha
|
||||
if (binding.button < 200) {
|
||||
// El binding no es un eje, no revisar axis
|
||||
return false;
|
||||
}
|
||||
|
||||
// Determinar qué eje y dirección revisar según el binding
|
||||
bool axis_active_now = false;
|
||||
|
||||
if (binding.button == 200) {
|
||||
// Left stick izquierda
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
||||
} else if (binding.button == 201) {
|
||||
// Left stick derecha
|
||||
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
||||
} else {
|
||||
// Binding de eje no soportado
|
||||
return false;
|
||||
}
|
||||
|
||||
if (repeat) {
|
||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||
return axis_active_now;
|
||||
} // Si no se permite repetir, aplicamos la lógica de transición
|
||||
if (axis_active_now && !binding.axis_active) {
|
||||
// Transición de inactivo a activo
|
||||
binding.axis_active = true;
|
||||
return true;
|
||||
}
|
||||
if (!axis_active_now && binding.axis_active) {
|
||||
// Transición de activo a inactivo
|
||||
binding.axis_active = false;
|
||||
}
|
||||
// Mantener el estado actual
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba los triggers del mando como botones digitales
|
||||
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||
// Solo manejamos botones específicos que pueden ser triggers
|
||||
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
|
||||
// Solo procesamos L2 y R2 como triggers
|
||||
int button = gamepad->bindings[action].button;
|
||||
|
||||
// Verificar si el botón mapeado corresponde a un trigger virtual
|
||||
// (Para esto necesitamos valores especiales que representen L2/R2 como botones)
|
||||
bool trigger_active_now = false;
|
||||
|
||||
// Usamos constantes especiales para L2 y R2 como botones
|
||||
if (button == TRIGGER_L2_AS_BUTTON) { // L2 como botón
|
||||
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER);
|
||||
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
|
||||
} else if (button == TRIGGER_R2_AS_BUTTON) { // R2 como botón
|
||||
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER);
|
||||
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
|
||||
} else {
|
||||
return false; // No es un trigger
|
||||
}
|
||||
|
||||
// Referencia al binding correspondiente
|
||||
auto& binding = gamepad->bindings[action];
|
||||
|
||||
if (repeat) {
|
||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||
return trigger_active_now;
|
||||
}
|
||||
|
||||
// Si no se permite repetir, aplicamos la lógica de transición
|
||||
if (trigger_active_now && !binding.trigger_active) {
|
||||
// Transición de inactivo a activo
|
||||
binding.trigger_active = true;
|
||||
return true;
|
||||
}
|
||||
if (!trigger_active_now && binding.trigger_active) {
|
||||
// Transición de activo a inactivo
|
||||
binding.trigger_active = false;
|
||||
}
|
||||
|
||||
// Mantener el estado actual
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void Input::addGamepadMappingsFromFile() {
|
||||
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
|
||||
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
void Input::discoverGamepads() {
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
handleEvent(event); // Comprueba mandos conectados
|
||||
}
|
||||
}
|
||||
|
||||
void Input::initSDLGamePad() {
|
||||
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
|
||||
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError());
|
||||
} else {
|
||||
addGamepadMappingsFromFile();
|
||||
discoverGamepads();
|
||||
std::cout << "\n** INPUT SYSTEM **\n";
|
||||
std::cout << "Input System initialized successfully\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Input::resetInputStates() {
|
||||
// Resetear todos los KeyBindings.active a false
|
||||
for (auto& key : keyboard_.bindings) {
|
||||
key.second.is_held = false;
|
||||
key.second.just_pressed = false;
|
||||
}
|
||||
// Resetear todos los ControllerBindings.active a false
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
for (auto& binding : gamepad->bindings) {
|
||||
binding.second.is_held = false;
|
||||
binding.second.just_pressed = false;
|
||||
binding.second.trigger_active = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Input::update() {
|
||||
// --- TECLADO ---
|
||||
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
||||
|
||||
for (auto& binding : keyboard_.bindings) {
|
||||
bool key_is_down_now = key_states[binding.second.scancode];
|
||||
|
||||
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||
binding.second.just_pressed = key_is_down_now && !binding.second.is_held;
|
||||
binding.second.is_held = key_is_down_now;
|
||||
}
|
||||
|
||||
// --- MANDOS ---
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
for (auto& binding : gamepad->bindings) {
|
||||
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, static_cast<SDL_GamepadButton>(binding.second.button))) != 0;
|
||||
|
||||
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||
binding.second.just_pressed = button_is_down_now && !binding.second.is_held;
|
||||
binding.second.is_held = button_is_down_now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto Input::handleEvent(const SDL_Event& event) -> std::string {
|
||||
switch (event.type) {
|
||||
case SDL_EVENT_GAMEPAD_ADDED:
|
||||
return addGamepad(event.gdevice.which);
|
||||
case SDL_EVENT_GAMEPAD_REMOVED:
|
||||
return removeGamepad(event.gdevice.which);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Input::addGamepad(int device_index) -> std::string {
|
||||
SDL_Gamepad* pad = SDL_OpenGamepad(device_index);
|
||||
if (pad == nullptr) {
|
||||
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
|
||||
return {};
|
||||
}
|
||||
|
||||
auto gamepad = std::make_shared<Gamepad>(pad);
|
||||
auto name = gamepad->name;
|
||||
std::cout << "Gamepad connected (" << name << ")" << '\n';
|
||||
gamepads_.push_back(std::move(gamepad));
|
||||
return name + " CONNECTED";
|
||||
}
|
||||
|
||||
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
|
||||
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) {
|
||||
return gamepad->instance_id == id;
|
||||
});
|
||||
|
||||
if (it != gamepads_.end()) {
|
||||
std::string name = (*it)->name;
|
||||
std::cout << "Gamepad disconnected (" << name << ")" << '\n';
|
||||
gamepads_.erase(it);
|
||||
return name + " DISCONNECTED";
|
||||
}
|
||||
std::cerr << "No se encontró el gamepad con ID " << id << '\n';
|
||||
return {};
|
||||
}
|
||||
|
||||
void Input::printConnectedGamepads() const {
|
||||
if (gamepads_.empty()) {
|
||||
std::cout << "No hay gamepads conectados." << '\n';
|
||||
return;
|
||||
}
|
||||
|
||||
std::cout << "Gamepads conectados:\n";
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
|
||||
std::cout << " - ID: " << gamepad->instance_id
|
||||
<< ", Nombre: " << name << ")" << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Input::Gamepad> {
|
||||
// Si no hay gamepads disponibles, devolver gamepad por defecto
|
||||
if (gamepads_.empty()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Buscar por nombre
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (gamepad && gamepad->name == gamepad_name) {
|
||||
return gamepad;
|
||||
}
|
||||
}
|
||||
|
||||
// Si no se encuentra por nombre, devolver el primer gamepad válido
|
||||
for (const auto& gamepad : gamepads_) {
|
||||
if (gamepad) {
|
||||
return gamepad;
|
||||
}
|
||||
}
|
||||
|
||||
// Si llegamos aquí, no hay gamepads válidos
|
||||
return nullptr;
|
||||
}
|
||||
140
source/core/input/input.hpp
Normal file
140
source/core/input/input.hpp
Normal file
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton, SDL_JoystickID, SDL_CloseGamepad, SDL_Gamepad, SDL_GetGamepadJoystick, SDL_GetGamepadName, SDL_GetGamepadPath, SDL_GetJoystickID, Sint16, Uint8, SDL_Event
|
||||
|
||||
#include <array> // Para array
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string, basic_string
|
||||
#include <unordered_map> // Para unordered_map
|
||||
#include <utility> // Para pair
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/input/input_types.hpp" // for InputAction
|
||||
|
||||
// --- 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
|
||||
|
||||
// --- 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
|
||||
};
|
||||
|
||||
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 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)}}} {}
|
||||
|
||||
~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);
|
||||
}
|
||||
};
|
||||
|
||||
// --- 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*;
|
||||
|
||||
// --- 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);
|
||||
|
||||
// --- 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;
|
||||
|
||||
// --- 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
|
||||
|
||||
// --- 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();
|
||||
|
||||
// --- 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
|
||||
};
|
||||
80
source/core/input/input_types.cpp
Normal file
80
source/core/input/input_types.cpp
Normal file
@@ -0,0 +1,80 @@
|
||||
#include "input_types.hpp"
|
||||
|
||||
#include <utility> // Para pair
|
||||
|
||||
// Definición de los mapas
|
||||
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
|
||||
{InputAction::LEFT, "LEFT"},
|
||||
{InputAction::RIGHT, "RIGHT"},
|
||||
{InputAction::JUMP, "JUMP"},
|
||||
{InputAction::PAUSE, "PAUSE"},
|
||||
{InputAction::EXIT, "EXIT"},
|
||||
{InputAction::ACCEPT, "ACCEPT"},
|
||||
{InputAction::CANCEL, "CANCEL"},
|
||||
{InputAction::WINDOW_INC_ZOOM, "WINDOW_INC_ZOOM"},
|
||||
{InputAction::WINDOW_DEC_ZOOM, "WINDOW_DEC_ZOOM"},
|
||||
{InputAction::TOGGLE_FULLSCREEN, "TOGGLE_FULLSCREEN"},
|
||||
{InputAction::TOGGLE_VSYNC, "TOGGLE_VSYNC"},
|
||||
{InputAction::TOGGLE_INTEGER_SCALE, "TOGGLE_INTEGER_SCALE"},
|
||||
{InputAction::TOGGLE_BORDER, "TOGGLE_BORDER"},
|
||||
{InputAction::TOGGLE_MUSIC, "TOGGLE_MUSIC"},
|
||||
{InputAction::NEXT_PALETTE, "NEXT_PALETTE"},
|
||||
{InputAction::PREVIOUS_PALETTE, "PREVIOUS_PALETTE"},
|
||||
{InputAction::TOGGLE_SHADERS, "TOGGLE_SHADERS"},
|
||||
{InputAction::SHOW_DEBUG_INFO, "SHOW_DEBUG_INFO"},
|
||||
{InputAction::TOGGLE_DEBUG, "TOGGLE_DEBUG"},
|
||||
{InputAction::NONE, "NONE"}};
|
||||
|
||||
const std::unordered_map<std::string, InputAction> STRING_TO_ACTION = {
|
||||
{"LEFT", InputAction::LEFT},
|
||||
{"RIGHT", InputAction::RIGHT},
|
||||
{"JUMP", InputAction::JUMP},
|
||||
{"PAUSE", InputAction::PAUSE},
|
||||
{"EXIT", InputAction::EXIT},
|
||||
{"ACCEPT", InputAction::ACCEPT},
|
||||
{"CANCEL", InputAction::CANCEL},
|
||||
{"WINDOW_INC_ZOOM", InputAction::WINDOW_INC_ZOOM},
|
||||
{"WINDOW_DEC_ZOOM", InputAction::WINDOW_DEC_ZOOM},
|
||||
{"TOGGLE_FULLSCREEN", InputAction::TOGGLE_FULLSCREEN},
|
||||
{"TOGGLE_VSYNC", InputAction::TOGGLE_VSYNC},
|
||||
{"TOGGLE_INTEGER_SCALE", InputAction::TOGGLE_INTEGER_SCALE},
|
||||
{"TOGGLE_BORDER", InputAction::TOGGLE_BORDER},
|
||||
{"TOGGLE_MUSIC", InputAction::TOGGLE_MUSIC},
|
||||
{"NEXT_PALETTE", InputAction::NEXT_PALETTE},
|
||||
{"PREVIOUS_PALETTE", InputAction::PREVIOUS_PALETTE},
|
||||
{"TOGGLE_SHADERS", InputAction::TOGGLE_SHADERS},
|
||||
{"SHOW_DEBUG_INFO", InputAction::SHOW_DEBUG_INFO},
|
||||
{"TOGGLE_DEBUG", InputAction::TOGGLE_DEBUG},
|
||||
{"NONE", InputAction::NONE}};
|
||||
|
||||
const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING = {
|
||||
{SDL_GAMEPAD_BUTTON_WEST, "WEST"},
|
||||
{SDL_GAMEPAD_BUTTON_NORTH, "NORTH"},
|
||||
{SDL_GAMEPAD_BUTTON_EAST, "EAST"},
|
||||
{SDL_GAMEPAD_BUTTON_SOUTH, "SOUTH"},
|
||||
{SDL_GAMEPAD_BUTTON_START, "START"},
|
||||
{SDL_GAMEPAD_BUTTON_BACK, "BACK"},
|
||||
{SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, "LEFT_SHOULDER"},
|
||||
{SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, "RIGHT_SHOULDER"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT"},
|
||||
{static_cast<SDL_GamepadButton>(100), "L2_AS_BUTTON"},
|
||||
{static_cast<SDL_GamepadButton>(101), "R2_AS_BUTTON"}};
|
||||
|
||||
const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON = {
|
||||
{"WEST", SDL_GAMEPAD_BUTTON_WEST},
|
||||
{"NORTH", SDL_GAMEPAD_BUTTON_NORTH},
|
||||
{"EAST", SDL_GAMEPAD_BUTTON_EAST},
|
||||
{"SOUTH", SDL_GAMEPAD_BUTTON_SOUTH},
|
||||
{"START", SDL_GAMEPAD_BUTTON_START},
|
||||
{"BACK", SDL_GAMEPAD_BUTTON_BACK},
|
||||
{"LEFT_SHOULDER", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
|
||||
{"RIGHT_SHOULDER", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
|
||||
{"DPAD_UP", SDL_GAMEPAD_BUTTON_DPAD_UP},
|
||||
{"DPAD_DOWN", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
|
||||
{"DPAD_LEFT", SDL_GAMEPAD_BUTTON_DPAD_LEFT},
|
||||
{"DPAD_RIGHT", SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
|
||||
{"L2_AS_BUTTON", static_cast<SDL_GamepadButton>(100)},
|
||||
{"R2_AS_BUTTON", static_cast<SDL_GamepadButton>(101)}};
|
||||
44
source/core/input/input_types.hpp
Normal file
44
source/core/input/input_types.hpp
Normal file
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
// --- Enums ---
|
||||
enum class InputAction : int { // Acciones de entrada posibles en el juego
|
||||
// Inputs de movimiento
|
||||
LEFT,
|
||||
RIGHT,
|
||||
JUMP,
|
||||
|
||||
// Inputs de control
|
||||
PAUSE,
|
||||
EXIT,
|
||||
ACCEPT,
|
||||
CANCEL,
|
||||
|
||||
// Inputs de sistema
|
||||
WINDOW_INC_ZOOM,
|
||||
WINDOW_DEC_ZOOM,
|
||||
TOGGLE_FULLSCREEN,
|
||||
TOGGLE_VSYNC,
|
||||
TOGGLE_INTEGER_SCALE,
|
||||
TOGGLE_SHADERS,
|
||||
TOGGLE_BORDER,
|
||||
TOGGLE_MUSIC,
|
||||
NEXT_PALETTE,
|
||||
PREVIOUS_PALETTE,
|
||||
SHOW_DEBUG_INFO,
|
||||
TOGGLE_DEBUG,
|
||||
|
||||
// Input obligatorio
|
||||
NONE,
|
||||
SIZE,
|
||||
};
|
||||
|
||||
// --- Variables ---
|
||||
extern const std::unordered_map<InputAction, std::string> ACTION_TO_STRING; // Mapeo de acción a string
|
||||
extern const std::unordered_map<std::string, InputAction> STRING_TO_ACTION; // Mapeo de string a acción
|
||||
extern const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING; // Mapeo de botón a string
|
||||
extern const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON; // Mapeo de string a botón
|
||||
25
source/core/input/mouse.cpp
Normal file
25
source/core/input/mouse.cpp
Normal file
@@ -0,0 +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
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
} // namespace Mouse
|
||||
12
source/core/input/mouse.hpp
Normal file
12
source/core/input/mouse.hpp
Normal file
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#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
|
||||
|
||||
void handleEvent(const SDL_Event& event);
|
||||
void updateCursorVisibility();
|
||||
} // namespace Mouse
|
||||
295
source/core/rendering/gif.cpp
Normal file
295
source/core/rendering/gif.cpp
Normal file
@@ -0,0 +1,295 @@
|
||||
#include "core/rendering/gif.hpp"
|
||||
|
||||
#include <cstring> // Para memcpy, size_t
|
||||
#include <iostream> // Para std::cout
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <string> // Para allocator, char_traits, operator==, basic_string
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
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
|
||||
92
source/core/rendering/gif.hpp
Normal file
92
source/core/rendering/gif.hpp
Normal file
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint> // Para uint8_t, uint16_t, uint32_t
|
||||
#include <vector> // Para vector
|
||||
|
||||
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;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct ScreenDescriptor {
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
uint8_t fields;
|
||||
uint8_t background_color_index;
|
||||
uint8_t pixel_aspect_ratio;
|
||||
};
|
||||
|
||||
struct RGB {
|
||||
uint8_t r, g, b;
|
||||
};
|
||||
|
||||
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 {
|
||||
uint8_t byte;
|
||||
int prev;
|
||||
int len;
|
||||
};
|
||||
|
||||
struct Extension {
|
||||
uint8_t extension_code;
|
||||
uint8_t block_size;
|
||||
};
|
||||
|
||||
struct GraphicControlExtension {
|
||||
uint8_t fields;
|
||||
uint16_t delay_time;
|
||||
uint8_t transparent_color_index;
|
||||
};
|
||||
|
||||
struct ApplicationExtension {
|
||||
uint8_t application_id[8];
|
||||
uint8_t version[3];
|
||||
};
|
||||
|
||||
struct PlaintextExtension {
|
||||
uint16_t left, top, width, height;
|
||||
uint8_t cell_width, cell_height;
|
||||
uint8_t foreground_color, background_color;
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
// Carga la paleta (global color table) a partir de un buffer,
|
||||
// retornándola en un vector de uint32_t (cada color se compone de R, G, B).
|
||||
static auto loadPalette(const uint8_t* buffer) -> std::vector<uint32_t>;
|
||||
|
||||
// Carga el stream GIF; devuelve un vector con los datos de imagen sin comprimir y
|
||||
// asigna el ancho y alto mediante referencias.
|
||||
static auto loadGif(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
|
||||
|
||||
private:
|
||||
// Lee los sub-bloques de datos y los acumula en un std::vector<uint8_t>.
|
||||
static auto readSubBlocks(const uint8_t*& buffer) -> std::vector<uint8_t>;
|
||||
|
||||
// Procesa el Image Descriptor y retorna el vector de datos sin comprimir.
|
||||
static auto processImageDescriptor(const uint8_t*& buffer, const std::vector<RGB>& gct, int resolution_bits) -> std::vector<uint8_t>;
|
||||
|
||||
// Procesa el stream completo del GIF y devuelve los datos sin comprimir.
|
||||
static auto processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector<uint8_t>;
|
||||
};
|
||||
|
||||
} // namespace GIF
|
||||
500
source/core/rendering/opengl/opengl_shader.cpp
Normal file
500
source/core/rendering/opengl/opengl_shader.cpp
Normal file
@@ -0,0 +1,500 @@
|
||||
#include "core/rendering/opengl/opengl_shader.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace Rendering {
|
||||
|
||||
OpenGLShader::~OpenGLShader() {
|
||||
cleanup();
|
||||
}
|
||||
|
||||
#ifndef __APPLE__
|
||||
auto OpenGLShader::initGLExtensions() -> bool {
|
||||
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
|
||||
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
|
||||
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
|
||||
glGetShaderiv = (PFNGLGETSHADERIVPROC)SDL_GL_GetProcAddress("glGetShaderiv");
|
||||
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)SDL_GL_GetProcAddress("glGetShaderInfoLog");
|
||||
glDeleteShader = (PFNGLDELETESHADERPROC)SDL_GL_GetProcAddress("glDeleteShader");
|
||||
glAttachShader = (PFNGLATTACHSHADERPROC)SDL_GL_GetProcAddress("glAttachShader");
|
||||
glCreateProgram = (PFNGLCREATEPROGRAMPROC)SDL_GL_GetProcAddress("glCreateProgram");
|
||||
glLinkProgram = (PFNGLLINKPROGRAMPROC)SDL_GL_GetProcAddress("glLinkProgram");
|
||||
glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)SDL_GL_GetProcAddress("glValidateProgram");
|
||||
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)SDL_GL_GetProcAddress("glGetProgramiv");
|
||||
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)SDL_GL_GetProcAddress("glGetProgramInfoLog");
|
||||
glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram");
|
||||
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)SDL_GL_GetProcAddress("glDeleteProgram");
|
||||
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)SDL_GL_GetProcAddress("glGetUniformLocation");
|
||||
glUniform2f = (PFNGLUNIFORM2FPROC)SDL_GL_GetProcAddress("glUniform2f");
|
||||
glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glGenVertexArrays");
|
||||
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)SDL_GL_GetProcAddress("glBindVertexArray");
|
||||
glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glDeleteVertexArrays");
|
||||
glGenBuffers = (PFNGLGENBUFFERSPROC)SDL_GL_GetProcAddress("glGenBuffers");
|
||||
glBindBuffer = (PFNGLBINDBUFFERPROC)SDL_GL_GetProcAddress("glBindBuffer");
|
||||
glBufferData = (PFNGLBUFFERDATAPROC)SDL_GL_GetProcAddress("glBufferData");
|
||||
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)SDL_GL_GetProcAddress("glDeleteBuffers");
|
||||
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)SDL_GL_GetProcAddress("glVertexAttribPointer");
|
||||
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
|
||||
|
||||
return (glCreateShader != nullptr) && (glShaderSource != nullptr) && (glCompileShader != nullptr) && (glGetShaderiv != nullptr) &&
|
||||
(glGetShaderInfoLog != nullptr) && (glDeleteShader != nullptr) && (glAttachShader != nullptr) && (glCreateProgram != nullptr) &&
|
||||
(glLinkProgram != nullptr) && (glValidateProgram != nullptr) && (glGetProgramiv != nullptr) && (glGetProgramInfoLog != nullptr) &&
|
||||
(glUseProgram != nullptr) && (glDeleteProgram != nullptr) && (glGetUniformLocation != nullptr) && (glUniform2f != nullptr) &&
|
||||
(glGenVertexArrays != nullptr) && (glBindVertexArray != nullptr) && (glDeleteVertexArrays != nullptr) &&
|
||||
(glGenBuffers != nullptr) && (glBindBuffer != nullptr) && (glBufferData != nullptr) && (glDeleteBuffers != nullptr) &&
|
||||
(glVertexAttribPointer != nullptr) && (glEnableVertexAttribArray != nullptr);
|
||||
}
|
||||
#endif
|
||||
|
||||
void OpenGLShader::checkGLError(const char* operation) {
|
||||
GLenum error = glGetError();
|
||||
if (error != GL_NO_ERROR) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Error OpenGL en %s: 0x%x",
|
||||
operation,
|
||||
error);
|
||||
}
|
||||
}
|
||||
|
||||
auto OpenGLShader::compileShader(const std::string& source, GLenum shader_type) -> GLuint {
|
||||
if (source.empty()) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"ERROR: El código fuente del shader está vacío");
|
||||
return 0;
|
||||
}
|
||||
|
||||
GLuint shader_id = glCreateShader(shader_type);
|
||||
if (shader_id == 0) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al crear shader");
|
||||
checkGLError("glCreateShader");
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char* sources[1] = {source.c_str()};
|
||||
glShaderSource(shader_id, 1, sources, nullptr);
|
||||
checkGLError("glShaderSource");
|
||||
|
||||
glCompileShader(shader_id);
|
||||
checkGLError("glCompileShader");
|
||||
|
||||
// Verificar compilación
|
||||
GLint compiled = GL_FALSE;
|
||||
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled);
|
||||
if (compiled != GL_TRUE) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Error en compilación del shader");
|
||||
GLint log_length;
|
||||
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);
|
||||
if (log_length > 0) {
|
||||
std::vector<char> log(log_length);
|
||||
glGetShaderInfoLog(shader_id, log_length, &log_length, log.data());
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Log de compilación: %s",
|
||||
log.data());
|
||||
}
|
||||
glDeleteShader(shader_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return shader_id;
|
||||
}
|
||||
|
||||
auto OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint {
|
||||
GLuint program = glCreateProgram();
|
||||
if (program == 0) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Error al crear programa de shaders");
|
||||
return 0;
|
||||
}
|
||||
|
||||
glAttachShader(program, vertex_shader);
|
||||
checkGLError("glAttachShader(vertex)");
|
||||
glAttachShader(program, fragment_shader);
|
||||
checkGLError("glAttachShader(fragment)");
|
||||
|
||||
glLinkProgram(program);
|
||||
checkGLError("glLinkProgram");
|
||||
|
||||
// Verificar enlace
|
||||
GLint linked = GL_FALSE;
|
||||
glGetProgramiv(program, GL_LINK_STATUS, &linked);
|
||||
if (linked != GL_TRUE) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Error al enlazar programa");
|
||||
GLint log_length;
|
||||
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
|
||||
if (log_length > 0) {
|
||||
std::vector<char> log(log_length);
|
||||
glGetProgramInfoLog(program, log_length, &log_length, log.data());
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Log de enlace: %s",
|
||||
log.data());
|
||||
}
|
||||
glDeleteProgram(program);
|
||||
return 0;
|
||||
}
|
||||
|
||||
glValidateProgram(program);
|
||||
checkGLError("glValidateProgram");
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
void OpenGLShader::createQuadGeometry() {
|
||||
// Datos del quad: posición (x, y) + coordenadas de textura (u, v)
|
||||
// Formato: x, y, u, v
|
||||
float vertices[] = {
|
||||
// Posición // TexCoords
|
||||
-1.0F,
|
||||
-1.0F,
|
||||
0.0F,
|
||||
0.0F, // Inferior izquierda
|
||||
1.0F,
|
||||
-1.0F,
|
||||
1.0F,
|
||||
0.0F, // Inferior derecha
|
||||
1.0F,
|
||||
1.0F,
|
||||
1.0F,
|
||||
1.0F, // Superior derecha
|
||||
-1.0F,
|
||||
1.0F,
|
||||
0.0F,
|
||||
1.0F // Superior izquierda
|
||||
};
|
||||
|
||||
// Índices para dibujar el quad con dos triángulos
|
||||
unsigned int indices[] = {
|
||||
0,
|
||||
1,
|
||||
2, // Primer triángulo
|
||||
2,
|
||||
3,
|
||||
0 // Segundo triángulo
|
||||
};
|
||||
|
||||
// Generar y configurar VAO
|
||||
glGenVertexArrays(1, &vao_);
|
||||
glBindVertexArray(vao_);
|
||||
checkGLError("glBindVertexArray");
|
||||
|
||||
// Generar y configurar VBO
|
||||
glGenBuffers(1, &vbo_);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo_);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
|
||||
checkGLError("glBufferData(VBO)");
|
||||
|
||||
// Generar y configurar EBO
|
||||
glGenBuffers(1, &ebo_);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
|
||||
checkGLError("glBufferData(EBO)");
|
||||
|
||||
// Atributo 0: Posición (2 floats)
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)nullptr);
|
||||
glEnableVertexAttribArray(0);
|
||||
checkGLError("glVertexAttribPointer(position)");
|
||||
|
||||
// Atributo 1: Coordenadas de textura (2 floats)
|
||||
// NOLINTNEXTLINE(performance-no-int-to-ptr) - OpenGL uses pointer as buffer offset
|
||||
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), reinterpret_cast<void*>(static_cast<uintptr_t>(2 * sizeof(float))));
|
||||
glEnableVertexAttribArray(1);
|
||||
checkGLError("glVertexAttribPointer(texcoord)");
|
||||
|
||||
// Desvincular
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
auto OpenGLShader::getTextureID(SDL_Texture* texture) -> GLuint {
|
||||
if (texture == nullptr) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
SDL_PropertiesID props = SDL_GetTextureProperties(texture);
|
||||
GLuint texture_id = 0;
|
||||
|
||||
// Intentar obtener ID de textura OpenGL
|
||||
texture_id = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "SDL.texture.opengl.texture", nullptr);
|
||||
|
||||
if (texture_id == 0) {
|
||||
texture_id = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "texture.opengl.texture", nullptr);
|
||||
}
|
||||
|
||||
if (texture_id == 0) {
|
||||
texture_id = (GLuint)SDL_GetNumberProperty(props, "SDL.texture.opengl.texture", 1);
|
||||
}
|
||||
|
||||
if (texture_id == 0) {
|
||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"No se pudo obtener ID de textura OpenGL, usando 1 por defecto");
|
||||
texture_id = 1;
|
||||
}
|
||||
|
||||
return texture_id;
|
||||
}
|
||||
|
||||
auto OpenGLShader::init(SDL_Window* window,
|
||||
SDL_Texture* texture,
|
||||
const std::string& vertex_source,
|
||||
const std::string& fragment_source) -> bool {
|
||||
window_ = window;
|
||||
back_buffer_ = texture;
|
||||
renderer_ = SDL_GetRenderer(window);
|
||||
|
||||
if (renderer_ == nullptr) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Error: No se pudo obtener el renderer");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Obtener tamaños
|
||||
SDL_GetWindowSize(window_, &window_width_, &window_height_);
|
||||
SDL_GetTextureSize(back_buffer_, &texture_width_, &texture_height_);
|
||||
|
||||
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Initializing shaders: window=%dx%d, texture=%.0fx%.0f",
|
||||
window_width_,
|
||||
window_height_,
|
||||
texture_width_,
|
||||
texture_height_);
|
||||
|
||||
// Verificar que es OpenGL
|
||||
const char* renderer_name = SDL_GetRendererName(renderer_);
|
||||
if ((renderer_name == nullptr) || strncmp(renderer_name, "opengl", 6) != 0) {
|
||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Renderer is not OpenGL: %s",
|
||||
(renderer_name != nullptr) ? renderer_name : "unknown");
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifndef __APPLE__
|
||||
// Inicializar extensiones OpenGL en Windows/Linux
|
||||
if (!initGLExtensions()) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Failed to initialize OpenGL extensions");
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Limpiar shader anterior si existe
|
||||
if (program_id_ != 0) {
|
||||
glDeleteProgram(program_id_);
|
||||
program_id_ = 0;
|
||||
}
|
||||
|
||||
// Compilar shaders
|
||||
GLuint vertex_shader = compileShader(vertex_source, GL_VERTEX_SHADER);
|
||||
GLuint fragment_shader = compileShader(fragment_source, GL_FRAGMENT_SHADER);
|
||||
|
||||
if (vertex_shader == 0 || fragment_shader == 0) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Failed to compile shaders");
|
||||
if (vertex_shader != 0) {
|
||||
glDeleteShader(vertex_shader);
|
||||
}
|
||||
if (fragment_shader != 0) {
|
||||
glDeleteShader(fragment_shader);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Enlazar programa
|
||||
program_id_ = linkProgram(vertex_shader, fragment_shader);
|
||||
|
||||
// Limpiar shaders (ya no necesarios tras el enlace)
|
||||
glDeleteShader(vertex_shader);
|
||||
glDeleteShader(fragment_shader);
|
||||
|
||||
if (program_id_ == 0) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Failed to create shader program");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Crear geometría del quad
|
||||
createQuadGeometry();
|
||||
|
||||
// Obtener ubicación del uniform TextureSize
|
||||
glUseProgram(program_id_);
|
||||
texture_size_location_ = glGetUniformLocation(program_id_, "TextureSize");
|
||||
if (texture_size_location_ != -1) {
|
||||
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Configuring TextureSize uniform: %.0fx%.0f",
|
||||
texture_width_,
|
||||
texture_height_);
|
||||
glUniform2f(texture_size_location_, texture_width_, texture_height_);
|
||||
checkGLError("glUniform2f(TextureSize)");
|
||||
} else {
|
||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"Uniform 'TextureSize' not found in shader");
|
||||
}
|
||||
glUseProgram(0);
|
||||
|
||||
is_initialized_ = true;
|
||||
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
|
||||
"** OpenGL 3.3 Shader Backend initialized successfully");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void OpenGLShader::render() {
|
||||
if (!is_initialized_ || program_id_ == 0) {
|
||||
// Fallback: renderizado SDL normal
|
||||
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255);
|
||||
SDL_SetRenderTarget(renderer_, nullptr);
|
||||
SDL_RenderClear(renderer_);
|
||||
SDL_RenderTexture(renderer_, back_buffer_, nullptr, nullptr);
|
||||
SDL_RenderPresent(renderer_);
|
||||
return;
|
||||
}
|
||||
|
||||
// Obtener tamaño actual de ventana (puede haber cambiado)
|
||||
int current_width;
|
||||
int current_height;
|
||||
SDL_GetWindowSize(window_, ¤t_width, ¤t_height);
|
||||
|
||||
// Guardar estados OpenGL
|
||||
GLint old_program;
|
||||
glGetIntegerv(GL_CURRENT_PROGRAM, &old_program);
|
||||
|
||||
GLint old_viewport[4];
|
||||
glGetIntegerv(GL_VIEWPORT, old_viewport);
|
||||
|
||||
GLboolean was_texture_enabled = glIsEnabled(GL_TEXTURE_2D);
|
||||
GLint old_texture;
|
||||
glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_texture);
|
||||
|
||||
GLint old_vao;
|
||||
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &old_vao);
|
||||
|
||||
// Preparar renderizado
|
||||
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255);
|
||||
SDL_SetRenderTarget(renderer_, nullptr);
|
||||
SDL_RenderClear(renderer_);
|
||||
|
||||
// Obtener y bindear textura
|
||||
GLuint texture_id = getTextureID(back_buffer_);
|
||||
glEnable(GL_TEXTURE_2D);
|
||||
glBindTexture(GL_TEXTURE_2D, texture_id);
|
||||
checkGLError("glBindTexture");
|
||||
|
||||
// Usar nuestro programa
|
||||
glUseProgram(program_id_);
|
||||
checkGLError("glUseProgram");
|
||||
|
||||
// Configurar viewport (obtener tamaño lógico de SDL)
|
||||
int logical_w;
|
||||
int logical_h;
|
||||
SDL_RendererLogicalPresentation mode;
|
||||
SDL_GetRenderLogicalPresentation(renderer_, &logical_w, &logical_h, &mode);
|
||||
|
||||
if (logical_w == 0 || logical_h == 0) {
|
||||
logical_w = current_width;
|
||||
logical_h = current_height;
|
||||
}
|
||||
|
||||
// Calcular viewport considerando aspect ratio
|
||||
int viewport_x = 0;
|
||||
int viewport_y = 0;
|
||||
int viewport_w = current_width;
|
||||
int viewport_h = current_height;
|
||||
|
||||
if (mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE) {
|
||||
int scale_x = current_width / logical_w;
|
||||
int scale_y = current_height / logical_h;
|
||||
int scale = (scale_x < scale_y) ? scale_x : scale_y;
|
||||
scale = std::max(scale, 1);
|
||||
|
||||
viewport_w = logical_w * scale;
|
||||
viewport_h = logical_h * scale;
|
||||
viewport_x = (current_width - viewport_w) / 2;
|
||||
viewport_y = (current_height - viewport_h) / 2;
|
||||
} else {
|
||||
float window_aspect = static_cast<float>(current_width) / current_height;
|
||||
float logical_aspect = static_cast<float>(logical_w) / logical_h;
|
||||
|
||||
if (window_aspect > logical_aspect) {
|
||||
viewport_w = static_cast<int>(logical_aspect * current_height);
|
||||
viewport_x = (current_width - viewport_w) / 2;
|
||||
} else {
|
||||
viewport_h = static_cast<int>(current_width / logical_aspect);
|
||||
viewport_y = (current_height - viewport_h) / 2;
|
||||
}
|
||||
}
|
||||
|
||||
glViewport(viewport_x, viewport_y, viewport_w, viewport_h);
|
||||
checkGLError("glViewport");
|
||||
|
||||
// Dibujar quad usando VAO
|
||||
glBindVertexArray(vao_);
|
||||
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
|
||||
checkGLError("glDrawElements");
|
||||
|
||||
// Presentar
|
||||
SDL_GL_SwapWindow(window_);
|
||||
|
||||
// Restaurar estados OpenGL
|
||||
glUseProgram(old_program);
|
||||
glBindTexture(GL_TEXTURE_2D, old_texture);
|
||||
if (was_texture_enabled == 0U) {
|
||||
glDisable(GL_TEXTURE_2D);
|
||||
}
|
||||
glBindVertexArray(old_vao);
|
||||
glViewport(old_viewport[0], old_viewport[1], old_viewport[2], old_viewport[3]);
|
||||
}
|
||||
|
||||
void OpenGLShader::setTextureSize(float width, float height) {
|
||||
if (!is_initialized_ || program_id_ == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
texture_width_ = width;
|
||||
texture_height_ = height;
|
||||
|
||||
GLint old_program;
|
||||
glGetIntegerv(GL_CURRENT_PROGRAM, &old_program);
|
||||
|
||||
glUseProgram(program_id_);
|
||||
|
||||
if (texture_size_location_ != -1) {
|
||||
glUniform2f(texture_size_location_, width, height);
|
||||
checkGLError("glUniform2f(TextureSize)");
|
||||
}
|
||||
|
||||
glUseProgram(old_program);
|
||||
}
|
||||
|
||||
void OpenGLShader::cleanup() {
|
||||
if (vao_ != 0) {
|
||||
glDeleteVertexArrays(1, &vao_);
|
||||
vao_ = 0;
|
||||
}
|
||||
|
||||
if (vbo_ != 0) {
|
||||
glDeleteBuffers(1, &vbo_);
|
||||
vbo_ = 0;
|
||||
}
|
||||
|
||||
if (ebo_ != 0) {
|
||||
glDeleteBuffers(1, &ebo_);
|
||||
ebo_ = 0;
|
||||
}
|
||||
|
||||
if (program_id_ != 0) {
|
||||
glDeleteProgram(program_id_);
|
||||
program_id_ = 0;
|
||||
}
|
||||
|
||||
is_initialized_ = false;
|
||||
window_ = nullptr;
|
||||
renderer_ = nullptr;
|
||||
back_buffer_ = nullptr;
|
||||
}
|
||||
|
||||
} // namespace Rendering
|
||||
100
source/core/rendering/opengl/opengl_shader.hpp
Normal file
100
source/core/rendering/opengl/opengl_shader.hpp
Normal file
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/rendering/shader_backend.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <OpenGL/gl3.h>
|
||||
#else
|
||||
#include <SDL3/SDL_opengl.h>
|
||||
#endif
|
||||
|
||||
namespace Rendering {
|
||||
|
||||
/**
|
||||
* @brief Backend de shaders usando OpenGL 3.3 Core Profile
|
||||
*
|
||||
* Implementa el renderizado de shaders usando APIs modernas de OpenGL:
|
||||
* - VAO (Vertex Array Objects)
|
||||
* - VBO (Vertex Buffer Objects)
|
||||
* - Shaders GLSL #version 330 core
|
||||
*/
|
||||
class OpenGLShader : public ShaderBackend {
|
||||
public:
|
||||
OpenGLShader() = default;
|
||||
~OpenGLShader() override;
|
||||
|
||||
auto init(SDL_Window* window,
|
||||
SDL_Texture* texture,
|
||||
const std::string& vertex_source,
|
||||
const std::string& fragment_source) -> bool override;
|
||||
|
||||
void render() override;
|
||||
void setTextureSize(float width, float height) override;
|
||||
void cleanup() final;
|
||||
[[nodiscard]] auto isHardwareAccelerated() const -> bool override { return is_initialized_; }
|
||||
|
||||
private:
|
||||
// Funciones auxiliares
|
||||
auto initGLExtensions() -> bool;
|
||||
auto compileShader(const std::string& source, GLenum shader_type) -> GLuint;
|
||||
auto linkProgram(GLuint vertex_shader, GLuint fragment_shader) -> GLuint;
|
||||
void createQuadGeometry();
|
||||
static auto getTextureID(SDL_Texture* texture) -> GLuint;
|
||||
static void checkGLError(const char* operation);
|
||||
|
||||
// Estado SDL
|
||||
SDL_Window* window_ = nullptr;
|
||||
SDL_Renderer* renderer_ = nullptr;
|
||||
SDL_Texture* back_buffer_ = nullptr;
|
||||
|
||||
// Estado OpenGL
|
||||
GLuint program_id_ = 0;
|
||||
GLuint vao_ = 0; // Vertex Array Object
|
||||
GLuint vbo_ = 0; // Vertex Buffer Object
|
||||
GLuint ebo_ = 0; // Element Buffer Object
|
||||
|
||||
// Ubicaciones de uniforms
|
||||
GLint texture_size_location_ = -1;
|
||||
|
||||
// Tamaños
|
||||
int window_width_ = 0;
|
||||
int window_height_ = 0;
|
||||
float texture_width_ = 0.0F;
|
||||
float texture_height_ = 0.0F;
|
||||
|
||||
// Estado
|
||||
bool is_initialized_ = false;
|
||||
|
||||
#ifndef __APPLE__
|
||||
// NOLINTBEGIN
|
||||
// Punteros a funciones OpenGL en Windows/Linux
|
||||
PFNGLCREATESHADERPROC glCreateShader = nullptr;
|
||||
PFNGLSHADERSOURCEPROC glShaderSource = nullptr;
|
||||
PFNGLCOMPILESHADERPROC glCompileShader = nullptr;
|
||||
PFNGLGETSHADERIVPROC glGetShaderiv = nullptr;
|
||||
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr;
|
||||
PFNGLDELETESHADERPROC glDeleteShader = nullptr;
|
||||
PFNGLATTACHSHADERPROC glAttachShader = nullptr;
|
||||
PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr;
|
||||
PFNGLLINKPROGRAMPROC glLinkProgram = nullptr;
|
||||
PFNGLVALIDATEPROGRAMPROC glValidateProgram = nullptr;
|
||||
PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr;
|
||||
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr;
|
||||
PFNGLUSEPROGRAMPROC glUseProgram = nullptr;
|
||||
PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr;
|
||||
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr;
|
||||
PFNGLUNIFORM2FPROC glUniform2f = nullptr;
|
||||
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr;
|
||||
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr;
|
||||
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr;
|
||||
PFNGLGENBUFFERSPROC glGenBuffers = nullptr;
|
||||
PFNGLBINDBUFFERPROC glBindBuffer = nullptr;
|
||||
PFNGLBUFFERDATAPROC glBufferData = nullptr;
|
||||
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
|
||||
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
|
||||
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
|
||||
// NOLINTEND
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace Rendering
|
||||
597
source/core/rendering/screen.cpp
Normal file
597
source/core/rendering/screen.cpp
Normal file
@@ -0,0 +1,597 @@
|
||||
#include "core/rendering/screen.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // Para max, min, transform
|
||||
#include <cctype> // Para toupper
|
||||
#include <fstream> // Para basic_ostream, operator<<, endl, basic_...
|
||||
#include <iostream> // Para cerr
|
||||
#include <iterator> // Para istreambuf_iterator, operator==
|
||||
#include <string> // Para char_traits, string, operator+, operator==
|
||||
|
||||
#include "core/input/mouse.hpp" // Para updateCursorVisibility
|
||||
#include "core/rendering/opengl/opengl_shader.hpp" // Para OpenGLShader
|
||||
#include "core/rendering/surface.hpp" // Para Surface, readPalFile
|
||||
#include "core/rendering/text.hpp" // Para Text
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||
#include "core/resources/resource_list.hpp" // Para Asset, AssetType
|
||||
#include "game/options.hpp" // Para Options, options, OptionsVideo, Border
|
||||
#include "game/ui/notifier.hpp" // Para Notifier
|
||||
#include "utils/color.hpp" // Para Color
|
||||
|
||||
// [SINGLETON]
|
||||
Screen* Screen::screen = nullptr;
|
||||
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void Screen::init() {
|
||||
Screen::screen = new Screen();
|
||||
}
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void Screen::destroy() {
|
||||
delete Screen::screen;
|
||||
}
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
auto Screen::get() -> Screen* {
|
||||
return Screen::screen;
|
||||
}
|
||||
|
||||
// Constructor
|
||||
Screen::Screen()
|
||||
: palettes_(Resource::List::get()->getListByType(Resource::List::Type::PALETTE)) {
|
||||
// Arranca SDL VIDEO, crea la ventana y el renderizador
|
||||
initSDLVideo();
|
||||
if (Options::video.fullscreen) {
|
||||
SDL_HideCursor();
|
||||
}
|
||||
|
||||
// Ajusta los tamaños
|
||||
game_surface_dstrect_ = {.x = Options::video.border.width, .y = Options::video.border.height, .w = Options::game.width, .h = Options::game.height};
|
||||
// adjustWindowSize();
|
||||
current_palette_ = findPalette(Options::video.palette);
|
||||
|
||||
// Define el color del borde para el modo de pantalla completa
|
||||
border_color_ = Color::index(Color::Cpc::BLACK);
|
||||
|
||||
// Crea la textura donde se dibujan los graficos del juego
|
||||
game_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, Options::game.width, Options::game.height);
|
||||
if (game_texture_ == nullptr) {
|
||||
// Registrar el error si está habilitado
|
||||
if (Options::console) {
|
||||
std::cerr << "Error: game_texture_ could not be created!\nSDL Error: " << SDL_GetError() << '\n';
|
||||
}
|
||||
}
|
||||
SDL_SetTextureScaleMode(game_texture_, SDL_SCALEMODE_NEAREST);
|
||||
|
||||
// Crea la textura donde se dibuja el borde que rodea el area de juego
|
||||
border_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, Options::game.width + (Options::video.border.width * 2), Options::game.height + (Options::video.border.height * 2));
|
||||
if (border_texture_ == nullptr) {
|
||||
// Registrar el error si está habilitado
|
||||
if (Options::console) {
|
||||
std::cerr << "Error: border_texture_ could not be created!\nSDL Error: " << SDL_GetError() << '\n';
|
||||
}
|
||||
}
|
||||
SDL_SetTextureScaleMode(border_texture_, SDL_SCALEMODE_NEAREST);
|
||||
|
||||
// Cargar la paleta una sola vez
|
||||
auto initial_palette = readPalFile(palettes_.at(current_palette_));
|
||||
|
||||
// Crea la surface donde se dibujan los graficos del juego
|
||||
game_surface_ = std::make_shared<Surface>(Options::game.width, Options::game.height);
|
||||
game_surface_->setPalette(initial_palette);
|
||||
game_surface_->clear(Color::index(Color::Cpc::BLACK));
|
||||
|
||||
// Crea la surface para el borde de colores
|
||||
border_surface_ = std::make_shared<Surface>(Options::game.width + (Options::video.border.width * 2), Options::game.height + (Options::video.border.height * 2));
|
||||
border_surface_->setPalette(initial_palette);
|
||||
border_surface_->clear(border_color_);
|
||||
|
||||
// Establece la surface que actuará como renderer para recibir las llamadas a render()
|
||||
renderer_surface_ = std::make_shared<std::shared_ptr<Surface>>(game_surface_);
|
||||
|
||||
// Crea el objeto de texto para la pantalla de carga
|
||||
createText();
|
||||
|
||||
// Extrae el nombre de las paletas desde su ruta
|
||||
processPaletteList();
|
||||
|
||||
// Renderizar una vez la textura vacía para que tenga contenido válido
|
||||
// antes de inicializar los shaders (evita pantalla negra)
|
||||
SDL_RenderTexture(renderer_, game_texture_, nullptr, nullptr);
|
||||
SDL_RenderTexture(renderer_, border_texture_, nullptr, nullptr);
|
||||
|
||||
// Ahora sí inicializar los shaders
|
||||
initShaders();
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Screen::~Screen() {
|
||||
SDL_DestroyTexture(game_texture_);
|
||||
SDL_DestroyTexture(border_texture_);
|
||||
}
|
||||
|
||||
// Limpia el renderer
|
||||
void Screen::clearRenderer(ColorRGB color) {
|
||||
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF);
|
||||
SDL_RenderClear(renderer_);
|
||||
}
|
||||
|
||||
// Prepara para empezar a dibujar en la textura de juego
|
||||
void Screen::start() { setRendererSurface(nullptr); }
|
||||
|
||||
// Vuelca el contenido del renderizador en pantalla
|
||||
void Screen::render() {
|
||||
fps_.increment();
|
||||
|
||||
// Renderiza todos los overlays
|
||||
renderOverlays();
|
||||
|
||||
// Copia la surface a la textura
|
||||
surfaceToTexture();
|
||||
|
||||
// Copia la textura al renderizador
|
||||
textureToRenderer();
|
||||
}
|
||||
|
||||
// Establece el modo de video
|
||||
void Screen::setVideoMode(bool mode) {
|
||||
// Actualiza las opciones
|
||||
Options::video.fullscreen = mode;
|
||||
|
||||
// Configura el modo de pantalla y ajusta la ventana
|
||||
SDL_SetWindowFullscreen(window_, Options::video.fullscreen);
|
||||
adjustWindowSize();
|
||||
adjustRenderLogicalSize();
|
||||
}
|
||||
|
||||
// Camibia entre pantalla completa y ventana
|
||||
void Screen::toggleVideoMode() {
|
||||
Options::video.fullscreen = !Options::video.fullscreen;
|
||||
setVideoMode(Options::video.fullscreen);
|
||||
}
|
||||
|
||||
// Reduce el tamaño de la ventana
|
||||
auto Screen::decWindowZoom() -> bool {
|
||||
if (static_cast<int>(Options::video.fullscreen) == 0) {
|
||||
const int PREVIOUS_ZOOM = Options::window.zoom;
|
||||
--Options::window.zoom;
|
||||
Options::window.zoom = std::max(Options::window.zoom, 1);
|
||||
|
||||
if (Options::window.zoom != PREVIOUS_ZOOM) {
|
||||
setVideoMode(Options::video.fullscreen);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Aumenta el tamaño de la ventana
|
||||
auto Screen::incWindowZoom() -> bool {
|
||||
if (static_cast<int>(Options::video.fullscreen) == 0) {
|
||||
const int PREVIOUS_ZOOM = Options::window.zoom;
|
||||
++Options::window.zoom;
|
||||
Options::window.zoom = std::min(Options::window.zoom, Options::window.max_zoom);
|
||||
|
||||
if (Options::window.zoom != PREVIOUS_ZOOM) {
|
||||
setVideoMode(Options::video.fullscreen);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Cambia el color del borde
|
||||
void Screen::setBorderColor(Uint8 color) {
|
||||
border_color_ = color;
|
||||
border_surface_->clear(border_color_);
|
||||
}
|
||||
|
||||
// Cambia entre borde visible y no visible
|
||||
void Screen::toggleBorder() {
|
||||
Options::video.border.enabled = !Options::video.border.enabled;
|
||||
setVideoMode(Options::video.fullscreen);
|
||||
initShaders();
|
||||
}
|
||||
|
||||
// Dibuja las notificaciones
|
||||
void Screen::renderNotifications() const {
|
||||
if (notifications_enabled_) {
|
||||
Notifier::get()->render();
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia el estado de los shaders
|
||||
void Screen::toggleShaders() {
|
||||
Options::video.shaders = !Options::video.shaders;
|
||||
initShaders();
|
||||
}
|
||||
|
||||
// Actualiza la lógica de la clase (versión nueva con delta_time para escenas migradas)
|
||||
void Screen::update(float delta_time) {
|
||||
int old_fps = fps_.last_value;
|
||||
fps_.calculate(SDL_GetTicks());
|
||||
|
||||
// Actualizar título de ventana si cambió el FPS
|
||||
if (fps_.last_value != old_fps) {
|
||||
std::string title = Options::window.caption + " - " + std::to_string(fps_.last_value) + " FPS";
|
||||
SDL_SetWindowTitle(window_, title.c_str());
|
||||
}
|
||||
|
||||
Notifier::get()->update(delta_time);
|
||||
Mouse::updateCursorVisibility();
|
||||
}
|
||||
|
||||
// Calcula el tamaño de la ventana
|
||||
void Screen::adjustWindowSize() {
|
||||
window_width_ = Options::game.width + (Options::video.border.enabled ? Options::video.border.width * 2 : 0);
|
||||
window_height_ = Options::game.height + (Options::video.border.enabled ? Options::video.border.height * 2 : 0);
|
||||
|
||||
// Establece el nuevo tamaño
|
||||
if (static_cast<int>(Options::video.fullscreen) == 0) {
|
||||
int old_width;
|
||||
int old_height;
|
||||
SDL_GetWindowSize(window_, &old_width, &old_height);
|
||||
|
||||
int old_pos_x;
|
||||
int old_pos_y;
|
||||
SDL_GetWindowPosition(window_, &old_pos_x, &old_pos_y);
|
||||
|
||||
const int NEW_POS_X = old_pos_x + ((old_width - (window_width_ * Options::window.zoom)) / 2);
|
||||
const int NEW_POS_Y = old_pos_y + ((old_height - (window_height_ * Options::window.zoom)) / 2);
|
||||
|
||||
SDL_SetWindowSize(window_, window_width_ * Options::window.zoom, window_height_ * Options::window.zoom);
|
||||
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS), std::max(NEW_POS_Y, 0));
|
||||
}
|
||||
}
|
||||
|
||||
// Ajusta el tamaño lógico del renderizador
|
||||
void Screen::adjustRenderLogicalSize() {
|
||||
SDL_SetRenderLogicalPresentation(renderer_, window_width_, window_height_, Options::video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
|
||||
}
|
||||
|
||||
// Establece el renderizador para las surfaces
|
||||
void Screen::setRendererSurface(const std::shared_ptr<Surface>& surface) {
|
||||
(surface) ? renderer_surface_ = std::make_shared<std::shared_ptr<Surface>>(surface) : renderer_surface_ = std::make_shared<std::shared_ptr<Surface>>(game_surface_);
|
||||
}
|
||||
|
||||
// Cambia la paleta
|
||||
void Screen::nextPalette() {
|
||||
++current_palette_;
|
||||
if (current_palette_ == static_cast<int>(palettes_.size())) {
|
||||
current_palette_ = 0;
|
||||
}
|
||||
|
||||
setPalete();
|
||||
}
|
||||
|
||||
// Cambia la paleta
|
||||
void Screen::previousPalette() {
|
||||
if (current_palette_ > 0) {
|
||||
--current_palette_;
|
||||
} else {
|
||||
current_palette_ = static_cast<Uint8>(palettes_.size() - 1);
|
||||
}
|
||||
|
||||
setPalete();
|
||||
}
|
||||
|
||||
// Establece la paleta
|
||||
void Screen::setPalete() {
|
||||
game_surface_->loadPalette(Resource::Cache::get()->getPalette(palettes_.at(current_palette_)));
|
||||
border_surface_->loadPalette(Resource::Cache::get()->getPalette(palettes_.at(current_palette_)));
|
||||
|
||||
Options::video.palette = palettes_.at(current_palette_);
|
||||
|
||||
// Eliminar ".gif"
|
||||
size_t pos = Options::video.palette.find(".pal");
|
||||
if (pos != std::string::npos) {
|
||||
Options::video.palette.erase(pos, 4);
|
||||
}
|
||||
|
||||
// Convertir a mayúsculas
|
||||
std::ranges::transform(Options::video.palette, Options::video.palette.begin(), ::toupper);
|
||||
}
|
||||
|
||||
// Extrae los nombres de las paletas
|
||||
void Screen::processPaletteList() {
|
||||
for (auto& palette : palettes_) {
|
||||
palette = getFileName(palette);
|
||||
}
|
||||
}
|
||||
|
||||
// Copia la surface a la textura
|
||||
void Screen::surfaceToTexture() {
|
||||
if (Options::video.border.enabled) {
|
||||
border_surface_->copyToTexture(renderer_, border_texture_);
|
||||
game_surface_->copyToTexture(renderer_, border_texture_, nullptr, &game_surface_dstrect_);
|
||||
} else {
|
||||
game_surface_->copyToTexture(renderer_, game_texture_);
|
||||
}
|
||||
}
|
||||
|
||||
// Copia la textura al renderizador
|
||||
void Screen::textureToRenderer() {
|
||||
SDL_Texture* texture_to_render = Options::video.border.enabled ? border_texture_ : game_texture_;
|
||||
|
||||
if (Options::video.shaders && shader_backend_) {
|
||||
shader_backend_->render();
|
||||
} else {
|
||||
SDL_SetRenderTarget(renderer_, nullptr);
|
||||
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
|
||||
SDL_RenderClear(renderer_);
|
||||
SDL_RenderTexture(renderer_, texture_to_render, nullptr, nullptr);
|
||||
SDL_RenderPresent(renderer_);
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza todos los overlays
|
||||
void Screen::renderOverlays() {
|
||||
renderNotifications();
|
||||
#ifdef _DEBUG
|
||||
//renderInfo();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Localiza la paleta dentro del vector de paletas
|
||||
auto Screen::findPalette(const std::string& name) -> size_t {
|
||||
std::string upper_name = toUpper(name + ".pal");
|
||||
|
||||
for (size_t i = 0; i < palettes_.size(); ++i) {
|
||||
if (toUpper(getFileName(palettes_[i])) == upper_name) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return static_cast<size_t>(0);
|
||||
}
|
||||
|
||||
// Muestra información por pantalla
|
||||
void Screen::renderInfo() {
|
||||
if (show_debug_info_ && (Resource::Cache::get() != nullptr)) {
|
||||
auto text = Resource::Cache::get()->getText("smb2");
|
||||
auto color = Color::index(Color::Cpc::YELLOW);
|
||||
|
||||
// FPS
|
||||
const std::string FPS_TEXT = std::to_string(fps_.last_value) + " FPS";
|
||||
text->writeColored(Options::game.width - text->length(FPS_TEXT), 0, FPS_TEXT, color);
|
||||
}
|
||||
}
|
||||
|
||||
// Limpia la game_surface_
|
||||
void Screen::clearSurface(Uint8 index) { game_surface_->clear(index); }
|
||||
|
||||
// Establece el tamaño del borde
|
||||
void Screen::setBorderWidth(int width) { Options::video.border.width = width; }
|
||||
|
||||
// Establece el tamaño del borde
|
||||
void Screen::setBorderHeight(int height) { Options::video.border.height = height; }
|
||||
|
||||
// Establece si se ha de ver el borde en el modo ventana
|
||||
void Screen::setBorderEnabled(bool value) { Options::video.border.enabled = value; }
|
||||
|
||||
// Muestra la ventana
|
||||
void Screen::show() { SDL_ShowWindow(window_); }
|
||||
|
||||
// Oculta la ventana
|
||||
void Screen::hide() { SDL_HideWindow(window_); }
|
||||
|
||||
// Establece la visibilidad de las notificaciones
|
||||
void Screen::setNotificationsEnabled(bool value) { notifications_enabled_ = value; }
|
||||
|
||||
// Activa / desactiva la información de debug
|
||||
void Screen::toggleDebugInfo() { show_debug_info_ = !show_debug_info_; }
|
||||
|
||||
// Alterna entre activar y desactivar el escalado entero
|
||||
void Screen::toggleIntegerScale() {
|
||||
Options::video.integer_scale = !Options::video.integer_scale;
|
||||
SDL_SetRenderLogicalPresentation(renderer_, Options::game.width, Options::game.height, Options::video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
|
||||
}
|
||||
|
||||
// Alterna entre activar y desactivar el V-Sync
|
||||
void Screen::toggleVSync() {
|
||||
Options::video.vertical_sync = !Options::video.vertical_sync;
|
||||
SDL_SetRenderVSync(renderer_, Options::video.vertical_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED);
|
||||
}
|
||||
|
||||
// Getters
|
||||
auto Screen::getRenderer() -> SDL_Renderer* { return renderer_; }
|
||||
auto Screen::getRendererSurface() -> std::shared_ptr<Surface> { return (*renderer_surface_); }
|
||||
auto Screen::getBorderSurface() -> std::shared_ptr<Surface> { return border_surface_; }
|
||||
|
||||
auto loadData(const std::string& filepath) -> std::vector<uint8_t> {
|
||||
// Load using ResourceHelper (supports both filesystem and pack)
|
||||
return Resource::Helper::loadFile(filepath);
|
||||
}
|
||||
|
||||
// Carga el contenido de los archivos GLSL
|
||||
void Screen::loadShaders() {
|
||||
if (vertex_shader_source_.empty()) {
|
||||
// Detectar si necesitamos OpenGL ES (Raspberry Pi)
|
||||
// Intentar cargar versión ES primero si existe
|
||||
std::string vertex_file = "crtpi_vertex_es.glsl";
|
||||
auto data = loadData(Resource::List::get()->get(vertex_file));
|
||||
|
||||
if (data.empty()) {
|
||||
// Si no existe versión ES, usar versión Desktop
|
||||
vertex_file = "crtpi_vertex.glsl";
|
||||
data = loadData(Resource::List::get()->get(vertex_file));
|
||||
std::cout << "Usando shaders OpenGL Desktop 3.3\n";
|
||||
} else {
|
||||
std::cout << "Usando shaders OpenGL ES 3.0 (Raspberry Pi)\n";
|
||||
}
|
||||
|
||||
if (!data.empty()) {
|
||||
vertex_shader_source_ = std::string(data.begin(), data.end());
|
||||
}
|
||||
}
|
||||
if (fragment_shader_source_.empty()) {
|
||||
// Intentar cargar versión ES primero si existe
|
||||
std::string fragment_file = "crtpi_fragment_es.glsl";
|
||||
auto data = loadData(Resource::List::get()->get(fragment_file));
|
||||
|
||||
if (data.empty()) {
|
||||
// Si no existe versión ES, usar versión Desktop
|
||||
fragment_file = "crtpi_fragment.glsl";
|
||||
data = loadData(Resource::List::get()->get(fragment_file));
|
||||
}
|
||||
|
||||
if (!data.empty()) {
|
||||
fragment_shader_source_ = std::string(data.begin(), data.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializa los shaders
|
||||
void Screen::initShaders() {
|
||||
#ifndef __APPLE__
|
||||
if (Options::video.shaders) {
|
||||
loadShaders();
|
||||
if (!shader_backend_) {
|
||||
shader_backend_ = std::make_unique<Rendering::OpenGLShader>();
|
||||
}
|
||||
shader_backend_->init(window_, Options::video.border.enabled ? border_texture_ : game_texture_, vertex_shader_source_, fragment_shader_source_);
|
||||
// shader_backend_->init(window_, shaders_texture_, vertex_shader_source_, fragment_shader_source_);
|
||||
}
|
||||
#else
|
||||
// En macOS, OpenGL está deprecated y rinde mal
|
||||
// TODO: Implementar backend de Metal para shaders en macOS
|
||||
std::cout << "WARNING: Shaders no disponibles en macOS (OpenGL deprecated). Usa Metal backend.\n";
|
||||
#endif
|
||||
}
|
||||
|
||||
// Obtiene información sobre la pantalla
|
||||
void Screen::getDisplayInfo() {
|
||||
std::cout << "\n** VIDEO SYSTEM **\n";
|
||||
|
||||
int num_displays = 0;
|
||||
SDL_DisplayID* displays = SDL_GetDisplays(&num_displays);
|
||||
if (displays != nullptr) {
|
||||
for (int i = 0; i < num_displays; ++i) {
|
||||
SDL_DisplayID instance_id = displays[i];
|
||||
const char* name = SDL_GetDisplayName(instance_id);
|
||||
|
||||
std::cout << "Display " << instance_id << ": " << ((name != nullptr) ? name : "Unknown") << '\n';
|
||||
}
|
||||
|
||||
const auto* dm = SDL_GetCurrentDisplayMode(displays[0]);
|
||||
|
||||
// Guarda información del monitor en display_monitor_
|
||||
const char* first_display_name = SDL_GetDisplayName(displays[0]);
|
||||
display_monitor_.name = (first_display_name != nullptr) ? first_display_name : "Unknown";
|
||||
display_monitor_.width = static_cast<int>(dm->w);
|
||||
display_monitor_.height = static_cast<int>(dm->h);
|
||||
display_monitor_.refresh_rate = static_cast<int>(dm->refresh_rate);
|
||||
|
||||
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
|
||||
Options::window.max_zoom = std::min(dm->w / Options::game.width, dm->h / Options::game.height);
|
||||
Options::window.zoom = std::min(Options::window.zoom, Options::window.max_zoom);
|
||||
|
||||
// Muestra información sobre el tamaño de la pantalla y de la ventana de juego
|
||||
std::cout << "Current display mode: " << static_cast<int>(dm->w) << "x" << static_cast<int>(dm->h) << " @ " << static_cast<int>(dm->refresh_rate) << "Hz\n";
|
||||
|
||||
std::cout << "Window resolution: " << static_cast<int>(Options::game.width) << "x" << static_cast<int>(Options::game.height) << " x" << Options::window.zoom << '\n';
|
||||
|
||||
Options::video.info = std::to_string(static_cast<int>(dm->w)) + "x" +
|
||||
std::to_string(static_cast<int>(dm->h)) + " @ " +
|
||||
std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz";
|
||||
|
||||
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
|
||||
const int MAX_ZOOM = std::min(dm->w / Options::game.width, (dm->h - WINDOWS_DECORATIONS) / Options::game.height);
|
||||
|
||||
// Normaliza los valores de zoom
|
||||
Options::window.zoom = std::min(Options::window.zoom, MAX_ZOOM);
|
||||
|
||||
SDL_free(displays);
|
||||
}
|
||||
}
|
||||
|
||||
// Arranca SDL VIDEO y crea la ventana
|
||||
auto Screen::initSDLVideo() -> bool {
|
||||
// Inicializar SDL
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
||||
std::cerr << "FATAL: Failed to initialize SDL_VIDEO! SDL Error: " << SDL_GetError() << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
// Obtener información de la pantalla
|
||||
getDisplayInfo();
|
||||
|
||||
// Configurar hint para renderizado
|
||||
#ifdef __APPLE__
|
||||
if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal")) {
|
||||
std::cout << "WARNING: Failed to set Metal hint!\n";
|
||||
}
|
||||
#else
|
||||
// Configurar hint de render driver
|
||||
if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl")) {
|
||||
std::cout << "WARNING: Failed to set OpenGL hint!\n";
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// Windows: Pedir explícitamente OpenGL 3.3 Core Profile
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
std::cout << "Solicitando OpenGL 3.3 Core Profile\n";
|
||||
#else
|
||||
// Linux: Dejar que SDL elija (Desktop 3.3 en PC, ES 3.0 en RPi automáticamente)
|
||||
std::cout << "Usando OpenGL por defecto del sistema\n";
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Crear ventana
|
||||
const auto WINDOW_WIDTH = Options::video.border.enabled ? Options::game.width + (Options::video.border.width * 2) : Options::game.width;
|
||||
const auto WINDOW_HEIGHT = Options::video.border.enabled ? Options::game.height + (Options::video.border.height * 2) : Options::game.height;
|
||||
#ifdef __APPLE__
|
||||
SDL_WindowFlags window_flags = SDL_WINDOW_METAL;
|
||||
#else
|
||||
SDL_WindowFlags window_flags = SDL_WINDOW_OPENGL;
|
||||
#endif
|
||||
if (Options::video.fullscreen) {
|
||||
window_flags |= SDL_WINDOW_FULLSCREEN;
|
||||
}
|
||||
window_ = SDL_CreateWindow(Options::window.caption.c_str(), WINDOW_WIDTH * Options::window.zoom, WINDOW_HEIGHT * Options::window.zoom, window_flags);
|
||||
|
||||
if (window_ == nullptr) {
|
||||
std::cerr << "FATAL: Failed to create window! SDL Error: " << SDL_GetError() << '\n';
|
||||
SDL_Quit();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Crear renderer
|
||||
renderer_ = SDL_CreateRenderer(window_, nullptr);
|
||||
if (renderer_ == nullptr) {
|
||||
std::cerr << "FATAL: Failed to create renderer! SDL Error: " << SDL_GetError() << '\n';
|
||||
SDL_DestroyWindow(window_);
|
||||
window_ = nullptr;
|
||||
SDL_Quit();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Configurar renderer
|
||||
const int EXTRA_WIDTH = Options::video.border.enabled ? Options::video.border.width * 2 : 0;
|
||||
const int EXTRA_HEIGHT = Options::video.border.enabled ? Options::video.border.height * 2 : 0;
|
||||
SDL_SetRenderLogicalPresentation(
|
||||
renderer_,
|
||||
Options::game.width + EXTRA_WIDTH,
|
||||
Options::game.height + EXTRA_HEIGHT,
|
||||
Options::video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
|
||||
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
|
||||
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
|
||||
SDL_SetRenderVSync(renderer_, Options::video.vertical_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED);
|
||||
|
||||
std::cout << "Video system initialized successfully\n";
|
||||
return true;
|
||||
}
|
||||
|
||||
// Crea el objeto de texto
|
||||
void Screen::createText() {
|
||||
// Carga la surface de la fuente directamente del archivo
|
||||
auto surface = std::make_shared<Surface>(Resource::List::get()->get("aseprite.gif"));
|
||||
|
||||
// Crea el objeto de texto (el constructor de Text carga el archivo text_file internamente)
|
||||
text_ = std::make_shared<Text>(surface, Resource::List::get()->get("aseprite.txt"));
|
||||
}
|
||||
164
source/core/rendering/screen.hpp
Normal file
164
source/core/rendering/screen.hpp
Normal file
@@ -0,0 +1,164 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <cstddef> // Para size_t
|
||||
#include <memory> // Para shared_ptr, __shared_ptr_access
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "utils/utils.hpp" // Para ColorRGB
|
||||
class Surface;
|
||||
class Text;
|
||||
namespace Rendering {
|
||||
class ShaderBackend;
|
||||
}
|
||||
|
||||
class Screen {
|
||||
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
|
||||
|
||||
// Renderizado
|
||||
void clearRenderer(ColorRGB 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
|
||||
|
||||
// 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 shaders
|
||||
void nextPalette(); // Cambia a la siguiente paleta
|
||||
void previousPalette(); // Cambia a la paleta anterior
|
||||
void setPalete(); // Establece la paleta actual
|
||||
void toggleShaders(); // Cambia el estado de los shaders
|
||||
|
||||
// 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_; }
|
||||
|
||||
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
|
||||
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
// Constantes
|
||||
static constexpr int WINDOWS_DECORATIONS = 35; // Decoraciones de la ventana
|
||||
|
||||
// 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 loadShaders(); // Carga el contenido del archivo GLSL
|
||||
void renderInfo(); // 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();
|
||||
|
||||
// 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
|
||||
|
||||
// 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
|
||||
|
||||
// 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::string vertex_shader_source_; // Almacena el vertex shader
|
||||
std::string fragment_shader_source_; // Almacena el fragment shader
|
||||
|
||||
#ifdef _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
|
||||
#endif
|
||||
};
|
||||
56
source/core/rendering/shader_backend.hpp
Normal file
56
source/core/rendering/shader_backend.hpp
Normal file
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Rendering {
|
||||
|
||||
/**
|
||||
* @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;
|
||||
|
||||
/**
|
||||
* @brief Inicializa el backend de shaders
|
||||
* @param window Ventana SDL
|
||||
* @param texture Textura de backbuffer a la que aplicar shaders
|
||||
* @param vertex_source Código fuente del vertex shader
|
||||
* @param fragment_source Código fuente del fragment shader
|
||||
* @return true si la inicialización fue exitosa
|
||||
*/
|
||||
virtual auto init(SDL_Window* window,
|
||||
SDL_Texture* texture,
|
||||
const std::string& vertex_source,
|
||||
const std::string& fragment_source) -> bool = 0;
|
||||
|
||||
/**
|
||||
* @brief Renderiza la textura con los shaders aplicados
|
||||
*/
|
||||
virtual void render() = 0;
|
||||
|
||||
/**
|
||||
* @brief Establece el tamaño de la textura como parámetro del shader
|
||||
* @param width Ancho de la textura
|
||||
* @param height Alto de la textura
|
||||
*/
|
||||
virtual void setTextureSize(float width, float height) = 0;
|
||||
|
||||
/**
|
||||
* @brief Limpia y libera recursos del backend
|
||||
*/
|
||||
virtual void cleanup() = 0;
|
||||
|
||||
/**
|
||||
* @brief Verifica si el backend está usando aceleración por hardware
|
||||
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
|
||||
*/
|
||||
[[nodiscard]] virtual auto isHardwareAccelerated() const -> bool = 0;
|
||||
};
|
||||
|
||||
} // namespace Rendering
|
||||
567
source/core/rendering/surface.cpp
Normal file
567
source/core/rendering/surface.cpp
Normal file
@@ -0,0 +1,567 @@
|
||||
// IWYU pragma: no_include <bits/std_abs.h>
|
||||
#include "core/rendering/surface.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // Para min, max, copy_n, fill
|
||||
#include <cmath> // Para abs
|
||||
#include <cstdint> // Para uint32_t
|
||||
#include <cstring> // Para memcpy, size_t
|
||||
#include <fstream> // Para basic_ifstream, basic_ostream, basic_ist...
|
||||
#include <iostream> // Para cerr
|
||||
#include <memory> // Para shared_ptr, __shared_ptr_access, default...
|
||||
#include <sstream> // Para basic_istringstream
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/rendering/gif.hpp" // Para Gif
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||
|
||||
// Carga una paleta desde un archivo .gif
|
||||
auto loadPalette(const std::string& file_path) -> Palette {
|
||||
// Load file using ResourceHelper (supports both filesystem and pack)
|
||||
auto buffer = Resource::Helper::loadFile(file_path);
|
||||
if (buffer.empty()) {
|
||||
throw std::runtime_error("Error opening file: " + file_path);
|
||||
}
|
||||
|
||||
// Cargar la paleta usando los datos del buffer
|
||||
std::vector<uint32_t> pal = GIF::Gif::loadPalette(buffer.data());
|
||||
if (pal.empty()) {
|
||||
throw std::runtime_error("No palette found in GIF file: " + file_path);
|
||||
}
|
||||
|
||||
// Crear la paleta y copiar los datos desde 'pal'
|
||||
Palette palette = {}; // Inicializa la paleta con ceros
|
||||
std::copy_n(pal.begin(), std::min(pal.size(), palette.size()), palette.begin());
|
||||
|
||||
// Mensaje de depuración
|
||||
printWithDots("Palette : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
||||
|
||||
return palette;
|
||||
}
|
||||
|
||||
// Carga una paleta desde un archivo .pal
|
||||
auto readPalFile(const std::string& file_path) -> Palette {
|
||||
Palette palette{};
|
||||
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)
|
||||
|
||||
// Load file using ResourceHelper (supports both filesystem and pack)
|
||||
auto file_data = Resource::Helper::loadFile(file_path);
|
||||
if (file_data.empty()) {
|
||||
throw std::runtime_error("No se pudo abrir el archivo .pal: " + file_path);
|
||||
}
|
||||
|
||||
// Convert bytes to string for parsing
|
||||
std::string content(file_data.begin(), file_data.end());
|
||||
std::istringstream stream(content);
|
||||
|
||||
std::string line;
|
||||
int line_number = 0;
|
||||
int color_index = 0;
|
||||
|
||||
while (std::getline(stream, line)) {
|
||||
++line_number;
|
||||
|
||||
// Ignorar las tres primeras líneas del archivo
|
||||
if (line_number <= 3) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Procesar las líneas restantes con valores RGB
|
||||
std::istringstream ss(line);
|
||||
int r;
|
||||
int g;
|
||||
int b;
|
||||
if (ss >> r >> g >> b) {
|
||||
// Construir el color ARGB (A = 255 por defecto)
|
||||
Uint32 color = (255 << 24) | (r << 16) | (g << 8) | b;
|
||||
palette[color_index++] = color;
|
||||
|
||||
// Limitar a un máximo de 256 colores (opcional)
|
||||
if (color_index >= 256) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printWithDots("Palette : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
||||
return palette;
|
||||
}
|
||||
|
||||
// Constructor
|
||||
Surface::Surface(int w, int h)
|
||||
: surface_data_(std::make_shared<SurfaceData>(w, h)),
|
||||
transparent_color_(Color::index(Color::Cpc::TRANSPARENT)) { initializeSubPalette(sub_palette_); }
|
||||
|
||||
Surface::Surface(const std::string& file_path)
|
||||
: transparent_color_(Color::index(Color::Cpc::TRANSPARENT)) {
|
||||
SurfaceData loaded_data = loadSurface(file_path);
|
||||
surface_data_ = std::make_shared<SurfaceData>(std::move(loaded_data));
|
||||
|
||||
initializeSubPalette(sub_palette_);
|
||||
}
|
||||
|
||||
// Carga una superficie desde un archivo
|
||||
auto Surface::loadSurface(const std::string& file_path) -> SurfaceData {
|
||||
// Load file using ResourceHelper (supports both filesystem and pack)
|
||||
std::vector<Uint8> buffer = Resource::Helper::loadFile(file_path);
|
||||
if (buffer.empty()) {
|
||||
std::cerr << "Error opening file: " << file_path << '\n';
|
||||
throw std::runtime_error("Error opening file");
|
||||
}
|
||||
|
||||
// Crear un objeto Gif y llamar a la función loadGif
|
||||
Uint16 w = 0;
|
||||
Uint16 h = 0;
|
||||
std::vector<Uint8> raw_pixels = GIF::Gif::loadGif(buffer.data(), w, h);
|
||||
if (raw_pixels.empty()) {
|
||||
std::cerr << "Error loading GIF from file: " << file_path << '\n';
|
||||
throw std::runtime_error("Error loading GIF");
|
||||
}
|
||||
|
||||
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>,
|
||||
// reservamos un bloque dinámico y copiamos los datos del vector.
|
||||
size_t pixel_count = raw_pixels.size();
|
||||
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>());
|
||||
std::memcpy(pixels.get(), raw_pixels.data(), pixel_count);
|
||||
|
||||
// Crear y devolver directamente el objeto SurfaceData
|
||||
printWithDots("Surface : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
||||
return {static_cast<float>(w), static_cast<float>(h), pixels};
|
||||
}
|
||||
|
||||
// Carga una paleta desde un archivo
|
||||
void Surface::loadPalette(const std::string& file_path) {
|
||||
palette_ = ::loadPalette(file_path);
|
||||
}
|
||||
|
||||
// Carga una paleta desde otra paleta
|
||||
void Surface::loadPalette(const Palette& palette) {
|
||||
palette_ = palette;
|
||||
}
|
||||
|
||||
// Establece un color en la paleta
|
||||
void Surface::setColor(int index, Uint32 color) {
|
||||
palette_.at(index) = color;
|
||||
}
|
||||
|
||||
// Rellena la superficie con un color
|
||||
void Surface::clear(Uint8 color) {
|
||||
const size_t TOTAL_PIXELS = surface_data_->width * surface_data_->height;
|
||||
Uint8* data_ptr = surface_data_->data.get();
|
||||
std::fill(data_ptr, data_ptr + TOTAL_PIXELS, color);
|
||||
}
|
||||
|
||||
// Pone un pixel en la SurfaceData
|
||||
void Surface::putPixel(int x, int y, Uint8 color) {
|
||||
if (x < 0 || y < 0 || x >= surface_data_->width || y >= surface_data_->height) {
|
||||
return; // Coordenadas fuera de rango
|
||||
}
|
||||
|
||||
const int INDEX = x + (y * surface_data_->width);
|
||||
surface_data_->data.get()[INDEX] = color;
|
||||
}
|
||||
|
||||
// Obtiene el color de un pixel de la surface_data
|
||||
auto Surface::getPixel(int x, int y) -> Uint8 { return surface_data_->data.get()[x + (y * static_cast<int>(surface_data_->width))]; }
|
||||
|
||||
// Dibuja un rectangulo relleno
|
||||
void Surface::fillRect(const SDL_FRect* rect, Uint8 color) {
|
||||
// Limitar los valores del rectángulo al tamaño de la superficie
|
||||
float x_start = std::max(0.0F, rect->x);
|
||||
float y_start = std::max(0.0F, rect->y);
|
||||
float x_end = std::min(rect->x + rect->w, surface_data_->width);
|
||||
float y_end = std::min(rect->y + rect->h, surface_data_->height);
|
||||
|
||||
// Recorrer cada píxel dentro del rectángulo directamente
|
||||
for (int y = y_start; y < y_end; ++y) {
|
||||
for (int x = x_start; x < x_end; ++x) {
|
||||
const int INDEX = x + (y * surface_data_->width);
|
||||
surface_data_->data.get()[INDEX] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja el borde de un rectangulo
|
||||
void Surface::drawRectBorder(const SDL_FRect* rect, Uint8 color) {
|
||||
// Limitar los valores del rectángulo al tamaño de la superficie
|
||||
float x_start = std::max(0.0F, rect->x);
|
||||
float y_start = std::max(0.0F, rect->y);
|
||||
float x_end = std::min(rect->x + rect->w, surface_data_->width);
|
||||
float y_end = std::min(rect->y + rect->h, surface_data_->height);
|
||||
|
||||
// Dibujar bordes horizontales
|
||||
for (int x = x_start; x < x_end; ++x) {
|
||||
// Borde superior
|
||||
const int TOP_INDEX = x + (y_start * surface_data_->width);
|
||||
surface_data_->data.get()[TOP_INDEX] = color;
|
||||
|
||||
// Borde inferior
|
||||
const int BOTTOM_INDEX = x + ((y_end - 1) * surface_data_->width);
|
||||
surface_data_->data.get()[BOTTOM_INDEX] = color;
|
||||
}
|
||||
|
||||
// Dibujar bordes verticales
|
||||
for (int y = y_start; y < y_end; ++y) {
|
||||
// Borde izquierdo
|
||||
const int LEFT_INDEX = x_start + (y * surface_data_->width);
|
||||
surface_data_->data.get()[LEFT_INDEX] = color;
|
||||
|
||||
// Borde derecho
|
||||
const int RIGHT_INDEX = (x_end - 1) + (y * surface_data_->width);
|
||||
surface_data_->data.get()[RIGHT_INDEX] = color;
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja una linea
|
||||
void Surface::drawLine(float x1, float y1, float x2, float y2, Uint8 color) {
|
||||
// Calcula las diferencias
|
||||
float dx = std::abs(x2 - x1);
|
||||
float dy = std::abs(y2 - y1);
|
||||
|
||||
// Determina la dirección del incremento
|
||||
float sx = (x1 < x2) ? 1 : -1;
|
||||
float sy = (y1 < y2) ? 1 : -1;
|
||||
|
||||
float err = dx - dy;
|
||||
|
||||
while (true) {
|
||||
// Asegúrate de no dibujar fuera de los límites de la superficie
|
||||
if (x1 >= 0 && x1 < surface_data_->width && y1 >= 0 && y1 < surface_data_->height) {
|
||||
surface_data_->data.get()[static_cast<size_t>(x1 + (y1 * surface_data_->width))] = color;
|
||||
}
|
||||
|
||||
// Si alcanzamos el punto final, salimos
|
||||
if (x1 == x2 && y1 == y2) {
|
||||
break;
|
||||
}
|
||||
|
||||
int e2 = 2 * err;
|
||||
if (e2 > -dy) {
|
||||
err -= dy;
|
||||
x1 += sx;
|
||||
}
|
||||
if (e2 < dx) {
|
||||
err += dx;
|
||||
y1 += sy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Surface::render(float dx, float dy, float sx, float sy, float w, float h) {
|
||||
auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData();
|
||||
|
||||
// Limitar la región para evitar accesos fuera de rango en origen
|
||||
w = std::min(w, surface_data_->width - sx);
|
||||
h = std::min(h, surface_data_->height - sy);
|
||||
|
||||
// Limitar la región para evitar accesos fuera de rango en destino
|
||||
w = std::min(w, surface_data->width - dx);
|
||||
h = std::min(h, surface_data->height - dy);
|
||||
|
||||
for (int iy = 0; iy < h; ++iy) {
|
||||
for (int ix = 0; ix < w; ++ix) {
|
||||
// Verificar que las coordenadas de destino están dentro de los límites
|
||||
if (int dest_x = dx + ix; dest_x >= 0 && dest_x < surface_data->width) {
|
||||
if (int dest_y = dy + iy; dest_y >= 0 && dest_y < surface_data->height) {
|
||||
int src_x = sx + ix;
|
||||
int src_y = sy + iy;
|
||||
|
||||
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
|
||||
if (color != transparent_color_) {
|
||||
surface_data->data.get()[static_cast<size_t>(dest_x + (dest_y * surface_data->width))] = sub_palette_[color];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Surface::render(int x, int y, SDL_FRect* src_rect, SDL_FlipMode flip) {
|
||||
auto surface_data_dest = Screen::get()->getRendererSurface()->getSurfaceData();
|
||||
|
||||
// Determina la región de origen (clip) a renderizar
|
||||
float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
|
||||
float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
|
||||
float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
|
||||
float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
|
||||
|
||||
// Limitar la región para evitar accesos fuera de rango en origen
|
||||
w = std::min(w, surface_data_->width - sx);
|
||||
h = std::min(h, surface_data_->height - sy);
|
||||
w = std::min(w, surface_data_dest->width - x);
|
||||
h = std::min(h, surface_data_dest->height - y);
|
||||
|
||||
// Limitar la región para evitar accesos fuera de rango en destino
|
||||
w = std::min(w, surface_data_dest->width - x);
|
||||
h = std::min(h, surface_data_dest->height - y);
|
||||
|
||||
// Renderiza píxel por píxel aplicando el flip si es necesario
|
||||
for (int iy = 0; iy < h; ++iy) {
|
||||
for (int ix = 0; ix < w; ++ix) {
|
||||
// Coordenadas de origen
|
||||
int src_x = (flip == SDL_FLIP_HORIZONTAL) ? (sx + w - 1 - ix) : (sx + ix);
|
||||
int src_y = (flip == SDL_FLIP_VERTICAL) ? (sy + h - 1 - iy) : (sy + iy);
|
||||
|
||||
// Coordenadas de destino
|
||||
int dest_x = x + ix;
|
||||
int dest_y = y + iy;
|
||||
|
||||
// Verificar que las coordenadas de destino están dentro de los límites
|
||||
if (dest_x >= 0 && dest_x < surface_data_dest->width && dest_y >= 0 && dest_y < surface_data_dest->height) {
|
||||
// Copia el píxel si no es transparente
|
||||
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
|
||||
if (color != transparent_color_) {
|
||||
surface_data_dest->data[dest_x + (dest_y * surface_data_dest->width)] = sub_palette_[color];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper para calcular coordenadas con flip
|
||||
void Surface::calculateFlippedCoords(int ix, int iy, float sx, float sy, float w, float h, SDL_FlipMode flip, int& src_x, int& src_y) {
|
||||
src_x = (flip == SDL_FLIP_HORIZONTAL) ? (sx + w - 1 - ix) : (sx + ix);
|
||||
src_y = (flip == SDL_FLIP_VERTICAL) ? (sy + h - 1 - iy) : (sy + iy);
|
||||
}
|
||||
|
||||
// Helper para copiar un pixel si no es transparente
|
||||
void Surface::copyPixelIfNotTransparent(Uint8* dest_data, int dest_x, int dest_y, int dest_width, int src_x, int src_y) const {
|
||||
if (dest_x < 0 || dest_y < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
|
||||
if (color != transparent_color_) {
|
||||
dest_data[dest_x + (dest_y * dest_width)] = sub_palette_[color];
|
||||
}
|
||||
}
|
||||
|
||||
// Copia una región de la superficie de origen a la de destino
|
||||
void Surface::render(SDL_FRect* src_rect, SDL_FRect* dst_rect, SDL_FlipMode flip) {
|
||||
auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData();
|
||||
|
||||
// Si srcRect es nullptr, tomar toda la superficie fuente
|
||||
float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
|
||||
float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
|
||||
float sw = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
|
||||
float sh = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
|
||||
|
||||
// Si dstRect es nullptr, asignar las mismas dimensiones que srcRect
|
||||
float dx = ((dst_rect) != nullptr) ? dst_rect->x : 0;
|
||||
float dy = ((dst_rect) != nullptr) ? dst_rect->y : 0;
|
||||
float dw = ((dst_rect) != nullptr) ? dst_rect->w : sw;
|
||||
float dh = ((dst_rect) != nullptr) ? dst_rect->h : sh;
|
||||
|
||||
// Asegurarse de que srcRect y dstRect tienen las mismas dimensiones
|
||||
if (sw != dw || sh != dh) {
|
||||
dw = sw; // Respetar las dimensiones de srcRect
|
||||
dh = sh;
|
||||
}
|
||||
|
||||
// Limitar la región para evitar accesos fuera de rango en src y dst
|
||||
sw = std::min(sw, surface_data_->width - sx);
|
||||
sh = std::min(sh, surface_data_->height - sy);
|
||||
dw = std::min(dw, surface_data->width - dx);
|
||||
dh = std::min(dh, surface_data->height - dy);
|
||||
|
||||
int final_width = std::min(sw, dw);
|
||||
int final_height = std::min(sh, dh);
|
||||
|
||||
// Renderiza píxel por píxel aplicando el flip si es necesario
|
||||
for (int iy = 0; iy < final_height; ++iy) {
|
||||
for (int ix = 0; ix < final_width; ++ix) {
|
||||
int src_x = 0;
|
||||
int src_y = 0;
|
||||
calculateFlippedCoords(ix, iy, sx, sy, final_width, final_height, flip, src_x, src_y);
|
||||
|
||||
int dest_x = dx + ix;
|
||||
int dest_y = dy + iy;
|
||||
|
||||
// Verificar límites de destino antes de copiar
|
||||
if (dest_x >= 0 && dest_x < surface_data->width && dest_y >= 0 && dest_y < surface_data->height) {
|
||||
copyPixelIfNotTransparent(surface_data->data.get(), dest_x, dest_y, surface_data->width, src_x, src_y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro
|
||||
void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect, SDL_FlipMode flip) {
|
||||
auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData();
|
||||
|
||||
// Determina la región de origen (clip) a renderizar
|
||||
float sx = ((src_rect) != nullptr) ? src_rect->x : 0;
|
||||
float sy = ((src_rect) != nullptr) ? src_rect->y : 0;
|
||||
float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width;
|
||||
float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height;
|
||||
|
||||
// Limitar la región para evitar accesos fuera de rango
|
||||
w = std::min(w, surface_data_->width - sx);
|
||||
h = std::min(h, surface_data_->height - sy);
|
||||
|
||||
// Renderiza píxel por píxel aplicando el flip si es necesario
|
||||
for (int iy = 0; iy < h; ++iy) {
|
||||
for (int ix = 0; ix < w; ++ix) {
|
||||
// Coordenadas de origen
|
||||
int src_x = (flip == SDL_FLIP_HORIZONTAL) ? (sx + w - 1 - ix) : (sx + ix);
|
||||
int src_y = (flip == SDL_FLIP_VERTICAL) ? (sy + h - 1 - iy) : (sy + iy);
|
||||
|
||||
// Coordenadas de destino
|
||||
int dest_x = x + ix;
|
||||
int dest_y = y + iy;
|
||||
|
||||
// Verifica que las coordenadas de destino estén dentro de los límites
|
||||
if (dest_x < 0 || dest_y < 0 || dest_x >= surface_data->width || dest_y >= surface_data->height) {
|
||||
continue; // Saltar píxeles fuera del rango del destino
|
||||
}
|
||||
|
||||
// Copia el píxel si no es transparente
|
||||
Uint8 color = surface_data_->data.get()[static_cast<size_t>(src_x + (src_y * surface_data_->width))];
|
||||
if (color != transparent_color_) {
|
||||
surface_data->data[dest_x + (dest_y * surface_data->width)] =
|
||||
(color == source_color) ? target_color : color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vuelca la superficie a una textura
|
||||
void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) {
|
||||
if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) {
|
||||
throw std::runtime_error("Renderer or texture is null.");
|
||||
}
|
||||
|
||||
if (surface_data_->width <= 0 || surface_data_->height <= 0 || (surface_data_->data == nullptr)) {
|
||||
throw std::runtime_error("Invalid surface dimensions or data.");
|
||||
}
|
||||
|
||||
Uint32* pixels = nullptr;
|
||||
int pitch = 0;
|
||||
|
||||
// Bloquea la textura para modificar los píxeles directamente
|
||||
if (!SDL_LockTexture(texture, nullptr, reinterpret_cast<void**>(&pixels), &pitch)) {
|
||||
throw std::runtime_error("Failed to lock texture: " + std::string(SDL_GetError()));
|
||||
}
|
||||
|
||||
// Convertir `pitch` de bytes a Uint32 (asegurando alineación correcta en hardware)
|
||||
int row_stride = pitch / sizeof(Uint32);
|
||||
|
||||
for (int y = 0; y < surface_data_->height; ++y) {
|
||||
for (int x = 0; x < surface_data_->width; ++x) {
|
||||
// Calcular la posición correcta en la textura teniendo en cuenta el stride
|
||||
int texture_index = (y * row_stride) + x;
|
||||
int surface_index = (y * surface_data_->width) + x;
|
||||
|
||||
pixels[texture_index] = palette_[surface_data_->data.get()[surface_index]];
|
||||
}
|
||||
}
|
||||
|
||||
SDL_UnlockTexture(texture); // Desbloquea la textura
|
||||
|
||||
// Renderiza la textura en la pantalla completa
|
||||
if (!SDL_RenderTexture(renderer, texture, nullptr, nullptr)) {
|
||||
throw std::runtime_error("Failed to copy texture to renderer: " + std::string(SDL_GetError()));
|
||||
}
|
||||
}
|
||||
|
||||
// Vuelca la superficie a una textura
|
||||
void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect) {
|
||||
if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) {
|
||||
throw std::runtime_error("Renderer or texture is null.");
|
||||
}
|
||||
|
||||
if (surface_data_->width <= 0 || surface_data_->height <= 0 || (surface_data_->data == nullptr)) {
|
||||
throw std::runtime_error("Invalid surface dimensions or data.");
|
||||
}
|
||||
|
||||
Uint32* pixels = nullptr;
|
||||
int pitch = 0;
|
||||
|
||||
SDL_Rect lock_rect;
|
||||
if (dest_rect != nullptr) {
|
||||
lock_rect.x = static_cast<int>(dest_rect->x);
|
||||
lock_rect.y = static_cast<int>(dest_rect->y);
|
||||
lock_rect.w = static_cast<int>(dest_rect->w);
|
||||
lock_rect.h = static_cast<int>(dest_rect->h);
|
||||
}
|
||||
|
||||
// Usa lockRect solo si destRect no es nulo
|
||||
if (!SDL_LockTexture(texture, (dest_rect != nullptr) ? &lock_rect : nullptr, reinterpret_cast<void**>(&pixels), &pitch)) {
|
||||
throw std::runtime_error("Failed to lock texture: " + std::string(SDL_GetError()));
|
||||
}
|
||||
|
||||
int row_stride = pitch / sizeof(Uint32);
|
||||
|
||||
for (int y = 0; y < surface_data_->height; ++y) {
|
||||
for (int x = 0; x < surface_data_->width; ++x) {
|
||||
int texture_index = (y * row_stride) + x;
|
||||
int surface_index = (y * surface_data_->width) + x;
|
||||
|
||||
pixels[texture_index] = palette_[surface_data_->data.get()[surface_index]];
|
||||
}
|
||||
}
|
||||
|
||||
SDL_UnlockTexture(texture);
|
||||
|
||||
// Renderiza la textura con los rectángulos especificados
|
||||
if (!SDL_RenderTexture(renderer, texture, src_rect, dest_rect)) {
|
||||
throw std::runtime_error("Failed to copy texture to renderer: " + std::string(SDL_GetError()));
|
||||
}
|
||||
}
|
||||
|
||||
// Realiza un efecto de fundido en la paleta principal
|
||||
auto Surface::fadePalette() -> bool {
|
||||
// Verificar que el tamaño mínimo de palette_ sea adecuado
|
||||
static constexpr int PALETTE_SIZE = 19;
|
||||
if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) {
|
||||
throw std::runtime_error("Palette size is insufficient for fadePalette operation.");
|
||||
}
|
||||
|
||||
// Desplazar colores (pares e impares)
|
||||
for (int i = 18; i > 1; --i) {
|
||||
palette_[i] = palette_[i - 2];
|
||||
}
|
||||
|
||||
// Ajustar el primer color
|
||||
palette_[1] = palette_[0];
|
||||
|
||||
// Devolver si el índice 15 coincide con el índice 0
|
||||
return palette_[15] == palette_[0];
|
||||
}
|
||||
|
||||
// Realiza un efecto de fundido en la paleta secundaria
|
||||
auto Surface::fadeSubPalette(Uint32 delay) -> bool {
|
||||
// Variable estática para almacenar el último tick
|
||||
static Uint32 last_tick_ = 0;
|
||||
|
||||
// Obtener el tiempo actual
|
||||
Uint32 current_tick = SDL_GetTicks();
|
||||
|
||||
// Verificar si ha pasado el tiempo de retardo
|
||||
if (current_tick - last_tick_ < delay) {
|
||||
return false; // No se realiza el fade
|
||||
}
|
||||
|
||||
// Actualizar el último tick
|
||||
last_tick_ = current_tick;
|
||||
|
||||
// Verificar que el tamaño mínimo de sub_palette_ sea adecuado
|
||||
static constexpr int SUB_PALETTE_SIZE = 19;
|
||||
if (sizeof(sub_palette_) / sizeof(sub_palette_[0]) < SUB_PALETTE_SIZE) {
|
||||
throw std::runtime_error("Palette size is insufficient for fadePalette operation.");
|
||||
}
|
||||
|
||||
// Desplazar colores (pares e impares)
|
||||
for (int i = 18; i > 1; --i) {
|
||||
sub_palette_[i] = sub_palette_[i - 2];
|
||||
}
|
||||
|
||||
// Ajustar el primer color
|
||||
sub_palette_[1] = sub_palette_[0];
|
||||
|
||||
// Devolver si el índice 15 coincide con el índice 0
|
||||
return sub_palette_[15] == sub_palette_[0];
|
||||
}
|
||||
140
source/core/rendering/surface.hpp
Normal file
140
source/core/rendering/surface.hpp
Normal file
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array> // Para array
|
||||
#include <memory> // Para default_delete, shared_ptr, __shared_pt...
|
||||
#include <numeric> // Para iota
|
||||
#include <string> // Para string
|
||||
#include <utility> // Para move
|
||||
|
||||
#include "utils/color.hpp" // Para Color
|
||||
|
||||
// Alias
|
||||
using Palette = std::array<Uint32, 256>;
|
||||
using SubPalette = std::array<Uint8, 256>;
|
||||
|
||||
// Carga una paleta desde un archivo .gif
|
||||
auto loadPalette(const std::string& file_path) -> Palette;
|
||||
|
||||
// Carga una paleta desde un archivo .pal
|
||||
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
|
||||
|
||||
// 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 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;
|
||||
|
||||
// Operador de movimiento
|
||||
auto operator=(SurfaceData&& other) noexcept -> SurfaceData& = default;
|
||||
|
||||
// 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
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
Surface(int w, int h);
|
||||
explicit Surface(const std::string& file_path);
|
||||
|
||||
// Destructor
|
||||
~Surface() = default;
|
||||
|
||||
// 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);
|
||||
|
||||
// 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);
|
||||
|
||||
// Establece un color en la paleta
|
||||
void setColor(int index, Uint32 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);
|
||||
|
||||
// Realiza un efecto de fundido en las paletas
|
||||
auto fadePalette() -> bool;
|
||||
auto fadeSubPalette(Uint32 delay = 0) -> bool;
|
||||
|
||||
// Pone un pixel en la SurfaceData
|
||||
void putPixel(int x, int y, Uint8 color);
|
||||
|
||||
// Obtiene el color de un pixel de la surface_data
|
||||
auto getPixel(int x, int y) -> Uint8;
|
||||
|
||||
// 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 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); }
|
||||
|
||||
// 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; }
|
||||
|
||||
// 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); }
|
||||
|
||||
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;
|
||||
};
|
||||
334
source/core/rendering/surface_animated_sprite.cpp
Normal file
334
source/core/rendering/surface_animated_sprite.cpp
Normal file
@@ -0,0 +1,334 @@
|
||||
#include "core/rendering/surface_animated_sprite.hpp"
|
||||
|
||||
#include <cstddef> // Para size_t
|
||||
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
|
||||
#include <iostream> // Para cout, cerr
|
||||
#include <sstream> // Para basic_stringstream
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <utility>
|
||||
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||
#include "external/fkyaml_node.hpp" // Para fkyaml::node
|
||||
#include "utils/utils.hpp" // Para printWithDots
|
||||
|
||||
// Helper: Convierte un nodo YAML de frames (array) a vector de SDL_FRect
|
||||
auto convertYAMLFramesToRects(const fkyaml::node& frames_node, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> std::vector<SDL_FRect> {
|
||||
std::vector<SDL_FRect> frames;
|
||||
SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height};
|
||||
|
||||
for (const auto& frame_index_node : frames_node) {
|
||||
const int NUM_TILE = frame_index_node.get_value<int>();
|
||||
if (NUM_TILE <= max_tiles) {
|
||||
rect.x = (NUM_TILE % frames_per_row) * frame_width;
|
||||
rect.y = (NUM_TILE / frames_per_row) * frame_height;
|
||||
frames.emplace_back(rect);
|
||||
}
|
||||
}
|
||||
|
||||
return frames;
|
||||
}
|
||||
|
||||
// Carga las animaciones desde un fichero YAML
|
||||
auto SurfaceAnimatedSprite::loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr<Surface>& surface, float& frame_width, float& frame_height) -> std::vector<AnimationData> {
|
||||
std::vector<AnimationData> animations;
|
||||
|
||||
// Extract filename for logging
|
||||
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
|
||||
try {
|
||||
// Load YAML file using ResourceHelper (supports both filesystem and pack)
|
||||
auto file_data = Resource::Helper::loadFile(file_path);
|
||||
|
||||
if (file_data.empty()) {
|
||||
std::cerr << "Error: Unable to load animation file " << FILE_NAME << '\n';
|
||||
throw std::runtime_error("Animation file not found: " + file_path);
|
||||
}
|
||||
|
||||
printWithDots("Animation : ", FILE_NAME, "[ LOADED ]");
|
||||
|
||||
// Parse YAML from string
|
||||
std::string yaml_content(file_data.begin(), file_data.end());
|
||||
auto yaml = fkyaml::node::deserialize(yaml_content);
|
||||
|
||||
// --- Parse global configuration ---
|
||||
if (yaml.contains("tileSetFile")) {
|
||||
auto tile_set_file = yaml["tileSetFile"].get_value<std::string>();
|
||||
surface = Resource::Cache::get()->getSurface(tile_set_file);
|
||||
}
|
||||
|
||||
if (yaml.contains("frameWidth")) {
|
||||
frame_width = static_cast<float>(yaml["frameWidth"].get_value<int>());
|
||||
}
|
||||
|
||||
if (yaml.contains("frameHeight")) {
|
||||
frame_height = static_cast<float>(yaml["frameHeight"].get_value<int>());
|
||||
}
|
||||
|
||||
// Calculate sprite sheet parameters
|
||||
int frames_per_row = 1;
|
||||
int max_tiles = 1;
|
||||
if (surface) {
|
||||
frames_per_row = surface->getWidth() / static_cast<int>(frame_width);
|
||||
const int W = surface->getWidth() / static_cast<int>(frame_width);
|
||||
const int H = surface->getHeight() / static_cast<int>(frame_height);
|
||||
max_tiles = W * H;
|
||||
}
|
||||
|
||||
// --- Parse animations array ---
|
||||
if (yaml.contains("animations") && yaml["animations"].is_sequence()) {
|
||||
const auto& animations_node = yaml["animations"];
|
||||
|
||||
for (const auto& anim_node : animations_node) {
|
||||
AnimationData animation;
|
||||
|
||||
// Parse animation name
|
||||
if (anim_node.contains("name")) {
|
||||
animation.name = anim_node["name"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Parse speed (seconds per frame)
|
||||
if (anim_node.contains("speed")) {
|
||||
animation.speed = anim_node["speed"].get_value<float>();
|
||||
}
|
||||
|
||||
// Parse loop frame index
|
||||
if (anim_node.contains("loop")) {
|
||||
animation.loop = anim_node["loop"].get_value<int>();
|
||||
}
|
||||
|
||||
// Parse frames array
|
||||
if (anim_node.contains("frames") && anim_node["frames"].is_sequence()) {
|
||||
animation.frames = convertYAMLFramesToRects(
|
||||
anim_node["frames"],
|
||||
frame_width,
|
||||
frame_height,
|
||||
frames_per_row,
|
||||
max_tiles);
|
||||
}
|
||||
|
||||
animations.push_back(animation);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (const fkyaml::exception& e) {
|
||||
std::cerr << "YAML parsing error in " << FILE_NAME << ": " << e.what() << '\n';
|
||||
throw;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error loading animation " << FILE_NAME << ": " << e.what() << '\n';
|
||||
throw;
|
||||
}
|
||||
|
||||
return animations;
|
||||
}
|
||||
|
||||
// Constructor con bytes YAML del cache (parsing lazy)
|
||||
SurfaceAnimatedSprite::SurfaceAnimatedSprite(const AnimationResource& cached_data) {
|
||||
// Parsear YAML desde los bytes cargados en cache
|
||||
std::string yaml_content(cached_data.yaml_data.begin(), cached_data.yaml_data.end());
|
||||
|
||||
try {
|
||||
auto yaml = fkyaml::node::deserialize(yaml_content);
|
||||
|
||||
// Variables para almacenar configuración global
|
||||
float frame_width = 0.0F;
|
||||
float frame_height = 0.0F;
|
||||
|
||||
// --- Parse global configuration ---
|
||||
if (yaml.contains("tileSetFile")) {
|
||||
auto tile_set_file = yaml["tileSetFile"].get_value<std::string>();
|
||||
// Ahora SÍ podemos acceder al cache (ya está completamente cargado)
|
||||
surface_ = Resource::Cache::get()->getSurface(tile_set_file);
|
||||
}
|
||||
|
||||
if (yaml.contains("frameWidth")) {
|
||||
frame_width = static_cast<float>(yaml["frameWidth"].get_value<int>());
|
||||
}
|
||||
|
||||
if (yaml.contains("frameHeight")) {
|
||||
frame_height = static_cast<float>(yaml["frameHeight"].get_value<int>());
|
||||
}
|
||||
|
||||
// Calculate sprite sheet parameters
|
||||
int frames_per_row = 1;
|
||||
int max_tiles = 1;
|
||||
if (surface_) {
|
||||
frames_per_row = surface_->getWidth() / static_cast<int>(frame_width);
|
||||
const int W = surface_->getWidth() / static_cast<int>(frame_width);
|
||||
const int H = surface_->getHeight() / static_cast<int>(frame_height);
|
||||
max_tiles = W * H;
|
||||
}
|
||||
|
||||
// --- Parse animations array ---
|
||||
if (yaml.contains("animations") && yaml["animations"].is_sequence()) {
|
||||
const auto& animations_node = yaml["animations"];
|
||||
|
||||
for (const auto& anim_node : animations_node) {
|
||||
AnimationData animation;
|
||||
|
||||
// Parse animation name
|
||||
if (anim_node.contains("name")) {
|
||||
animation.name = anim_node["name"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Parse speed (seconds per frame)
|
||||
if (anim_node.contains("speed")) {
|
||||
animation.speed = anim_node["speed"].get_value<float>();
|
||||
}
|
||||
|
||||
// Parse loop frame index
|
||||
if (anim_node.contains("loop")) {
|
||||
animation.loop = anim_node["loop"].get_value<int>();
|
||||
}
|
||||
|
||||
// Parse frames array
|
||||
if (anim_node.contains("frames") && anim_node["frames"].is_sequence()) {
|
||||
animation.frames = convertYAMLFramesToRects(
|
||||
anim_node["frames"],
|
||||
frame_width,
|
||||
frame_height,
|
||||
frames_per_row,
|
||||
max_tiles);
|
||||
}
|
||||
|
||||
animations_.push_back(animation);
|
||||
}
|
||||
}
|
||||
|
||||
// Set dimensions
|
||||
setWidth(frame_width);
|
||||
setHeight(frame_height);
|
||||
|
||||
// Inicializar con la primera animación si existe
|
||||
if (!animations_.empty() && !animations_[0].frames.empty()) {
|
||||
setClip(animations_[0].frames[0]);
|
||||
}
|
||||
|
||||
} catch (const fkyaml::exception& e) {
|
||||
std::cerr << "YAML parsing error in animation " << cached_data.name << ": " << e.what() << '\n';
|
||||
throw;
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error loading animation " << cached_data.name << ": " << e.what() << '\n';
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Obtiene el indice de la animación a partir del nombre
|
||||
auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int {
|
||||
auto index = -1;
|
||||
|
||||
for (const auto& a : animations_) {
|
||||
index++;
|
||||
if (a.name == name) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << '\n';
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Calcula el frame correspondiente a la animación (time-based)
|
||||
void SurfaceAnimatedSprite::animate(float delta_time) {
|
||||
if (animations_[current_animation_].speed <= 0.0F) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Acumula el tiempo transcurrido
|
||||
animations_[current_animation_].accumulated_time += delta_time;
|
||||
|
||||
// Calcula el frame actual a partir del tiempo acumulado
|
||||
const int TARGET_FRAME = static_cast<int>(
|
||||
animations_[current_animation_].accumulated_time /
|
||||
animations_[current_animation_].speed);
|
||||
|
||||
// Si alcanza el final de la animación, maneja el loop
|
||||
if (TARGET_FRAME >= static_cast<int>(animations_[current_animation_].frames.size())) {
|
||||
if (animations_[current_animation_].loop == -1) {
|
||||
// Si no hay loop, congela en el último frame
|
||||
animations_[current_animation_].current_frame =
|
||||
static_cast<int>(animations_[current_animation_].frames.size()) - 1;
|
||||
animations_[current_animation_].completed = true;
|
||||
|
||||
// Establece el clip del último frame
|
||||
if (animations_[current_animation_].current_frame >= 0) {
|
||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||
}
|
||||
} else {
|
||||
// Si hay loop, vuelve al frame indicado
|
||||
animations_[current_animation_].accumulated_time =
|
||||
static_cast<float>(animations_[current_animation_].loop) *
|
||||
animations_[current_animation_].speed;
|
||||
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
|
||||
|
||||
// Establece el clip del frame de loop
|
||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||
}
|
||||
} else {
|
||||
// Actualiza el frame actual
|
||||
animations_[current_animation_].current_frame = TARGET_FRAME;
|
||||
|
||||
// Establece el clip del frame actual
|
||||
if (animations_[current_animation_].current_frame >= 0 &&
|
||||
animations_[current_animation_].current_frame <
|
||||
static_cast<int>(animations_[current_animation_].frames.size())) {
|
||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si ha terminado la animación
|
||||
auto SurfaceAnimatedSprite::animationIsCompleted() -> bool {
|
||||
return animations_[current_animation_].completed;
|
||||
}
|
||||
|
||||
// Establece la animacion actual
|
||||
void SurfaceAnimatedSprite::setCurrentAnimation(const std::string& name) {
|
||||
const auto NEW_ANIMATION = getIndex(name);
|
||||
if (current_animation_ != NEW_ANIMATION) {
|
||||
current_animation_ = NEW_ANIMATION;
|
||||
animations_[current_animation_].current_frame = 0;
|
||||
animations_[current_animation_].accumulated_time = 0.0F;
|
||||
animations_[current_animation_].completed = false;
|
||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||
}
|
||||
}
|
||||
|
||||
// Establece la animacion actual
|
||||
void SurfaceAnimatedSprite::setCurrentAnimation(int index) {
|
||||
const auto NEW_ANIMATION = index;
|
||||
if (current_animation_ != NEW_ANIMATION) {
|
||||
current_animation_ = NEW_ANIMATION;
|
||||
animations_[current_animation_].current_frame = 0;
|
||||
animations_[current_animation_].accumulated_time = 0.0F;
|
||||
animations_[current_animation_].completed = false;
|
||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza las variables del objeto (time-based)
|
||||
void SurfaceAnimatedSprite::update(float delta_time) {
|
||||
animate(delta_time);
|
||||
SurfaceMovingSprite::update(delta_time);
|
||||
}
|
||||
|
||||
// Reinicia la animación
|
||||
void SurfaceAnimatedSprite::resetAnimation() {
|
||||
animations_[current_animation_].current_frame = 0;
|
||||
animations_[current_animation_].accumulated_time = 0.0F;
|
||||
animations_[current_animation_].completed = false;
|
||||
}
|
||||
|
||||
// Establece el frame actual de la animación
|
||||
void SurfaceAnimatedSprite::setCurrentAnimationFrame(int num) {
|
||||
// Descarta valores fuera de rango
|
||||
if (num < 0 || num >= static_cast<int>(animations_[current_animation_].frames.size())) {
|
||||
num = 0;
|
||||
}
|
||||
|
||||
// Cambia el valor de la variable
|
||||
animations_[current_animation_].current_frame = num;
|
||||
|
||||
// Escoge el frame correspondiente de la animación
|
||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||
}
|
||||
59
source/core/rendering/surface_animated_sprite.hpp
Normal file
59
source/core/rendering/surface_animated_sprite.hpp
Normal file
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite
|
||||
#include "core/resources/resource_types.hpp" // Para AnimationResource
|
||||
|
||||
class Surface;
|
||||
|
||||
class SurfaceAnimatedSprite : public SurfaceMovingSprite {
|
||||
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)
|
||||
};
|
||||
|
||||
// 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
|
||||
|
||||
~SurfaceAnimatedSprite() override = default; // Destructor
|
||||
|
||||
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
|
||||
|
||||
// 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:
|
||||
// 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
|
||||
};
|
||||
103
source/core/rendering/surface_moving_sprite.cpp
Normal file
103
source/core/rendering/surface_moving_sprite.cpp
Normal file
@@ -0,0 +1,103 @@
|
||||
#include "core/rendering/surface_moving_sprite.hpp"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
|
||||
// Constructor
|
||||
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos, SDL_FlipMode flip)
|
||||
: SurfaceSprite(std::move(surface), pos),
|
||||
x_(pos.x),
|
||||
y_(pos.y),
|
||||
flip_(flip) { SurfaceSprite::pos_ = pos; }
|
||||
|
||||
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface, SDL_FRect pos)
|
||||
: SurfaceSprite(std::move(surface), pos),
|
||||
x_(pos.x),
|
||||
y_(pos.y) { SurfaceSprite::pos_ = pos; }
|
||||
|
||||
SurfaceMovingSprite::SurfaceMovingSprite() { SurfaceSprite::clear(); }
|
||||
|
||||
SurfaceMovingSprite::SurfaceMovingSprite(std::shared_ptr<Surface> surface)
|
||||
: SurfaceSprite(std::move(surface)) { SurfaceSprite::clear(); }
|
||||
|
||||
// Reinicia todas las variables
|
||||
void SurfaceMovingSprite::clear() {
|
||||
// Resetea posición
|
||||
x_ = 0.0F;
|
||||
y_ = 0.0F;
|
||||
|
||||
// Resetea velocidad
|
||||
vx_ = 0.0F;
|
||||
vy_ = 0.0F;
|
||||
|
||||
// Resetea aceleración
|
||||
ax_ = 0.0F;
|
||||
ay_ = 0.0F;
|
||||
|
||||
// Resetea flip
|
||||
flip_ = SDL_FLIP_NONE;
|
||||
|
||||
SurfaceSprite::clear();
|
||||
}
|
||||
|
||||
// Mueve el sprite (time-based)
|
||||
// Nota: vx_, vy_ ahora se interpretan como pixels/segundo
|
||||
// Nota: ax_, ay_ ahora se interpretan como pixels/segundo²
|
||||
void SurfaceMovingSprite::move(float delta_time) {
|
||||
// Aplica aceleración a velocidad (time-based)
|
||||
vx_ += ax_ * delta_time;
|
||||
vy_ += ay_ * delta_time;
|
||||
|
||||
// Aplica velocidad a posición (time-based)
|
||||
x_ += vx_ * delta_time;
|
||||
y_ += vy_ * delta_time;
|
||||
|
||||
// Actualiza posición entera para renderizado
|
||||
pos_.x = static_cast<int>(x_);
|
||||
pos_.y = static_cast<int>(y_);
|
||||
}
|
||||
|
||||
// Actualiza las variables internas del objeto (time-based)
|
||||
void SurfaceMovingSprite::update(float delta_time) {
|
||||
move(delta_time);
|
||||
}
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void SurfaceMovingSprite::render() {
|
||||
surface_->render(pos_.x, pos_.y, &clip_, flip_);
|
||||
}
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void SurfaceMovingSprite::render(Uint8 source_color, Uint8 target_color) {
|
||||
surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_, flip_);
|
||||
}
|
||||
|
||||
// Establece la posición y_ el tamaño del objeto
|
||||
void SurfaceMovingSprite::setPos(SDL_FRect rect) {
|
||||
x_ = rect.x;
|
||||
y_ = rect.y;
|
||||
|
||||
pos_ = rect;
|
||||
}
|
||||
|
||||
// Establece el valor de las variables
|
||||
void SurfaceMovingSprite::setPos(float x, float y) {
|
||||
x_ = x;
|
||||
y_ = y;
|
||||
|
||||
pos_.x = static_cast<int>(x_);
|
||||
pos_.y = static_cast<int>(y_);
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void SurfaceMovingSprite::setPosX(float value) {
|
||||
x_ = value;
|
||||
pos_.x = static_cast<int>(x_);
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void SurfaceMovingSprite::setPosY(float value) {
|
||||
y_ = value;
|
||||
pos_.y = static_cast<int>(y_);
|
||||
}
|
||||
77
source/core/rendering/surface_moving_sprite.hpp
Normal file
77
source/core/rendering/surface_moving_sprite.hpp
Normal file
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
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;
|
||||
|
||||
// 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
|
||||
|
||||
// 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 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 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; }
|
||||
|
||||
// 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)
|
||||
|
||||
// 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 - 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
|
||||
};
|
||||
56
source/core/rendering/surface_sprite.cpp
Normal file
56
source/core/rendering/surface_sprite.cpp
Normal file
@@ -0,0 +1,56 @@
|
||||
#include "core/rendering/surface_sprite.hpp"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
|
||||
// Constructor
|
||||
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, float x, float y, float w, float h)
|
||||
: surface_(std::move(surface)),
|
||||
pos_{x, y, w, h},
|
||||
clip_{0.0F, 0.0F, pos_.w, pos_.h} {}
|
||||
|
||||
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface, SDL_FRect rect)
|
||||
: surface_(std::move(surface)),
|
||||
pos_(rect),
|
||||
clip_{0.0F, 0.0F, pos_.w, pos_.h} {}
|
||||
|
||||
SurfaceSprite::SurfaceSprite() = default;
|
||||
|
||||
SurfaceSprite::SurfaceSprite(std::shared_ptr<Surface> surface)
|
||||
: surface_(std::move(surface)),
|
||||
pos_{0.0F, 0.0F, surface_->getWidth(), surface_->getHeight()},
|
||||
clip_(pos_) {}
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void SurfaceSprite::render() {
|
||||
surface_->render(pos_.x, pos_.y, &clip_);
|
||||
}
|
||||
|
||||
void SurfaceSprite::render(Uint8 source_color, Uint8 target_color) {
|
||||
surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_);
|
||||
}
|
||||
|
||||
// Establece la posición del objeto
|
||||
void SurfaceSprite::setPosition(float x, float y) {
|
||||
pos_.x = x;
|
||||
pos_.y = y;
|
||||
}
|
||||
|
||||
// Establece la posición del objeto
|
||||
void SurfaceSprite::setPosition(SDL_FPoint p) {
|
||||
pos_.x = p.x;
|
||||
pos_.y = p.y;
|
||||
}
|
||||
|
||||
// Reinicia las variables a cero
|
||||
void SurfaceSprite::clear() {
|
||||
pos_ = {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F};
|
||||
clip_ = {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F};
|
||||
}
|
||||
|
||||
// Actualiza el estado del sprite (time-based)
|
||||
void SurfaceSprite::update(float delta_time) {
|
||||
// Base implementation does nothing (static sprites)
|
||||
(void)delta_time; // Evita warning de parámetro no usado
|
||||
}
|
||||
60
source/core/rendering/surface_sprite.hpp
Normal file
60
source/core/rendering/surface_sprite.hpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <utility>
|
||||
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>);
|
||||
|
||||
// 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
|
||||
|
||||
// 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_; }
|
||||
|
||||
// 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); }
|
||||
|
||||
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
|
||||
};
|
||||
239
source/core/rendering/text.cpp
Normal file
239
source/core/rendering/text.cpp
Normal file
@@ -0,0 +1,239 @@
|
||||
#include "core/rendering/text.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <cstddef> // Para size_t
|
||||
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
|
||||
#include <iostream> // Para cerr
|
||||
#include <sstream> // Para istringstream
|
||||
#include <stdexcept> // Para runtime_error
|
||||
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
|
||||
|
||||
// Llena una estructuta TextFile desde un fichero
|
||||
auto Text::loadTextFile(const std::string& file_path) -> std::shared_ptr<File> {
|
||||
auto tf = std::make_shared<File>();
|
||||
|
||||
// No es necesario inicializar - los miembros tienen valores por defecto
|
||||
|
||||
// Load file using ResourceHelper (supports both filesystem and pack)
|
||||
auto file_data = Resource::Helper::loadFile(file_path);
|
||||
if (file_data.empty()) {
|
||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
|
||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||
}
|
||||
|
||||
// Convert bytes to string and parse
|
||||
std::string content(file_data.begin(), file_data.end());
|
||||
std::istringstream stream(content);
|
||||
std::string buffer;
|
||||
|
||||
// Lee los dos primeros valores del fichero
|
||||
std::getline(stream, buffer);
|
||||
// Remove Windows line ending if present
|
||||
if (!buffer.empty() && buffer.back() == '\r') {
|
||||
buffer.pop_back();
|
||||
}
|
||||
std::getline(stream, buffer);
|
||||
// Remove Windows line ending if present
|
||||
if (!buffer.empty() && buffer.back() == '\r') {
|
||||
buffer.pop_back();
|
||||
}
|
||||
tf->box_width = std::stoi(buffer);
|
||||
|
||||
std::getline(stream, buffer);
|
||||
// Remove Windows line ending if present
|
||||
if (!buffer.empty() && buffer.back() == '\r') {
|
||||
buffer.pop_back();
|
||||
}
|
||||
std::getline(stream, buffer);
|
||||
// Remove Windows line ending if present
|
||||
if (!buffer.empty() && buffer.back() == '\r') {
|
||||
buffer.pop_back();
|
||||
}
|
||||
tf->box_height = std::stoi(buffer);
|
||||
|
||||
// lee el resto de datos del fichero
|
||||
auto index = 32;
|
||||
auto line_read = 0;
|
||||
while (std::getline(stream, buffer)) {
|
||||
// Remove Windows line ending if present
|
||||
if (!buffer.empty() && buffer.back() == '\r') {
|
||||
buffer.pop_back();
|
||||
}
|
||||
// Almacena solo las lineas impares
|
||||
if (line_read % 2 == 1) {
|
||||
tf->offset[index++].w = std::stoi(buffer);
|
||||
}
|
||||
|
||||
// Limpia el buffer
|
||||
buffer.clear();
|
||||
line_read++;
|
||||
};
|
||||
|
||||
printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]");
|
||||
|
||||
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho
|
||||
for (int i = 32; i < 128; ++i) {
|
||||
tf->offset[i].x = ((i - 32) % 15) * tf->box_width;
|
||||
tf->offset[i].y = ((i - 32) / 15) * tf->box_height;
|
||||
}
|
||||
|
||||
return tf;
|
||||
}
|
||||
|
||||
// Constructor
|
||||
Text::Text(const std::shared_ptr<Surface>& surface, const std::string& text_file) {
|
||||
// Carga los offsets desde el fichero
|
||||
auto tf = loadTextFile(text_file);
|
||||
|
||||
// Inicializa variables desde la estructura
|
||||
box_height_ = tf->box_height;
|
||||
box_width_ = tf->box_width;
|
||||
offset_ = tf->offset;
|
||||
|
||||
// Crea los objetos
|
||||
sprite_ = std::make_unique<SurfaceSprite>(surface, (SDL_FRect){0.0F, 0.0F, static_cast<float>(box_width_), static_cast<float>(box_height_)});
|
||||
}
|
||||
|
||||
// Constructor
|
||||
Text::Text(const std::shared_ptr<Surface>& surface, const std::shared_ptr<File>& text_file)
|
||||
: sprite_(std::make_unique<SurfaceSprite>(surface, (SDL_FRect){0.0F, 0.0F, static_cast<float>(text_file->box_width), static_cast<float>(text_file->box_height)})),
|
||||
box_width_(text_file->box_width),
|
||||
box_height_(text_file->box_height),
|
||||
offset_(text_file->offset) {
|
||||
}
|
||||
|
||||
// Escribe texto en pantalla
|
||||
void Text::write(int x, int y, const std::string& text, int kerning, int lenght) {
|
||||
int shift = 0;
|
||||
|
||||
if (lenght == -1) {
|
||||
lenght = text.length();
|
||||
}
|
||||
|
||||
sprite_->setY(y);
|
||||
for (int i = 0; i < lenght; ++i) {
|
||||
auto index = static_cast<int>(text[i]);
|
||||
sprite_->setClip(offset_[index].x, offset_[index].y, box_width_, box_height_);
|
||||
sprite_->setX(x + shift);
|
||||
sprite_->render(1, 15);
|
||||
shift += offset_[static_cast<int>(text[i])].w + kerning;
|
||||
}
|
||||
}
|
||||
|
||||
// Escribe el texto en una surface
|
||||
auto Text::writeToSurface(const std::string& text, int zoom, int kerning) -> std::shared_ptr<Surface> {
|
||||
auto width = length(text, kerning) * zoom;
|
||||
auto height = box_height_ * zoom;
|
||||
auto surface = std::make_shared<Surface>(width, height);
|
||||
auto previuos_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(surface);
|
||||
surface->clear(stringToColor("transparent"));
|
||||
write(0, 0, text, kerning);
|
||||
Screen::get()->setRendererSurface(previuos_renderer);
|
||||
|
||||
return surface;
|
||||
}
|
||||
|
||||
// Escribe el texto con extras en una surface
|
||||
auto Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) -> std::shared_ptr<Surface> {
|
||||
auto width = Text::length(text, kerning) + shadow_distance;
|
||||
auto height = box_height_ + shadow_distance;
|
||||
auto surface = std::make_shared<Surface>(width, height);
|
||||
auto previuos_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(surface);
|
||||
surface->clear(stringToColor("transparent"));
|
||||
writeDX(flags, 0, 0, text, kerning, text_color, shadow_distance, shadow_color, lenght);
|
||||
Screen::get()->setRendererSurface(previuos_renderer);
|
||||
|
||||
return surface;
|
||||
}
|
||||
|
||||
// Escribe el texto con colores
|
||||
void Text::writeColored(int x, int y, const std::string& text, Uint8 color, int kerning, int lenght) {
|
||||
int shift = 0;
|
||||
|
||||
if (lenght == -1) {
|
||||
lenght = text.length();
|
||||
}
|
||||
|
||||
sprite_->setY(y);
|
||||
for (int i = 0; i < lenght; ++i) {
|
||||
auto index = static_cast<int>(text[i]);
|
||||
sprite_->setClip(offset_[index].x, offset_[index].y, box_width_, box_height_);
|
||||
sprite_->setX(x + shift);
|
||||
sprite_->render(1, color);
|
||||
shift += offset_[static_cast<int>(text[i])].w + kerning;
|
||||
}
|
||||
}
|
||||
|
||||
// Escribe el texto con sombra
|
||||
void Text::writeShadowed(int x, int y, const std::string& text, Uint8 color, Uint8 shadow_distance, int kerning, int lenght) {
|
||||
writeColored(x + shadow_distance, y + shadow_distance, text, color, kerning, lenght);
|
||||
write(x, y, text, kerning, lenght);
|
||||
}
|
||||
|
||||
// Escribe el texto centrado en un punto x
|
||||
void Text::writeCentered(int x, int y, const std::string& text, int kerning, int lenght) {
|
||||
x -= (Text::length(text, kerning) / 2);
|
||||
write(x, y, text, kerning, lenght);
|
||||
}
|
||||
|
||||
// Escribe texto con extras
|
||||
void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) {
|
||||
const auto CENTERED = ((flags & CENTER_FLAG) == CENTER_FLAG);
|
||||
const auto SHADOWED = ((flags & SHADOW_FLAG) == SHADOW_FLAG);
|
||||
const auto COLORED = ((flags & COLOR_FLAG) == COLOR_FLAG);
|
||||
const auto STROKED = ((flags & STROKE_FLAG) == STROKE_FLAG);
|
||||
|
||||
if (CENTERED) {
|
||||
x -= (Text::length(text, kerning) / 2);
|
||||
}
|
||||
|
||||
if (SHADOWED) {
|
||||
writeColored(x + shadow_distance, y + shadow_distance, text, shadow_color, kerning, lenght);
|
||||
}
|
||||
|
||||
if (STROKED) {
|
||||
for (int dist = 1; dist <= shadow_distance; ++dist) {
|
||||
for (int dy = -dist; dy <= dist; ++dy) {
|
||||
for (int dx = -dist; dx <= dist; ++dx) {
|
||||
writeColored(x + dx, y + dy, text, shadow_color, kerning, lenght);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (COLORED) {
|
||||
writeColored(x, y, text, text_color, kerning, lenght);
|
||||
} else {
|
||||
writeColored(x, y, text, text_color, kerning, lenght);
|
||||
// write(x, y, text, kerning, lenght);
|
||||
}
|
||||
}
|
||||
|
||||
// Obtiene la longitud en pixels de una cadena
|
||||
auto Text::length(const std::string& text, int kerning) const -> int {
|
||||
int shift = 0;
|
||||
for (size_t i = 0; i < text.length(); ++i) {
|
||||
shift += (offset_[static_cast<int>(text[i])].w + kerning);
|
||||
}
|
||||
|
||||
// Descuenta el kerning del último caracter
|
||||
return shift - kerning;
|
||||
}
|
||||
|
||||
// Devuelve el valor de la variable
|
||||
auto Text::getCharacterSize() const -> int {
|
||||
return box_width_;
|
||||
}
|
||||
|
||||
// Establece si se usa un tamaño fijo de letra
|
||||
void Text::setFixedWidth(bool value) {
|
||||
fixed_width_ = value;
|
||||
}
|
||||
64
source/core/rendering/text.hpp
Normal file
64
source/core/rendering/text.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array> // Para std::array
|
||||
#include <memory> // Para shared_ptr, unique_ptr
|
||||
#include <string> // Para string
|
||||
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
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};
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
// 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;
|
||||
|
||||
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
|
||||
|
||||
[[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
|
||||
|
||||
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
|
||||
|
||||
// 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
|
||||
};
|
||||
163
source/core/rendering/texture.cpp
Normal file
163
source/core/rendering/texture.cpp
Normal file
@@ -0,0 +1,163 @@
|
||||
|
||||
#include "core/rendering/texture.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <iostream> // Para basic_ostream, operator<<, endl, cout
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <string> // Para char_traits, operator<<, string, opera...
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "utils/utils.hpp" // Para getFileName, ColorRGB, printWithDots
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#include "external/stb_image.h" // para stbi_failure_reason, stbi_image_free
|
||||
|
||||
// Constructor
|
||||
Texture::Texture(SDL_Renderer* renderer, std::string path)
|
||||
: renderer_(renderer),
|
||||
path_(std::move(path)) {
|
||||
// Carga el fichero en la textura
|
||||
if (!path_.empty()) {
|
||||
// Obtiene la extensión
|
||||
const std::string EXTENSION = path_.substr(path_.find_last_of('.') + 1);
|
||||
|
||||
// .png
|
||||
if (EXTENSION == "png") {
|
||||
loadFromFile(path_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Texture::~Texture() {
|
||||
unloadTexture();
|
||||
palettes_.clear();
|
||||
}
|
||||
|
||||
// Carga una imagen desde un fichero
|
||||
auto Texture::loadFromFile(const std::string& file_path) -> bool {
|
||||
if (file_path.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int req_format = STBI_rgb_alpha;
|
||||
int width;
|
||||
int height;
|
||||
int orig_format;
|
||||
unsigned char* data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||
if (data == nullptr) {
|
||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n';
|
||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||
}
|
||||
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
||||
|
||||
int pitch;
|
||||
SDL_PixelFormat pixel_format;
|
||||
// STBI_rgb_alpha (RGBA)
|
||||
pitch = 4 * width;
|
||||
pixel_format = SDL_PIXELFORMAT_RGBA32;
|
||||
|
||||
// Limpia
|
||||
unloadTexture();
|
||||
|
||||
// La textura final
|
||||
SDL_Texture* new_texture = nullptr;
|
||||
|
||||
// Carga la imagen desde una ruta específica
|
||||
auto* loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void*>(data), pitch);
|
||||
if (loaded_surface == nullptr) {
|
||||
std::cout << "Unable to load image " << file_path << '\n';
|
||||
} else {
|
||||
// Crea la textura desde los pixels de la surface
|
||||
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
||||
if (new_texture == nullptr) {
|
||||
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << '\n';
|
||||
} else {
|
||||
// Obtiene las dimensiones de la imagen
|
||||
width_ = loaded_surface->w;
|
||||
height_ = loaded_surface->h;
|
||||
}
|
||||
|
||||
// Elimina la textura cargada
|
||||
SDL_DestroySurface(loaded_surface);
|
||||
}
|
||||
|
||||
// Return success
|
||||
stbi_image_free(data);
|
||||
texture_ = new_texture;
|
||||
return texture_ != nullptr;
|
||||
}
|
||||
|
||||
// Crea una textura en blanco
|
||||
auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) -> bool {
|
||||
// Crea una textura sin inicializar
|
||||
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
|
||||
if (texture_ == nullptr) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create blank texture! SDL Error: %s", SDL_GetError());
|
||||
} else {
|
||||
width_ = width;
|
||||
height_ = height;
|
||||
}
|
||||
|
||||
return texture_ != nullptr;
|
||||
}
|
||||
|
||||
// Libera la memoria de la textura
|
||||
void Texture::unloadTexture() {
|
||||
// Libera la textura
|
||||
if (texture_ != nullptr) {
|
||||
SDL_DestroyTexture(texture_);
|
||||
texture_ = nullptr;
|
||||
width_ = 0;
|
||||
height_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el color para la modulacion
|
||||
void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue) { SDL_SetTextureColorMod(texture_, red, green, blue); }
|
||||
void Texture::setColor(ColorRGB color) { SDL_SetTextureColorMod(texture_, color.r, color.g, color.b); }
|
||||
|
||||
// Establece el blending
|
||||
void Texture::setBlendMode(SDL_BlendMode blending) { SDL_SetTextureBlendMode(texture_, blending); }
|
||||
|
||||
// Establece el alpha para la modulación
|
||||
void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); }
|
||||
|
||||
// Renderiza la textura en un punto específico
|
||||
void Texture::render(float x, float y, SDL_FRect* clip, float zoom_w, float zoom_h, double angle, SDL_FPoint* center, SDL_FlipMode flip) {
|
||||
// Establece el destino de renderizado en la pantalla
|
||||
SDL_FRect render_quad = {x, y, width_, height_};
|
||||
|
||||
// Obtiene las dimesiones del clip de renderizado
|
||||
if (clip != nullptr) {
|
||||
render_quad.w = clip->w;
|
||||
render_quad.h = clip->h;
|
||||
}
|
||||
|
||||
// Calcula el zoom y las coordenadas
|
||||
if (zoom_h != 1.0F || zoom_w != 1.0F) {
|
||||
render_quad.x = render_quad.x + (render_quad.w / 2);
|
||||
render_quad.y = render_quad.y + (render_quad.h / 2);
|
||||
render_quad.w = render_quad.w * zoom_w;
|
||||
render_quad.h = render_quad.h * zoom_h;
|
||||
render_quad.x = render_quad.x - (render_quad.w / 2);
|
||||
render_quad.y = render_quad.y - (render_quad.h / 2);
|
||||
}
|
||||
|
||||
// Renderiza a pantalla
|
||||
SDL_RenderTextureRotated(renderer_, texture_, clip, &render_quad, angle, center, flip);
|
||||
}
|
||||
|
||||
// Establece la textura como objetivo de renderizado
|
||||
void Texture::setAsRenderTarget(SDL_Renderer* renderer) { SDL_SetRenderTarget(renderer, texture_); }
|
||||
|
||||
// Recarga la textura
|
||||
auto Texture::reLoad() -> bool { return loadFromFile(path_); }
|
||||
|
||||
// Obtiene la textura
|
||||
auto Texture::getSDLTexture() -> SDL_Texture* { return texture_; }
|
||||
|
||||
// Obtiene el renderizador
|
||||
auto Texture::getRenderer() -> SDL_Renderer* { return renderer_; }
|
||||
43
source/core/rendering/texture.hpp
Normal file
43
source/core/rendering/texture.hpp
Normal file
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
struct ColorRGB; // Forward declaration
|
||||
|
||||
class Texture {
|
||||
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
|
||||
|
||||
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulacion
|
||||
void setColor(ColorRGB 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
|
||||
|
||||
[[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
|
||||
|
||||
// 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
|
||||
};
|
||||
492
source/core/resources/resource_cache.cpp
Normal file
492
source/core/resources/resource_cache.cpp
Normal file
@@ -0,0 +1,492 @@
|
||||
#include "core/resources/resource_cache.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // Para find_if
|
||||
#include <cstdlib> // Para exit, size_t
|
||||
#include <iostream> // Para basic_ostream, operator<<, endl, cout
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <utility>
|
||||
|
||||
#include "core/audio/jail_audio.hpp" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa...
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/text.hpp" // Para Text, loadTextFile
|
||||
#include "core/resources/resource_helper.hpp" // Para Helper
|
||||
#include "core/resources/resource_list.hpp" // Para List, List::Type
|
||||
#include "game/defaults.hpp" // Para Defaults namespace
|
||||
#include "game/gameplay/room.hpp" // Para RoomData, loadRoomFile, loadRoomTileFile
|
||||
#include "game/options.hpp" // Para Options, OptionsGame, options
|
||||
#include "project.h" // Para Project::GIT_HASH
|
||||
#include "utils/color.hpp" // Para Color
|
||||
#include "utils/utils.hpp" // Para getFileName, printWithDots
|
||||
struct JA_Music_t; // lines 17-17
|
||||
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] 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] 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(Color::index(Color::Cpc::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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga las musicas
|
||||
void Cache::loadMusics() {
|
||||
std::cout << "\n>> MUSIC FILES" << '\n';
|
||||
auto list = List::get()->getListByType(List::Type::MUSIC);
|
||||
musics_.clear();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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::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;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
count_ = ResourceCount{.total = total, .loaded = 0};
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
const float BAR_POSITION = Options::game.height - BAR_HEIGHT - Y_PADDING;
|
||||
Screen::get()->start();
|
||||
Screen::get()->clearSurface(Color::index(Color::Cpc::BLACK));
|
||||
|
||||
auto surface = Screen::get()->getRendererSurface();
|
||||
const auto LOADING_TEXT_COLOR = Color::index(Color::Cpc::ORANGE);
|
||||
const auto BAR_COLOR = Color::index(Color::Cpc::PASTEL_BLUE);
|
||||
const int TEXT_HEIGHT = loading_text_->getCharacterSize();
|
||||
const int CENTER_X = Options::game.width / 2;
|
||||
const int CENTER_Y = Options::game.height / 2;
|
||||
|
||||
// Draw APP_NAME centered above center
|
||||
const std::string APP_NAME = spaceBetweenLetters(Project::LONG_NAME);
|
||||
loading_text_->writeColored(
|
||||
CENTER_X - (loading_text_->length(APP_NAME) / 2),
|
||||
CENTER_Y - TEXT_HEIGHT,
|
||||
APP_NAME,
|
||||
LOADING_TEXT_COLOR);
|
||||
|
||||
// Draw VERSION centered below center
|
||||
const std::string VERSION_TEXT = "ver. " + std::string(Project::VERSION) + " (" + std::string(Project::GIT_HASH) + ")";
|
||||
loading_text_->writeColored(
|
||||
CENTER_X - (loading_text_->length(VERSION_TEXT) / 2),
|
||||
CENTER_Y + TEXT_HEIGHT,
|
||||
VERSION_TEXT,
|
||||
LOADING_TEXT_COLOR);
|
||||
|
||||
// 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;
|
||||
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();
|
||||
}
|
||||
checkEvents();
|
||||
}
|
||||
|
||||
} // namespace Resource
|
||||
93
source/core/resources/resource_cache.hpp
Normal file
93
source/core/resources/resource_cache.hpp
Normal file
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/resources/resource_types.hpp" // Para structs de recursos
|
||||
|
||||
namespace Resource {
|
||||
|
||||
class Cache {
|
||||
public:
|
||||
static void init(); // Inicialización singleton
|
||||
static void destroy(); // Destrucción singleton
|
||||
static auto get() -> Cache*; // Acceso al singleton
|
||||
|
||||
auto getSound(const std::string& name) -> JA_Sound_t*; // Getters de recursos
|
||||
auto getMusic(const std::string& name) -> JA_Music_t*;
|
||||
auto getSurface(const std::string& name) -> std::shared_ptr<Surface>;
|
||||
auto getPalette(const std::string& name) -> Palette;
|
||||
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>;
|
||||
auto getText(const std::string& name) -> std::shared_ptr<Text>;
|
||||
auto getAnimationData(const std::string& name) -> const AnimationResource&;
|
||||
auto getRoom(const std::string& name) -> std::shared_ptr<Room::Data>;
|
||||
auto getRooms() -> std::vector<RoomResource>&;
|
||||
|
||||
void reload(); // Recarga todos los recursos
|
||||
|
||||
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
|
||||
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
|
||||
// Métodos de carga de recursos
|
||||
void loadSounds();
|
||||
void loadMusics();
|
||||
void loadSurfaces();
|
||||
void loadPalettes();
|
||||
void loadTextFiles();
|
||||
void loadAnimations();
|
||||
void loadRooms();
|
||||
void createText();
|
||||
|
||||
// Métodos de limpieza
|
||||
void clear();
|
||||
void clearSounds();
|
||||
void clearMusics();
|
||||
|
||||
// Métodos de gestión de carga
|
||||
void load();
|
||||
void calculateTotal();
|
||||
void renderProgress();
|
||||
static void checkEvents();
|
||||
void updateLoadingProgress(int steps = 5);
|
||||
|
||||
// Helper para mensajes de error de carga
|
||||
[[noreturn]] static void throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e);
|
||||
|
||||
// Constructor y destructor
|
||||
Cache();
|
||||
~Cache() = default;
|
||||
|
||||
// Singleton instance
|
||||
static Cache* cache;
|
||||
|
||||
// Variables miembro
|
||||
std::vector<SoundResource> sounds_; // Vector con los sonidos
|
||||
std::vector<MusicResource> musics_; // Vector con las musicas
|
||||
std::vector<SurfaceResource> surfaces_; // Vector con las surfaces
|
||||
std::vector<ResourcePalette> palettes_; // Vector con las paletas
|
||||
std::vector<TextFileResource> text_files_; // Vector con los ficheros de texto
|
||||
std::vector<TextResource> texts_; // Vector con los objetos de texto
|
||||
std::vector<AnimationResource> animations_; // Vector con las animaciones
|
||||
std::vector<RoomResource> rooms_; // Vector con las habitaciones
|
||||
|
||||
ResourceCount count_{}; // Contador de recursos
|
||||
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
|
||||
};
|
||||
|
||||
} // namespace Resource
|
||||
182
source/core/resources/resource_helper.cpp
Normal file
182
source/core/resources/resource_helper.cpp
Normal file
@@ -0,0 +1,182 @@
|
||||
// resource_helper.cpp
|
||||
// Resource helper implementation
|
||||
|
||||
#include "resource_helper.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
#include "resource_loader.hpp"
|
||||
|
||||
namespace Resource::Helper {
|
||||
|
||||
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 {};
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// Check if a file exists
|
||||
auto fileExists(const std::string& filepath) -> bool {
|
||||
if (!resource_system_initialized) {
|
||||
return std::filesystem::exists(filepath);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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 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
|
||||
38
source/core/resources/resource_helper.hpp
Normal file
38
source/core/resources/resource_helper.hpp
Normal file
@@ -0,0 +1,38 @@
|
||||
// resource_helper.hpp
|
||||
// Helper functions for resource loading (bridge to pack system)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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;
|
||||
|
||||
// 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>;
|
||||
|
||||
// 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;
|
||||
|
||||
// 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;
|
||||
|
||||
} // namespace Resource::Helper
|
||||
320
source/core/resources/resource_list.cpp
Normal file
320
source/core/resources/resource_list.cpp
Normal file
@@ -0,0 +1,320 @@
|
||||
#include "core/resources/resource_list.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError
|
||||
|
||||
#include <algorithm> // Para sort
|
||||
#include <cstddef> // Para size_t
|
||||
#include <exception> // Para exception
|
||||
#include <filesystem> // Para exists, path
|
||||
#include <fstream> // Para ifstream, istringstream
|
||||
#include <iostream> // Para cout
|
||||
#include <sstream> // Para istringstream
|
||||
#include <stdexcept> // Para runtime_error
|
||||
|
||||
#include "external/fkyaml_node.hpp" // Para parsear YAML
|
||||
#include "utils/utils.hpp" // Para getFileName, printWithDots
|
||||
|
||||
namespace Resource {
|
||||
|
||||
// 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());
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Read entire file into string
|
||||
std::stringstream buffer;
|
||||
buffer << file.rdbuf();
|
||||
file.close();
|
||||
|
||||
// Parse using loadFromString
|
||||
loadFromString(buffer.str(), prefix, system_folder);
|
||||
}
|
||||
|
||||
// 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 estructura básica
|
||||
if (!yaml.contains("assets")) {
|
||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Invalid assets.yaml format - missing 'assets' key");
|
||||
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);
|
||||
file.close();
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found for data loading", filename.c_str());
|
||||
return {};
|
||||
}
|
||||
|
||||
// Verifica si un recurso existe
|
||||
auto List::exists(const std::string& filename) const -> bool {
|
||||
return file_list_.find(filename) != file_list_.end();
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
throw std::runtime_error("Unknown asset type: " + type_str);
|
||||
}
|
||||
|
||||
// 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
|
||||
76
source/core/resources/resource_list.hpp
Normal file
76
source/core/resources/resource_list.hpp
Normal file
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint> // Para uint8_t
|
||||
#include <string> // Para string
|
||||
#include <unordered_map> // Para unordered_map
|
||||
#include <utility> // Para move
|
||||
#include <vector> // Para vector
|
||||
|
||||
namespace Resource {
|
||||
|
||||
// --- Clase List: gestor optimizado de recursos (singleton) ---
|
||||
class List {
|
||||
public:
|
||||
// --- Enums ---
|
||||
enum class Type : int {
|
||||
DATA, // Datos
|
||||
BITMAP, // Imágenes
|
||||
ANIMATION, // Animaciones
|
||||
MUSIC, // Música
|
||||
SOUND, // Sonidos
|
||||
FONT, // Fuentes
|
||||
ROOM, // Datos de habitación (.yaml - formato unificado con tilemap)
|
||||
PALETTE, // Paletas
|
||||
SIZE, // Tamaño (para iteración)
|
||||
};
|
||||
|
||||
// --- Métodos de singleton ---
|
||||
static void init(const std::string& executable_path);
|
||||
static void destroy();
|
||||
static auto get() -> List*;
|
||||
List(const List&) = delete;
|
||||
auto operator=(const List&) -> List& = delete;
|
||||
|
||||
// --- Métodos para la gestión de recursos ---
|
||||
void add(const std::string& file_path, Type type, bool required = true, bool absolute = false);
|
||||
void loadFromFile(const std::string& config_file_path, const std::string& prefix = "", const std::string& system_folder = ""); // Con soporte para variables
|
||||
void loadFromString(const std::string& config_content, const std::string& prefix = "", const std::string& system_folder = ""); // Para cargar desde pack (release)
|
||||
[[nodiscard]] auto get(const std::string& filename) const -> std::string; // Obtiene la ruta completa
|
||||
[[nodiscard]] auto loadData(const std::string& filename) const -> std::vector<uint8_t>; // Carga datos del archivo
|
||||
[[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:
|
||||
// --- Estructuras privadas ---
|
||||
struct Item {
|
||||
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) {}
|
||||
};
|
||||
|
||||
// --- Variables internas ---
|
||||
std::unordered_map<std::string, Item> file_list_; // Mapa para búsqueda O(1)
|
||||
std::string executable_path_; // Ruta del ejecutable
|
||||
|
||||
// --- Métodos internos ---
|
||||
[[nodiscard]] static auto getTypeName(Type type) -> std::string; // Obtiene el nombre del tipo
|
||||
[[nodiscard]] static auto parseAssetType(const std::string& type_str) -> Type; // Convierte string a tipo
|
||||
void addToMap(const std::string& file_path, Type type, bool required, bool absolute); // Añade archivo al mapa
|
||||
[[nodiscard]] static auto replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string; // Reemplaza variables en la ruta
|
||||
static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones
|
||||
|
||||
// --- Constructores y destructor privados (singleton) ---
|
||||
explicit List(std::string executable_path) // Constructor privado
|
||||
: executable_path_(std::move(executable_path)) {}
|
||||
~List() = default; // Destructor privado
|
||||
|
||||
// --- Instancia singleton ---
|
||||
static List* instance; // Instancia única de List
|
||||
};
|
||||
|
||||
} // namespace Resource
|
||||
199
source/core/resources/resource_loader.cpp
Normal file
199
source/core/resources/resource_loader.cpp
Normal file
@@ -0,0 +1,199 @@
|
||||
// resource_loader.cpp
|
||||
// Resource loader implementation
|
||||
|
||||
#include "resource_loader.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
namespace Resource {
|
||||
|
||||
// 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";
|
||||
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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
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
|
||||
48
source/core/resources/resource_loader.hpp
Normal file
48
source/core/resources/resource_loader.hpp
Normal file
@@ -0,0 +1,48 @@
|
||||
// resource_loader.hpp
|
||||
// Singleton resource loader for managing pack and filesystem access
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "resource_pack.hpp"
|
||||
|
||||
namespace Resource {
|
||||
|
||||
// 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
|
||||
|
||||
auto loadResource(const std::string& filename) -> std::vector<uint8_t>; // Load resource data
|
||||
auto resourceExists(const std::string& filename) -> bool; // Check resource availability
|
||||
|
||||
[[nodiscard]] auto isPackLoaded() const -> bool; // Pack status queries
|
||||
[[nodiscard]] auto getPackResourceCount() const -> size_t;
|
||||
[[nodiscard]] auto validatePack() const -> bool; // Validate pack integrity
|
||||
[[nodiscard]] auto loadAssetsConfig() const -> std::string; // Load assets.yaml from pack
|
||||
|
||||
void shutdown(); // Cleanup
|
||||
|
||||
Loader(const Loader&) = delete; // Deleted copy/move constructors
|
||||
auto operator=(const Loader&) -> Loader& = delete;
|
||||
Loader(Loader&&) = delete;
|
||||
auto operator=(Loader&&) -> Loader& = delete;
|
||||
|
||||
private:
|
||||
Loader() = default;
|
||||
~Loader() = default;
|
||||
|
||||
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>; // Filesystem helpers
|
||||
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
|
||||
|
||||
std::unique_ptr<Pack> resource_pack_; // Member variables
|
||||
bool fallback_to_files_{true};
|
||||
bool initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace Resource
|
||||
303
source/core/resources/resource_pack.cpp
Normal file
303
source/core/resources/resource_pack.cpp
Normal file
@@ -0,0 +1,303 @@
|
||||
// resource_pack.cpp
|
||||
// Resource pack implementation for JailDoctor's Dilemma
|
||||
|
||||
#include "resource_pack.hpp"
|
||||
|
||||
#include <SDL3/SDL_filesystem.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
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 {};
|
||||
}
|
||||
|
||||
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 {};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// 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 header
|
||||
file.write(MAGIC_HEADER.data(), MAGIC_HEADER.size());
|
||||
file.write(reinterpret_cast<const char*>(&VERSION), sizeof(VERSION));
|
||||
|
||||
// Write resource count
|
||||
auto resource_count = static_cast<uint32_t>(resources_.size());
|
||||
file.write(reinterpret_cast<const char*>(&resource_count), sizeof(resource_count));
|
||||
|
||||
// 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);
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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
|
||||
68
source/core/resources/resource_pack.hpp
Normal file
68
source/core/resources/resource_pack.hpp
Normal file
@@ -0,0 +1,68 @@
|
||||
// resource_pack.hpp
|
||||
// Resource pack file format and management for JailDoctor's Dilemma
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Resource {
|
||||
|
||||
// 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:
|
||||
Pack() = default;
|
||||
~Pack() = default;
|
||||
|
||||
Pack(const Pack&) = delete; // Deleted copy/move constructors
|
||||
auto operator=(const Pack&) -> Pack& = delete;
|
||||
Pack(Pack&&) = delete;
|
||||
auto operator=(Pack&&) -> Pack& = delete;
|
||||
|
||||
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool; // Building packs
|
||||
auto addDirectory(const std::string& dir_path, const std::string& base_path = "") -> bool;
|
||||
|
||||
auto savePack(const std::string& pack_file) -> bool; // Pack I/O
|
||||
auto loadPack(const std::string& pack_file) -> bool;
|
||||
|
||||
auto getResource(const std::string& filename) -> std::vector<uint8_t>; // Resource access
|
||||
auto hasResource(const std::string& filename) const -> bool;
|
||||
auto getResourceList() const -> std::vector<std::string>;
|
||||
|
||||
auto isLoaded() const -> bool { return loaded_; } // Status queries
|
||||
auto getResourceCount() const -> size_t { return resources_.size(); }
|
||||
auto getDataSize() const -> size_t { return data_.size(); }
|
||||
auto calculatePackChecksum() const -> uint32_t; // Validation
|
||||
|
||||
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";
|
||||
|
||||
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t; // Utility methods
|
||||
|
||||
static void encryptData(std::vector<uint8_t>& data, const std::string& key); // Encryption/decryption
|
||||
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||
|
||||
static auto readFile(const std::string& filepath) -> std::vector<uint8_t>; // File I/O
|
||||
|
||||
std::unordered_map<std::string, ResourceEntry> resources_; // Member variables
|
||||
std::vector<uint8_t> data_; // Encrypted data block
|
||||
bool loaded_{false};
|
||||
};
|
||||
|
||||
} // namespace Resource
|
||||
62
source/core/resources/resource_types.hpp
Normal file
62
source/core/resources/resource_types.hpp
Normal file
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint> // Para uint8_t
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/rendering/surface.hpp" // Para Palette y Surface
|
||||
#include "core/rendering/text.hpp" // Para Text y Text::File
|
||||
#include "game/gameplay/room.hpp" // Para Room::Data
|
||||
|
||||
// Forward declarations
|
||||
struct JA_Music_t;
|
||||
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
|
||||
};
|
||||
|
||||
// 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
|
||||
};
|
||||
|
||||
// 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
|
||||
};
|
||||
|
||||
// Estructura para almacenar objetos Palette y su nombre
|
||||
struct ResourcePalette {
|
||||
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
|
||||
};
|
||||
|
||||
// Estructura para almacenar objetos Text y su nombre
|
||||
struct TextResource {
|
||||
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
|
||||
};
|
||||
|
||||
// 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
|
||||
};
|
||||
60
source/core/system/debug.cpp
Normal file
60
source/core/system/debug.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#include "core/system/debug.hpp"
|
||||
|
||||
#ifdef _DEBUG
|
||||
|
||||
#include <algorithm> // Para max
|
||||
#include <memory> // Para __shared_ptr_access, shared_ptr
|
||||
|
||||
#include "core/rendering/text.hpp" // Para Text
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "utils/defines.hpp" // Para PlayArea
|
||||
#include "utils/color.hpp" // Para Color
|
||||
|
||||
// [SINGLETON]
|
||||
Debug* Debug::debug = nullptr;
|
||||
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void Debug::init() {
|
||||
Debug::debug = new Debug();
|
||||
}
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void Debug::destroy() {
|
||||
delete Debug::debug;
|
||||
}
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
auto Debug::get() -> Debug* {
|
||||
return Debug::debug;
|
||||
}
|
||||
|
||||
// Dibuja en pantalla
|
||||
void Debug::render() {
|
||||
auto text = Resource::Cache::get()->getText("aseprite");
|
||||
int y = y_;
|
||||
int w = 0;
|
||||
|
||||
for (const auto& s : slot_) {
|
||||
text->write(x_, y, s);
|
||||
w = (std::max(w, (int)s.length()));
|
||||
y += text->getCharacterSize() + 1;
|
||||
if (y > PlayArea::HEIGHT - text->getCharacterSize()) {
|
||||
y = y_;
|
||||
x_ += w * text->getCharacterSize() + 2;
|
||||
}
|
||||
}
|
||||
|
||||
y = 0;
|
||||
for (const auto& l : log_) {
|
||||
text->writeColored(x_ + 10, y, l, Color::index(Color::Cpc::WHITE));
|
||||
y += text->getCharacterSize() + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Establece la posición donde se colocará la información de debug
|
||||
void Debug::setPos(SDL_FPoint p) {
|
||||
x_ = p.x;
|
||||
y_ = p.y;
|
||||
}
|
||||
|
||||
#endif // _DEBUG
|
||||
44
source/core/system/debug.hpp
Normal file
44
source/core/system/debug.hpp
Normal file
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef _DEBUG
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
// 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
|
||||
|
||||
void render(); // Dibuja en pantalla
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
#endif // _DEBUG
|
||||
308
source/core/system/director.cpp
Normal file
308
source/core/system/director.cpp
Normal file
@@ -0,0 +1,308 @@
|
||||
#include "core/system/director.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
|
||||
#include <unistd.h> // Para getuid
|
||||
|
||||
#include <cerrno> // Para errno, EEXIST, EACCES, ENAMETOO...
|
||||
#include <cstdio> // Para printf, perror
|
||||
#include <cstdlib> // Para exit, EXIT_FAILURE, srand
|
||||
#include <iostream> // Para basic_ostream, operator<<, cout
|
||||
#include <memory> // Para make_unique, unique_ptr
|
||||
#include <string> // Para operator+, allocator, char_traits
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "core/input/input.hpp" // Para Input, InputAction
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||
#include "core/resources/resource_list.hpp" // Para Asset, AssetType
|
||||
#include "core/resources/resource_loader.hpp" // Para ResourceLoader
|
||||
#include "game/options.hpp" // Para Options, options, OptionsVideo
|
||||
#include "game/scene_manager.hpp" // Para SceneManager
|
||||
#include "game/scenes/game.hpp" // Para Game, GameMode
|
||||
#include "game/scenes/logo.hpp" // Para Logo
|
||||
#include "game/scenes/title.hpp" // Para Title
|
||||
#include "game/ui/notifier.hpp" // Para Notifier
|
||||
#include "project.h"
|
||||
#include "utils/defines.hpp" // Para WINDOW_CAPTION
|
||||
|
||||
#ifdef _DEBUG
|
||||
#include "core/system/debug.hpp" // Para Debug
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <pwd.h>
|
||||
#endif
|
||||
|
||||
// Constructor
|
||||
Director::Director(std::vector<std::string> const& args) {
|
||||
std::cout << "Game start" << '\n';
|
||||
|
||||
// Crea e inicializa las opciones del programa
|
||||
Options::init();
|
||||
|
||||
// Comprueba los parametros del programa
|
||||
executable_path_ = getPath(checkProgramArguments(args));
|
||||
|
||||
// Crea la carpeta del sistema donde guardar datos
|
||||
createSystemFolder("jailgames");
|
||||
createSystemFolder(std::string("jailgames/") + Project::NAME);
|
||||
|
||||
// Determinar el prefijo de ruta según la plataforma
|
||||
#ifdef MACOS_BUNDLE
|
||||
const std::string PREFIX = "/../Resources";
|
||||
#else
|
||||
const std::string PREFIX;
|
||||
#endif
|
||||
|
||||
// Preparar ruta al pack (en macOS bundle está en Contents/Resources/)
|
||||
std::string pack_path = executable_path_ + PREFIX + "/resources.pack";
|
||||
|
||||
#ifdef RELEASE_BUILD
|
||||
// ============================================================
|
||||
// RELEASE BUILD: Pack-first architecture
|
||||
// ============================================================
|
||||
std::cout << "\n** RELEASE MODE: Pack-first initialization\n";
|
||||
|
||||
// 1. Initialize resource pack system (required, no fallback)
|
||||
std::cout << "Initializing resource pack: " << pack_path << '\n';
|
||||
if (!Resource::Helper::initializeResourceSystem(pack_path, false)) {
|
||||
std::cerr << "ERROR: Failed to load resources.pack (required in release builds)\n";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// 2. Validate pack integrity
|
||||
std::cout << "Validating pack integrity..." << '\n';
|
||||
if (!Resource::Loader::get().validatePack()) {
|
||||
std::cerr << "ERROR: Pack validation failed\n";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// 3. Load assets.yaml from pack
|
||||
std::cout << "Loading assets configuration from pack..." << '\n';
|
||||
std::string assets_config = Resource::Loader::get().loadAssetsConfig();
|
||||
if (assets_config.empty()) {
|
||||
std::cerr << "ERROR: Failed to load assets.yaml from pack\n";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// 4. Initialize Asset system with config from pack
|
||||
// NOTE: In release, don't use executable_path or PREFIX - paths in pack are relative
|
||||
// Pass empty string to avoid issues when running from different directories
|
||||
Resource::List::init(""); // Empty executable_path in release
|
||||
Resource::List::get()->loadFromString(assets_config, "", system_folder_); // Empty PREFIX for pack
|
||||
std::cout << "Asset system initialized from pack\n";
|
||||
|
||||
#else
|
||||
// ============================================================
|
||||
// DEVELOPMENT BUILD: Filesystem-first architecture
|
||||
// ============================================================
|
||||
std::cout << "\n** DEVELOPMENT MODE: Filesystem-first initialization\n";
|
||||
|
||||
// 1. Initialize Asset system from filesystem
|
||||
Resource::List::init(executable_path_);
|
||||
|
||||
// 2. Load asset configuration from disk
|
||||
// Note: Asset verification happens during Resource::Cache::load()
|
||||
setFileList();
|
||||
|
||||
// 3. Initialize resource pack system (optional, with fallback)
|
||||
std::cout << "Initializing resource pack (development mode): " << pack_path << '\n';
|
||||
Resource::Helper::initializeResourceSystem(pack_path, true);
|
||||
|
||||
#endif
|
||||
|
||||
// Configura la ruta y carga las opciones desde un fichero
|
||||
Options::setConfigFile(Resource::List::get()->get("config.yaml"));
|
||||
Options::loadFromFile();
|
||||
|
||||
// Inicializa JailAudio
|
||||
Audio::init();
|
||||
|
||||
// Crea los objetos
|
||||
Screen::init();
|
||||
|
||||
// Initialize resources (works for both release and development)
|
||||
Resource::Cache::init();
|
||||
Notifier::init("", "8bithud");
|
||||
Screen::get()->setNotificationsEnabled(true);
|
||||
|
||||
// Special handling for gamecontrollerdb.txt - SDL needs filesystem path
|
||||
#ifdef RELEASE_BUILD
|
||||
// In release, construct the path manually (not from Asset which has empty executable_path)
|
||||
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
|
||||
Input::init(gamecontroller_db);
|
||||
#else
|
||||
// In development, use Asset as normal
|
||||
Input::init(Resource::List::get()->get("gamecontrollerdb.txt")); // Carga configuración de controles
|
||||
#endif
|
||||
|
||||
// Aplica las teclas y botones del gamepad configurados desde Options
|
||||
Input::get()->applyKeyboardBindingsFromOptions();
|
||||
Input::get()->applyGamepadBindingsFromOptions();
|
||||
|
||||
#ifdef _DEBUG
|
||||
Debug::init();
|
||||
#endif
|
||||
|
||||
std::cout << "\n"; // Fin de inicialización de sistemas
|
||||
}
|
||||
|
||||
Director::~Director() {
|
||||
// Guarda las opciones a un fichero
|
||||
Options::saveToFile();
|
||||
|
||||
// Destruye los singletones
|
||||
#ifdef _DEBUG
|
||||
Debug::destroy();
|
||||
#endif
|
||||
Input::destroy();
|
||||
Notifier::destroy();
|
||||
Resource::Cache::destroy();
|
||||
Resource::Helper::shutdownResourceSystem(); // Shutdown resource pack system
|
||||
Audio::destroy();
|
||||
Screen::destroy();
|
||||
Resource::List::destroy();
|
||||
|
||||
SDL_Quit();
|
||||
|
||||
std::cout << "\nBye!" << '\n';
|
||||
}
|
||||
|
||||
// Comprueba los parametros del programa
|
||||
auto Director::checkProgramArguments(std::vector<std::string> const& args) -> std::string {
|
||||
// Iterar sobre los argumentos del programa (saltando args[0] que es el ejecutable)
|
||||
for (std::size_t i = 1; i < args.size(); ++i) {
|
||||
const std::string& argument = args[i];
|
||||
|
||||
if (argument == "--console") {
|
||||
Options::console = true;
|
||||
} else if (argument == "--infiniteLives") {
|
||||
Options::cheats.infinite_lives = Options::Cheat::State::ENABLED;
|
||||
} else if (argument == "--invincible") {
|
||||
Options::cheats.invincible = Options::Cheat::State::ENABLED;
|
||||
} else if (argument == "--jailEnabled") {
|
||||
Options::cheats.jail_is_open = Options::Cheat::State::ENABLED;
|
||||
} else if (argument == "--altSkin") {
|
||||
Options::cheats.alternate_skin = Options::Cheat::State::ENABLED;
|
||||
}
|
||||
}
|
||||
|
||||
return args[0];
|
||||
}
|
||||
|
||||
// Crea la carpeta del sistema donde guardar datos
|
||||
void Director::createSystemFolder(const std::string& folder) {
|
||||
#ifdef _WIN32
|
||||
system_folder_ = std::string(getenv("APPDATA")) + "/" + folder;
|
||||
#elif __APPLE__
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
const char* homedir = pw->pw_dir;
|
||||
system_folder_ = std::string(homedir) + "/Library/Application Support" + "/" + folder;
|
||||
#elif __linux__
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
const char* homedir = pw->pw_dir;
|
||||
system_folder_ = std::string(homedir) + "/.config/" + folder;
|
||||
|
||||
{
|
||||
// Intenta crear ".config", per si no existeix
|
||||
std::string config_base_folder = std::string(homedir) + "/.config";
|
||||
int ret = mkdir(config_base_folder.c_str(), S_IRWXU);
|
||||
if (ret == -1 && errno != EEXIST) {
|
||||
printf("ERROR CREATING CONFIG BASE FOLDER.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
struct stat st = {.st_dev = 0};
|
||||
if (stat(system_folder_.c_str(), &st) == -1) {
|
||||
errno = 0;
|
||||
#ifdef _WIN32
|
||||
int ret = mkdir(system_folder_.c_str());
|
||||
#else
|
||||
int ret = mkdir(system_folder_.c_str(), S_IRWXU);
|
||||
#endif
|
||||
|
||||
if (ret == -1) {
|
||||
switch (errno) {
|
||||
case EACCES:
|
||||
printf("the parent directory does not allow write");
|
||||
exit(EXIT_FAILURE);
|
||||
|
||||
case EEXIST:
|
||||
printf("pathname already exists");
|
||||
exit(EXIT_FAILURE);
|
||||
|
||||
case ENAMETOOLONG:
|
||||
printf("pathname is too long");
|
||||
exit(EXIT_FAILURE);
|
||||
|
||||
default:
|
||||
perror("mkdir");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga la configuración de assets desde assets.yaml
|
||||
void Director::setFileList() {
|
||||
// Determinar el prefijo de ruta según la plataforma
|
||||
#ifdef MACOS_BUNDLE
|
||||
const std::string PREFIX = "/../Resources";
|
||||
#else
|
||||
const std::string PREFIX;
|
||||
#endif
|
||||
|
||||
// Construir ruta al archivo de configuración de assets
|
||||
std::string config_path = executable_path_ + PREFIX + "/config/assets.yaml";
|
||||
|
||||
// Cargar todos los assets desde el archivo de configuración
|
||||
// La verificación de existencia de archivos se realiza durante Resource::Cache::load()
|
||||
Resource::List::get()->loadFromFile(config_path, PREFIX, system_folder_);
|
||||
}
|
||||
|
||||
// Ejecuta la seccion de juego con el logo
|
||||
void Director::runLogo() {
|
||||
auto logo = std::make_unique<Logo>();
|
||||
logo->run();
|
||||
}
|
||||
|
||||
// Ejecuta la seccion de juego con el titulo y los menus
|
||||
void Director::runTitle() {
|
||||
auto title = std::make_unique<Title>();
|
||||
title->run();
|
||||
}
|
||||
|
||||
// Ejecuta la seccion de juego donde se juega
|
||||
void Director::runGame() {
|
||||
Audio::get()->stopMusic();
|
||||
auto game = std::make_unique<Game>(Game::Mode::GAME);
|
||||
game->run();
|
||||
}
|
||||
|
||||
auto Director::run() -> int {
|
||||
// Bucle principal
|
||||
while (SceneManager::current != SceneManager::Scene::QUIT) {
|
||||
switch (SceneManager::current) {
|
||||
case SceneManager::Scene::LOGO:
|
||||
runLogo();
|
||||
break;
|
||||
|
||||
case SceneManager::Scene::TITLE:
|
||||
runTitle();
|
||||
break;
|
||||
|
||||
case SceneManager::Scene::GAME:
|
||||
runGame();
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
26
source/core/system/director.hpp
Normal file
26
source/core/system/director.hpp
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
class Director {
|
||||
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
|
||||
|
||||
// --- 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 runTitle(); // Ejecuta la seccion de juego con el titulo y los menus
|
||||
static void runGame(); // Ejecuta la seccion de juego donde se juega
|
||||
};
|
||||
22
source/core/system/global_events.cpp
Normal file
22
source/core/system/global_events.cpp
Normal file
@@ -0,0 +1,22 @@
|
||||
#include "core/system/global_events.hpp"
|
||||
|
||||
#include "core/input/mouse.hpp"
|
||||
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
|
||||
#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;
|
||||
}
|
||||
|
||||
if (event.type == SDL_EVENT_RENDER_DEVICE_RESET || event.type == SDL_EVENT_RENDER_TARGETS_RESET) {
|
||||
// reLoadTextures();
|
||||
}
|
||||
|
||||
Mouse::handleEvent(event);
|
||||
}
|
||||
} // namespace GlobalEvents
|
||||
8
source/core/system/global_events.hpp
Normal file
8
source/core/system/global_events.hpp
Normal file
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#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);
|
||||
} // namespace GlobalEvents
|
||||
2
source/external/.clang-format
vendored
Normal file
2
source/external/.clang-format
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
DisableFormat: true
|
||||
SortIncludes: Never
|
||||
4
source/external/.clang-tidy
vendored
Normal file
4
source/external/.clang-tidy
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
# source/external/.clang-tidy
|
||||
Checks: '-*'
|
||||
WarningsAsErrors: ''
|
||||
HeaderFilterRegex: ''
|
||||
14726
source/external/fkyaml_node.hpp
vendored
Normal file
14726
source/external/fkyaml_node.hpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
9251
source/external/stb_image.h
vendored
Normal file
9251
source/external/stb_image.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
5565
source/external/stb_vorbis.h
vendored
Normal file
5565
source/external/stb_vorbis.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
91
source/game/defaults.hpp
Normal file
91
source/game/defaults.hpp
Normal file
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include "core/rendering/screen.hpp" // Para Screen::Filter
|
||||
#include "utils/defines.hpp" // Para GameCanvas
|
||||
|
||||
// Forward declarations from Options namespace
|
||||
namespace Options {
|
||||
// enum class ControlScheme;
|
||||
enum class NotificationPosition;
|
||||
} // namespace Options
|
||||
|
||||
namespace Defaults {
|
||||
|
||||
// --- CANVAS ---
|
||||
// Dimensiones del canvas del juego (usa GameCanvas como fuente única)
|
||||
namespace Canvas {
|
||||
constexpr int WIDTH = GameCanvas::WIDTH; // Ancho del canvas del juego (320)
|
||||
constexpr int HEIGHT = GameCanvas::HEIGHT; // Alto del canvas del juego (240)
|
||||
} // namespace Canvas
|
||||
|
||||
// --- WINDOW ---
|
||||
namespace Window {
|
||||
constexpr int ZOOM = 2; // Zoom de la ventana por defecto
|
||||
} // namespace Window
|
||||
|
||||
// --- VIDEO ---
|
||||
namespace Video {
|
||||
constexpr bool FULLSCREEN = false; // Modo de pantalla completa por defecto (false = ventana)
|
||||
constexpr Screen::Filter FILTER = Screen::Filter::NEAREST; // Filtro por defecto
|
||||
constexpr bool VERTICAL_SYNC = true; // Vsync activado por defecto
|
||||
constexpr bool SHADERS = false; // Shaders desactivados por defecto
|
||||
constexpr bool INTEGER_SCALE = true; // Escalado entero activado por defecto
|
||||
constexpr bool KEEP_ASPECT = true; // Mantener aspecto activado por defecto
|
||||
constexpr const char* PALETTE_NAME = "cpc"; // Paleta por defecto
|
||||
} // namespace Video
|
||||
|
||||
// --- BORDER ---
|
||||
namespace Border {
|
||||
constexpr bool ENABLED = true; // Borde activado por defecto
|
||||
constexpr int WIDTH = 32; // Ancho del borde por defecto
|
||||
constexpr int HEIGHT = 24; // Alto del borde por defecto
|
||||
} // namespace Border
|
||||
|
||||
// --- AUDIO ---
|
||||
namespace Audio {
|
||||
constexpr float VOLUME = 1.0F; // Volumen por defecto
|
||||
constexpr bool ENABLED = true; // Audio por defecto
|
||||
} // namespace Audio
|
||||
|
||||
// --- MUSIC ---
|
||||
namespace Music {
|
||||
constexpr float VOLUME = 0.8F; // Volumen por defecto de la musica
|
||||
constexpr bool ENABLED = true; // Musica habilitada por defecto
|
||||
constexpr const char* TITLE_TRACK = "574070_KUVO_Farewell_to_school.ogg"; // Musica de la escena title
|
||||
constexpr const char* GAME_TRACK = "574071_EA_DTV.ogg"; // Musica de la escena game
|
||||
constexpr int FADE_DURATION_MS = 1000; // Duracion del fade out en milisegundos
|
||||
} // namespace Music
|
||||
|
||||
// --- SOUND ---
|
||||
namespace Sound {
|
||||
constexpr float VOLUME = 1.0F; // Volumen por defecto de los efectos de sonido
|
||||
constexpr bool ENABLED = true; // Sonido habilitado por defecto
|
||||
constexpr const char* JUMP = "jump.wav"; // Sonido de salto
|
||||
constexpr const char* HIT = "hit.wav"; // Sonido de golpe/daño
|
||||
constexpr const char* LAND = "land.wav"; // Sonido de aterrizaje
|
||||
constexpr const char* ITEM = "item.wav"; // Sonido de recoger item
|
||||
constexpr const char* NOTIFY = "notify.wav"; // Sonido de notificación
|
||||
} // namespace Sound
|
||||
|
||||
// --- CHEATS ---
|
||||
namespace Cheat {
|
||||
constexpr bool INFINITE_LIVES = false; // Vidas infinitas desactivadas por defecto
|
||||
constexpr bool INVINCIBLE = false; // Invencibilidad desactivada por defecto
|
||||
constexpr bool JAIL_IS_OPEN = false; // Jail abierta desactivada por defecto
|
||||
constexpr bool ALTERNATE_SKIN = false; // Skin alternativa desactivada por defecto
|
||||
} // namespace Cheat
|
||||
|
||||
// --- CONTROLS ---
|
||||
namespace Controls {
|
||||
constexpr SDL_Scancode KEY_LEFT = SDL_SCANCODE_LEFT; // Tecla izquierda por defecto
|
||||
constexpr SDL_Scancode KEY_RIGHT = SDL_SCANCODE_RIGHT; // Tecla derecha por defecto
|
||||
constexpr SDL_Scancode KEY_JUMP = SDL_SCANCODE_UP; // Tecla salto por defecto
|
||||
|
||||
constexpr int GAMEPAD_BUTTON_LEFT = SDL_GAMEPAD_BUTTON_DPAD_LEFT; // Botón izquierda por defecto
|
||||
constexpr int GAMEPAD_BUTTON_RIGHT = SDL_GAMEPAD_BUTTON_DPAD_RIGHT; // Botón derecha por defecto
|
||||
constexpr int GAMEPAD_BUTTON_JUMP = SDL_GAMEPAD_BUTTON_WEST; // Botón salto por defecto
|
||||
} // namespace Controls
|
||||
|
||||
} // namespace Defaults
|
||||
96
source/game/entities/enemy.cpp
Normal file
96
source/game/entities/enemy.cpp
Normal file
@@ -0,0 +1,96 @@
|
||||
#include "game/entities/enemy.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <cstdlib> // Para rand
|
||||
|
||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "utils/utils.hpp" // Para stringToColor
|
||||
|
||||
// Constructor
|
||||
Enemy::Enemy(const Data& enemy)
|
||||
: sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::Cache::get()->getAnimationData(enemy.animation_path))),
|
||||
color_string_(enemy.color),
|
||||
x1_(enemy.x1),
|
||||
x2_(enemy.x2),
|
||||
y1_(enemy.y1),
|
||||
y2_(enemy.y2),
|
||||
should_flip_(enemy.flip),
|
||||
should_mirror_(enemy.mirror) {
|
||||
// Obten el resto de valores
|
||||
sprite_->setPosX(enemy.x);
|
||||
sprite_->setPosY(enemy.y);
|
||||
sprite_->setVelX(enemy.vx);
|
||||
sprite_->setVelY(enemy.vy);
|
||||
|
||||
const int FLIP = (should_flip_ && enemy.vx < 0.0F) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
|
||||
const int MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
|
||||
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR));
|
||||
|
||||
collider_ = getRect();
|
||||
|
||||
color_ = stringToColor(color_string_);
|
||||
|
||||
// Coloca un frame al azar o el designado
|
||||
sprite_->setCurrentAnimationFrame((enemy.frame == -1) ? (rand() % sprite_->getCurrentAnimationSize()) : enemy.frame);
|
||||
}
|
||||
|
||||
// Pinta el enemigo en pantalla
|
||||
void Enemy::render() {
|
||||
sprite_->render(1, color_);
|
||||
}
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void Enemy::update(float delta_time) {
|
||||
sprite_->update(delta_time);
|
||||
checkPath();
|
||||
collider_ = getRect();
|
||||
}
|
||||
|
||||
// Comprueba si ha llegado al limite del recorrido para darse media vuelta
|
||||
void Enemy::checkPath() {
|
||||
if (sprite_->getPosX() > x2_ || sprite_->getPosX() < x1_) {
|
||||
// Recoloca
|
||||
if (sprite_->getPosX() > x2_) {
|
||||
sprite_->setPosX(x2_);
|
||||
} else {
|
||||
sprite_->setPosX(x1_);
|
||||
}
|
||||
|
||||
// Cambia el sentido
|
||||
sprite_->setVelX(sprite_->getVelX() * (-1));
|
||||
|
||||
// Invierte el sprite
|
||||
if (should_flip_) {
|
||||
sprite_->flip();
|
||||
}
|
||||
}
|
||||
|
||||
if (sprite_->getPosY() > y2_ || sprite_->getPosY() < y1_) {
|
||||
// Recoloca
|
||||
if (sprite_->getPosY() > y2_) {
|
||||
sprite_->setPosY(y2_);
|
||||
} else {
|
||||
sprite_->setPosY(y1_);
|
||||
}
|
||||
|
||||
// Cambia el sentido
|
||||
sprite_->setVelY(sprite_->getVelY() * (-1));
|
||||
|
||||
// Invierte el sprite
|
||||
if (should_flip_) {
|
||||
sprite_->flip();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Devuelve el rectangulo que contiene al enemigo
|
||||
auto Enemy::getRect() -> SDL_FRect {
|
||||
return sprite_->getRect();
|
||||
}
|
||||
|
||||
// Obtiene el rectangulo de colision del enemigo
|
||||
auto Enemy::getCollider() -> SDL_FRect& {
|
||||
return collider_;
|
||||
}
|
||||
51
source/game/entities/enemy.hpp
Normal file
51
source/game/entities/enemy.hpp
Normal file
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
class SurfaceAnimatedSprite; // lines 7-7
|
||||
|
||||
class Enemy {
|
||||
public:
|
||||
struct Data {
|
||||
std::string animation_path; // Ruta al fichero con la animación
|
||||
float x{0.0F}; // Posición inicial en el eje X
|
||||
float y{0.0F}; // Posición inicial en el eje Y
|
||||
float vx{0.0F}; // Velocidad en el eje X
|
||||
float vy{0.0F}; // Velocidad en el eje Y
|
||||
int x1{0}; // Límite izquierdo de la ruta en el eje X
|
||||
int x2{0}; // Límite derecho de la ruta en el eje X
|
||||
int y1{0}; // Límite superior de la ruta en el eje Y
|
||||
int y2{0}; // Límite inferior de la ruta en el eje Y
|
||||
bool flip{false}; // Indica si el enemigo hace flip al terminar su ruta
|
||||
bool mirror{false}; // Indica si el enemigo está volteado verticalmente
|
||||
int frame{0}; // Frame inicial para la animación del enemigo
|
||||
std::string color; // Color del enemigo
|
||||
};
|
||||
|
||||
explicit Enemy(const Data& enemy); // Constructor
|
||||
~Enemy() = default; // Destructor
|
||||
|
||||
void render(); // Pinta el enemigo en pantalla
|
||||
void update(float delta_time); // Actualiza las variables del objeto
|
||||
|
||||
auto getRect() -> SDL_FRect; // Devuelve el rectangulo que contiene al enemigo
|
||||
auto getCollider() -> SDL_FRect&; // Obtiene el rectangulo de colision del enemigo
|
||||
|
||||
private:
|
||||
void checkPath(); // Comprueba si ha llegado al limite del recorrido para darse media vuelta
|
||||
|
||||
std::shared_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del enemigo
|
||||
|
||||
// Variables
|
||||
Uint8 color_{0}; // Color del enemigo
|
||||
std::string color_string_; // Color del enemigo en formato texto
|
||||
int x1_{0}; // Limite izquierdo de la ruta en el eje X
|
||||
int x2_{0}; // Limite derecho de la ruta en el eje X
|
||||
int y1_{0}; // Limite superior de la ruta en el eje Y
|
||||
int y2_{0}; // Limite inferior de la ruta en el eje Y
|
||||
SDL_FRect collider_{}; // Caja de colisión
|
||||
bool should_flip_{false}; // Indica si el enemigo hace flip al terminar su ruta
|
||||
bool should_mirror_{false}; // Indica si el enemigo se dibuja volteado verticalmente
|
||||
};
|
||||
56
source/game/entities/item.cpp
Normal file
56
source/game/entities/item.cpp
Normal file
@@ -0,0 +1,56 @@
|
||||
#include "game/entities/item.hpp"
|
||||
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
|
||||
// Constructor
|
||||
Item::Item(const Data& item)
|
||||
: sprite_(std::make_shared<SurfaceSprite>(Resource::Cache::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
|
||||
time_accumulator_(static_cast<float>(item.counter) * COLOR_CHANGE_INTERVAL) {
|
||||
// Inicia variables
|
||||
sprite_->setClip((item.tile % 10) * ITEM_SIZE, (item.tile / 10) * ITEM_SIZE, ITEM_SIZE, ITEM_SIZE);
|
||||
collider_ = sprite_->getRect();
|
||||
|
||||
// Inicializa los colores
|
||||
color_.push_back(item.color1);
|
||||
color_.push_back(item.color1);
|
||||
|
||||
color_.push_back(item.color2);
|
||||
color_.push_back(item.color2);
|
||||
}
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void Item::update(float delta_time) {
|
||||
if (is_paused_) {
|
||||
return;
|
||||
}
|
||||
|
||||
time_accumulator_ += delta_time;
|
||||
}
|
||||
|
||||
// Pinta el objeto en pantalla
|
||||
void Item::render() const {
|
||||
// Calcula el índice de color basado en el tiempo acumulado
|
||||
const int INDEX = static_cast<int>(time_accumulator_ / COLOR_CHANGE_INTERVAL) % static_cast<int>(color_.size());
|
||||
sprite_->render(1, color_.at(INDEX));
|
||||
}
|
||||
|
||||
// Obtiene su ubicación
|
||||
auto Item::getPos() -> SDL_FPoint {
|
||||
const SDL_FPoint P = {sprite_->getX(), sprite_->getY()};
|
||||
return P;
|
||||
}
|
||||
|
||||
// Asigna los colores del objeto
|
||||
void Item::setColors(Uint8 col1, Uint8 col2) {
|
||||
// Reinicializa el vector de colores
|
||||
color_.clear();
|
||||
|
||||
// Añade el primer color
|
||||
color_.push_back(col1);
|
||||
color_.push_back(col1);
|
||||
|
||||
// Añade el segundo color
|
||||
color_.push_back(col2);
|
||||
color_.push_back(col2);
|
||||
}
|
||||
44
source/game/entities/item.hpp
Normal file
44
source/game/entities/item.hpp
Normal file
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
class SurfaceSprite;
|
||||
|
||||
class Item {
|
||||
public:
|
||||
struct Data {
|
||||
std::string tile_set_file; // Ruta al fichero con los gráficos del item
|
||||
float x{0.0F}; // Posición del item en pantalla
|
||||
float y{0.0F}; // Posición del item en pantalla
|
||||
int tile{0}; // Número de tile dentro de la textura
|
||||
int counter{0}; // Contador inicial. Es el que lo hace cambiar de color
|
||||
Uint8 color1{0}; // Uno de los dos colores que se utiliza para el item
|
||||
Uint8 color2{0}; // Uno de los dos colores que se utiliza para el item
|
||||
};
|
||||
|
||||
explicit Item(const Data& item); // Constructor
|
||||
~Item() = default; // Destructor
|
||||
|
||||
void render() const; // Pinta el objeto en pantalla
|
||||
void update(float delta_time); // Actualiza las variables del objeto
|
||||
|
||||
void setPaused(bool paused) { is_paused_ = paused; } // Pausa/despausa el item
|
||||
auto getCollider() -> SDL_FRect& { return collider_; } // Obtiene el rectangulo de colision del objeto
|
||||
auto getPos() -> SDL_FPoint; // Obtiene su ubicación
|
||||
void setColors(Uint8 col1, Uint8 col2); // Asigna los colores del objeto
|
||||
|
||||
private:
|
||||
static constexpr float ITEM_SIZE = 8.0F; // Tamaño del item en pixels
|
||||
static constexpr float COLOR_CHANGE_INTERVAL = 0.06F; // Intervalo de cambio de color en segundos (4 frames a 66.67fps)
|
||||
|
||||
std::shared_ptr<SurfaceSprite> sprite_; // SSprite del objeto
|
||||
|
||||
// Variables
|
||||
std::vector<Uint8> color_; // Vector con los colores del objeto
|
||||
float time_accumulator_{0.0F}; // Acumulador de tiempo para cambio de color
|
||||
SDL_FRect collider_{}; // Rectangulo de colisión
|
||||
bool is_paused_{false}; // Indica si el item está pausado
|
||||
};
|
||||
559
source/game/entities/player.cpp
Normal file
559
source/game/entities/player.cpp
Normal file
@@ -0,0 +1,559 @@
|
||||
// IWYU pragma: no_include <bits/std_abs.h>
|
||||
#include "game/entities/player.hpp"
|
||||
|
||||
#include <algorithm> // Para max, min
|
||||
#include <cmath> // Para ceil, abs
|
||||
#include <iostream>
|
||||
#include <ranges> // Para std::ranges::any_of
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "core/input/input.hpp" // Para Input, InputAction
|
||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "game/defaults.hpp" // Para Defaults::Sound
|
||||
#include "game/gameplay/room.hpp" // Para Room, TileType
|
||||
#include "game/options.hpp" // Para Cheat, Options, options
|
||||
#include "utils/color.hpp" // Para Color
|
||||
#include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
|
||||
|
||||
#ifdef _DEBUG
|
||||
#include "core/system/debug.hpp" // Para Debug
|
||||
#endif
|
||||
|
||||
// Constructor
|
||||
Player::Player(const Data& player)
|
||||
: room_(player.room) {
|
||||
initSprite(player.animations_path);
|
||||
setColor();
|
||||
applySpawnValues(player.spawn_data);
|
||||
placeSprite();
|
||||
|
||||
previous_state_ = state_;
|
||||
}
|
||||
|
||||
// Pinta el jugador en pantalla
|
||||
void Player::render() {
|
||||
sprite_->render();
|
||||
#ifdef _DEBUG
|
||||
if (Debug::get()->isEnabled()) {
|
||||
Screen::get()->getRendererSurface()->putPixel(under_right_foot_.x, under_right_foot_.y, Color::index(Color::Cpc::GREEN));
|
||||
Screen::get()->getRendererSurface()->putPixel(under_left_foot_.x, under_left_foot_.y, Color::index(Color::Cpc::GREEN));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void Player::update(float delta_time) {
|
||||
if (!is_paused_) {
|
||||
handleInput();
|
||||
updateState(delta_time);
|
||||
move(delta_time);
|
||||
animate(delta_time);
|
||||
border_ = handleBorders();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas y modifica variables
|
||||
void Player::handleInput() {
|
||||
if (Input::get()->checkAction(InputAction::LEFT)) {
|
||||
wanna_go_ = Direction::LEFT;
|
||||
} else if (Input::get()->checkAction(InputAction::RIGHT)) {
|
||||
wanna_go_ = Direction::RIGHT;
|
||||
} else {
|
||||
wanna_go_ = Direction::NONE;
|
||||
}
|
||||
|
||||
wanna_jump_ = Input::get()->checkAction(InputAction::JUMP);
|
||||
}
|
||||
|
||||
// La lógica de movimiento está distribuida en move
|
||||
void Player::move(float delta_time) {
|
||||
switch (state_) {
|
||||
case State::ON_GROUND:
|
||||
moveOnGround(delta_time);
|
||||
break;
|
||||
case State::ON_AIR:
|
||||
moveOnAir(delta_time);
|
||||
break;
|
||||
}
|
||||
syncSpriteAndCollider(); // Actualiza la posición del sprite y las colisiones
|
||||
#ifdef _DEBUG
|
||||
Debug::get()->add(std::string("X : " + std::to_string(static_cast<int>(x_))));
|
||||
Debug::get()->add(std::string("Y : " + std::to_string(static_cast<int>(y_))));
|
||||
Debug::get()->add(std::string("LGP: " + std::to_string(last_grounded_position_)));
|
||||
switch (state_) {
|
||||
case State::ON_GROUND:
|
||||
Debug::get()->add(std::string("ON_GROUND"));
|
||||
break;
|
||||
case State::ON_AIR:
|
||||
Debug::get()->add(std::string("ON_AIR"));
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void Player::handleConveyorBelts() {
|
||||
if (!auto_movement_ and isOnConveyorBelt() and wanna_go_ == Direction::NONE) {
|
||||
auto_movement_ = true;
|
||||
}
|
||||
|
||||
if (auto_movement_ and !isOnConveyorBelt()) {
|
||||
auto_movement_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::handleShouldFall() {
|
||||
if (!isOnFloor() and state_ == State::ON_GROUND) {
|
||||
// Pasar a ON_AIR sin impulso de salto (caída)
|
||||
previous_state_ = state_;
|
||||
state_ = State::ON_AIR;
|
||||
last_grounded_position_ = static_cast<int>(y_);
|
||||
vy_ = 0.0F; // Sin impulso inicial, la gravedad lo acelerará
|
||||
}
|
||||
}
|
||||
|
||||
void Player::transitionToState(State state) {
|
||||
previous_state_ = state_;
|
||||
state_ = state;
|
||||
|
||||
switch (state) {
|
||||
case State::ON_GROUND:
|
||||
vy_ = 0;
|
||||
break;
|
||||
case State::ON_AIR:
|
||||
if (previous_state_ == State::ON_GROUND) {
|
||||
vy_ = JUMP_VELOCITY; // Impulso de salto
|
||||
last_grounded_position_ = y_;
|
||||
Audio::get()->playSound(Defaults::Sound::JUMP, Audio::Group::GAME);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::updateState(float delta_time) {
|
||||
switch (state_) {
|
||||
case State::ON_GROUND:
|
||||
updateOnGround(delta_time);
|
||||
break;
|
||||
case State::ON_AIR:
|
||||
updateOnAir(delta_time);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualización lógica del estado ON_GROUND
|
||||
void Player::updateOnGround(float delta_time) {
|
||||
(void)delta_time; // No usado en este método, pero se mantiene por consistencia
|
||||
handleConveyorBelts(); // Gestiona las cintas transportadoras
|
||||
handleShouldFall(); // Verifica si debe caer (no tiene suelo)
|
||||
|
||||
// Verifica si el jugador quiere saltar
|
||||
if (wanna_jump_) { transitionToState(State::ON_AIR); }
|
||||
}
|
||||
|
||||
// Actualización lógica del estado ON_AIR
|
||||
void Player::updateOnAir(float delta_time) {
|
||||
(void)delta_time; // No usado, pero se mantiene por consistencia de interfaz
|
||||
auto_movement_ = false; // Desactiva el movimiento automático mientras está en el aire
|
||||
}
|
||||
|
||||
// Movimiento físico del estado ON_GROUND
|
||||
void Player::moveOnGround(float delta_time) {
|
||||
// Determina cuál debe ser la velocidad a partir de automovement o de wanna_go_
|
||||
updateVelocity(delta_time);
|
||||
|
||||
if (vx_ == 0.0F) { return; }
|
||||
|
||||
// Movimiento horizontal y colision con muros
|
||||
applyHorizontalMovement(delta_time);
|
||||
}
|
||||
|
||||
// Movimiento físico del estado ON_AIR
|
||||
void Player::moveOnAir(float delta_time) {
|
||||
// Movimiento horizontal (el jugador puede moverse en el aire)
|
||||
updateVelocity(delta_time);
|
||||
applyHorizontalMovement(delta_time);
|
||||
|
||||
// Aplicar gravedad
|
||||
applyGravity(delta_time);
|
||||
|
||||
const float DISPLACEMENT_Y = vy_ * delta_time;
|
||||
|
||||
// Movimiento vertical hacia arriba
|
||||
if (vy_ < 0.0F) {
|
||||
const SDL_FRect PROJECTION = getProjection(Direction::UP, DISPLACEMENT_Y);
|
||||
const int POS = room_->checkBottomSurfaces(PROJECTION);
|
||||
|
||||
if (POS == Collision::NONE) {
|
||||
y_ += DISPLACEMENT_Y;
|
||||
} else {
|
||||
// Colisión con el techo: detener ascenso
|
||||
y_ = POS + 1;
|
||||
vy_ = 0.0F;
|
||||
}
|
||||
}
|
||||
// Movimiento vertical hacia abajo
|
||||
else if (vy_ > 0.0F) {
|
||||
const SDL_FRect PROJECTION = getProjection(Direction::DOWN, DISPLACEMENT_Y);
|
||||
handleLandingFromAir(DISPLACEMENT_Y, PROJECTION);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si está situado en alguno de los cuatro bordes de la habitación
|
||||
auto Player::handleBorders() -> Room::Border {
|
||||
if (x_ < PlayArea::LEFT) {
|
||||
return Room::Border::LEFT;
|
||||
}
|
||||
|
||||
if (x_ + WIDTH > PlayArea::RIGHT) {
|
||||
return Room::Border::RIGHT;
|
||||
}
|
||||
|
||||
if (y_ < PlayArea::TOP) {
|
||||
return Room::Border::TOP;
|
||||
}
|
||||
|
||||
if (y_ + HEIGHT > PlayArea::BOTTOM) {
|
||||
return Room::Border::BOTTOM;
|
||||
}
|
||||
|
||||
return Room::Border::NONE;
|
||||
}
|
||||
|
||||
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
||||
void Player::switchBorders() {
|
||||
switch (border_) {
|
||||
case Room::Border::TOP:
|
||||
y_ = PlayArea::BOTTOM - HEIGHT - Tile::SIZE;
|
||||
// CRÍTICO: Resetear last_grounded_position_ para evitar muerte falsa por diferencia de Y entre pantallas
|
||||
last_grounded_position_ = static_cast<int>(y_);
|
||||
transitionToState(State::ON_GROUND);
|
||||
break;
|
||||
|
||||
case Room::Border::BOTTOM:
|
||||
y_ = PlayArea::TOP;
|
||||
// CRÍTICO: Resetear last_grounded_position_ para evitar muerte falsa por diferencia de Y entre pantallas
|
||||
last_grounded_position_ = static_cast<int>(y_);
|
||||
transitionToState(State::ON_GROUND);
|
||||
break;
|
||||
|
||||
case Room::Border::RIGHT:
|
||||
x_ = PlayArea::LEFT;
|
||||
break;
|
||||
|
||||
case Room::Border::LEFT:
|
||||
x_ = PlayArea::RIGHT - WIDTH;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
border_ = Room::Border::NONE;
|
||||
syncSpriteAndCollider();
|
||||
}
|
||||
|
||||
// Aplica gravedad al jugador
|
||||
void Player::applyGravity(float delta_time) {
|
||||
// La gravedad se aplica siempre que el jugador está en el aire
|
||||
if (state_ == State::ON_AIR) {
|
||||
vy_ += GRAVITY_FORCE * delta_time;
|
||||
}
|
||||
}
|
||||
|
||||
// Establece la animación del jugador
|
||||
void Player::animate(float delta_time) {
|
||||
if (vx_ != 0) {
|
||||
sprite_->update(delta_time);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si el jugador tiene suelo debajo de los pies
|
||||
auto Player::isOnFloor() -> bool {
|
||||
bool on_top_surface = false;
|
||||
bool on_conveyor_belt = false;
|
||||
updateFeet();
|
||||
|
||||
// Comprueba las superficies
|
||||
on_top_surface |= room_->checkTopSurfaces(under_left_foot_);
|
||||
on_top_surface |= room_->checkTopSurfaces(under_right_foot_);
|
||||
|
||||
// Comprueba las cintas transportadoras
|
||||
on_conveyor_belt |= room_->checkConveyorBelts(under_left_foot_);
|
||||
on_conveyor_belt |= room_->checkConveyorBelts(under_right_foot_);
|
||||
|
||||
return on_top_surface || on_conveyor_belt;
|
||||
}
|
||||
|
||||
// Comprueba si el jugador está sobre una superficie
|
||||
auto Player::isOnTopSurface() -> bool {
|
||||
bool on_top_surface = false;
|
||||
updateFeet();
|
||||
|
||||
// Comprueba las superficies
|
||||
on_top_surface |= room_->checkTopSurfaces(under_left_foot_);
|
||||
on_top_surface |= room_->checkTopSurfaces(under_right_foot_);
|
||||
|
||||
return on_top_surface;
|
||||
}
|
||||
|
||||
// Comprueba si el jugador esta sobre una cinta transportadora
|
||||
auto Player::isOnConveyorBelt() -> bool {
|
||||
bool on_conveyor_belt = false;
|
||||
updateFeet();
|
||||
|
||||
// Comprueba las superficies
|
||||
on_conveyor_belt |= room_->checkConveyorBelts(under_left_foot_);
|
||||
on_conveyor_belt |= room_->checkConveyorBelts(under_right_foot_);
|
||||
|
||||
return on_conveyor_belt;
|
||||
}
|
||||
|
||||
// Comprueba que el jugador no toque ningun tile de los que matan
|
||||
auto Player::handleKillingTiles() -> bool {
|
||||
// Comprueba si hay contacto con algún tile que mata
|
||||
if (std::ranges::any_of(collider_points_, [this](const auto& c) {
|
||||
return room_->getTile(c) == Room::Tile::KILL;
|
||||
})) {
|
||||
markAsDead(); // Mata al jugador inmediatamente
|
||||
return true; // Retorna en cuanto se detecta una colisión
|
||||
}
|
||||
|
||||
return false; // No se encontró ninguna colisión
|
||||
}
|
||||
|
||||
// Establece el color del jugador (0 = automático según cheats)
|
||||
void Player::setColor(Uint8 color) {
|
||||
if (color != 0) {
|
||||
color_ = color;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Options::cheats.invincible == Options::Cheat::State::ENABLED) {
|
||||
color_ = Color::index(Color::Cpc::CYAN);
|
||||
} else if (Options::cheats.infinite_lives == Options::Cheat::State::ENABLED) {
|
||||
color_ = Color::index(Color::Cpc::YELLOW);
|
||||
} else {
|
||||
color_ = Color::index(Color::Cpc::WHITE);
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza los puntos de colisión
|
||||
void Player::updateColliderPoints() {
|
||||
const SDL_FRect RECT = getRect();
|
||||
collider_points_[0] = {.x = RECT.x, .y = RECT.y};
|
||||
collider_points_[1] = {.x = RECT.x + 7, .y = RECT.y};
|
||||
collider_points_[2] = {.x = RECT.x + 7, .y = RECT.y + 7};
|
||||
collider_points_[3] = {.x = RECT.x, .y = RECT.y + 7};
|
||||
collider_points_[4] = {.x = RECT.x, .y = RECT.y + 8};
|
||||
collider_points_[5] = {.x = RECT.x + 7, .y = RECT.y + 8};
|
||||
collider_points_[6] = {.x = RECT.x + 7, .y = RECT.y + 15};
|
||||
collider_points_[7] = {.x = RECT.x, .y = RECT.y + 15};
|
||||
}
|
||||
|
||||
// Actualiza los puntos de los pies
|
||||
void Player::updateFeet() {
|
||||
under_left_foot_ = {
|
||||
.x = x_,
|
||||
.y = y_ + HEIGHT};
|
||||
under_right_foot_ = {
|
||||
.x = x_ + WIDTH - 1,
|
||||
.y = y_ + HEIGHT};
|
||||
}
|
||||
|
||||
// Aplica los valores de spawn al jugador
|
||||
void Player::applySpawnValues(const SpawnData& spawn) {
|
||||
x_ = spawn.x;
|
||||
y_ = spawn.y;
|
||||
y_prev_ = spawn.y; // Inicializar y_prev_ igual a y_ para evitar saltos en primer frame
|
||||
vx_ = spawn.vx;
|
||||
vy_ = spawn.vy;
|
||||
last_grounded_position_ = spawn.last_grounded_position;
|
||||
state_ = spawn.state;
|
||||
sprite_->setFlip(spawn.flip);
|
||||
}
|
||||
|
||||
// Inicializa el sprite del jugador
|
||||
void Player::initSprite(const std::string& animations_path) {
|
||||
const auto& animation_data = Resource::Cache::get()->getAnimationData(animations_path);
|
||||
sprite_ = std::make_unique<SurfaceAnimatedSprite>(animation_data);
|
||||
sprite_->setWidth(WIDTH);
|
||||
sprite_->setHeight(HEIGHT);
|
||||
sprite_->setCurrentAnimation("walk");
|
||||
}
|
||||
|
||||
// Actualiza la posición del sprite y las colisiones
|
||||
void Player::syncSpriteAndCollider() {
|
||||
placeSprite(); // Coloca el sprite en la posición del jugador
|
||||
collider_box_ = getRect(); // Actualiza el rectangulo de colisión
|
||||
updateColliderPoints(); // Actualiza los puntos de colisión
|
||||
#ifdef _DEBUG
|
||||
updateFeet();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Coloca el sprite en la posición del jugador
|
||||
void Player::placeSprite() {
|
||||
sprite_->setPos(x_, y_);
|
||||
}
|
||||
|
||||
// Calcula la velocidad en x con sistema caminar/correr y momentum
|
||||
void Player::updateVelocity(float delta_time) {
|
||||
if (auto_movement_) {
|
||||
// La cinta transportadora tiene el control (velocidad fija)
|
||||
vx_ = RUN_VELOCITY * room_->getConveyorBeltDirection();
|
||||
sprite_->setFlip(vx_ < 0.0F ? Flip::LEFT : Flip::RIGHT);
|
||||
movement_time_ = 0.0F;
|
||||
} else {
|
||||
// El jugador tiene el control
|
||||
switch (wanna_go_) {
|
||||
case Direction::LEFT:
|
||||
movement_time_ += delta_time;
|
||||
if (movement_time_ < TIME_TO_RUN) {
|
||||
// Caminando: velocidad fija inmediata
|
||||
vx_ = -WALK_VELOCITY;
|
||||
} else {
|
||||
// Corriendo: acelerar hacia RUN_VELOCITY
|
||||
vx_ -= RUN_ACCELERATION * delta_time;
|
||||
vx_ = std::max(vx_, -RUN_VELOCITY);
|
||||
}
|
||||
sprite_->setFlip(Flip::LEFT);
|
||||
break;
|
||||
case Direction::RIGHT:
|
||||
movement_time_ += delta_time;
|
||||
if (movement_time_ < TIME_TO_RUN) {
|
||||
// Caminando: velocidad fija inmediata
|
||||
vx_ = WALK_VELOCITY;
|
||||
} else {
|
||||
// Corriendo: acelerar hacia RUN_VELOCITY
|
||||
vx_ += RUN_ACCELERATION * delta_time;
|
||||
vx_ = std::min(vx_, RUN_VELOCITY);
|
||||
}
|
||||
sprite_->setFlip(Flip::RIGHT);
|
||||
break;
|
||||
case Direction::NONE:
|
||||
movement_time_ = 0.0F;
|
||||
// Desacelerar gradualmente (momentum)
|
||||
if (vx_ > 0.0F) {
|
||||
vx_ -= HORIZONTAL_DECELERATION * delta_time;
|
||||
vx_ = std::max(vx_, 0.0F);
|
||||
} else if (vx_ < 0.0F) {
|
||||
vx_ += HORIZONTAL_DECELERATION * delta_time;
|
||||
vx_ = std::min(vx_, 0.0F);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Aplica movimiento horizontal con colisión de muros
|
||||
void Player::applyHorizontalMovement(float delta_time) {
|
||||
if (vx_ == 0.0F) { return; }
|
||||
|
||||
const float DISPLACEMENT = vx_ * delta_time;
|
||||
if (vx_ < 0.0F) {
|
||||
const SDL_FRect PROJECTION = getProjection(Direction::LEFT, DISPLACEMENT);
|
||||
const int POS = room_->checkRightSurfaces(PROJECTION);
|
||||
if (POS == Collision::NONE) {
|
||||
x_ += DISPLACEMENT;
|
||||
} else {
|
||||
x_ = POS + 1;
|
||||
}
|
||||
} else {
|
||||
const SDL_FRect PROJECTION = getProjection(Direction::RIGHT, DISPLACEMENT);
|
||||
const int POS = room_->checkLeftSurfaces(PROJECTION);
|
||||
if (POS == Collision::NONE) {
|
||||
x_ += DISPLACEMENT;
|
||||
} else {
|
||||
x_ = POS - WIDTH;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Detecta aterrizaje en superficies
|
||||
auto Player::handleLandingFromAir(float displacement, const SDL_FRect& projection) -> bool {
|
||||
// Comprueba la colisión con las superficies y las cintas transportadoras
|
||||
const float POS = std::max(room_->checkTopSurfaces(projection), room_->checkAutoSurfaces(projection));
|
||||
if (POS != Collision::NONE) {
|
||||
// Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
|
||||
y_ = POS - HEIGHT;
|
||||
transitionToState(State::ON_GROUND);
|
||||
Audio::get()->playSound(Defaults::Sound::LAND, Audio::Group::GAME);
|
||||
return true;
|
||||
}
|
||||
|
||||
// No hay colisión
|
||||
y_ += displacement;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Devuelve el rectangulo de proyeccion
|
||||
auto Player::getProjection(Direction direction, float displacement) -> SDL_FRect {
|
||||
switch (direction) {
|
||||
case Direction::LEFT:
|
||||
return {
|
||||
.x = x_ + displacement,
|
||||
.y = y_,
|
||||
.w = std::ceil(std::fabs(displacement)), // Para evitar que tenga una anchura de 0 pixels
|
||||
.h = HEIGHT};
|
||||
|
||||
case Direction::RIGHT:
|
||||
return {
|
||||
.x = x_ + WIDTH,
|
||||
.y = y_,
|
||||
.w = std::ceil(displacement), // Para evitar que tenga una anchura de 0 pixels
|
||||
.h = HEIGHT};
|
||||
|
||||
case Direction::UP:
|
||||
return {
|
||||
.x = x_,
|
||||
.y = y_ + displacement,
|
||||
.w = WIDTH,
|
||||
.h = std::ceil(std::fabs(displacement)) // Para evitar que tenga una altura de 0 pixels
|
||||
};
|
||||
|
||||
case Direction::DOWN:
|
||||
return {
|
||||
.x = x_,
|
||||
.y = y_ + HEIGHT,
|
||||
.w = WIDTH,
|
||||
.h = std::ceil(displacement) // Para evitar que tenga una altura de 0 pixels
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
.x = 0.0F,
|
||||
.y = 0.0F,
|
||||
.w = 0.0F,
|
||||
.h = 0.0F};
|
||||
}
|
||||
}
|
||||
|
||||
// Marca al jugador como muerto
|
||||
void Player::markAsDead() {
|
||||
if (Options::cheats.invincible == Options::Cheat::State::ENABLED) {
|
||||
is_alive_ = true; // No puede morir
|
||||
} else {
|
||||
is_alive_ = false; // Muere
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
// Establece la posición del jugador directamente (debug)
|
||||
void Player::setDebugPosition(float x, float y) {
|
||||
x_ = x;
|
||||
y_ = y;
|
||||
syncSpriteAndCollider();
|
||||
}
|
||||
|
||||
// Fija estado ON_GROUND, velocidades a 0, actualiza last_grounded_position_ (debug)
|
||||
void Player::finalizeDebugTeleport() {
|
||||
vx_ = 0.0F;
|
||||
vy_ = 0.0F;
|
||||
last_grounded_position_ = static_cast<int>(y_);
|
||||
transitionToState(State::ON_GROUND);
|
||||
syncSpriteAndCollider();
|
||||
}
|
||||
#endif
|
||||
174
source/game/entities/player.hpp
Normal file
174
source/game/entities/player.hpp
Normal file
@@ -0,0 +1,174 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array> // Para array
|
||||
#include <limits> // Para numeric_limits
|
||||
#include <memory> // Para shared_ptr, __shared_ptr_access
|
||||
#include <string> // Para string
|
||||
#include <utility>
|
||||
|
||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||
#include "game/gameplay/room.hpp"
|
||||
#include "game/options.hpp" // Para Cheat, Options, options
|
||||
#include "utils/defines.hpp" // Para BORDER_TOP, BLOCK
|
||||
#include "utils/utils.hpp" // Para Color
|
||||
|
||||
class Player {
|
||||
public:
|
||||
// --- Enums y Structs ---
|
||||
enum class State {
|
||||
ON_GROUND, // En suelo plano o conveyor belt
|
||||
ON_AIR, // En el aire (saltando o cayendo)
|
||||
};
|
||||
|
||||
enum class Direction {
|
||||
LEFT,
|
||||
RIGHT,
|
||||
UP,
|
||||
DOWN,
|
||||
NONE
|
||||
};
|
||||
|
||||
|
||||
struct SpawnData {
|
||||
float x = 0;
|
||||
float y = 0;
|
||||
float vx = 0;
|
||||
float vy = 0;
|
||||
int last_grounded_position = 0;
|
||||
State state = State::ON_GROUND;
|
||||
SDL_FlipMode flip = SDL_FLIP_NONE;
|
||||
};
|
||||
|
||||
struct Data {
|
||||
SpawnData spawn_data;
|
||||
std::string animations_path;
|
||||
std::shared_ptr<Room> room = nullptr;
|
||||
};
|
||||
|
||||
// --- Constructor y Destructor ---
|
||||
explicit Player(const Data& player);
|
||||
~Player() = default;
|
||||
|
||||
// --- Funciones ---
|
||||
void render(); // Pinta el enemigo en pantalla
|
||||
void update(float delta_time); // Actualiza las variables del objeto
|
||||
[[nodiscard]] auto isOnBorder() const -> bool { return border_ != Room::Border::NONE; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
||||
[[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra
|
||||
void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
||||
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; } // Obtiene el rectangulo que delimita al jugador
|
||||
auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador
|
||||
auto getSpawnParams() -> SpawnData { return {.x = x_, .y = y_, .vx = vx_, .vy = vy_, .last_grounded_position = last_grounded_position_, .state = state_, .flip = sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador
|
||||
void setColor(Uint8 color = 0); // Establece el color del jugador (0 = automático según cheats)
|
||||
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); } // Establece la habitación en la que se encuentra el jugador
|
||||
//[[nodiscard]] auto isAlive() const -> bool { return is_alive_ || (Options::cheats.invincible == Options::Cheat::State::ENABLED); } // Comprueba si el jugador esta vivo
|
||||
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; } // Comprueba si el jugador esta vivo
|
||||
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
|
||||
|
||||
#ifdef _DEBUG
|
||||
// --- Funciones de debug ---
|
||||
void setDebugPosition(float x, float y); // Establece la posición del jugador directamente (debug)
|
||||
void finalizeDebugTeleport(); // Fija estado ON_GROUND, velocidades a 0, actualiza last_grounded_position_ (debug)
|
||||
#endif
|
||||
|
||||
private:
|
||||
// --- Constantes de tamaño ---
|
||||
static constexpr int WIDTH = 8; // Ancho del jugador en pixels
|
||||
static constexpr int HEIGHT = 16; // Alto del jugador en pixels
|
||||
|
||||
// --- Constantes de movimiento horizontal ---
|
||||
static constexpr float WALK_VELOCITY = 50.0F; // Velocidad al caminar (inmediata) en pixels/segundo
|
||||
static constexpr float RUN_VELOCITY = 80.0F; // Velocidad al correr en pixels/segundo
|
||||
static constexpr float TIME_TO_RUN = 0.8F; // Segundos caminando antes de empezar a correr
|
||||
static constexpr float RUN_ACCELERATION = 150.0F; // Aceleración de caminar a correr en pixels/segundo²
|
||||
static constexpr float HORIZONTAL_DECELERATION = 250.0F; // Desaceleración al soltar (momentum) en pixels/segundo²
|
||||
|
||||
// --- Constantes de salto ---
|
||||
static constexpr float JUMP_VELOCITY = -160.0F; // Impulso de salto en pixels/segundo (más fuerte, menos floaty)
|
||||
static constexpr float GRAVITY_FORCE = 280.0F; // Gravedad en pixels/segundo² (más alta, menos floaty)
|
||||
|
||||
// --- Objetos y punteros ---
|
||||
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
|
||||
std::unique_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del jugador
|
||||
|
||||
// --- Variables de posición y física ---
|
||||
float x_ = 0.0F; // Posición del jugador en el eje X
|
||||
float y_ = 0.0F; // Posición del jugador en el eje Y
|
||||
float y_prev_ = 0.0F; // Posición Y del frame anterior (para detectar hitos de distancia en sonidos)
|
||||
float vx_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje X
|
||||
float vy_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje Y
|
||||
float movement_time_ = 0.0F; // Tiempo que lleva moviéndose en la misma dirección (para transición caminar→correr)
|
||||
|
||||
Direction wanna_go_ = Direction::NONE;
|
||||
bool wanna_jump_ = false;
|
||||
|
||||
// --- Variables de estado ---
|
||||
State state_ = State::ON_GROUND; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
|
||||
State previous_state_ = State::ON_GROUND; // Estado previo en el que se encontraba el jugador
|
||||
|
||||
// --- Variables de colisión ---
|
||||
SDL_FRect collider_box_{}; // Caja de colisión con los enemigos u objetos
|
||||
std::array<SDL_FPoint, 8> collider_points_{}; // Puntos de colisión con el mapa
|
||||
SDL_FPoint under_left_foot_ = {0.0F, 0.0F}; // El punto bajo la esquina inferior izquierda del jugador
|
||||
SDL_FPoint under_right_foot_ = {0.0F, 0.0F}; // El punto bajo la esquina inferior derecha del jugador
|
||||
|
||||
// --- Variables de juego ---
|
||||
bool is_alive_ = true; // Indica si el jugador esta vivo o no
|
||||
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
|
||||
bool auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
|
||||
Room::Border border_ = Room::Border::TOP; // Indica en cual de los cuatro bordes se encuentra
|
||||
int last_grounded_position_ = 0; // Ultima posición en Y en la que se estaba en contacto con el suelo (hace doble función: tracking de caída + altura inicial del salto)
|
||||
|
||||
// --- Variables de renderizado ---
|
||||
Uint8 color_ = 0; // Color del jugador
|
||||
|
||||
void handleConveyorBelts();
|
||||
void handleShouldFall();
|
||||
void updateState(float delta_time);
|
||||
|
||||
// --- Métodos de actualización por estado ---
|
||||
void updateOnGround(float delta_time); // Actualización lógica estado ON_GROUND
|
||||
void updateOnAir(float delta_time); // Actualización lógica estado ON_AIR
|
||||
|
||||
// --- Métodos de movimiento por estado ---
|
||||
void moveOnGround(float delta_time); // Movimiento físico estado ON_GROUND
|
||||
void moveOnAir(float delta_time); // Movimiento físico estado ON_AIR
|
||||
|
||||
// --- Funciones de inicialización ---
|
||||
void initSprite(const std::string& animations_path); // Inicializa el sprite del jugador
|
||||
void applySpawnValues(const SpawnData& spawn); // Aplica los valores de spawn al jugador
|
||||
|
||||
// --- Funciones de procesamiento de entrada ---
|
||||
void handleInput(); // Comprueba las entradas y modifica variables
|
||||
|
||||
// --- Funciones de gestión de estado ---
|
||||
void transitionToState(State state); // Cambia el estado del jugador
|
||||
|
||||
// --- Funciones de física ---
|
||||
void applyGravity(float delta_time); // Aplica gravedad al jugador
|
||||
|
||||
// --- Funciones de movimiento y colisión ---
|
||||
void move(float delta_time); // Orquesta el movimiento del jugador
|
||||
auto getProjection(Direction direction, float displacement) -> SDL_FRect; // Devuelve el rectangulo de proyeccion
|
||||
void applyHorizontalMovement(float delta_time); // Aplica movimiento horizontal con colisión de muros
|
||||
auto handleLandingFromAir(float displacement, const SDL_FRect& projection) -> bool; // Detecta aterrizaje en superficies
|
||||
|
||||
// --- Funciones de detección de superficies ---
|
||||
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
|
||||
auto isOnTopSurface() -> bool; // Comprueba si el jugador está sobre una superficie
|
||||
auto isOnConveyorBelt() -> bool; // Comprueba si el jugador esta sobre una cinta transportadora
|
||||
|
||||
// --- Funciones de actualización de geometría ---
|
||||
void syncSpriteAndCollider(); // Actualiza collider_box y collision points
|
||||
void updateColliderPoints(); // Actualiza los puntos de colisión
|
||||
void updateFeet(); // Actualiza los puntos de los pies
|
||||
void placeSprite(); // Coloca el sprite en la posición del jugador
|
||||
|
||||
// --- Funciones de finalización ---
|
||||
void animate(float delta_time); // Establece la animación del jugador
|
||||
auto handleBorders() -> Room::Border; // Comprueba si se halla en alguno de los cuatro bordes
|
||||
auto handleKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
|
||||
void updateVelocity(float delta_time); // Calcula la velocidad en x con aceleración
|
||||
void markAsDead(); // Marca al jugador como muerto
|
||||
};
|
||||
333
source/game/gameplay/collision_map.cpp
Normal file
333
source/game/gameplay/collision_map.cpp
Normal file
@@ -0,0 +1,333 @@
|
||||
#include "collision_map.hpp"
|
||||
|
||||
#include <algorithm> // Para std::ranges::any_of
|
||||
|
||||
#ifdef _DEBUG
|
||||
#include "core/system/debug.hpp" // Para Debug
|
||||
#endif
|
||||
#include "utils/defines.hpp" // Para Collision
|
||||
|
||||
// Constructor
|
||||
CollisionMap::CollisionMap(std::vector<int> collision_map, int conveyor_belt_direction)
|
||||
: tile_map_(std::move(collision_map)),
|
||||
conveyor_belt_direction_(conveyor_belt_direction) {
|
||||
// Inicializa todas las superficies de colisión
|
||||
initializeSurfaces();
|
||||
}
|
||||
|
||||
// Inicializa todas las superficies de colisión
|
||||
void CollisionMap::initializeSurfaces() {
|
||||
setBottomSurfaces();
|
||||
setTopSurfaces();
|
||||
setLeftSurfaces();
|
||||
setRightSurfaces();
|
||||
setAutoSurfaces();
|
||||
}
|
||||
|
||||
// Devuelve el tipo de tile que hay en ese pixel
|
||||
auto CollisionMap::getTile(SDL_FPoint point) const -> Tile {
|
||||
const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
|
||||
return getTile(POS);
|
||||
}
|
||||
|
||||
// Devuelve el tipo de tile que hay en ese indice
|
||||
// Mapeo directo desde collisionmap: 1=WALL, 2=PASSABLE, 3=ANIMATED, 6=KILL
|
||||
auto CollisionMap::getTile(int index) const -> Tile {
|
||||
const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size());
|
||||
|
||||
if (ON_RANGE) {
|
||||
switch (tile_map_[index]) {
|
||||
case 1:
|
||||
return Tile::WALL;
|
||||
case 2:
|
||||
return Tile::PASSABLE;
|
||||
case 3:
|
||||
return Tile::ANIMATED;
|
||||
case 6:
|
||||
return Tile::KILL;
|
||||
default:
|
||||
return Tile::EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
return Tile::EMPTY;
|
||||
}
|
||||
|
||||
// === Queries de colisión ===
|
||||
|
||||
// Comprueba las colisiones con paredes derechas
|
||||
auto CollisionMap::checkRightSurfaces(const SDL_FRect& rect) -> int {
|
||||
for (const auto& s : right_walls_) {
|
||||
if (checkCollision(s, rect)) {
|
||||
return s.x;
|
||||
}
|
||||
}
|
||||
return Collision::NONE;
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con paredes izquierdas
|
||||
auto CollisionMap::checkLeftSurfaces(const SDL_FRect& rect) -> int {
|
||||
for (const auto& s : left_walls_) {
|
||||
if (checkCollision(s, rect)) {
|
||||
return s.x;
|
||||
}
|
||||
}
|
||||
return Collision::NONE;
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con techos
|
||||
auto CollisionMap::checkTopSurfaces(const SDL_FRect& rect) -> int {
|
||||
for (const auto& s : top_floors_) {
|
||||
if (checkCollision(s, rect)) {
|
||||
return s.y;
|
||||
}
|
||||
}
|
||||
return Collision::NONE;
|
||||
}
|
||||
|
||||
// Comprueba las colisiones punto con techos
|
||||
auto CollisionMap::checkTopSurfaces(const SDL_FPoint& p) -> bool {
|
||||
return std::ranges::any_of(top_floors_, [&](const auto& s) {
|
||||
return checkCollision(s, p);
|
||||
});
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con suelos
|
||||
auto CollisionMap::checkBottomSurfaces(const SDL_FRect& rect) -> int {
|
||||
for (const auto& s : bottom_floors_) {
|
||||
if (checkCollision(s, rect)) {
|
||||
return s.y;
|
||||
}
|
||||
}
|
||||
return Collision::NONE;
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con conveyor belts
|
||||
auto CollisionMap::checkAutoSurfaces(const SDL_FRect& rect) -> int {
|
||||
for (const auto& s : conveyor_belt_floors_) {
|
||||
if (checkCollision(s, rect)) {
|
||||
return s.y;
|
||||
}
|
||||
}
|
||||
return Collision::NONE;
|
||||
}
|
||||
|
||||
// Comprueba las colisiones punto con conveyor belts
|
||||
auto CollisionMap::checkConveyorBelts(const SDL_FPoint& p) -> bool {
|
||||
return std::ranges::any_of(conveyor_belt_floors_, [&](const auto& s) {
|
||||
return checkCollision(s, p);
|
||||
});
|
||||
}
|
||||
|
||||
// === Helpers para recopilar tiles ===
|
||||
|
||||
// Helper: recopila tiles inferiores (muros sin muro debajo)
|
||||
auto CollisionMap::collectBottomTiles() -> std::vector<int> {
|
||||
std::vector<int> tile;
|
||||
|
||||
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
|
||||
// Hay que recorrer la habitación por filas (excepto los de la última fila)
|
||||
for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH; ++i) {
|
||||
if (getTile(i) == Tile::WALL && getTile(i + MAP_WIDTH) != Tile::WALL) {
|
||||
tile.push_back(i);
|
||||
|
||||
// Si llega al final de la fila, introduce un separador
|
||||
if (i % MAP_WIDTH == MAP_WIDTH - 1) {
|
||||
tile.push_back(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Añade un terminador
|
||||
tile.push_back(-1);
|
||||
return tile;
|
||||
}
|
||||
|
||||
// Helper: recopila tiles superiores (muros o pasables sin muro encima)
|
||||
auto CollisionMap::collectTopTiles() -> std::vector<int> {
|
||||
std::vector<int> tile;
|
||||
|
||||
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
|
||||
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
|
||||
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
|
||||
if ((getTile(i) == Tile::WALL || getTile(i) == Tile::PASSABLE) && getTile(i - MAP_WIDTH) != Tile::WALL) {
|
||||
tile.push_back(i);
|
||||
|
||||
// Si llega al final de la fila, introduce un separador
|
||||
if (i % MAP_WIDTH == MAP_WIDTH - 1) {
|
||||
tile.push_back(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Añade un terminador
|
||||
tile.push_back(-1);
|
||||
return tile;
|
||||
}
|
||||
|
||||
// Helper: recopila tiles animados (para superficies automaticas/conveyor belts)
|
||||
auto CollisionMap::collectAnimatedTiles() -> std::vector<int> {
|
||||
std::vector<int> tile;
|
||||
|
||||
// Busca todos los tiles de tipo animado
|
||||
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
|
||||
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
|
||||
if (getTile(i) == Tile::ANIMATED) {
|
||||
tile.push_back(i);
|
||||
|
||||
// Si llega al final de la fila, introduce un separador
|
||||
if (i % MAP_WIDTH == MAP_WIDTH - 1) {
|
||||
tile.push_back(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Añade un terminador si hay tiles
|
||||
if (!tile.empty()) {
|
||||
tile.push_back(-1);
|
||||
}
|
||||
|
||||
return tile;
|
||||
}
|
||||
|
||||
// Helper: construye lineas horizontales a partir de tiles consecutivos
|
||||
void CollisionMap::buildHorizontalLines(const std::vector<int>& tiles, std::vector<LineHorizontal>& lines, bool is_bottom_surface) {
|
||||
if (tiles.size() <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
while (i < (int)tiles.size() - 1) {
|
||||
LineHorizontal line;
|
||||
line.x1 = (tiles[i] % MAP_WIDTH) * TILE_SIZE;
|
||||
|
||||
// Calcula Y segun si es superficie inferior o superior
|
||||
if (is_bottom_surface) {
|
||||
line.y = ((tiles[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
|
||||
} else {
|
||||
line.y = (tiles[i] / MAP_WIDTH) * TILE_SIZE;
|
||||
}
|
||||
|
||||
int last_one = i;
|
||||
i++;
|
||||
|
||||
// Encuentra tiles consecutivos
|
||||
if (i < (int)tiles.size()) {
|
||||
while (tiles[i] == tiles[i - 1] + 1) {
|
||||
last_one = i;
|
||||
i++;
|
||||
if (i >= (int)tiles.size()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
line.x2 = ((tiles[last_one] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
|
||||
lines.push_back(line);
|
||||
|
||||
// Salta separadores
|
||||
if (i < (int)tiles.size() && tiles[i] == -1) {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Métodos de generación de geometría ===
|
||||
|
||||
// Calcula las superficies inferiores
|
||||
void CollisionMap::setBottomSurfaces() {
|
||||
std::vector<int> tile = collectBottomTiles();
|
||||
buildHorizontalLines(tile, bottom_floors_, true);
|
||||
}
|
||||
|
||||
// Calcula las superficies superiores
|
||||
void CollisionMap::setTopSurfaces() {
|
||||
std::vector<int> tile = collectTopTiles();
|
||||
buildHorizontalLines(tile, top_floors_, false);
|
||||
}
|
||||
|
||||
// Calcula las superficies laterales izquierdas
|
||||
void CollisionMap::setLeftSurfaces() {
|
||||
std::vector<int> tile;
|
||||
|
||||
// Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro
|
||||
// Hay que recorrer la habitación por columnas (excepto los de la primera columna)
|
||||
for (int i = 1; i < MAP_WIDTH; ++i) {
|
||||
for (int j = 0; j < MAP_HEIGHT; ++j) {
|
||||
const int POS = ((j * MAP_WIDTH) + i);
|
||||
if (getTile(POS) == Tile::WALL && getTile(POS - 1) != Tile::WALL) {
|
||||
tile.push_back(POS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Añade un terminador
|
||||
tile.push_back(-1);
|
||||
|
||||
// Recorre el vector de tiles buscando tiles consecutivos
|
||||
// (Los tiles de la misma columna, la diferencia entre ellos es de mapWidth)
|
||||
// para localizar las superficies
|
||||
if ((int)tile.size() > 1) {
|
||||
int i = 0;
|
||||
do {
|
||||
LineVertical line;
|
||||
line.x = (tile[i] % MAP_WIDTH) * TILE_SIZE;
|
||||
line.y1 = ((tile[i] / MAP_WIDTH) * TILE_SIZE);
|
||||
while (tile[i] + MAP_WIDTH == tile[i + 1]) {
|
||||
if (i == (int)tile.size() - 1) {
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
line.y2 = ((tile[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
|
||||
left_walls_.push_back(line);
|
||||
i++;
|
||||
} while (i < (int)tile.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Calcula las superficies laterales derechas
|
||||
void CollisionMap::setRightSurfaces() {
|
||||
std::vector<int> tile;
|
||||
|
||||
// Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro
|
||||
// Hay que recorrer la habitación por columnas (excepto los de la última columna)
|
||||
for (int i = 0; i < MAP_WIDTH - 1; ++i) {
|
||||
for (int j = 0; j < MAP_HEIGHT; ++j) {
|
||||
const int POS = ((j * MAP_WIDTH) + i);
|
||||
if (getTile(POS) == Tile::WALL && getTile(POS + 1) != Tile::WALL) {
|
||||
tile.push_back(POS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Añade un terminador
|
||||
tile.push_back(-1);
|
||||
|
||||
// Recorre el vector de tiles buscando tiles consecutivos
|
||||
// (Los tiles de la misma columna, la diferencia entre ellos es de mapWidth)
|
||||
// para localizar las superficies
|
||||
if ((int)tile.size() > 1) {
|
||||
int i = 0;
|
||||
do {
|
||||
LineVertical line;
|
||||
line.x = ((tile[i] % MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
|
||||
line.y1 = ((tile[i] / MAP_WIDTH) * TILE_SIZE);
|
||||
while (tile[i] + MAP_WIDTH == tile[i + 1]) {
|
||||
if (i == (int)tile.size() - 1) {
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
line.y2 = ((tile[i] / MAP_WIDTH) * TILE_SIZE) + TILE_SIZE - 1;
|
||||
right_walls_.push_back(line);
|
||||
i++;
|
||||
} while (i < (int)tile.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Calcula las superficies automaticas (conveyor belts)
|
||||
void CollisionMap::setAutoSurfaces() {
|
||||
std::vector<int> tile = collectAnimatedTiles();
|
||||
buildHorizontalLines(tile, conveyor_belt_floors_, false);
|
||||
}
|
||||
104
source/game/gameplay/collision_map.hpp
Normal file
104
source/game/gameplay/collision_map.hpp
Normal file
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "utils/defines.hpp" // Para Tile::SIZE, PlayArea
|
||||
#include "utils/utils.hpp" // Para LineHorizontal, LineVertical
|
||||
|
||||
/**
|
||||
* @brief Mapa de colisiones de una habitación
|
||||
*
|
||||
* Responsabilidades:
|
||||
* - Almacenar la geometría de colisión (superficies, conveyor belts)
|
||||
* - Generar geometría a partir del tilemap
|
||||
* - Proporcionar queries de colisión para Player y otras entidades
|
||||
* - Determinar tipo de tile en posiciones específicas
|
||||
*/
|
||||
class CollisionMap {
|
||||
public:
|
||||
// Enumeración de tipos de tile (para colisiones)
|
||||
enum class Tile {
|
||||
EMPTY,
|
||||
WALL,
|
||||
PASSABLE,
|
||||
KILL,
|
||||
ANIMATED
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Constructor
|
||||
* @param collision_map Vector con índices de colisión (1=WALL, 2=PASSABLE, etc.)
|
||||
* @param conveyor_belt_direction Dirección de las cintas transportadoras (-1, 0, +1)
|
||||
*/
|
||||
CollisionMap(std::vector<int> collision_map, int conveyor_belt_direction);
|
||||
~CollisionMap() = default;
|
||||
|
||||
// Prohibir copia y movimiento
|
||||
CollisionMap(const CollisionMap&) = delete;
|
||||
auto operator=(const CollisionMap&) -> CollisionMap& = delete;
|
||||
CollisionMap(CollisionMap&&) = delete;
|
||||
auto operator=(CollisionMap&&) -> CollisionMap& = delete;
|
||||
|
||||
// --- Queries de tipo de tile ---
|
||||
[[nodiscard]] auto getTile(SDL_FPoint point) const -> Tile; // Devuelve el tipo de tile en un punto (pixel)
|
||||
[[nodiscard]] auto getTile(int index) const -> Tile; // Devuelve el tipo de tile en un índice del tilemap
|
||||
|
||||
// --- Queries de colisión con superficies ---
|
||||
auto checkRightSurfaces(const SDL_FRect& rect) -> int; // Colisión con paredes derechas (retorna X)
|
||||
auto checkLeftSurfaces(const SDL_FRect& rect) -> int; // Colisión con paredes izquierdas (retorna X)
|
||||
auto checkTopSurfaces(const SDL_FRect& rect) -> int; // Colisión con techos (retorna Y)
|
||||
auto checkTopSurfaces(const SDL_FPoint& p) -> bool; // Colisión punto con techos
|
||||
auto checkBottomSurfaces(const SDL_FRect& rect) -> int; // Colisión con suelos (retorna Y)
|
||||
|
||||
// --- Queries de colisión con superficies automáticas (conveyor belts) ---
|
||||
auto checkAutoSurfaces(const SDL_FRect& rect) -> int; // Colisión con conveyor belts (retorna Y)
|
||||
auto checkConveyorBelts(const SDL_FPoint& p) -> bool; // Colisión punto con conveyor belts
|
||||
|
||||
// --- Métodos estáticos ---
|
||||
static auto getTileSize() -> int { return TILE_SIZE; } // Tamaño del tile en pixels
|
||||
|
||||
// --- Getters ---
|
||||
[[nodiscard]] auto getConveyorBeltDirection() const -> int { return conveyor_belt_direction_; }
|
||||
|
||||
// Getters para debug visualization
|
||||
[[nodiscard]] auto getBottomFloors() const -> const std::vector<LineHorizontal>& { return bottom_floors_; }
|
||||
[[nodiscard]] auto getTopFloors() const -> const std::vector<LineHorizontal>& { return top_floors_; }
|
||||
[[nodiscard]] auto getLeftWalls() const -> const std::vector<LineVertical>& { return left_walls_; }
|
||||
[[nodiscard]] auto getRightWalls() const -> const std::vector<LineVertical>& { return right_walls_; }
|
||||
[[nodiscard]] auto getConveyorBeltFloors() const -> const std::vector<LineHorizontal>& { return conveyor_belt_floors_; }
|
||||
|
||||
private:
|
||||
// --- Constantes (usar defines de PlayArea) ---
|
||||
static constexpr int TILE_SIZE = ::Tile::SIZE; // Tamaño del tile en pixels
|
||||
static constexpr int MAP_WIDTH = PlayArea::TILE_COLS; // Ancho del mapa en tiles
|
||||
static constexpr int MAP_HEIGHT = PlayArea::TILE_ROWS; // Alto del mapa en tiles
|
||||
|
||||
// --- Datos de la habitación ---
|
||||
std::vector<int> tile_map_; // Índices de colisión de la habitación
|
||||
int conveyor_belt_direction_; // Dirección de conveyor belts
|
||||
|
||||
// --- Geometría de colisión ---
|
||||
std::vector<LineHorizontal> bottom_floors_; // Superficies inferiores (suelos)
|
||||
std::vector<LineHorizontal> top_floors_; // Superficies superiores (techos)
|
||||
std::vector<LineVertical> left_walls_; // Paredes izquierdas
|
||||
std::vector<LineVertical> right_walls_; // Paredes derechas
|
||||
std::vector<LineHorizontal> conveyor_belt_floors_; // Superficies automáticas (conveyor belts)
|
||||
|
||||
// --- Métodos privados de generación de geometría ---
|
||||
void initializeSurfaces(); // Inicializa todas las superficies de colisión
|
||||
|
||||
// Helpers para recopilar tiles
|
||||
auto collectBottomTiles() -> std::vector<int>; // Tiles con superficie inferior
|
||||
auto collectTopTiles() -> std::vector<int>; // Tiles con superficie superior
|
||||
auto collectAnimatedTiles() -> std::vector<int>; // Tiles animados (conveyor belts)
|
||||
|
||||
// Construcción de geometría
|
||||
static void buildHorizontalLines(const std::vector<int>& tiles, std::vector<LineHorizontal>& lines, bool is_bottom_surface);
|
||||
void setBottomSurfaces(); // Calcula superficies inferiores
|
||||
void setTopSurfaces(); // Calcula superficies superiores
|
||||
void setLeftSurfaces(); // Calcula paredes izquierdas
|
||||
void setRightSurfaces(); // Calcula paredes derechas
|
||||
void setAutoSurfaces(); // Calcula conveyor belts
|
||||
};
|
||||
49
source/game/gameplay/enemy_manager.cpp
Normal file
49
source/game/gameplay/enemy_manager.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#include "enemy_manager.hpp"
|
||||
|
||||
#include <algorithm> // Para std::ranges::any_of
|
||||
|
||||
#include "game/entities/enemy.hpp" // Para Enemy
|
||||
#include "utils/utils.hpp" // Para checkCollision
|
||||
|
||||
// Añade un enemigo a la colección
|
||||
void EnemyManager::addEnemy(std::shared_ptr<Enemy> enemy) {
|
||||
enemies_.push_back(std::move(enemy));
|
||||
}
|
||||
|
||||
// Elimina todos los enemigos
|
||||
void EnemyManager::clear() {
|
||||
enemies_.clear();
|
||||
}
|
||||
|
||||
// Elimina el último enemigo de la colección
|
||||
void EnemyManager::removeLastEnemy() {
|
||||
if (!enemies_.empty()) {
|
||||
enemies_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si no hay enemigos
|
||||
auto EnemyManager::isEmpty() const -> bool {
|
||||
return enemies_.empty();
|
||||
}
|
||||
|
||||
// Actualiza todos los enemigos
|
||||
void EnemyManager::update(float delta_time) {
|
||||
for (const auto& enemy : enemies_) {
|
||||
enemy->update(delta_time);
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza todos los enemigos
|
||||
void EnemyManager::render() {
|
||||
for (const auto& enemy : enemies_) {
|
||||
enemy->render();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si hay colisión con algún enemigo
|
||||
auto EnemyManager::checkCollision(SDL_FRect& rect) -> bool {
|
||||
return std::ranges::any_of(enemies_, [&rect](const auto& enemy) {
|
||||
return ::checkCollision(rect, enemy->getCollider());
|
||||
});
|
||||
}
|
||||
45
source/game/gameplay/enemy_manager.hpp
Normal file
45
source/game/gameplay/enemy_manager.hpp
Normal file
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <vector> // Para vector
|
||||
|
||||
class Enemy;
|
||||
|
||||
/**
|
||||
* @brief Gestor de enemigos de una habitación
|
||||
*
|
||||
* Responsabilidades:
|
||||
* - Almacenar y gestionar la colección de enemigos
|
||||
* - Actualizar todos los enemigos
|
||||
* - Renderizar todos los enemigos
|
||||
* - Detectar colisiones con enemigos
|
||||
*/
|
||||
class EnemyManager {
|
||||
public:
|
||||
EnemyManager() = default;
|
||||
~EnemyManager() = default;
|
||||
|
||||
// Prohibir copia y movimiento para evitar duplicación accidental
|
||||
EnemyManager(const EnemyManager&) = delete;
|
||||
auto operator=(const EnemyManager&) -> EnemyManager& = delete;
|
||||
EnemyManager(EnemyManager&&) = delete;
|
||||
auto operator=(EnemyManager&&) -> EnemyManager& = delete;
|
||||
|
||||
// Gestión de enemigos
|
||||
void addEnemy(std::shared_ptr<Enemy> enemy); // Añade un enemigo a la colección
|
||||
void clear(); // Elimina todos los enemigos
|
||||
void removeLastEnemy(); // Elimina el último enemigo de la colección
|
||||
[[nodiscard]] auto isEmpty() const -> bool; // Comprueba si no hay enemigos
|
||||
|
||||
// Actualización y renderizado
|
||||
void update(float delta_time); // Actualiza todos los enemigos
|
||||
void render(); // Renderiza todos los enemigos
|
||||
|
||||
// Detección de colisiones
|
||||
auto checkCollision(SDL_FRect& rect) -> bool; // Comprueba si hay colisión con algún enemigo
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Enemy>> enemies_; // Colección de enemigos
|
||||
};
|
||||
68
source/game/gameplay/item_manager.cpp
Normal file
68
source/game/gameplay/item_manager.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
#include "item_manager.hpp"
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "game/entities/item.hpp" // Para Item
|
||||
#include "game/options.hpp" // Para Options
|
||||
#include "item_tracker.hpp" // Para ItemTracker
|
||||
#include "scoreboard.hpp" // Para Scoreboard::Data
|
||||
#include "utils/utils.hpp" // Para checkCollision
|
||||
|
||||
// Constructor
|
||||
ItemManager::ItemManager(std::string room_name, std::shared_ptr<Scoreboard::Data> scoreboard_data)
|
||||
: room_name_(std::move(room_name)),
|
||||
data_(std::move(scoreboard_data)) {
|
||||
}
|
||||
|
||||
// Añade un item a la colección
|
||||
void ItemManager::addItem(std::shared_ptr<Item> item) {
|
||||
items_.push_back(std::move(item));
|
||||
}
|
||||
|
||||
// Elimina todos los items
|
||||
void ItemManager::clear() {
|
||||
items_.clear();
|
||||
}
|
||||
|
||||
// Actualiza todos los items
|
||||
void ItemManager::update(float delta_time) {
|
||||
for (const auto& item : items_) {
|
||||
item->update(delta_time);
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza todos los items
|
||||
void ItemManager::render() {
|
||||
for (const auto& item : items_) {
|
||||
item->render();
|
||||
}
|
||||
}
|
||||
|
||||
// Pausa/despausa todos los items
|
||||
void ItemManager::setPaused(bool paused) {
|
||||
for (const auto& item : items_) {
|
||||
item->setPaused(paused);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si hay colisión con algún item
|
||||
auto ItemManager::checkCollision(SDL_FRect& rect) -> bool {
|
||||
for (int i = 0; i < static_cast<int>(items_.size()); ++i) {
|
||||
if (::checkCollision(rect, items_.at(i)->getCollider())) {
|
||||
// Registra el item como recogido
|
||||
ItemTracker::get()->addItem(room_name_, items_.at(i)->getPos());
|
||||
|
||||
// Elimina el item de la colección
|
||||
items_.erase(items_.begin() + i);
|
||||
|
||||
// Reproduce el sonido de pickup
|
||||
Audio::get()->playSound("item.wav", Audio::Group::GAME);
|
||||
|
||||
// Actualiza el scoreboard
|
||||
data_->items++;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
69
source/game/gameplay/item_manager.hpp
Normal file
69
source/game/gameplay/item_manager.hpp
Normal file
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "scoreboard.hpp" // Para Scoreboard::Data
|
||||
|
||||
class Item;
|
||||
|
||||
/**
|
||||
* @brief Gestor de items de una habitación
|
||||
*
|
||||
* Responsabilidades:
|
||||
* - Almacenar y gestionar la colección de items
|
||||
* - Actualizar todos los items
|
||||
* - Renderizar todos los items
|
||||
* - Detectar colisiones con items y gestionar pickup
|
||||
* - Integración con ItemTracker, Scoreboard y Audio
|
||||
*/
|
||||
class ItemManager {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor
|
||||
* @param room_name Nombre de la habitación (para ItemTracker)
|
||||
* @param scoreboard_data Puntero compartido a los datos del scoreboard
|
||||
*/
|
||||
ItemManager(std::string room_name, std::shared_ptr<Scoreboard::Data> scoreboard_data);
|
||||
~ItemManager() = default;
|
||||
|
||||
// Prohibir copia y movimiento para evitar duplicación accidental
|
||||
ItemManager(const ItemManager&) = delete;
|
||||
auto operator=(const ItemManager&) -> ItemManager& = delete;
|
||||
ItemManager(ItemManager&&) = delete;
|
||||
auto operator=(ItemManager&&) -> ItemManager& = delete;
|
||||
|
||||
// Gestión de items
|
||||
void addItem(std::shared_ptr<Item> item); // Añade un item a la colección
|
||||
void clear(); // Elimina todos los items
|
||||
|
||||
// Actualización y renderizado
|
||||
void update(float delta_time); // Actualiza todos los items
|
||||
void render(); // Renderiza todos los items
|
||||
|
||||
// Estado
|
||||
void setPaused(bool paused); // Pausa/despausa todos los items
|
||||
|
||||
// Detección de colisiones
|
||||
/**
|
||||
* @brief Comprueba si hay colisión con algún item
|
||||
*
|
||||
* Si hay colisión:
|
||||
* - Añade el item a ItemTracker
|
||||
* - Elimina el item de la colección
|
||||
* - Reproduce el sonido de pickup
|
||||
* - Actualiza el scoreboard y estadísticas
|
||||
*
|
||||
* @param rect Rectángulo de colisión
|
||||
* @return true si hubo colisión, false en caso contrario
|
||||
*/
|
||||
auto checkCollision(SDL_FRect& rect) -> bool;
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Item>> items_; // Colección de items
|
||||
std::string room_name_; // Nombre de la habitación
|
||||
std::shared_ptr<Scoreboard::Data> data_; // Datos del scoreboard
|
||||
};
|
||||
75
source/game/gameplay/item_tracker.cpp
Normal file
75
source/game/gameplay/item_tracker.cpp
Normal file
@@ -0,0 +1,75 @@
|
||||
#include "game/gameplay/item_tracker.hpp"
|
||||
|
||||
// [SINGLETON]
|
||||
ItemTracker* ItemTracker::item_tracker = nullptr;
|
||||
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void ItemTracker::init() {
|
||||
ItemTracker::item_tracker = new ItemTracker();
|
||||
}
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void ItemTracker::destroy() {
|
||||
delete ItemTracker::item_tracker;
|
||||
}
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
auto ItemTracker::get() -> ItemTracker* {
|
||||
return ItemTracker::item_tracker;
|
||||
}
|
||||
|
||||
// Comprueba si el objeto ya ha sido cogido
|
||||
auto ItemTracker::hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool {
|
||||
// Primero busca si ya hay una entrada con ese nombre
|
||||
if (const int INDEX = findByName(name); INDEX != NOT_FOUND) {
|
||||
// Luego busca si existe ya una entrada con esa posición
|
||||
if (findByPos(INDEX, pos) != NOT_FOUND) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Añade el objeto a la lista de objetos cogidos
|
||||
void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) {
|
||||
// Comprueba si el objeto no ha sido recogido con anterioridad
|
||||
if (!hasBeenPicked(name, pos)) {
|
||||
// Primero busca si ya hay una entrada con ese nombre
|
||||
if (const int INDEX = findByName(name); INDEX != NOT_FOUND) {
|
||||
items_.at(INDEX).pos.push_back(pos);
|
||||
}
|
||||
// En caso contrario crea la entrada
|
||||
else {
|
||||
items_.emplace_back(name, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Busca una entrada en la lista por nombre
|
||||
auto ItemTracker::findByName(const std::string& name) -> int {
|
||||
int i = 0;
|
||||
|
||||
for (const auto& item : items_) {
|
||||
if (item.name == name) {
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
// Busca una entrada en la lista por posición
|
||||
auto ItemTracker::findByPos(int index, SDL_FPoint pos) -> int {
|
||||
int i = 0;
|
||||
|
||||
for (const auto& item : items_[index].pos) {
|
||||
if ((item.x == pos.x) && (item.y == pos.y)) {
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
return NOT_FOUND;
|
||||
}
|
||||
49
source/game/gameplay/item_tracker.hpp
Normal file
49
source/game/gameplay/item_tracker.hpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string> // Para string, basic_string
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
|
||||
class ItemTracker {
|
||||
public:
|
||||
// Gestión singleton
|
||||
static void init(); // Inicialización
|
||||
static void destroy(); // Destrucción
|
||||
static auto get() -> ItemTracker*; // Acceso al singleton
|
||||
|
||||
// Gestión de items
|
||||
auto hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool; // Comprueba si el objeto ya ha sido cogido
|
||||
void addItem(const std::string& name, SDL_FPoint pos); // Añade el objeto a la lista
|
||||
|
||||
private:
|
||||
// Tipos anidados privados
|
||||
struct Data {
|
||||
std::string name; // Nombre de la habitación donde se encuentra el objeto
|
||||
std::vector<SDL_FPoint> pos; // Lista de objetos cogidos de la habitación
|
||||
|
||||
// Constructor para facilitar creación con posición inicial
|
||||
Data(std::string name, const SDL_FPoint& position)
|
||||
: name(std::move(name)) {
|
||||
pos.push_back(position);
|
||||
}
|
||||
};
|
||||
|
||||
// Constantes privadas
|
||||
static constexpr int NOT_FOUND = -1; // Valor de retorno cuando no se encuentra un elemento
|
||||
|
||||
// Constantes singleton
|
||||
static ItemTracker* item_tracker; // [SINGLETON] Objeto privado
|
||||
|
||||
// Métodos privados
|
||||
auto findByName(const std::string& name) -> int; // Busca una entrada en la lista por nombre
|
||||
auto findByPos(int index, SDL_FPoint pos) -> int; // Busca una entrada en la lista por posición
|
||||
|
||||
// Constructor y destructor privados [SINGLETON]
|
||||
ItemTracker() = default;
|
||||
~ItemTracker() = default;
|
||||
|
||||
// Variables miembro
|
||||
std::vector<Data> items_; // Lista con todos los objetos recogidos
|
||||
};
|
||||
232
source/game/gameplay/room.cpp
Normal file
232
source/game/gameplay/room.cpp
Normal file
@@ -0,0 +1,232 @@
|
||||
#include "game/gameplay/room.hpp"
|
||||
|
||||
#include <utility> // Para std::move
|
||||
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "game/gameplay/collision_map.hpp" // Para CollisionMap
|
||||
#include "game/gameplay/enemy_manager.hpp" // Para EnemyManager
|
||||
#include "game/gameplay/item_manager.hpp" // Para ItemManager
|
||||
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
||||
#include "game/gameplay/room_loader.hpp" // Para RoomLoader
|
||||
#include "game/gameplay/scoreboard.hpp" // Para Scoreboard::Data
|
||||
#include "game/gameplay/tilemap_renderer.hpp" // Para TilemapRenderer
|
||||
#include "utils/defines.hpp" // Para TILE_SIZE
|
||||
#include "utils/utils.hpp" // Para stringToColor
|
||||
|
||||
// Constructor
|
||||
Room::Room(const std::string& room_path, std::shared_ptr<Scoreboard::Data> data)
|
||||
: data_(std::move(data)) {
|
||||
auto room = Resource::Cache::get()->getRoom(room_path);
|
||||
|
||||
// Crea los managers de enemigos e items
|
||||
enemy_manager_ = std::make_unique<EnemyManager>();
|
||||
item_manager_ = std::make_unique<ItemManager>(room->name, data_);
|
||||
|
||||
initializeRoom(*room);
|
||||
openTheJail(); // Abre la Jail si se da el caso
|
||||
|
||||
// Crea el mapa de colisiones (necesita collision_data_, conveyor_belt_direction_)
|
||||
collision_map_ = std::make_unique<CollisionMap>(collision_data_, conveyor_belt_direction_);
|
||||
|
||||
// Crea el renderizador del tilemap (necesita tile_map_, tile_set_width_, surface_, bg_color_, conveyor_belt_direction_)
|
||||
tilemap_renderer_ = std::make_unique<TilemapRenderer>(tile_map_, tile_set_width_, surface_, bg_color_, conveyor_belt_direction_);
|
||||
tilemap_renderer_->initialize(collision_map_.get()); // Inicializa (crea map_surface, pinta tiles, busca animados)
|
||||
|
||||
Screen::get()->setBorderColor(stringToColor(border_color_)); // Establece el color del borde
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Room::~Room() = default;
|
||||
|
||||
void Room::initializeRoom(const Data& room) {
|
||||
// Asignar valores a las variables miembro
|
||||
number_ = room.number;
|
||||
name_ = room.name;
|
||||
bg_color_ = room.bg_color;
|
||||
border_color_ = room.border_color;
|
||||
item_color1_ = room.item_color1.empty() ? "yellow" : room.item_color1;
|
||||
item_color2_ = room.item_color2.empty() ? "magenta" : room.item_color2;
|
||||
upper_room_ = room.upper_room;
|
||||
lower_room_ = room.lower_room;
|
||||
left_room_ = room.left_room;
|
||||
right_room_ = room.right_room;
|
||||
tile_set_file_ = room.tile_set_file;
|
||||
conveyor_belt_direction_ = room.conveyor_belt_direction;
|
||||
tile_map_ = room.tile_map; // Tilemap para renderizado (viene embebido en el YAML)
|
||||
collision_data_ = room.collision_map; // Collisionmap para colisiones (viene embebido en el YAML)
|
||||
surface_ = Resource::Cache::get()->getSurface(room.tile_set_file);
|
||||
tile_set_width_ = surface_->getWidth() / TILE_SIZE;
|
||||
is_paused_ = false;
|
||||
|
||||
// Crear los enemigos usando el manager
|
||||
for (const auto& enemy_data : room.enemies) {
|
||||
enemy_manager_->addEnemy(std::make_shared<Enemy>(enemy_data));
|
||||
}
|
||||
|
||||
// Crear los items usando el manager
|
||||
for (const auto& item : room.items) {
|
||||
const SDL_FPoint ITEM_POS = {item.x, item.y};
|
||||
|
||||
if (!ItemTracker::get()->hasBeenPicked(room.name, ITEM_POS)) {
|
||||
// Crear una copia local de los datos del item
|
||||
Item::Data item_copy = item;
|
||||
item_copy.color1 = stringToColor(item_color1_);
|
||||
item_copy.color2 = stringToColor(item_color2_);
|
||||
|
||||
// Crear el objeto Item usando la copia modificada
|
||||
item_manager_->addItem(std::make_shared<Item>(item_copy));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Abre la jail para poder entrar
|
||||
void Room::openTheJail() {
|
||||
if (data_->jail_is_open && name_ == "THE JAIL") {
|
||||
// Elimina el último enemigo (Bry debe ser el último enemigo definido en el fichero)
|
||||
if (!enemy_manager_->isEmpty()) {
|
||||
enemy_manager_->removeLastEnemy();
|
||||
}
|
||||
|
||||
// Abre las puertas (tanto en tilemap para renderizado como en collisionmap para colisiones)
|
||||
constexpr int TILE_A = 16 + (13 * MAP_WIDTH);
|
||||
constexpr int TILE_B = 16 + (14 * MAP_WIDTH);
|
||||
if (TILE_A < tile_map_.size()) {
|
||||
tile_map_[TILE_A] = -1; // Renderizado: vacío
|
||||
collision_data_[TILE_A] = -1; // Colisiones: vacío
|
||||
}
|
||||
if (TILE_B < tile_map_.size()) {
|
||||
tile_map_[TILE_B] = -1; // Renderizado: vacío
|
||||
collision_data_[TILE_B] = -1; // Colisiones: vacío
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja el mapa en pantalla
|
||||
void Room::renderMap() {
|
||||
tilemap_renderer_->render();
|
||||
}
|
||||
|
||||
// Dibuja los enemigos en pantalla
|
||||
void Room::renderEnemies() {
|
||||
enemy_manager_->render();
|
||||
}
|
||||
|
||||
// Dibuja los objetos en pantalla
|
||||
void Room::renderItems() {
|
||||
item_manager_->render();
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
// Redibuja el mapa (para actualizar modo debug)
|
||||
void Room::redrawMap() {
|
||||
tilemap_renderer_->redrawMap(collision_map_.get());
|
||||
}
|
||||
#endif
|
||||
|
||||
// Actualiza las variables y objetos de la habitación
|
||||
void Room::update(float delta_time) {
|
||||
if (is_paused_) {
|
||||
// Si está en modo pausa no se actualiza nada
|
||||
return;
|
||||
}
|
||||
|
||||
// Actualiza los tiles animados usando el renderer
|
||||
tilemap_renderer_->update(delta_time);
|
||||
|
||||
// Actualiza los enemigos usando el manager
|
||||
enemy_manager_->update(delta_time);
|
||||
|
||||
// Actualiza los items usando el manager
|
||||
item_manager_->update(delta_time);
|
||||
}
|
||||
|
||||
// Pone el mapa en modo pausa
|
||||
void Room::setPaused(bool value) {
|
||||
is_paused_ = value;
|
||||
tilemap_renderer_->setPaused(value);
|
||||
item_manager_->setPaused(value);
|
||||
}
|
||||
|
||||
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
||||
auto Room::getRoom(Border border) -> std::string {
|
||||
switch (border) {
|
||||
case Border::TOP:
|
||||
return upper_room_;
|
||||
case Border::BOTTOM:
|
||||
return lower_room_;
|
||||
case Border::RIGHT:
|
||||
return right_room_;
|
||||
case Border::LEFT:
|
||||
return left_room_;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Devuelve el tipo de tile que hay en ese pixel
|
||||
auto Room::getTile(SDL_FPoint point) -> Tile {
|
||||
// Delega a CollisionMap y convierte el resultado
|
||||
const auto COLLISION_TILE = collision_map_->getTile(point);
|
||||
return static_cast<Tile>(COLLISION_TILE);
|
||||
}
|
||||
|
||||
// Devuelve el tipo de tile en un índice del tilemap
|
||||
auto Room::getTile(int index) -> Tile {
|
||||
// Delega a CollisionMap y convierte el resultado
|
||||
const auto COLLISION_TILE = collision_map_->getTile(index);
|
||||
return static_cast<Tile>(COLLISION_TILE);
|
||||
}
|
||||
|
||||
// Indica si hay colision con un enemigo a partir de un rectangulo
|
||||
auto Room::enemyCollision(SDL_FRect& rect) -> bool {
|
||||
return enemy_manager_->checkCollision(rect);
|
||||
}
|
||||
|
||||
// Indica si hay colision con un objeto a partir de un rectangulo
|
||||
auto Room::itemCollision(SDL_FRect& rect) -> bool {
|
||||
return item_manager_->checkCollision(rect);
|
||||
}
|
||||
|
||||
// === Métodos de colisión (delegados a CollisionMap) ===
|
||||
|
||||
// Comprueba las colisiones con paredes derechas
|
||||
auto Room::checkRightSurfaces(const SDL_FRect& rect) -> int {
|
||||
return collision_map_->checkRightSurfaces(rect);
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con paredes izquierdas
|
||||
auto Room::checkLeftSurfaces(const SDL_FRect& rect) -> int {
|
||||
return collision_map_->checkLeftSurfaces(rect);
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con techos
|
||||
auto Room::checkTopSurfaces(const SDL_FRect& rect) -> int {
|
||||
return collision_map_->checkTopSurfaces(rect);
|
||||
}
|
||||
|
||||
// Comprueba las colisiones punto con techos
|
||||
auto Room::checkTopSurfaces(const SDL_FPoint& p) -> bool {
|
||||
return collision_map_->checkTopSurfaces(p);
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con suelos
|
||||
auto Room::checkBottomSurfaces(const SDL_FRect& rect) -> int {
|
||||
return collision_map_->checkBottomSurfaces(rect);
|
||||
}
|
||||
|
||||
// Comprueba las colisiones con conveyor belts
|
||||
auto Room::checkAutoSurfaces(const SDL_FRect& rect) -> int {
|
||||
return collision_map_->checkAutoSurfaces(rect);
|
||||
}
|
||||
|
||||
// Comprueba las colisiones punto con conveyor belts
|
||||
auto Room::checkConveyorBelts(const SDL_FPoint& p) -> bool {
|
||||
return collision_map_->checkConveyorBelts(p);
|
||||
}
|
||||
|
||||
// Carga una habitación desde un archivo YAML (delegado a RoomLoader)
|
||||
auto Room::loadYAML(const std::string& file_path, bool verbose) -> Data {
|
||||
return RoomLoader::loadYAML(file_path, verbose);
|
||||
}
|
||||
128
source/game/gameplay/room.hpp
Normal file
128
source/game/gameplay/room.hpp
Normal file
@@ -0,0 +1,128 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "game/entities/enemy.hpp" // Para EnemyData
|
||||
#include "game/entities/item.hpp" // Para ItemData
|
||||
#include "game/gameplay/scoreboard.hpp" // Para Scoreboard::Data
|
||||
#include "utils/defines.hpp" // Para Tile::SIZE, PlayArea
|
||||
#include "utils/utils.hpp" // Para LineHorizontal, LineVertical
|
||||
class SurfaceSprite; // lines 12-12
|
||||
class Surface; // lines 13-13
|
||||
class EnemyManager;
|
||||
class ItemManager;
|
||||
class CollisionMap;
|
||||
class TilemapRenderer;
|
||||
|
||||
class Room {
|
||||
public:
|
||||
// -- Enumeraciones y estructuras ---
|
||||
enum class Border : int {
|
||||
TOP = 0,
|
||||
RIGHT = 1,
|
||||
BOTTOM = 2,
|
||||
LEFT = 3,
|
||||
NONE = 4
|
||||
};
|
||||
|
||||
enum class Tile {
|
||||
EMPTY,
|
||||
WALL,
|
||||
PASSABLE,
|
||||
KILL,
|
||||
ANIMATED
|
||||
};
|
||||
|
||||
struct Data {
|
||||
std::string number; // Numero de la habitación
|
||||
std::string name; // Nombre de la habitación
|
||||
std::string bg_color; // Color de fondo de la habitación
|
||||
std::string border_color; // Color del borde de la pantalla
|
||||
std::string item_color1; // Color 1 para los items de la habitación
|
||||
std::string item_color2; // Color 2 para los items de la habitación
|
||||
std::string upper_room; // Identificador de la habitación que se encuentra arriba
|
||||
std::string lower_room; // Identificador de la habitación que se encuentra abajo
|
||||
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
|
||||
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
|
||||
std::string tile_set_file; // Imagen con los gráficos para la habitación
|
||||
int conveyor_belt_direction{0}; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||
std::vector<int> tile_map; // Índice de los tiles a dibujar en la habitación (embebido desde YAML)
|
||||
std::vector<int> collision_map; // Índice de colisiones de la habitación (embebido desde YAML)
|
||||
std::vector<Enemy::Data> enemies; // Listado con los enemigos de la habitación
|
||||
std::vector<Item::Data> items; // Listado con los items que hay en la habitación
|
||||
};
|
||||
|
||||
// Constructor y destructor
|
||||
Room(const std::string& room_path, std::shared_ptr<Scoreboard::Data> data);
|
||||
~Room(); // Definido en .cpp para poder usar unique_ptr con forward declarations
|
||||
|
||||
// --- Funciones ---
|
||||
[[nodiscard]] auto getName() const -> const std::string& { return name_; } // Devuelve el nombre de la habitación
|
||||
[[nodiscard]] auto getBGColor() const -> Uint8 { return stringToColor(bg_color_); } // Devuelve el color de la habitación
|
||||
[[nodiscard]] auto getBorderColor() const -> Uint8 { return stringToColor(border_color_); } // Devuelve el color del borde
|
||||
void renderMap(); // Dibuja el mapa en pantalla
|
||||
void renderEnemies(); // Dibuja los enemigos en pantalla
|
||||
void renderItems(); // Dibuja los objetos en pantalla
|
||||
#ifdef _DEBUG
|
||||
void redrawMap(); // Redibuja el mapa (para actualizar modo debug)
|
||||
#endif
|
||||
void update(float delta_time); // Actualiza las variables y objetos de la habitación
|
||||
auto getRoom(Border border) -> std::string; // Devuelve la cadena del fichero de la habitación contigua segun el borde
|
||||
auto getTile(SDL_FPoint point) -> Tile; // Devuelve el tipo de tile que hay en ese pixel
|
||||
auto getTile(int index) -> Tile; // Devuelve el tipo de tile en un índice del tilemap
|
||||
auto enemyCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un enemigo a partir de un rectangulo
|
||||
auto itemCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un objeto a partir de un rectangulo
|
||||
static auto getTileSize() -> int { return TILE_SIZE; } // Obten el tamaño del tile
|
||||
auto checkRightSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones
|
||||
auto checkLeftSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones
|
||||
auto checkTopSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones
|
||||
auto checkBottomSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones
|
||||
auto checkAutoSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones
|
||||
auto checkTopSurfaces(const SDL_FPoint& p) -> bool; // Comprueba las colisiones
|
||||
auto checkConveyorBelts(const SDL_FPoint& p) -> bool; // Comprueba las colisiones
|
||||
void setPaused(bool value); // Pone el mapa en modo pausa
|
||||
[[nodiscard]] auto getConveyorBeltDirection() const -> int { return conveyor_belt_direction_; } // Obten la direccion de las superficies automaticas
|
||||
|
||||
// Método de carga de archivos YAML (delegado a RoomLoader)
|
||||
static auto loadYAML(const std::string& file_path, bool verbose = false) -> Data; // Carga habitación desde archivo YAML unificado
|
||||
|
||||
private:
|
||||
// Constantes (usar defines de PlayArea)
|
||||
static constexpr int TILE_SIZE = ::Tile::SIZE; // Ancho del tile en pixels
|
||||
static constexpr int MAP_WIDTH = PlayArea::TILE_COLS; // Ancho del mapa en tiles
|
||||
static constexpr int MAP_HEIGHT = PlayArea::TILE_ROWS; // Alto del mapa en tiles
|
||||
|
||||
// Objetos y punteros
|
||||
std::unique_ptr<EnemyManager> enemy_manager_; // Gestor de enemigos de la habitación
|
||||
std::unique_ptr<ItemManager> item_manager_; // Gestor de items de la habitación
|
||||
std::unique_ptr<CollisionMap> collision_map_; // Mapa de colisiones de la habitación
|
||||
std::unique_ptr<TilemapRenderer> tilemap_renderer_; // Renderizador del mapa de tiles
|
||||
std::shared_ptr<Surface> surface_; // Textura con los graficos de la habitación
|
||||
std::shared_ptr<Scoreboard::Data> data_; // Puntero a los datos del marcador
|
||||
|
||||
// --- Variables ---
|
||||
std::string number_; // Numero de la habitación
|
||||
std::string name_; // Nombre de la habitación
|
||||
std::string bg_color_; // Color de fondo de la habitación
|
||||
std::string border_color_; // Color del borde de la pantalla
|
||||
std::string item_color1_; // Color 1 para los items de la habitación
|
||||
std::string item_color2_; // Color 2 para los items de la habitación
|
||||
std::string upper_room_; // Identificador de la habitación que se encuentra arriba
|
||||
std::string lower_room_; // Identificador de la habitación que se encuentra abajp
|
||||
std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda
|
||||
std::string right_room_; // Identificador de la habitación que se encuentra a la derecha
|
||||
std::string tile_set_file_; // Imagen con los graficos para la habitación
|
||||
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación (embebido desde YAML)
|
||||
std::vector<int> collision_data_; // Indice de colisiones de la habitación (embebido desde YAML)
|
||||
int conveyor_belt_direction_{0}; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||
bool is_paused_{false}; // Indica si el mapa esta en modo pausa
|
||||
int tile_set_width_{0}; // Ancho del tileset en tiles
|
||||
|
||||
// --- Funciones ---
|
||||
void initializeRoom(const Data& room); // Inicializa los valores
|
||||
void openTheJail(); // Abre la jail para poder entrar
|
||||
};
|
||||
388
source/game/gameplay/room_loader.cpp
Normal file
388
source/game/gameplay/room_loader.cpp
Normal file
@@ -0,0 +1,388 @@
|
||||
#include "room_loader.hpp"
|
||||
|
||||
#include <exception> // Para exception
|
||||
#include <iostream> // Para cout, cerr
|
||||
|
||||
#include "core/resources/resource_helper.hpp" // Para Resource::Helper
|
||||
#include "external/fkyaml_node.hpp" // Para fkyaml::node
|
||||
#include "utils/defines.hpp" // Para Tile::SIZE
|
||||
#include "utils/utils.hpp" // Para stringToColor
|
||||
|
||||
// Convierte room connection de YAML a formato interno
|
||||
auto RoomLoader::convertRoomConnection(const std::string& value) -> std::string {
|
||||
if (value == "null" || value.empty()) {
|
||||
return "0";
|
||||
}
|
||||
// Si ya tiene .yaml, devolverlo tal cual; si no, añadirlo
|
||||
if (value.size() > 5 && value.substr(value.size() - 5) == ".yaml") {
|
||||
return value;
|
||||
}
|
||||
return value + ".yaml";
|
||||
}
|
||||
|
||||
// Convierte string de autoSurface a int
|
||||
auto RoomLoader::convertAutoSurface(const fkyaml::node& node) -> int {
|
||||
if (node.is_integer()) {
|
||||
return node.get_value<int>();
|
||||
}
|
||||
if (node.is_string()) {
|
||||
const auto VALUE = node.get_value<std::string>();
|
||||
if (VALUE == "left") {
|
||||
return -1;
|
||||
}
|
||||
if (VALUE == "right") {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0; // "none" o default
|
||||
}
|
||||
|
||||
// Convierte un tilemap 2D a vector 1D flat
|
||||
auto RoomLoader::flattenTilemap(const std::vector<std::vector<int>>& tilemap_2d) -> std::vector<int> {
|
||||
std::vector<int> tilemap_flat;
|
||||
tilemap_flat.reserve(PlayArea::TILE_COUNT); // TILE_ROWS × TILE_COLS
|
||||
|
||||
for (const auto& row : tilemap_2d) {
|
||||
for (int tile : row) {
|
||||
tilemap_flat.push_back(tile);
|
||||
}
|
||||
}
|
||||
|
||||
return tilemap_flat;
|
||||
}
|
||||
|
||||
// Parsea la configuración general de la habitación
|
||||
void RoomLoader::parseRoomConfig(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name) {
|
||||
if (!yaml.contains("room")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& room_node = yaml["room"];
|
||||
|
||||
// Extract room number from filename (e.g., "01.yaml" → "01")
|
||||
room.number = file_name.substr(0, file_name.find_last_of('.'));
|
||||
|
||||
// Basic properties
|
||||
if (room_node.contains("name")) {
|
||||
room.name = room_node["name"].get_value<std::string>();
|
||||
}
|
||||
if (room_node.contains("bgColor")) {
|
||||
room.bg_color = room_node["bgColor"].get_value<std::string>();
|
||||
}
|
||||
if (room_node.contains("border")) {
|
||||
room.border_color = room_node["border"].get_value<std::string>();
|
||||
}
|
||||
if (room_node.contains("tileSetFile")) {
|
||||
room.tile_set_file = room_node["tileSetFile"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Room connections
|
||||
if (room_node.contains("connections")) {
|
||||
parseRoomConnections(room_node["connections"], room);
|
||||
}
|
||||
|
||||
// Item colors
|
||||
room.item_color1 = room_node.contains("itemColor1")
|
||||
? room_node["itemColor1"].get_value_or<std::string>("yellow")
|
||||
: "yellow";
|
||||
|
||||
room.item_color2 = room_node.contains("itemColor2")
|
||||
? room_node["itemColor2"].get_value_or<std::string>("magenta")
|
||||
: "magenta";
|
||||
|
||||
// Dirección de la cinta transportadora (left/none/right)
|
||||
room.conveyor_belt_direction = room_node.contains("conveyorBelt")
|
||||
? convertAutoSurface(room_node["conveyorBelt"])
|
||||
: 0;
|
||||
}
|
||||
|
||||
// Parsea las conexiones de la habitación (arriba/abajo/izq/der)
|
||||
void RoomLoader::parseRoomConnections(const fkyaml::node& conn_node, Room::Data& room) {
|
||||
room.upper_room = conn_node.contains("up")
|
||||
? convertRoomConnection(conn_node["up"].get_value_or<std::string>("null"))
|
||||
: "0";
|
||||
|
||||
room.lower_room = conn_node.contains("down")
|
||||
? convertRoomConnection(conn_node["down"].get_value_or<std::string>("null"))
|
||||
: "0";
|
||||
|
||||
room.left_room = conn_node.contains("left")
|
||||
? convertRoomConnection(conn_node["left"].get_value_or<std::string>("null"))
|
||||
: "0";
|
||||
|
||||
room.right_room = conn_node.contains("right")
|
||||
? convertRoomConnection(conn_node["right"].get_value_or<std::string>("null"))
|
||||
: "0";
|
||||
}
|
||||
|
||||
// Parsea el tilemap de la habitación
|
||||
void RoomLoader::parseTilemap(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name, bool verbose) {
|
||||
if (!yaml.contains("tilemap")) {
|
||||
std::cerr << "Warning: No tilemap found in " << file_name << '\n';
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& tilemap_node = yaml["tilemap"];
|
||||
|
||||
// Read 2D array
|
||||
std::vector<std::vector<int>> tilemap_2d;
|
||||
tilemap_2d.reserve(PlayArea::TILE_ROWS);
|
||||
|
||||
for (const auto& row_node : tilemap_node) {
|
||||
std::vector<int> row;
|
||||
row.reserve(PlayArea::TILE_COLS);
|
||||
|
||||
for (const auto& tile_node : row_node) {
|
||||
row.push_back(tile_node.get_value<int>());
|
||||
}
|
||||
|
||||
tilemap_2d.push_back(row);
|
||||
}
|
||||
|
||||
// Convert to 1D flat array
|
||||
room.tile_map = flattenTilemap(tilemap_2d);
|
||||
|
||||
if (verbose) {
|
||||
std::cout << "Loaded tilemap: " << room.tile_map.size() << " tiles\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Parsea el collisionmap de la habitación
|
||||
void RoomLoader::parseCollisionmap(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name, bool verbose) {
|
||||
if (!yaml.contains("collisionmap")) {
|
||||
// Si no hay collisionmap, es opcional - no es error
|
||||
if (verbose) {
|
||||
std::cout << "No collisionmap found in " << file_name << " (optional)\n";
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& collisionmap_node = yaml["collisionmap"];
|
||||
|
||||
// Read 2D array
|
||||
std::vector<std::vector<int>> collisionmap_2d;
|
||||
collisionmap_2d.reserve(PlayArea::TILE_ROWS);
|
||||
|
||||
for (const auto& row_node : collisionmap_node) {
|
||||
std::vector<int> row;
|
||||
row.reserve(PlayArea::TILE_COLS);
|
||||
|
||||
for (const auto& tile_node : row_node) {
|
||||
row.push_back(tile_node.get_value<int>());
|
||||
}
|
||||
|
||||
collisionmap_2d.push_back(row);
|
||||
}
|
||||
|
||||
// Convert to 1D flat array (reutilizamos flattenTilemap)
|
||||
room.collision_map = flattenTilemap(collisionmap_2d);
|
||||
|
||||
if (verbose) {
|
||||
std::cout << "Loaded collisionmap: " << room.collision_map.size() << " tiles\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Parsea los límites de movimiento de un enemigo
|
||||
void RoomLoader::parseEnemyBoundaries(const fkyaml::node& bounds_node, Enemy::Data& enemy) {
|
||||
// Nuevo formato: position1 y position2
|
||||
if (bounds_node.contains("position1")) {
|
||||
const auto& pos1 = bounds_node["position1"];
|
||||
if (pos1.contains("x")) {
|
||||
enemy.x1 = pos1["x"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
if (pos1.contains("y")) {
|
||||
enemy.y1 = pos1["y"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
}
|
||||
if (bounds_node.contains("position2")) {
|
||||
const auto& pos2 = bounds_node["position2"];
|
||||
if (pos2.contains("x")) {
|
||||
enemy.x2 = pos2["x"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
if (pos2.contains("y")) {
|
||||
enemy.y2 = pos2["y"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
// Formato antiguo: x1/y1/x2/y2 (compatibilidad)
|
||||
if (bounds_node.contains("x1")) {
|
||||
enemy.x1 = bounds_node["x1"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
if (bounds_node.contains("y1")) {
|
||||
enemy.y1 = bounds_node["y1"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
if (bounds_node.contains("x2")) {
|
||||
enemy.x2 = bounds_node["x2"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
if (bounds_node.contains("y2")) {
|
||||
enemy.y2 = bounds_node["y2"].get_value<int>() * Tile::SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
// Parsea los datos de un enemigo individual
|
||||
auto RoomLoader::parseEnemyData(const fkyaml::node& enemy_node) -> Enemy::Data {
|
||||
Enemy::Data enemy;
|
||||
|
||||
// Animation path
|
||||
if (enemy_node.contains("animation")) {
|
||||
enemy.animation_path = enemy_node["animation"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Position (in tiles, convert to pixels)
|
||||
if (enemy_node.contains("position")) {
|
||||
const auto& pos = enemy_node["position"];
|
||||
if (pos.contains("x")) {
|
||||
enemy.x = pos["x"].get_value<float>() * Tile::SIZE;
|
||||
}
|
||||
if (pos.contains("y")) {
|
||||
enemy.y = pos["y"].get_value<float>() * Tile::SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
// Velocity (already in pixels/second)
|
||||
if (enemy_node.contains("velocity")) {
|
||||
const auto& vel = enemy_node["velocity"];
|
||||
if (vel.contains("x")) {
|
||||
enemy.vx = vel["x"].get_value<float>();
|
||||
}
|
||||
if (vel.contains("y")) {
|
||||
enemy.vy = vel["y"].get_value<float>();
|
||||
}
|
||||
}
|
||||
|
||||
// Boundaries (in tiles, convert to pixels)
|
||||
if (enemy_node.contains("boundaries")) {
|
||||
parseEnemyBoundaries(enemy_node["boundaries"], enemy);
|
||||
}
|
||||
|
||||
// Color
|
||||
enemy.color = enemy_node.contains("color")
|
||||
? enemy_node["color"].get_value_or<std::string>("white")
|
||||
: "white";
|
||||
|
||||
// Optional fields
|
||||
enemy.flip = enemy_node.contains("flip")
|
||||
? enemy_node["flip"].get_value_or<bool>(false)
|
||||
: false;
|
||||
|
||||
enemy.mirror = enemy_node.contains("mirror")
|
||||
? enemy_node["mirror"].get_value_or<bool>(false)
|
||||
: false;
|
||||
|
||||
enemy.frame = enemy_node.contains("frame")
|
||||
? enemy_node["frame"].get_value_or<int>(-1)
|
||||
: -1;
|
||||
|
||||
return enemy;
|
||||
}
|
||||
|
||||
// Parsea la lista de enemigos de la habitación
|
||||
void RoomLoader::parseEnemies(const fkyaml::node& yaml, Room::Data& room, bool verbose) {
|
||||
if (!yaml.contains("enemies") || yaml["enemies"].is_null()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& enemies_node = yaml["enemies"];
|
||||
|
||||
for (const auto& enemy_node : enemies_node) {
|
||||
room.enemies.push_back(parseEnemyData(enemy_node));
|
||||
}
|
||||
|
||||
if (verbose) {
|
||||
std::cout << "Loaded " << room.enemies.size() << " enemies\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Parsea los datos de un item individual
|
||||
auto RoomLoader::parseItemData(const fkyaml::node& item_node, const Room::Data& room) -> Item::Data {
|
||||
Item::Data item;
|
||||
|
||||
// Tileset file
|
||||
if (item_node.contains("tileSetFile")) {
|
||||
item.tile_set_file = item_node["tileSetFile"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Tile index
|
||||
if (item_node.contains("tile")) {
|
||||
item.tile = item_node["tile"].get_value<int>();
|
||||
}
|
||||
|
||||
// Position (in tiles, convert to pixels)
|
||||
if (item_node.contains("position")) {
|
||||
const auto& pos = item_node["position"];
|
||||
if (pos.contains("x")) {
|
||||
item.x = pos["x"].get_value<float>() * Tile::SIZE;
|
||||
}
|
||||
if (pos.contains("y")) {
|
||||
item.y = pos["y"].get_value<float>() * Tile::SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
// Counter
|
||||
item.counter = item_node.contains("counter")
|
||||
? item_node["counter"].get_value_or<int>(0)
|
||||
: 0;
|
||||
|
||||
// Colors (assigned from room defaults)
|
||||
item.color1 = stringToColor(room.item_color1);
|
||||
item.color2 = stringToColor(room.item_color2);
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
// Parsea la lista de items de la habitación
|
||||
void RoomLoader::parseItems(const fkyaml::node& yaml, Room::Data& room, bool verbose) {
|
||||
if (!yaml.contains("items") || yaml["items"].is_null()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& items_node = yaml["items"];
|
||||
|
||||
for (const auto& item_node : items_node) {
|
||||
room.items.push_back(parseItemData(item_node, room));
|
||||
}
|
||||
|
||||
if (verbose) {
|
||||
std::cout << "Loaded " << room.items.size() << " items\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Carga un archivo de room en formato YAML
|
||||
auto RoomLoader::loadYAML(const std::string& file_path, bool verbose) -> Room::Data {
|
||||
Room::Data room;
|
||||
|
||||
// Extract filename for logging
|
||||
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
|
||||
try {
|
||||
// Load YAML file using ResourceHelper (supports both filesystem and pack)
|
||||
auto file_data = Resource::Helper::loadFile(file_path);
|
||||
|
||||
if (file_data.empty()) {
|
||||
std::cerr << "Error: Unable to load file " << FILE_NAME << '\n';
|
||||
return room;
|
||||
}
|
||||
|
||||
// Parse YAML from string
|
||||
std::string yaml_content(file_data.begin(), file_data.end());
|
||||
auto yaml = fkyaml::node::deserialize(yaml_content);
|
||||
|
||||
// Delegación a funciones especializadas
|
||||
parseRoomConfig(yaml, room, FILE_NAME);
|
||||
parseTilemap(yaml, room, FILE_NAME, verbose);
|
||||
parseCollisionmap(yaml, room, FILE_NAME, verbose);
|
||||
parseEnemies(yaml, room, verbose);
|
||||
parseItems(yaml, room, verbose);
|
||||
|
||||
if (verbose) {
|
||||
std::cout << "Room loaded successfully: " << FILE_NAME << '\n';
|
||||
}
|
||||
|
||||
} catch (const fkyaml::exception& e) {
|
||||
std::cerr << "YAML parsing error in " << FILE_NAME << ": " << e.what() << '\n';
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error loading room " << FILE_NAME << ": " << e.what() << '\n';
|
||||
}
|
||||
|
||||
return room;
|
||||
}
|
||||
142
source/game/gameplay/room_loader.hpp
Normal file
142
source/game/gameplay/room_loader.hpp
Normal file
@@ -0,0 +1,142 @@
|
||||
#pragma once
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "external/fkyaml_node.hpp" // Para fkyaml::node
|
||||
#include "game/entities/enemy.hpp" // Para Enemy::Data
|
||||
#include "game/entities/item.hpp" // Para Item::Data
|
||||
#include "game/gameplay/room.hpp" // Para Room::Data
|
||||
|
||||
/**
|
||||
* @brief Cargador de archivos de habitaciones en formato YAML
|
||||
*
|
||||
* Responsabilidades:
|
||||
* - Cargar archivos de room en formato YAML unificado (.yaml)
|
||||
* - Parsear datos de room, tilemap, enemies e items
|
||||
* - Convertir tipos de datos (tiles, posiciones, colores)
|
||||
* - Validar y propagar errores de carga
|
||||
*
|
||||
* Esta clase contiene solo métodos estáticos y no debe instanciarse.
|
||||
*/
|
||||
class RoomLoader {
|
||||
public:
|
||||
// Constructor eliminado para prevenir instanciación
|
||||
RoomLoader() = delete;
|
||||
~RoomLoader() = delete;
|
||||
RoomLoader(const RoomLoader&) = delete;
|
||||
auto operator=(const RoomLoader&) -> RoomLoader& = delete;
|
||||
RoomLoader(RoomLoader&&) = delete;
|
||||
auto operator=(RoomLoader&&) -> RoomLoader& = delete;
|
||||
|
||||
/**
|
||||
* @brief Carga un archivo de room en formato YAML
|
||||
* @param file_path Ruta al archivo YAML de habitación
|
||||
* @param verbose Si true, muestra información de debug
|
||||
* @return Room::Data con todos los datos de la habitación incluyendo:
|
||||
* - Configuración de la habitación (nombre, colores, etc.)
|
||||
* - Tilemap completo (convertido de 2D a 1D)
|
||||
* - Lista de enemigos con todas sus propiedades
|
||||
* - Lista de items con todas sus propiedades
|
||||
*
|
||||
* El formato YAML esperado incluye:
|
||||
* - room: configuración general
|
||||
* - tilemap: array 2D de 24x40 tiles (convertido a vector 1D de 960 elementos)
|
||||
* - enemies: lista de enemigos (opcional)
|
||||
* - items: lista de items (opcional)
|
||||
*/
|
||||
static auto loadYAML(const std::string& file_path, bool verbose = false) -> Room::Data;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Convierte room connection de YAML a formato interno
|
||||
* @param value Valor del YAML (vacío, "02" o "02.yaml")
|
||||
* @return "0" para sin conexión, o nombre del archivo con extensión
|
||||
*/
|
||||
static auto convertRoomConnection(const std::string& value) -> std::string;
|
||||
|
||||
/**
|
||||
* @brief Convierte autoSurface de YAML a int
|
||||
* @param node Nodo YAML (puede ser int o string "left"/"none"/"right")
|
||||
* @return -1 para left, 0 para none, 1 para right
|
||||
*/
|
||||
static auto convertAutoSurface(const fkyaml::node& node) -> int;
|
||||
|
||||
/**
|
||||
* @brief Convierte un tilemap 2D a vector 1D flat
|
||||
* @param tilemap_2d Array 2D de tiles (24 rows × 40 cols)
|
||||
* @return Vector 1D flat con 960 elementos
|
||||
*/
|
||||
static auto flattenTilemap(const std::vector<std::vector<int>>& tilemap_2d) -> std::vector<int>;
|
||||
|
||||
/**
|
||||
* @brief Parsea la configuración general de la habitación
|
||||
* @param yaml Nodo raíz del YAML
|
||||
* @param room Estructura de datos de la habitación a rellenar
|
||||
* @param file_name Nombre del archivo para logging
|
||||
*/
|
||||
static void parseRoomConfig(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name);
|
||||
|
||||
/**
|
||||
* @brief Parsea las conexiones de la habitación (arriba/abajo/izq/der)
|
||||
* @param conn_node Nodo YAML con las conexiones
|
||||
* @param room Estructura de datos de la habitación a rellenar
|
||||
*/
|
||||
static void parseRoomConnections(const fkyaml::node& conn_node, Room::Data& room);
|
||||
|
||||
/**
|
||||
* @brief Parsea el tilemap de la habitación
|
||||
* @param yaml Nodo raíz del YAML
|
||||
* @param room Estructura de datos de la habitación a rellenar
|
||||
* @param file_name Nombre del archivo para logging
|
||||
* @param verbose Si true, muestra información de debug
|
||||
*/
|
||||
static void parseTilemap(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name, bool verbose);
|
||||
|
||||
/**
|
||||
* @brief Parsea el collisionmap de la habitación
|
||||
* @param yaml Nodo raíz del YAML
|
||||
* @param room Estructura de datos de la habitación a rellenar
|
||||
* @param file_name Nombre del archivo para logging
|
||||
* @param verbose Si true, muestra información de debug
|
||||
*/
|
||||
static void parseCollisionmap(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name, bool verbose);
|
||||
|
||||
/**
|
||||
* @brief Parsea la lista de enemigos de la habitación
|
||||
* @param yaml Nodo raíz del YAML
|
||||
* @param room Estructura de datos de la habitación a rellenar
|
||||
* @param verbose Si true, muestra información de debug
|
||||
*/
|
||||
static void parseEnemies(const fkyaml::node& yaml, Room::Data& room, bool verbose);
|
||||
|
||||
/**
|
||||
* @brief Parsea los datos de un enemigo individual
|
||||
* @param enemy_node Nodo YAML del enemigo
|
||||
* @return Estructura Enemy::Data con los datos parseados
|
||||
*/
|
||||
static auto parseEnemyData(const fkyaml::node& enemy_node) -> Enemy::Data;
|
||||
|
||||
/**
|
||||
* @brief Parsea los límites de movimiento de un enemigo
|
||||
* @param bounds_node Nodo YAML con los límites
|
||||
* @param enemy Estructura del enemigo a rellenar
|
||||
*/
|
||||
static void parseEnemyBoundaries(const fkyaml::node& bounds_node, Enemy::Data& enemy);
|
||||
|
||||
/**
|
||||
* @brief Parsea la lista de items de la habitación
|
||||
* @param yaml Nodo raíz del YAML
|
||||
* @param room Estructura de datos de la habitación a rellenar
|
||||
* @param verbose Si true, muestra información de debug
|
||||
*/
|
||||
static void parseItems(const fkyaml::node& yaml, Room::Data& room, bool verbose);
|
||||
|
||||
/**
|
||||
* @brief Parsea los datos de un item individual
|
||||
* @param item_node Nodo YAML del item
|
||||
* @param room Datos de la habitación (para colores por defecto)
|
||||
* @return Estructura Item::Data con los datos parseados
|
||||
*/
|
||||
static auto parseItemData(const fkyaml::node& item_node, const Room::Data& room) -> Item::Data;
|
||||
};
|
||||
20
source/game/gameplay/room_tracker.cpp
Normal file
20
source/game/gameplay/room_tracker.cpp
Normal file
@@ -0,0 +1,20 @@
|
||||
#include "game/gameplay/room_tracker.hpp"
|
||||
|
||||
#include <algorithm> // Para std::ranges::any_of
|
||||
|
||||
// Comprueba si la habitación ya ha sido visitada
|
||||
auto RoomTracker::hasBeenVisited(const std::string& name) -> bool {
|
||||
return std::ranges::any_of(rooms_, [&name](const auto& l) { return l == name; });
|
||||
}
|
||||
|
||||
// Añade la habitación a la lista
|
||||
auto RoomTracker::addRoom(const std::string& name) -> bool {
|
||||
// Comprueba si la habitación ya ha sido visitada
|
||||
if (!hasBeenVisited(name)) {
|
||||
// En caso contrario añádela a la lista
|
||||
rooms_.push_back(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
17
source/game/gameplay/room_tracker.hpp
Normal file
17
source/game/gameplay/room_tracker.hpp
Normal file
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
class RoomTracker {
|
||||
public:
|
||||
RoomTracker() = default; // Constructor
|
||||
~RoomTracker() = default; // Destructor
|
||||
|
||||
auto addRoom(const std::string& name) -> bool; // Añade la habitación a la lista
|
||||
|
||||
private:
|
||||
auto hasBeenVisited(const std::string& name) -> bool; // Comprueba si ya ha sido visitada
|
||||
|
||||
std::vector<std::string> rooms_; // Lista con habitaciones visitadas
|
||||
};
|
||||
170
source/game/gameplay/scoreboard.cpp
Normal file
170
source/game/gameplay/scoreboard.cpp
Normal file
@@ -0,0 +1,170 @@
|
||||
#include "game/gameplay/scoreboard.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||
#include "core/rendering/text.hpp" // Para Text
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "game/options.hpp" // Para Options, options, Cheat, OptionsGame
|
||||
#include "utils/defines.hpp" // Para BLOCK
|
||||
#include "utils/utils.hpp" // Para stringToColor
|
||||
|
||||
// Constructor
|
||||
Scoreboard::Scoreboard(std::shared_ptr<Data> data)
|
||||
: item_surface_(Resource::Cache::get()->getSurface("items.gif")),
|
||||
data_(std::move(std::move(data))) {
|
||||
constexpr float SURFACE_WIDTH = ScoreboardArea::WIDTH;
|
||||
constexpr float SURFACE_HEIGHT = ScoreboardArea::HEIGHT;
|
||||
|
||||
// Reserva memoria para los objetos
|
||||
const auto& player_animation_data = Resource::Cache::get()->getAnimationData(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.yaml" : "player.yaml");
|
||||
player_sprite_ = std::make_shared<SurfaceAnimatedSprite>(player_animation_data);
|
||||
player_sprite_->setCurrentAnimation("walk_menu");
|
||||
|
||||
surface_ = std::make_shared<Surface>(SURFACE_WIDTH, SURFACE_HEIGHT);
|
||||
surface_dest_ = {.x = ScoreboardArea::X, .y = ScoreboardArea::Y, .w = SURFACE_WIDTH, .h = SURFACE_HEIGHT};
|
||||
|
||||
// Inicializa el color de items
|
||||
items_color_ = stringToColor("white");
|
||||
|
||||
// Inicializa el vector de colores
|
||||
const std::vector<std::string> COLORS = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
|
||||
for (const auto& color : COLORS) {
|
||||
color_.push_back(stringToColor(color));
|
||||
}
|
||||
}
|
||||
|
||||
// Pinta el objeto en pantalla
|
||||
void Scoreboard::render() {
|
||||
surface_->render(nullptr, &surface_dest_);
|
||||
}
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void Scoreboard::update(float delta_time) {
|
||||
// Acumular tiempo para animaciones
|
||||
time_accumulator_ += delta_time;
|
||||
|
||||
// Actualizar sprite con delta time
|
||||
player_sprite_->update(delta_time);
|
||||
|
||||
// Actualiza el color de la cantidad de items recogidos
|
||||
updateItemsColor(delta_time);
|
||||
|
||||
// Dibuja la textura
|
||||
fillTexture();
|
||||
|
||||
if (!is_paused_) {
|
||||
// Si está en pausa no se actualiza el reloj
|
||||
clock_ = getTime();
|
||||
}
|
||||
}
|
||||
|
||||
// Obtiene el tiempo transcurrido de partida
|
||||
auto Scoreboard::getTime() -> Scoreboard::ClockData {
|
||||
const Uint32 TIME_ELAPSED = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_;
|
||||
|
||||
ClockData time;
|
||||
time.hours = TIME_ELAPSED / 3600000;
|
||||
time.minutes = TIME_ELAPSED / 60000;
|
||||
time.seconds = TIME_ELAPSED / 1000;
|
||||
time.separator = (TIME_ELAPSED % 1000 <= 500) ? ":" : " ";
|
||||
|
||||
return time;
|
||||
}
|
||||
|
||||
// Pone el marcador en modo pausa
|
||||
void Scoreboard::setPaused(bool value) {
|
||||
if (is_paused_ == value) {
|
||||
// Evita ejecutar lógica si el estado no cambia
|
||||
return;
|
||||
}
|
||||
|
||||
is_paused_ = value;
|
||||
|
||||
if (is_paused_) {
|
||||
// Guarda el tiempo actual al pausar
|
||||
paused_time_ = SDL_GetTicks();
|
||||
} else {
|
||||
// Calcula el tiempo pausado acumulado al reanudar
|
||||
paused_time_elapsed_ += SDL_GetTicks() - paused_time_;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el color de la cantidad de items recogidos
|
||||
void Scoreboard::updateItemsColor(float delta_time) {
|
||||
if (!data_->jail_is_open) {
|
||||
return;
|
||||
}
|
||||
|
||||
items_color_timer_ += delta_time;
|
||||
|
||||
// Resetear timer cada 2 ciclos (0.666s total)
|
||||
if (items_color_timer_ >= ITEMS_COLOR_BLINK_DURATION * 2.0F) {
|
||||
items_color_timer_ = 0.0F;
|
||||
}
|
||||
|
||||
// Alternar color cada ITEMS_COLOR_BLINK_DURATION
|
||||
if (items_color_timer_ < ITEMS_COLOR_BLINK_DURATION) {
|
||||
items_color_ = stringToColor("white");
|
||||
} else {
|
||||
items_color_ = stringToColor("magenta");
|
||||
}
|
||||
}
|
||||
|
||||
// Devuelve la cantidad de minutos de juego transcurridos
|
||||
auto Scoreboard::getMinutes() -> int {
|
||||
return getTime().minutes;
|
||||
}
|
||||
|
||||
// Dibuja los elementos del marcador en la textura
|
||||
void Scoreboard::fillTexture() {
|
||||
// Empieza a dibujar en la textura
|
||||
auto previuos_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(surface_);
|
||||
|
||||
// Limpia la textura
|
||||
surface_->clear(stringToColor("black"));
|
||||
|
||||
// Anclas
|
||||
constexpr int LINE1 = Tile::SIZE;
|
||||
constexpr int LINE2 = 3 * Tile::SIZE;
|
||||
|
||||
// Dibuja las vidas
|
||||
// Calcular desplazamiento basado en tiempo
|
||||
const int DESP = static_cast<int>(time_accumulator_ / SPRITE_WALK_CYCLE_DURATION) % 8;
|
||||
const int FRAME = DESP % SPRITE_WALK_FRAMES;
|
||||
player_sprite_->setCurrentAnimationFrame(FRAME);
|
||||
player_sprite_->setPosY(LINE2);
|
||||
for (int i = 0; i < data_->lives; ++i) {
|
||||
player_sprite_->setPosX(8 + (16 * i) + DESP);
|
||||
const int INDEX = i % color_.size();
|
||||
player_sprite_->render(4, color_.at(INDEX));
|
||||
}
|
||||
|
||||
// Muestra si suena la música
|
||||
if (data_->music) {
|
||||
const Uint8 C = data_->color;
|
||||
SDL_FRect clip = {0, 8, 8, 8};
|
||||
item_surface_->renderWithColorReplace(20 * Tile::SIZE, LINE2, 1, C, &clip);
|
||||
}
|
||||
|
||||
// Escribe los textos
|
||||
auto text = Resource::Cache::get()->getText("smb2");
|
||||
const std::string TIME_TEXT = std::to_string((clock_.minutes % 100) / 10) + std::to_string(clock_.minutes % 10) + clock_.separator + std::to_string((clock_.seconds % 60) / 10) + std::to_string(clock_.seconds % 10);
|
||||
const std::string ITEMS_TEXT = std::to_string(data_->items / 100) + std::to_string((data_->items % 100) / 10) + std::to_string(data_->items % 10);
|
||||
text->writeColored(Tile::SIZE, LINE1, "Items collected ", data_->color);
|
||||
text->writeColored(17 * Tile::SIZE, LINE1, ITEMS_TEXT, items_color_);
|
||||
text->writeColored(20 * Tile::SIZE, LINE1, " Time ", data_->color);
|
||||
text->writeColored(26 * Tile::SIZE, LINE1, TIME_TEXT, stringToColor("white"));
|
||||
|
||||
const std::string ROOMS_TEXT = std::to_string(data_->rooms / 100) + std::to_string((data_->rooms % 100) / 10) + std::to_string(data_->rooms % 10);
|
||||
text->writeColored(22 * Tile::SIZE, LINE2, "Rooms", stringToColor("white"));
|
||||
text->writeColored(28 * Tile::SIZE, LINE2, ROOMS_TEXT, stringToColor("white"));
|
||||
|
||||
// Deja el renderizador como estaba
|
||||
Screen::get()->setRendererSurface(previuos_renderer);
|
||||
}
|
||||
68
source/game/gameplay/scoreboard.hpp
Normal file
68
source/game/gameplay/scoreboard.hpp
Normal file
@@ -0,0 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string, basic_string
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
class SurfaceAnimatedSprite; // lines 10-10
|
||||
class Surface; // lines 11-11
|
||||
|
||||
class Scoreboard {
|
||||
public:
|
||||
// Tipos anidados
|
||||
struct Data {
|
||||
int items{0}; // Lleva la cuenta de los objetos recogidos
|
||||
int lives{0}; // Lleva la cuenta de las vidas restantes del jugador
|
||||
int rooms{0}; // Lleva la cuenta de las habitaciones visitadas
|
||||
bool music{true}; // Indica si ha de sonar la música durante el juego
|
||||
Uint8 color{0}; // Color para escribir el texto del marcador
|
||||
Uint32 ini_clock{0}; // Tiempo inicial para calcular el tiempo transcurrido
|
||||
bool jail_is_open{false}; // Indica si se puede entrar a la Jail
|
||||
};
|
||||
|
||||
// Métodos públicos
|
||||
explicit Scoreboard(std::shared_ptr<Data> data); // Constructor
|
||||
~Scoreboard() = default; // Destructor
|
||||
void render(); // Pinta el objeto en pantalla
|
||||
void update(float delta_time); // Actualiza las variables del objeto
|
||||
void setPaused(bool value); // Pone el marcador en modo pausa
|
||||
auto getMinutes() -> int; // Devuelve la cantidad de minutos de juego transcurridos
|
||||
|
||||
private:
|
||||
// Tipos anidados
|
||||
struct ClockData {
|
||||
int hours{0}; // Horas transcurridas
|
||||
int minutes{0}; // Minutos transcurridos
|
||||
int seconds{0}; // Segundos transcurridos
|
||||
std::string separator{":"}; // Separador para mostrar el tiempo
|
||||
};
|
||||
|
||||
// Constantes de tiempo
|
||||
static constexpr float ITEMS_COLOR_BLINK_DURATION = 0.333F; // Duración de cada estado del parpadeo (era 10 frames @ 60fps)
|
||||
static constexpr float SPRITE_WALK_CYCLE_DURATION = 0.667F; // Duración del ciclo de caminar (era 40 frames @ 60fps)
|
||||
static constexpr int SPRITE_WALK_FRAMES = 4; // Número de frames de animación
|
||||
|
||||
// Métodos privados
|
||||
auto getTime() -> ClockData; // Obtiene el tiempo transcurrido de partida
|
||||
void updateItemsColor(float delta_time); // Actualiza el color de la cantidad de items recogidos
|
||||
void fillTexture(); // Dibuja los elementos del marcador en la surface
|
||||
|
||||
// Objetos y punteros
|
||||
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite para mostrar las vidas en el marcador
|
||||
std::shared_ptr<Surface> item_surface_; // Surface con los graficos para los elementos del marcador
|
||||
std::shared_ptr<Data> data_; // Contiene las variables a mostrar en el marcador
|
||||
std::shared_ptr<Surface> surface_; // Surface donde dibujar el marcador
|
||||
|
||||
// Variables de estado
|
||||
std::vector<Uint8> color_; // Vector con los colores del objeto
|
||||
bool is_paused_{false}; // Indica si el marcador esta en modo pausa
|
||||
Uint32 paused_time_{0}; // Milisegundos que ha estado el marcador en pausa
|
||||
Uint32 paused_time_elapsed_{0}; // Tiempo acumulado en pausa
|
||||
ClockData clock_{}; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
|
||||
Uint8 items_color_{0}; // Color de la cantidad de items recogidos
|
||||
SDL_FRect surface_dest_{}; // Rectangulo donde dibujar la surface del marcador
|
||||
float time_accumulator_{0.0F}; // Acumulador de tiempo para animaciones
|
||||
float items_color_timer_{0.0F}; // Timer para parpadeo de color de items
|
||||
};
|
||||
188
source/game/gameplay/tilemap_renderer.cpp
Normal file
188
source/game/gameplay/tilemap_renderer.cpp
Normal file
@@ -0,0 +1,188 @@
|
||||
#include "tilemap_renderer.hpp"
|
||||
|
||||
#include "core/rendering/screen.hpp"
|
||||
#include "core/rendering/surface.hpp"
|
||||
#include "core/rendering/surface_sprite.hpp"
|
||||
#ifdef _DEBUG
|
||||
#include "core/system/debug.hpp"
|
||||
#endif
|
||||
#include "game/gameplay/collision_map.hpp"
|
||||
#include "utils/color.hpp"
|
||||
#include "utils/utils.hpp"
|
||||
|
||||
// Constructor
|
||||
TilemapRenderer::TilemapRenderer(std::vector<int> tile_map, int tile_set_width, std::shared_ptr<Surface> tileset_surface, std::string bg_color, int conveyor_belt_direction)
|
||||
: tile_map_(std::move(tile_map)),
|
||||
tile_set_width_(tile_set_width),
|
||||
tileset_surface_(std::move(tileset_surface)),
|
||||
bg_color_(std::move(bg_color)),
|
||||
conveyor_belt_direction_(conveyor_belt_direction) {
|
||||
// Crear la surface del mapa
|
||||
map_surface_ = std::make_shared<Surface>(PlayArea::WIDTH, PlayArea::HEIGHT);
|
||||
}
|
||||
|
||||
// Inicializa el renderizador
|
||||
void TilemapRenderer::initialize(const CollisionMap* collision_map) {
|
||||
setAnimatedTiles(collision_map);
|
||||
fillMapTexture(collision_map);
|
||||
}
|
||||
|
||||
// Actualiza las animaciones de tiles
|
||||
void TilemapRenderer::update(float delta_time) {
|
||||
if (is_paused_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Actualiza el acumulador de tiempo
|
||||
time_accumulator_ += delta_time;
|
||||
|
||||
// Actualiza los tiles animados
|
||||
updateAnimatedTiles();
|
||||
}
|
||||
|
||||
// Renderiza el mapa completo en pantalla
|
||||
void TilemapRenderer::render() {
|
||||
// Dibuja la textura con el mapa en pantalla
|
||||
SDL_FRect dest = {0, 0, PlayArea::WIDTH, PlayArea::HEIGHT};
|
||||
map_surface_->render(nullptr, &dest);
|
||||
|
||||
// Dibuja los tiles animados
|
||||
#ifdef _DEBUG
|
||||
if (!Debug::get()->isEnabled()) {
|
||||
renderAnimatedTiles();
|
||||
}
|
||||
#else
|
||||
renderAnimatedTiles();
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
// Renderiza las superficies de colisión en modo debug (función helper estática)
|
||||
static void renderDebugCollisionSurfaces(const CollisionMap* collision_map) {
|
||||
auto surface = Screen::get()->getRendererSurface();
|
||||
|
||||
// BottomSurfaces
|
||||
for (auto l : collision_map->getBottomFloors()) {
|
||||
surface->drawLine(l.x1, l.y, l.x2, l.y, Color::index(Color::Cpc::BLUE));
|
||||
}
|
||||
|
||||
// TopSurfaces
|
||||
for (auto l : collision_map->getTopFloors()) {
|
||||
surface->drawLine(l.x1, l.y, l.x2, l.y, Color::index(Color::Cpc::RED));
|
||||
}
|
||||
|
||||
// LeftSurfaces
|
||||
for (auto l : collision_map->getLeftWalls()) {
|
||||
surface->drawLine(l.x, l.y1, l.x, l.y2, Color::index(Color::Cpc::GREEN));
|
||||
}
|
||||
|
||||
// RightSurfaces
|
||||
for (auto l : collision_map->getRightWalls()) {
|
||||
surface->drawLine(l.x, l.y1, l.x, l.y2, Color::index(Color::Cpc::MAGENTA));
|
||||
}
|
||||
|
||||
// AutoSurfaces (Conveyor Belts)
|
||||
for (auto l : collision_map->getConveyorBeltFloors()) {
|
||||
surface->drawLine(l.x1, l.y, l.x2, l.y, Color::index(Color::Cpc::WHITE));
|
||||
}
|
||||
}
|
||||
|
||||
// Redibuja el tilemap (para actualizar modo debug)
|
||||
void TilemapRenderer::redrawMap(const CollisionMap* collision_map) {
|
||||
fillMapTexture(collision_map);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Pinta el mapa estático y debug lines
|
||||
void TilemapRenderer::fillMapTexture(const CollisionMap* collision_map) {
|
||||
const Uint8 COLOR = stringToColor(bg_color_);
|
||||
auto previous_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(map_surface_);
|
||||
map_surface_->clear(COLOR);
|
||||
|
||||
// Los tileSetFiles son de 20x20 tiles. El primer tile es el 0. Cuentan hacia la derecha y hacia abajo
|
||||
|
||||
SDL_FRect clip = {0, 0, TILE_SIZE, TILE_SIZE};
|
||||
for (int y = 0; y < MAP_HEIGHT; ++y) {
|
||||
for (int x = 0; x < MAP_WIDTH; ++x) {
|
||||
// Tiled pone los tiles vacios del mapa como cero y empieza a contar de 1 a n.
|
||||
// Al cargar el mapa en memoria, se resta uno, por tanto los tiles vacios son -1
|
||||
// Tampoco hay que dibujar los tiles animados (se dibujan en renderAnimatedTiles)
|
||||
const int INDEX = (y * MAP_WIDTH) + x;
|
||||
const bool IS_ANIMATED = collision_map->getTile(INDEX) == CollisionMap::Tile::ANIMATED;
|
||||
const bool IS_VISIBLE = tile_map_[INDEX] > -1;
|
||||
|
||||
if (IS_VISIBLE && !IS_ANIMATED) {
|
||||
clip.x = (tile_map_[INDEX] % tile_set_width_) * TILE_SIZE;
|
||||
clip.y = (tile_map_[INDEX] / tile_set_width_) * TILE_SIZE;
|
||||
#ifdef _DEBUG
|
||||
if (!Debug::get()->isEnabled()) {
|
||||
tileset_surface_->render(x * TILE_SIZE, y * TILE_SIZE, &clip);
|
||||
}
|
||||
#else
|
||||
tileset_surface_->render(x * TILE_SIZE, y * TILE_SIZE, &clip);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
// Pinta las superficies en el modo debug
|
||||
if (Debug::get()->isEnabled()) {
|
||||
renderDebugCollisionSurfaces(collision_map);
|
||||
}
|
||||
#endif // _DEBUG
|
||||
Screen::get()->setRendererSurface(previous_renderer);
|
||||
}
|
||||
|
||||
// Localiza todos los tiles animados
|
||||
void TilemapRenderer::setAnimatedTiles(const CollisionMap* collision_map) {
|
||||
// Recorre la habitación entera por filas buscando tiles de tipo t_animated
|
||||
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
||||
const auto TILE_TYPE = collision_map->getTile(i);
|
||||
if (TILE_TYPE == CollisionMap::Tile::ANIMATED) {
|
||||
// La i es la ubicación
|
||||
const int X = (i % MAP_WIDTH) * TILE_SIZE;
|
||||
const int Y = (i / MAP_WIDTH) * TILE_SIZE;
|
||||
|
||||
// TileMap[i] es el tile a poner
|
||||
const int XC = (tile_map_[i] % tile_set_width_) * TILE_SIZE;
|
||||
const int YC = (tile_map_[i] / tile_set_width_) * TILE_SIZE;
|
||||
|
||||
AnimatedTile at;
|
||||
at.sprite = std::make_shared<SurfaceSprite>(tileset_surface_, X, Y, 8, 8);
|
||||
at.sprite->setClip(XC, YC, 8, 8);
|
||||
at.x_orig = XC;
|
||||
animated_tiles_.push_back(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza tiles animados
|
||||
void TilemapRenderer::updateAnimatedTiles() {
|
||||
const int NUM_FRAMES = 4;
|
||||
|
||||
// Calcular frame actual basado en tiempo
|
||||
const int CURRENT_FRAME = static_cast<int>(time_accumulator_ / CONVEYOR_FRAME_DURATION) % NUM_FRAMES;
|
||||
|
||||
// Calcular offset basado en dirección
|
||||
int offset = 0;
|
||||
if (conveyor_belt_direction_ == -1) {
|
||||
offset = CURRENT_FRAME * TILE_SIZE;
|
||||
} else {
|
||||
offset = (NUM_FRAMES - 1 - CURRENT_FRAME) * TILE_SIZE;
|
||||
}
|
||||
|
||||
for (auto& a : animated_tiles_) {
|
||||
SDL_FRect rect = a.sprite->getClip();
|
||||
rect.x = a.x_orig + offset;
|
||||
a.sprite->setClip(rect);
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza tiles animados
|
||||
void TilemapRenderer::renderAnimatedTiles() {
|
||||
for (const auto& a : animated_tiles_) {
|
||||
a.sprite->render();
|
||||
}
|
||||
}
|
||||
118
source/game/gameplay/tilemap_renderer.hpp
Normal file
118
source/game/gameplay/tilemap_renderer.hpp
Normal file
@@ -0,0 +1,118 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "utils/defines.hpp"
|
||||
|
||||
class Surface;
|
||||
class SurfaceSprite;
|
||||
class CollisionMap;
|
||||
|
||||
/**
|
||||
* @brief Renderizador de tilemap de una habitación
|
||||
*
|
||||
* Responsabilidades:
|
||||
* - Renderizar el mapa de tiles estático
|
||||
* - Gestionar tiles animados (conveyor belts)
|
||||
* - Actualizar animaciones basadas en tiempo
|
||||
* - Renderizar debug visualization (en modo DEBUG)
|
||||
*/
|
||||
class TilemapRenderer {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor
|
||||
* @param tile_map Vector con índices de tiles de la habitación
|
||||
* @param tile_set_width Ancho del tileset en tiles
|
||||
* @param tileset_surface Surface con los gráficos del tileset
|
||||
* @param bg_color Color de fondo de la habitación (como string)
|
||||
* @param conveyor_belt_direction Dirección de las cintas transportadoras (-1, 0, +1)
|
||||
*/
|
||||
TilemapRenderer(std::vector<int> tile_map, int tile_set_width, std::shared_ptr<Surface> tileset_surface, std::string bg_color, int conveyor_belt_direction);
|
||||
~TilemapRenderer() = default;
|
||||
|
||||
// Prohibir copia y movimiento
|
||||
TilemapRenderer(const TilemapRenderer&) = delete;
|
||||
auto operator=(const TilemapRenderer&) -> TilemapRenderer& = delete;
|
||||
TilemapRenderer(TilemapRenderer&&) = delete;
|
||||
auto operator=(TilemapRenderer&&) -> TilemapRenderer& = delete;
|
||||
|
||||
/**
|
||||
* @brief Inicializa el renderizador
|
||||
* @param collision_map Mapa de colisiones para determinar tiles animados
|
||||
*
|
||||
* Crea la textura del mapa, pinta los tiles estáticos, y localiza tiles animados
|
||||
*/
|
||||
void initialize(const CollisionMap* collision_map);
|
||||
|
||||
/**
|
||||
* @brief Actualiza las animaciones de tiles
|
||||
* @param delta_time Tiempo transcurrido desde el último frame (segundos)
|
||||
*/
|
||||
void update(float delta_time);
|
||||
|
||||
/**
|
||||
* @brief Renderiza el mapa completo en pantalla
|
||||
*
|
||||
* Dibuja la textura del mapa y los tiles animados
|
||||
*/
|
||||
void render();
|
||||
|
||||
#ifdef _DEBUG
|
||||
/**
|
||||
* @brief Redibuja el tilemap (para actualizar modo debug)
|
||||
* @param collision_map Mapa de colisiones para dibujar líneas de debug
|
||||
*
|
||||
* Llamado cuando se activa/desactiva el modo debug para actualizar la visualización
|
||||
*/
|
||||
void redrawMap(const CollisionMap* collision_map);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Activa/desactiva modo pausa
|
||||
* @param paused true para pausar, false para reanudar
|
||||
*
|
||||
* Nota: Actualmente no afecta al renderizado, pero mantiene consistencia con Room
|
||||
*/
|
||||
void setPaused(bool paused) { is_paused_ = paused; }
|
||||
|
||||
// Getter para la surface del mapa (usado por Room para acceso directo si es necesario)
|
||||
[[nodiscard]] auto getMapSurface() const -> std::shared_ptr<Surface> { return map_surface_; }
|
||||
|
||||
private:
|
||||
// Estructura para tiles animados (conveyor belts)
|
||||
struct AnimatedTile {
|
||||
std::shared_ptr<SurfaceSprite> sprite{nullptr}; // SurfaceSprite para dibujar el tile
|
||||
int x_orig{0}; // Posición X del primer tile de la animación en tilesheet
|
||||
};
|
||||
|
||||
// === Constantes ===
|
||||
static constexpr int TILE_SIZE = Tile::SIZE; // Ancho del tile en pixels
|
||||
static constexpr int MAP_WIDTH = PlayArea::WIDTH / Tile::SIZE; // Ancho del mapa en tiles
|
||||
static constexpr int MAP_HEIGHT = PlayArea::HEIGHT / Tile::SIZE; // Alto del mapa en tiles
|
||||
static constexpr int PLAY_AREA_WIDTH = PlayArea::WIDTH; // Ancho del área de juego en pixels
|
||||
static constexpr int PLAY_AREA_HEIGHT = PlayArea::HEIGHT; // Alto del área de juego en pixels
|
||||
static constexpr float CONVEYOR_FRAME_DURATION = 0.05F; // Duración de cada frame (3 frames @ 60fps)
|
||||
|
||||
// === Datos de la habitación ===
|
||||
std::vector<int> tile_map_; // Índices de tiles de la habitación
|
||||
int tile_set_width_; // Ancho del tileset en tiles
|
||||
std::shared_ptr<Surface> tileset_surface_; // Gráficos del tileset
|
||||
std::string bg_color_; // Color de fondo
|
||||
int conveyor_belt_direction_; // Dirección de conveyor belts
|
||||
|
||||
// === Renderizado ===
|
||||
std::shared_ptr<Surface> map_surface_; // Textura para el mapa de la habitación
|
||||
std::vector<AnimatedTile> animated_tiles_; // Tiles animados (conveyor belts)
|
||||
float time_accumulator_{0.0F}; // Acumulador de tiempo para animaciones
|
||||
bool is_paused_{false}; // Indica si está en modo pausa
|
||||
|
||||
// === Métodos privados ===
|
||||
void fillMapTexture(const CollisionMap* collision_map); // Pinta el mapa estático y debug lines
|
||||
void setAnimatedTiles(const CollisionMap* collision_map); // Localiza todos los tiles animados
|
||||
void updateAnimatedTiles(); // Actualiza tiles animados
|
||||
void renderAnimatedTiles(); // Renderiza tiles animados
|
||||
};
|
||||
610
source/game/options.cpp
Normal file
610
source/game/options.cpp
Normal file
@@ -0,0 +1,610 @@
|
||||
#include "game/options.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <fstream> // Para ifstream, ofstream
|
||||
#include <iostream> // Para cout, cerr
|
||||
#include <string> // Para string
|
||||
#include <unordered_map> // Para unordered_map
|
||||
|
||||
#include "core/input/input_types.hpp" // Para BUTTON_TO_STRING, STRING_TO_BUTTON
|
||||
#include "external/fkyaml_node.hpp" // Para fkyaml::node
|
||||
#include "game/defaults.hpp" // Para GameDefaults::VERSION
|
||||
|
||||
namespace Options {
|
||||
|
||||
// --- Funciones helper de conversión ---
|
||||
|
||||
// Mapa de nombres de filtro
|
||||
const std::unordered_map<Screen::Filter, std::string> FILTER_TO_STRING = {
|
||||
{Screen::Filter::NEAREST, "nearest"},
|
||||
{Screen::Filter::LINEAR, "linear"}};
|
||||
|
||||
const std::unordered_map<std::string, Screen::Filter> STRING_TO_FILTER = {
|
||||
{"nearest", Screen::Filter::NEAREST},
|
||||
{"linear", Screen::Filter::LINEAR}};
|
||||
|
||||
// Mapa de scancodes comunes (los más usados para controles de juego)
|
||||
const std::unordered_map<SDL_Scancode, std::string> SCANCODE_TO_STRING = {
|
||||
// Flechas
|
||||
{SDL_SCANCODE_LEFT, "LEFT"},
|
||||
{SDL_SCANCODE_RIGHT, "RIGHT"},
|
||||
{SDL_SCANCODE_UP, "UP"},
|
||||
{SDL_SCANCODE_DOWN, "DOWN"},
|
||||
// Letras
|
||||
{SDL_SCANCODE_A, "A"},
|
||||
{SDL_SCANCODE_B, "B"},
|
||||
{SDL_SCANCODE_C, "C"},
|
||||
{SDL_SCANCODE_D, "D"},
|
||||
{SDL_SCANCODE_E, "E"},
|
||||
{SDL_SCANCODE_F, "F"},
|
||||
{SDL_SCANCODE_G, "G"},
|
||||
{SDL_SCANCODE_H, "H"},
|
||||
{SDL_SCANCODE_I, "I"},
|
||||
{SDL_SCANCODE_J, "J"},
|
||||
{SDL_SCANCODE_K, "K"},
|
||||
{SDL_SCANCODE_L, "L"},
|
||||
{SDL_SCANCODE_M, "M"},
|
||||
{SDL_SCANCODE_N, "N"},
|
||||
{SDL_SCANCODE_O, "O"},
|
||||
{SDL_SCANCODE_P, "P"},
|
||||
{SDL_SCANCODE_Q, "Q"},
|
||||
{SDL_SCANCODE_R, "R"},
|
||||
{SDL_SCANCODE_S, "S"},
|
||||
{SDL_SCANCODE_T, "T"},
|
||||
{SDL_SCANCODE_U, "U"},
|
||||
{SDL_SCANCODE_V, "V"},
|
||||
{SDL_SCANCODE_W, "W"},
|
||||
{SDL_SCANCODE_X, "X"},
|
||||
{SDL_SCANCODE_Y, "Y"},
|
||||
{SDL_SCANCODE_Z, "Z"},
|
||||
// Números
|
||||
{SDL_SCANCODE_0, "0"},
|
||||
{SDL_SCANCODE_1, "1"},
|
||||
{SDL_SCANCODE_2, "2"},
|
||||
{SDL_SCANCODE_3, "3"},
|
||||
{SDL_SCANCODE_4, "4"},
|
||||
{SDL_SCANCODE_5, "5"},
|
||||
{SDL_SCANCODE_6, "6"},
|
||||
{SDL_SCANCODE_7, "7"},
|
||||
{SDL_SCANCODE_8, "8"},
|
||||
{SDL_SCANCODE_9, "9"},
|
||||
// Teclas especiales
|
||||
{SDL_SCANCODE_SPACE, "SPACE"},
|
||||
{SDL_SCANCODE_RETURN, "RETURN"},
|
||||
{SDL_SCANCODE_ESCAPE, "ESCAPE"},
|
||||
{SDL_SCANCODE_TAB, "TAB"},
|
||||
{SDL_SCANCODE_BACKSPACE, "BACKSPACE"},
|
||||
{SDL_SCANCODE_LSHIFT, "LSHIFT"},
|
||||
{SDL_SCANCODE_RSHIFT, "RSHIFT"},
|
||||
{SDL_SCANCODE_LCTRL, "LCTRL"},
|
||||
{SDL_SCANCODE_RCTRL, "RCTRL"},
|
||||
{SDL_SCANCODE_LALT, "LALT"},
|
||||
{SDL_SCANCODE_RALT, "RALT"}};
|
||||
|
||||
const std::unordered_map<std::string, SDL_Scancode> STRING_TO_SCANCODE = {
|
||||
// Flechas
|
||||
{"LEFT", SDL_SCANCODE_LEFT},
|
||||
{"RIGHT", SDL_SCANCODE_RIGHT},
|
||||
{"UP", SDL_SCANCODE_UP},
|
||||
{"DOWN", SDL_SCANCODE_DOWN},
|
||||
// Letras
|
||||
{"A", SDL_SCANCODE_A},
|
||||
{"B", SDL_SCANCODE_B},
|
||||
{"C", SDL_SCANCODE_C},
|
||||
{"D", SDL_SCANCODE_D},
|
||||
{"E", SDL_SCANCODE_E},
|
||||
{"F", SDL_SCANCODE_F},
|
||||
{"G", SDL_SCANCODE_G},
|
||||
{"H", SDL_SCANCODE_H},
|
||||
{"I", SDL_SCANCODE_I},
|
||||
{"J", SDL_SCANCODE_J},
|
||||
{"K", SDL_SCANCODE_K},
|
||||
{"L", SDL_SCANCODE_L},
|
||||
{"M", SDL_SCANCODE_M},
|
||||
{"N", SDL_SCANCODE_N},
|
||||
{"O", SDL_SCANCODE_O},
|
||||
{"P", SDL_SCANCODE_P},
|
||||
{"Q", SDL_SCANCODE_Q},
|
||||
{"R", SDL_SCANCODE_R},
|
||||
{"S", SDL_SCANCODE_S},
|
||||
{"T", SDL_SCANCODE_T},
|
||||
{"U", SDL_SCANCODE_U},
|
||||
{"V", SDL_SCANCODE_V},
|
||||
{"W", SDL_SCANCODE_W},
|
||||
{"X", SDL_SCANCODE_X},
|
||||
{"Y", SDL_SCANCODE_Y},
|
||||
{"Z", SDL_SCANCODE_Z},
|
||||
// Números
|
||||
{"0", SDL_SCANCODE_0},
|
||||
{"1", SDL_SCANCODE_1},
|
||||
{"2", SDL_SCANCODE_2},
|
||||
{"3", SDL_SCANCODE_3},
|
||||
{"4", SDL_SCANCODE_4},
|
||||
{"5", SDL_SCANCODE_5},
|
||||
{"6", SDL_SCANCODE_6},
|
||||
{"7", SDL_SCANCODE_7},
|
||||
{"8", SDL_SCANCODE_8},
|
||||
{"9", SDL_SCANCODE_9},
|
||||
// Teclas especiales
|
||||
{"SPACE", SDL_SCANCODE_SPACE},
|
||||
{"RETURN", SDL_SCANCODE_RETURN},
|
||||
{"ESCAPE", SDL_SCANCODE_ESCAPE},
|
||||
{"TAB", SDL_SCANCODE_TAB},
|
||||
{"BACKSPACE", SDL_SCANCODE_BACKSPACE},
|
||||
{"LSHIFT", SDL_SCANCODE_LSHIFT},
|
||||
{"RSHIFT", SDL_SCANCODE_RSHIFT},
|
||||
{"LCTRL", SDL_SCANCODE_LCTRL},
|
||||
{"RCTRL", SDL_SCANCODE_RCTRL},
|
||||
{"LALT", SDL_SCANCODE_LALT},
|
||||
{"RALT", SDL_SCANCODE_RALT}};
|
||||
|
||||
// Mapa extendido de botones de gamepad (incluye ejes como botones)
|
||||
const std::unordered_map<int, std::string> GAMEPAD_BUTTON_TO_STRING = {
|
||||
{SDL_GAMEPAD_BUTTON_WEST, "WEST"},
|
||||
{SDL_GAMEPAD_BUTTON_NORTH, "NORTH"},
|
||||
{SDL_GAMEPAD_BUTTON_EAST, "EAST"},
|
||||
{SDL_GAMEPAD_BUTTON_SOUTH, "SOUTH"},
|
||||
{SDL_GAMEPAD_BUTTON_START, "START"},
|
||||
{SDL_GAMEPAD_BUTTON_BACK, "BACK"},
|
||||
{SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, "LEFT_SHOULDER"},
|
||||
{SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, "RIGHT_SHOULDER"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT"},
|
||||
{SDL_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT"},
|
||||
{100, "L2_AS_BUTTON"},
|
||||
{101, "R2_AS_BUTTON"},
|
||||
{200, "LEFT_STICK_LEFT"},
|
||||
{201, "LEFT_STICK_RIGHT"}};
|
||||
|
||||
const std::unordered_map<std::string, int> STRING_TO_GAMEPAD_BUTTON = {
|
||||
{"WEST", SDL_GAMEPAD_BUTTON_WEST},
|
||||
{"NORTH", SDL_GAMEPAD_BUTTON_NORTH},
|
||||
{"EAST", SDL_GAMEPAD_BUTTON_EAST},
|
||||
{"SOUTH", SDL_GAMEPAD_BUTTON_SOUTH},
|
||||
{"START", SDL_GAMEPAD_BUTTON_START},
|
||||
{"BACK", SDL_GAMEPAD_BUTTON_BACK},
|
||||
{"LEFT_SHOULDER", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
|
||||
{"RIGHT_SHOULDER", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
|
||||
{"DPAD_UP", SDL_GAMEPAD_BUTTON_DPAD_UP},
|
||||
{"DPAD_DOWN", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
|
||||
{"DPAD_LEFT", SDL_GAMEPAD_BUTTON_DPAD_LEFT},
|
||||
{"DPAD_RIGHT", SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
|
||||
{"L2_AS_BUTTON", 100},
|
||||
{"R2_AS_BUTTON", 101},
|
||||
{"LEFT_STICK_LEFT", 200},
|
||||
{"LEFT_STICK_RIGHT", 201}};
|
||||
|
||||
// Lista de paletas válidas
|
||||
const std::vector<std::string> VALID_PALETTES = {
|
||||
"black-and-white",
|
||||
"green-phosphor",
|
||||
"island-joy-16",
|
||||
"lost-century",
|
||||
"na16",
|
||||
"orange-screen",
|
||||
"pico-8",
|
||||
"ruzx-spectrum",
|
||||
"ruzx-spectrum-revision-2",
|
||||
"steam-lords",
|
||||
"sweetie-16",
|
||||
"sweetie-16_bona",
|
||||
"zx-spectrum",
|
||||
"zx-spectrum-adjusted",
|
||||
"zxarne-5-2"};
|
||||
|
||||
// Funciones helper de conversión
|
||||
auto filterToString(Screen::Filter filter) -> std::string {
|
||||
auto it = FILTER_TO_STRING.find(filter);
|
||||
if (it != FILTER_TO_STRING.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return "nearest";
|
||||
}
|
||||
|
||||
auto stringToFilter(const std::string& str) -> Screen::Filter {
|
||||
auto it = STRING_TO_FILTER.find(str);
|
||||
if (it != STRING_TO_FILTER.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return Defaults::Video::FILTER;
|
||||
}
|
||||
|
||||
auto scancodeToString(SDL_Scancode scancode) -> std::string {
|
||||
auto it = SCANCODE_TO_STRING.find(scancode);
|
||||
if (it != SCANCODE_TO_STRING.end()) {
|
||||
return it->second;
|
||||
}
|
||||
// Fallback: devolver el código numérico como string
|
||||
return std::to_string(static_cast<int>(scancode));
|
||||
}
|
||||
|
||||
auto stringToScancode(const std::string& str, SDL_Scancode default_value) -> SDL_Scancode {
|
||||
auto it = STRING_TO_SCANCODE.find(str);
|
||||
if (it != STRING_TO_SCANCODE.end()) {
|
||||
return it->second;
|
||||
}
|
||||
// Intentar parsear como número (compatibilidad hacia atrás)
|
||||
try {
|
||||
int val = std::stoi(str);
|
||||
return static_cast<SDL_Scancode>(val);
|
||||
} catch (...) {
|
||||
return default_value;
|
||||
}
|
||||
}
|
||||
|
||||
auto gamepadButtonToString(int button) -> std::string {
|
||||
auto it = GAMEPAD_BUTTON_TO_STRING.find(button);
|
||||
if (it != GAMEPAD_BUTTON_TO_STRING.end()) {
|
||||
return it->second;
|
||||
}
|
||||
// Fallback: devolver el código numérico como string
|
||||
return std::to_string(button);
|
||||
}
|
||||
|
||||
auto stringToGamepadButton(const std::string& str, int default_value) -> int {
|
||||
auto it = STRING_TO_GAMEPAD_BUTTON.find(str);
|
||||
if (it != STRING_TO_GAMEPAD_BUTTON.end()) {
|
||||
return it->second;
|
||||
}
|
||||
// Intentar parsear como número (compatibilidad hacia atrás)
|
||||
try {
|
||||
return std::stoi(str);
|
||||
} catch (...) {
|
||||
return default_value;
|
||||
}
|
||||
}
|
||||
|
||||
auto isValidPalette(const std::string& palette) -> bool {
|
||||
return std::ranges::any_of(VALID_PALETTES, [&palette](const auto& valid) { return valid == palette; });
|
||||
}
|
||||
|
||||
// --- Funciones helper para loadFromFile() ---
|
||||
|
||||
// Carga configuración de ventana desde YAML
|
||||
void loadWindowConfigFromYaml(const fkyaml::node& yaml) {
|
||||
if (yaml.contains("window")) {
|
||||
const auto& win = yaml["window"];
|
||||
if (win.contains("zoom")) {
|
||||
try {
|
||||
int val = win["zoom"].get_value<int>();
|
||||
window.zoom = (val > 0) ? val : Defaults::Window::ZOOM;
|
||||
} catch (...) {
|
||||
window.zoom = Defaults::Window::ZOOM;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga configuración de borde desde YAML
|
||||
void loadBorderConfigFromYaml(const fkyaml::node& border) {
|
||||
if (border.contains("enabled")) {
|
||||
try {
|
||||
video.border.enabled = border["enabled"].get_value<bool>();
|
||||
} catch (...) {
|
||||
video.border.enabled = Defaults::Border::ENABLED;
|
||||
}
|
||||
}
|
||||
|
||||
if (border.contains("width")) {
|
||||
try {
|
||||
auto val = border["width"].get_value<float>();
|
||||
video.border.width = (val > 0) ? val : Defaults::Border::WIDTH;
|
||||
} catch (...) {
|
||||
video.border.width = Defaults::Border::WIDTH;
|
||||
}
|
||||
}
|
||||
|
||||
if (border.contains("height")) {
|
||||
try {
|
||||
auto val = border["height"].get_value<float>();
|
||||
video.border.height = (val > 0) ? val : Defaults::Border::HEIGHT;
|
||||
} catch (...) {
|
||||
video.border.height = Defaults::Border::HEIGHT;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga los campos básicos de configuración de video
|
||||
void loadBasicVideoFieldsFromYaml(const fkyaml::node& vid) {
|
||||
// fullscreen (antes era "mode")
|
||||
if (vid.contains("fullscreen")) {
|
||||
try {
|
||||
video.fullscreen = vid["fullscreen"].get_value<bool>();
|
||||
} catch (...) {
|
||||
video.fullscreen = Defaults::Video::FULLSCREEN;
|
||||
}
|
||||
}
|
||||
|
||||
// filter (ahora es string)
|
||||
if (vid.contains("filter")) {
|
||||
try {
|
||||
auto filter_str = vid["filter"].get_value<std::string>();
|
||||
video.filter = stringToFilter(filter_str);
|
||||
} catch (...) {
|
||||
video.filter = Defaults::Video::FILTER;
|
||||
}
|
||||
}
|
||||
|
||||
if (vid.contains("shaders")) {
|
||||
try {
|
||||
video.shaders = vid["shaders"].get_value<bool>();
|
||||
} catch (...) {
|
||||
video.shaders = Defaults::Video::SHADERS;
|
||||
}
|
||||
}
|
||||
|
||||
if (vid.contains("vertical_sync")) {
|
||||
try {
|
||||
video.vertical_sync = vid["vertical_sync"].get_value<bool>();
|
||||
} catch (...) {
|
||||
video.vertical_sync = Defaults::Video::VERTICAL_SYNC;
|
||||
}
|
||||
}
|
||||
|
||||
if (vid.contains("integer_scale")) {
|
||||
try {
|
||||
video.integer_scale = vid["integer_scale"].get_value<bool>();
|
||||
} catch (...) {
|
||||
video.integer_scale = Defaults::Video::INTEGER_SCALE;
|
||||
}
|
||||
}
|
||||
|
||||
if (vid.contains("keep_aspect")) {
|
||||
try {
|
||||
video.keep_aspect = vid["keep_aspect"].get_value<bool>();
|
||||
} catch (...) {
|
||||
video.keep_aspect = Defaults::Video::KEEP_ASPECT;
|
||||
}
|
||||
}
|
||||
|
||||
if (vid.contains("palette")) {
|
||||
try {
|
||||
auto palette_str = vid["palette"].get_value<std::string>();
|
||||
if (isValidPalette(palette_str)) {
|
||||
video.palette = palette_str;
|
||||
} else {
|
||||
video.palette = Defaults::Video::PALETTE_NAME;
|
||||
}
|
||||
} catch (...) {
|
||||
video.palette = Defaults::Video::PALETTE_NAME;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga configuración de video desde YAML
|
||||
void loadVideoConfigFromYaml(const fkyaml::node& yaml) {
|
||||
if (yaml.contains("video")) {
|
||||
const auto& vid = yaml["video"];
|
||||
loadBasicVideoFieldsFromYaml(vid);
|
||||
|
||||
// Lee border
|
||||
if (vid.contains("border")) {
|
||||
loadBorderConfigFromYaml(vid["border"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga controles de teclado desde YAML
|
||||
void loadKeyboardControlsFromYaml(const fkyaml::node& yaml) {
|
||||
if (yaml.contains("keyboard_controls")) {
|
||||
const auto& ctrl = yaml["keyboard_controls"];
|
||||
|
||||
if (ctrl.contains("key_left")) {
|
||||
try {
|
||||
auto key_str = ctrl["key_left"].get_value<std::string>();
|
||||
keyboard_controls.key_left = stringToScancode(key_str, Defaults::Controls::KEY_LEFT);
|
||||
} catch (...) {
|
||||
keyboard_controls.key_left = Defaults::Controls::KEY_LEFT;
|
||||
}
|
||||
}
|
||||
|
||||
if (ctrl.contains("key_right")) {
|
||||
try {
|
||||
auto key_str = ctrl["key_right"].get_value<std::string>();
|
||||
keyboard_controls.key_right = stringToScancode(key_str, Defaults::Controls::KEY_RIGHT);
|
||||
} catch (...) {
|
||||
keyboard_controls.key_right = Defaults::Controls::KEY_RIGHT;
|
||||
}
|
||||
}
|
||||
|
||||
if (ctrl.contains("key_jump")) {
|
||||
try {
|
||||
auto key_str = ctrl["key_jump"].get_value<std::string>();
|
||||
keyboard_controls.key_jump = stringToScancode(key_str, Defaults::Controls::KEY_JUMP);
|
||||
} catch (...) {
|
||||
keyboard_controls.key_jump = Defaults::Controls::KEY_JUMP;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carga controles de gamepad desde YAML
|
||||
void loadGamepadControlsFromYaml(const fkyaml::node& yaml) {
|
||||
if (yaml.contains("gamepad_controls")) {
|
||||
const auto& gp = yaml["gamepad_controls"];
|
||||
|
||||
if (gp.contains("button_left")) {
|
||||
try {
|
||||
auto button_str = gp["button_left"].get_value<std::string>();
|
||||
gamepad_controls.button_left = stringToGamepadButton(button_str, Defaults::Controls::GAMEPAD_BUTTON_LEFT);
|
||||
} catch (...) {
|
||||
gamepad_controls.button_left = Defaults::Controls::GAMEPAD_BUTTON_LEFT;
|
||||
}
|
||||
}
|
||||
|
||||
if (gp.contains("button_right")) {
|
||||
try {
|
||||
auto button_str = gp["button_right"].get_value<std::string>();
|
||||
gamepad_controls.button_right = stringToGamepadButton(button_str, Defaults::Controls::GAMEPAD_BUTTON_RIGHT);
|
||||
} catch (...) {
|
||||
gamepad_controls.button_right = Defaults::Controls::GAMEPAD_BUTTON_RIGHT;
|
||||
}
|
||||
}
|
||||
|
||||
if (gp.contains("button_jump")) {
|
||||
try {
|
||||
auto button_str = gp["button_jump"].get_value<std::string>();
|
||||
gamepad_controls.button_jump = stringToGamepadButton(button_str, Defaults::Controls::GAMEPAD_BUTTON_JUMP);
|
||||
} catch (...) {
|
||||
gamepad_controls.button_jump = Defaults::Controls::GAMEPAD_BUTTON_JUMP;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Crea e inicializa las opciones del programa
|
||||
void init() {
|
||||
#ifdef _DEBUG
|
||||
console = true;
|
||||
#else
|
||||
console = false;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Establece la ruta del fichero de configuración
|
||||
void setConfigFile(const std::string& path) {
|
||||
config_file_path = path;
|
||||
}
|
||||
|
||||
// Carga las opciones desde el fichero configurado
|
||||
auto loadFromFile() -> bool {
|
||||
// Versión esperada del fichero
|
||||
const std::string CONFIG_VERSION = std::string(Project::VERSION);
|
||||
version = "";
|
||||
|
||||
// Intenta abrir y leer el fichero
|
||||
std::ifstream file(config_file_path);
|
||||
if (!file.good()) {
|
||||
if (console) {
|
||||
std::cout << "Config file not found, creating default: " << config_file_path << '\n';
|
||||
}
|
||||
saveToFile();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Lee todo el contenido del fichero
|
||||
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
try {
|
||||
if (console) {
|
||||
std::cout << "Reading config file: " << config_file_path << '\n';
|
||||
}
|
||||
|
||||
// Parsea el YAML
|
||||
auto yaml = fkyaml::node::deserialize(content);
|
||||
|
||||
// Lee la versión
|
||||
if (yaml.contains("version")) {
|
||||
version = yaml["version"].get_value<std::string>();
|
||||
}
|
||||
|
||||
// Si la versión no coincide, crea un fichero nuevo con valores por defecto
|
||||
if (CONFIG_VERSION != version) {
|
||||
if (console) {
|
||||
std::cout << "Config version mismatch (expected: " << CONFIG_VERSION << ", got: " << version << "), creating new config\n";
|
||||
}
|
||||
init();
|
||||
saveToFile();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Carga las diferentes secciones de configuración usando funciones helper
|
||||
loadWindowConfigFromYaml(yaml);
|
||||
loadVideoConfigFromYaml(yaml);
|
||||
loadKeyboardControlsFromYaml(yaml);
|
||||
loadGamepadControlsFromYaml(yaml);
|
||||
|
||||
if (console) {
|
||||
std::cout << "Config file loaded successfully\n\n";
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (const fkyaml::exception& e) {
|
||||
if (console) {
|
||||
std::cerr << "Error parsing YAML config: " << e.what() << '\n';
|
||||
std::cerr << "Creating new config with defaults\n";
|
||||
}
|
||||
init();
|
||||
saveToFile();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Guarda las opciones al fichero configurado
|
||||
auto saveToFile() -> bool {
|
||||
// Abre el fichero para escritura
|
||||
std::ofstream file(config_file_path);
|
||||
if (!file.is_open()) {
|
||||
if (console) {
|
||||
std::cerr << "Error: Unable to open file " << config_file_path << " for writing\n";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (console) {
|
||||
std::cout << "Writing config file: " << config_file_path << '\n';
|
||||
}
|
||||
|
||||
// Escribe el fichero manualmente para controlar el orden y los comentarios
|
||||
file << "# JailDoctor's Dilemma - Configuration File\n";
|
||||
file << "# \n";
|
||||
file << "# This file is automatically generated and managed by the game.\n";
|
||||
file << "# Manual edits are preserved if valid.\n";
|
||||
file << "\n";
|
||||
|
||||
// VERSION
|
||||
file << "# VERSION \n";
|
||||
file << "version: \"" << Project::VERSION << "\"\n";
|
||||
file << "\n";
|
||||
|
||||
// WINDOW
|
||||
file << "# WINDOW\n";
|
||||
file << "window:\n";
|
||||
file << " zoom: " << window.zoom << "\n";
|
||||
file << "\n";
|
||||
|
||||
// VIDEO
|
||||
file << "# VIDEO \n";
|
||||
file << "video:\n";
|
||||
file << " fullscreen: " << (video.fullscreen ? "true" : "false") << "\n";
|
||||
file << " filter: " << filterToString(video.filter) << " # filter: nearest (pixel perfect) | linear (smooth)\n";
|
||||
file << " shaders: " << (video.shaders ? "true" : "false") << "\n";
|
||||
file << " vertical_sync: " << (video.vertical_sync ? "true" : "false") << "\n";
|
||||
file << " integer_scale: " << (video.integer_scale ? "true" : "false") << "\n";
|
||||
file << " keep_aspect: " << (video.keep_aspect ? "true" : "false") << "\n";
|
||||
file << " palette: " << video.palette << "\n";
|
||||
file << " border:\n";
|
||||
file << " enabled: " << (video.border.enabled ? "true" : "false") << "\n";
|
||||
file << " width: " << video.border.width << "\n";
|
||||
file << " height: " << video.border.height << "\n";
|
||||
file << "\n";
|
||||
|
||||
// KEYBOARD CONTROLS
|
||||
file << "# KEYBOARD CONTROLS\n";
|
||||
file << "keyboard_controls:\n";
|
||||
file << " key_left: " << scancodeToString(keyboard_controls.key_left) << "\n";
|
||||
file << " key_right: " << scancodeToString(keyboard_controls.key_right) << "\n";
|
||||
file << " key_jump: " << scancodeToString(keyboard_controls.key_jump) << "\n";
|
||||
file << "\n";
|
||||
|
||||
// GAMEPAD CONTROLS
|
||||
file << "# GAMEPAD CONTROLS\n";
|
||||
file << "gamepad_controls:\n";
|
||||
file << " button_left: " << gamepadButtonToString(gamepad_controls.button_left) << "\n";
|
||||
file << " button_right: " << gamepadButtonToString(gamepad_controls.button_right) << "\n";
|
||||
file << " button_jump: " << gamepadButtonToString(gamepad_controls.button_jump) << "\n";
|
||||
|
||||
file.close();
|
||||
|
||||
if (console) {
|
||||
std::cout << "Config file saved successfully\n\n";
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Options
|
||||
123
source/game/options.hpp
Normal file
123
source/game/options.hpp
Normal file
@@ -0,0 +1,123 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <string> // Para string, basic_string
|
||||
#include <utility>
|
||||
|
||||
#include "core/rendering/screen.hpp" // Para Screen::Filter
|
||||
#include "game/defaults.hpp"
|
||||
#include "project.h" // Para Project::NAME, VERSION, COPYRIGHT
|
||||
#include "utils/utils.hpp" // Para Color, Palette
|
||||
|
||||
// --- Namespace Options: gestión de configuración y opciones del juego ---
|
||||
namespace Options {
|
||||
|
||||
// Estructura para las opciones de control de teclado
|
||||
struct KeyboardControls {
|
||||
SDL_Scancode key_left{Defaults::Controls::KEY_LEFT}; // Tecla para mover a la izquierda
|
||||
SDL_Scancode key_right{Defaults::Controls::KEY_RIGHT}; // Tecla para mover a la derecha
|
||||
SDL_Scancode key_jump{Defaults::Controls::KEY_JUMP}; // Tecla para saltar
|
||||
};
|
||||
|
||||
// Estructura para las opciones de control del gamepad/joystick
|
||||
struct GamepadControls {
|
||||
int button_left{Defaults::Controls::GAMEPAD_BUTTON_LEFT}; // Botón para mover a la izquierda (por defecto: DPAD_LEFT)
|
||||
int button_right{Defaults::Controls::GAMEPAD_BUTTON_RIGHT}; // Botón para mover a la derecha (por defecto: DPAD_RIGHT)
|
||||
int button_jump{Defaults::Controls::GAMEPAD_BUTTON_JUMP}; // Botón para saltar (por defecto: WEST/X button)
|
||||
};
|
||||
|
||||
// Estructura para albergar trucos
|
||||
struct Cheat {
|
||||
enum class State : bool {
|
||||
DISABLED = false,
|
||||
ENABLED = true
|
||||
};
|
||||
|
||||
State infinite_lives{Defaults::Cheat::INFINITE_LIVES ? State::ENABLED : State::DISABLED}; // Indica si el jugador dispone de vidas infinitas
|
||||
State invincible{Defaults::Cheat::INVINCIBLE ? State::ENABLED : State::DISABLED}; // Indica si el jugador puede morir
|
||||
State jail_is_open{Defaults::Cheat::JAIL_IS_OPEN ? State::ENABLED : State::DISABLED}; // Indica si la Jail está abierta
|
||||
State alternate_skin{Defaults::Cheat::ALTERNATE_SKIN ? State::ENABLED : State::DISABLED}; // Indica si se usa una skin diferente para el jugador
|
||||
|
||||
// Método para comprobar si alguno de los tres primeros trucos está activo
|
||||
[[nodiscard]] auto enabled() const -> bool {
|
||||
return infinite_lives == State::ENABLED || invincible == State::ENABLED || jail_is_open == State::ENABLED;
|
||||
}
|
||||
};
|
||||
|
||||
// Estructura con opciones de la ventana
|
||||
struct Window {
|
||||
std::string caption{std::format("{} v{} ({})", Project::LONG_NAME, Project::VERSION, Project::COPYRIGHT)}; // Texto que aparece en la barra de título de la ventana
|
||||
int zoom{Defaults::Window::ZOOM}; // Zoom de la ventana
|
||||
int max_zoom{Defaults::Window::ZOOM}; // Máximo tamaño de zoom para la ventana
|
||||
};
|
||||
|
||||
// Estructura para gestionar el borde de la pantalla
|
||||
struct Border {
|
||||
bool enabled{Defaults::Border::ENABLED}; // Indica si se ha de mostrar el borde
|
||||
float width{Defaults::Border::WIDTH}; // Ancho del borde
|
||||
float height{Defaults::Border::HEIGHT}; // Alto del borde
|
||||
};
|
||||
|
||||
// Estructura para las opciones de video
|
||||
struct Video {
|
||||
bool fullscreen{Defaults::Video::FULLSCREEN}; // Contiene el valor del modo de pantalla completa
|
||||
Screen::Filter filter{Defaults::Video::FILTER}; // Filtro usado para el escalado de la imagen
|
||||
bool vertical_sync{Defaults::Video::VERTICAL_SYNC}; // Indica si se quiere usar vsync o no
|
||||
bool shaders{Defaults::Video::SHADERS}; // Indica si se van a usar shaders o no
|
||||
bool integer_scale{Defaults::Video::INTEGER_SCALE}; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa
|
||||
bool keep_aspect{Defaults::Video::KEEP_ASPECT}; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa
|
||||
Border border{}; // Borde de la pantalla
|
||||
std::string palette{Defaults::Video::PALETTE_NAME}; // Paleta de colores a usar en el juego
|
||||
std::string info; // Información sobre el modo de vídeo
|
||||
};
|
||||
|
||||
// Estructura para las opciones de musica
|
||||
struct Music {
|
||||
bool enabled{Defaults::Music::ENABLED}; // Indica si la música suena o no
|
||||
float volume{Defaults::Music::VOLUME}; // Volumen al que suena la música
|
||||
};
|
||||
|
||||
// Estructura para las opciones de sonido
|
||||
struct Sound {
|
||||
bool enabled{Defaults::Sound::ENABLED}; // Indica si los sonidos suenan o no
|
||||
float volume{Defaults::Sound::VOLUME}; // Volumen al que suenan los sonidos (0 a 128 internamente)
|
||||
};
|
||||
|
||||
// Estructura para las opciones de audio
|
||||
struct Audio {
|
||||
Music music{}; // Opciones para la música
|
||||
Sound sound{}; // Opciones para los efectos de sonido
|
||||
bool enabled{Defaults::Audio::ENABLED}; // Indica si el audio está activo o no
|
||||
float volume{Defaults::Audio::VOLUME}; // Volumen al que suenan el audio (0-128 internamente)
|
||||
};
|
||||
|
||||
// Estructura para las opciones de juego
|
||||
struct Game {
|
||||
float width{Defaults::Canvas::WIDTH}; // Ancho de la resolucion del juego
|
||||
float height{Defaults::Canvas::HEIGHT}; // Alto de la resolucion del juego
|
||||
};
|
||||
|
||||
// --- Variables globales ---
|
||||
inline std::string version{}; // Versión del fichero de configuración. Sirve para saber si las opciones son compatibles
|
||||
inline bool console{false}; // Indica si ha de mostrar información por la consola de texto
|
||||
inline Cheat cheats{}; // Contiene trucos y ventajas para el juego
|
||||
inline Game game{}; // Opciones de juego
|
||||
inline Video video{}; // Opciones de video
|
||||
inline Window window{}; // Opciones relativas a la ventana
|
||||
inline Audio audio{}; // Opciones relativas al audio
|
||||
inline KeyboardControls keyboard_controls{}; // Teclas usadas para jugar
|
||||
inline GamepadControls gamepad_controls{}; // Botones del gamepad usados para jugar
|
||||
|
||||
// Ruta completa del fichero de configuración (establecida mediante setConfigFile)
|
||||
inline std::string config_file_path{};
|
||||
|
||||
// --- Funciones públicas ---
|
||||
void init(); // Crea e inicializa las opciones del programa
|
||||
void setConfigFile(const std::string& path); // Establece la ruta del fichero de configuración
|
||||
auto loadFromFile() -> bool; // Carga las opciones desde el fichero configurado
|
||||
auto saveToFile() -> bool; // Guarda las opciones al fichero configurado
|
||||
|
||||
} // namespace Options
|
||||
34
source/game/scene_manager.hpp
Normal file
34
source/game/scene_manager.hpp
Normal file
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
Namespace SceneManager: gestiona el flujo entre las diferentes escenas del juego.
|
||||
|
||||
Define las escenas principales del programa y las opciones de transición entre ellas.
|
||||
Proporciona variables globales inline para gestionar el estado actual de la escena.
|
||||
*/
|
||||
|
||||
namespace SceneManager {
|
||||
|
||||
// --- Escenas del programa ---
|
||||
enum class Scene {
|
||||
LOGO, // Pantalla del logo
|
||||
TITLE, // Pantalla de título/menú principal
|
||||
GAME, // Juego principal
|
||||
QUIT // Salir del programa
|
||||
};
|
||||
|
||||
// --- Opciones para transiciones entre escenas ---
|
||||
enum class Options {
|
||||
NONE, // Sin opciones especiales
|
||||
};
|
||||
|
||||
// --- Variables de estado globales ---
|
||||
#ifdef _DEBUG
|
||||
inline Scene current = Scene::GAME; // Escena actual
|
||||
inline Options options = Options::NONE; // Opciones de la escena actual
|
||||
#else
|
||||
inline Scene current = Scene::LOGO; // Escena actual
|
||||
inline Options options = Options::NONE; // Opciones de la escena actual
|
||||
#endif
|
||||
|
||||
} // namespace SceneManager
|
||||
778
source/game/scenes/game.cpp
Normal file
778
source/game/scenes/game.cpp
Normal file
@@ -0,0 +1,778 @@
|
||||
#include "game/scenes/game.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <cmath> // Para std::sqrt, std::min
|
||||
#include <utility>
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "core/input/global_inputs.hpp" // Para check
|
||||
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/rendering/text.hpp" // Para Text, Text::CENTER_FLAG, Text::COLOR_FLAG
|
||||
#include "core/resources/resource_cache.hpp" // Para ResourceRoom, Resource
|
||||
#include "core/resources/resource_list.hpp" // Para Asset
|
||||
#include "core/system/global_events.hpp" // Para check
|
||||
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
||||
#include "game/gameplay/room.hpp" // Para Room, RoomData
|
||||
#include "game/gameplay/room_tracker.hpp" // Para RoomTracker
|
||||
#include "game/gameplay/scoreboard.hpp" // Para Scoreboard::Data, Scoreboard
|
||||
#include "game/defaults.hpp" // Para Defaults::Music
|
||||
#include "game/options.hpp" // Para Options, options, Cheat, SectionState
|
||||
#include "game/scene_manager.hpp" // Para SceneManager
|
||||
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText, CHEEVO_NO...
|
||||
#include "utils/defines.hpp" // Para Tile::SIZE, PlayArea::HEIGHT, RoomBorder::BOTTOM
|
||||
#include "utils/color.hpp" // Para Color
|
||||
#include "utils/utils.hpp" // Para stringToColor
|
||||
|
||||
#ifdef _DEBUG
|
||||
#include "core/system/debug.hpp" // Para Debug
|
||||
#endif
|
||||
|
||||
// Constructor
|
||||
Game::Game(Mode mode)
|
||||
: scoreboard_data_(std::make_shared<Scoreboard::Data>(0, 9, 0, true, 0, SDL_GetTicks(), Options::cheats.jail_is_open == Options::Cheat::State::ENABLED)),
|
||||
scoreboard_(std::make_shared<Scoreboard>(scoreboard_data_)),
|
||||
room_tracker_(std::make_shared<RoomTracker>()),
|
||||
mode_(mode),
|
||||
#ifdef _DEBUG
|
||||
current_room_("03.yaml"),
|
||||
spawn_data_(Player::SpawnData(25 * Tile::SIZE, 21 * Tile::SIZE, 0, 0, 0, Player::State::ON_GROUND, Flip::LEFT))
|
||||
#else
|
||||
current_room_("03.yaml"),
|
||||
spawn_data_(Player::SpawnData(25 * Tile::SIZE, 13 * Tile::SIZE, 0, 0, 0, Player::State::ON_GROUND, Flip::LEFT))
|
||||
#endif
|
||||
{
|
||||
// Crea objetos e inicializa variables
|
||||
ItemTracker::init();
|
||||
demoInit();
|
||||
room_ = std::make_shared<Room>(current_room_, scoreboard_data_);
|
||||
initPlayer(spawn_data_, room_);
|
||||
total_items_ = getTotalItems();
|
||||
|
||||
createRoomNameTexture();
|
||||
game_backbuffer_surface_ = std::make_shared<Surface>(Options::game.width, Options::game.height);
|
||||
changeRoom(current_room_);
|
||||
|
||||
SceneManager::current = SceneManager::Scene::GAME;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
}
|
||||
|
||||
Game::~Game() {
|
||||
ItemTracker::destroy();
|
||||
}
|
||||
|
||||
// Comprueba los eventos de la cola
|
||||
void Game::handleEvents() {
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
GlobalEvents::handle(event);
|
||||
#ifdef _DEBUG
|
||||
handleDebugEvents(event);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el teclado
|
||||
void Game::handleInput() {
|
||||
Input::get()->update();
|
||||
|
||||
// Inputs globales siempre funcionan
|
||||
if (Input::get()->checkAction(InputAction::TOGGLE_MUSIC, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
scoreboard_data_->music = !scoreboard_data_->music;
|
||||
scoreboard_data_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
||||
Notifier::get()->show({"MUSIC " + std::string(scoreboard_data_->music ? "ENABLED" : "DISABLED")});
|
||||
}
|
||||
|
||||
// Durante fade/postfade, solo procesar inputs globales
|
||||
if (state_ != State::PLAYING) {
|
||||
GlobalInputs::handle();
|
||||
return;
|
||||
}
|
||||
|
||||
// Input de pausa solo en estado PLAYING
|
||||
if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
togglePause();
|
||||
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")});
|
||||
}
|
||||
|
||||
GlobalInputs::handle();
|
||||
}
|
||||
|
||||
// Bucle para el juego
|
||||
void Game::run() {
|
||||
keepMusicPlaying();
|
||||
if (!scoreboard_data_->music && mode_ == Mode::GAME) {
|
||||
Audio::get()->pauseMusic();
|
||||
}
|
||||
|
||||
while (SceneManager::current == SceneManager::Scene::GAME) {
|
||||
update();
|
||||
render();
|
||||
}
|
||||
|
||||
if (mode_ == Mode::GAME) {
|
||||
Audio::get()->stopMusic();
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el juego, las variables, comprueba la entrada, etc.
|
||||
void Game::update() {
|
||||
const float DELTA_TIME = delta_timer_.tick();
|
||||
|
||||
handleEvents(); // Comprueba los eventos
|
||||
handleInput(); // Comprueba las entradas
|
||||
|
||||
#ifdef _DEBUG
|
||||
Debug::get()->clear();
|
||||
#endif
|
||||
|
||||
// Dispatch por estado
|
||||
switch (state_) {
|
||||
case State::PLAYING:
|
||||
updatePlaying(DELTA_TIME);
|
||||
break;
|
||||
case State::BLACK_SCREEN:
|
||||
updateBlackScreen(DELTA_TIME);
|
||||
break;
|
||||
case State::GAME_OVER:
|
||||
updateGameOver(DELTA_TIME);
|
||||
break;
|
||||
case State::FADE_TO_ENDING:
|
||||
updateFadeToEnding(DELTA_TIME);
|
||||
break;
|
||||
case State::POST_FADE_ENDING:
|
||||
updatePostFadeEnding(DELTA_TIME);
|
||||
break;
|
||||
}
|
||||
|
||||
Audio::update(); // Actualiza el objeto Audio
|
||||
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||
|
||||
#ifdef _DEBUG
|
||||
updateDebugInfo();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Actualiza el juego en estado PLAYING
|
||||
void Game::updatePlaying(float delta_time) {
|
||||
// Actualiza los objetos
|
||||
room_->update(delta_time);
|
||||
switch (mode_) {
|
||||
case Mode::GAME:
|
||||
#ifdef _DEBUG
|
||||
// Maneja el arrastre del jugador con el ratón (debug)
|
||||
handleDebugMouseDrag(delta_time);
|
||||
|
||||
// Si estamos arrastrando, no ejecutar la física normal del jugador
|
||||
if (!debug_dragging_player_) {
|
||||
player_->update(delta_time);
|
||||
}
|
||||
#else
|
||||
player_->update(delta_time);
|
||||
#endif
|
||||
checkPlayerIsOnBorder();
|
||||
checkPlayerAndItems();
|
||||
checkPlayerAndEnemies();
|
||||
checkIfPlayerIsAlive();
|
||||
checkEndGame();
|
||||
checkRestoringJail(delta_time);
|
||||
break;
|
||||
|
||||
case Mode::DEMO:
|
||||
demoCheckRoomChange(delta_time);
|
||||
break;
|
||||
}
|
||||
scoreboard_->update(delta_time);
|
||||
keepMusicPlaying();
|
||||
}
|
||||
|
||||
// Actualiza el juego en estado BLACK_SCREEN
|
||||
void Game::updateBlackScreen(float delta_time) {
|
||||
state_time_ += delta_time;
|
||||
|
||||
// Si se acabaron las vidas Y pasó el threshold → GAME_OVER
|
||||
if (scoreboard_data_->lives < 0 && state_time_ > GAME_OVER_THRESHOLD) {
|
||||
transitionToState(State::GAME_OVER);
|
||||
return;
|
||||
}
|
||||
|
||||
// Si pasó la duración completa → volver a PLAYING
|
||||
if (state_time_ > BLACK_SCREEN_DURATION) {
|
||||
// Despausar al salir
|
||||
player_->setPaused(false);
|
||||
room_->setPaused(false);
|
||||
Screen::get()->setBorderColor(room_->getBorderColor());
|
||||
transitionToState(State::PLAYING);
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el juego en estado GAME_OVER
|
||||
void Game::updateGameOver(float delta_time) {
|
||||
// Pequeño delay antes de cambiar escena
|
||||
state_time_ += delta_time;
|
||||
if (state_time_ > 0.1F) { // 100ms de delay mínimo
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el juego en estado FADE_TO_ENDING
|
||||
void Game::updateFadeToEnding(float delta_time) {
|
||||
// Actualiza room, enemies, items (todo sigue funcionando)
|
||||
room_->update(delta_time);
|
||||
|
||||
// NO actualizar player (congelar movimiento)
|
||||
// player_->update(delta_time); -- COMENTADO INTENCIONALMENTE
|
||||
|
||||
// Actualiza scoreboard
|
||||
scoreboard_->update(delta_time);
|
||||
keepMusicPlaying();
|
||||
|
||||
// Aplica el fade progresivo al BACKBUFFER (no al renderer de pantalla)
|
||||
fade_accumulator_ += delta_time;
|
||||
if (fade_accumulator_ >= FADE_STEP_INTERVAL) {
|
||||
fade_accumulator_ = 0.0F;
|
||||
if (game_backbuffer_surface_->fadeSubPalette()) {
|
||||
// Fade completado, transicionar a POST_FADE
|
||||
transitionToState(State::POST_FADE_ENDING);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el juego en estado POST_FADE_ENDING
|
||||
void Game::updatePostFadeEnding(float delta_time) {
|
||||
// Pantalla negra estática, acumular tiempo
|
||||
state_time_ += delta_time;
|
||||
|
||||
// Después del delay, cambiar a la escena de ending
|
||||
if (state_time_ >= POST_FADE_DELAY) {
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia al estado especificado y resetea los timers
|
||||
void Game::transitionToState(State new_state) {
|
||||
// Lógica de ENTRADA según el nuevo estado
|
||||
if (new_state == State::BLACK_SCREEN) {
|
||||
// Respawn room y player
|
||||
room_ = std::make_shared<Room>(current_room_, scoreboard_data_);
|
||||
initPlayer(spawn_data_, room_);
|
||||
// Pausar ambos
|
||||
room_->setPaused(true);
|
||||
player_->setPaused(true);
|
||||
}
|
||||
|
||||
state_ = new_state;
|
||||
state_time_ = 0.0F;
|
||||
fade_accumulator_ = 0.0F;
|
||||
}
|
||||
|
||||
// Pinta los objetos en pantalla
|
||||
void Game::render() {
|
||||
// Dispatch por estado
|
||||
switch (state_) {
|
||||
case State::PLAYING:
|
||||
renderPlaying();
|
||||
break;
|
||||
case State::BLACK_SCREEN:
|
||||
renderBlackScreen();
|
||||
break;
|
||||
case State::GAME_OVER:
|
||||
renderGameOver();
|
||||
break;
|
||||
case State::FADE_TO_ENDING:
|
||||
renderFadeToEnding();
|
||||
break;
|
||||
case State::POST_FADE_ENDING:
|
||||
renderPostFadeEnding();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza el juego en estado PLAYING (directo a pantalla)
|
||||
void Game::renderPlaying() {
|
||||
// Prepara para dibujar el frame
|
||||
Screen::get()->start();
|
||||
|
||||
// Dibuja los elementos del juego en orden
|
||||
room_->renderMap();
|
||||
room_->renderEnemies();
|
||||
room_->renderItems();
|
||||
if (mode_ == Mode::GAME) {
|
||||
player_->render();
|
||||
}
|
||||
renderRoomName();
|
||||
#ifdef _DEBUG
|
||||
if (!Debug::get()->isEnabled()) {
|
||||
scoreboard_->render();
|
||||
}
|
||||
// Debug info
|
||||
renderDebugInfo();
|
||||
#else
|
||||
scoreboard_->render();
|
||||
#endif
|
||||
|
||||
// Actualiza la pantalla
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Renderiza el juego en estado BLACK_SCREEN (pantalla negra)
|
||||
void Game::renderBlackScreen() {
|
||||
Screen::get()->start();
|
||||
auto const COLOR = Color::index(Color::Cpc::BLACK);
|
||||
Screen::get()->clearSurface(COLOR);
|
||||
Screen::get()->setBorderColor(COLOR);
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Renderiza el juego en estado GAME_OVER (pantalla negra)
|
||||
void Game::renderGameOver() {
|
||||
Screen::get()->start();
|
||||
Screen::get()->clearSurface(Color::index(Color::Cpc::BLACK));
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Renderiza el juego en estado FADE_TO_ENDING (via backbuffer)
|
||||
void Game::renderFadeToEnding() {
|
||||
// 1. Guardar renderer actual
|
||||
auto previous_renderer = Screen::get()->getRendererSurface();
|
||||
|
||||
// 2. Cambiar target a backbuffer
|
||||
Screen::get()->setRendererSurface(game_backbuffer_surface_);
|
||||
|
||||
// 3. Renderizar todo a backbuffer
|
||||
game_backbuffer_surface_->clear(Color::index(Color::Cpc::BLACK));
|
||||
room_->renderMap();
|
||||
room_->renderEnemies();
|
||||
room_->renderItems();
|
||||
player_->render(); // Player congelado pero visible
|
||||
renderRoomName();
|
||||
scoreboard_->render();
|
||||
|
||||
// 4. Restaurar renderer original
|
||||
Screen::get()->setRendererSurface(previous_renderer);
|
||||
|
||||
// 5. Preparar pantalla y volcar backbuffer (fade YA aplicado en update)
|
||||
Screen::get()->start();
|
||||
game_backbuffer_surface_->render();
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Renderiza el juego en estado POST_FADE_ENDING (pantalla negra)
|
||||
void Game::renderPostFadeEnding() {
|
||||
Screen::get()->start();
|
||||
Screen::get()->clearSurface(Color::index(Color::Cpc::BLACK));
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
#ifdef _DEBUG
|
||||
// Pasa la información de debug
|
||||
void Game::updateDebugInfo() {
|
||||
// Debug::get()->add("X = " + std::to_string(static_cast<int>(player_->x_)) + ", Y = " + std::to_string(static_cast<int>(player_->y_)));
|
||||
// Debug::get()->add("VX = " + std::to_string(player_->vx_).substr(0, 4) + ", VY = " + std::to_string(player_->vy_).substr(0, 4));
|
||||
// Debug::get()->add("STATE = " + std::to_string(static_cast<int>(player_->state_)));
|
||||
}
|
||||
|
||||
// Pone la información de debug en pantalla
|
||||
void Game::renderDebugInfo() {
|
||||
if (!Debug::get()->isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto surface = Screen::get()->getRendererSurface();
|
||||
|
||||
// Borra el área del scoreboard
|
||||
SDL_FRect rect = {ScoreboardArea::X, ScoreboardArea::Y, ScoreboardArea::WIDTH, ScoreboardArea::HEIGHT};
|
||||
surface->fillRect(&rect, Color::index(Color::Cpc::BLACK));
|
||||
|
||||
// Pinta la rejilla
|
||||
/*for (int i = 0; i < PlayArea::BOTTOM; i += 8)
|
||||
{
|
||||
// Lineas horizontales
|
||||
surface->drawLine(0, i, PlayArea::RIGHT, i, static_cast<Uint8>(PaletteColor::BRIGHT_BLACK));
|
||||
}
|
||||
for (int i = 0; i < PlayArea::RIGHT; i += 8)
|
||||
{
|
||||
// Lineas verticales
|
||||
surface->drawLine(i, 0, i, PlayArea::BOTTOM - 1, static_cast<Uint8>(PaletteColor::BRIGHT_BLACK));
|
||||
}*/
|
||||
|
||||
// Pinta el texto de debug en el área del scoreboard
|
||||
Debug::get()->setPos({ScoreboardArea::X, ScoreboardArea::Y});
|
||||
Debug::get()->render();
|
||||
}
|
||||
|
||||
// Comprueba los eventos
|
||||
void Game::handleDebugEvents(const SDL_Event& event) {
|
||||
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_F12:
|
||||
Debug::get()->toggleEnabled();
|
||||
Notifier::get()->show({"DEBUG " + std::string(Debug::get()->isEnabled() ? "ENABLED" : "DISABLED")});
|
||||
room_->redrawMap(); // Redibuja el tilemap para mostrar/ocultar líneas de colisión
|
||||
Options::cheats.invincible = static_cast<Options::Cheat::State>(Debug::get()->isEnabled());
|
||||
player_->setColor();
|
||||
scoreboard_data_->music = !Debug::get()->isEnabled();
|
||||
scoreboard_data_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
||||
break;
|
||||
|
||||
case SDLK_R:
|
||||
Resource::Cache::get()->reload();
|
||||
break;
|
||||
|
||||
case SDLK_W:
|
||||
changeRoom(room_->getRoom(Room::Border::TOP));
|
||||
break;
|
||||
|
||||
case SDLK_A:
|
||||
changeRoom(room_->getRoom(Room::Border::LEFT));
|
||||
break;
|
||||
|
||||
case SDLK_S:
|
||||
changeRoom(room_->getRoom(Room::Border::BOTTOM));
|
||||
break;
|
||||
|
||||
case SDLK_D:
|
||||
changeRoom(room_->getRoom(Room::Border::RIGHT));
|
||||
break;
|
||||
|
||||
case SDLK_1:
|
||||
Options::cheats.infinite_lives = Options::cheats.infinite_lives == Options::Cheat::State::ENABLED ? Options::Cheat::State::DISABLED : Options::Cheat::State::ENABLED;
|
||||
Notifier::get()->show({std::string("INFINITE LIVES ") + (Options::cheats.infinite_lives == Options::Cheat::State::ENABLED ? "ENABLED" : "DISABLED")}, Notifier::Style::DEFAULT, -1, true);
|
||||
player_->setColor();
|
||||
break;
|
||||
|
||||
case SDLK_2:
|
||||
Options::cheats.invincible = Options::cheats.invincible == Options::Cheat::State::ENABLED ? Options::Cheat::State::DISABLED : Options::Cheat::State::ENABLED;
|
||||
Notifier::get()->show({std::string("INVINCIBLE ") + (Options::cheats.invincible == Options::Cheat::State::ENABLED ? "ENABLED" : "DISABLED")}, Notifier::Style::DEFAULT, -1, true);
|
||||
player_->setColor();
|
||||
break;
|
||||
|
||||
case SDLK_3:
|
||||
Options::cheats.jail_is_open = Options::cheats.jail_is_open == Options::Cheat::State::ENABLED ? Options::Cheat::State::DISABLED : Options::Cheat::State::ENABLED;
|
||||
Notifier::get()->show({std::string("JAIL IS OPEN ") + (Options::cheats.jail_is_open == Options::Cheat::State::ENABLED ? "ENABLED" : "DISABLED")}, Notifier::Style::DEFAULT, -1, true);
|
||||
break;
|
||||
|
||||
case SDLK_0:
|
||||
Screen::get()->toggleDebugInfo();
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Maneja el arrastre del jugador con el ratón (debug)
|
||||
void Game::handleDebugMouseDrag(float delta_time) {
|
||||
// Solo funciona si Debug está habilitado
|
||||
if (!Debug::get()->isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Obtener estado del ratón (coordenadas de ventana física)
|
||||
float mouse_x = 0.0F;
|
||||
float mouse_y = 0.0F;
|
||||
SDL_MouseButtonFlags buttons = SDL_GetMouseState(&mouse_x, &mouse_y);
|
||||
|
||||
// Convertir coordenadas de ventana a coordenadas lógicas del renderer
|
||||
float render_x = 0.0F;
|
||||
float render_y = 0.0F;
|
||||
SDL_RenderCoordinatesFromWindow(Screen::get()->getRenderer(), mouse_x, mouse_y, &render_x, &render_y);
|
||||
|
||||
// Restar el offset del borde para obtener coordenadas del área de juego
|
||||
SDL_FRect dst_rect = Screen::get()->getGameSurfaceDstRect();
|
||||
float game_x = render_x - dst_rect.x;
|
||||
float game_y = render_y - dst_rect.y;
|
||||
|
||||
// Verificar si los botones están presionados
|
||||
bool left_button_pressed = (buttons & SDL_BUTTON_LMASK) != 0;
|
||||
bool right_button_pressed = (buttons & SDL_BUTTON_RMASK) != 0;
|
||||
|
||||
// Botón derecho: teleport instantáneo a la posición del cursor
|
||||
if (right_button_pressed && !debug_dragging_player_) {
|
||||
player_->setDebugPosition(game_x, game_y);
|
||||
player_->finalizeDebugTeleport();
|
||||
} else if (left_button_pressed) {
|
||||
// Obtener posición actual del jugador
|
||||
SDL_FRect player_rect = player_->getRect();
|
||||
float player_x = player_rect.x;
|
||||
float player_y = player_rect.y;
|
||||
|
||||
// Calcular distancia al objetivo
|
||||
float dx = game_x - player_x;
|
||||
float dy = game_y - player_y;
|
||||
float distance = std::sqrt(dx * dx + dy * dy);
|
||||
|
||||
// Constantes de velocidad con ease-in (aceleración progresiva)
|
||||
constexpr float DRAG_SPEED_MIN = 30.0F; // Velocidad inicial (pixels/segundo)
|
||||
constexpr float DRAG_SPEED_MAX = 600.0F; // Velocidad máxima (pixels/segundo)
|
||||
constexpr float DRAG_ACCELERATION = 600.0F; // Aceleración (pixels/segundo²)
|
||||
|
||||
// Incrementar velocidad con el tiempo (ease-in)
|
||||
if (!debug_dragging_player_) {
|
||||
debug_drag_speed_ = DRAG_SPEED_MIN; // Iniciar con velocidad mínima
|
||||
}
|
||||
debug_drag_speed_ = std::min(DRAG_SPEED_MAX, debug_drag_speed_ + DRAG_ACCELERATION * delta_time);
|
||||
|
||||
if (distance > 1.0F) {
|
||||
// Calcular el movimiento con la velocidad actual
|
||||
float move_factor = std::min(1.0F, debug_drag_speed_ * delta_time / distance);
|
||||
float new_x = player_x + dx * move_factor;
|
||||
float new_y = player_y + dy * move_factor;
|
||||
|
||||
// Mover el jugador hacia la posición del cursor
|
||||
player_->setDebugPosition(new_x, new_y);
|
||||
}
|
||||
|
||||
debug_dragging_player_ = true;
|
||||
Debug::get()->add(std::string("X : " + std::to_string(static_cast<int>(player_rect.x))));
|
||||
Debug::get()->add(std::string("Y : " + std::to_string(static_cast<int>(player_rect.y))));
|
||||
} else if (debug_dragging_player_) {
|
||||
// Botón soltado después de arrastrar: finalizar teleport
|
||||
player_->finalizeDebugTeleport();
|
||||
debug_dragging_player_ = false;
|
||||
debug_drag_speed_ = 0.0F; // Reset para el próximo arrastre
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Escribe el nombre de la pantalla
|
||||
void Game::renderRoomName() {
|
||||
// Dibuja la textura con el nombre de la habitación
|
||||
room_name_surface_->render(nullptr, &room_name_rect_);
|
||||
}
|
||||
|
||||
// Cambia de habitación
|
||||
auto Game::changeRoom(const std::string& room_path) -> bool {
|
||||
// En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
|
||||
if (room_path == "0") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verifica que exista el fichero que se va a cargar
|
||||
if (!Resource::List::get()->get(room_path).empty()) {
|
||||
// Crea un objeto habitación nuevo a partir del fichero
|
||||
room_ = std::make_shared<Room>(room_path, scoreboard_data_);
|
||||
|
||||
// Pone el nombre de la habitación en la textura
|
||||
fillRoomNameTexture();
|
||||
|
||||
// Pone el color del marcador en función del color del borde de la habitación
|
||||
setScoreBoardColor();
|
||||
|
||||
if (room_tracker_->addRoom(room_path)) {
|
||||
// Incrementa el contador de habitaciones visitadas
|
||||
scoreboard_data_->rooms++;
|
||||
}
|
||||
|
||||
// Pasa la nueva habitación al jugador
|
||||
player_->setRoom(room_);
|
||||
|
||||
// Cambia la habitación actual
|
||||
current_room_ = room_path;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el jugador esta en el borde de la pantalla
|
||||
void Game::checkPlayerIsOnBorder() {
|
||||
if (player_->isOnBorder()) {
|
||||
const auto BORDER = player_->getBorder();
|
||||
const auto ROOM_NAME = room_->getRoom(BORDER);
|
||||
|
||||
// Si puede cambiar de habitación, cambia
|
||||
if (changeRoom(ROOM_NAME)) {
|
||||
player_->switchBorders();
|
||||
spawn_data_ = player_->getSpawnParams();
|
||||
return;
|
||||
}
|
||||
|
||||
// Si ha llegado al fondo y no hay habitación, muere
|
||||
if (BORDER == Room::Border::BOTTOM) {
|
||||
killPlayer();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las colisiones del jugador con los enemigos
|
||||
auto Game::checkPlayerAndEnemies() -> bool {
|
||||
const bool DEATH = room_->enemyCollision(player_->getCollider());
|
||||
if (DEATH) {
|
||||
killPlayer();
|
||||
}
|
||||
return DEATH;
|
||||
}
|
||||
|
||||
// Comprueba las colisiones del jugador con los objetos
|
||||
void Game::checkPlayerAndItems() {
|
||||
room_->itemCollision(player_->getCollider());
|
||||
}
|
||||
|
||||
// Comprueba si el jugador esta vivo
|
||||
void Game::checkIfPlayerIsAlive() {
|
||||
if (!player_->isAlive()) {
|
||||
killPlayer();
|
||||
}
|
||||
}
|
||||
|
||||
// Mata al jugador
|
||||
void Game::killPlayer() {
|
||||
if (Options::cheats.invincible == Options::Cheat::State::ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Resta una vida al jugador
|
||||
if (Options::cheats.infinite_lives == Options::Cheat::State::DISABLED) {
|
||||
--scoreboard_data_->lives;
|
||||
}
|
||||
|
||||
// Sonido
|
||||
Audio::get()->playSound(Defaults::Sound::HIT, Audio::Group::GAME);
|
||||
|
||||
// Transicionar al estado BLACK_SCREEN (el respawn ocurre en transitionToState)
|
||||
transitionToState(State::BLACK_SCREEN);
|
||||
}
|
||||
|
||||
// Pone el color del marcador en función del color del borde de la habitación
|
||||
void Game::setScoreBoardColor() {
|
||||
// Obtiene el color del borde
|
||||
const Uint8 BORDER_COLOR = room_->getBorderColor();
|
||||
|
||||
const bool IS_BLACK = BORDER_COLOR == Color::index(Color::Cpc::BLACK);
|
||||
|
||||
// Si el color del borde es negro cambia el texto del marcador a blanco
|
||||
scoreboard_data_->color = IS_BLACK ? Color::index(Color::Cpc::WHITE) : BORDER_COLOR;
|
||||
}
|
||||
|
||||
// Comprueba si ha finalizado el juego
|
||||
auto Game::checkEndGame() -> bool {
|
||||
const bool IS_ON_THE_ROOM = room_->getName() == "THE JAIL"; // Estar en la habitación que toca
|
||||
const bool HAVE_THE_ITEMS = scoreboard_data_->items >= int(total_items_ * 0.9F) || Options::cheats.jail_is_open == Options::Cheat::State::ENABLED; // Con mas del 90% de los items recogidos
|
||||
const bool IS_ON_THE_DOOR = player_->getRect().x <= 128; // Y en la ubicación que toca (En la puerta)
|
||||
|
||||
scoreboard_data_->jail_is_open = HAVE_THE_ITEMS;
|
||||
|
||||
if (HAVE_THE_ITEMS && IS_ON_THE_ROOM && IS_ON_THE_DOOR) {
|
||||
// Iniciar transición de fade en vez de cambio inmediato de escena
|
||||
transitionToState(State::FADE_TO_ENDING);
|
||||
Audio::get()->fadeOutMusic(Defaults::Music::FADE_DURATION_MS); // Fade out de música
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Obtiene la cantidad total de items que hay en el mapeado del juego
|
||||
auto Game::getTotalItems() -> int {
|
||||
int items = 0;
|
||||
auto rooms = Resource::Cache::get()->getRooms();
|
||||
|
||||
for (const auto& room : rooms) {
|
||||
items += room.room->items.size();
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
// Pone el juego en pausa
|
||||
void Game::togglePause() {
|
||||
paused_ = !paused_;
|
||||
|
||||
player_->setPaused(paused_);
|
||||
room_->setPaused(paused_);
|
||||
scoreboard_->setPaused(paused_);
|
||||
}
|
||||
|
||||
// Da vidas al jugador cuando está en la Jail
|
||||
void Game::checkRestoringJail(float delta_time) {
|
||||
if (room_->getName() != "THE JAIL" || scoreboard_data_->lives == 9) {
|
||||
jail_restore_time_ = 0.0F; // Reset timer cuando no está en la Jail
|
||||
return;
|
||||
}
|
||||
|
||||
if (!paused_) {
|
||||
jail_restore_time_ += delta_time;
|
||||
}
|
||||
|
||||
// Incrementa el numero de vidas
|
||||
if (jail_restore_time_ >= JAIL_RESTORE_INTERVAL) {
|
||||
jail_restore_time_ -= JAIL_RESTORE_INTERVAL; // Mantiene el excedente para precisión
|
||||
scoreboard_data_->lives++;
|
||||
Audio::get()->playSound(Defaults::Sound::HIT, Audio::Group::GAME);
|
||||
}
|
||||
}
|
||||
|
||||
// Crea la textura con el nombre de la habitación
|
||||
void Game::fillRoomNameTexture() {
|
||||
// Pone la textura como destino de renderizado
|
||||
auto previuos_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(room_name_surface_);
|
||||
|
||||
// Rellena la textura de color
|
||||
room_name_surface_->clear(stringToColor("white"));
|
||||
|
||||
// Escribe el texto en la textura
|
||||
auto text = Resource::Cache::get()->getText("smb2");
|
||||
text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, text->getCharacterSize() / 2, room_->getName(), 1, room_->getBGColor());
|
||||
|
||||
// Deja el renderizador por defecto
|
||||
Screen::get()->setRendererSurface(previuos_renderer);
|
||||
}
|
||||
|
||||
// Inicializa al jugador
|
||||
void Game::initPlayer(const Player::SpawnData& spawn_point, std::shared_ptr<Room> room) {
|
||||
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.yaml" : "player.yaml";
|
||||
const Player::Data PLAYER{.spawn_data = spawn_point, .animations_path = player_animations, .room = std::move(room)};
|
||||
player_ = std::make_shared<Player>(PLAYER);
|
||||
}
|
||||
|
||||
// Crea la textura para poner el nombre de la habitación
|
||||
void Game::createRoomNameTexture() {
|
||||
auto text = Resource::Cache::get()->getText("smb2");
|
||||
room_name_surface_ = std::make_shared<Surface>(Options::game.width, text->getCharacterSize() * 2);
|
||||
|
||||
// Establece el destino de la textura
|
||||
room_name_rect_ = {.x = 0.0F, .y = PlayArea::HEIGHT, .w = Options::game.width, .h = text->getCharacterSize() * 2.0F};
|
||||
}
|
||||
|
||||
// Hace sonar la música
|
||||
void Game::keepMusicPlaying() {
|
||||
const std::string MUSIC_PATH = mode_ == Mode::GAME ? Defaults::Music::GAME_TRACK : Defaults::Music::TITLE_TRACK;
|
||||
|
||||
// Si la música no está sonando
|
||||
if (Audio::get()->getMusicState() == Audio::MusicState::STOPPED) {
|
||||
Audio::get()->playMusic(MUSIC_PATH);
|
||||
}
|
||||
}
|
||||
|
||||
// DEMO MODE: Inicializa las variables para el modo demo
|
||||
void Game::demoInit() {
|
||||
if (mode_ == Mode::DEMO) {
|
||||
demo_ = DemoData(0.0F, 0, {"04.yaml", "54.yaml", "20.yaml", "09.yaml", "05.yaml", "11.yaml", "31.yaml", "44.yaml"});
|
||||
current_room_ = demo_.rooms.front();
|
||||
}
|
||||
}
|
||||
|
||||
// DEMO MODE: Comprueba si se ha de cambiar de habitación
|
||||
void Game::demoCheckRoomChange(float delta_time) {
|
||||
if (mode_ == Mode::DEMO) {
|
||||
demo_.time_accumulator += delta_time;
|
||||
if (demo_.time_accumulator >= DEMO_ROOM_DURATION) {
|
||||
demo_.time_accumulator = 0.0F;
|
||||
demo_.room_index++;
|
||||
if (demo_.room_index == (int)demo_.rooms.size()) {
|
||||
SceneManager::current = SceneManager::Scene::LOGO;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
} else {
|
||||
changeRoom(demo_.rooms[demo_.room_index]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
132
source/game/scenes/game.hpp
Normal file
132
source/game/scenes/game.hpp
Normal file
@@ -0,0 +1,132 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <initializer_list> // Para initializer_list
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "game/entities/player.hpp" // Para PlayerSpawn
|
||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||
class Room; // lines 12-12
|
||||
class RoomTracker; // lines 13-13
|
||||
class Scoreboard; // lines 14-14
|
||||
class Surface;
|
||||
|
||||
class Game {
|
||||
public:
|
||||
// --- Estructuras ---
|
||||
enum class Mode {
|
||||
DEMO,
|
||||
GAME
|
||||
};
|
||||
|
||||
enum class State {
|
||||
PLAYING, // Normal gameplay
|
||||
BLACK_SCREEN, // Black screen after death (0.30s)
|
||||
GAME_OVER, // Intermediate state before changing scene
|
||||
FADE_TO_ENDING, // Fade out transition
|
||||
POST_FADE_ENDING, // Black screen delay before ending
|
||||
};
|
||||
|
||||
// --- Constructor y Destructor ---
|
||||
explicit Game(Mode mode);
|
||||
~Game();
|
||||
|
||||
// --- Bucle para el juego ---
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Constantes de tiempo ---
|
||||
static constexpr float BLACK_SCREEN_DURATION = 0.30F; // Duración de la pantalla negra en segundos (20 frames a 66.67fps)
|
||||
static constexpr float GAME_OVER_THRESHOLD = 0.255F; // Tiempo antes del game over en segundos (17 frames a 66.67fps)
|
||||
static constexpr float DEMO_ROOM_DURATION = 6.0F; // Duración de cada habitación en modo demo en segundos (400 frames)
|
||||
static constexpr float JAIL_RESTORE_INTERVAL = 1.5F; // Intervalo de restauración de vidas en la Jail en segundos (100 frames)
|
||||
static constexpr float FADE_STEP_INTERVAL = 0.05F; // Intervalo entre pasos de fade en segundos
|
||||
static constexpr float POST_FADE_DELAY = 2.0F; // Duración de la pantalla negra después del fade
|
||||
|
||||
// --- Estructuras ---
|
||||
struct DemoData {
|
||||
float time_accumulator{0.0F}; // Acumulador de tiempo para el modo demo
|
||||
int room_index{0}; // Índice para el vector de habitaciones
|
||||
std::vector<std::string> rooms; // Listado con los mapas de la demo
|
||||
};
|
||||
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
|
||||
void render(); // Pinta los objetos en pantalla
|
||||
void handleEvents(); // Comprueba los eventos de la cola
|
||||
void renderRoomName(); // Escribe el nombre de la pantalla
|
||||
void transitionToState(State new_state); // Cambia al estado especificado y resetea los timers
|
||||
void updatePlaying(float delta_time); // Actualiza el juego en estado PLAYING
|
||||
void updateBlackScreen(float delta_time); // Actualiza el juego en estado BLACK_SCREEN
|
||||
void updateGameOver(float delta_time); // Actualiza el juego en estado GAME_OVER
|
||||
void updateFadeToEnding(float delta_time); // Actualiza el juego en estado FADE_TO_ENDING
|
||||
void updatePostFadeEnding(float delta_time); // Actualiza el juego en estado POST_FADE_ENDING
|
||||
void renderPlaying(); // Renderiza el juego en estado PLAYING (directo a pantalla)
|
||||
void renderBlackScreen(); // Renderiza el juego en estado BLACK_SCREEN (pantalla negra)
|
||||
void renderGameOver(); // Renderiza el juego en estado GAME_OVER (pantalla negra)
|
||||
void renderFadeToEnding(); // Renderiza el juego en estado FADE_TO_ENDING (via backbuffer)
|
||||
void renderPostFadeEnding(); // Renderiza el juego en estado POST_FADE_ENDING (pantalla negra)
|
||||
auto changeRoom(const std::string& room_path) -> bool; // Cambia de habitación
|
||||
void handleInput(); // Comprueba el teclado
|
||||
void checkPlayerIsOnBorder(); // Comprueba si el jugador esta en el borde de la pantalla y actua
|
||||
auto checkPlayerAndEnemies() -> bool; // Comprueba las colisiones del jugador con los enemigos
|
||||
void checkPlayerAndItems(); // Comprueba las colisiones del jugador con los objetos
|
||||
void checkIfPlayerIsAlive(); // Comprueba si el jugador esta vivo
|
||||
void killPlayer(); // Mata al jugador
|
||||
void setScoreBoardColor(); // Pone el color del marcador en función del color del borde de la habitación
|
||||
auto checkEndGame() -> bool; // Comprueba si ha finalizado el juego
|
||||
static auto getTotalItems() -> int; // Obtiene la cantidad total de items que hay en el mapeado del juego
|
||||
void togglePause(); // Pone el juego en pausa
|
||||
void checkRestoringJail(float delta_time); // Da vidas al jugador cuando está en la Jail
|
||||
void fillRoomNameTexture(); // Pone el nombre de la habitación en la textura
|
||||
void checkSomeCheevos(); // Comprueba algunos logros
|
||||
void checkEndGameCheevos(); // Comprueba los logros de completar el juego
|
||||
void initPlayer(const Player::SpawnData& spawn_point, std::shared_ptr<Room> room); // Inicializa al jugador
|
||||
void createRoomNameTexture(); // Crea la textura para poner el nombre de la habitación
|
||||
void keepMusicPlaying(); // Hace sonar la música
|
||||
void demoInit(); // DEMO MODE: Inicializa las variables para el modo demo
|
||||
void demoCheckRoomChange(float delta_time); // DEMO MODE: Comprueba si se ha de cambiar de habitación
|
||||
#ifdef _DEBUG
|
||||
void updateDebugInfo(); // Pone la información de debug en pantalla
|
||||
static void renderDebugInfo(); // Pone la información de debug en pantalla
|
||||
void handleDebugEvents(const SDL_Event& event); // Comprueba los eventos
|
||||
void handleDebugMouseDrag(float delta_time); // Maneja el arrastre del jugador con el ratón (debug)
|
||||
#endif
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<Scoreboard::Data> scoreboard_data_; // Estructura con los datos del marcador
|
||||
std::shared_ptr<Scoreboard> scoreboard_; // Objeto encargado de gestionar el marcador
|
||||
std::shared_ptr<RoomTracker> room_tracker_; // Lleva el control de las habitaciones visitadas
|
||||
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
|
||||
std::shared_ptr<Player> player_; // Objeto con el jugador
|
||||
std::shared_ptr<Surface> room_name_surface_; // Textura para escribir el nombre de la habitación
|
||||
std::shared_ptr<Surface> game_backbuffer_surface_; // Backbuffer para efectos de fade
|
||||
|
||||
// Variables de estado del juego
|
||||
Mode mode_; // Modo del juego
|
||||
State state_{State::PLAYING}; // Estado actual de la escena
|
||||
DeltaTimer delta_timer_; // Timer para calcular delta time
|
||||
std::string current_room_; // Fichero de la habitación actual
|
||||
Player::SpawnData spawn_data_; // Lugar de la habitación donde aparece el jugador
|
||||
int total_items_; // Cantidad total de items que hay en el mapeado del juego
|
||||
bool paused_{false}; // Indica si el juego se encuentra en pausa
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
float fade_accumulator_{0.0F}; // Acumulador de tiempo para el fade
|
||||
|
||||
// Variables de demo mode
|
||||
DemoData demo_; // Variables para el modo demo
|
||||
|
||||
// Variables de efectos visuales
|
||||
SDL_FRect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación
|
||||
float jail_restore_time_{0.0F}; // Tiempo acumulado para restauración de vidas en la Jail
|
||||
|
||||
#ifdef _DEBUG
|
||||
// Variables de debug para arrastre con ratón
|
||||
bool debug_dragging_player_{false}; // Indica si estamos arrastrando al jugador con el ratón
|
||||
float debug_drag_speed_{0.0F}; // Velocidad actual del arrastre (ease-in)
|
||||
#endif
|
||||
};
|
||||
296
source/game/scenes/logo.cpp
Normal file
296
source/game/scenes/logo.cpp
Normal file
@@ -0,0 +1,296 @@
|
||||
#include "game/scenes/logo.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // Para std::clamp
|
||||
#include <array> // Para std::array
|
||||
#include <random> // Para generador aleatorio
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "core/input/global_inputs.hpp" // Para check
|
||||
#include "core/input/input.hpp" // Para Input
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "core/system/global_events.hpp" // Para check
|
||||
#include "game/options.hpp" // Para Options, SectionState, options, Section
|
||||
#include "game/scene_manager.hpp" // Para SceneManager
|
||||
#include "utils/defines.hpp" // Para GameCanvas
|
||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||
#include "utils/easing_functions.hpp" // Para funciones de suavizado
|
||||
#include "utils/color.hpp" // Para Color
|
||||
|
||||
// Constructor
|
||||
Logo::Logo()
|
||||
: jailgames_surface_(Resource::Cache::get()->getSurface("jailgames.gif")),
|
||||
since_1998_surface_(Resource::Cache::get()->getSurface("since_1998.gif")),
|
||||
delta_timer_(std::make_unique<DeltaTimer>()) {
|
||||
// Calcula posiciones dinámicas basadas en el tamaño del canvas y las texturas
|
||||
jailgames_dest_x_ = GameCanvas::CENTER_X - (jailgames_surface_->getWidth() / 2);
|
||||
base_y_ = GameCanvas::CENTER_Y - (jailgames_surface_->getHeight() / 2);
|
||||
|
||||
// Crea el sprite "Since 1998" centrado horizontalmente, debajo del logo JAILGAMES
|
||||
const int SINCE_1998_X = GameCanvas::CENTER_X - (since_1998_surface_->getWidth() / 2);
|
||||
const int SINCE_1998_Y = base_y_ + jailgames_surface_->getHeight() + 5;
|
||||
since_1998_sprite_ = std::make_shared<SurfaceSprite>(
|
||||
since_1998_surface_,
|
||||
SINCE_1998_X,
|
||||
SINCE_1998_Y,
|
||||
since_1998_surface_->getWidth(),
|
||||
since_1998_surface_->getHeight());
|
||||
|
||||
// Configura variables
|
||||
since_1998_sprite_->setClip(0, 0, since_1998_surface_->getWidth(), since_1998_surface_->getHeight());
|
||||
since_1998_color_ = Color::index(Color::Cpc::BLACK);
|
||||
jailgames_color_ = Color::index(Color::Cpc::BRIGHT_WHITE);
|
||||
|
||||
// Inicializa variables
|
||||
SceneManager::current = SceneManager::Scene::LOGO;
|
||||
|
||||
initSprites(); // Crea los sprites de cada linea
|
||||
initColors(); // Inicializa el vector de colores
|
||||
|
||||
// Seleccionar función de easing aleatoria para la animación del logo
|
||||
// Usamos lambdas para funciones con parámetros opcionales
|
||||
static const std::array<EasingFunction, 4> EASING_OPTIONS = {
|
||||
[](float t) { return Easing::backOut(t); }, // Overshoot retro
|
||||
[](float t) { return Easing::elasticOut(t); }, // Rebote múltiple con oscilación
|
||||
Easing::bounceOut, // Rebote físico decreciente
|
||||
Easing::cubicOut // Suavizado sin overshoot (para variedad)
|
||||
};
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
std::uniform_int_distribution<size_t> dist(0, EASING_OPTIONS.size() - 1);
|
||||
easing_function_ = EASING_OPTIONS[dist(gen)];
|
||||
|
||||
// Cambia el color del borde
|
||||
Screen::get()->setBorderColor(Color::index(Color::Cpc::BLACK));
|
||||
}
|
||||
|
||||
// Comprueba el manejador de eventos
|
||||
void Logo::handleEvents() {
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
GlobalEvents::handle(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas
|
||||
void Logo::handleInput() {
|
||||
Input::get()->update();
|
||||
GlobalInputs::handle();
|
||||
}
|
||||
|
||||
// Gestiona el logo de JAILGAME
|
||||
void Logo::updateJAILGAMES(float delta_time) {
|
||||
// Solo actualizar durante el estado JAILGAMES_SLIDE_IN
|
||||
if (state_ != State::JAILGAMES_SLIDE_IN) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcular el progreso de la animación (0.0 a 1.0)
|
||||
const float PROGRESS = std::clamp(state_time_ / JAILGAMES_SLIDE_DURATION, 0.0F, 1.0F);
|
||||
|
||||
// Aplicar función de suavizado seleccionada aleatoriamente (permite overshoot para efecto de rebote)
|
||||
// La posición final exacta se garantiza en updateState() antes de transicionar
|
||||
const float EASED_PROGRESS = easing_function_(PROGRESS);
|
||||
|
||||
// Actualizar cada línea del sprite JAILGAMES interpolando con easing
|
||||
for (size_t i = 0; i < jailgames_sprite_.size(); ++i) {
|
||||
// Interpolar entre posición inicial y destino usando el progreso suavizado
|
||||
const auto INITIAL_X = static_cast<float>(jailgames_initial_x_[i]);
|
||||
const auto DEST_X = static_cast<float>(jailgames_dest_x_);
|
||||
const float NEW_X = INITIAL_X + ((DEST_X - INITIAL_X) * EASED_PROGRESS);
|
||||
|
||||
jailgames_sprite_[i]->setX(NEW_X);
|
||||
}
|
||||
}
|
||||
|
||||
// Calcula el índice de color según el progreso (0.0-1.0)
|
||||
auto Logo::getColorIndex(float progress) const -> int {
|
||||
// Asegurar que progress esté en el rango [0.0, 1.0]
|
||||
progress = std::clamp(progress, 0.0F, 1.0F);
|
||||
|
||||
// Mapear el progreso al índice de color (0-7)
|
||||
const int MAX_INDEX = static_cast<int>(color_.size()) - 1;
|
||||
const int INDEX = static_cast<int>(progress * MAX_INDEX);
|
||||
|
||||
return INDEX;
|
||||
}
|
||||
|
||||
// Gestiona el color de las texturas
|
||||
void Logo::updateTextureColors() {
|
||||
switch (state_) {
|
||||
case State::SINCE_1998_FADE_IN: {
|
||||
// Fade-in de "Since 1998" de negro a blanco
|
||||
const float PROGRESS = state_time_ / SINCE_1998_FADE_DURATION;
|
||||
since_1998_color_ = color_[getColorIndex(PROGRESS)];
|
||||
break;
|
||||
}
|
||||
|
||||
case State::DISPLAY: {
|
||||
// Asegurar que ambos logos estén en blanco durante el display
|
||||
jailgames_color_ = color_.back(); // BRIGHT_WHITE
|
||||
since_1998_color_ = color_.back(); // BRIGHT_WHITE
|
||||
break;
|
||||
}
|
||||
|
||||
case State::FADE_OUT: {
|
||||
// Fade-out de ambos logos de blanco a negro
|
||||
const float PROGRESS = 1.0F - (state_time_ / FADE_OUT_DURATION);
|
||||
const int COLOR_INDEX = getColorIndex(PROGRESS);
|
||||
jailgames_color_ = color_[COLOR_INDEX];
|
||||
since_1998_color_ = color_[COLOR_INDEX];
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// En otros estados, mantener los colores actuales
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Transiciona a un nuevo estado
|
||||
void Logo::transitionToState(State new_state) {
|
||||
state_ = new_state;
|
||||
state_time_ = 0.0F;
|
||||
}
|
||||
|
||||
// Actualiza el estado actual
|
||||
void Logo::updateState(float delta_time) {
|
||||
state_time_ += delta_time;
|
||||
|
||||
// Gestionar transiciones entre estados basándose en el tiempo
|
||||
switch (state_) {
|
||||
case State::INITIAL:
|
||||
if (state_time_ >= INITIAL_DELAY) {
|
||||
transitionToState(State::JAILGAMES_SLIDE_IN);
|
||||
}
|
||||
break;
|
||||
|
||||
case State::JAILGAMES_SLIDE_IN:
|
||||
if (state_time_ >= JAILGAMES_SLIDE_DURATION) {
|
||||
// Garantizar que todas las líneas estén exactamente en la posición final
|
||||
// antes de transicionar (previene race condition con updateJAILGAMES)
|
||||
for (auto& sprite : jailgames_sprite_) {
|
||||
sprite->setX(jailgames_dest_x_);
|
||||
}
|
||||
transitionToState(State::SINCE_1998_FADE_IN);
|
||||
}
|
||||
break;
|
||||
|
||||
case State::SINCE_1998_FADE_IN:
|
||||
if (state_time_ >= SINCE_1998_FADE_DURATION) {
|
||||
transitionToState(State::DISPLAY);
|
||||
}
|
||||
break;
|
||||
|
||||
case State::DISPLAY:
|
||||
if (state_time_ >= DISPLAY_DURATION) {
|
||||
transitionToState(State::FADE_OUT);
|
||||
}
|
||||
break;
|
||||
|
||||
case State::FADE_OUT:
|
||||
if (state_time_ >= FADE_OUT_DURATION) {
|
||||
transitionToState(State::END);
|
||||
endSection();
|
||||
}
|
||||
break;
|
||||
|
||||
case State::END:
|
||||
// Estado final, no hacer nada
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza las variables
|
||||
void Logo::update() {
|
||||
const float DELTA_TIME = delta_timer_->tick();
|
||||
|
||||
handleEvents(); // Comprueba los eventos
|
||||
handleInput(); // Comprueba las entradas
|
||||
|
||||
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
||||
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
|
||||
updateTextureColors(); // Gestiona el color de las texturas
|
||||
|
||||
Audio::update(); // Actualiza el objeto Audio
|
||||
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||
}
|
||||
|
||||
// Dibuja en pantalla
|
||||
void Logo::render() {
|
||||
// Prepara para empezar a dibujar en la textura de juego
|
||||
Screen::get()->start();
|
||||
Screen::get()->clearSurface(Color::index(Color::Cpc::BLACK));
|
||||
|
||||
// Dibuja los objetos
|
||||
for (const auto& sprite : jailgames_sprite_) {
|
||||
sprite->render(27, jailgames_color_);
|
||||
}
|
||||
since_1998_sprite_->render(27, since_1998_color_);
|
||||
|
||||
// Vuelca el contenido del renderizador en pantalla
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Bucle para el logo del juego
|
||||
void Logo::run() {
|
||||
while (SceneManager::current == SceneManager::Scene::LOGO) {
|
||||
update();
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
// Termina la sección
|
||||
void Logo::endSection() {
|
||||
switch (SceneManager::options) {
|
||||
case SceneManager::Options::NONE:
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
break;
|
||||
|
||||
default:
|
||||
// Ninguna acción por defecto
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializa el vector de colores
|
||||
void Logo::initColors() {
|
||||
// Inicializa el vector de colores
|
||||
const std::vector<Uint8> COLORS = {
|
||||
Color::index(Color::Cpc::BLACK),
|
||||
Color::index(Color::Cpc::BLUE),
|
||||
Color::index(Color::Cpc::RED),
|
||||
Color::index(Color::Cpc::MAGENTA),
|
||||
Color::index(Color::Cpc::GREEN),
|
||||
Color::index(Color::Cpc::CYAN),
|
||||
Color::index(Color::Cpc::YELLOW),
|
||||
Color::index(Color::Cpc::BRIGHT_WHITE)};
|
||||
for (const auto& color : COLORS) {
|
||||
color_.push_back(color);
|
||||
}
|
||||
}
|
||||
|
||||
// Crea los sprites de cada linea
|
||||
void Logo::initSprites() {
|
||||
const int TEXTURE_WIDTH = jailgames_surface_->getWidth();
|
||||
jailgames_initial_x_.reserve(jailgames_surface_->getHeight());
|
||||
|
||||
for (int i = 0; i < jailgames_surface_->getHeight(); ++i) {
|
||||
jailgames_sprite_.push_back(std::make_shared<SurfaceSprite>(jailgames_surface_, 0, i, TEXTURE_WIDTH, 1));
|
||||
jailgames_sprite_.back()->setClip(0, i, TEXTURE_WIDTH, 1);
|
||||
|
||||
// Calcular posición inicial (alternando entre derecha e izquierda, fuera del canvas)
|
||||
constexpr int LINE_OFFSET = 6;
|
||||
const int INITIAL_X = (i % 2 == 0)
|
||||
? (GameCanvas::WIDTH + (i * LINE_OFFSET))
|
||||
: (-TEXTURE_WIDTH - (i * LINE_OFFSET));
|
||||
jailgames_initial_x_.push_back(INITIAL_X);
|
||||
|
||||
jailgames_sprite_.at(i)->setX(INITIAL_X);
|
||||
jailgames_sprite_.at(i)->setY(base_y_ + i);
|
||||
}
|
||||
}
|
||||
81
source/game/scenes/logo.hpp
Normal file
81
source/game/scenes/logo.hpp
Normal file
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <functional> // Para std::function
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||
class SurfaceSprite; // Forward declaration
|
||||
class Surface; // Forward declaration
|
||||
|
||||
class Logo {
|
||||
public:
|
||||
// --- Tipos ---
|
||||
using EasingFunction = std::function<float(float)>; // Función de easing (permite lambdas)
|
||||
|
||||
// --- Enumeraciones ---
|
||||
enum class State {
|
||||
INITIAL, // Espera inicial
|
||||
JAILGAMES_SLIDE_IN, // Las líneas de JAILGAMES se deslizan hacia el centro
|
||||
SINCE_1998_FADE_IN, // Aparición gradual del texto "Since 1998"
|
||||
DISPLAY, // Logo completo visible
|
||||
FADE_OUT, // Desaparición gradual
|
||||
END // Fin de la secuencia
|
||||
};
|
||||
|
||||
// --- Constructor y Destructor ---
|
||||
Logo();
|
||||
~Logo() = default;
|
||||
|
||||
// --- Bucle principal ---
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Constantes de tiempo (en segundos) ---
|
||||
static constexpr float INITIAL_DELAY = 0.5F; // Tiempo antes de que empiece la animación
|
||||
static constexpr float SINCE_1998_FADE_DURATION = 0.5F; // Duración del fade-in de "Since 1998"
|
||||
static constexpr float DISPLAY_DURATION = 3.5F; // Tiempo que el logo permanece visible
|
||||
static constexpr float FADE_OUT_DURATION = 0.5F; // Duración del fade-out final
|
||||
|
||||
// --- Constantes de animación ---
|
||||
static constexpr float JAILGAMES_SLIDE_DURATION = 0.8F; // Duración de la animación de slide-in (segundos)
|
||||
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
static void handleEvents(); // Comprueba el manejador de eventos
|
||||
static void handleInput(); // Comprueba las entradas
|
||||
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
|
||||
void updateTextureColors(); // Gestiona el color de las texturas
|
||||
void updateState(float delta_time); // Actualiza el estado actual
|
||||
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
||||
[[nodiscard]] auto getColorIndex(float progress) const -> int; // Calcula el índice de color según el progreso (0.0-1.0)
|
||||
static void endSection(); // Termina la sección
|
||||
void initColors(); // Inicializa el vector de colores
|
||||
void initSprites(); // Crea los sprites de cada linea
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros a recursos
|
||||
std::shared_ptr<Surface> jailgames_surface_; // Textura con los graficos "JAILGAMES"
|
||||
std::shared_ptr<Surface> since_1998_surface_; // Textura con los graficos "Since 1998"
|
||||
std::vector<std::shared_ptr<SurfaceSprite>> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
|
||||
std::vector<int> jailgames_initial_x_; // Posiciones X iniciales de cada línea (para interpolación con easing)
|
||||
std::shared_ptr<SurfaceSprite> since_1998_sprite_; // SSprite para manejar la textura2
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
|
||||
// Posiciones calculadas dinámicamente (centrado independiente del tamaño del canvas)
|
||||
int jailgames_dest_x_{0}; // Posición X de destino para JAILGAMES (centrado horizontal)
|
||||
int base_y_{0}; // Posición Y base para los sprites (centrado vertical)
|
||||
|
||||
// Variables de estado de colores
|
||||
std::vector<Uint8> color_; // Vector con los colores para el fade
|
||||
Uint8 jailgames_color_{0}; // Color para el sprite de "JAILGAMES"
|
||||
Uint8 since_1998_color_{0}; // Color para el sprite de "Since 1998"
|
||||
|
||||
// Variables de estado de la secuencia
|
||||
State state_{State::INITIAL}; // Estado actual de la secuencia
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
EasingFunction easing_function_; // Función de easing para la animación del logo
|
||||
};
|
||||
612
source/game/scenes/title.cpp
Normal file
612
source/game/scenes/title.cpp
Normal file
@@ -0,0 +1,612 @@
|
||||
#include "game/scenes/title.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // Para clamp
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "core/input/global_inputs.hpp" // Para check
|
||||
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT, REP...
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
#include "core/rendering/text.hpp" // Para Text, Text::CENTER_FLAG, Text::COLOR_FLAG
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "core/resources/resource_list.hpp" // Para Asset
|
||||
#include "core/system/global_events.hpp" // Para check
|
||||
#include "game/defaults.hpp" // Para Defaults::Music
|
||||
#include "game/options.hpp" // Para Options, options, SectionState, Section
|
||||
#include "game/scene_manager.hpp" // Para SceneManager
|
||||
#include "utils/defines.hpp" // Para GameCanvas::CENTER_X, GameCanvas::WIDTH
|
||||
#include "utils/color.hpp" // Para Color
|
||||
#include "utils/utils.hpp" // Para stringToColor
|
||||
|
||||
// Constructor
|
||||
Title::Title()
|
||||
: game_logo_surface_(Resource::Cache::get()->getSurface("title_logo.gif")),
|
||||
game_logo_sprite_(std::make_unique<SurfaceSprite>(
|
||||
game_logo_surface_,
|
||||
(GameCanvas::WIDTH - game_logo_surface_->getWidth()) / 2, // Centrado horizontal dinámico
|
||||
static_cast<int>(GameCanvas::HEIGHT * 0.05F), // Posición Y proporcional (~5% desde arriba)
|
||||
game_logo_surface_->getWidth(),
|
||||
game_logo_surface_->getHeight())),
|
||||
title_surface_(std::make_shared<Surface>(Options::game.width, Options::game.height)),
|
||||
delta_timer_(std::make_unique<DeltaTimer>()),
|
||||
menu_text_(Resource::Cache::get()->getText("gauntlet")) {
|
||||
// Inicializa arrays con valores por defecto
|
||||
temp_keys_.fill(SDL_SCANCODE_UNKNOWN);
|
||||
temp_buttons_.fill(-1);
|
||||
|
||||
// Determina el estado inicial
|
||||
state_ = State::MAIN_MENU;
|
||||
|
||||
// Establece SceneManager
|
||||
SceneManager::current = SceneManager::Scene::TITLE;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
|
||||
// Acciones iniciales
|
||||
Screen::get()->setBorderColor(Color::index(Color::Cpc::BLACK)); // Cambia el color del borde
|
||||
Audio::get()->playMusic(Defaults::Music::TITLE_TRACK); // Inicia la musica
|
||||
}
|
||||
|
||||
// Comprueba el manejador de eventos
|
||||
void Title::handleEvents() {
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
GlobalEvents::handle(event);
|
||||
|
||||
// Manejo especial para captura de botones de gamepad
|
||||
if (is_remapping_joystick_ && !remap_completed_ &&
|
||||
(event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN || event.type == SDL_EVENT_GAMEPAD_AXIS_MOTION)) {
|
||||
handleJoystickRemap(event);
|
||||
continue; // No procesar más este evento
|
||||
}
|
||||
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
// Si estamos en modo remap de teclado, capturar tecla
|
||||
if (is_remapping_keyboard_ && !remap_completed_) {
|
||||
handleKeyboardRemap(event);
|
||||
}
|
||||
// Si estamos en el menú principal normal
|
||||
else if (state_ == State::MAIN_MENU && !is_remapping_keyboard_ && !is_remapping_joystick_) {
|
||||
handleMainMenuKeyPress(event.key.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Maneja las teclas del menu principal
|
||||
void Title::handleMainMenuKeyPress(SDL_Keycode key) {
|
||||
switch (key) {
|
||||
case SDLK_1:
|
||||
// PLAY
|
||||
exit_scene_ = SceneManager::Scene::GAME;
|
||||
transitionToState(State::FADE_MENU);
|
||||
Audio::get()->fadeOutMusic(Defaults::Music::FADE_DURATION_MS);
|
||||
break;
|
||||
|
||||
case SDLK_2:
|
||||
// REDEFINE KEYBOARD
|
||||
is_remapping_keyboard_ = true;
|
||||
is_remapping_joystick_ = false;
|
||||
remap_step_ = 0;
|
||||
remap_completed_ = false;
|
||||
remap_error_message_.clear();
|
||||
state_time_ = 0.0F;
|
||||
break;
|
||||
|
||||
case SDLK_3:
|
||||
// REDEFINE JOYSTICK (siempre visible, pero solo funciona si hay gamepad)
|
||||
if (Input::get()->gameControllerFound()) {
|
||||
is_remapping_keyboard_ = false;
|
||||
is_remapping_joystick_ = true;
|
||||
remap_step_ = 0;
|
||||
remap_completed_ = false;
|
||||
remap_error_message_.clear();
|
||||
axis_cooldown_ = 0.0F;
|
||||
state_time_ = 0.0F;
|
||||
}
|
||||
// Si no hay gamepad, simplemente no hacer nada
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas
|
||||
void Title::handleInput(float delta_time) {
|
||||
Input::get()->update();
|
||||
|
||||
// Permitir cancelar remap con ESC/CANCEL
|
||||
if ((is_remapping_keyboard_ || is_remapping_joystick_) && !remap_completed_) {
|
||||
if (Input::get()->checkAction(InputAction::CANCEL, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||
is_remapping_keyboard_ = false;
|
||||
is_remapping_joystick_ = false;
|
||||
remap_step_ = 0;
|
||||
remap_completed_ = false;
|
||||
remap_error_message_.clear();
|
||||
}
|
||||
// Durante el remap, no procesar otras entradas
|
||||
GlobalInputs::handle();
|
||||
return;
|
||||
}
|
||||
|
||||
GlobalInputs::handle();
|
||||
}
|
||||
|
||||
// Actualiza las variables
|
||||
void Title::update() {
|
||||
const float DELTA_TIME = delta_timer_->tick();
|
||||
|
||||
handleEvents(); // Comprueba los eventos
|
||||
handleInput(DELTA_TIME); // Comprueba las entradas
|
||||
|
||||
updateState(DELTA_TIME); // Actualiza el estado actual
|
||||
|
||||
Audio::update(); // Actualiza el objeto Audio
|
||||
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||
}
|
||||
|
||||
// Actualiza el estado actual
|
||||
void Title::updateState(float delta_time) {
|
||||
switch (state_) {
|
||||
case State::MAIN_MENU:
|
||||
updateMainMenu(delta_time);
|
||||
break;
|
||||
|
||||
case State::FADE_MENU:
|
||||
updateFadeMenu(delta_time);
|
||||
break;
|
||||
|
||||
case State::POST_FADE_MENU:
|
||||
updatePostFadeMenu(delta_time);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Transiciona a un nuevo estado
|
||||
void Title::transitionToState(State new_state) {
|
||||
state_ = new_state;
|
||||
state_time_ = 0.0F;
|
||||
fade_accumulator_ = 0.0F;
|
||||
}
|
||||
|
||||
// Actualiza el estado MAIN_MENU
|
||||
void Title::updateMainMenu(float delta_time) {
|
||||
// Si estamos en modo remap, manejar la lógica específica
|
||||
if (is_remapping_keyboard_ || is_remapping_joystick_) {
|
||||
// Decrementar cooldown de ejes si estamos capturando botones de joystick
|
||||
if (is_remapping_joystick_ && axis_cooldown_ > 0.0F) {
|
||||
axis_cooldown_ -= delta_time;
|
||||
axis_cooldown_ = std::max(axis_cooldown_, 0.0F);
|
||||
}
|
||||
|
||||
// Si el remap está completado, esperar antes de guardar
|
||||
if (remap_completed_) {
|
||||
state_time_ += delta_time;
|
||||
if (state_time_ >= KEYBOARD_REMAP_DISPLAY_DELAY) {
|
||||
if (is_remapping_keyboard_) {
|
||||
applyKeyboardRemap();
|
||||
} else if (is_remapping_joystick_) {
|
||||
applyJoystickRemap();
|
||||
}
|
||||
// Resetear estado de remap
|
||||
is_remapping_keyboard_ = false;
|
||||
is_remapping_joystick_ = false;
|
||||
remap_completed_ = false;
|
||||
state_time_ = 0.0F;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Incrementa el temporizador solo en el menú principal normal
|
||||
state_time_ += delta_time;
|
||||
|
||||
// Si el tiempo alcanza el timeout, vuelve al logo
|
||||
if (state_time_ >= MAIN_MENU_IDLE_TIMEOUT) {
|
||||
exit_scene_ = SceneManager::Scene::LOGO;
|
||||
transitionToState(State::FADE_MENU);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado FADE_MENU
|
||||
void Title::updateFadeMenu(float delta_time) {
|
||||
fade_accumulator_ += delta_time;
|
||||
if (fade_accumulator_ >= FADE_STEP_INTERVAL) {
|
||||
fade_accumulator_ = 0.0F;
|
||||
if (title_surface_->fadeSubPalette()) {
|
||||
transitionToState(State::POST_FADE_MENU);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado POST_FADE_MENU
|
||||
void Title::updatePostFadeMenu(float delta_time) {
|
||||
state_time_ += delta_time;
|
||||
if (state_time_ >= POST_FADE_DELAY) {
|
||||
SceneManager::current = exit_scene_;
|
||||
SceneManager::options = SceneManager::Options::NONE;
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja en pantalla
|
||||
void Title::render() {
|
||||
// Rellena la surface
|
||||
fillTitleSurface();
|
||||
|
||||
// Prepara para empezar a dibujar en la textura de juego
|
||||
Screen::get()->start();
|
||||
Screen::get()->clearSurface(Color::index(Color::Cpc::BLACK));
|
||||
|
||||
// Dibuja en pantalla la surface con la composicion
|
||||
title_surface_->render();
|
||||
|
||||
// Vuelca el contenido del renderizador en pantalla
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Bucle para el logo del juego
|
||||
void Title::run() {
|
||||
while (SceneManager::current == SceneManager::Scene::TITLE) {
|
||||
update();
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja el logo con el titulo del juego
|
||||
void Title::renderGameLogo() {
|
||||
game_logo_sprite_->render();
|
||||
}
|
||||
|
||||
// Dibuja el menu principal
|
||||
void Title::renderMainMenu() {
|
||||
// Si estamos en modo remap, mostrar la pantalla correspondiente
|
||||
if (is_remapping_keyboard_) {
|
||||
renderKeyboardRemap();
|
||||
return;
|
||||
}
|
||||
if (is_remapping_joystick_) {
|
||||
renderJoystickRemap();
|
||||
return;
|
||||
}
|
||||
|
||||
// Zona dinámica del menú (proporcional al canvas)
|
||||
// El logo ocupa la parte superior, el menú se centra en el espacio restante
|
||||
const int LOGO_BOTTOM = static_cast<int>(GameCanvas::HEIGHT * 0.25F); // Espacio reservado para logo
|
||||
const int MENU_ZONE_HEIGHT = GameCanvas::HEIGHT - LOGO_BOTTOM; // Espacio disponible para menú
|
||||
|
||||
// Menú principal normal con 3 opciones centradas verticalmente en la zona
|
||||
const Uint8 COLOR = stringToColor("green");
|
||||
const int TEXT_SIZE = menu_text_->getCharacterSize();
|
||||
const int MENU_CENTER_Y = LOGO_BOTTOM + (MENU_ZONE_HEIGHT / 2);
|
||||
const int SPACING = 2 * TEXT_SIZE; // Espaciado entre opciones
|
||||
|
||||
// Calcula posiciones centradas verticalmente (3 items con espaciado)
|
||||
const int TOTAL_HEIGHT = 2 * SPACING; // 2 espacios entre 3 items
|
||||
const int START_Y = MENU_CENTER_Y - (TOTAL_HEIGHT / 2);
|
||||
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y, "1. PLAY", 1, COLOR);
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y + SPACING, "2. REDEFINE KEYBOARD", 1, COLOR);
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y + (2 * SPACING), "3. REDEFINE JOYSTICK", 1, COLOR);
|
||||
}
|
||||
|
||||
// Dibuja los elementos en la surface
|
||||
void Title::fillTitleSurface() {
|
||||
// Renderiza sobre la textura
|
||||
auto previuos_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(title_surface_);
|
||||
|
||||
// Rellena la textura de color
|
||||
title_surface_->clear(Color::index(Color::Cpc::BLACK));
|
||||
|
||||
switch (state_) {
|
||||
case State::MAIN_MENU:
|
||||
case State::FADE_MENU:
|
||||
renderGameLogo();
|
||||
renderMainMenu();
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Deja el renderizador como estaba
|
||||
Screen::get()->setRendererSurface(previuos_renderer);
|
||||
}
|
||||
|
||||
// Maneja la captura de teclas para redefinir el teclado
|
||||
void Title::handleKeyboardRemap(const SDL_Event& event) {
|
||||
SDL_Scancode scancode = event.key.scancode;
|
||||
|
||||
// Valida la tecla
|
||||
if (!isKeyValid(scancode)) {
|
||||
remap_error_message_ = "INVALID KEY! TRY ANOTHER";
|
||||
return;
|
||||
}
|
||||
|
||||
// Verifica duplicados
|
||||
if (isKeyDuplicate(scancode, remap_step_)) {
|
||||
remap_error_message_ = "KEY ALREADY USED! TRY ANOTHER";
|
||||
return;
|
||||
}
|
||||
|
||||
// Tecla valida, guardar
|
||||
temp_keys_[remap_step_] = scancode;
|
||||
remap_error_message_.clear();
|
||||
remap_step_++;
|
||||
|
||||
// Si completamos los 3 pasos, mostrar resultado y esperar
|
||||
if (remap_step_ >= 3) {
|
||||
remap_completed_ = true;
|
||||
state_time_ = 0.0F; // Resetear el timer para el delay de 1 segundo
|
||||
}
|
||||
}
|
||||
|
||||
// Valida si una tecla es permitida
|
||||
auto Title::isKeyValid(SDL_Scancode scancode) -> bool {
|
||||
// Prohibir ESC (reservado para cancelar)
|
||||
if (scancode == SDL_SCANCODE_ESCAPE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Prohibir teclas F1-F12 (reservadas para funciones del sistema)
|
||||
if (scancode >= SDL_SCANCODE_F1 && scancode <= SDL_SCANCODE_F12) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Prohibir Enter/Return (reservado para confirmaciones)
|
||||
if (scancode == SDL_SCANCODE_RETURN || scancode == SDL_SCANCODE_RETURN2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Verifica si una tecla ya fue usada en pasos anteriores
|
||||
auto Title::isKeyDuplicate(SDL_Scancode scancode, int current_step) -> bool {
|
||||
for (int i = 0; i < current_step; i++) {
|
||||
if (temp_keys_[i] == scancode) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Retorna el nombre de la accion para el paso actual
|
||||
auto Title::getActionName(int step) -> std::string {
|
||||
switch (step) {
|
||||
case 0:
|
||||
return "LEFT";
|
||||
case 1:
|
||||
return "RIGHT";
|
||||
case 2:
|
||||
return "JUMP";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
// Aplica y guarda las teclas redefinidas
|
||||
void Title::applyKeyboardRemap() {
|
||||
// Guardar las nuevas teclas en Options::controls
|
||||
Options::keyboard_controls.key_left = temp_keys_[0];
|
||||
Options::keyboard_controls.key_right = temp_keys_[1];
|
||||
Options::keyboard_controls.key_jump = temp_keys_[2];
|
||||
|
||||
// Aplicar los bindings al sistema de Input
|
||||
Input::get()->applyKeyboardBindingsFromOptions();
|
||||
|
||||
// Guardar a archivo de configuracion
|
||||
Options::saveToFile();
|
||||
}
|
||||
|
||||
// Dibuja la pantalla de redefinir teclado
|
||||
void Title::renderKeyboardRemap() {
|
||||
// Zona dinámica del menú (proporcional al canvas)
|
||||
const int LOGO_BOTTOM = static_cast<int>(GameCanvas::HEIGHT * 0.25F);
|
||||
const int MENU_ZONE_HEIGHT = GameCanvas::HEIGHT - LOGO_BOTTOM;
|
||||
|
||||
const Uint8 COLOR = stringToColor("green");
|
||||
const Uint8 ERROR_COLOR = stringToColor("red");
|
||||
const int TEXT_SIZE = menu_text_->getCharacterSize();
|
||||
const int MENU_CENTER_Y = LOGO_BOTTOM + (MENU_ZONE_HEIGHT / 2);
|
||||
|
||||
// Calcula posiciones centradas verticalmente
|
||||
// Layout: Mensaje principal, espacio, 3 teclas (LEFT/RIGHT/JUMP), espacio, mensaje de error
|
||||
const int LINE_SPACING = TEXT_SIZE;
|
||||
const int START_Y = MENU_CENTER_Y - (2 * TEXT_SIZE); // Centrado aproximado
|
||||
|
||||
// Mensaje principal: "PRESS KEY FOR [ACTION]" o "KEYS DEFINED" si completado
|
||||
if (remap_step_ >= 3) {
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y, "KEYS DEFINED", 1, COLOR);
|
||||
} else {
|
||||
const std::string ACTION = getActionName(remap_step_);
|
||||
const std::string MESSAGE = "PRESS KEY FOR " + ACTION;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y, MESSAGE, 1, COLOR);
|
||||
}
|
||||
|
||||
// Mostrar teclas ya capturadas (con espaciado de 2 líneas desde el mensaje principal)
|
||||
const int KEYS_START_Y = START_Y + (2 * LINE_SPACING);
|
||||
if (remap_step_ > 0) {
|
||||
const std::string LEFT_KEY = SDL_GetScancodeName(temp_keys_[0]);
|
||||
const std::string LEFT_MSG = "LEFT: " + LEFT_KEY;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, KEYS_START_Y, LEFT_MSG, 1, COLOR);
|
||||
}
|
||||
if (remap_step_ > 1) {
|
||||
const std::string RIGHT_KEY = SDL_GetScancodeName(temp_keys_[1]);
|
||||
const std::string RIGHT_MSG = "RIGHT: " + RIGHT_KEY;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, KEYS_START_Y + LINE_SPACING, RIGHT_MSG, 1, COLOR);
|
||||
}
|
||||
if (remap_step_ >= 3) {
|
||||
const std::string JUMP_KEY = SDL_GetScancodeName(temp_keys_[2]);
|
||||
const std::string JUMP_MSG = "JUMP: " + JUMP_KEY;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, KEYS_START_Y + (2 * LINE_SPACING), JUMP_MSG, 1, COLOR);
|
||||
}
|
||||
|
||||
// Mensaje de error si existe (4 líneas después del inicio de las teclas)
|
||||
if (!remap_error_message_.empty()) {
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, KEYS_START_Y + (4 * LINE_SPACING), remap_error_message_, 1, ERROR_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja la pantalla de redefinir joystick
|
||||
void Title::renderJoystickRemap() {
|
||||
// Zona dinámica del menú (proporcional al canvas)
|
||||
const int LOGO_BOTTOM = static_cast<int>(GameCanvas::HEIGHT * 0.25F);
|
||||
const int MENU_ZONE_HEIGHT = GameCanvas::HEIGHT - LOGO_BOTTOM;
|
||||
|
||||
const Uint8 COLOR = stringToColor("green");
|
||||
const Uint8 ERROR_COLOR = stringToColor("red");
|
||||
const int TEXT_SIZE = menu_text_->getCharacterSize();
|
||||
const int MENU_CENTER_Y = LOGO_BOTTOM + (MENU_ZONE_HEIGHT / 2);
|
||||
|
||||
// Calcula posiciones centradas verticalmente
|
||||
// Layout: Mensaje principal, espacio, 3 botones (LEFT/RIGHT/JUMP), espacio, mensaje de error
|
||||
const int LINE_SPACING = TEXT_SIZE;
|
||||
const int START_Y = MENU_CENTER_Y - (2 * TEXT_SIZE); // Centrado aproximado
|
||||
|
||||
// Mensaje principal: "PRESS BUTTON FOR [ACTION]" o "BUTTONS DEFINED" si completado
|
||||
if (remap_step_ >= 3) {
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y, "BUTTONS DEFINED", 1, COLOR);
|
||||
} else {
|
||||
const std::string ACTION = getActionName(remap_step_);
|
||||
const std::string MESSAGE = "PRESS BUTTON FOR " + ACTION;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, START_Y, MESSAGE, 1, COLOR);
|
||||
}
|
||||
|
||||
// Mostrar botones ya capturados (con espaciado de 2 líneas desde el mensaje principal)
|
||||
const int BUTTONS_START_Y = START_Y + (2 * LINE_SPACING);
|
||||
if (remap_step_ > 0) {
|
||||
const std::string LEFT_BTN = getButtonName(temp_buttons_[0]);
|
||||
const std::string LEFT_MSG = "LEFT: " + LEFT_BTN;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, BUTTONS_START_Y, LEFT_MSG, 1, COLOR);
|
||||
}
|
||||
if (remap_step_ > 1) {
|
||||
const std::string RIGHT_BTN = getButtonName(temp_buttons_[1]);
|
||||
const std::string RIGHT_MSG = "RIGHT: " + RIGHT_BTN;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, BUTTONS_START_Y + LINE_SPACING, RIGHT_MSG, 1, COLOR);
|
||||
}
|
||||
if (remap_step_ >= 3) {
|
||||
const std::string JUMP_BTN = getButtonName(temp_buttons_[2]);
|
||||
const std::string JUMP_MSG = "JUMP: " + JUMP_BTN;
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, BUTTONS_START_Y + (2 * LINE_SPACING), JUMP_MSG, 1, COLOR);
|
||||
}
|
||||
|
||||
// Mensaje de error si existe (4 líneas después del inicio de los botones)
|
||||
if (!remap_error_message_.empty()) {
|
||||
menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, BUTTONS_START_Y + (4 * LINE_SPACING), remap_error_message_, 1, ERROR_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
// Maneja la captura de botones del gamepad para redefinir
|
||||
void Title::handleJoystickRemap(const SDL_Event& event) {
|
||||
int captured_button = -1;
|
||||
|
||||
// Capturar botones del gamepad
|
||||
if (event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN) {
|
||||
captured_button = static_cast<int>(event.gbutton.button);
|
||||
}
|
||||
// Capturar triggers y ejes analógicos
|
||||
else if (event.type == SDL_EVENT_GAMEPAD_AXIS_MOTION) {
|
||||
// Si el cooldown está activo, ignorar eventos de ejes (evita múltiples capturas)
|
||||
if (axis_cooldown_ > 0.0F) {
|
||||
return;
|
||||
}
|
||||
|
||||
constexpr Sint16 TRIGGER_THRESHOLD = 20000;
|
||||
constexpr Sint16 AXIS_THRESHOLD = 20000;
|
||||
|
||||
// Capturar triggers como botones (usando valores especiales 100/101)
|
||||
if (event.gaxis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER && event.gaxis.value > TRIGGER_THRESHOLD) {
|
||||
captured_button = Input::TRIGGER_L2_AS_BUTTON; // 100
|
||||
axis_cooldown_ = 0.5F; // Cooldown de medio segundo
|
||||
} else if (event.gaxis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER && event.gaxis.value > TRIGGER_THRESHOLD) {
|
||||
captured_button = Input::TRIGGER_R2_AS_BUTTON; // 101
|
||||
axis_cooldown_ = 0.5F;
|
||||
}
|
||||
// Capturar ejes del stick analógico (usando valores especiales 200+)
|
||||
else if (event.gaxis.axis == SDL_GAMEPAD_AXIS_LEFTX) {
|
||||
if (event.gaxis.value < -AXIS_THRESHOLD) {
|
||||
captured_button = 200; // Left stick izquierda
|
||||
axis_cooldown_ = 0.5F;
|
||||
} else if (event.gaxis.value > AXIS_THRESHOLD) {
|
||||
captured_button = 201; // Left stick derecha
|
||||
axis_cooldown_ = 0.5F;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si no se capturó ningún input válido, salir
|
||||
if (captured_button == -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Verifica duplicados
|
||||
if (isButtonDuplicate(captured_button, remap_step_)) {
|
||||
remap_error_message_ = "BUTTON ALREADY USED! TRY ANOTHER";
|
||||
return;
|
||||
}
|
||||
|
||||
// Botón válido, guardar
|
||||
temp_buttons_[remap_step_] = captured_button;
|
||||
remap_error_message_.clear();
|
||||
remap_step_++;
|
||||
|
||||
// Si completamos los 3 pasos, mostrar resultado y esperar
|
||||
if (remap_step_ >= 3) {
|
||||
remap_completed_ = true;
|
||||
state_time_ = 0.0F; // Resetear el timer para el delay
|
||||
}
|
||||
}
|
||||
|
||||
// Valida si un botón está duplicado
|
||||
auto Title::isButtonDuplicate(int button, int current_step) -> bool {
|
||||
for (int i = 0; i < current_step; ++i) {
|
||||
if (temp_buttons_[i] == button) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Aplica y guarda los botones del gamepad redefinidos
|
||||
void Title::applyJoystickRemap() {
|
||||
// Guardar los nuevos botones en Options::gamepad_controls
|
||||
Options::gamepad_controls.button_left = temp_buttons_[0];
|
||||
Options::gamepad_controls.button_right = temp_buttons_[1];
|
||||
Options::gamepad_controls.button_jump = temp_buttons_[2];
|
||||
|
||||
// Aplicar los bindings al sistema de Input
|
||||
Input::get()->applyGamepadBindingsFromOptions();
|
||||
|
||||
// Guardar a archivo de configuracion
|
||||
Options::saveToFile();
|
||||
}
|
||||
|
||||
// Retorna el nombre amigable del botón del gamepad
|
||||
auto Title::getButtonName(int button) -> std::string {
|
||||
// Triggers especiales
|
||||
if (button == Input::TRIGGER_L2_AS_BUTTON) {
|
||||
return "L2";
|
||||
}
|
||||
if (button == Input::TRIGGER_R2_AS_BUTTON) {
|
||||
return "R2";
|
||||
}
|
||||
|
||||
// Ejes del stick analógico
|
||||
if (button == 200) {
|
||||
return "LEFT STICK LEFT";
|
||||
}
|
||||
if (button == 201) {
|
||||
return "LEFT STICK RIGHT";
|
||||
}
|
||||
|
||||
// Botones estándar SDL
|
||||
const auto GAMEPAD_BUTTON = static_cast<SDL_GamepadButton>(button);
|
||||
const char* button_name = SDL_GetGamepadStringForButton(GAMEPAD_BUTTON);
|
||||
return (button_name != nullptr) ? std::string(button_name) : "UNKNOWN";
|
||||
}
|
||||
87
source/game/scenes/title.hpp
Normal file
87
source/game/scenes/title.hpp
Normal file
@@ -0,0 +1,87 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <array> // Para std::array
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
|
||||
#include "game/scene_manager.hpp" // Para SceneManager::Scene
|
||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||
class SurfaceSprite; // Forward declaration
|
||||
class Surface; // Forward declaration
|
||||
class Text; // Forward declaration
|
||||
|
||||
class Title {
|
||||
public:
|
||||
// --- Constructor y Destructor ---
|
||||
Title();
|
||||
~Title() = default;
|
||||
|
||||
// --- Bucle principal ---
|
||||
void run();
|
||||
|
||||
private:
|
||||
// --- Enumeraciones ---
|
||||
enum class State {
|
||||
MAIN_MENU,
|
||||
FADE_MENU,
|
||||
POST_FADE_MENU,
|
||||
};
|
||||
|
||||
// --- Constantes de tiempo (en segundos) ---
|
||||
static constexpr float FADE_STEP_INTERVAL = 0.05F; // Intervalo entre pasos de fade (antes cada 4 frames)
|
||||
static constexpr float POST_FADE_DELAY = 1.0F; // Delay después del fade (pantalla en negro)
|
||||
static constexpr float MAIN_MENU_IDLE_TIMEOUT = 20.0F; // Timeout para ir a créditos (antes 2200 frames)
|
||||
static constexpr float KEYBOARD_REMAP_DISPLAY_DELAY = 2.0F; // Tiempo mostrando teclas definidas antes de guardar
|
||||
|
||||
// --- Métodos ---
|
||||
void update(); // Actualiza las variables
|
||||
void render(); // Dibuja en pantalla
|
||||
void handleEvents(); // Comprueba el manejador de eventos
|
||||
void handleMainMenuKeyPress(SDL_Keycode key); // Maneja las teclas del menu principal
|
||||
void handleInput(float delta_time); // Comprueba las entradas
|
||||
void updateState(float delta_time); // Actualiza el estado actual
|
||||
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
||||
void updateMainMenu(float delta_time); // Actualiza MAIN_MENU
|
||||
void updateFadeMenu(float delta_time); // Actualiza FADE_MENU
|
||||
void updatePostFadeMenu(float delta_time); // Actualiza POST_FADE_MENU
|
||||
void renderGameLogo(); // Dibuja el logo con el titulo del juego
|
||||
void renderMainMenu(); // Dibuja el menu principal
|
||||
void renderKeyboardRemap(); // Dibuja la pantalla de redefinir teclado
|
||||
void renderJoystickRemap(); // Dibuja la pantalla de redefinir joystick
|
||||
void handleKeyboardRemap(const SDL_Event& event); // Maneja la captura de teclas
|
||||
void handleJoystickRemap(const SDL_Event& event); // Maneja la captura de botones del gamepad
|
||||
static auto isKeyValid(SDL_Scancode scancode) -> bool; // Valida si una tecla es permitida
|
||||
auto isKeyDuplicate(SDL_Scancode scancode, int current_step) -> bool; // Valida si una tecla esta duplicada
|
||||
auto isButtonDuplicate(int button, int current_step) -> bool; // Valida si un boton esta duplicado
|
||||
void applyKeyboardRemap(); // Aplica y guarda las teclas redefinidas
|
||||
void applyJoystickRemap(); // Aplica y guarda los botones del gamepad redefinidos
|
||||
static auto getActionName(int step) -> std::string; // Retorna el nombre de la accion (LEFT/RIGHT/JUMP)
|
||||
static auto getButtonName(int button) -> std::string; // Retorna el nombre amigable del boton del gamepad
|
||||
void fillTitleSurface(); // Dibuja los elementos en la surface
|
||||
|
||||
// --- Variables miembro ---
|
||||
// Objetos y punteros
|
||||
std::shared_ptr<Surface> game_logo_surface_; // Textura con los graficos
|
||||
std::unique_ptr<SurfaceSprite> game_logo_sprite_; // SSprite para manejar la surface
|
||||
std::shared_ptr<Surface> title_surface_; // Surface donde se dibuja toda la clase
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer para delta time
|
||||
std::shared_ptr<Text> menu_text_; // Texto para los menus
|
||||
|
||||
// Variables de estado general
|
||||
State state_; // Estado en el que se encuentra el bucle principal
|
||||
float state_time_{0.0F}; // Tiempo acumulado en el estado actual
|
||||
float fade_accumulator_{0.0F}; // Acumulador para controlar el fade por tiempo
|
||||
SceneManager::Scene exit_scene_{SceneManager::Scene::GAME}; // Escena de destino al salir del título
|
||||
|
||||
// Variables para redefinir controles
|
||||
bool is_remapping_keyboard_{false}; // True si estamos redefiniendo teclado
|
||||
bool is_remapping_joystick_{false}; // True si estamos redefiniendo joystick
|
||||
int remap_step_{0}; // Paso actual en la redefinicion (0=LEFT, 1=RIGHT, 2=JUMP)
|
||||
std::array<SDL_Scancode, 3> temp_keys_; // Almacenamiento temporal de teclas capturadas
|
||||
std::array<int, 3> temp_buttons_; // Almacenamiento temporal de botones de gamepad capturados
|
||||
std::string remap_error_message_; // Mensaje de error si la tecla/boton es invalido
|
||||
float axis_cooldown_{0.0F}; // Cooldown para evitar múltiples capturas de ejes
|
||||
bool remap_completed_{false}; // True cuando se completa el remap (mostrar antes de guardar)
|
||||
};
|
||||
289
source/game/ui/notifier.cpp
Normal file
289
source/game/ui/notifier.cpp
Normal file
@@ -0,0 +1,289 @@
|
||||
#include "game/ui/notifier.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // Para remove_if
|
||||
#include <iterator> // Para prev
|
||||
#include <ranges> // Para reverse_view
|
||||
#include <string> // Para string, basic_string
|
||||
#include <vector> // Para vector
|
||||
|
||||
#include "core/audio/audio.hpp" // Para Audio
|
||||
#include "core/rendering/screen.hpp" // Para Screen
|
||||
#include "core/rendering/surface.hpp" // Para Surface
|
||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||
#include "core/rendering/text.hpp" // Para Text, Text::CENTER_FLAG, Text::COLOR_FLAG
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "game/options.hpp" // Para Options, options, NotificationPosition
|
||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||
#include "utils/color.hpp" // Para Color
|
||||
|
||||
// [SINGLETON]
|
||||
Notifier* Notifier::notifier = nullptr;
|
||||
|
||||
// Definición de estilos predefinidos
|
||||
const Notifier::Style Notifier::Style::DEFAULT = {
|
||||
.bg_color = Color::index(Color::Cpc::BLUE),
|
||||
.border_color = Color::index(Color::Cpc::CYAN),
|
||||
.text_color = Color::index(Color::Cpc::CYAN),
|
||||
.shape = Notifier::Shape::SQUARED,
|
||||
.text_align = Notifier::TextAlign::CENTER,
|
||||
.duration = 2.0F,
|
||||
.sound_file = "notify.wav",
|
||||
.play_sound = false};
|
||||
|
||||
const Notifier::Style Notifier::Style::CHEEVO = {
|
||||
.bg_color = Color::index(Color::Cpc::MAGENTA),
|
||||
.border_color = Color::index(Color::Cpc::BRIGHT_MAGENTA),
|
||||
.text_color = Color::index(Color::Cpc::WHITE),
|
||||
.shape = Notifier::Shape::SQUARED,
|
||||
.text_align = Notifier::TextAlign::CENTER,
|
||||
.duration = 4.0F,
|
||||
.sound_file = "notify.wav",
|
||||
.play_sound = true};
|
||||
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void Notifier::init(const std::string& icon_file, const std::string& text) {
|
||||
Notifier::notifier = new Notifier(icon_file, text);
|
||||
}
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void Notifier::destroy() {
|
||||
delete Notifier::notifier;
|
||||
}
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
auto Notifier::get() -> Notifier* {
|
||||
return Notifier::notifier;
|
||||
}
|
||||
|
||||
// Constructor
|
||||
Notifier::Notifier(const std::string& icon_file, const std::string& text)
|
||||
: icon_surface_(!icon_file.empty() ? Resource::Cache::get()->getSurface(icon_file) : nullptr),
|
||||
text_(Resource::Cache::get()->getText(text)),
|
||||
delta_timer_(std::make_unique<DeltaTimer>()),
|
||||
has_icons_(!icon_file.empty()) {}
|
||||
|
||||
// Dibuja las notificaciones por pantalla
|
||||
void Notifier::render() {
|
||||
for (auto& notification : std::ranges::reverse_view(notifications_)) {
|
||||
notification.sprite->render();
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado de las notificaiones
|
||||
void Notifier::update(float delta_time) {
|
||||
for (auto& notification : notifications_) {
|
||||
// Si la notificación anterior está "saliendo", no hagas nada
|
||||
if (!notifications_.empty() && ¬ification != ¬ifications_.front()) {
|
||||
const auto& previous_notification = *(std::prev(¬ification));
|
||||
if (previous_notification.state == Status::RISING) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (notification.state) {
|
||||
case Status::RISING: {
|
||||
const float DISPLACEMENT = SLIDE_SPEED * delta_time;
|
||||
notification.rect.y += DISPLACEMENT;
|
||||
|
||||
if (notification.rect.y >= notification.y) {
|
||||
notification.rect.y = notification.y;
|
||||
notification.state = Status::STAY;
|
||||
notification.elapsed_time = 0.0F;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Status::STAY: {
|
||||
notification.elapsed_time += delta_time;
|
||||
if (notification.elapsed_time >= notification.display_duration) {
|
||||
notification.state = Status::VANISHING;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case Status::VANISHING: {
|
||||
const float DISPLACEMENT = SLIDE_SPEED * delta_time;
|
||||
notification.rect.y -= DISPLACEMENT;
|
||||
|
||||
const float TARGET_Y = notification.y - notification.travel_dist;
|
||||
if (notification.rect.y <= TARGET_Y) {
|
||||
notification.rect.y = TARGET_Y;
|
||||
notification.state = Status::FINISHED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case Status::FINISHED:
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
notification.sprite->setPosition(notification.rect);
|
||||
}
|
||||
|
||||
clearFinishedNotifications();
|
||||
}
|
||||
|
||||
// Elimina las notificaciones finalizadas
|
||||
void Notifier::clearFinishedNotifications() {
|
||||
auto result = std::ranges::remove_if(notifications_, [](const Notification& notification) {
|
||||
return notification.state == Status::FINISHED;
|
||||
});
|
||||
notifications_.erase(result.begin(), result.end());
|
||||
}
|
||||
|
||||
void Notifier::show(std::vector<std::string> texts, const Style& style, int icon, bool can_be_removed, const std::string& code) {
|
||||
// Si no hay texto, acaba
|
||||
if (texts.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Si las notificaciones no se apilan, elimina las anteriores
|
||||
if (!stack_) {
|
||||
clearNotifications();
|
||||
}
|
||||
|
||||
// Elimina las cadenas vacías
|
||||
auto result = std::ranges::remove_if(texts, [](const std::string& s) { return s.empty(); });
|
||||
texts.erase(result.begin(), result.end());
|
||||
|
||||
// Encuentra la cadena más larga
|
||||
std::string longest;
|
||||
for (const auto& text : texts) {
|
||||
if (text.length() > longest.length()) {
|
||||
longest = text;
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializa variables
|
||||
const int TEXT_SIZE = 6;
|
||||
const auto PADDING_IN_H = TEXT_SIZE;
|
||||
const auto PADDING_IN_V = TEXT_SIZE / 2;
|
||||
const int ICON_SPACE = icon >= 0 ? ICON_SIZE + PADDING_IN_H : 0;
|
||||
const TextAlign TEXT_IS = ICON_SPACE > 0 ? TextAlign::LEFT : style.text_align;
|
||||
const float WIDTH = Options::game.width - (PADDING_OUT * 2);
|
||||
const float HEIGHT = (TEXT_SIZE * texts.size()) + (PADDING_IN_V * 2);
|
||||
const auto SHAPE = style.shape;
|
||||
|
||||
// Posición horizontal
|
||||
float desp_h = ((Options::game.width / 2) - (WIDTH / 2));
|
||||
;
|
||||
|
||||
// Posición vertical
|
||||
const int DESP_V = PADDING_OUT;
|
||||
|
||||
// Offset
|
||||
const auto TRAVEL_DIST = HEIGHT + PADDING_OUT;
|
||||
const int TRAVEL_MOD = 1;
|
||||
const int OFFSET = !notifications_.empty() ? notifications_.back().y + (TRAVEL_MOD * notifications_.back().travel_dist) : DESP_V;
|
||||
|
||||
// Crea la notificacion
|
||||
Notification n;
|
||||
|
||||
// Inicializa variables
|
||||
n.code = code;
|
||||
n.can_be_removed = can_be_removed;
|
||||
n.y = OFFSET;
|
||||
n.travel_dist = TRAVEL_DIST;
|
||||
n.texts = texts;
|
||||
n.shape = SHAPE;
|
||||
n.display_duration = style.duration;
|
||||
const float Y_POS = OFFSET + -TRAVEL_DIST;
|
||||
n.rect = {.x = desp_h, .y = Y_POS, .w = WIDTH, .h = HEIGHT};
|
||||
|
||||
// Crea la textura
|
||||
n.surface = std::make_shared<Surface>(WIDTH, HEIGHT);
|
||||
|
||||
// Prepara para dibujar en la textura
|
||||
auto previuos_renderer = Screen::get()->getRendererSurface();
|
||||
Screen::get()->setRendererSurface(n.surface);
|
||||
|
||||
// Dibuja el fondo de la notificación
|
||||
SDL_FRect rect;
|
||||
if (SHAPE == Shape::ROUNDED) {
|
||||
rect = {.x = 4, .y = 0, .w = WIDTH - (4 * 2), .h = HEIGHT};
|
||||
n.surface->fillRect(&rect, style.bg_color);
|
||||
|
||||
rect = {.x = 4 / 2, .y = 1, .w = WIDTH - 4, .h = HEIGHT - 2};
|
||||
n.surface->fillRect(&rect, style.bg_color);
|
||||
|
||||
rect = {.x = 1, .y = 4 / 2, .w = WIDTH - 2, .h = HEIGHT - 4};
|
||||
n.surface->fillRect(&rect, style.bg_color);
|
||||
|
||||
rect = {.x = 0, .y = 4, .w = WIDTH, .h = HEIGHT - (4 * 2)};
|
||||
n.surface->fillRect(&rect, style.bg_color);
|
||||
}
|
||||
|
||||
else if (SHAPE == Shape::SQUARED) {
|
||||
n.surface->clear(style.bg_color);
|
||||
SDL_FRect squared_rect = {0, 0, n.surface->getWidth(), n.surface->getHeight()};
|
||||
n.surface->drawRectBorder(&squared_rect, style.border_color);
|
||||
}
|
||||
|
||||
// Dibuja el icono de la notificación
|
||||
if (has_icons_ && icon >= 0 && texts.size() >= 2) {
|
||||
auto sp = std::make_unique<SurfaceSprite>(icon_surface_, (SDL_FRect){0, 0, ICON_SIZE, ICON_SIZE});
|
||||
sp->setPosition({PADDING_IN_H, PADDING_IN_V, ICON_SIZE, ICON_SIZE});
|
||||
sp->setClip((SDL_FRect){ICON_SIZE * (icon % 10), ICON_SIZE * (icon / 10), ICON_SIZE, ICON_SIZE});
|
||||
sp->render();
|
||||
}
|
||||
|
||||
// Escribe el texto de la notificación
|
||||
const auto COLOR = style.text_color;
|
||||
int iterator = 0;
|
||||
for (const auto& text : texts) {
|
||||
switch (TEXT_IS) {
|
||||
case TextAlign::LEFT:
|
||||
text_->writeColored(PADDING_IN_H + ICON_SPACE, PADDING_IN_V + (iterator * (TEXT_SIZE + 1)), text, COLOR);
|
||||
break;
|
||||
case TextAlign::CENTER:
|
||||
text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, WIDTH / 2, PADDING_IN_V + (iterator * (TEXT_SIZE + 1)), text, 1, COLOR);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
++iterator;
|
||||
}
|
||||
|
||||
// Deja de dibujar en la textura
|
||||
Screen::get()->setRendererSurface(previuos_renderer);
|
||||
|
||||
// Crea el sprite de la notificación
|
||||
n.sprite = std::make_shared<SurfaceSprite>(n.surface, n.rect);
|
||||
|
||||
// Añade la notificación a la lista
|
||||
notifications_.emplace_back(n);
|
||||
|
||||
// Reproduce el sonido de la notificación
|
||||
if (style.play_sound && !style.sound_file.empty()) {
|
||||
Audio::get()->playSound(style.sound_file, Audio::Group::INTERFACE);
|
||||
}
|
||||
}
|
||||
|
||||
// Indica si hay notificaciones activas
|
||||
auto Notifier::isActive() -> bool { return !notifications_.empty(); }
|
||||
|
||||
// Finaliza y elimnina todas las notificaciones activas
|
||||
void Notifier::clearNotifications() {
|
||||
for (auto& notification : notifications_) {
|
||||
if (notification.can_be_removed) {
|
||||
notification.state = Status::FINISHED;
|
||||
}
|
||||
}
|
||||
|
||||
clearFinishedNotifications();
|
||||
}
|
||||
|
||||
// Obtiene los códigos de las notificaciones
|
||||
auto Notifier::getCodes() -> std::vector<std::string> {
|
||||
std::vector<std::string> codes;
|
||||
codes.reserve(notifications_.size());
|
||||
for (const auto& notification : notifications_) {
|
||||
codes.emplace_back(notification.code);
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
110
source/game/ui/notifier.hpp
Normal file
110
source/game/ui/notifier.hpp
Normal file
@@ -0,0 +1,110 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string, basic_string
|
||||
#include <vector> // Para vector
|
||||
class SurfaceSprite; // lines 8-8
|
||||
class Surface; // lines 10-10
|
||||
class Text; // lines 9-9
|
||||
class DeltaTimer; // lines 11-11
|
||||
|
||||
class Notifier {
|
||||
public:
|
||||
// Justificado para las notificaciones
|
||||
enum class TextAlign {
|
||||
LEFT,
|
||||
CENTER,
|
||||
};
|
||||
|
||||
// Forma de las notificaciones
|
||||
enum class Shape {
|
||||
ROUNDED,
|
||||
SQUARED,
|
||||
};
|
||||
|
||||
// Estilo de notificación
|
||||
struct Style {
|
||||
Uint8 bg_color; // Color de fondo
|
||||
Uint8 border_color; // Color del borde
|
||||
Uint8 text_color; // Color del texto
|
||||
Shape shape; // Forma (ROUNDED/SQUARED)
|
||||
TextAlign text_align; // Alineación del texto
|
||||
float duration; // Duración en segundos
|
||||
std::string sound_file; // Archivo de sonido (vacío = sin sonido)
|
||||
bool play_sound; // Si reproduce sonido
|
||||
|
||||
// Estilos predefinidos
|
||||
static const Style DEFAULT;
|
||||
static const Style CHEEVO;
|
||||
};
|
||||
|
||||
// Gestión singleton
|
||||
static void init(const std::string& icon_file, const std::string& text); // Inicialización
|
||||
static void destroy(); // Destrucción
|
||||
static auto get() -> Notifier*; // Acceso al singleton
|
||||
|
||||
// Métodos principales
|
||||
void render(); // Renderizado
|
||||
void update(float delta_time); // Actualización lógica
|
||||
void show(
|
||||
std::vector<std::string> texts,
|
||||
const Style& style = Style::DEFAULT,
|
||||
int icon = -1,
|
||||
bool can_be_removed = true,
|
||||
const std::string& code = std::string()); // Mostrar notificación
|
||||
|
||||
// Consultas
|
||||
auto isActive() -> bool; // Indica si hay notificaciones activas
|
||||
auto getCodes() -> std::vector<std::string>; // Obtiene códigos de notificaciones
|
||||
|
||||
private:
|
||||
// Tipos anidados
|
||||
enum class Status {
|
||||
RISING,
|
||||
STAY,
|
||||
VANISHING,
|
||||
FINISHED,
|
||||
};
|
||||
|
||||
struct Notification {
|
||||
std::shared_ptr<Surface> surface{nullptr};
|
||||
std::shared_ptr<SurfaceSprite> sprite{nullptr};
|
||||
std::vector<std::string> texts;
|
||||
Status state{Status::RISING};
|
||||
Shape shape{Shape::SQUARED};
|
||||
SDL_FRect rect{0.0F, 0.0F, 0.0F, 0.0F};
|
||||
int y{0};
|
||||
int travel_dist{0};
|
||||
std::string code;
|
||||
bool can_be_removed{true};
|
||||
int height{0};
|
||||
float elapsed_time{0.0F};
|
||||
float display_duration{0.0F};
|
||||
};
|
||||
|
||||
// Constantes
|
||||
static constexpr float ICON_SIZE = 16.0F;
|
||||
static constexpr float PADDING_OUT = 0.0F;
|
||||
static constexpr float SLIDE_SPEED = 120.0F; // Pixels per second for slide animations
|
||||
|
||||
// [SINGLETON] Objeto notifier
|
||||
static Notifier* notifier;
|
||||
|
||||
// Métodos privados
|
||||
void clearFinishedNotifications(); // Elimina las notificaciones finalizadas
|
||||
void clearNotifications(); // Finaliza y elimina todas las notificaciones activas
|
||||
|
||||
// Constructor y destructor privados [SINGLETON]
|
||||
Notifier(const std::string& icon_file, const std::string& text);
|
||||
~Notifier() = default;
|
||||
|
||||
// Variables miembro
|
||||
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos
|
||||
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer for frame-independent animations
|
||||
std::vector<Notification> notifications_; // Lista de notificaciones activas
|
||||
bool stack_{false}; // Indica si las notificaciones se apilan
|
||||
bool has_icons_{false}; // Indica si el notificador tiene textura para iconos
|
||||
};
|
||||
23
source/main.cpp
Normal file
23
source/main.cpp
Normal file
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
|
||||
Código fuente creado por JailDesigner
|
||||
Empezado en Castalla el 01/07/2022.
|
||||
|
||||
*/
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "core/system/director.hpp"
|
||||
|
||||
auto main(int argc, char* argv[]) -> int {
|
||||
// Convierte argumentos a formato moderno C++
|
||||
std::vector<std::string> args(argv, argv + argc);
|
||||
|
||||
// Crea el objeto Director
|
||||
auto director = std::make_unique<Director>(args);
|
||||
|
||||
// Bucle principal
|
||||
return Director::run();
|
||||
}
|
||||
9
source/project.h
Normal file
9
source/project.h
Normal file
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
namespace Project {
|
||||
constexpr const char* NAME = "pollo";
|
||||
constexpr const char* LONG_NAME = "Los pollos hermanos";
|
||||
constexpr const char* VERSION = "0.1";
|
||||
constexpr const char* COPYRIGHT = "@2025 JailDesigner";
|
||||
constexpr const char* GIT_HASH = "e397f0a";
|
||||
} // namespace Project
|
||||
9
source/project.h.in
Normal file
9
source/project.h.in
Normal file
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
namespace Project {
|
||||
constexpr const char* NAME = "@PROJECT_NAME@";
|
||||
constexpr const char* LONG_NAME = "@PROJECT_LONG_NAME@";
|
||||
constexpr const char* VERSION = "@PROJECT_VERSION@";
|
||||
constexpr const char* COPYRIGHT = "@PROJECT_COPYRIGHT@";
|
||||
constexpr const char* GIT_HASH = "@GIT_HASH@";
|
||||
} // namespace Project
|
||||
57
source/utils/color.cpp
Normal file
57
source/utils/color.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @file color.cpp
|
||||
* @brief Implementación de la gestión de colores de la paleta Amstrad CPC
|
||||
*/
|
||||
|
||||
#include "color.hpp"
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
auto Color::fromString(const std::string& name) -> Uint8 {
|
||||
// Mapa de nombres de colores a índices de paleta
|
||||
// Incluye nombres oficiales del CPC y aliases para compatibilidad
|
||||
static const std::unordered_map<std::string, Uint8> COLOR_MAP = {
|
||||
// Transparente
|
||||
{"transparent", index(Cpc::TRANSPARENT)},
|
||||
|
||||
// Colores oficiales Amstrad CPC
|
||||
{"black", index(Cpc::BLACK)},
|
||||
{"blue", index(Cpc::BLUE)},
|
||||
{"bright_blue", index(Cpc::BRIGHT_BLUE)},
|
||||
{"red", index(Cpc::RED)},
|
||||
{"magenta", index(Cpc::MAGENTA)},
|
||||
{"mauve", index(Cpc::MAUVE)},
|
||||
{"bright_red", index(Cpc::BRIGHT_RED)},
|
||||
{"purple", index(Cpc::PURPLE)},
|
||||
{"bright_magenta", index(Cpc::BRIGHT_MAGENTA)},
|
||||
{"green", index(Cpc::GREEN)},
|
||||
{"cyan", index(Cpc::CYAN)},
|
||||
{"sky_blue", index(Cpc::SKY_BLUE)},
|
||||
{"yellow", index(Cpc::YELLOW)},
|
||||
{"white", index(Cpc::WHITE)},
|
||||
{"pastel_blue", index(Cpc::PASTEL_BLUE)},
|
||||
{"orange", index(Cpc::ORANGE)},
|
||||
{"pink", index(Cpc::PINK)},
|
||||
{"pastel_magenta", index(Cpc::PASTEL_MAGENTA)},
|
||||
{"bright_green", index(Cpc::BRIGHT_GREEN)},
|
||||
{"sea_green", index(Cpc::SEA_GREEN)},
|
||||
{"bright_cyan", index(Cpc::BRIGHT_CYAN)},
|
||||
{"lime", index(Cpc::LIME)},
|
||||
{"pastel_green", index(Cpc::PASTEL_GREEN)},
|
||||
{"pastel_cyan", index(Cpc::PASTEL_CYAN)},
|
||||
{"bright_yellow", index(Cpc::BRIGHT_YELLOW)},
|
||||
{"pastel_yellow", index(Cpc::PASTEL_YELLOW)},
|
||||
{"bright_white", index(Cpc::BRIGHT_WHITE)},
|
||||
|
||||
// Aliases para compatibilidad con archivos YAML existentes (Spectrum)
|
||||
{"bright_black", index(Cpc::BLACK)}, // No existe en CPC, mapea a negro
|
||||
};
|
||||
|
||||
auto it = COLOR_MAP.find(name);
|
||||
if (it != COLOR_MAP.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
// Si no se encuentra, devuelve negro por defecto
|
||||
return index(Cpc::BLACK);
|
||||
}
|
||||
94
source/utils/color.hpp
Normal file
94
source/utils/color.hpp
Normal file
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* @file color.hpp
|
||||
* @brief Gestión de colores de la paleta Amstrad CPC
|
||||
*/
|
||||
|
||||
#ifndef COLOR_HPP
|
||||
#define COLOR_HPP
|
||||
|
||||
#include <SDL2/SDL_stdinc.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @class Color
|
||||
* @brief Clase para gestionar los colores de la paleta Amstrad CPC
|
||||
*
|
||||
* La paleta del Amstrad CPC tiene 27 colores únicos organizados en un sistema
|
||||
* de 3 niveles de intensidad (0, 128, 255) para cada componente RGB.
|
||||
*/
|
||||
class Color {
|
||||
public:
|
||||
/**
|
||||
* @enum Cpc
|
||||
* @brief Índices de los colores de la paleta Amstrad CPC
|
||||
*
|
||||
* Los nombres corresponden a los colores oficiales documentados por Amstrad.
|
||||
* El índice 0 está reservado para transparencia.
|
||||
*/
|
||||
enum class Cpc : Uint8 {
|
||||
// Transparente (índice 0)
|
||||
TRANSPARENT = 0,
|
||||
|
||||
// Negros y azules (R=0)
|
||||
BLACK = 1, // 0, 0, 0
|
||||
BLUE = 2, // 0, 0, 128
|
||||
BRIGHT_BLUE = 3, // 0, 0, 255
|
||||
|
||||
// Rojos y magentas (G=0)
|
||||
RED = 4, // 128, 0, 0
|
||||
MAGENTA = 5, // 128, 0, 128
|
||||
MAUVE = 6, // 128, 0, 255
|
||||
BRIGHT_RED = 7, // 255, 0, 0
|
||||
PURPLE = 8, // 255, 0, 128
|
||||
BRIGHT_MAGENTA = 9, // 255, 0, 255
|
||||
|
||||
// Verdes y cianes (R=0, G>0)
|
||||
GREEN = 10, // 0, 128, 0
|
||||
CYAN = 11, // 0, 128, 128
|
||||
SKY_BLUE = 12, // 0, 128, 255
|
||||
|
||||
// Amarillos y blancos medios (G=128)
|
||||
YELLOW = 13, // 128, 128, 0
|
||||
WHITE = 14, // 128, 128, 128
|
||||
PASTEL_BLUE = 15, // 128, 128, 255
|
||||
|
||||
// Naranjas y rosas (R=255, G=128)
|
||||
ORANGE = 16, // 255, 128, 0
|
||||
PINK = 17, // 255, 128, 128
|
||||
PASTEL_MAGENTA = 18, // 255, 128, 255
|
||||
|
||||
// Verdes brillantes (G=255)
|
||||
BRIGHT_GREEN = 19, // 0, 255, 0
|
||||
SEA_GREEN = 20, // 0, 255, 128
|
||||
BRIGHT_CYAN = 21, // 0, 255, 255
|
||||
|
||||
// Limas y pasteles verdes (G=255)
|
||||
LIME = 22, // 128, 255, 0
|
||||
PASTEL_GREEN = 23, // 128, 255, 128
|
||||
PASTEL_CYAN = 24, // 128, 255, 255
|
||||
|
||||
// Amarillos brillantes y blancos (R=255, G=255)
|
||||
BRIGHT_YELLOW = 25, // 255, 255, 0
|
||||
PASTEL_YELLOW = 26, // 255, 255, 128
|
||||
BRIGHT_WHITE = 27 // 255, 255, 255
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Obtiene el índice de paleta de un color CPC
|
||||
* @param color Color del enum Cpc
|
||||
* @return Índice de paleta (Uint8)
|
||||
*/
|
||||
static constexpr auto index(Cpc color) -> Uint8 {
|
||||
return static_cast<Uint8>(color);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Convierte un nombre de color (string) a índice de paleta
|
||||
* @param name Nombre del color en minúsculas (ej: "cyan", "bright_blue")
|
||||
* @return Índice de paleta, o 1 (BLACK) si no se encuentra
|
||||
*/
|
||||
static auto fromString(const std::string& name) -> Uint8;
|
||||
};
|
||||
|
||||
#endif // COLOR_HPP
|
||||
72
source/utils/defines.hpp
Normal file
72
source/utils/defines.hpp
Normal file
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
// Tamaño de bloque
|
||||
namespace Tile {
|
||||
constexpr int SIZE = 8;
|
||||
constexpr int HALF_SIZE = SIZE / 2;
|
||||
} // namespace Tile
|
||||
|
||||
namespace GameCanvas {
|
||||
constexpr int WIDTH = 320;
|
||||
constexpr int HEIGHT = 240;
|
||||
constexpr int CENTER_X = WIDTH / 2;
|
||||
constexpr int FIRST_QUARTER_X = WIDTH / 4;
|
||||
constexpr int THIRD_QUARTER_X = (WIDTH / 4) * 3;
|
||||
constexpr int CENTER_Y = HEIGHT / 2;
|
||||
constexpr int FIRST_QUARTER_Y = HEIGHT / 4;
|
||||
constexpr int THIRD_QUARTER_Y = (HEIGHT / 4) * 3;
|
||||
} // namespace GameCanvas
|
||||
|
||||
namespace PlayArea {
|
||||
// Origen (esquina superior izquierda)
|
||||
constexpr int X = 0;
|
||||
constexpr int Y = 0;
|
||||
|
||||
// Dimensiones en tiles
|
||||
constexpr int TILE_COLS = 40; // Ancho del mapa en tiles
|
||||
constexpr int TILE_ROWS = 24; // Alto del mapa en tiles
|
||||
constexpr int TILE_COUNT = TILE_COLS * TILE_ROWS; // 960 tiles totales
|
||||
|
||||
// Dimensiones en pixels
|
||||
constexpr int WIDTH = TILE_COLS * Tile::SIZE; // 320
|
||||
constexpr int HEIGHT = TILE_ROWS * Tile::SIZE; // 192
|
||||
|
||||
// Bordes (derivados, útiles para colisiones)
|
||||
constexpr int LEFT = X;
|
||||
constexpr int TOP = Y;
|
||||
constexpr int RIGHT = X + WIDTH; // 320
|
||||
constexpr int BOTTOM = Y + HEIGHT; // 192
|
||||
|
||||
// Puntos de referencia
|
||||
constexpr int CENTER_X = X + (WIDTH / 2); // 160
|
||||
constexpr int CENTER_Y = Y + (HEIGHT / 2); // 96
|
||||
constexpr int QUARTER_X = WIDTH / 4;
|
||||
constexpr int QUARTER_Y = HEIGHT / 4;
|
||||
} // namespace PlayArea
|
||||
|
||||
namespace ScoreboardArea {
|
||||
// Origen (justo debajo de PlayArea)
|
||||
constexpr int X = 0;
|
||||
constexpr int Y = PlayArea::BOTTOM; // 192
|
||||
|
||||
// Dimensiones
|
||||
constexpr int WIDTH = GameCanvas::WIDTH; // 320
|
||||
constexpr int HEIGHT = (6 * Tile::SIZE); // 48
|
||||
|
||||
// Bordes
|
||||
constexpr int LEFT = X;
|
||||
constexpr int TOP = Y;
|
||||
constexpr int RIGHT = X + WIDTH;
|
||||
constexpr int BOTTOM = Y + HEIGHT; // 240
|
||||
} // namespace ScoreboardArea
|
||||
|
||||
namespace Collision {
|
||||
constexpr int NONE = -1;
|
||||
} // namespace Collision
|
||||
|
||||
namespace Flip {
|
||||
constexpr SDL_FlipMode LEFT = SDL_FLIP_HORIZONTAL;
|
||||
constexpr SDL_FlipMode RIGHT = SDL_FLIP_NONE;
|
||||
} // namespace Flip
|
||||
38
source/utils/delta_timer.cpp
Normal file
38
source/utils/delta_timer.cpp
Normal file
@@ -0,0 +1,38 @@
|
||||
#include "utils/delta_timer.hpp"
|
||||
|
||||
DeltaTimer::DeltaTimer() noexcept
|
||||
: last_counter_(SDL_GetPerformanceCounter()),
|
||||
perf_freq_(static_cast<double>(SDL_GetPerformanceFrequency())),
|
||||
time_scale_(1.0F) {
|
||||
}
|
||||
|
||||
auto DeltaTimer::tick() noexcept -> float {
|
||||
const Uint64 NOW = SDL_GetPerformanceCounter();
|
||||
const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
|
||||
last_counter_ = NOW;
|
||||
const double SECONDS = static_cast<double>(DIFF) / perf_freq_;
|
||||
return static_cast<float>(SECONDS * static_cast<double>(time_scale_));
|
||||
}
|
||||
|
||||
auto DeltaTimer::peek() const noexcept -> float {
|
||||
const Uint64 NOW = SDL_GetPerformanceCounter();
|
||||
const Uint64 DIFF = (NOW > last_counter_) ? (NOW - last_counter_) : 0;
|
||||
const double SECONDS = static_cast<double>(DIFF) / perf_freq_;
|
||||
return static_cast<float>(SECONDS * static_cast<double>(time_scale_));
|
||||
}
|
||||
|
||||
void DeltaTimer::reset(Uint64 counter) noexcept {
|
||||
if (counter == 0) {
|
||||
last_counter_ = SDL_GetPerformanceCounter();
|
||||
} else {
|
||||
last_counter_ = counter;
|
||||
}
|
||||
}
|
||||
|
||||
void DeltaTimer::setTimeScale(float scale) noexcept {
|
||||
time_scale_ = std::max(scale, 0.0F);
|
||||
}
|
||||
|
||||
auto DeltaTimer::getTimeScale() const noexcept -> float {
|
||||
return time_scale_;
|
||||
}
|
||||
28
source/utils/delta_timer.hpp
Normal file
28
source/utils/delta_timer.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
class DeltaTimer {
|
||||
public:
|
||||
DeltaTimer() noexcept;
|
||||
|
||||
// Calcula delta en segundos y actualiza el contador interno
|
||||
auto tick() noexcept -> float;
|
||||
|
||||
// Devuelve el delta estimado desde el último tick sin actualizar el contador
|
||||
[[nodiscard]] auto peek() const noexcept -> float;
|
||||
|
||||
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
|
||||
void reset(Uint64 counter = 0) noexcept;
|
||||
|
||||
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
|
||||
void setTimeScale(float scale) noexcept;
|
||||
[[nodiscard]] auto getTimeScale() const noexcept -> float;
|
||||
|
||||
private:
|
||||
Uint64 last_counter_;
|
||||
double perf_freq_;
|
||||
float time_scale_;
|
||||
};
|
||||
251
source/utils/easing_functions.hpp
Normal file
251
source/utils/easing_functions.hpp
Normal file
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* @file easing_functions.hpp
|
||||
* @brief Colección de funciones de suavizado (easing) para animaciones
|
||||
*
|
||||
* Todas las funciones toman un parámetro t (0.0 a 1.0) que representa
|
||||
* el progreso de la animación y retornan el valor suavizado.
|
||||
*
|
||||
* Convenciones:
|
||||
* - In: Aceleración (slow -> fast)
|
||||
* - Out: Desaceleración (fast -> slow)
|
||||
* - InOut: Aceleración + Desaceleración (slow -> fast -> slow)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.14159265358979323846
|
||||
#endif
|
||||
|
||||
namespace Easing {
|
||||
|
||||
// LINEAR
|
||||
inline auto linear(float t) -> float {
|
||||
return t;
|
||||
}
|
||||
|
||||
// QUAD (Cuadrática: t^2)
|
||||
inline auto quadIn(float t) -> float {
|
||||
return t * t;
|
||||
}
|
||||
|
||||
inline auto quadOut(float t) -> float {
|
||||
return t * (2.0F - t);
|
||||
}
|
||||
|
||||
inline auto quadInOut(float t) -> float {
|
||||
if (t < 0.5F) {
|
||||
return 2.0F * t * t;
|
||||
}
|
||||
return -1.0F + ((4.0F - 2.0F * t) * t);
|
||||
}
|
||||
|
||||
// CUBIC (Cúbica: t^3)
|
||||
inline auto cubicIn(float t) -> float {
|
||||
return t * t * t;
|
||||
}
|
||||
|
||||
inline auto cubicOut(float t) -> float {
|
||||
const float F = t - 1.0F;
|
||||
return (F * F * F) + 1.0F;
|
||||
}
|
||||
|
||||
inline auto cubicInOut(float t) -> float {
|
||||
if (t < 0.5F) {
|
||||
return 4.0F * t * t * t;
|
||||
}
|
||||
const float F = ((2.0F * t) - 2.0F);
|
||||
return (0.5F * F * F * F) + 1.0F;
|
||||
}
|
||||
|
||||
// QUART (Cuártica: t^4)
|
||||
inline auto quartIn(float t) -> float {
|
||||
return t * t * t * t;
|
||||
}
|
||||
|
||||
inline auto quartOut(float t) -> float {
|
||||
const float F = t - 1.0F;
|
||||
return 1.0F - (F * F * F * F);
|
||||
}
|
||||
|
||||
inline auto quartInOut(float t) -> float {
|
||||
if (t < 0.5F) {
|
||||
return 8.0F * t * t * t * t;
|
||||
}
|
||||
const float F = t - 1.0F;
|
||||
return 1.0F - (8.0F * F * F * F * F);
|
||||
}
|
||||
|
||||
// QUINT (Quíntica: t^5)
|
||||
inline auto quintIn(float t) -> float {
|
||||
return t * t * t * t * t;
|
||||
}
|
||||
|
||||
inline auto quintOut(float t) -> float {
|
||||
const float F = t - 1.0F;
|
||||
return (F * F * F * F * F) + 1.0F;
|
||||
}
|
||||
|
||||
inline auto quintInOut(float t) -> float {
|
||||
if (t < 0.5F) {
|
||||
return 16.0F * t * t * t * t * t;
|
||||
}
|
||||
const float F = ((2.0F * t) - 2.0F);
|
||||
return (0.5F * F * F * F * F * F) + 1.0F;
|
||||
}
|
||||
|
||||
// SINE (Sinusoidal)
|
||||
inline auto sineIn(float t) -> float {
|
||||
return 1.0F - std::cos(t * std::numbers::pi_v<float> * 0.5F);
|
||||
}
|
||||
|
||||
inline auto sineOut(float t) -> float {
|
||||
return std::sin(t * std::numbers::pi_v<float> * 0.5F);
|
||||
}
|
||||
|
||||
inline auto sineInOut(float t) -> float {
|
||||
return 0.5F * (1.0F - std::cos(std::numbers::pi_v<float> * t));
|
||||
}
|
||||
|
||||
// EXPO (Exponencial)
|
||||
inline auto expoIn(float t) -> float {
|
||||
if (t == 0.0F) {
|
||||
return 0.0F;
|
||||
}
|
||||
return std::pow(2.0F, 10.0F * (t - 1.0F));
|
||||
}
|
||||
|
||||
inline auto expoOut(float t) -> float {
|
||||
if (t == 1.0F) {
|
||||
return 1.0F;
|
||||
}
|
||||
return 1.0F - std::pow(2.0F, -10.0F * t);
|
||||
}
|
||||
|
||||
inline auto expoInOut(float t) -> float {
|
||||
if (t == 0.0F || t == 1.0F) {
|
||||
return t;
|
||||
}
|
||||
|
||||
if (t < 0.5F) {
|
||||
return 0.5F * std::pow(2.0F, (20.0F * t) - 10.0F);
|
||||
}
|
||||
return 0.5F * (2.0F - std::pow(2.0F, (-20.0F * t) + 10.0F));
|
||||
}
|
||||
|
||||
// CIRC (Circular)
|
||||
inline auto circIn(float t) -> float {
|
||||
return 1.0F - std::sqrt(1.0F - (t * t));
|
||||
}
|
||||
|
||||
inline auto circOut(float t) -> float {
|
||||
const float F = t - 1.0F;
|
||||
return std::sqrt(1.0F - (F * F));
|
||||
}
|
||||
|
||||
inline auto circInOut(float t) -> float {
|
||||
if (t < 0.5F) {
|
||||
return 0.5F * (1.0F - std::sqrt(1.0F - (4.0F * t * t)));
|
||||
}
|
||||
const float F = (2.0F * t) - 2.0F;
|
||||
return 0.5F * (std::sqrt(1.0F - (F * F)) + 1.0F);
|
||||
}
|
||||
|
||||
// BACK (Overshoot - retrocede antes de avanzar)
|
||||
inline auto backIn(float t, float overshoot = 1.70158F) -> float {
|
||||
return t * t * ((overshoot + 1.0F) * t - overshoot);
|
||||
}
|
||||
|
||||
inline auto backOut(float t, float overshoot = 1.70158F) -> float {
|
||||
const float F = t - 1.0F;
|
||||
return (F * F * ((overshoot + 1.0F) * F + overshoot)) + 1.0F;
|
||||
}
|
||||
|
||||
inline auto backInOut(float t, float overshoot = 1.70158F) -> float {
|
||||
const float S = overshoot * 1.525F;
|
||||
|
||||
if (t < 0.5F) {
|
||||
const float F = 2.0F * t;
|
||||
return 0.5F * (F * F * ((S + 1.0F) * F - S));
|
||||
}
|
||||
|
||||
const float F = (2.0F * t) - 2.0F;
|
||||
return 0.5F * (F * F * ((S + 1.0F) * F + S) + 2.0F);
|
||||
}
|
||||
|
||||
// ELASTIC (Oscilación elástica - efecto de resorte)
|
||||
inline auto elasticIn(float t, float amplitude = 1.0F, float period = 0.3F) -> float {
|
||||
if (t == 0.0F || t == 1.0F) {
|
||||
return t;
|
||||
}
|
||||
|
||||
const float S = period / (2.0F * std::numbers::pi_v<float>)*std::asin(1.0F / amplitude);
|
||||
const float F = t - 1.0F;
|
||||
return -(amplitude * std::pow(2.0F, 10.0F * F) *
|
||||
std::sin((F - S) * (2.0F * std::numbers::pi_v<float>) / period));
|
||||
}
|
||||
|
||||
inline auto elasticOut(float t, float amplitude = 1.0F, float period = 0.3F) -> float {
|
||||
if (t == 0.0F || t == 1.0F) {
|
||||
return t;
|
||||
}
|
||||
|
||||
const float S = period / (2.0F * std::numbers::pi_v<float>)*std::asin(1.0F / amplitude);
|
||||
return (amplitude * std::pow(2.0F, -10.0F * t) *
|
||||
std::sin((t - S) * (2.0F * std::numbers::pi_v<float>) / period)) +
|
||||
1.0F;
|
||||
}
|
||||
|
||||
inline auto elasticInOut(float t, float amplitude = 1.0F, float period = 0.3F) -> float {
|
||||
if (t == 0.0F || t == 1.0F) {
|
||||
return t;
|
||||
}
|
||||
|
||||
const float S = period / (2.0F * std::numbers::pi_v<float>)*std::asin(1.0F / amplitude);
|
||||
|
||||
if (t < 0.5F) {
|
||||
const float F = (2.0F * t) - 1.0F;
|
||||
return -0.5F * (amplitude * std::pow(2.0F, 10.0F * F) * std::sin((F - S) * (2.0F * std::numbers::pi_v<float>) / period));
|
||||
}
|
||||
|
||||
const float F = (2.0F * t) - 1.0F;
|
||||
return (0.5F * amplitude * std::pow(2.0F, -10.0F * F) *
|
||||
std::sin((F - S) * (2.0F * std::numbers::pi_v<float>) / period)) +
|
||||
1.0F;
|
||||
}
|
||||
|
||||
// BOUNCE (Rebote - simula física de rebote)
|
||||
inline auto bounceOut(float t) -> float {
|
||||
const float N1 = 7.5625F;
|
||||
const float D1 = 2.75F;
|
||||
|
||||
if (t < 1.0F / D1) {
|
||||
return N1 * t * t;
|
||||
}
|
||||
if (t < 2.0F / D1) {
|
||||
const float F = t - (1.5F / D1);
|
||||
return (N1 * F * F) + 0.75F;
|
||||
}
|
||||
if (t < 2.5F / D1) {
|
||||
const float F = t - (2.25F / D1);
|
||||
return (N1 * F * F) + 0.9375F;
|
||||
}
|
||||
const float F = t - (2.625F / D1);
|
||||
return (N1 * F * F) + 0.984375F;
|
||||
}
|
||||
|
||||
inline auto bounceIn(float t) -> float {
|
||||
return 1.0F - bounceOut(1.0F - t);
|
||||
}
|
||||
|
||||
inline auto bounceInOut(float t) -> float {
|
||||
if (t < 0.5F) {
|
||||
return 0.5F * bounceIn(2.0F * t);
|
||||
}
|
||||
return (0.5F * bounceOut((2.0F * t) - 1.0F)) + 0.5F;
|
||||
}
|
||||
|
||||
} // namespace Easing
|
||||
367
source/utils/utils.cpp
Normal file
367
source/utils/utils.cpp
Normal file
@@ -0,0 +1,367 @@
|
||||
#include "utils/utils.hpp"
|
||||
|
||||
#include <algorithm> // Para find, transform
|
||||
#include <cctype> // Para tolower
|
||||
#include <cmath> // Para round, abs
|
||||
#include <cstdlib> // Para abs
|
||||
#include <exception> // Para exception
|
||||
#include <filesystem> // Para path
|
||||
#include <iostream> // Para basic_ostream, cout, basic_ios, ios, endl
|
||||
#include <string> // Para basic_string, string, char_traits, allocator
|
||||
#include <unordered_map> // Para unordered_map, operator==, _Node_const_iter...
|
||||
#include <utility> // Para pair
|
||||
|
||||
#include "core/resources/resource_cache.hpp" // Para Resource
|
||||
#include "utils/color.hpp" // Para Color
|
||||
|
||||
// Calcula el cuadrado de la distancia entre dos puntos
|
||||
auto distanceSquared(int x1, int y1, int x2, int y2) -> double {
|
||||
const int DELTA_X = x2 - x1;
|
||||
const int DELTA_Y = y2 - y1;
|
||||
return (DELTA_X * DELTA_X) + (DELTA_Y * DELTA_Y);
|
||||
}
|
||||
|
||||
// Detector de colisiones entre dos circulos
|
||||
auto checkCollision(const Circle& a, const Circle& b) -> bool {
|
||||
// Calcula el radio total al cuadrado
|
||||
int total_radius_squared = a.r + b.r;
|
||||
total_radius_squared = total_radius_squared * total_radius_squared;
|
||||
|
||||
// Si la distancia entre el centro de los circulos es inferior a la suma de sus radios
|
||||
return distanceSquared(a.x, a.y, b.x, b.y) < total_radius_squared;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre un circulo y un rectangulo
|
||||
auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool {
|
||||
SDL_Rect b = toSDLRect(rect);
|
||||
// Closest point on collision box
|
||||
int c_x;
|
||||
int c_y;
|
||||
|
||||
// Find closest x offset
|
||||
if (a.x < b.x) {
|
||||
c_x = b.x;
|
||||
} else if (a.x > b.x + b.w) {
|
||||
c_x = b.x + b.w;
|
||||
} else {
|
||||
c_x = a.x;
|
||||
}
|
||||
|
||||
// Find closest y offset
|
||||
if (a.y < b.y) {
|
||||
c_y = b.y;
|
||||
} else if (a.y > b.y + b.h) {
|
||||
c_y = b.y + b.h;
|
||||
} else {
|
||||
c_y = a.y;
|
||||
}
|
||||
|
||||
// If the closest point is inside the circle_t
|
||||
if (distanceSquared(a.x, a.y, c_x, c_y) < a.r * a.r) {
|
||||
// This box and the circle_t have collided
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the shapes have not collided
|
||||
return false;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre dos rectangulos
|
||||
auto checkCollision(const SDL_FRect& rect_a, const SDL_FRect& rect_b) -> bool {
|
||||
SDL_Rect a = toSDLRect(rect_a);
|
||||
SDL_Rect b = toSDLRect(rect_b);
|
||||
// Calcula las caras del rectangulo a
|
||||
const int LEFT_A = a.x;
|
||||
const int RIGHT_A = a.x + a.w;
|
||||
const int TOP_A = a.y;
|
||||
const int BOTTOM_A = a.y + a.h;
|
||||
|
||||
// Calcula las caras del rectangulo b
|
||||
const int LEFT_B = b.x;
|
||||
const int RIGHT_B = b.x + b.w;
|
||||
const int TOP_B = b.y;
|
||||
const int BOTTOM_B = b.y + b.h;
|
||||
|
||||
// Si cualquiera de las caras de a está fuera de b
|
||||
if (BOTTOM_A <= TOP_B) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TOP_A >= BOTTOM_B) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (RIGHT_A <= LEFT_B) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (LEFT_A >= RIGHT_B) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Si ninguna de las caras está fuera de b
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre un punto y un rectangulo
|
||||
auto checkCollision(const SDL_FPoint& point, const SDL_FRect& rect) -> bool {
|
||||
SDL_Rect r = toSDLRect(rect);
|
||||
SDL_Point p = toSDLPoint(point);
|
||||
|
||||
// Comprueba si el punto está a la izquierda del rectangulo
|
||||
if (p.x < r.x) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el punto está a la derecha del rectangulo
|
||||
if (p.x > r.x + r.w) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el punto está por encima del rectangulo
|
||||
if (p.y < r.y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el punto está por debajo del rectangulo
|
||||
if (p.y > r.y + r.h) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Si no está fuera, es que está dentro
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre una linea horizontal y un rectangulo
|
||||
auto checkCollision(const LineHorizontal& l, const SDL_FRect& rect) -> bool {
|
||||
SDL_Rect r = toSDLRect(rect);
|
||||
// Comprueba si la linea esta por encima del rectangulo
|
||||
if (l.y < r.y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si la linea esta por debajo del rectangulo
|
||||
if (l.y >= r.y + r.h) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el inicio de la linea esta a la derecha del rectangulo
|
||||
if (l.x1 >= r.x + r.w) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el final de la linea esta a la izquierda del rectangulo
|
||||
if (l.x2 < r.x) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Si ha llegado hasta aquí, hay colisión
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre una linea vertical y un rectangulo
|
||||
auto checkCollision(const LineVertical& l, const SDL_FRect& rect) -> bool {
|
||||
SDL_Rect r = toSDLRect(rect);
|
||||
// Comprueba si la linea esta por la izquierda del rectangulo
|
||||
if (l.x < r.x) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si la linea esta por la derecha del rectangulo
|
||||
if (l.x >= r.x + r.w) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el inicio de la linea esta debajo del rectangulo
|
||||
if (l.y1 >= r.y + r.h) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el final de la linea esta encima del rectangulo
|
||||
if (l.y2 < r.y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Si ha llegado hasta aquí, hay colisión
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre una linea horizontal y un punto
|
||||
auto checkCollision(const LineHorizontal& l, const SDL_FPoint& point) -> bool {
|
||||
SDL_Point p = toSDLPoint(point);
|
||||
|
||||
// Comprueba si el punto esta sobre la linea
|
||||
if (p.y > l.y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el punto esta bajo la linea
|
||||
if (p.y < l.y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el punto esta a la izquierda de la linea
|
||||
if (p.x < l.x1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Comprueba si el punto esta a la derecha de la linea
|
||||
if (p.x > l.x2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Si ha llegado aquí, hay colisión
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detector de colisiones entre dos lineas
|
||||
auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point {
|
||||
const float X1 = l1.x1;
|
||||
const float Y1 = l1.y1;
|
||||
const float X2 = l1.x2;
|
||||
const float Y2 = l1.y2;
|
||||
|
||||
const float X3 = l2.x1;
|
||||
const float Y3 = l2.y1;
|
||||
const float X4 = l2.x2;
|
||||
const float Y4 = l2.y2;
|
||||
|
||||
// calculate the direction of the lines
|
||||
float u_a = ((X4 - X3) * (Y1 - Y3) - (Y4 - Y3) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1));
|
||||
float u_b = ((X2 - X1) * (Y1 - Y3) - (Y2 - Y1) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1));
|
||||
|
||||
// if uA and uB are between 0-1, lines are colliding
|
||||
if (u_a >= 0 && u_a <= 1 && u_b >= 0 && u_b <= 1) {
|
||||
// Calcula la intersección
|
||||
const float X = X1 + (u_a * (X2 - X1));
|
||||
const float Y = Y1 + (u_a * (Y2 - Y1));
|
||||
|
||||
return {static_cast<int>(std::round(X)), static_cast<int>(std::round(Y))};
|
||||
}
|
||||
return {-1, -1};
|
||||
}
|
||||
|
||||
// Convierte SDL_FRect a SDL_Rect
|
||||
auto toSDLRect(const SDL_FRect& frect) -> SDL_Rect {
|
||||
SDL_Rect rect = {
|
||||
.x = static_cast<int>(frect.x),
|
||||
.y = static_cast<int>(frect.y),
|
||||
.w = static_cast<int>(frect.w),
|
||||
.h = static_cast<int>(frect.h)};
|
||||
return rect;
|
||||
}
|
||||
|
||||
// Convierte SDL_FPoint a SDL_Point
|
||||
auto toSDLPoint(const SDL_FPoint& fpoint) -> SDL_Point {
|
||||
SDL_Point point = {
|
||||
.x = static_cast<int>(fpoint.x),
|
||||
.y = static_cast<int>(fpoint.y)};
|
||||
return point;
|
||||
}
|
||||
|
||||
// Convierte una cadena a un indice de la paleta
|
||||
auto stringToColor(const std::string& str) -> Uint8 {
|
||||
return Color::fromString(str);
|
||||
}
|
||||
|
||||
// Convierte una cadena a un entero de forma segura
|
||||
auto safeStoi(const std::string& value, int default_value) -> int {
|
||||
try {
|
||||
return std::stoi(value);
|
||||
} catch (const std::exception&) {
|
||||
return default_value;
|
||||
}
|
||||
}
|
||||
|
||||
// Convierte una cadena a un booleano
|
||||
auto stringToBool(const std::string& str) -> bool {
|
||||
std::string lower_str = str;
|
||||
std::ranges::transform(lower_str, lower_str.begin(), ::tolower);
|
||||
return (lower_str == "true" || lower_str == "1" || lower_str == "yes" || lower_str == "on");
|
||||
}
|
||||
|
||||
// Convierte un booleano a una cadena
|
||||
auto boolToString(bool value) -> std::string {
|
||||
return value ? "1" : "0";
|
||||
}
|
||||
|
||||
// Compara dos colores
|
||||
auto colorAreEqual(ColorRGB color1, ColorRGB color2) -> bool {
|
||||
const bool R = color1.r == color2.r;
|
||||
const bool G = color1.g == color2.g;
|
||||
const bool B = color1.b == color2.b;
|
||||
|
||||
return (R && G && B);
|
||||
}
|
||||
|
||||
// Función para convertir un string a minúsculas
|
||||
auto toLower(const std::string& str) -> std::string {
|
||||
std::string lower_str = str;
|
||||
std::ranges::transform(lower_str, lower_str.begin(), ::tolower);
|
||||
return lower_str;
|
||||
}
|
||||
|
||||
// Función para convertir un string a mayúsculas
|
||||
auto toUpper(const std::string& str) -> std::string {
|
||||
std::string upper_str = str;
|
||||
std::ranges::transform(upper_str, upper_str.begin(), ::toupper);
|
||||
return upper_str;
|
||||
}
|
||||
|
||||
// Obtiene el nombre de un fichero a partir de una ruta completa
|
||||
auto getFileName(const std::string& path) -> std::string {
|
||||
return std::filesystem::path(path).filename().string();
|
||||
}
|
||||
|
||||
// Obtiene la ruta eliminando el nombre del fichero
|
||||
auto getPath(const std::string& full_path) -> std::string {
|
||||
std::filesystem::path path(full_path);
|
||||
return path.parent_path().string();
|
||||
}
|
||||
|
||||
// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos
|
||||
void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3) {
|
||||
std::cout.setf(std::ios::left, std::ios::adjustfield);
|
||||
std::cout << text1;
|
||||
|
||||
std::cout.width(50 - text1.length() - text3.length());
|
||||
std::cout.fill('.');
|
||||
std::cout << text2;
|
||||
|
||||
std::cout << text3 << '\n';
|
||||
}
|
||||
|
||||
// Comprueba si una vector contiene una cadena
|
||||
auto stringInVector(const std::vector<std::string>& vec, const std::string& str) -> bool {
|
||||
return std::ranges::find(vec, str) != vec.end();
|
||||
}
|
||||
|
||||
// Rellena una textura de un color
|
||||
void fillTextureWithColor(SDL_Renderer* renderer, SDL_Texture* texture, Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
|
||||
// Guardar el render target actual
|
||||
SDL_Texture* previous_target = SDL_GetRenderTarget(renderer);
|
||||
|
||||
// Establecer la textura como el render target
|
||||
SDL_SetRenderTarget(renderer, texture);
|
||||
|
||||
// Establecer el color deseado
|
||||
SDL_SetRenderDrawColor(renderer, r, g, b, a);
|
||||
|
||||
// Pintar toda el área
|
||||
SDL_RenderClear(renderer);
|
||||
|
||||
// Restaurar el render target previo
|
||||
SDL_SetRenderTarget(renderer, previous_target);
|
||||
}
|
||||
|
||||
// Añade espacios entre las letras de un string
|
||||
auto spaceBetweenLetters(const std::string& input) -> std::string {
|
||||
std::string result;
|
||||
for (size_t i = 0; i < input.size(); ++i) {
|
||||
result += input[i];
|
||||
if (i != input.size() - 1) {
|
||||
result += ' ';
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
81
source/utils/utils.hpp
Normal file
81
source/utils/utils.hpp
Normal file
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
|
||||
// Estructura para definir un circulo
|
||||
struct Circle {
|
||||
int x{0};
|
||||
int y{0};
|
||||
int r{0};
|
||||
};
|
||||
|
||||
// Estructura para definir una linea horizontal
|
||||
struct LineHorizontal {
|
||||
int x1{0}, x2{0}, y{0};
|
||||
};
|
||||
|
||||
// Estructura para definir una linea vertical
|
||||
struct LineVertical {
|
||||
int x{0}, y1{0}, y2{0};
|
||||
};
|
||||
|
||||
// Estructura para definir una linea
|
||||
struct Line {
|
||||
int x1{0}, y1{0}, x2{0}, y2{0};
|
||||
};
|
||||
|
||||
// Estructura para definir un color RGB
|
||||
struct ColorRGB {
|
||||
Uint8 r{0};
|
||||
Uint8 g{0};
|
||||
Uint8 b{0};
|
||||
|
||||
// Constructor
|
||||
ColorRGB(Uint8 red, Uint8 green, Uint8 blue)
|
||||
: r(red),
|
||||
g(green),
|
||||
b(blue) {}
|
||||
};
|
||||
|
||||
// COLISIONES Y GEOMETRÍA
|
||||
auto distanceSquared(int x1, int y1, int x2, int y2) -> double; // Distancia² entre dos puntos
|
||||
auto checkCollision(const Circle& a, const Circle& b) -> bool; // Colisión círculo-círculo
|
||||
auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool; // Colisión círculo-rectángulo
|
||||
auto checkCollision(const SDL_FRect& a, const SDL_FRect& b) -> bool; // Colisión rectángulo-rectángulo
|
||||
auto checkCollision(const SDL_FPoint& p, const SDL_FRect& r) -> bool; // Colisión punto-rectángulo
|
||||
auto checkCollision(const LineHorizontal& l, const SDL_FRect& r) -> bool; // Colisión línea horizontal-rectángulo
|
||||
auto checkCollision(const LineVertical& l, const SDL_FRect& r) -> bool; // Colisión línea vertical-rectángulo
|
||||
auto checkCollision(const LineHorizontal& l, const SDL_FPoint& p) -> bool; // Colisión línea horizontal-punto
|
||||
auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point; // Colisión línea-línea (intersección)
|
||||
|
||||
// CONVERSIONES DE TIPOS SDL
|
||||
auto toSDLRect(const SDL_FRect& frect) -> SDL_Rect; // Convierte SDL_FRect a SDL_Rect
|
||||
auto toSDLPoint(const SDL_FPoint& fpoint) -> SDL_Point; // Convierte SDL_FPoint a SDL_Point
|
||||
|
||||
// CONVERSIONES DE STRING
|
||||
auto stringToColor(const std::string& str) -> Uint8; // String a índice de paleta
|
||||
auto safeStoi(const std::string& value, int default_value = 0) -> int; // String a int seguro (sin excepciones)
|
||||
auto stringToBool(const std::string& str) -> bool; // String a bool (true/1/yes/on)
|
||||
auto boolToString(bool value) -> std::string; // Bool a string (1/0)
|
||||
auto toLower(const std::string& str) -> std::string; // String a minúsculas
|
||||
auto toUpper(const std::string& str) -> std::string; // String a mayúsculas
|
||||
|
||||
// OPERACIONES CON STRINGS
|
||||
auto stringInVector(const std::vector<std::string>& vec, const std::string& str) -> bool; // Busca string en vector
|
||||
auto spaceBetweenLetters(const std::string& input) -> std::string; // Añade espacios entre letras
|
||||
|
||||
// OPERACIONES CON COLORES
|
||||
auto colorAreEqual(ColorRGB color1, ColorRGB color2) -> bool; // Compara dos colores RGB
|
||||
|
||||
// OPERACIONES CON FICHEROS
|
||||
auto getFileName(const std::string& path) -> std::string; // Extrae nombre de fichero de ruta
|
||||
auto getPath(const std::string& full_path) -> std::string; // Extrae directorio de ruta completa
|
||||
|
||||
// RENDERIZADO
|
||||
void fillTextureWithColor(SDL_Renderer* renderer, SDL_Texture* texture, Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Rellena textura
|
||||
|
||||
// OUTPUT Y UTILIDADES DE CONSOLA
|
||||
void printWithDots(const std::string& text1, const std::string& text2, const std::string& text3); // Imprime línea con puntos
|
||||
Reference in New Issue
Block a user