migrant a SDL3

This commit is contained in:
2025-03-25 20:26:45 +01:00
parent f1b0303474
commit a9c869baf6
49 changed files with 374 additions and 416 deletions

View File

@@ -217,7 +217,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
// Se introducen los valores separados por comas en un vector // Se introducen los valores separados por comas en un vector
std::stringstream ss(value); std::stringstream ss(value);
std::string tmp; 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, ',')) while (getline(ss, tmp, ','))
{ {
// Comprueba que el tile no sea mayor que el maximo indice permitido // Comprueba que el tile no sea mayor que el maximo indice permitido

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <string> // Para string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector
@@ -10,7 +10,7 @@ class Texture; // lines 9-9
struct Animation struct Animation
{ {
std::string name; // Nombre de la animacion std::string name; // Nombre de la animacion
std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación std::vector<SDL_FRect> frames; // Cada uno de los frames que componen la animación
int speed; // Velocidad de 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 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 bool completed; // Indica si ha finalizado la animación

View File

@@ -1,3 +1,4 @@
#define _USE_MATH_DEFINES
#include "background.h" #include "background.h"
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND #include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888 #include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
@@ -46,8 +47,8 @@ Background::Background()
const float BOTTOM_CLOUDS_TEXTURE_HEIGHT = bottom_clouds_texture_->getHeight() / 4; const float BOTTOM_CLOUDS_TEXTURE_HEIGHT = bottom_clouds_texture_->getHeight() / 4;
for (int i = 0; i < 4; ++i) 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}; top_clouds_rect_[i] = {0, i * TOP_CLOUDS_TEXTURE_HEIGHT, static_cast<float>(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}; bottom_clouds_rect_[i] = {0, i * BOTTOM_CLOUDS_TEXTURE_HEIGHT, static_cast<float>(bottom_clouds_texture_->getWidth()), BOTTOM_CLOUDS_TEXTURE_HEIGHT};
} }
} }
@@ -56,11 +57,11 @@ Background::Background()
const float TOP_CLOUDS_Y = base_ - 165; const float TOP_CLOUDS_Y = base_ - 165;
const float BOTTOM_CLOUDS_Y = base_ - 101; const float BOTTOM_CLOUDS_Y = base_ - 101;
top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_Rect){0, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){0, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()});
top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_Rect){rect_.w, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()}); top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_FRect){rect_.w, TOP_CLOUDS_Y, rect_.w, top_clouds_texture_->getHeight()});
bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_Rect){0, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){0, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()});
bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_Rect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()}); bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_FRect){rect_.w, BOTTOM_CLOUDS_Y, rect_.w, bottom_clouds_texture_->getHeight()});
buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_); buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_);
gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h); gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h);

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point
#include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer
#include <stddef.h> // Para size_t #include <stddef.h> // Para size_t
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr

View File

@@ -9,7 +9,7 @@
#include "jail_audio.h" #include "jail_audio.h"
// Constructor // 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> texture, const std::vector<std::string> &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> texture, const std::vector<std::string> &animation)
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)), : sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
x_(x), x_(x),
y_(y), y_(y),

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para string #include <string> // 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 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 float speed_; // Velocidad a la que se mueven los globos
Uint8 power_; // Cantidad de poder que alberga el globo 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 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 bool sound_enabled_ = false; // Indica si ha de sonar el sonido del globo al rebotar
@@ -154,7 +154,7 @@ public:
float vel_x, float vel_x,
float speed, float speed,
Uint16 creation_timer, Uint16 creation_timer,
SDL_Rect play_area, SDL_FRect play_area,
std::shared_ptr<Texture> texture, std::shared_ptr<Texture> texture,
const std::vector<std::string> &animation); const std::vector<std::string> &animation);

View File

@@ -381,7 +381,7 @@ void BalloonManager::createRandomBalloons()
const int num_balloons = 2 + rand() % 4; const int num_balloons = 2 + rand() % 4;
for (int i = 0; i < num_balloons; ++i) 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<int>(param.game.game_area.rect.w)) - BALLOON_SIZE[3];
const int y = param.game.game_area.rect.y + (rand() % 50); const int y = param.game.game_area.rect.y + (rand() % 50);
const BalloonSize size = static_cast<BalloonSize>(rand() % 4); const BalloonSize size = static_cast<BalloonSize>(rand() % 4);
const float vel_x = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE; const float vel_x = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector

View File

@@ -1,5 +1,5 @@
#include "bullet.h" #include "bullet.h"
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <memory> // Para unique_ptr, make_unique, shared_ptr #include <memory> // Para unique_ptr, make_unique, shared_ptr
#include "param.h" // Para Param, ParamGame, param #include "param.h" // Para Param, ParamGame, param
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
@@ -7,7 +7,7 @@ class Texture; // lines 5-5
// Constructor // Constructor
Bullet::Bullet(int x, int y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture) Bullet::Bullet(int x, int y, BulletType bullet_type, bool powered_up, int owner, std::shared_ptr<Texture> texture)
: sprite_(std::make_unique<Sprite>(texture, SDL_Rect{x, y, BULLET_WIDTH_, BULLET_HEIGHT_})), : sprite_(std::make_unique<Sprite>(texture, SDL_FRect{x, y, BULLET_WIDTH_, BULLET_HEIGHT_})),
pos_x_(x), pos_x_(x),
pos_y_(y), pos_y_(y),
bullet_type_(bullet_type), bullet_type_(bullet_type),

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr

View File

@@ -24,7 +24,6 @@
#include <vector> // Para vector #include <vector> // Para vector
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "credits.h" // Para Credits #include "credits.h" // Para Credits
#include "dbgtxt.h" // Para dbg_init
#include "game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_... #include "game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_...
#include "hiscore_table.h" // Para HiScoreTable #include "hiscore_table.h" // Para HiScoreTable
#include "input.h" // Para Input, InputAction #include "input.h" // Para Input, InputAction
@@ -103,7 +102,6 @@ void Director::init()
initSDL(); initSDL();
SDL_HideCursor(); SDL_HideCursor();
initJailAudio(); initJailAudio();
dbg_init(renderer_);
lang::loadFromFile(getLangFile(static_cast<lang::Code>(options.game.language))); lang::loadFromFile(getLangFile(static_cast<lang::Code>(options.game.language)));
Screen::init(window_, renderer_); Screen::init(window_, renderer_);
Resource::init(); Resource::init();

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16 #include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16
#include <vector> // Para vector #include <vector> // Para vector

View File

@@ -795,12 +795,12 @@ void Game::createItemText(int x, std::shared_ptr<Texture> texture)
const int y2 = -h; const int y2 = -h;
// Ajusta para que no se dibuje fuera de pantalla // 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<int>(param.game.play_area.rect.w) - w - 2);
// Inicializa // Inicializa
path_sprites_.back()->setWidth(w); path_sprites_.back()->setWidth(w);
path_sprites_.back()->setHeight(h); path_sprites_.back()->setHeight(h);
path_sprites_.back()->setSpriteClip({0, 0, w, h}); path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(w), static_cast<float>(h)});
path_sprites_.back()->addPath(y0, y1, PathType::VERTICAL, x, 100, easeOutQuint, 0); 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()->addPath(y1, y2, PathType::VERTICAL, x, 80, easeInQuint, 0);
path_sprites_.back()->enable(); path_sprites_.back()->enable();
@@ -1225,25 +1225,21 @@ void Game::checkEvents()
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) while (SDL_PollEvent(&event))
{ {
if (event.type == SDL_WINDOWEVENT) switch (event.type)
{ {
switch (event.window.event) case SDL_EVENT_WINDOW_FOCUS_LOST:
{
case SDL_WINDOWEVENT_FOCUS_LOST:
{ {
pause(!demo_.enabled); pause(!demo_.enabled);
break; break;
} }
case SDL_WINDOWEVENT_FOCUS_GAINED: case SDL_EVENT_WINDOW_FOCUS_GAINED:
{ {
pause(false); pause(false);
break; break;
} }
default: default:
break; break;
} }
}
#ifdef DEBUG #ifdef DEBUG
checkDebugEvents(event); checkDebugEvents(event);
@@ -1987,9 +1983,9 @@ void Game::setState(GameState state)
// Comprueba los eventos en el modo DEBUG // Comprueba los eventos en el modo DEBUG
void Game::checkDebugEvents(const SDL_Event &event) 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 case SDLK_1: // Crea una powerball
{ {

View File

@@ -11,19 +11,16 @@ namespace globalEvents
{ {
switch (event.type) 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::name = section::Name::QUIT;
section::options = section::Options::QUIT_FROM_EVENT; section::options = section::Options::QUIT_FROM_EVENT;
return; return;
case SDL_RENDER_DEVICE_RESET: case SDL_EVENT_RENDER_DEVICE_RESET:
case SDL_RENDER_TARGETS_RESET: case SDL_EVENT_RENDER_TARGETS_RESET:
std::cout << "SDL_RENDER_TARGETS_RESET" << std::endl; std::cout << "SDL_RENDER_TARGETS_RESET" << std::endl;
break; break;
case SDL_WINDOWEVENT: case SDL_EVENT_WINDOW_RESIZED:
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl; std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl;
}
break; break;
default: default:
break; break;

View File

@@ -78,7 +78,7 @@ namespace globalInputs
void toggleintegerScale() void toggleintegerScale()
{ {
options.video.integer_scale = !options.video.integer_scale; 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(); Screen::get()->setVideoMode();
Notifier::get()->show({lang::getText(134) + " " + boolToOnOff(options.video.integer_scale)}); Notifier::get()->show({lang::getText(134) + " " + boolToOnOff(options.video.integer_scale)});
} }

View File

@@ -1,7 +1,8 @@
#include "hiscore_table.h" #include "hiscore_table.h"
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND #include <SDL3/SDL.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event #include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888 #include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
#include <SDL3/SDL_render.h> // Para SDL_QueryTexture
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <stdlib.h> // Para rand, size_t #include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para max #include <algorithm> // Para max
@@ -33,7 +34,7 @@ HiScoreTable::HiScoreTable()
background_(std::make_unique<Background>()), background_(std::make_unique<Background>()),
counter_(0), counter_(0),
ticks_(0), ticks_(0),
view_area_({0, 0, param.game.width, param.game.height}), view_area_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
fade_mode_(FadeMode::IN), fade_mode_(FadeMode::IN),
background_fade_color_(Color(0, 0, 0)) background_fade_color_(Color(0, 0, 0))
{ {
@@ -214,15 +215,15 @@ void HiScoreTable::createSprites()
auto entry_text = Resource::get()->getText("smb2"); auto entry_text = Resource::get()->getText("smb2");
// Obtiene el tamaño de la textura // Obtiene el tamaño de la textura
int backbuffer_width; float backbuffer_width;
int backbuffer_height; float backbuffer_height;
SDL_QueryTexture(backbuffer_, nullptr, nullptr, &backbuffer_width, &backbuffer_height); SDL_GetTextureSize(backbuffer_, &backbuffer_width, &backbuffer_height);
constexpr int entry_lenght = 22; constexpr int ENTRY_LENGHT = 22;
constexpr int max_names = 10; constexpr int MAX_NAMES = 10;
const int space_between_header = entry_text->getCharacterSize() * 4; const int space_between_header = entry_text->getCharacterSize() * 4;
const int space_between_lines = entry_text->getCharacterSize() * 2; 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; const int first_line = (param.game.height - size) / 2;
// Crea el sprite para el texto de cabecera // 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 // Crea los sprites para las entradas en la tabla de puntuaciones
const int animation = rand() % 4; 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<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, orange_color, 1, shdw_txt_color)); auto sample_entry = std::make_unique<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, orange_color, 1, shdw_txt_color));
const auto entry_width = sample_entry->getWidth(); 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 table_position = format(i + 1) + ". ";
const auto score = format(options.game.hi_score_table.at(i).score); 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 ? " }" : ""; const auto one_cc = options.game.hi_score_table.at(i).one_credit_complete ? " }" : "";
std::string dots; std::string dots;
for (int j = 0; j < (int)num_dots; ++j) for (int j = 0; j < (int)num_dots; ++j)

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint16, Uint32, Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint16, Uint32, Uint8
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
@@ -44,7 +44,7 @@ private:
// Variables // Variables
Uint16 counter_ = 0; // Contador Uint16 counter_ = 0; // Contador
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa 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 FadeMode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo Color background_fade_color_; // Color de atenuación del fondo
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla

View File

@@ -52,7 +52,7 @@ void Input::bindKey(InputAction input, SDL_Scancode code)
} }
// Asigna inputs a botones del mando // 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_) 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) if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY)
{ {
const Uint8 *keyStates = SDL_GetKeyboardState(nullptr); const bool *keyStates = SDL_GetKeyboardState(nullptr);
if (repeat) if (repeat)
{ {
@@ -119,13 +119,13 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
{ {
if (repeat) 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 else
{ {
if (!controller_bindings_.at(controller_index).at(input_index).active) 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; controller_bindings_.at(controller_index).at(input_index).active = true;
success_controller = true; success_controller = true;
@@ -137,7 +137,7 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
} }
else 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; 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) 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) 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) 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; controller_bindings_[controller_index][i].active = true;
return true; return true;
@@ -222,26 +222,26 @@ bool Input::discoverGameControllers()
{ {
bool found = false; 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; 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; num_gamepads_ = 0;
// Cuenta el número de mandos // Cuenta el número de mandos
joysticks_.clear(); joysticks_.clear();
for (int i = 0; i < num_joysticks_; ++i) for (int i = 0; i < num_joysticks_; ++i)
{ {
auto joy = SDL_JoystickOpen(i); auto joy = SDL_OpenJoystick(i);
joysticks_.push_back(joy); joysticks_.push_back(joy);
if (SDL_IsGameController(i)) if (SDL_IsGamepad(i))
{ {
num_gamepads_++; num_gamepads_++;
} }
@@ -265,11 +265,11 @@ bool Input::discoverGameControllers()
for (int i = 0; i < num_gamepads_; i++) for (int i = 0; i < num_gamepads_; i++)
{ {
// Abre el mando y lo añade a la lista // Abre el mando y lo añade a la lista
auto pad = SDL_GameControllerOpen(i); auto pad = SDL_OpenGamepad(i);
if (SDL_GameControllerGetAttached(pad) == 1) if (SDL_GamepadConnected(pad) == 1)
{ {
connected_controllers_.push_back(pad); 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; std::cout << "#" << i << ": " << name << std::endl;
controller_names_.push_back(name); 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; 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) for (int i = 0; i < num_joysticks_; ++i)
{ {
if (SDL_JoystickInstanceID(joysticks_[i]) == id) if (SDL_GetJoystickID(joysticks_[i]) == id)
{ {
return i; return i;
} }
@@ -334,8 +334,8 @@ void Input::printBindings(InputDeviceToUse device, int controller_index) const
} }
} }
// Obtiene el SDL_GameControllerButton asignado a un input // Obtiene el SDL_GamepadButton asignado a un input
SDL_GameControllerButton Input::getControllerBinding(int controller_index, InputAction input) const SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const
{ {
return controller_bindings_[controller_index][static_cast<int>(input)].button; return controller_bindings_[controller_index][static_cast<int>(input)].button;
} }
@@ -391,16 +391,16 @@ bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
switch (input) switch (input)
{ {
case InputAction::LEFT: 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; break;
case InputAction::RIGHT: 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; break;
case InputAction::UP: 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; break;
case InputAction::DOWN: 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; break;
default: default:
return false; return false;

View File

@@ -86,7 +86,7 @@ void Instructions::iniSprites()
// Actualiza los sprites // Actualiza los sprites
void Instructions::updateSprites() 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 // Disquito
src_rect.y = param.game.item_size * (((counter_ + 12) / 36) % 2); 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) for (const auto &line : lines)
{ {
SDL_Rect srcRect = {0, line.y, 320, 1}; SDL_FRect srcRect = {0, line.y, 320, 1};
SDL_Rect dstRect = {static_cast<int>(line.x), line.y, 320, 1}; SDL_FRect dstRect = {static_cast<int>(line.x), line.y, 320, 1};
SDL_RenderTexture(renderer, texture, &srcRect, &dstRect); SDL_RenderTexture(renderer, texture, &srcRect, &dstRect);
} }
} }

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
@@ -55,7 +55,7 @@ private:
// Variables // Variables
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones 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 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 SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
int item_space_ = 2; // Espacio entre los items en pantalla int item_space_ = 2; // Espacio entre los items en pantalla
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla

View File

@@ -2,7 +2,7 @@
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND, SDL_BLENDMODE_MOD #include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND, SDL_BLENDMODE_MOD
#include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event #include <SDL3/SDL_events.h> // Para SDL_PollEvent, SDL_Event
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888 #include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_SetTextureBlendMode, SDL_GetRend... #include <SDL3/SDL_render.h> // Para SDL_SetTextureBlendMode, SDL_GetRend...
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <array> // Para array #include <array> // Para array

View File

@@ -5,7 +5,7 @@
#include "param.h" // Para Param, ParamGame, param #include "param.h" // Para Param, ParamGame, param
class Texture; // lines 6-6 class Texture; // lines 6-6
Item::Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation)
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)), : sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
type_(type), type_(type),
play_area_(play_area) 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; width_ = param.game.coffee_machine_w;
height_ = param.game.coffee_machine_h; height_ = param.game.coffee_machine_h;
pos_x_ = ((static_cast<int>(x) + (play_area.w / 2)) % (play_area.w - width_ - 5)) + 2; pos_x_ = (static_cast<int>(x + (play_area.w / 2)) % static_cast<int>(play_area.w - width_ - 5)) + 2;
pos_y_ = y; pos_y_ = y;
vel_x_ = 0.0f; vel_x_ = 0.0f;
vel_y_ = -0.1f; vel_y_ = -0.1f;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint16 #include <SDL3/SDL_stdinc.h> // Para Uint16
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para string #include <string> // Para string
@@ -51,7 +51,7 @@ private:
ItemType type_; /**< Especifica el tipo de objeto que es */ ItemType type_; /**< Especifica el tipo de objeto que es */
bool enabled_ = true; /**< Especifica si el objeto está habilitado */ bool enabled_ = true; /**< Especifica si el objeto está habilitado */
Circle collider_; /**< Círculo de colisión del objeto */ 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 */ 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 texture La textura del objeto.
* @param animation La animación asociada al objeto. * @param animation La animación asociada al objeto.
*/ */
Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation); Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
/** /**
* @brief Destructor de la clase Item. * @brief Destructor de la clase Item.

View File

@@ -1,165 +1,163 @@
#ifndef JA_USESDLMIXER #ifndef JA_USESDLMIXER
#include "jail_audio.h" #include "jail_audio.h"
#include <SDL3/SDL_rwops.h> // Para SDL_RWFromMem #include "stb_vorbis.c"
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL.h>
#include <stdint.h> // Para uint8_t, uint32_t #include <stdio.h>
#include <stdio.h> // Para NULL, fseek, fclose, fopen, fread, ftell
#include <stdlib.h> // Para free, malloc
#include "stb_vorbis.c" // Para stb_vorbis_decode_memory
#define JA_MAX_SIMULTANEOUS_CHANNELS 20 #define JA_MAX_SIMULTANEOUS_CHANNELS 20
struct JA_Sound_t struct JA_Sound_t
{ {
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0}; Uint32 length{0};
Uint8 *buffer{NULL}; Uint8 *buffer{NULL};
}; };
struct JA_Channel_t struct JA_Channel_t
{ {
JA_Sound_t *sound; JA_Sound_t *sound{nullptr};
int pos{0}; int pos{0};
int times{0}; int times{0};
SDL_AudioStream *stream{nullptr};
JA_Channel_state state{JA_CHANNEL_FREE}; JA_Channel_state state{JA_CHANNEL_FREE};
}; };
struct JA_Music_t struct JA_Music_t
{ {
int samples{0}; SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0}; Uint32 length{0};
Uint8 *buffer{nullptr};
int pos{0}; int pos{0};
int times{0}; int times{0};
short *output{NULL}; SDL_AudioStream *stream{nullptr};
JA_Music_state state{JA_MUSIC_INVALID}; 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]; JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
int JA_freq{48000}; SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000};
SDL_AudioFormat JA_format{AUDIO_S16}; float JA_musicVolume{1.0f};
Uint8 JA_channels{2}; float JA_soundVolume{0.5f};
int JA_musicVolume = 128; bool JA_musicEnabled{true};
int JA_soundVolume = 64; bool JA_soundEnabled{true};
bool JA_musicEnabled = true; SDL_AudioDeviceID sdlAudioDevice{0};
bool JA_soundEnabled = true; SDL_TimerID JA_timerID{0};
SDL_AudioDeviceID sdlAudioDevice = 0;
bool fading = false; /*
int fade_start_time; void audioCallback(void * userdata, uint8_t * stream, int len) {
int fade_duration;
int fade_initial_volume;
void audioCallback(void *userdata, uint8_t *stream, int len)
{
SDL_memset(stream, 0, len); SDL_memset(stream, 0, len);
if (current_music != NULL && current_music->state == JA_MUSIC_PLAYING) if (current_music != NULL && current_music->state == JA_MUSIC_PLAYING) {
{ const int size = SDL_min(len, current_music->samples*2-current_music->pos);
int volume = JA_musicVolume; SDL_MixAudioFormat(stream, (Uint8*)(current_music->output+current_music->pos), AUDIO_S16, size, JA_musicVolume);
if (fading) current_music->pos += size/2;
{ if (size < len) {
int time = SDL_GetTicks(); if (current_music->times != 0) {
if (time > (fade_start_time + fade_duration)) SDL_MixAudioFormat(stream+size, (Uint8*)current_music->output, AUDIO_S16, len-size, JA_musicVolume);
{ current_music->pos = (len-size)/2;
fading = false; if (current_music->times > 0) current_music->times--;
current_music->pos = 0; } else {
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
{
current_music->pos = 0; current_music->pos = 0;
current_music->state = JA_MUSIC_STOPPED; current_music->state = JA_MUSIC_STOPPED;
} }
} }
} }
// Mixar els channels mi amol // Mixar els channels mi amol
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)
{
const int size = SDL_min(len, channels[i].sound->length - channels[i].pos); 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); SDL_MixAudioFormat(stream, channels[i].sound->buffer + channels[i].pos, AUDIO_S16, size, JA_soundVolume);
channels[i].pos += size; channels[i].pos += size;
if (size < len) if (size < len) {
{ if (channels[i].times != 0) {
if (channels[i].times != 0)
{
SDL_MixAudioFormat(stream + size, channels[i].sound->buffer, AUDIO_S16, len-size, JA_soundVolume); SDL_MixAudioFormat(stream + size, channels[i].sound->buffer, AUDIO_S16, len-size, JA_soundVolume);
channels[i].pos = len-size; channels[i].pos = len-size;
if (channels[i].times > 0) if (channels[i].times > 0) channels[i].times--;
channels[i].times--; } else {
}
else
{
JA_StopChannel(i); 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) void JA_Init(const int freq, const SDL_AudioFormat format, const int channels)
{ {
JA_freq = freq; JA_audioSpec = {format, channels, freq};
JA_format = format; if (!sdlAudioDevice)
JA_channels = channels;
SDL_AudioSpec audioSpec{JA_freq, JA_format, JA_channels, 0, 1024, 0, 0, audioCallback, NULL};
if (sdlAudioDevice != 0)
SDL_CloseAudioDevice(sdlAudioDevice); SDL_CloseAudioDevice(sdlAudioDevice);
sdlAudioDevice = SDL_OpenAudioDevice(NULL, 0, &audioSpec, NULL, 0); sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
SDL_PauseAudioDevice(sdlAudioDevice, 0); SDL_PauseAudioDevice(sdlAudioDevice);
JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr);
} }
void JA_Quit() void JA_Quit()
{ {
SDL_PauseAudioDevice(sdlAudioDevice, 1); if (JA_timerID)
if (sdlAudioDevice != 0) SDL_RemoveTimer(JA_timerID);
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)
{ {
int chan, samplerate;
JA_Music_t *music = new JA_Music_t(); JA_Music_t *music = new JA_Music_t();
music->samples = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &music->output); int chan, samplerate;
// [RZC 28/08/22] Abans el descomprimiem mentre el teniem obert short *output;
// music->samples = stb_vorbis_decode_filename(filename, &chan, &samplerate, &music->output); music->length = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &output) * chan * 2;
SDL_AudioCVT cvt; music->spec.channels = chan;
SDL_BuildAudioCVT(&cvt, AUDIO_S16, chan, samplerate, JA_format, JA_channels, JA_freq); music->spec.freq = samplerate;
if (cvt.needed) music->spec.format = SDL_AUDIO_S16;
{ music->buffer = (Uint8 *)SDL_malloc(music->length);
cvt.len = music->samples * chan * 2; SDL_memcpy(music->buffer, output, music->length);
music->length = cvt.len; SDL_free(output);
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->pos = 0; music->pos = 0;
music->state = JA_MUSIC_STOPPED; 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->pos = 0;
current_music->state = JA_MUSIC_PLAYING; current_music->state = JA_MUSIC_PLAYING;
current_music->times = loop; current_music->times = loop;
current_music->stream = SDL_CreateAudioStream(&current_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() void JA_PauseMusic()
{ {
if (!JA_musicEnabled) if (!JA_musicEnabled)
return; return;
if (!current_music || current_music->state == JA_MUSIC_INVALID)
if (current_music == NULL || 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);
} }
void JA_ResumeMusic() void JA_ResumeMusic()
{ {
if (!JA_musicEnabled) if (!JA_musicEnabled)
return; return;
if (!current_music || current_music->state == JA_MUSIC_INVALID)
if (current_music == NULL || 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);
} }
void JA_StopMusic() void JA_StopMusic()
{ {
if (!JA_musicEnabled) if (!JA_musicEnabled)
return; return;
if (!current_music || current_music->state == JA_MUSIC_INVALID)
if (current_music == NULL || 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_DestroyAudioStream(current_music->stream);
void JA_FadeOutMusic(const int milliseconds) current_music->stream = nullptr;
{
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;
} }
JA_Music_state JA_GetMusicState() JA_Music_state JA_GetMusicState()
{ {
if (!JA_musicEnabled) if (!JA_musicEnabled)
return JA_MUSIC_DISABLED; return JA_MUSIC_DISABLED;
if (!current_music)
if (current_music == NULL)
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) if (current_music == music)
current_music = NULL; current_music = nullptr;
free(music->output); SDL_free(music->buffer);
SDL_DestroyAudioStream(music->stream);
delete music; delete music;
} }
int JA_SetMusicVolume(int volume) float JA_SetMusicVolume(float volume)
{ {
JA_musicVolume = volume > 128 ? 128 : volume < 0 ? 0 JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f);
: volume; if (current_music)
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
return 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) 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_StopMusic();
JA_musicEnabled = value; 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 *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_AudioSpec wavSpec; SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length);
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;
return sound; 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 *JA_LoadSound(const char *filename)
{ {
JA_Sound_t *sound = new JA_Sound_t(); JA_Sound_t *sound = new JA_Sound_t();
SDL_AudioSpec wavSpec; SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length);
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;
return sound; return sound;
} }
@@ -355,21 +318,11 @@ int JA_PlaySound(JA_Sound_t *sound, const int loop)
channels[channel].times = loop; channels[channel].times = loop;
channels[channel].pos = 0; channels[channel].pos = 0;
channels[channel].state = JA_CHANNEL_PLAYING; 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; return channel;
} }
@@ -392,15 +345,19 @@ void JA_PauseChannel(const int channel)
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);
} }
} }
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
{ {
if (channels[channel].state == JA_CHANNEL_PLAYING) if (channels[channel].state == JA_CHANNEL_PLAYING)
{
channels[channel].state = JA_CHANNEL_PAUSED; channels[channel].state = JA_CHANNEL_PAUSED;
SDL_PauseAudioStreamDevice(channels[channel].stream);
}
} }
} }
@@ -412,15 +369,19 @@ void JA_ResumeChannel(const int channel)
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);
} }
} }
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
{ {
if (channels[channel].state == JA_CHANNEL_PAUSED) if (channels[channel].state == JA_CHANNEL_PAUSED)
{
channels[channel].state = JA_CHANNEL_PLAYING; 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].state = JA_CHANNEL_FREE;
channels[i].pos = 0; channels[i].pos = 0;
channels[i].sound = NULL; channels[i].sound = NULL;
SDL_DestroyAudioStream(channels[i].stream);
} }
} }
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) 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].state = JA_CHANNEL_FREE;
channels[channel].pos = 0; channels[channel].pos = 0;
channels[channel].sound = NULL; 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) if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS)
return JA_CHANNEL_INVALID; return JA_CHANNEL_INVALID;
return channels[channel].state; return channels[channel].state;
} }
int JA_SetSoundVolume(int volume) float JA_SetSoundVolume(float volume)
{ {
JA_soundVolume = volume > 128 ? 128 : volume < 0 ? 0 JA_soundVolume = SDL_clamp(volume, 0.0f, 1.0f);
: volume;
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; return JA_soundVolume;
} }
@@ -473,11 +441,10 @@ void JA_EnableSound(const bool value)
JA_soundEnabled = value; JA_soundEnabled = value;
} }
int JA_SetVolume(int volume) float JA_SetVolume(float volume)
{ {
JA_musicVolume = volume > 128 ? 128 : volume < 0 ? 0 JA_SetSoundVolume(JA_SetMusicVolume(volume) / 2.0f);
: volume;
JA_soundVolume = JA_musicVolume / 2;
return JA_musicVolume; return JA_musicVolume;
} }

View File

@@ -1,9 +1,5 @@
#pragma once #pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL_audio.h> // Para SDL_AudioFormat
#include <SDL3/SDL_stdinc.h> // Para Uint32, Uint8
struct JA_Music_t; // lines 4-4
struct JA_Sound_t; // lines 5-5
enum JA_Channel_state enum JA_Channel_state
{ {
@@ -22,6 +18,9 @@ enum JA_Music_state
JA_MUSIC_DISABLED 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_Init(const int freq, const SDL_AudioFormat format, const int channels);
void JA_Quit(); void JA_Quit();
@@ -31,25 +30,21 @@ void JA_PlayMusic(JA_Music_t *music, const int loop = -1);
void JA_PauseMusic(); void JA_PauseMusic();
void JA_ResumeMusic(); void JA_ResumeMusic();
void JA_StopMusic(); void JA_StopMusic();
void JA_FadeOutMusic(const int milliseconds);
JA_Music_state JA_GetMusicState(); JA_Music_state JA_GetMusicState();
void JA_DeleteMusic(JA_Music_t *music); void JA_DeleteMusic(JA_Music_t *music);
int JA_SetMusicVolume(int volume); float JA_SetMusicVolume(float volume);
void JA_SetMusicPosition(float value);
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); 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_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);
int JA_SetSoundVolume(int volume); float JA_SetSoundVolume(float volume);
void JA_EnableSound(const bool value); void JA_EnableSound(const bool value);
int JA_SetVolume(int volume); float JA_SetVolume(float volume);

View File

@@ -164,11 +164,10 @@ namespace shader
throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET."); throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET.");
} }
SDL_RendererInfo infoRenderer; const auto RENDER_NAME = SDL_GetRendererName(renderer);
SDL_GetRendererInfo(renderer, &infoRenderer);
// Verificar que el renderer sea OpenGL // Verificar que el renderer sea OpenGL
if (!strncmp(infoRenderer.name, "opengl", 6)) if (!strncmp(RENDER_NAME, "opengl", 6))
{ {
#ifndef __APPLE__ #ifndef __APPLE__
if (!initGLExtensions()) if (!initGLExtensions())
@@ -201,7 +200,8 @@ namespace shader
if (usingOpenGL) if (usingOpenGL)
{ {
SDL_GL_BindTexture(backBuffer, nullptr, nullptr); SDL_GetTextureProperties(backBuffer);
// SDL_GL_BindTexture(backBuffer, nullptr, nullptr);
if (programId != 0) if (programId != 0)
{ {
glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgramId); glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgramId);
@@ -210,7 +210,8 @@ namespace shader
// Recupera el tamaño lógico configurado con SDL_RenderSetLogicalSize // Recupera el tamaño lógico configurado con SDL_RenderSetLogicalSize
int logicalW, logicalH; int logicalW, logicalH;
SDL_RenderGetLogicalSize(renderer, &logicalW, &logicalH); SDL_RendererLogicalPresentation mode;
SDL_GetRenderLogicalPresentation(renderer, &logicalW, &logicalH, &mode);
if (logicalW == 0 || logicalH == 0) if (logicalW == 0 || logicalH == 0)
{ {
logicalW = win_size.x; logicalW = win_size.x;
@@ -219,15 +220,17 @@ namespace shader
// Cálculo del viewport // Cálculo del viewport
int viewportX = 0, viewportY = 0, viewportW = win_size.x, viewportH = win_size.y; int viewportX = 0, viewportY = 0, viewportW = win_size.x, viewportH = win_size.y;
SDL_bool useIntegerScale = SDL_RenderGetIntegerScale(renderer); const bool USE_INTEGER_SCALE = mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE;
if (useIntegerScale) if (USE_INTEGER_SCALE)
{ {
// Calcula el factor de escalado entero máximo que se puede aplicar // Calcula el factor de escalado entero máximo que se puede aplicar
int scaleX = win_size.x / logicalW; int scaleX = win_size.x / logicalW;
int scaleY = win_size.y / logicalH; int scaleY = win_size.y / logicalH;
int scale = (scaleX < scaleY ? scaleX : scaleY); int scale = (scaleX < scaleY ? scaleX : scaleY);
if (scale < 1) if (scale < 1)
{
scale = 1; scale = 1;
}
viewportW = logicalW * scale; viewportW = logicalW * scale;
viewportH = logicalH * scale; viewportH = logicalH * scale;
viewportX = (win_size.x - viewportW) / 2; viewportX = (win_size.x - viewportW) / 2;

View File

@@ -2,7 +2,7 @@
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
// Constructor // Constructor
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip)
: Sprite(texture, pos), : Sprite(texture, pos),
x_(pos.x), x_(pos.x),
y_(pos.y), y_(pos.y),
@@ -11,7 +11,7 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, Rotat
zoom_h_(zoom_h), zoom_h_(zoom_h),
flip_(flip) {} flip_(flip) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
: Sprite(texture, pos), : Sprite(texture, pos),
x_(pos.x), x_(pos.x),
y_(pos.y), y_(pos.y),
@@ -96,7 +96,7 @@ void MovingSprite::setRotate(bool enable)
} }
// Establece la posición y_ el tamaño del objeto // 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<float>(rect.x); x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(rect.y); y_ = static_cast<float>(rect.y);

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point
#include <SDL3/SDL_render.h> // Para SDL_RendererFlip #include <SDL3/SDL_render.h> // Para SDL_RendererFlip
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <algorithm> #include <algorithm>
@@ -49,8 +49,8 @@ protected:
public: public:
// Constructor // Constructor
MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip); MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip);
MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos); MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos);
explicit MovingSprite(std::shared_ptr<Texture> texture); explicit MovingSprite(std::shared_ptr<Texture> texture);
// Destructor // Destructor
@@ -110,7 +110,7 @@ public:
SDL_RendererFlip getFlip() { return flip_; } SDL_RendererFlip getFlip() { return flip_; }
// Establece la posición y_ el tamaño del objeto // 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 // Establece el valor de las variables
void setPos(float x, float y); void setPos(float x, float y);

View File

@@ -242,7 +242,7 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Dibuja el fondo de la notificación // Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255); SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255);
SDL_Rect rect; SDL_FRect rect;
if (shape == NotificationShape::ROUNDED) if (shape == NotificationShape::ROUNDED)
{ {
rect = {4, 0, width - (4 * 2), height}; rect = {4, 0, width - (4 * 2), height};
@@ -266,7 +266,7 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Dibuja el icono de la notificación // Dibuja el icono de la notificación
if (has_icons_ && icon >= 0 && texts.size() >= 2) if (has_icons_ && icon >= 0 && texts.size() >= 2)
{ {
auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_Rect){0, 0, icon_size, icon_size}); auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_FRect){0, 0, icon_size, icon_size});
sp->setPosition({padding_in_h, padding_in_v, 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->setSpriteClip({icon_size * (icon % 10), icon_size * (icon / 10), icon_size, icon_size});
sp->render(); sp->render();

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Renderer
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
#include <string> // Para string, basic_string #include <string> // Para string, basic_string
@@ -38,7 +38,7 @@ private:
int counter; int counter;
NotificationStatus state; NotificationStatus state;
NotificationShape shape; NotificationShape shape;
SDL_Rect rect; SDL_FRect rect;
int y; int y;
int travel_dist; int travel_dist;
std::string code; // Permite asignar un código a la notificación std::string code; // Permite asignar un código a la notificación

View File

@@ -18,21 +18,21 @@ constexpr int ICONSIZE = 16;
constexpr SDL_Point PADDING = {8, 8}; constexpr SDL_Point PADDING = {8, 8};
constexpr SDL_Point DESP = {ICONSIZE + 4, 5}; constexpr SDL_Point DESP = {ICONSIZE + 4, 5};
constexpr SDL_Rect CONTROLLER_UP = {16, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect CONTROLLER_UP = {16, 0, ICONSIZE, ICONSIZE};
constexpr SDL_Rect CONTROLLER_DOWN = {48, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect CONTROLLER_DOWN = {48, 0, ICONSIZE, ICONSIZE};
constexpr SDL_Rect CONTROLLER_LEFT = {64, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect CONTROLLER_LEFT = {64, 0, ICONSIZE, ICONSIZE};
constexpr SDL_Rect LEFT_BUTTON = {112, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect LEFT_BUTTON = {112, 0, ICONSIZE, ICONSIZE};
constexpr SDL_Rect TOP_BUTTON = {80, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect TOP_BUTTON = {80, 0, ICONSIZE, ICONSIZE};
constexpr SDL_Rect RIGHT_BUTTON = {96, 0, ICONSIZE, ICONSIZE}; constexpr SDL_FRect RIGHT_BUTTON = {96, 0, ICONSIZE, ICONSIZE};
constexpr SDL_Rect START_BUTTON = {0, 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_FRect 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_FRect 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_FRect 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_FRect 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_FRect 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_FRect 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 START_BUTTON_POS = {PADDING.x, PADDING.y + 18 * 6, ICONSIZE, ICONSIZE};
// [SINGLETON] Crearemos el objeto onScreenHelp con esta función estática // [SINGLETON] Crearemos el objeto onScreenHelp con esta función estática
void OnScreenHelp::init() void OnScreenHelp::init()
@@ -100,7 +100,7 @@ void OnScreenHelp::fillTexture()
auto controllersTexture = Resource::get()->getTexture("controllers.png"); auto controllersTexture = Resource::get()->getTexture("controllers.png");
// Crea el sprite para dibujar los gráficos // Crea el sprite para dibujar los gráficos
auto sprite = std::make_unique<Sprite>(controllersTexture, (SDL_Rect){0, 0, 16, 16}); auto sprite = std::make_unique<Sprite>(controllersTexture, (SDL_FRect){0, 0, 16, 16});
// Borra la textura // Borra la textura
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0);
@@ -108,7 +108,7 @@ void OnScreenHelp::fillTexture()
// Pon el color de fondo con el bisel // Pon el color de fondo con el bisel
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0x55, 0x5D, 0x77, 255); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0x55, 0x5D, 0x77, 255);
SDL_Rect rect; SDL_FRect rect;
rect = {4, 0, dest.w - (4 * 2), dest.h}; rect = {4, 0, dest.w - (4 * 2), dest.h};
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect); SDL_RenderFillRect(Screen::get()->getRenderer(), &rect);
@@ -146,7 +146,7 @@ void OnScreenHelp::setSize()
const auto x = 0; const auto x = 0;
const auto y = (param.game.height - height) / 2; const auto y = (param.game.height - height) / 2;
dest = (SDL_Rect){x, y, width, height}; dest = (SDL_FRect){x, y, width, height};
hiddenPos = -width; hiddenPos = -width;
showingPos = 0; showingPos = 0;
@@ -182,7 +182,7 @@ auto OnScreenHelp::getLargestStringSize() -> int const
} }
// Renderizara el boton y el texto // 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->setSpriteClip(buttonClip);
sprite->setPosition(buttonPos); sprite->setPosition(buttonPos);

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Texture
#include <vector> // Para vector #include <vector> // Para vector
class Sprite; class Sprite;
@@ -22,7 +22,7 @@ private:
static OnScreenHelp *onScreenHelp; static OnScreenHelp *onScreenHelp;
SDL_Texture *texture; // Textura donde dibujar 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 int hiddenPos, showingPos; // Las dos posiciones donde colocar la textura
OnScreenHelpStatus state; // Estado del objeto OnScreenHelpStatus state; // Estado del objeto
@@ -47,7 +47,7 @@ private:
auto getLargestStringSize() -> int const; auto getLargestStringSize() -> int const;
// Renderizara el boton y el texto // 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 // Actualiza la posición
void updatePosition(); void updatePosition();

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <string> // Para string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector
@@ -71,7 +71,7 @@ struct Param
{ {
ParamGame game; ParamGame game;
ParamFade fade; ParamFade fade;
SDL_Rect scoreboard; SDL_FRect scoreboard;
ParamTitle title; ParamTitle title;
ParamBackground background; ParamBackground background;
std::vector<ParamBalloon> balloon; std::vector<ParamBalloon> balloon;

View File

@@ -14,7 +14,7 @@
#include <array> #include <array>
// Constructor // Constructor
Player::Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations) Player::Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations)
: player_sprite_(std::make_unique<AnimatedSprite>(texture[0], animations[0])), : player_sprite_(std::make_unique<AnimatedSprite>(texture[0], animations[0])),
power_sprite_(std::make_unique<AnimatedSprite>(texture[1], animations[1])), power_sprite_(std::make_unique<AnimatedSprite>(texture[1], animations[1])),
enter_name_(std::make_unique<EnterName>()), enter_name_(std::make_unique<EnterName>()),

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string #include <string> // Para string
@@ -63,7 +63,7 @@ private:
// Variables // Variables
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 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 float pos_x_ = 0.0f; // Posicion en el eje X
int pos_y_ = 0; // Posicion en el eje Y int pos_y_ = 0; // Posicion en el eje Y
float default_pos_x_; // Posición inicial para el jugador float default_pos_x_; // Posición inicial para el jugador
@@ -134,7 +134,7 @@ private:
public: public:
// Constructor // Constructor
Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations); Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
// Destructor // Destructor
~Player() = default; ~Player() = default;

View File

@@ -131,7 +131,7 @@ void Scoreboard::setColor(Color color)
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setPos(SDL_Rect rect) void Scoreboard::setPos(SDL_FRect rect)
{ {
rect_ = rect; rect_ = rect;
@@ -259,7 +259,7 @@ void Scoreboard::fillPanelTextures()
// ENTER NAME // ENTER NAME
{ {
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106)); 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 // Recorre todos los slots de letras del nombre
for (size_t j = 0; j < MAX_NAME_LENGHT; ++j) for (size_t j = 0; j < MAX_NAME_LENGHT; ++j)

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Texture, SDL_Renderer
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL_timer.h> // Para SDL_GetTicks
@@ -38,7 +38,7 @@ enum class ScoreboardMode : int
struct Panel struct Panel
{ {
ScoreboardMode mode; // Modo en el que se encuentra el 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 // Clase Scoreboard
@@ -71,7 +71,7 @@ private:
float power_ = 0; // Poder actual de la fase float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador 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() Uint32 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks()
int time_counter_ = 0; // Contador de segundos int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle int loop_counter_ = 0; // Contador de bucle
@@ -136,7 +136,7 @@ public:
void setColor(Color color); void setColor(Color color);
// Establece el valor de la variable // 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 setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; }
void setHiScore(int hi_score) { hi_score_ = hi_score; } void setHiScore(int hi_score) { hi_score_ = hi_score; }

View File

@@ -259,7 +259,7 @@ void Screen::adjustWindowSize()
const int NEW_POS_X = old_pos_x + (old_width - WIDTH) / 2; const int NEW_POS_X = old_pos_x + (old_width - WIDTH) / 2;
const int NEW_POS_Y = old_pos_y + (old_height - HEIGHT) / 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_SetRenderViewport(renderer_, &viewport);
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0)); SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0));

View File

@@ -1,7 +1,7 @@
#pragma once #pragma once
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode #include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL_video.h> // Para SDL_Window #include <SDL3/SDL_video.h> // Para SDL_Window

View File

@@ -4,13 +4,13 @@
// Constructor // Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, int x, int y, int w, int h) Sprite::Sprite(std::shared_ptr<Texture> texture, int x, int y, int w, int h)
: texture_(texture), : texture_(texture),
pos_((SDL_Rect){x, y, w, h}), pos_((SDL_FRect){x, y, w, h}),
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, SDL_Rect rect) Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: texture_(texture), : texture_(texture),
pos_(rect), 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) Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture), : texture_(texture),

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
class Texture; class Texture;
@@ -10,14 +10,14 @@ class Sprite
protected: protected:
// Variables // Variables
std::shared_ptr<Texture> texture_; // Textura donde estan todos los dibujos del sprite std::shared_ptr<Texture> texture_; // Textura donde estan todos los dibujos del sprite
SDL_Rect pos_; // Posición y tamaño donde dibujar el sprite SDL_FRect 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 sprite_clip_; // Rectangulo de origen de la textura que se dibujará en pantalla
double zoom_ = 1.0f; // Zoom aplicado a la textura double zoom_ = 1.0f; // Zoom aplicado a la textura
public: public:
// Constructor // Constructor
Sprite(std::shared_ptr<Texture>, int x, int y, int w, int h); Sprite(std::shared_ptr<Texture>, int x, int y, int w, int h);
Sprite(std::shared_ptr<Texture>, SDL_Rect rect); Sprite(std::shared_ptr<Texture>, SDL_FRect rect);
explicit Sprite(std::shared_ptr<Texture>); explicit Sprite(std::shared_ptr<Texture>);
// Destructor // Destructor
@@ -36,8 +36,8 @@ public:
int getHeight() const { return pos_.h; } int getHeight() const { return pos_.h; }
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect getPosition() const { return pos_; } SDL_FRect getPosition() const { return pos_; }
SDL_Rect &getRect() { return pos_; } SDL_FRect &getRect() { return pos_; }
// Establece la posición y el tamaño // Establece la posición y el tamaño
void setX(int x) { pos_.x = x; } void setX(int x) { pos_.x = x; }
@@ -48,7 +48,7 @@ public:
// Establece la posición del objeto // Establece la posición del objeto
void setPosition(int x, int y); void setPosition(int x, int y);
void setPosition(SDL_Point p); void setPosition(SDL_Point p);
void setPosition(SDL_Rect r) { pos_ = r; } void setPosition(SDL_FRect r) { pos_ = r; }
// Establece el nivel de zoom // Establece el nivel de zoom
void setZoom(float zoom) { zoom_ = zoom; } void setZoom(float zoom) { zoom_ = zoom; }
@@ -58,11 +58,11 @@ public:
void incY(int value) { pos_.y += value; } void incY(int value) { pos_.y += value; }
// Obtiene el rectangulo que se dibuja de la textura // 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 // Establece el rectangulo que se dibuja de la textura
void setSpriteClip(SDL_Rect rect) { sprite_clip_ = rect; } void setSpriteClip(SDL_FRect rect) { sprite_clip_ = rect; }
void setSpriteClip(int x, int y, int w, int h) { sprite_clip_ = (SDL_Rect){x, y, w, h}; } void setSpriteClip(int x, int y, int w, int h) { sprite_clip_ = (SDL_FRect){x, y, w, h}; }
// Obtiene un puntero a la textura // Obtiene un puntero a la textura
std::shared_ptr<Texture> getTexture() const { return texture_; } std::shared_ptr<Texture> getTexture() const { return texture_; }

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_stdinc.h> // Para Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint32
#include <SDL3/SDL_timer.h> // Para SDL_GetTicks #include <SDL3/SDL_timer.h> // Para SDL_GetTicks
#include <stdlib.h> // Para rand #include <stdlib.h> // Para rand
@@ -136,7 +136,7 @@ public:
bool tryToGetBonus(); bool tryToGetBonus();
// Obtiene el area de colisión // Obtiene el area de colisión
SDL_Rect &getCollider() { return sprite_->getRect(); } SDL_FRect &getCollider() { return sprite_->getRect(); }
// Getters // Getters
bool isEnabled() const { return enabled_; } bool isEnabled() const { return enabled_; }

View File

@@ -1,7 +1,7 @@
#include "text.h" #include "text.h"
#include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND #include <SDL3/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888 #include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_TEXTUREACCESS_TARGET #include <SDL3/SDL_render.h> // Para SDL_TEXTUREACCESS_TARGET
#include <stddef.h> // Para size_t #include <stddef.h> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic... #include <fstream> // Para basic_ifstream, basic_istream, basic...
@@ -96,7 +96,7 @@ Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file)
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_Rect){0, 0, box_width_, box_height_}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -116,7 +116,7 @@ Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>(texture, (SDL_Rect){0, 0, box_width_, box_height_}); sprite_ = std::make_unique<Sprite>(texture, (SDL_FRect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixed_width_ = false; 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) for (size_t i = 0; i < text.length(); ++i)
{ {
auto index = static_cast<size_t>(text[i]); auto index = static_cast<size_t>(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); sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f);
shift += (offset_[index].w + kerning) * 2; shift += (offset_[index].w + kerning) * 2;
} }

View File

@@ -174,10 +174,10 @@ void Texture::setAlpha(Uint8 alpha)
} }
// Renderiza la textura en un punto específico // 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 // 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 // Obtiene las dimesiones del clip de renderizado
if (clip != nullptr) if (clip != nullptr)

View File

@@ -2,7 +2,7 @@
#include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode #include <SDL3/SDL_blendmode.h> // Para SDL_BlendMode
#include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF... #include <SDL3/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF...
#include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_Point, SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX... #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX...
#include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32 #include <SDL3/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
#include <memory> // Para shared_ptr #include <memory> // Para shared_ptr
@@ -75,7 +75,7 @@ public:
void setAlpha(Uint8 alpha); void setAlpha(Uint8 alpha);
// Renderiza la textura en un punto específico // 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 // Establece la textura como objetivo de renderizado
void setAsRenderTarget(SDL_Renderer *renderer); void setAsRenderTarget(SDL_Renderer *renderer);

View File

@@ -8,7 +8,7 @@
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
// Constructor // Constructor
TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode) TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode)
: renderer_(Screen::get()->getRenderer()), : renderer_(Screen::get()->getRenderer()),
pos_(pos), pos_(pos),
mode_(mode == TiledBGMode::RANDOM ? static_cast<TiledBGMode>(rand() % 2) : mode) mode_(mode == TiledBGMode::RANDOM ? static_cast<TiledBGMode>(rand() % 2) : mode)
@@ -54,7 +54,7 @@ TiledBG::~TiledBG()
void TiledBG::fillTexture() void TiledBG::fillTexture()
{ {
// Crea los objetos para pintar en la textura de fondo // Crea los objetos para pintar en la textura de fondo
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_Rect){0, 0, TILE_WIDTH_, TILE_HEIGHT_}); auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH_, TILE_HEIGHT_});
// Prepara para dibujar sobre la textura // Prepara para dibujar sobre la textura
auto temp = SDL_GetRenderTarget(renderer_); auto temp = SDL_GetRenderTarget(renderer_);

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect #include <SDL3/SDL_rect.h> // Para SDL_FRect
#include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL3/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include "utils.h" #include "utils.h"
@@ -32,8 +32,8 @@ private:
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
// Variables // Variables
SDL_Rect pos_; // Posición y tamaño del mosaico SDL_FRect pos_; // Posición y tamaño del mosaico
SDL_Rect window_; // Ventana visible para la textura de fondo del titulo SDL_FRect window_; // Ventana visible para la textura de fondo del titulo
TiledBGMode mode_; // Tipo de movimiento del mosaico TiledBGMode mode_; // Tipo de movimiento del mosaico
double sin_[360]; // Vector con los valores del seno precalculados double sin_[360]; // Vector con los valores del seno precalculados
float desp_ = 0.0f; // Desplazamiento aplicado float desp_ = 0.0f; // Desplazamiento aplicado
@@ -51,7 +51,7 @@ private:
public: public:
// Constructor // Constructor
TiledBG(SDL_Rect pos, TiledBGMode mode); TiledBG(SDL_FRect pos, TiledBGMode mode);
// Destructor // Destructor
~TiledBG(); ~TiledBG();

View File

@@ -69,7 +69,7 @@ bool checkCollision(const Circle &a, const Circle &b)
} }
// Detector de colisiones entre un circulo y un rectangulo // 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 // Encuentra el punto más cercano en el rectángulo
int cX = std::clamp(a.x, b.x, b.x + b.w); 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 // 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 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; 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 // 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) if (p.x < r.x || p.x > r.x + r.w)
return false; return false;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point #include <SDL3/SDL_rect.h> // Para SDL_FRect, SDL_Point
#include <SDL3/SDL_render.h> // Para SDL_Renderer #include <SDL3/SDL_render.h> // Para SDL_Renderer
#include <SDL3/SDL_stdinc.h> // Para Uint8 #include <SDL3/SDL_stdinc.h> // Para Uint8
#include <stdint.h> // Para int32_t #include <stdint.h> // 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); bool checkCollision(const Circle &a, const Circle &b);
// Detector de colisiones entre un circulo y un rectangulo // 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 // 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 // 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 // Convierte una cadena en un valor booleano
bool stringToBool(const std::string &str); bool stringToBool(const std::string &str);