diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 1df4f78..ab452b1 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -217,7 +217,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so // Se introducen los valores separados por comas en un vector std::stringstream ss(value); std::string tmp; - SDL_Rect rect = {0, 0, frame_width, frame_height}; + SDL_FRect rect = {0, 0, frame_width, frame_height}; while (getline(ss, tmp, ',')) { // Comprueba que el tile no sea mayor que el maximo indice permitido diff --git a/source/animated_sprite.h b/source/animated_sprite.h index fb15d37..4bc5e8f 100644 --- a/source/animated_sprite.h +++ b/source/animated_sprite.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para shared_ptr #include // Para string #include // Para vector @@ -9,13 +9,13 @@ class Texture; // lines 9-9 struct Animation { - std::string name; // Nombre de la animacion - std::vector frames; // Cada uno de los frames que componen la animación - int speed; // Velocidad de la animación - int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva - bool completed; // Indica si ha finalizado la animación - int current_frame; // Frame actual - int counter; // Contador para las animaciones + std::string name; // Nombre de la animacion + std::vector frames; // Cada uno de los frames que componen la animación + int speed; // Velocidad de la animación + int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva + bool completed; // Indica si ha finalizado la animación + int current_frame; // Frame actual + int counter; // Contador para las animaciones Animation() : name(std::string()), speed(5), loop(0), completed(false), current_frame(0), counter(0) {} }; diff --git a/source/background.cpp b/source/background.cpp index c8ed159..ca9c4ca 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -1,3 +1,4 @@ +#define _USE_MATH_DEFINES #include "background.h" #include // Para SDL_BLENDMODE_BLEND #include // Para SDL_PIXELFORMAT_RGBA8888 @@ -46,8 +47,8 @@ Background::Background() const float BOTTOM_CLOUDS_TEXTURE_HEIGHT = bottom_clouds_texture_->getHeight() / 4; for (int i = 0; i < 4; ++i) { - top_clouds_rect_[i] = {0, i * TOP_CLOUDS_TEXTURE_HEIGHT, top_clouds_texture_->getWidth(), TOP_CLOUDS_TEXTURE_HEIGHT}; - bottom_clouds_rect_[i] = {0, i * BOTTOM_CLOUDS_TEXTURE_HEIGHT, bottom_clouds_texture_->getWidth(), BOTTOM_CLOUDS_TEXTURE_HEIGHT}; + top_clouds_rect_[i] = {0, i * TOP_CLOUDS_TEXTURE_HEIGHT, static_cast(top_clouds_texture_->getWidth()), TOP_CLOUDS_TEXTURE_HEIGHT}; + bottom_clouds_rect_[i] = {0, i * BOTTOM_CLOUDS_TEXTURE_HEIGHT, static_cast(bottom_clouds_texture_->getWidth()), BOTTOM_CLOUDS_TEXTURE_HEIGHT}; } } @@ -56,11 +57,11 @@ Background::Background() const float TOP_CLOUDS_Y = base_ - 165; const float BOTTOM_CLOUDS_Y = base_ - 101; - top_clouds_sprite_a_ = std::make_unique(top_clouds_texture_, (SDL_Rect){0, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); - top_clouds_sprite_b_ = std::make_unique(top_clouds_texture_, (SDL_Rect){rect_.w, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); + top_clouds_sprite_a_ = std::make_unique(top_clouds_texture_, (SDL_FRect){0, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); + top_clouds_sprite_b_ = std::make_unique(top_clouds_texture_, (SDL_FRect){rect_.w, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); - bottom_clouds_sprite_a_ = std::make_unique(bottom_clouds_texture_, (SDL_Rect){0, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); - bottom_clouds_sprite_b_ = std::make_unique(bottom_clouds_texture_, (SDL_Rect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); + bottom_clouds_sprite_a_ = std::make_unique(bottom_clouds_texture_, (SDL_FRect){0, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); + bottom_clouds_sprite_b_ = std::make_unique(bottom_clouds_texture_, (SDL_FRect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); buildings_sprite_ = std::make_unique(buildings_texture_); gradient_sprite_ = std::make_unique(gradients_texture_, 0, 0, rect_.w, rect_.h); diff --git a/source/background.h b/source/background.h index 1b71204..888eb2d 100644 --- a/source/background.h +++ b/source/background.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point +#include // Para SDL_FRect, SDL_Point #include // Para SDL_Texture, SDL_Renderer #include // Para size_t #include // Para unique_ptr, shared_ptr @@ -71,17 +71,17 @@ private: SDL_Texture *color_texture_; // Textura para atenuar el fondo // Variables - SDL_FRect gradient_rect_[4]; // Vector con las coordenadas de los 4 degradados para el cielo - SDL_FRect top_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de arriba - SDL_FRect bottom_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de abajo + SDL_FRect gradient_rect_[4]; // Vector con las coordenadas de los 4 degradados para el cielo + SDL_FRect top_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de arriba + SDL_FRect bottom_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de abajo int gradient_number_ = 0; // Indica el número de degradado de fondo que se va a dibujar int alpha_ = 0; // Transparencia entre los dos degradados float clouds_speed_ = 0; // Velocidad a la que se desplazan las nubes float transition_ = 0; // Nivel de transición del fondo 0..1 int counter_ = 0; // Contador interno - SDL_FRect rect_; // Tamaño del objeto fondo - SDL_FRect src_rect_; // Parte del objeto fondo que se va a dibujará en pantalla - SDL_FRect dst_rect_; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla + SDL_FRect rect_; // Tamaño del objeto fondo + SDL_FRect src_rect_; // Parte del objeto fondo que se va a dibujará en pantalla + SDL_FRect dst_rect_; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla int base_; // Linea de fondo coincidente con el area inferior de la zona de juego Color attenuate_color_; // Color para atenuar el fondo int alpha_color_text_; // Alpha para atenuar el fondo diff --git a/source/balloon.cpp b/source/balloon.cpp index 870a20b..8c15831 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -9,7 +9,7 @@ #include "jail_audio.h" // Constructor -Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel_x, float speed, Uint16 creation_timer, SDL_Rect play_area, std::shared_ptr texture, const std::vector &animation) +Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, std::shared_ptr texture, const std::vector &animation) : sprite_(std::make_unique(texture, animation)), x_(x), y_(y), diff --git a/source/balloon.h b/source/balloon.h index 89c4820..cd7dec9 100644 --- a/source/balloon.h +++ b/source/balloon.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para Uint8, Uint16, Uint32 #include // Para shared_ptr, unique_ptr #include // Para string @@ -113,7 +113,7 @@ private: float travel_y_ = 1.0f; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad float speed_; // Velocidad a la que se mueven los globos Uint8 power_; // Cantidad de poder que alberga el globo - SDL_Rect play_area_; // Zona por donde se puede mover el globo + SDL_FRect play_area_; // Zona por donde se puede mover el globo std::string sound_; // Archivo de sonido que hace el globo al rebotar bool sound_enabled_ = false; // Indica si ha de sonar el sonido del globo al rebotar @@ -154,7 +154,7 @@ public: float vel_x, float speed, Uint16 creation_timer, - SDL_Rect play_area, + SDL_FRect play_area, std::shared_ptr texture, const std::vector &animation); diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index 0fccc90..0d7e041 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -381,7 +381,7 @@ void BalloonManager::createRandomBalloons() const int num_balloons = 2 + rand() % 4; for (int i = 0; i < num_balloons; ++i) { - const float x = param.game.game_area.rect.x + (rand() % param.game.game_area.rect.w) - BALLOON_SIZE[3]; + const float x = param.game.game_area.rect.x + (rand() % static_cast(param.game.game_area.rect.w)) - BALLOON_SIZE[3]; const int y = param.game.game_area.rect.y + (rand() % 50); const BalloonSize size = static_cast(rand() % 4); const float vel_x = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE; diff --git a/source/balloon_manager.h b/source/balloon_manager.h index a3fb7fc..9cc1b4e 100644 --- a/source/balloon_manager.h +++ b/source/balloon_manager.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para shared_ptr, unique_ptr #include // Para string #include // Para vector @@ -26,15 +26,15 @@ private: std::vector> balloon_animations_; // Vector con las animaciones de los globos std::vector> explosions_animations_; // Vector con las animaciones de las explosiones - float balloon_speed_ = BALLOON_SPEED[0]; // Velocidad a la que se mueven los enemigos - float default_balloon_speed_ = BALLOON_SPEED[0]; // Velocidad base de los enemigos, sin incrementar - int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero - bool power_ball_enabled_ = false; // Indica si hay una powerball ya activa - int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra - int last_balloon_deploy_ = 0; // Guarda cual ha sido la última formación desplegada para no repetir; + float balloon_speed_ = BALLOON_SPEED[0]; // Velocidad a la que se mueven los enemigos + float default_balloon_speed_ = BALLOON_SPEED[0]; // Velocidad base de los enemigos, sin incrementar + int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero + bool power_ball_enabled_ = false; // Indica si hay una powerball ya activa + int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra + int last_balloon_deploy_ = 0; // Guarda cual ha sido la última formación desplegada para no repetir; SDL_FRect play_area_ = param.game.play_area.rect; // Zona por donde se moveran los globos - bool creation_time_enabled_ = true; // Indica si los globos se crean con tiempo - bool can_deploy_balloons_ = true; // Indica si creará globos + bool creation_time_enabled_ = true; // Indica si los globos se crean con tiempo + bool can_deploy_balloons_ = true; // Indica si creará globos // Inicializa void init(); diff --git a/source/bullet.cpp b/source/bullet.cpp index 507bbba..298f6a7 100644 --- a/source/bullet.cpp +++ b/source/bullet.cpp @@ -1,5 +1,5 @@ #include "bullet.h" -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para unique_ptr, make_unique, shared_ptr #include "param.h" // Para Param, ParamGame, param #include "sprite.h" // Para Sprite @@ -7,7 +7,7 @@ class Texture; // lines 5-5 // Constructor Bullet::Bullet(int x, int y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr texture) - : sprite_(std::make_unique(texture, SDL_Rect{x, y, BULLET_WIDTH_, BULLET_HEIGHT_})), + : sprite_(std::make_unique(texture, SDL_FRect{x, y, BULLET_WIDTH_, BULLET_HEIGHT_})), pos_x_(x), pos_y_(y), bullet_type_(bullet_type), diff --git a/source/credits.h b/source/credits.h index 432a16b..ad0696e 100644 --- a/source/credits.h +++ b/source/credits.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_Texture #include // Para Uint32 #include // Para unique_ptr, shared_ptr @@ -49,7 +49,7 @@ private: param.game.game_area.rect.x, param.game.game_area.rect.y + black_bars_size_, param.game.game_area.rect.w, - PLAY_AREA_HEIGHT}; // Area visible para los creditos + PLAY_AREA_HEIGHT}; // Area visible para los creditos SDL_FRect top_black_rect_ = {play_area_.x, param.game.game_area.rect.y, play_area_.w, black_bars_size_}; // Rectangulo negro superior SDL_FRect bottom_black_rect_ = {play_area_.x, param.game.game_area.rect.h - black_bars_size_, play_area_.w, black_bars_size_}; // Rectangulo negro inferior SDL_FRect left_black_rect_ = {play_area_.x, param.game.game_area.center_y - 1, 0, 2}; // Rectangulo negro situado a la izquierda diff --git a/source/director.cpp b/source/director.cpp index 0605567..38325bc 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -24,7 +24,6 @@ #include // Para vector #include "asset.h" // Para Asset, AssetType #include "credits.h" // Para Credits -#include "dbgtxt.h" // Para dbg_init #include "game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_... #include "hiscore_table.h" // Para HiScoreTable #include "input.h" // Para Input, InputAction @@ -103,7 +102,6 @@ void Director::init() initSDL(); SDL_HideCursor(); initJailAudio(); - dbg_init(renderer_); lang::loadFromFile(getLangFile(static_cast(options.game.language))); Screen::init(window_, renderer_); Resource::init(); diff --git a/source/fade.h b/source/fade.h index 2bbfe2f..b564cd5 100644 --- a/source/fade.h +++ b/source/fade.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_Renderer, SDL_Texture #include // Para Uint8, Uint16 #include // Para vector diff --git a/source/game.cpp b/source/game.cpp index e1096fb..6a099ae 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -795,12 +795,12 @@ void Game::createItemText(int x, std::shared_ptr texture) const int y2 = -h; // Ajusta para que no se dibuje fuera de pantalla - x = std::clamp(x, 2, param.game.play_area.rect.w - w - 2); + x = std::clamp(x, 2, static_cast(param.game.play_area.rect.w) - w - 2); // Inicializa path_sprites_.back()->setWidth(w); path_sprites_.back()->setHeight(h); - path_sprites_.back()->setSpriteClip({0, 0, w, h}); + path_sprites_.back()->setSpriteClip({0, 0, static_cast(w), static_cast(h)}); path_sprites_.back()->addPath(y0, y1, PathType::VERTICAL, x, 100, easeOutQuint, 0); path_sprites_.back()->addPath(y1, y2, PathType::VERTICAL, x, 80, easeInQuint, 0); path_sprites_.back()->enable(); @@ -1225,24 +1225,20 @@ void Game::checkEvents() SDL_Event event; while (SDL_PollEvent(&event)) { - if (event.type == SDL_WINDOWEVENT) + switch (event.type) { - switch (event.window.event) - { - case SDL_WINDOWEVENT_FOCUS_LOST: - { - pause(!demo_.enabled); - break; - } - case SDL_WINDOWEVENT_FOCUS_GAINED: - { - pause(false); - break; - } - - default: - break; - } + case SDL_EVENT_WINDOW_FOCUS_LOST: + { + pause(!demo_.enabled); + break; + } + case SDL_EVENT_WINDOW_FOCUS_GAINED: + { + pause(false); + break; + } + default: + break; } #ifdef DEBUG @@ -1987,9 +1983,9 @@ void Game::setState(GameState state) // Comprueba los eventos en el modo DEBUG void Game::checkDebugEvents(const SDL_Event &event) { - if (event.type == SDL_KEYDOWN && event.key.repeat == 0) + if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) { - switch (event.key.keysym.sym) + switch (event.key.key) { case SDLK_1: // Crea una powerball { diff --git a/source/global_events.cpp b/source/global_events.cpp index 564a25d..123c576 100644 --- a/source/global_events.cpp +++ b/source/global_events.cpp @@ -11,19 +11,16 @@ namespace globalEvents { switch (event.type) { - case SDL_QUIT: // Evento de salida de la aplicación + case SDL_EVENT_QUIT: // Evento de salida de la aplicación section::name = section::Name::QUIT; section::options = section::Options::QUIT_FROM_EVENT; return; - case SDL_RENDER_DEVICE_RESET: - case SDL_RENDER_TARGETS_RESET: + case SDL_EVENT_RENDER_DEVICE_RESET: + case SDL_EVENT_RENDER_TARGETS_RESET: std::cout << "SDL_RENDER_TARGETS_RESET" << std::endl; break; - case SDL_WINDOWEVENT: - if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) - { - std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl; - } + case SDL_EVENT_WINDOW_RESIZED: + std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl; break; default: break; diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index e976905..314313a 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -78,7 +78,7 @@ namespace globalInputs void toggleintegerScale() { options.video.integer_scale = !options.video.integer_scale; - SDL_RenderSetIntegerScale(Screen::get()->getRenderer(), options.video.integer_scale ? SDL_TRUE : SDL_FALSE); + SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX); Screen::get()->setVideoMode(); Notifier::get()->show({lang::getText(134) + " " + boolToOnOff(options.video.integer_scale)}); } diff --git a/source/hiscore_table.cpp b/source/hiscore_table.cpp index a0072a7..4a4c313 100644 --- a/source/hiscore_table.cpp +++ b/source/hiscore_table.cpp @@ -1,7 +1,8 @@ #include "hiscore_table.h" -#include // Para SDL_BLENDMODE_BLEND +#include // Para SDL_BLENDMODE_BLEND #include // Para SDL_PollEvent, SDL_Event #include // Para SDL_PIXELFORMAT_RGBA8888 +#include // Para SDL_QueryTexture #include // Para SDL_GetTicks #include // Para rand, size_t #include // Para max @@ -33,7 +34,7 @@ HiScoreTable::HiScoreTable() background_(std::make_unique()), counter_(0), ticks_(0), - view_area_({0, 0, param.game.width, param.game.height}), + view_area_(SDL_FRect{0, 0, static_cast(param.game.width), static_cast(param.game.height)}), fade_mode_(FadeMode::IN), background_fade_color_(Color(0, 0, 0)) { @@ -214,15 +215,15 @@ void HiScoreTable::createSprites() auto entry_text = Resource::get()->getText("smb2"); // Obtiene el tamaño de la textura - int backbuffer_width; - int backbuffer_height; - SDL_QueryTexture(backbuffer_, nullptr, nullptr, &backbuffer_width, &backbuffer_height); + float backbuffer_width; + float backbuffer_height; + SDL_GetTextureSize(backbuffer_, &backbuffer_width, &backbuffer_height); - constexpr int entry_lenght = 22; - constexpr int max_names = 10; + constexpr int ENTRY_LENGHT = 22; + constexpr int MAX_NAMES = 10; const int space_between_header = entry_text->getCharacterSize() * 4; const int space_between_lines = entry_text->getCharacterSize() * 2; - const int size = space_between_header + space_between_lines * (max_names - 1) + entry_text->getCharacterSize(); + const int size = space_between_header + space_between_lines * (MAX_NAMES - 1) + entry_text->getCharacterSize(); const int first_line = (param.game.height - size) / 2; // Crea el sprite para el texto de cabecera @@ -231,14 +232,14 @@ void HiScoreTable::createSprites() // Crea los sprites para las entradas en la tabla de puntuaciones const int animation = rand() % 4; - const std::string sample_line(entry_lenght + 3, ' '); + const std::string sample_line(ENTRY_LENGHT + 3, ' '); auto sample_entry = std::make_unique(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, orange_color, 1, shdw_txt_color)); const auto entry_width = sample_entry->getWidth(); - for (int i = 0; i < max_names; ++i) + for (int i = 0; i < MAX_NAMES; ++i) { const auto table_position = format(i + 1) + ". "; const auto score = format(options.game.hi_score_table.at(i).score); - const auto num_dots = entry_lenght - options.game.hi_score_table.at(i).name.size() - score.size(); + const auto num_dots = ENTRY_LENGHT - options.game.hi_score_table.at(i).name.size() - score.size(); const auto one_cc = options.game.hi_score_table.at(i).one_credit_complete ? " }" : ""; std::string dots; for (int j = 0; j < (int)num_dots; ++j) diff --git a/source/hiscore_table.h b/source/hiscore_table.h index de30de7..7d301b5 100644 --- a/source/hiscore_table.h +++ b/source/hiscore_table.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_Renderer, SDL_Texture #include // Para Uint16, Uint32, Uint8 #include // Para unique_ptr, shared_ptr @@ -44,7 +44,7 @@ private: // Variables Uint16 counter_ = 0; // Contador Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - SDL_Rect view_area_; // Parte de la textura que se muestra en pantalla + SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla FadeMode fade_mode_; // Modo de fade a utilizar Color background_fade_color_; // Color de atenuación del fondo std::vector entry_colors_; // Colores para destacar las entradas en la tabla diff --git a/source/input.cpp b/source/input.cpp index 89ad070..37b9b6d 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -52,7 +52,7 @@ void Input::bindKey(InputAction input, SDL_Scancode code) } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GameControllerButton button) +void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button) { if (controller_index < num_gamepads_) { @@ -78,7 +78,7 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) { - const Uint8 *keyStates = SDL_GetKeyboardState(nullptr); + const bool *keyStates = SDL_GetKeyboardState(nullptr); if (repeat) { @@ -119,13 +119,13 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, { if (repeat) { - success_controller = SDL_GameControllerGetButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0; + success_controller = SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0; } else { if (!controller_bindings_.at(controller_index).at(input_index).active) { - if (SDL_GameControllerGetButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0) + if (SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) != 0) { controller_bindings_.at(controller_index).at(input_index).active = true; success_controller = true; @@ -137,7 +137,7 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, } else { - if (SDL_GameControllerGetButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) == 0) + if (SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(input_index).button) == 0) { controller_bindings_.at(controller_index).at(input_index).active = false; } @@ -156,7 +156,7 @@ bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) { if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) { - const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr); + const bool *mKeystates = SDL_GetKeyboardState(nullptr); for (int i = 0; i < (int)key_bindings_.size(); ++i) { @@ -174,7 +174,7 @@ bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) { for (int i = 0; i < (int)controller_bindings_.size(); ++i) { - if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button) != 0 && !controller_bindings_[controller_index][i].active) + if (SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button) != 0 && !controller_bindings_[controller_index][i].active) { controller_bindings_[controller_index][i].active = true; return true; @@ -222,26 +222,26 @@ bool Input::discoverGameControllers() { bool found = false; - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) != 1) + if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) { - SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER); + SDL_InitSubSystem(SDL_INIT_GAMEPAD); } - if (SDL_GameControllerAddMappingsFromFile(game_controller_db_path_.c_str()) < 0) + if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) { std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl; } - num_joysticks_ = SDL_NumJoysticks(); + SDL_GetJoysticks(&num_joysticks_); num_gamepads_ = 0; // Cuenta el número de mandos joysticks_.clear(); for (int i = 0; i < num_joysticks_; ++i) { - auto joy = SDL_JoystickOpen(i); + auto joy = SDL_OpenJoystick(i); joysticks_.push_back(joy); - if (SDL_IsGameController(i)) + if (SDL_IsGamepad(i)) { num_gamepads_++; } @@ -265,11 +265,11 @@ bool Input::discoverGameControllers() for (int i = 0; i < num_gamepads_; i++) { // Abre el mando y lo añade a la lista - auto pad = SDL_GameControllerOpen(i); - if (SDL_GameControllerGetAttached(pad) == 1) + auto pad = SDL_OpenGamepad(i); + if (SDL_GamepadConnected(pad) == 1) { connected_controllers_.push_back(pad); - const std::string name = SDL_GameControllerNameForIndex(i); + const std::string name = SDL_GetGamepadNameForID(i); std::cout << "#" << i << ": " << name << std::endl; controller_names_.push_back(name); } @@ -279,7 +279,7 @@ bool Input::discoverGameControllers() } } - SDL_GameControllerEventState(SDL_ENABLE); + SDL_SetGamepadEventsEnabled(true); } std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << std::endl; @@ -300,7 +300,7 @@ int Input::getJoyIndex(int id) const { for (int i = 0; i < num_joysticks_; ++i) { - if (SDL_JoystickInstanceID(joysticks_[i]) == id) + if (SDL_GetJoystickID(joysticks_[i]) == id) { return i; } @@ -334,8 +334,8 @@ void Input::printBindings(InputDeviceToUse device, int controller_index) const } } -// Obtiene el SDL_GameControllerButton asignado a un input -SDL_GameControllerButton Input::getControllerBinding(int controller_index, InputAction input) const +// Obtiene el SDL_GamepadButton asignado a un input +SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const { return controller_bindings_[controller_index][static_cast(input)].button; } @@ -391,16 +391,16 @@ bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) switch (input) { case InputAction::LEFT: - axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) < -threshold; + axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -threshold; break; case InputAction::RIGHT: - axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) > threshold; + axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > threshold; break; case InputAction::UP: - axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) < -threshold; + axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -threshold; break; case InputAction::DOWN: - axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) > threshold; + axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > threshold; break; default: return false; diff --git a/source/instructions.cpp b/source/instructions.cpp index af14cbf..08f4709 100644 --- a/source/instructions.cpp +++ b/source/instructions.cpp @@ -86,7 +86,7 @@ void Instructions::iniSprites() // Actualiza los sprites void Instructions::updateSprites() { - SDL_Rect src_rect = {0, 0, param.game.item_size, param.game.item_size}; + SDL_FRect src_rect = {0, 0, param.game.item_size, param.game.item_size}; // Disquito src_rect.y = param.game.item_size * (((counter_ + 12) / 36) % 2); @@ -338,8 +338,8 @@ void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, con { for (const auto &line : lines) { - SDL_Rect srcRect = {0, line.y, 320, 1}; - SDL_Rect dstRect = {static_cast(line.x), line.y, 320, 1}; + SDL_FRect srcRect = {0, line.y, 320, 1}; + SDL_FRect dstRect = {static_cast(line.x), line.y, 320, 1}; SDL_RenderTexture(renderer, texture, &srcRect, &dstRect); } } diff --git a/source/instructions.h b/source/instructions.h index 3ac4bfc..0bee3c1 100644 --- a/source/instructions.h +++ b/source/instructions.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Point, SDL_Rect +#include // Para SDL_Point, SDL_FRect #include // Para SDL_Texture, SDL_Renderer #include // Para Uint32 #include // Para unique_ptr, shared_ptr @@ -55,7 +55,7 @@ private: // Variables int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa - SDL_Rect view_; // Vista del backbuffer que se va a mostrar por pantalla + SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista int item_space_ = 2; // Espacio entre los items en pantalla std::vector lines_; // Vector que contiene las líneas animadas en la pantalla diff --git a/source/intro.cpp b/source/intro.cpp index 8627b5e..cd3dcf2 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -2,7 +2,7 @@ #include // Para SDL_BLENDMODE_BLEND, SDL_BLENDMODE_MOD #include // Para SDL_PollEvent, SDL_Event #include // Para SDL_PIXELFORMAT_RGBA8888 -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_SetTextureBlendMode, SDL_GetRend... #include // Para SDL_GetTicks #include // Para array diff --git a/source/item.cpp b/source/item.cpp index 86128c4..a24ac89 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -5,7 +5,7 @@ #include "param.h" // Para Param, ParamGame, param class Texture; // lines 6-6 -Item::Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr texture, const std::vector &animation) +Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr texture, const std::vector &animation) : sprite_(std::make_unique(texture, animation)), type_(type), play_area_(play_area) @@ -16,7 +16,7 @@ Item::Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr { width_ = param.game.coffee_machine_w; height_ = param.game.coffee_machine_h; - pos_x_ = ((static_cast(x) + (play_area.w / 2)) % (play_area.w - width_ - 5)) + 2; + pos_x_ = (static_cast(x + (play_area.w / 2)) % static_cast(play_area.w - width_ - 5)) + 2; pos_y_ = y; vel_x_ = 0.0f; vel_y_ = -0.1f; diff --git a/source/item.h b/source/item.h index 28d5f90..2142c37 100644 --- a/source/item.h +++ b/source/item.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para Uint16 #include // Para shared_ptr, unique_ptr #include // Para string @@ -51,7 +51,7 @@ private: ItemType type_; /**< Especifica el tipo de objeto que es */ bool enabled_ = true; /**< Especifica si el objeto está habilitado */ Circle collider_; /**< Círculo de colisión del objeto */ - SDL_Rect play_area_; /**< Rectángulo con la zona de juego */ + SDL_FRect play_area_; /**< Rectángulo con la zona de juego */ Uint16 time_to_live_ = 600; /**< Temporizador con el tiempo que el objeto está presente */ /** @@ -101,7 +101,7 @@ public: * @param texture La textura del objeto. * @param animation La animación asociada al objeto. */ - Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr texture, const std::vector &animation); + Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr texture, const std::vector &animation); /** * @brief Destructor de la clase Item. diff --git a/source/jail_audio.cpp b/source/jail_audio.cpp index 5042432..92fc1ae 100644 --- a/source/jail_audio.cpp +++ b/source/jail_audio.cpp @@ -1,165 +1,163 @@ #ifndef JA_USESDLMIXER #include "jail_audio.h" -#include // Para SDL_RWFromMem -#include // Para SDL_GetTicks -#include // Para uint8_t, uint32_t -#include // Para NULL, fseek, fclose, fopen, fread, ftell -#include // Para free, malloc -#include "stb_vorbis.c" // Para stb_vorbis_decode_memory +#include "stb_vorbis.c" +#include +#include #define JA_MAX_SIMULTANEOUS_CHANNELS 20 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; + JA_Sound_t *sound{nullptr}; int pos{0}; int times{0}; + SDL_AudioStream *stream{nullptr}; JA_Channel_state state{JA_CHANNEL_FREE}; }; struct JA_Music_t { - int samples{0}; + SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; Uint32 length{0}; + Uint8 *buffer{nullptr}; + int pos{0}; int times{0}; - short *output{NULL}; + SDL_AudioStream *stream{nullptr}; JA_Music_state state{JA_MUSIC_INVALID}; }; -JA_Music_t *current_music{NULL}; +JA_Music_t *current_music{nullptr}; JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; -int JA_freq{48000}; -SDL_AudioFormat JA_format{AUDIO_S16}; -Uint8 JA_channels{2}; -int JA_musicVolume = 128; -int JA_soundVolume = 64; -bool JA_musicEnabled = true; -bool JA_soundEnabled = true; -SDL_AudioDeviceID sdlAudioDevice = 0; +SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000}; +float JA_musicVolume{1.0f}; +float JA_soundVolume{0.5f}; +bool JA_musicEnabled{true}; +bool JA_soundEnabled{true}; +SDL_AudioDeviceID sdlAudioDevice{0}; +SDL_TimerID JA_timerID{0}; -bool fading = false; -int fade_start_time; -int fade_duration; -int fade_initial_volume; - -void audioCallback(void *userdata, uint8_t *stream, int len) -{ +/* +void audioCallback(void * userdata, uint8_t * stream, int len) { SDL_memset(stream, 0, len); - if (current_music != NULL && current_music->state == JA_MUSIC_PLAYING) - { - int volume = JA_musicVolume; - if (fading) - { - int time = SDL_GetTicks(); - if (time > (fade_start_time + fade_duration)) - { - fading = false; - current_music->pos = 0; - current_music->state = JA_MUSIC_STOPPED; - volume = 0; - } - else - { - const int time_passed = time - fade_start_time; - const float percent = (float)time_passed / (float)fade_duration; - volume = JA_musicVolume * (1.0 - percent); - } - } - const int size = SDL_min(len, current_music->length - current_music->pos); - SDL_MixAudioFormat(stream, (Uint8 *)(current_music->output) + current_music->pos, AUDIO_S16, size, volume); - current_music->pos += size; - if (size < len) - { - if (current_music->times != 0) - { - SDL_MixAudioFormat(stream + size, (Uint8 *)current_music->output, AUDIO_S16, len - size, volume); - current_music->pos = len - size; - if (current_music->times > 0) - current_music->times--; - } - else - { + if (current_music != NULL && current_music->state == JA_MUSIC_PLAYING) { + const int size = SDL_min(len, current_music->samples*2-current_music->pos); + SDL_MixAudioFormat(stream, (Uint8*)(current_music->output+current_music->pos), AUDIO_S16, size, JA_musicVolume); + current_music->pos += size/2; + if (size < len) { + if (current_music->times != 0) { + SDL_MixAudioFormat(stream+size, (Uint8*)current_music->output, AUDIO_S16, len-size, JA_musicVolume); + current_music->pos = (len-size)/2; + if (current_music->times > 0) current_music->times--; + } else { current_music->pos = 0; current_music->state = JA_MUSIC_STOPPED; } } } // Mixar els channels mi amol - 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].state == JA_CHANNEL_PLAYING) { const int size = SDL_min(len, channels[i].sound->length - channels[i].pos); SDL_MixAudioFormat(stream, channels[i].sound->buffer + channels[i].pos, AUDIO_S16, size, JA_soundVolume); channels[i].pos += size; - if (size < len) - { - if (channels[i].times != 0) - { - SDL_MixAudioFormat(stream + size, channels[i].sound->buffer, AUDIO_S16, len - size, JA_soundVolume); - channels[i].pos = len - size; - if (channels[i].times > 0) - channels[i].times--; - } - else - { + if (size < len) { + if (channels[i].times != 0) { + SDL_MixAudioFormat(stream + size, channels[i].sound->buffer, AUDIO_S16, len-size, JA_soundVolume); + channels[i].pos = len-size; + if (channels[i].times > 0) channels[i].times--; + } else { JA_StopChannel(i); } } } } } +*/ + +Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval) +{ + if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) + { + if (current_music->times != 0) + { + if (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 (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); + } + } + + return 30; +} void JA_Init(const int freq, const SDL_AudioFormat format, const int channels) { - JA_freq = freq; - JA_format = format; - JA_channels = channels; - SDL_AudioSpec audioSpec{JA_freq, JA_format, JA_channels, 0, 1024, 0, 0, audioCallback, NULL}; - if (sdlAudioDevice != 0) + JA_audioSpec = {format, channels, freq}; + if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); - sdlAudioDevice = SDL_OpenAudioDevice(NULL, 0, &audioSpec, NULL, 0); - SDL_PauseAudioDevice(sdlAudioDevice, 0); + sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec); + SDL_PauseAudioDevice(sdlAudioDevice); + JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr); } void JA_Quit() { - SDL_PauseAudioDevice(sdlAudioDevice, 1); - if (sdlAudioDevice != 0) + if (JA_timerID) + SDL_RemoveTimer(JA_timerID); + + if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); sdlAudioDevice = 0; } JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length) { - int chan, samplerate; JA_Music_t *music = new JA_Music_t(); - music->samples = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &music->output); - // [RZC 28/08/22] Abans el descomprimiem mentre el teniem obert - // music->samples = stb_vorbis_decode_filename(filename, &chan, &samplerate, &music->output); + int chan, samplerate; + short *output; + music->length = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &output) * chan * 2; - SDL_AudioCVT cvt; - SDL_BuildAudioCVT(&cvt, AUDIO_S16, chan, samplerate, JA_format, JA_channels, JA_freq); - if (cvt.needed) - { - cvt.len = music->samples * chan * 2; - music->length = cvt.len; - cvt.buf = (Uint8 *)SDL_malloc(cvt.len * cvt.len_mult); - SDL_memcpy(cvt.buf, music->output, cvt.len); - SDL_ConvertAudio(&cvt); - free(music->output); - music->output = (short *)cvt.buf; - } - music->length = music->samples * chan * 2; + music->spec.channels = chan; + music->spec.freq = samplerate; + music->spec.format = SDL_AUDIO_S16; + music->buffer = (Uint8 *)SDL_malloc(music->length); + SDL_memcpy(music->buffer, output, music->length); + SDL_free(output); music->pos = 0; music->state = JA_MUSIC_STOPPED; @@ -199,94 +197,81 @@ void JA_PlayMusic(JA_Music_t *music, const int loop) 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 (!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"); } void JA_PauseMusic() { if (!JA_musicEnabled) return; - - if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) + if (!current_music || current_music->state == JA_MUSIC_INVALID) return; + current_music->state = JA_MUSIC_PAUSED; + SDL_PauseAudioStreamDevice(current_music->stream); } void JA_ResumeMusic() { if (!JA_musicEnabled) return; - - if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) + if (!current_music || current_music->state == JA_MUSIC_INVALID) return; + current_music->state = JA_MUSIC_PLAYING; + SDL_ResumeAudioStreamDevice(current_music->stream); } void JA_StopMusic() { if (!JA_musicEnabled) return; - - if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) + if (!current_music || current_music->state == JA_MUSIC_INVALID) return; + current_music->pos = 0; current_music->state = JA_MUSIC_STOPPED; -} - -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; + SDL_PauseAudioStreamDevice(current_music->stream); + SDL_DestroyAudioStream(current_music->stream); + current_music->stream = nullptr; } JA_Music_state JA_GetMusicState() { if (!JA_musicEnabled) return JA_MUSIC_DISABLED; - - if (current_music == NULL) + if (!current_music) return JA_MUSIC_INVALID; + return current_music->state; } void JA_DeleteMusic(JA_Music_t *music) { if (current_music == music) - current_music = NULL; - free(music->output); + current_music = nullptr; + SDL_free(music->buffer); + SDL_DestroyAudioStream(music->stream); delete music; } -int JA_SetMusicVolume(int volume) +float JA_SetMusicVolume(float volume) { - JA_musicVolume = volume > 128 ? 128 : volume < 0 ? 0 - : volume; + JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f); + if (current_music) + SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); return JA_musicVolume; } -void JA_SetMusicPosition(float value) -{ - if (!current_music) - return; - current_music->pos = value * JA_freq; -} - -float JA_GetMusicPosition() -{ - if (!current_music) - return 0; - return float(current_music->pos) / float(JA_freq); -} - void JA_EnableMusic(const bool value) { - if (!value && current_music != NULL && current_music->state == JA_MUSIC_PLAYING) + if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) JA_StopMusic(); JA_musicEnabled = value; @@ -303,18 +288,7 @@ JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length) JA_Sound_t *JA_LoadSound(uint8_t *buffer, uint32_t size) { JA_Sound_t *sound = new JA_Sound_t(); - SDL_AudioSpec wavSpec; - SDL_LoadWAV_RW(SDL_RWFromMem(buffer, size), 1, &wavSpec, &sound->buffer, &sound->length); - - SDL_AudioCVT cvt; - SDL_BuildAudioCVT(&cvt, wavSpec.format, wavSpec.channels, wavSpec.freq, JA_format, JA_channels, JA_freq); - cvt.len = sound->length; - cvt.buf = (Uint8 *)SDL_malloc(cvt.len * cvt.len_mult); - SDL_memcpy(cvt.buf, sound->buffer, sound->length); - SDL_ConvertAudio(&cvt); - SDL_FreeWAV(sound->buffer); - sound->buffer = cvt.buf; - sound->length = cvt.len_cvt; + SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length); return sound; } @@ -322,18 +296,7 @@ JA_Sound_t *JA_LoadSound(uint8_t *buffer, uint32_t size) JA_Sound_t *JA_LoadSound(const char *filename) { JA_Sound_t *sound = new JA_Sound_t(); - SDL_AudioSpec wavSpec; - SDL_LoadWAV(filename, &wavSpec, &sound->buffer, &sound->length); - - SDL_AudioCVT cvt; - SDL_BuildAudioCVT(&cvt, wavSpec.format, wavSpec.channels, wavSpec.freq, JA_format, JA_channels, JA_freq); - cvt.len = sound->length; - cvt.buf = (Uint8 *)SDL_malloc(cvt.len * cvt.len_mult); - SDL_memcpy(cvt.buf, sound->buffer, sound->length); - SDL_ConvertAudio(&cvt); - SDL_FreeWAV(sound->buffer); - sound->buffer = cvt.buf; - sound->length = cvt.len_cvt; + SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length); return sound; } @@ -355,21 +318,11 @@ int JA_PlaySound(JA_Sound_t *sound, const int loop) channels[channel].times = loop; channels[channel].pos = 0; channels[channel].state = JA_CHANNEL_PLAYING; - return channel; -} + channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec); + SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer, channels[channel].sound->length); + SDL_SetAudioStreamGain(channels[channel].stream, JA_soundVolume); + SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream); -int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop) -{ - if (!JA_soundEnabled) - return -1; - - if (channel >= JA_MAX_SIMULTANEOUS_CHANNELS) - return -1; - - channels[channel].sound = sound; - channels[channel].times = loop; - channels[channel].pos = 0; - channels[channel].state = JA_CHANNEL_PLAYING; return channel; } @@ -392,15 +345,19 @@ void JA_PauseChannel(const int channel) 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_PauseAudioStreamDevice(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_PauseAudioStreamDevice(channels[channel].stream); + } } } @@ -412,15 +369,19 @@ void JA_ResumeChannel(const int channel) 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_ResumeAudioStreamDevice(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_ResumeAudioStreamDevice(channels[channel].stream); + } } } @@ -436,6 +397,7 @@ void JA_StopChannel(const int channel) channels[i].state = JA_CHANNEL_FREE; channels[i].pos = 0; channels[i].sound = NULL; + SDL_DestroyAudioStream(channels[i].stream); } } else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) @@ -443,6 +405,7 @@ void JA_StopChannel(const int channel) channels[channel].state = JA_CHANNEL_FREE; channels[channel].pos = 0; channels[channel].sound = NULL; + SDL_DestroyAudioStream(channels[channel].stream); } } @@ -453,13 +416,18 @@ JA_Channel_state JA_GetChannelState(const int channel) if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID; + return channels[channel].state; } -int JA_SetSoundVolume(int volume) +float JA_SetSoundVolume(float volume) { - JA_soundVolume = volume > 128 ? 128 : volume < 0 ? 0 - : volume; + JA_soundVolume = SDL_clamp(volume, 0.0f, 1.0f); + + for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) + if ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) + SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume); + return JA_soundVolume; } @@ -473,11 +441,10 @@ void JA_EnableSound(const bool value) JA_soundEnabled = value; } -int JA_SetVolume(int volume) +float JA_SetVolume(float volume) { - JA_musicVolume = volume > 128 ? 128 : volume < 0 ? 0 - : volume; - JA_soundVolume = JA_musicVolume / 2; + JA_SetSoundVolume(JA_SetMusicVolume(volume) / 2.0f); + return JA_musicVolume; } diff --git a/source/jail_audio.h b/source/jail_audio.h index 3bd1591..384e70c 100644 --- a/source/jail_audio.h +++ b/source/jail_audio.h @@ -1,9 +1,5 @@ #pragma once - -#include // Para SDL_AudioFormat -#include // Para Uint32, Uint8 -struct JA_Music_t; // lines 4-4 -struct JA_Sound_t; // lines 5-5 +#include enum JA_Channel_state { @@ -22,6 +18,9 @@ enum JA_Music_state JA_MUSIC_DISABLED }; +struct JA_Sound_t; +struct JA_Music_t; + void JA_Init(const int freq, const SDL_AudioFormat format, const int channels); void JA_Quit(); @@ -31,25 +30,21 @@ void JA_PlayMusic(JA_Music_t *music, const int loop = -1); void JA_PauseMusic(); void JA_ResumeMusic(); void JA_StopMusic(); -void JA_FadeOutMusic(const int milliseconds); JA_Music_state JA_GetMusicState(); void JA_DeleteMusic(JA_Music_t *music); -int JA_SetMusicVolume(int volume); -void JA_SetMusicPosition(float value); -float JA_GetMusicPosition(); +float JA_SetMusicVolume(float volume); void JA_EnableMusic(const bool value); JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length); JA_Sound_t *JA_LoadSound(Uint8 *buffer, Uint32 length); JA_Sound_t *JA_LoadSound(const char *filename); int JA_PlaySound(JA_Sound_t *sound, const int loop = 0); -int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0); void JA_PauseChannel(const int channel); void JA_ResumeChannel(const int channel); void JA_StopChannel(const int channel); JA_Channel_state JA_GetChannelState(const int channel); void JA_DeleteSound(JA_Sound_t *sound); -int JA_SetSoundVolume(int volume); +float JA_SetSoundVolume(float volume); void JA_EnableSound(const bool value); -int JA_SetVolume(int volume); +float JA_SetVolume(float volume); diff --git a/source/jail_shader.cpp b/source/jail_shader.cpp index 52165bf..d377eba 100644 --- a/source/jail_shader.cpp +++ b/source/jail_shader.cpp @@ -164,11 +164,10 @@ namespace shader throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET."); } - SDL_RendererInfo infoRenderer; - SDL_GetRendererInfo(renderer, &infoRenderer); + const auto RENDER_NAME = SDL_GetRendererName(renderer); // Verificar que el renderer sea OpenGL - if (!strncmp(infoRenderer.name, "opengl", 6)) + if (!strncmp(RENDER_NAME, "opengl", 6)) { #ifndef __APPLE__ if (!initGLExtensions()) @@ -201,7 +200,8 @@ namespace shader if (usingOpenGL) { - SDL_GL_BindTexture(backBuffer, nullptr, nullptr); + SDL_GetTextureProperties(backBuffer); + // SDL_GL_BindTexture(backBuffer, nullptr, nullptr); if (programId != 0) { glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgramId); @@ -210,7 +210,8 @@ namespace shader // Recupera el tamaño lógico configurado con SDL_RenderSetLogicalSize int logicalW, logicalH; - SDL_RenderGetLogicalSize(renderer, &logicalW, &logicalH); + SDL_RendererLogicalPresentation mode; + SDL_GetRenderLogicalPresentation(renderer, &logicalW, &logicalH, &mode); if (logicalW == 0 || logicalH == 0) { logicalW = win_size.x; @@ -219,15 +220,17 @@ namespace shader // Cálculo del viewport int viewportX = 0, viewportY = 0, viewportW = win_size.x, viewportH = win_size.y; - SDL_bool useIntegerScale = SDL_RenderGetIntegerScale(renderer); - if (useIntegerScale) + const bool USE_INTEGER_SCALE = mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE; + if (USE_INTEGER_SCALE) { // Calcula el factor de escalado entero máximo que se puede aplicar int scaleX = win_size.x / logicalW; int scaleY = win_size.y / logicalH; int scale = (scaleX < scaleY ? scaleX : scaleY); if (scale < 1) + { scale = 1; + } viewportW = logicalW * scale; viewportH = logicalH * scale; viewportX = (win_size.x - viewportW) / 2; diff --git a/source/moving_sprite.cpp b/source/moving_sprite.cpp index 8b680fe..19faa1a 100644 --- a/source/moving_sprite.cpp +++ b/source/moving_sprite.cpp @@ -2,7 +2,7 @@ #include "texture.h" // Para Texture // Constructor -MovingSprite::MovingSprite(std::shared_ptr texture, SDL_Rect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip) +MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip) : Sprite(texture, pos), x_(pos.x), y_(pos.y), @@ -11,7 +11,7 @@ MovingSprite::MovingSprite(std::shared_ptr texture, SDL_Rect pos, Rotat zoom_h_(zoom_h), flip_(flip) {} -MovingSprite::MovingSprite(std::shared_ptr texture, SDL_Rect pos) +MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos) : Sprite(texture, pos), x_(pos.x), y_(pos.y), @@ -96,7 +96,7 @@ void MovingSprite::setRotate(bool enable) } // Establece la posición y_ el tamaño del objeto -void MovingSprite::setPos(SDL_Rect rect) +void MovingSprite::setPos(SDL_FRect rect) { x_ = static_cast(rect.x); y_ = static_cast(rect.y); diff --git a/source/moving_sprite.h b/source/moving_sprite.h index d23856a..bd0a8ff 100644 --- a/source/moving_sprite.h +++ b/source/moving_sprite.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point +#include // Para SDL_FRect, SDL_Point #include // Para SDL_RendererFlip #include // Para shared_ptr #include @@ -49,8 +49,8 @@ protected: public: // Constructor - MovingSprite(std::shared_ptr texture, SDL_Rect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip); - MovingSprite(std::shared_ptr texture, SDL_Rect pos); + MovingSprite(std::shared_ptr texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip); + MovingSprite(std::shared_ptr texture, SDL_FRect pos); explicit MovingSprite(std::shared_ptr texture); // Destructor @@ -110,7 +110,7 @@ public: SDL_RendererFlip getFlip() { return flip_; } // Establece la posición y_ el tamaño del objeto - void setPos(SDL_Rect rect); + void setPos(SDL_FRect rect); // Establece el valor de las variables void setPos(float x, float y); diff --git a/source/notifier.cpp b/source/notifier.cpp index 5c906df..4997a8c 100644 --- a/source/notifier.cpp +++ b/source/notifier.cpp @@ -242,7 +242,7 @@ void Notifier::show(std::vector texts, int icon, const std::string // Dibuja el fondo de la notificación SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255); - SDL_Rect rect; + SDL_FRect rect; if (shape == NotificationShape::ROUNDED) { rect = {4, 0, width - (4 * 2), height}; @@ -266,7 +266,7 @@ void Notifier::show(std::vector texts, int icon, const std::string // Dibuja el icono de la notificación if (has_icons_ && icon >= 0 && texts.size() >= 2) { - auto sp = std::make_unique(icon_texture_, (SDL_Rect){0, 0, icon_size, icon_size}); + auto sp = std::make_unique(icon_texture_, (SDL_FRect){0, 0, icon_size, icon_size}); sp->setPosition({padding_in_h, padding_in_v, icon_size, icon_size}); sp->setSpriteClip({icon_size * (icon % 10), icon_size * (icon / 10), icon_size, icon_size}); sp->render(); diff --git a/source/notifier.h b/source/notifier.h index 5b694e4..22843bb 100644 --- a/source/notifier.h +++ b/source/notifier.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_Renderer #include // Para shared_ptr #include // Para string, basic_string @@ -38,7 +38,7 @@ private: int counter; NotificationStatus state; NotificationShape shape; - SDL_Rect rect; + SDL_FRect rect; int y; int travel_dist; std::string code; // Permite asignar un código a la notificación diff --git a/source/on_screen_help.cpp b/source/on_screen_help.cpp index 7e02b44..1a8587f 100644 --- a/source/on_screen_help.cpp +++ b/source/on_screen_help.cpp @@ -18,21 +18,21 @@ constexpr int ICONSIZE = 16; constexpr SDL_Point PADDING = {8, 8}; constexpr SDL_Point DESP = {ICONSIZE + 4, 5}; -constexpr SDL_Rect CONTROLLER_UP = {16, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect CONTROLLER_DOWN = {48, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect CONTROLLER_LEFT = {64, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect LEFT_BUTTON = {112, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect TOP_BUTTON = {80, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect RIGHT_BUTTON = {96, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect START_BUTTON = {0, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect CONTROLLER_UP = {16, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect CONTROLLER_DOWN = {48, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect CONTROLLER_LEFT = {64, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect LEFT_BUTTON = {112, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect TOP_BUTTON = {80, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect RIGHT_BUTTON = {96, 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect START_BUTTON = {0, 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect CONTROLLER_UP_POS = {PADDING.x, PADDING.y + 18 * 0, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect CONTROLLER_DOWN_POS = {PADDING.x, PADDING.y + 18 * 1, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect CONTROLLER_LEFT_POS = {PADDING.x, PADDING.y + 18 * 2, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect LEFT_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 3, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect TOP_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 4, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect RIGHT_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 5, ICONSIZE, ICONSIZE}; -constexpr SDL_Rect START_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 6, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect CONTROLLER_UP_POS = {PADDING.x, PADDING.y + 18 * 0, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect CONTROLLER_DOWN_POS = {PADDING.x, PADDING.y + 18 * 1, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect CONTROLLER_LEFT_POS = {PADDING.x, PADDING.y + 18 * 2, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect LEFT_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 3, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect TOP_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 4, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect RIGHT_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 5, ICONSIZE, ICONSIZE}; +constexpr SDL_FRect START_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 6, ICONSIZE, ICONSIZE}; // [SINGLETON] Crearemos el objeto onScreenHelp con esta función estática void OnScreenHelp::init() @@ -100,7 +100,7 @@ void OnScreenHelp::fillTexture() auto controllersTexture = Resource::get()->getTexture("controllers.png"); // Crea el sprite para dibujar los gráficos - auto sprite = std::make_unique(controllersTexture, (SDL_Rect){0, 0, 16, 16}); + auto sprite = std::make_unique(controllersTexture, (SDL_FRect){0, 0, 16, 16}); // Borra la textura SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0); @@ -108,7 +108,7 @@ void OnScreenHelp::fillTexture() // Pon el color de fondo con el bisel SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0x55, 0x5D, 0x77, 255); - SDL_Rect rect; + SDL_FRect rect; rect = {4, 0, dest.w - (4 * 2), dest.h}; SDL_RenderFillRect(Screen::get()->getRenderer(), &rect); @@ -146,7 +146,7 @@ void OnScreenHelp::setSize() const auto x = 0; const auto y = (param.game.height - height) / 2; - dest = (SDL_Rect){x, y, width, height}; + dest = (SDL_FRect){x, y, width, height}; hiddenPos = -width; showingPos = 0; @@ -182,7 +182,7 @@ auto OnScreenHelp::getLargestStringSize() -> int const } // Renderizara el boton y el texto -void OnScreenHelp::renderButton(Sprite *sprite, Text *text, const SDL_Rect &buttonClip, const SDL_Rect &buttonPos, int textId) +void OnScreenHelp::renderButton(Sprite *sprite, Text *text, const SDL_FRect &buttonClip, const SDL_FRect &buttonPos, int textId) { sprite->setSpriteClip(buttonClip); sprite->setPosition(buttonPos); diff --git a/source/on_screen_help.h b/source/on_screen_help.h index 1f953f3..0487435 100644 --- a/source/on_screen_help.h +++ b/source/on_screen_help.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_Texture #include // Para vector class Sprite; @@ -22,7 +22,7 @@ private: static OnScreenHelp *onScreenHelp; SDL_Texture *texture; // Textura donde dibujar - SDL_Rect dest; // Posición donde dibujar la textura; + SDL_FRect dest; // Posición donde dibujar la textura; int hiddenPos, showingPos; // Las dos posiciones donde colocar la textura OnScreenHelpStatus state; // Estado del objeto @@ -47,7 +47,7 @@ private: auto getLargestStringSize() -> int const; // Renderizara el boton y el texto - void renderButton(Sprite *sprite, Text *text, const SDL_Rect &buttonClip, const SDL_Rect &buttonPos, int textId); + void renderButton(Sprite *sprite, Text *text, const SDL_FRect &buttonClip, const SDL_FRect &buttonPos, int textId); // Actualiza la posición void updatePosition(); diff --git a/source/param.h b/source/param.h index b56fd1b..ec47b2c 100644 --- a/source/param.h +++ b/source/param.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para Uint32 #include // Para string #include // Para vector @@ -71,7 +71,7 @@ struct Param { ParamGame game; ParamFade fade; - SDL_Rect scoreboard; + SDL_FRect scoreboard; ParamTitle title; ParamBackground background; std::vector balloon; diff --git a/source/player.cpp b/source/player.cpp index 7fd025f..bb11af4 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -14,7 +14,7 @@ #include // Constructor -Player::Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector> texture, const std::vector> &animations) +Player::Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector> texture, const std::vector> &animations) : player_sprite_(std::make_unique(texture[0], animations[0])), power_sprite_(std::make_unique(texture[1], animations[1])), enter_name_(std::make_unique()), diff --git a/source/player.h b/source/player.h index 68bb10d..d5201b7 100644 --- a/source/player.h +++ b/source/player.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para Uint32 #include // Para unique_ptr, shared_ptr #include // Para string @@ -63,7 +63,7 @@ private: // Variables int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 - SDL_Rect play_area_; // Rectangulo con la zona de juego + SDL_FRect play_area_; // Rectangulo con la zona de juego float pos_x_ = 0.0f; // Posicion en el eje X int pos_y_ = 0; // Posicion en el eje Y float default_pos_x_; // Posición inicial para el jugador @@ -134,7 +134,7 @@ private: public: // Constructor - Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector> texture, const std::vector> &animations); + Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector> texture, const std::vector> &animations); // Destructor ~Player() = default; diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 9386973..dee8a26 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -131,7 +131,7 @@ void Scoreboard::setColor(Color color) } // Establece el valor de la variable -void Scoreboard::setPos(SDL_Rect rect) +void Scoreboard::setPos(SDL_FRect rect) { rect_ = rect; @@ -259,7 +259,7 @@ void Scoreboard::fillPanelTextures() // ENTER NAME { text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106)); - SDL_Rect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7}; + SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7}; // Recorre todos los slots de letras del nombre for (size_t j = 0; j < MAX_NAME_LENGHT; ++j) diff --git a/source/scoreboard.h b/source/scoreboard.h index d7ec4f4..2ef33a4 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Point, SDL_Rect +#include // Para SDL_Point, SDL_FRect #include // Para SDL_Texture, SDL_Renderer #include // Para Uint32 #include // Para SDL_GetTicks @@ -38,7 +38,7 @@ enum class ScoreboardMode : int struct Panel { ScoreboardMode mode; // Modo en el que se encuentra el panel - SDL_Rect pos; // Posición donde dibujar el panel dentro del marcador + SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador }; // Clase Scoreboard @@ -71,7 +71,7 @@ private: float power_ = 0; // Poder actual de la fase std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación Color color_ = Color(); // Color del marcador - SDL_Rect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador + SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador Uint32 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks() int time_counter_ = 0; // Contador de segundos int loop_counter_ = 0; // Contador de bucle @@ -136,7 +136,7 @@ public: void setColor(Color color); // Establece el valor de la variable - void setPos(SDL_Rect rect); + void setPos(SDL_FRect rect); void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; } void setHiScore(int hi_score) { hi_score_ = hi_score; } diff --git a/source/screen.cpp b/source/screen.cpp index fba3570..6382bf5 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -259,7 +259,7 @@ void Screen::adjustWindowSize() const int NEW_POS_X = old_pos_x + (old_width - WIDTH) / 2; const int NEW_POS_Y = old_pos_y + (old_height - HEIGHT) / 2; - SDL_Rect viewport = {0, 0, WIDTH, HEIGHT}; + SDL_FRect viewport = {0, 0, WIDTH, HEIGHT}; SDL_SetRenderViewport(renderer_, &viewport); SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0)); @@ -273,7 +273,7 @@ void Screen::adjustWindowSize() int Screen::getMaxZoom() { // Obtiene información sobre la pantalla - auto DM = SDL_GetCurrentDisplayMode(0); + auto DM = SDL_GetCurrentDisplayMode(0); // Calcula el máximo factor de zoom que se puede aplicar a la pantalla const int MAX_ZOOM = std::min(DM->w / param.game.width, (DM->h - WINDOWS_DECORATIONS_) / param.game.height); diff --git a/source/screen.h b/source/screen.h index aff1fd8..48f122c 100644 --- a/source/screen.h +++ b/source/screen.h @@ -1,7 +1,7 @@ #pragma once #include // Para SDL_BlendMode -#include // Para SDL_Rect, SDL_Point +#include // Para SDL_FRect, SDL_Point #include // Para SDL_Renderer, SDL_Texture #include // Para Uint32 #include // Para SDL_Window @@ -162,8 +162,8 @@ private: SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador // Variables - SDL_FRect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla - SDL_FRect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana + SDL_FRect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla + SDL_FRect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana FPS fps_; // Variable para gestionar los frames por segundo std::string info_resolution_; // Texto con la informacion de la pantalla std::string shader_source_; // Almacena el contenido del archivo GLSL diff --git a/source/sprite.cpp b/source/sprite.cpp index 6b9ba84..a74311b 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -4,13 +4,13 @@ // Constructor Sprite::Sprite(std::shared_ptr texture, int x, int y, int w, int h) : texture_(texture), - pos_((SDL_Rect){x, y, w, h}), - sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} + pos_((SDL_FRect){x, y, w, h}), + sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} -Sprite::Sprite(std::shared_ptr texture, SDL_Rect rect) +Sprite::Sprite(std::shared_ptr texture, SDL_FRect rect) : texture_(texture), pos_(rect), - sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} + sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} Sprite::Sprite(std::shared_ptr texture) : texture_(texture), diff --git a/source/sprite.h b/source/sprite.h index 5f45c08..8b52f67 100644 --- a/source/sprite.h +++ b/source/sprite.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point +#include // Para SDL_FRect, SDL_Point #include // Para shared_ptr class Texture; @@ -10,14 +10,14 @@ class Sprite protected: // Variables std::shared_ptr texture_; // Textura donde estan todos los dibujos del sprite - SDL_Rect pos_; // Posición y tamaño donde dibujar el sprite - SDL_Rect sprite_clip_; // Rectangulo de origen de la textura que se dibujará en pantalla + SDL_FRect pos_; // Posición y tamaño donde dibujar el sprite + SDL_FRect sprite_clip_; // Rectangulo de origen de la textura que se dibujará en pantalla double zoom_ = 1.0f; // Zoom aplicado a la textura public: // Constructor Sprite(std::shared_ptr, int x, int y, int w, int h); - Sprite(std::shared_ptr, SDL_Rect rect); + Sprite(std::shared_ptr, SDL_FRect rect); explicit Sprite(std::shared_ptr); // Destructor @@ -36,8 +36,8 @@ public: int getHeight() const { return pos_.h; } // Devuelve el rectangulo donde está el sprite - SDL_Rect getPosition() const { return pos_; } - SDL_Rect &getRect() { return pos_; } + SDL_FRect getPosition() const { return pos_; } + SDL_FRect &getRect() { return pos_; } // Establece la posición y el tamaño void setX(int x) { pos_.x = x; } @@ -48,7 +48,7 @@ public: // Establece la posición del objeto void setPosition(int x, int y); void setPosition(SDL_Point p); - void setPosition(SDL_Rect r) { pos_ = r; } + void setPosition(SDL_FRect r) { pos_ = r; } // Establece el nivel de zoom void setZoom(float zoom) { zoom_ = zoom; } @@ -58,11 +58,11 @@ public: void incY(int value) { pos_.y += value; } // Obtiene el rectangulo que se dibuja de la textura - SDL_Rect getSpriteClip() const { return sprite_clip_; } + SDL_FRect getSpriteClip() const { return sprite_clip_; } // Establece el rectangulo que se dibuja de la textura - void setSpriteClip(SDL_Rect rect) { sprite_clip_ = rect; } - void setSpriteClip(int x, int y, int w, int h) { sprite_clip_ = (SDL_Rect){x, y, w, h}; } + void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; } + void setSpriteClip(int x, int y, int w, int h) { sprite_clip_ = (SDL_FRect){x, y, w, h}; } // Obtiene un puntero a la textura std::shared_ptr getTexture() const { return texture_; } diff --git a/source/tabe.h b/source/tabe.h index c1d9a82..8ea3def 100644 --- a/source/tabe.h +++ b/source/tabe.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para Uint32 #include // Para SDL_GetTicks #include // Para rand @@ -136,7 +136,7 @@ public: bool tryToGetBonus(); // Obtiene el area de colisión - SDL_Rect &getCollider() { return sprite_->getRect(); } + SDL_FRect &getCollider() { return sprite_->getRect(); } // Getters bool isEnabled() const { return enabled_; } diff --git a/source/text.cpp b/source/text.cpp index 69e583c..a53c7d2 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -1,7 +1,7 @@ #include "text.h" #include // Para SDL_BLENDMODE_BLEND #include // Para SDL_PIXELFORMAT_RGBA8888 -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_TEXTUREACCESS_TARGET #include // Para size_t #include // Para basic_ifstream, basic_istream, basic... @@ -96,7 +96,7 @@ Text::Text(std::shared_ptr texture, const std::string &text_file) } // Crea los objetos - sprite_ = std::make_unique(texture, (SDL_Rect){0, 0, box_width_, box_height_}); + sprite_ = std::make_unique(texture, (SDL_FRect){0, 0, box_width_, box_height_}); // Inicializa variables fixed_width_ = false; @@ -116,7 +116,7 @@ Text::Text(std::shared_ptr texture, std::shared_ptr text_file } // Crea los objetos - sprite_ = std::make_unique(texture, (SDL_Rect){0, 0, box_width_, box_height_}); + sprite_ = std::make_unique(texture, (SDL_FRect){0, 0, box_width_, box_height_}); // Inicializa variables fixed_width_ = false; @@ -148,7 +148,7 @@ void Text::write2X(int x, int y, const std::string &text, int kerning) for (size_t i = 0; i < text.length(); ++i) { auto index = static_cast(text[i]); - SDL_Rect rect = {offset_[index].x, offset_[index].y, box_width_, box_height_}; + SDL_FRect rect = {offset_[index].x, offset_[index].y, box_width_, box_height_}; sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f); shift += (offset_[index].w + kerning) * 2; } diff --git a/source/texture.cpp b/source/texture.cpp index 7959028..1ed8427 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -174,10 +174,10 @@ void Texture::setAlpha(Uint8 alpha) } // Renderiza la textura en un punto específico -void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) +void Texture::render(int x, int y, SDL_FRect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) { // Establece el destino de renderizado en la pantalla - SDL_Rect renderQuad = {x, y, width_, height_}; + SDL_FRect renderQuad = {x, y, width_, height_}; // Obtiene las dimesiones del clip de renderizado if (clip != nullptr) diff --git a/source/texture.h b/source/texture.h index d187cfb..1ebbd07 100644 --- a/source/texture.h +++ b/source/texture.h @@ -2,7 +2,7 @@ #include // Para SDL_BlendMode #include // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF... -#include // Para SDL_Point, SDL_Rect +#include // Para SDL_Point, SDL_FRect #include // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX... #include // Para Uint8, Uint16, Uint32 #include // Para shared_ptr @@ -75,7 +75,7 @@ public: void setAlpha(Uint8 alpha); // Renderiza la textura en un punto específico - void render(int x, int y, SDL_Rect *clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_Point *center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE); + void render(int x, int y, SDL_FRect *clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_Point *center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE); // Establece la textura como objetivo de renderizado void setAsRenderTarget(SDL_Renderer *renderer); diff --git a/source/tiled_bg.cpp b/source/tiled_bg.cpp index a730ceb..2d97d3b 100644 --- a/source/tiled_bg.cpp +++ b/source/tiled_bg.cpp @@ -8,7 +8,7 @@ #include "sprite.h" // Para Sprite // Constructor -TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode) +TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode) : renderer_(Screen::get()->getRenderer()), pos_(pos), mode_(mode == TiledBGMode::RANDOM ? static_cast(rand() % 2) : mode) @@ -54,7 +54,7 @@ TiledBG::~TiledBG() void TiledBG::fillTexture() { // Crea los objetos para pintar en la textura de fondo - auto tile = std::make_unique(Resource::get()->getTexture("title_bg_tile.png"), (SDL_Rect){0, 0, TILE_WIDTH_, TILE_HEIGHT_}); + auto tile = std::make_unique(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH_, TILE_HEIGHT_}); // Prepara para dibujar sobre la textura auto temp = SDL_GetRenderTarget(renderer_); diff --git a/source/tiled_bg.h b/source/tiled_bg.h index d18218c..9c12c5f 100644 --- a/source/tiled_bg.h +++ b/source/tiled_bg.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect +#include // Para SDL_FRect #include // Para SDL_Renderer, SDL_Texture #include "utils.h" @@ -32,8 +32,8 @@ private: SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles // Variables - SDL_Rect pos_; // Posición y tamaño del mosaico - SDL_Rect window_; // Ventana visible para la textura de fondo del titulo + SDL_FRect pos_; // Posición y tamaño del mosaico + SDL_FRect window_; // Ventana visible para la textura de fondo del titulo TiledBGMode mode_; // Tipo de movimiento del mosaico double sin_[360]; // Vector con los valores del seno precalculados float desp_ = 0.0f; // Desplazamiento aplicado @@ -51,7 +51,7 @@ private: public: // Constructor - TiledBG(SDL_Rect pos, TiledBGMode mode); + TiledBG(SDL_FRect pos, TiledBGMode mode); // Destructor ~TiledBG(); diff --git a/source/utils.cpp b/source/utils.cpp index 2852519..c7ec80a 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -69,7 +69,7 @@ bool checkCollision(const Circle &a, const Circle &b) } // Detector de colisiones entre un circulo y un rectangulo -bool checkCollision(const Circle &a, const SDL_Rect &b) +bool checkCollision(const Circle &a, const SDL_FRect &b) { // Encuentra el punto más cercano en el rectángulo int cX = std::clamp(a.x, b.x, b.x + b.w); @@ -80,7 +80,7 @@ bool checkCollision(const Circle &a, const SDL_Rect &b) } // Detector de colisiones entre dos rectangulos -bool checkCollision(const SDL_Rect &a, const SDL_Rect &b) +bool checkCollision(const SDL_FRect &a, const SDL_FRect &b) { const int leftA = a.x, rightA = a.x + a.w, topA = a.y, bottomA = a.y + a.h; const int leftB = b.x, rightB = b.x + b.w, topB = b.y, bottomB = b.y + b.h; @@ -98,7 +98,7 @@ bool checkCollision(const SDL_Rect &a, const SDL_Rect &b) } // Detector de colisiones entre un punto y un rectangulo -bool checkCollision(const SDL_Point &p, const SDL_Rect &r) +bool checkCollision(const SDL_Point &p, const SDL_FRect &r) { if (p.x < r.x || p.x > r.x + r.w) return false; diff --git a/source/utils.h b/source/utils.h index 8fc824c..c27a58a 100644 --- a/source/utils.h +++ b/source/utils.h @@ -1,6 +1,6 @@ #pragma once -#include // Para SDL_Rect, SDL_Point +#include // Para SDL_FRect, SDL_Point #include // Para SDL_Renderer #include // Para Uint8 #include // Para int32_t @@ -135,13 +135,13 @@ double distanceSquared(int x1, int y1, int x2, int y2); bool checkCollision(const Circle &a, const Circle &b); // Detector de colisiones entre un circulo y un rectangulo -bool checkCollision(const Circle &a, const SDL_Rect &b); +bool checkCollision(const Circle &a, const SDL_FRect &b); // Detector de colisiones entre un dos rectangulos -bool checkCollision(const SDL_Rect &a, const SDL_Rect &b); +bool checkCollision(const SDL_FRect &a, const SDL_FRect &b); // Detector de colisiones entre un punto y un rectangulo -bool checkCollision(const SDL_Point &p, const SDL_Rect &r); +bool checkCollision(const SDL_Point &p, const SDL_FRect &r); // Convierte una cadena en un valor booleano bool stringToBool(const std::string &str);