jail_audio: actualitzat a la ultima versió (ara sense threads)

This commit is contained in:
2025-07-24 20:04:02 +02:00
parent 91730def9a
commit 9eb97fd61c
12 changed files with 519 additions and 496 deletions

View File

@@ -32,6 +32,11 @@ Audio::~Audio() {
#endif #endif
} }
// Método principal
void Audio::update() {
JA_Update();
}
// Reproduce la música // Reproduce la música
void Audio::playMusic(const std::string &name, const int loop) { void Audio::playMusic(const std::string &name, const int loop) {
music_.name = name; music_.name = name;

View File

@@ -24,6 +24,9 @@ class Audio {
Audio(const Audio &) = delete; // Evitar copia Audio(const Audio &) = delete; // Evitar copia
auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación
// --- Método principal ---
void update();
// --- Control de Música --- // --- Control de Música ---
void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle
void pauseMusic(); // Pausar reproducción de música void pauseMusic(); // Pausar reproducción de música

View File

@@ -1,135 +1,139 @@
#ifndef JA_USESDLMIXER #ifndef JA_USESDLMIXER
#include "jail_audio.h" #include "jail_audio.h"
#include "stb_vorbis.h"
#include <SDL3/SDL.h> // Para SDL_AudioFormat, SDL_BindAudioStream, SDL_Se... #include <SDL3/SDL.h>
#include <stdint.h> // Para uint32_t, uint8_t #include <stdio.h>
#include <stdio.h> // Para NULL, fseek, printf, fclose, fopen, fread
#include <stdlib.h> // Para free, malloc
#include <string.h> // Para strcpy, strlen
#include "stb_vorbis.h" // Para stb_vorbis_decode_memory
#define JA_MAX_SIMULTANEOUS_CHANNELS 20 #define JA_MAX_SIMULTANEOUS_CHANNELS 20
#define JA_MAX_GROUPS 2 #define JA_MAX_GROUPS 2
struct JA_Sound_t { struct JA_Sound_t
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; {
Uint32 length{0}; SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 };
Uint8 *buffer{NULL}; Uint32 length { 0 };
Uint8 *buffer { NULL };
}; };
struct JA_Channel_t { struct JA_Channel_t
JA_Sound_t *sound{nullptr}; {
int pos{0}; JA_Sound_t *sound { nullptr };
int times{0}; int pos { 0 };
int group{0}; int times { 0 };
SDL_AudioStream *stream{nullptr}; int group { 0 };
JA_Channel_state state{JA_CHANNEL_FREE}; SDL_AudioStream *stream { nullptr };
JA_Channel_state state { JA_CHANNEL_FREE };
}; };
struct JA_Music_t { struct JA_Music_t
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; {
Uint32 length{0}; SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 };
Uint8 *buffer{nullptr}; Uint32 length { 0 };
char *filename{nullptr}; Uint8 *buffer { nullptr };
char *filename { nullptr };
int pos{0}; int pos { 0 };
int times{0}; int times { 0 };
SDL_AudioStream *stream{nullptr}; SDL_AudioStream *stream { nullptr };
JA_Music_state state{JA_MUSIC_INVALID}; JA_Music_state state { JA_MUSIC_INVALID };
}; };
JA_Music_t *current_music{nullptr}; JA_Music_t *current_music { nullptr };
JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000}; SDL_AudioSpec JA_audioSpec { SDL_AUDIO_S16, 2, 48000 };
float JA_musicVolume{1.0f}; float JA_musicVolume { 1.0f };
float JA_soundVolume[JA_MAX_GROUPS]; float JA_soundVolume[JA_MAX_GROUPS];
bool JA_musicEnabled{true}; bool JA_musicEnabled { true };
bool JA_soundEnabled{true}; bool JA_soundEnabled { true };
SDL_AudioDeviceID sdlAudioDevice{0}; SDL_AudioDeviceID sdlAudioDevice { 0 };
SDL_TimerID JA_timerID{0}; //SDL_TimerID JA_timerID { 0 };
bool fading = false; bool fading = false;
int fade_start_time; int fade_start_time;
int fade_duration; int fade_duration;
int fade_initial_volume; int fade_initial_volume;
Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval) {
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) { void JA_Update()
{
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING)
{
if (fading) { if (fading) {
int time = SDL_GetTicks(); int time = SDL_GetTicks();
if (time > (fade_start_time + fade_duration)) { if (time > (fade_start_time+fade_duration)) {
fading = false; fading = false;
JA_StopMusic(); JA_StopMusic();
return 30; return;
} else { } else {
const int time_passed = time - fade_start_time; const int time_passed = time - fade_start_time;
const float percent = (float)time_passed / (float)fade_duration; const float percent = (float)time_passed / (float)fade_duration;
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume * (1.0 - percent)); SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume*(1.0 - percent));
} }
} }
if (current_music->times != 0) { if (current_music->times != 0)
if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length / 2)) { {
if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length/2)) {
SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length); SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length);
} }
if (current_music->times > 0) if (current_music->times>0) current_music->times--;
current_music->times--; }
} else { else
if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
JA_StopMusic(); if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic();
} }
} }
if (JA_soundEnabled) { if (JA_soundEnabled)
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) {
if (channels[i].state == JA_CHANNEL_PLAYING) { for (int i=0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i)
if (channels[i].times != 0) { if (channels[i].state == JA_CHANNEL_PLAYING)
if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length / 2)) { {
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); SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length);
if (channels[i].times > 0) if (channels[i].times>0) channels[i].times--;
channels[i].times--;
} }
} else { }
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) else
JA_StopChannel(i); {
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i);
} }
} }
} }
return 30; return;
} }
void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels) { void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels)
#ifdef _DEBUG {
#ifdef DEBUG
SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG); SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
#endif #endif
SDL_Log("Iniciant JailAudio..."); SDL_Log("Iniciant JailAudio...");
JA_audioSpec = {format, num_channels, freq}; JA_audioSpec = {format, num_channels, freq };
if (!sdlAudioDevice) if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice);
SDL_CloseAudioDevice(sdlAudioDevice);
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec); sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
SDL_Log((sdlAudioDevice == 0) ? "Failed to initialize SDL audio!\n" : "OK!\n"); SDL_Log( (sdlAudioDevice==0) ? "Failed to initialize SDL audio!\n" : "OK!\n");
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) for (int i=0; i<JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE;
channels[i].state = JA_CHANNEL_FREE; for (int i=0; i<JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5f;
for (int i = 0; i < JA_MAX_GROUPS; ++i) //SDL_PauseAudioDevice(sdlAudioDevice);
JA_soundVolume[i] = 0.5f; //JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr);
// SDL_PauseAudioDevice(sdlAudioDevice);
JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr);
} }
void JA_Quit() { void JA_Quit()
if (JA_timerID) {
SDL_RemoveTimer(JA_timerID); //if (JA_timerID) SDL_RemoveTimer(JA_timerID);
if (!sdlAudioDevice) if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice);
SDL_CloseAudioDevice(sdlAudioDevice);
sdlAudioDevice = 0; sdlAudioDevice = 0;
} }
JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length) { JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length)
{
JA_Music_t *music = new JA_Music_t(); JA_Music_t *music = new JA_Music_t();
int chan, samplerate; int chan, samplerate;
@@ -139,7 +143,7 @@ JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length) {
music->spec.channels = chan; music->spec.channels = chan;
music->spec.freq = samplerate; music->spec.freq = samplerate;
music->spec.format = SDL_AUDIO_S16; music->spec.format = SDL_AUDIO_S16;
music->buffer = (Uint8 *)SDL_malloc(music->length); music->buffer = (Uint8*)SDL_malloc(music->length);
SDL_memcpy(music->buffer, output, music->length); SDL_memcpy(music->buffer, output, music->length);
free(output); free(output);
music->pos = 0; music->pos = 0;
@@ -148,19 +152,19 @@ JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length) {
return music; return music;
} }
JA_Music_t *JA_LoadMusic(const char *filename) { JA_Music_t *JA_LoadMusic(const char* filename)
{
// [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid. // [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid.
FILE *f = fopen(filename, "rb"); FILE *f = fopen(filename, "rb");
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
long fsize = ftell(f); long fsize = ftell(f);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(fsize + 1); Uint8 *buffer = (Uint8*)malloc(fsize + 1);
if (fread(buffer, fsize, 1, f) != 1) if (fread(buffer, fsize, 1, f)!=1) return NULL;
return NULL;
fclose(f); fclose(f);
JA_Music_t *music = JA_LoadMusic(buffer, fsize); JA_Music_t *music = JA_LoadMusic(buffer, fsize);
music->filename = (char *)malloc(strlen(filename) + 1); music->filename = (char*)malloc(strlen(filename)+1);
strcpy(music->filename, filename); strcpy(music->filename, filename);
free(buffer); free(buffer);
@@ -168,9 +172,9 @@ JA_Music_t *JA_LoadMusic(const char *filename) {
return music; return music;
} }
void JA_PlayMusic(JA_Music_t *music, const int loop) { void JA_PlayMusic(JA_Music_t *music, const int loop)
if (!JA_musicEnabled) {
return; if (!JA_musicEnabled) return;
JA_StopMusic(); JA_StopMusic();
@@ -180,62 +184,56 @@ void JA_PlayMusic(JA_Music_t *music, const int loop) {
current_music->times = loop; current_music->times = loop;
current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec); current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec);
if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n");
printf("[ERROR] SDL_PutAudioStreamData failed!\n");
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n");
printf("[ERROR] SDL_BindAudioStream failed!\n"); //SDL_ResumeAudioStreamDevice(current_music->stream);
// SDL_ResumeAudioStreamDevice(current_music->stream);
} }
char *JA_GetMusicFilename(JA_Music_t *music) { char *JA_GetMusicFilename(JA_Music_t *music)
if (!music) {
music = current_music; if (!music) music = current_music;
return music->filename; return music->filename;
} }
void JA_PauseMusic() { void JA_PauseMusic()
if (!JA_musicEnabled) {
return; if (!JA_musicEnabled) return;
if (!current_music || current_music->state == JA_MUSIC_INVALID) if (!current_music || current_music->state == JA_MUSIC_INVALID) return;
return;
current_music->state = JA_MUSIC_PAUSED; current_music->state = JA_MUSIC_PAUSED;
// SDL_PauseAudioStreamDevice(current_music->stream); //SDL_PauseAudioStreamDevice(current_music->stream);
SDL_UnbindAudioStream(current_music->stream); SDL_UnbindAudioStream(current_music->stream);
} }
void JA_ResumeMusic() { void JA_ResumeMusic()
if (!JA_musicEnabled) {
return; if (!JA_musicEnabled) return;
if (!current_music || current_music->state == JA_MUSIC_INVALID) if (!current_music || current_music->state == JA_MUSIC_INVALID) return;
return;
current_music->state = JA_MUSIC_PLAYING; current_music->state = JA_MUSIC_PLAYING;
// SDL_ResumeAudioStreamDevice(current_music->stream); //SDL_ResumeAudioStreamDevice(current_music->stream);
SDL_BindAudioStream(sdlAudioDevice, current_music->stream); SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
} }
void JA_StopMusic() { void JA_StopMusic()
if (!JA_musicEnabled) {
return; if (!JA_musicEnabled) return;
if (!current_music || current_music->state == JA_MUSIC_INVALID) if (!current_music || current_music->state == JA_MUSIC_INVALID) return;
return;
current_music->pos = 0; current_music->pos = 0;
current_music->state = JA_MUSIC_STOPPED; current_music->state = JA_MUSIC_STOPPED;
// SDL_PauseAudioStreamDevice(current_music->stream); //SDL_PauseAudioStreamDevice(current_music->stream);
SDL_DestroyAudioStream(current_music->stream); SDL_DestroyAudioStream(current_music->stream);
current_music->stream = nullptr; current_music->stream = nullptr;
free(current_music->filename); free(current_music->filename);
current_music->filename = nullptr; current_music->filename = nullptr;
} }
void JA_FadeOutMusic(const int milliseconds) { void JA_FadeOutMusic(const int milliseconds)
if (!JA_musicEnabled) {
return; if (!JA_musicEnabled) return;
if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return;
return;
fading = true; fading = true;
fade_start_time = SDL_GetTicks(); fade_start_time = SDL_GetTicks();
@@ -243,81 +241,83 @@ void JA_FadeOutMusic(const int milliseconds) {
fade_initial_volume = JA_musicVolume; fade_initial_volume = JA_musicVolume;
} }
JA_Music_state JA_GetMusicState() { JA_Music_state JA_GetMusicState()
if (!JA_musicEnabled) {
return JA_MUSIC_DISABLED; if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
if (!current_music) if (!current_music) return JA_MUSIC_INVALID;
return JA_MUSIC_INVALID;
return current_music->state; return current_music->state;
} }
void JA_DeleteMusic(JA_Music_t *music) { void JA_DeleteMusic(JA_Music_t *music)
if (current_music == music) {
current_music = nullptr; if (current_music == music) current_music = nullptr;
SDL_free(music->buffer); SDL_free(music->buffer);
if (music->stream) if (music->stream) SDL_DestroyAudioStream(music->stream);
SDL_DestroyAudioStream(music->stream);
delete music; delete music;
} }
float JA_SetMusicVolume(float volume) { float JA_SetMusicVolume(float volume)
JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f); {
if (current_music) JA_musicVolume = SDL_clamp( volume, 0.0f, 1.0f );
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); if (current_music) SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
return JA_musicVolume; return JA_musicVolume;
} }
void JA_SetMusicPosition(float value) { void JA_SetMusicPosition(float value)
if (!current_music) {
return; if (!current_music) return;
current_music->pos = value * current_music->spec.freq; current_music->pos = value * current_music->spec.freq;
} }
float JA_GetMusicPosition() { float JA_GetMusicPosition()
if (!current_music) {
return 0; if (!current_music) return 0;
return float(current_music->pos) / float(current_music->spec.freq); return float(current_music->pos)/float(current_music->spec.freq);
} }
void JA_EnableMusic(const bool value) { void JA_EnableMusic(const bool value)
if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) {
JA_StopMusic(); if ( !value && current_music && (current_music->state==JA_MUSIC_PLAYING) ) JA_StopMusic();
JA_musicEnabled = value; JA_musicEnabled = value;
} }
JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length) {
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length)
{
JA_Sound_t *sound = new JA_Sound_t(); JA_Sound_t *sound = new JA_Sound_t();
sound->buffer = buffer; sound->buffer = buffer;
sound->length = length; sound->length = length;
return sound; return sound;
} }
JA_Sound_t *JA_LoadSound(uint8_t *buffer, uint32_t size) { JA_Sound_t *JA_LoadSound(uint8_t* buffer, uint32_t size)
{
JA_Sound_t *sound = new JA_Sound_t(); JA_Sound_t *sound = new JA_Sound_t();
SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length); SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size),1, &sound->spec, &sound->buffer, &sound->length);
return sound; return sound;
} }
JA_Sound_t *JA_LoadSound(const char *filename) { JA_Sound_t *JA_LoadSound(const char* filename)
{
JA_Sound_t *sound = new JA_Sound_t(); JA_Sound_t *sound = new JA_Sound_t();
SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length); SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length);
return sound; return sound;
} }
int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group) { int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group)
if (!JA_soundEnabled) {
return -1; if (!JA_soundEnabled) return -1;
int channel = 0; int channel = 0;
while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; }
channel++; if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) channel = 0;
}
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS)
channel = 0;
JA_StopChannel(channel); JA_StopChannel(channel);
channels[channel].sound = sound; channels[channel].sound = sound;
@@ -332,12 +332,11 @@ int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group) {
return channel; return channel;
} }
int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop, const int group) { int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop, const int group)
if (!JA_soundEnabled) {
return -1; if (!JA_soundEnabled) return -1;
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1;
return -1;
JA_StopChannel(channel); JA_StopChannel(channel);
channels[channel].sound = sound; channels[channel].sound = sound;
@@ -352,71 +351,82 @@ int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop,
return channel; return channel;
} }
void JA_DeleteSound(JA_Sound_t *sound) { void JA_DeleteSound(JA_Sound_t *sound)
{
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
if (channels[i].sound == sound) if (channels[i].sound == sound) JA_StopChannel(i);
JA_StopChannel(i);
} }
SDL_free(sound->buffer); SDL_free(sound->buffer);
delete sound; delete sound;
} }
void JA_PauseChannel(const int channel) { void JA_PauseChannel(const int channel)
if (!JA_soundEnabled) {
return; if (!JA_soundEnabled) return;
if (channel == -1) { if (channel == -1)
{
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
if (channels[i].state == JA_CHANNEL_PLAYING) { if (channels[i].state == JA_CHANNEL_PLAYING)
{
channels[i].state = JA_CHANNEL_PAUSED; channels[i].state = JA_CHANNEL_PAUSED;
// SDL_PauseAudioStreamDevice(channels[i].stream); //SDL_PauseAudioStreamDevice(channels[i].stream);
SDL_UnbindAudioStream(channels[i].stream); SDL_UnbindAudioStream(channels[i].stream);
} }
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { }
if (channels[channel].state == JA_CHANNEL_PLAYING) { else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
{
if (channels[channel].state == JA_CHANNEL_PLAYING)
{
channels[channel].state = JA_CHANNEL_PAUSED; channels[channel].state = JA_CHANNEL_PAUSED;
// SDL_PauseAudioStreamDevice(channels[channel].stream); //SDL_PauseAudioStreamDevice(channels[channel].stream);
SDL_UnbindAudioStream(channels[channel].stream); SDL_UnbindAudioStream(channels[channel].stream);
} }
} }
} }
void JA_ResumeChannel(const int channel) { void JA_ResumeChannel(const int channel)
if (!JA_soundEnabled) {
return; if (!JA_soundEnabled) return;
if (channel == -1) { if (channel == -1)
{
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
if (channels[i].state == JA_CHANNEL_PAUSED) { if (channels[i].state == JA_CHANNEL_PAUSED)
{
channels[i].state = JA_CHANNEL_PLAYING; channels[i].state = JA_CHANNEL_PLAYING;
// SDL_ResumeAudioStreamDevice(channels[i].stream); //SDL_ResumeAudioStreamDevice(channels[i].stream);
SDL_BindAudioStream(sdlAudioDevice, channels[i].stream); SDL_BindAudioStream(sdlAudioDevice, channels[i].stream);
} }
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { }
if (channels[channel].state == JA_CHANNEL_PAUSED) { else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
{
if (channels[channel].state == JA_CHANNEL_PAUSED)
{
channels[channel].state = JA_CHANNEL_PLAYING; channels[channel].state = JA_CHANNEL_PLAYING;
// SDL_ResumeAudioStreamDevice(channels[channel].stream); //SDL_ResumeAudioStreamDevice(channels[channel].stream);
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream); SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
} }
} }
} }
void JA_StopChannel(const int channel) { void JA_StopChannel(const int channel)
if (!JA_soundEnabled) {
return; if (!JA_soundEnabled) return;
if (channel == -1) { if (channel == -1)
{
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
if (channels[i].state != JA_CHANNEL_FREE) if (channels[i].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[i].stream);
SDL_DestroyAudioStream(channels[i].stream);
channels[i].stream = nullptr; channels[i].stream = nullptr;
channels[i].state = JA_CHANNEL_FREE; channels[i].state = JA_CHANNEL_FREE;
channels[i].pos = 0; channels[i].pos = 0;
channels[i].sound = NULL; channels[i].sound = NULL;
} }
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { }
if (channels[channel].state != JA_CHANNEL_FREE) else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
SDL_DestroyAudioStream(channels[channel].stream); {
if (channels[channel].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[channel].stream);
channels[channel].stream = nullptr; channels[channel].stream = nullptr;
channels[channel].state = JA_CHANNEL_FREE; channels[channel].state = JA_CHANNEL_FREE;
channels[channel].pos = 0; channels[channel].pos = 0;
@@ -424,40 +434,41 @@ void JA_StopChannel(const int channel) {
} }
} }
JA_Channel_state JA_GetChannelState(const int channel) { JA_Channel_state JA_GetChannelState(const int channel)
if (!JA_soundEnabled) {
return JA_SOUND_DISABLED; if (!JA_soundEnabled) return JA_SOUND_DISABLED;
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID;
return JA_CHANNEL_INVALID;
return channels[channel].state; return channels[channel].state;
} }
float JA_SetSoundVolume(float volume, const int group) { float JA_SetSoundVolume(float volume, const int group)
const float v = SDL_clamp(volume, 0.0f, 1.0f); {
const float v = SDL_clamp( volume, 0.0f, 1.0f );
for (int i = 0; i < JA_MAX_GROUPS; ++i) { for (int i = 0; i < JA_MAX_GROUPS; ++i) {
if (group == -1 || group == i) if (group==-1 || group==i) JA_soundVolume[i]=v;
JA_soundVolume[i] = v;
} }
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
if (((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) && if ( ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) &&
((group == -1) || (channels[i].group == group))) ((group==-1) || (channels[i].group==group)) )
SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[i]); SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[i]);
return v; return v;
} }
void JA_EnableSound(const bool value) { void JA_EnableSound(const bool value)
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { {
if (channels[i].state == JA_CHANNEL_PLAYING) for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
JA_StopChannel(i); {
if (channels[i].state == JA_CHANNEL_PLAYING) JA_StopChannel(i);
} }
JA_soundEnabled = value; JA_soundEnabled = value;
} }
float JA_SetVolume(float volume) { float JA_SetVolume(float volume)
{
JA_SetSoundVolume(JA_SetMusicVolume(volume) / 2.0f); JA_SetSoundVolume(JA_SetMusicVolume(volume) / 2.0f);
return JA_musicVolume; return JA_musicVolume;

View File

@@ -1,29 +1,19 @@
#pragma once #pragma once
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
enum JA_Channel_state { enum JA_Channel_state { JA_CHANNEL_INVALID, JA_CHANNEL_FREE, JA_CHANNEL_PLAYING, JA_CHANNEL_PAUSED, JA_SOUND_DISABLED };
JA_CHANNEL_INVALID, enum JA_Music_state { JA_MUSIC_INVALID, JA_MUSIC_PLAYING, JA_MUSIC_PAUSED, JA_MUSIC_STOPPED, JA_MUSIC_DISABLED };
JA_CHANNEL_FREE,
JA_CHANNEL_PLAYING,
JA_CHANNEL_PAUSED,
JA_SOUND_DISABLED
};
enum JA_Music_state {
JA_MUSIC_INVALID,
JA_MUSIC_PLAYING,
JA_MUSIC_PAUSED,
JA_MUSIC_STOPPED,
JA_MUSIC_DISABLED
};
struct JA_Sound_t; struct JA_Sound_t;
struct JA_Music_t; struct JA_Music_t;
void JA_Update();
void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels); void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels);
void JA_Quit(); void JA_Quit();
JA_Music_t *JA_LoadMusic(const char *filename); JA_Music_t *JA_LoadMusic(const char* filename);
JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length); JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length);
void JA_PlayMusic(JA_Music_t *music, const int loop = -1); void JA_PlayMusic(JA_Music_t *music, const int loop = -1);
char *JA_GetMusicFilename(JA_Music_t *music = nullptr); char *JA_GetMusicFilename(JA_Music_t *music = nullptr);
void JA_PauseMusic(); void JA_PauseMusic();
@@ -37,17 +27,17 @@ void JA_SetMusicPosition(float value);
float JA_GetMusicPosition(); float JA_GetMusicPosition();
void JA_EnableMusic(const bool value); void JA_EnableMusic(const bool value);
JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length); JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length);
JA_Sound_t *JA_LoadSound(Uint8 *buffer, Uint32 length); JA_Sound_t *JA_LoadSound(Uint8* buffer, Uint32 length);
JA_Sound_t *JA_LoadSound(const char *filename); JA_Sound_t *JA_LoadSound(const char* filename);
int JA_PlaySound(JA_Sound_t *sound, const int loop = 0, const int group = 0); int JA_PlaySound(JA_Sound_t *sound, const int loop = 0, const int group=0);
int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0, const int group = 0); int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0, const int group=0);
void JA_PauseChannel(const int channel); void JA_PauseChannel(const int channel);
void JA_ResumeChannel(const int channel); void JA_ResumeChannel(const int channel);
void JA_StopChannel(const int channel); void JA_StopChannel(const int channel);
JA_Channel_state JA_GetChannelState(const int channel); JA_Channel_state JA_GetChannelState(const int channel);
void JA_DeleteSound(JA_Sound_t *sound); void JA_DeleteSound(JA_Sound_t *sound);
float JA_SetSoundVolume(float volume, const int group = 0); float JA_SetSoundVolume(float volume, const int group=0);
void JA_EnableSound(const bool value); void JA_EnableSound(const bool value);
float JA_SetVolume(float volume); float JA_SetVolume(float volume);

View File

@@ -104,18 +104,17 @@ void Credits::update() {
fillCanvas(); fillCanvas();
} }
static const auto audio = Audio::get();
audio->update();
} }
// Dibuja Credits::en patalla // Dibuja Credits::en patalla
void Credits::render() { void Credits::render() {
// Prepara para empezar a dibujar en la textura de juego static const auto screen = Screen::get();
Screen::get()->start();
// Copia la textura con la zona de juego a la pantalla screen->start(); // Prepara para empezar a dibujar en la textura de juego
SDL_RenderTexture(Screen::get()->getRenderer(), canvas_, nullptr, nullptr); SDL_RenderTexture(screen->getRenderer(), canvas_, nullptr, nullptr); // Copia la textura con la zona de juego a la pantalla
screen->render(); // Vuelca el contenido del renderizador en pantalla
// Vuelca el contenido del renderizador en pantalla
Screen::get()->render();
} }
// Comprueba el manejador de eventos // Comprueba el manejador de eventos

View File

@@ -6,8 +6,8 @@
#include <array> // Para array #include <array> // Para array
#include <cstdlib> // Para rand, size_t #include <cstdlib> // Para rand, size_t
#include <functional> // Para function #include <functional> // Para function
#include <iterator> // Para distance, size
#include <iostream> // Para std::cout, std::endl #include <iostream> // Para std::cout, std::endl
#include <iterator> // Para distance, size
#include "asset.h" // Para Asset #include "asset.h" // Para Asset
#include "audio.h" // Para Audio #include "audio.h" // Para Audio
@@ -886,40 +886,59 @@ void Game::updateTimeStopped() {
void Game::update() { void Game::update() {
if (SDL_GetTicks() - ticks_ > param.game.speed) { if (SDL_GetTicks() - ticks_ > param.game.speed) {
ticks_ = SDL_GetTicks(); ticks_ = SDL_GetTicks();
screen_->update();
checkServiceMenu(); checkServiceMenu();
updateDemo(); updateDemo();
#ifdef RECORDING #ifdef RECORDING
updateRecording(); updateRecording();
#endif #endif
if (!paused_) { updateGameStates();
switch (state_) {
case GameState::FADE_IN:
updateGameStateFadeIn();
break;
case GameState::ENTERING_PLAYER:
updateGameStateEnteringPlayer();
break;
case GameState::SHOWING_GET_READY_MESSAGE:
updateGameStateShowingGetReadyMessage();
break;
case GameState::PLAYING:
updateGameStatePlaying();
break;
case GameState::COMPLETED:
updateGameStateCompleted();
break;
case GameState::GAME_OVER:
updateGameStateGameOver();
break;
default:
break;
}
}
screen_->update();
fillCanvas(); fillCanvas();
} }
static const auto audio = Audio::get();
audio->update();
}
// Dibuja el juego
void Game::render() {
screen_->start(); // Prepara para empezar a dibujar en la textura de juego
SDL_RenderTexture(renderer_, canvas_, nullptr, &param.game.play_area.rect); // Copia la textura con la zona de juego a la pantalla
scoreboard_->render(); // Dibuja el marcador
fade_in_->render(); // Dibuja el fade de entrada
fade_out_->render(); // Dibuja el fade de salida
screen_->render(); // Vuelca el contenido del renderizador en pantalla
}
// Actualiza los estados del juego
void Game::updateGameStates() {
if (!paused_) {
switch (state_) {
case GameState::FADE_IN:
updateGameStateFadeIn();
break;
case GameState::ENTERING_PLAYER:
updateGameStateEnteringPlayer();
break;
case GameState::SHOWING_GET_READY_MESSAGE:
updateGameStateShowingGetReadyMessage();
break;
case GameState::PLAYING:
updateGameStatePlaying();
break;
case GameState::COMPLETED:
updateGameStateCompleted();
break;
case GameState::GAME_OVER:
updateGameStateGameOver();
break;
default:
break;
}
}
} }
// Actualiza el fondo // Actualiza el fondo
@@ -971,25 +990,6 @@ void Game::fillCanvas() {
SDL_SetRenderTarget(renderer_, temp); SDL_SetRenderTarget(renderer_, temp);
} }
// Dibuja el juego
void Game::render() {
// Prepara para empezar a dibujar en la textura de juego
screen_->start();
// Copia la textura con la zona de juego a la pantalla
SDL_RenderTexture(renderer_, canvas_, nullptr, &param.game.play_area.rect);
// Dibuja el marcador
scoreboard_->render();
// Dibuja el fade
fade_in_->render();
fade_out_->render();
// Vuelca el contenido del renderizador en pantalla
screen_->render();
}
// Habilita el efecto del item de detener el tiempo // Habilita el efecto del item de detener el tiempo
void Game::enableTimeStopItem() { void Game::enableTimeStopItem() {
balloon_manager_->stopAllBalloons(); balloon_manager_->stopAllBalloons();
@@ -1786,8 +1786,8 @@ void Game::playSound(const std::string &name) const {
return; return;
} }
static auto *audio_ = Audio::get(); static auto audio = Audio::get();
audio_->playSound(name); audio->playSound(name);
} }
// Organiza los jugadores para que los vivos se pinten sobre los muertos // Organiza los jugadores para que los vivos se pinten sobre los muertos
@@ -1895,14 +1895,14 @@ void Game::checkDebugEvents(const SDL_Event &event) {
tabe_->enable(); tabe_->enable();
break; break;
} }
case SDLK_KP_PLUS:{ case SDLK_KP_PLUS: {
++formation_id; ++formation_id;
balloon_manager_->destroyAllBalloons(); balloon_manager_->destroyAllBalloons();
balloon_manager_->deployFormation(formation_id); balloon_manager_->deployFormation(formation_id);
std::cout << formation_id << std::endl; std::cout << formation_id << std::endl;
break; break;
} }
case SDLK_KP_MINUS:{ case SDLK_KP_MINUS: {
--formation_id; --formation_id;
balloon_manager_->destroyAllBalloons(); balloon_manager_->destroyAllBalloons();
balloon_manager_->deployFormation(formation_id); balloon_manager_->deployFormation(formation_id);

View File

@@ -150,101 +150,152 @@ class Game {
#ifdef _DEBUG #ifdef _DEBUG
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
// Comprueba los eventos en el modo DEBUG
void checkDebugEvents(const SDL_Event &event);
#endif #endif
// --- Métodos internos --- // --- Ciclo principal del juego ---
void update(); // Actualiza el juego void update(); // Actualiza la lógica principal del juego
void render(); // Dibuja el juego void render(); // Renderiza todos los elementos del juego
void checkEvents(); // Comprueba los eventos que hay en cola void checkEvents(); // Procesa los eventos del sistema en cola
void setResources(); // Asigna texturas y animaciones void checkState(); // Verifica y actualiza el estado actual del juego
void updateHiScore(); // Actualiza el valor de HiScore en caso necesario void setState(GameState state); // Cambia el estado del juego
void updatePlayers(); // Actualiza las variables del jugador void pause(bool value); // Pausa o reanuda el juego
void renderPlayers(); // Dibuja a los jugadores void cleanVectors(); // Limpia vectores de elementos deshabilitados
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida // --- Gestión de estados del juego ---
void destroyAllItems(); // Destruye todos los items void updateGameStates(); // Actualiza todos los estados del juego
auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Comprueba la colisión entre el jugador y los globos activos void updateGameStateFadeIn(); // Gestiona el estado de transición de entrada
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items void updateGameStateEnteringPlayer(); // Gestiona el estado de entrada de jugador
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas void updateGameStateShowingGetReadyMessage(); // Gestiona el estado de mensaje "preparado"
void updateBullets(); // Mueve las balas activas void updateGameStatePlaying(); // Gestiona el estado de juego activo
void renderBullets(); // Pinta las balas activas void updateGameStateCompleted(); // Gestiona el estado de juego completado
void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea un objeto bala void updateGameStateGameOver(); // Gestiona el estado de fin de partida
void freeBullets(); // Vacia el vector de balas
void updateItems(); // Actualiza los items // --- Gestión de jugadores ---
void renderItems(); // Pinta los items activos void initPlayers(int player_id); // Inicializa los datos de los jugadores
auto dropItem() -> ItemType; // Devuelve un item en función del azar void updatePlayers(); // Actualiza las variables y estados de los jugadores
void createItem(ItemType type, float x, float y); // Crea un objeto item void renderPlayers(); // Renderiza todos los jugadores en pantalla
void freeItems(); // Vacia el vector de items void movePlayersToFront(); // Reorganiza el orden de dibujado de jugadores
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador por su identificador
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite static auto getController(int player_id) -> int; // Obtiene el controlador asignado a un jugador
void freeSmartSprites(); // Vacia el vector de smartsprites
void freePathSprites(); // Vacia el vector de pathsprites // --- Estado de jugadores ---
void throwCoffee(int x, int y); // Crea un SpriteSmart para arrojar el item café al recibir un impacto void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Actualiza estado entre jugadores
void updateSmartSprites(); // Actualiza los SpriteSmarts void checkPlayersStatusPlaying(); // Verifica el estado de juego de todos los jugadores
void renderSmartSprites(); // Pinta los SpriteSmarts activos auto allPlayersAreWaitingOrGameOver() -> bool; // Verifica si todos esperan o han perdido
void updatePathSprites(); // Actualiza los PathSprites auto allPlayersAreGameOver() -> bool; // Verifica si todos los jugadores han perdido
void renderPathSprites(); // Pinta los PathSprites activos auto allPlayersAreNotPlaying() -> bool; // Verifica si ningún jugador está activo
void handlePlayerCollision(std::shared_ptr<Player> &player); // Acciones a realizar cuando el jugador colisiona con un globo
void updateTimeStopped(); // Actualiza y comprueba el valor de la variable // --- Colisiones de jugadores ---
void updateBackground(); // Actualiza el fondo void handlePlayerCollision(std::shared_ptr<Player> &player); // Procesa colisión de jugador con globo
void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Detecta colisión jugador-globo
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Detecta colisión jugador-ítem
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
void updateHelper(); // Actualiza las variables de ayuda // --- Sistema de entrada (input) ---
auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar void checkInput(); // Gestiona toda la entrada durante el juego
auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar void checkPauseInput(); // Verifica solicitudes de pausa de controladores
auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar
void updateScoreboard(); // Actualiza el marcador // --- Entrada de jugadores normales ---
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura void handlePlayersInput(); // Gestiona entrada de todos los jugadores
void pause(bool value); // Pausa el juego void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Procesa entrada de un jugador específico
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Gestiona disparo de jugador
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa disparos automáticos
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores void handlePlayerContinue(const std::shared_ptr<Player> &player); // Permite continuar al jugador
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id" void handleNameInput(const std::shared_ptr<Player> &player); // Gestiona entrada de nombre del jugador
static auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador
void checkInput(); // Gestiona la entrada durante el juego // --- Entrada en modo demo ---
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego. void demoHandleInput(); // Gestiona entrada durante el modo demostración
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos. void demoHandlePassInput(); // Permite saltar la demostración
void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo. void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa entrada de jugador en demo
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos. // --- Sistema de balas y proyectiles ---
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo). void updateBullets(); // Actualiza posición y estado de todas las balas
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal. void renderBullets(); // Renderiza todas las balas activas
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado. void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea una nueva bala
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio. void checkBulletCollision(); // Verifica colisiones de todas las balas
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador. void freeBullets(); // Libera memoria del vector de balas
void initDemo(int player_id); // Inicializa las variables para el modo DEMO
void setTotalPower(); // Calcula el poder total necesario para completar el juego // --- Colisiones específicas de balas ---
void initScoreboard(); // Inicializa el marcador auto checkBulletTabeCollision(std::shared_ptr<Bullet> bullet) -> bool; // Detecta colisión bala-Tabe
void initDifficultyVars(); // Inicializa las opciones relacionadas con la dificultad auto checkBulletBalloonCollision(std::shared_ptr<Bullet> bullet) -> bool; // Detecta colisión bala-globo
void initPlayers(int player_id); // Inicializa los jugadores void processBalloonHit(std::shared_ptr<Bullet> bullet, std::shared_ptr<Balloon> balloon); // Procesa impacto en globo
static void playMusic(); // Hace sonar la música
void stopMusic() const; // Detiene la música // --- Sistema de ítems y power-ups ---
void playSound(const std::string &name) const; // Hace sonar un sonido void updateItems(); // Actualiza posición y estado de todos los ítems
void updateDemo(); // Actualiza las variables durante el modo demo void renderItems(); // Renderiza todos los ítems activos
void updateGameStateFadeIn(); // Actualiza las variables durante dicho estado auto dropItem() -> ItemType; // Determina aleatoriamente qué ítem soltar
void updateGameStateEnteringPlayer(); // Actualiza las variables durante dicho estado void createItem(ItemType type, float x, float y); // Crea un nuevo ítem en posición específica
void updateGameStateShowingGetReadyMessage(); // Actualiza las variables durante dicho estado void freeItems(); // Libera memoria del vector de ítems
void updateGameStatePlaying(); // Actualiza las variables durante el transcurso normal del juego void destroyAllItems(); // Elimina todos los ítems activos de la pantalla
void updateGameStateCompleted(); // Gestiona eventos para el estado del final del juego
void checkState(); // Comprueba el estado del juego // --- ítems especiales ---
void cleanVectors(); // Vacía los vectores de elementos deshabilitados void enableTimeStopItem(); // Activa el efecto de detener el tiempo
void updateMenace(); // Gestiona el nivel de amenaza void disableTimeStopItem(); // Desactiva el efecto de detener el tiempo
void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos void updateTimeStopped(); // Actualiza el estado del tiempo detenido
void checkAndUpdateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado
void setState(GameState state); // Cambia el estado del juego
void movePlayersToFront(); // Organiza los jugadores para que los vivos se pinten sobre los muertos // --- Gestión de caída de ítems ---
void checkServiceMenu(); // Comprueba si está activo el menu de servicio para poner el juego en pausa void handleItemDrop(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player); // Gestiona caída de ítem desde globo
auto checkBulletTabeCollision(std::shared_ptr<Bullet> bullet) -> bool;
void handleTabeHitEffects(); // --- Sprites inteligentes (smartsprites) ---
auto checkBulletBalloonCollision(std::shared_ptr<Bullet> bullet) -> bool; void updateSmartSprites(); // Actualiza todos los sprites con lógica propia
void processBalloonHit(std::shared_ptr<Bullet> bullet, std::shared_ptr<Balloon> balloon); void renderSmartSprites(); // Renderiza todos los sprites inteligentes
void handleItemDrop(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player); void freeSmartSprites(); // Libera memoria de sprites inteligentes
void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player);
// --- Sprites por ruta (pathsprites) ---
void updatePathSprites(); // Actualiza sprites que siguen rutas predefinidas
void renderPathSprites(); // Renderiza sprites animados por ruta
void freePathSprites(); // Libera memoria de sprites por ruta
void initPaths(); // Inicializa rutas predefinidas para animaciones
// --- Creación de sprites especiales ---
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea texto animado para ítems
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture); // Crea mensaje con animación por ruta
// --- Sistema de globos y enemigos ---
void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, std::shared_ptr<Player> player); // Procesa destrucción de globo
void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe
void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso
// --- Gestión de fases y progresión ---
void updateStage(); // Verifica y actualiza cambio de fase
void setTotalPower(); // Calcula poder total necesario para completar el juego
void initDifficultyVars(); // Inicializa variables de dificultad
// --- Sistema de amenaza ---
void updateMenace(); // Gestiona el nivel de amenaza del juego
void evaluateAndSetMenace(); // Calcula y establece amenaza según globos activos
// --- Puntuación y marcador ---
void updateHiScore(); // Actualiza el récord máximo si es necesario
void updateScoreboard(); // Actualiza la visualización del marcador
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade puntuación del jugador al marcador
void initScoreboard(); // Inicializa el sistema de puntuación
// --- Modo demostración ---
void initDemo(int player_id); // Inicializa variables para el modo demostración
void updateDemo(); // Actualiza lógica específica del modo demo
// --- Recursos y renderizado ---
void setResources(); // Asigna texturas y animaciones a los objetos
void updateBackground(); // Actualiza elementos del fondo
void fillCanvas(); // Renderiza elementos del área de juego en su textura
void updateHelper(); // Actualiza variables auxiliares de renderizado
// --- Sistema de audio ---
static void playMusic(); // Reproduce la música de fondo
void stopMusic() const; // Detiene la reproducción de música
void playSound(const std::string &name) const; // Reproduce un efecto de sonido específico
// --- Utilidades y servicios ---
void checkServiceMenu(); // Verifica si el menú de servicio está activo
// SISTEMA DE GRABACIÓN (CONDICIONAL)
#ifdef RECORDING #ifdef RECORDING
void updateRecording(); // Actualiza las variables durante el modo de grabación void updateRecording(); // Actualiza variables durante modo de grabación
#endif
// --- Depuración (solo en modo DEBUG) ---
#ifdef _DEBUG
void checkDebugEvents(const SDL_Event &event); // Comprueba los eventos en el modo DEBUG
#endif #endif
}; };

View File

@@ -56,29 +56,33 @@ HiScoreTable::~HiScoreTable() {
// Actualiza las variables // Actualiza las variables
void HiScoreTable::update() { void HiScoreTable::update() {
if (SDL_GetTicks() - ticks_ > param.game.speed) { if (SDL_GetTicks() - ticks_ > param.game.speed) {
// Actualiza el contador de ticks ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks
ticks_ = SDL_GetTicks(); Screen::get()->update(); // Actualiza el objeto screen
// Actualiza las posiciones de los sprites de texto updateSprites(); // Actualiza las posiciones de los sprites de texto
updateSprites(); background_->update(); // Actualiza el fondo
updateFade(); // Gestiona el fade
// Actualiza el fondo updateCounter(); // Gestiona el contador y sus eventos
background_->update(); fillTexture(); // Dibuja los sprites en la textura
// Gestiona el fade
updateFade();
// Gestiona el contador y sus eventos
updateCounter();
// Dibuja los sprites en la textura
fillTexture();
// Actualiza el objeto screen
Screen::get()->update();
// Actualiza las variables de globalInputs
} }
static const auto audio = Audio::get();
audio->update();
}
// Pinta en pantalla
void HiScoreTable::render() {
static const auto screen = Screen::get();
screen->start(); // Prepara para empezar a dibujar en la textura de juego
screen->clean(); // Limpia la pantalla
background_->render(); // Pinta el fondo
view_area_.y = std::max(0.0F, param.game.height - counter_ + 100); // Establece la ventana del backbuffer
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador
fade_->render(); // Renderiza el fade
screen->render(); // Vuelca el contenido del renderizador en pantalla
} }
// Dibuja los sprites en la textura // Dibuja los sprites en la textura
@@ -101,30 +105,6 @@ void HiScoreTable::fillTexture() {
SDL_SetRenderTarget(renderer_, temp); SDL_SetRenderTarget(renderer_, temp);
} }
// Pinta en pantalla
void HiScoreTable::render() {
// Prepara para empezar a dibujar en la textura de juego
Screen::get()->start();
// Limpia la pantalla
Screen::get()->clean();
// Pinta el fondo
background_->render();
// Establece la ventana del backbuffer
view_area_.y = std::max(0.0F, param.game.height - counter_ + 100);
// Copia el backbuffer al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_);
// Renderiza el fade
fade_->render();
// Vuelca el contenido del renderizador en pantalla
Screen::get()->render();
}
// Comprueba los eventos // Comprueba los eventos
void HiScoreTable::checkEvents() { void HiScoreTable::checkEvents() {
SDL_Event event; SDL_Event event;

View File

@@ -206,42 +206,29 @@ void Instructions::fillBackbuffer() {
// Actualiza las variables // Actualiza las variables
void Instructions::update() { void Instructions::update() {
if (SDL_GetTicks() - ticks_ > param.game.speed) { if (SDL_GetTicks() - ticks_ > param.game.speed) {
// Actualiza el contador de ticks ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks
ticks_ = SDL_GetTicks(); Screen::get()->update(); // Actualiza el objeto screen
// Actualiza el objeto screen counter_++; // Incrementa el contador
Screen::get()->update(); updateSprites(); // Actualiza los sprites
updateBackbuffer(); // Gestiona la textura con los graficos
// Incrementa el contador tiled_bg_->update(); // Actualiza el mosaico de fondo
counter_++; fade_->update(); // Actualiza el objeto "fade"
fillBackbuffer(); // Rellena el backbuffer
// Actualiza los sprites
updateSprites();
// Gestiona la textura con los graficos
updateBackbuffer();
// Actualiza el mosaico de fondo
tiled_bg_->update();
// Actualiza el objeto "fade"
fade_->update();
// Rellena el backbuffer
fillBackbuffer();
} }
static const auto audio = Audio::get();
audio->update();
} }
// Pinta en pantalla // Pinta en pantalla
void Instructions::render() { void Instructions::render() {
// Prepara para empezar a dibujar en la textura de juego static const auto screen = Screen::get();
Screen::get()->start();
// Limpia la pantalla screen->start();// Prepara para empezar a dibujar en la textura de juego
Screen::get()->clean(); screen->clean();// Limpia la pantalla
// Dibuja el mosacico de fondo tiled_bg_->render();// Dibuja el mosacico de fondo
tiled_bg_->render();
// Copia la textura y el backbuffer al renderizador // Copia la textura y el backbuffer al renderizador
if (view_.y == 0) { if (view_.y == 0) {
@@ -250,10 +237,9 @@ void Instructions::render() {
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_); SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_);
} }
fade_->render(); fade_->render(); // Renderiza el fundido
// Vuelca el contenido del renderizador en pantalla screen->render();// Vuelca el contenido del renderizador en pantalla
Screen::get()->render();
} }
// Comprueba los eventos // Comprueba los eventos

View File

@@ -222,11 +222,10 @@ void Intro::switchText(int from_index, int to_index) {
// Actualiza las variables del objeto // Actualiza las variables del objeto
void Intro::update() { void Intro::update() {
if (SDL_GetTicks() - ticks_ > param.game.speed) { if (SDL_GetTicks() - ticks_ > param.game.speed) {
// Actualiza el contador de ticks ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks
ticks_ = SDL_GetTicks(); Screen::get()->update(); // Actualiza el objeto screen
// Actualiza el fondo tiled_bg_->update(); // Actualiza el fondo
tiled_bg_->update();
switch (state_) { switch (state_) {
case IntroState::SCENES: case IntroState::SCENES:
@@ -239,22 +238,20 @@ void Intro::update() {
updatePostState(); updatePostState();
break; break;
} }
// Actualiza el objeto screen
Screen::get()->update();
} }
static const auto audio = Audio::get();
audio->update();
} }
// Dibuja el objeto en pantalla // Dibuja el objeto en pantalla
void Intro::render() { void Intro::render() {
// Prepara para empezar a dibujar en la textura de juego static const auto screen = Screen::get();
Screen::get()->start();
// Limpia la pantalla screen->start();// Prepara para empezar a dibujar en la textura de juego
Screen::get()->clean(); screen->clean();// Limpia la pantalla
// Dibuja el fondo tiled_bg_->render();// Dibuja el fondo
tiled_bg_->render();
switch (state_) { switch (state_) {
case IntroState::SCENES: { case IntroState::SCENES: {
@@ -267,8 +264,7 @@ void Intro::render() {
break; break;
} }
// Vuelca el contenido del renderizador en pantalla screen->render();// Vuelca el contenido del renderizador en pantalla
Screen::get()->render();
} }
// Bucle principal // Bucle principal

View File

@@ -132,31 +132,28 @@ void Logo::updateTextureColors() {
// Actualiza las variables // Actualiza las variables
void Logo::update() { void Logo::update() {
if (SDL_GetTicks() - ticks_ > param.game.speed) { if (SDL_GetTicks() - ticks_ > param.game.speed) {
// Actualiza el contador de ticks ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks
ticks_ = SDL_GetTicks(); Screen::get()->update(); // Actualiza el objeto screen
// Actualiza el objeto screen updateJAILGAMES(); // Actualiza el logo de JAILGAMES
Screen::get()->update(); updateTextureColors(); // Actualiza los colores de las texturas
++counter_; // Gestiona el contador
// Comprueba las entradas
checkInput();
updateJAILGAMES();
updateTextureColors();
// Gestiona el contador
++counter_;
} }
static const auto audio = Audio::get();
audio->update();
} }
// Dibuja en pantalla // Dibuja en pantalla
void Logo::render() { void Logo::render() {
Screen::get()->start(); static const auto screen = Screen::get();
Screen::get()->clean();
screen->start();
screen->clean();
renderJAILGAMES(); renderJAILGAMES();
Screen::get()->render(); screen->render();
} }
// Bucle para el logo del juego // Bucle para el logo del juego

View File

@@ -79,29 +79,34 @@ Title::~Title() {
void Title::update() { void Title::update() {
if (SDL_GetTicks() - ticks_ > param.game.speed) { if (SDL_GetTicks() - ticks_ > param.game.speed) {
ticks_ = SDL_GetTicks(); ticks_ = SDL_GetTicks();
Screen::get()->update();
updateFade(); updateFade();
updateState(); updateState();
updateStartPrompt(); updateStartPrompt();
updatePlayers(); updatePlayers();
Screen::get()->update();
} }
static const auto audio = Audio::get();
audio->update();
} }
// Dibuja el objeto en pantalla // Dibuja el objeto en pantalla
void Title::render() { void Title::render() {
Screen::get()->start(); static const auto screen = Screen::get();
Screen::get()->clean();
screen->start();
screen->clean();
tiled_bg_->render(); tiled_bg_->render();
game_logo_->render(); game_logo_->render();
renderPlayers(); renderPlayers();
renderStartPrompt(); renderStartPrompt();
renderCopyright(); renderCopyright();
define_buttons_->render(); define_buttons_->render();
fade_->render(); fade_->render();
Screen::get()->render(); screen->render();
} }
// Comprueba los eventos // Comprueba los eventos