From 41d72d48d53dafbfb505cb8bfdb6d55bfc4f3dbf Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Mon, 10 Oct 2022 13:51:51 +0200 Subject: [PATCH] Reubicados los cpp de librerias comunes --- Makefile | 2 +- source/const.h | 2 +- source/credits.h | 12 +- source/director.cpp | 3 +- source/director.h | 22 +- source/enemy.h | 6 +- source/game.h | 24 +- source/intro.h | 12 +- source/item.h | 7 +- source/item_tracker.h | 2 +- source/logo.h | 10 +- source/player.h | 14 +- source/room.h | 20 +- source/room_tracker.h | 3 +- source/scoreboard.h | 8 +- source/test.h | 12 +- source/title.h | 12 +- source/{ => utils}/animatedsprite.cpp | 0 source/{ => utils}/animatedsprite.h | 146 ++--- source/{ => utils}/asset.cpp | 0 source/{ => utils}/asset.h | 0 source/{ => utils}/debug.cpp | 0 source/{ => utils}/debug.h | 8 +- source/{ => utils}/input.cpp | 0 source/{ => utils}/input.h | 180 +++--- source/{ => utils}/jail_audio.cpp | 0 source/{ => utils}/jail_audio.h | 0 source/{ => utils}/ltexture.cpp | 370 +++++------ source/{ => utils}/ltexture.h | 122 ++-- source/utils/menu.cpp | 890 ++++++++++++++++++++++++++ source/utils/menu.h | 214 +++++++ source/{ => utils}/movingsprite.cpp | 0 source/{ => utils}/movingsprite.h | 346 +++++----- source/{ => utils}/screen.cpp | 0 source/{ => utils}/screen.h | 0 source/{ => utils}/sprite.cpp | 0 source/{ => utils}/sprite.h | 198 +++--- source/{ => utils}/stb_image.h | 0 source/{ => utils}/stb_vorbis.c | 0 source/{ => utils}/text.cpp | 1 - source/{ => utils}/text.h | 143 +++-- source/{ => utils}/utils.cpp | 0 source/{ => utils}/utils.h | 0 43 files changed, 1947 insertions(+), 842 deletions(-) rename source/{ => utils}/animatedsprite.cpp (100%) rename source/{ => utils}/animatedsprite.h (96%) rename source/{ => utils}/asset.cpp (100%) rename source/{ => utils}/asset.h (100%) rename source/{ => utils}/debug.cpp (100%) rename source/{ => utils}/debug.h (98%) rename source/{ => utils}/input.cpp (100%) rename source/{ => utils}/input.h (96%) rename source/{ => utils}/jail_audio.cpp (100%) rename source/{ => utils}/jail_audio.h (100%) rename source/{ => utils}/ltexture.cpp (95%) rename source/{ => utils}/ltexture.h (96%) create mode 100644 source/utils/menu.cpp create mode 100644 source/utils/menu.h rename source/{ => utils}/movingsprite.cpp (100%) rename source/{ => utils}/movingsprite.h (96%) rename source/{ => utils}/screen.cpp (100%) rename source/{ => utils}/screen.h (100%) rename source/{ => utils}/sprite.cpp (100%) rename source/{ => utils}/sprite.h (96%) rename source/{ => utils}/stb_image.h (100%) rename source/{ => utils}/stb_vorbis.c (100%) rename source/{ => utils}/text.cpp (99%) rename source/{ => utils}/text.h (96%) rename source/{ => utils}/utils.cpp (100%) rename source/{ => utils}/utils.h (100%) diff --git a/Makefile b/Makefile index 6280bd7..b85d10c 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ executable = jaildoctors_dilemma windows: @echo off if not exist bin\ (mkdir bin) - g++ -std=c++11 -Wall -O2 source/*.cpp -lmingw32 -lSDL2main -lSDL2 -o bin/$(executable).exe + g++ -std=c++11 -Wall -O2 source/*.cpp source/utils/*.cpp -lmingw32 -lSDL2main -lSDL2 -o bin/$(executable).exe macos: mkdir -p bin g++ source/*.cpp -std=c++11 -Wall -O2 -lSDL2 -o bin/$(executable)_macos diff --git a/source/const.h b/source/const.h index 1fb13bb..d7ccd17 100644 --- a/source/const.h +++ b/source/const.h @@ -2,7 +2,7 @@ #include #include -#include "utils.h" +#include "utils\utils.h" #ifndef CONST_H #define CONST_H diff --git a/source/credits.h b/source/credits.h index d2eb1d5..b5ffd22 100644 --- a/source/credits.h +++ b/source/credits.h @@ -2,12 +2,12 @@ #include #include "const.h" -#include "utils.h" -#include "sprite.h" -#include "screen.h" -#include "asset.h" -#include "text.h" -#include "jail_audio.h" +#include "utils\asset.h" +#include "utils\jail_audio.h" +#include "utils\screen.h" +#include "utils\sprite.h" +#include "utils\text.h" +#include "utils\utils.h" #include #ifndef CREDITS_H diff --git a/source/director.cpp b/source/director.cpp index dcc4fc9..695eb0e 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -1,6 +1,5 @@ - -#include "utils.h" #include "director.h" +#include "utils\utils.h" #include #include diff --git a/source/director.h b/source/director.h index 52d98f7..48847cf 100644 --- a/source/director.h +++ b/source/director.h @@ -1,19 +1,19 @@ #pragma once #include -#include "sprite.h" -#include "movingsprite.h" -#include "text.h" -#include "jail_audio.h" -#include "utils.h" -#include "input.h" +#include "const.h" +#include "credits.h" #include "game.h" +#include "intro.h" #include "logo.h" #include "title.h" -#include "credits.h" -#include "intro.h" -#include "asset.h" -#include "debug.h" -#include "const.h" +#include "utils\asset.h" +#include "utils\debug.h" +#include "utils\input.h" +#include "utils\jail_audio.h" +#include "utils\movingsprite.h" +#include "utils\sprite.h" +#include "utils\text.h" +#include "utils\utils.h" #ifndef DIRECTOR_H #define DIRECTOR_H diff --git a/source/enemy.h b/source/enemy.h index 614d818..25bf8f5 100644 --- a/source/enemy.h +++ b/source/enemy.h @@ -1,8 +1,8 @@ #pragma once #include -#include "utils.h" -#include "asset.h" -#include "animatedsprite.h" +#include "utils\animatedsprite.h" +#include "utils\asset.h" +#include "utils\utils.h" #include #ifndef ENEMY_H diff --git a/source/game.h b/source/game.h index 1c08d6f..8bcabf3 100644 --- a/source/game.h +++ b/source/game.h @@ -1,22 +1,22 @@ #pragma once -#include -#include "utils.h" +#include #include "const.h" -#include "sprite.h" -#include "animatedsprite.h" -#include "text.h" -#include "input.h" -#include "screen.h" -#include "asset.h" -#include "room.h" #include "item_tracker.h" -#include "room_tracker.h" #include "player.h" -#include "jail_audio.h" +#include "room_tracker.h" +#include "room.h" #include "scoreboard.h" -#include "debug.h" #include "test.h" +#include "utils\animatedsprite.h" +#include "utils\asset.h" +#include "utils\debug.h" +#include "utils\input.h" +#include "utils\jail_audio.h" +#include "utils\screen.h" +#include "utils\sprite.h" +#include "utils\text.h" +#include "utils\utils.h" #ifndef GAME_H #define GAME_H diff --git a/source/intro.h b/source/intro.h index 0e571c3..d81af82 100644 --- a/source/intro.h +++ b/source/intro.h @@ -2,15 +2,15 @@ #include #include "const.h" -#include "utils.h" -#include "sprite.h" -#include "screen.h" -#include "asset.h" -#include "jail_audio.h" +#include "utils\asset.h" +#include "utils\jail_audio.h" +#include "utils\screen.h" +#include "utils\sprite.h" +#include "utils\utils.h" #include #include -#include "text.h" +#include "utils\text.h" #ifndef INTRO_H #define INTRO_H diff --git a/source/item.h b/source/item.h index a44035a..7d86698 100644 --- a/source/item.h +++ b/source/item.h @@ -1,8 +1,9 @@ #pragma once + #include -#include "utils.h" -#include "asset.h" -#include "sprite.h" +#include "utils\asset.h" +#include "utils\sprite.h" +#include "utils\utils.h" #include #ifndef ITEM_H diff --git a/source/item_tracker.h b/source/item_tracker.h index 4f94570..6b6dfde 100644 --- a/source/item_tracker.h +++ b/source/item_tracker.h @@ -1,6 +1,6 @@ #pragma once #include -#include "utils.h" +#include "utils\utils.h" #include #include diff --git a/source/logo.h b/source/logo.h index faca962..6646bd8 100644 --- a/source/logo.h +++ b/source/logo.h @@ -2,11 +2,11 @@ #include #include "const.h" -#include "utils.h" -#include "sprite.h" -#include "screen.h" -#include "asset.h" -#include "jail_audio.h" +#include "utils\asset.h" +#include "utils\jail_audio.h" +#include "utils\screen.h" +#include "utils\sprite.h" +#include "utils\utils.h" #include #ifndef LOGO_H diff --git a/source/player.h b/source/player.h index cc67576..b0f9c52 100644 --- a/source/player.h +++ b/source/player.h @@ -1,13 +1,13 @@ #pragma once -#include -#include "utils.h" -#include "asset.h" -#include "room.h" -#include "animatedsprite.h" -#include "input.h" +#include #include "const.h" -#include "debug.h" +#include "room.h" +#include "utils\animatedsprite.h" +#include "utils\asset.h" +#include "utils\debug.h" +#include "utils\input.h" +#include "utils\utils.h" #include #include diff --git a/source/room.h b/source/room.h index 124aeee..eb0cd68 100644 --- a/source/room.h +++ b/source/room.h @@ -1,16 +1,16 @@ #pragma once -#include -#include "utils.h" -#include "asset.h" -#include "screen.h" -#include "enemy.h" -#include "item.h" -#include "sprite.h" -#include "item_tracker.h" +#include #include "const.h" -#include "jail_audio.h" -#include "debug.h" +#include "enemy.h" +#include "item_tracker.h" +#include "item.h" +#include "utils\asset.h" +#include "utils\debug.h" +#include "utils\jail_audio.h" +#include "utils\screen.h" +#include "utils\sprite.h" +#include "utils\utils.h" #include #include diff --git a/source/room_tracker.h b/source/room_tracker.h index fd02993..664164a 100644 --- a/source/room_tracker.h +++ b/source/room_tracker.h @@ -1,6 +1,7 @@ #pragma once + #include -#include "utils.h" +#include "utils\utils.h" #include #include diff --git a/source/scoreboard.h b/source/scoreboard.h index 09a47d2..69a8f3e 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -1,11 +1,11 @@ #pragma once #include -#include "utils.h" -#include "text.h" -#include "asset.h" -#include "animatedsprite.h" #include "const.h" +#include "utils\animatedsprite.h" +#include "utils\asset.h" +#include "utils\text.h" +#include "utils\utils.h" #include #ifndef SCOREBOARD_H diff --git a/source/test.h b/source/test.h index 13cc1d3..e54e105 100644 --- a/source/test.h +++ b/source/test.h @@ -2,13 +2,13 @@ #include #include "const.h" -#include "utils.h" -#include "screen.h" -#include "asset.h" -#include "text.h" -#include "debug.h" -#include +#include "utils\asset.h" +#include "utils\debug.h" +#include "utils\screen.h" +#include "utils\text.h" +#include "utils\utils.h" #include +#include #ifndef TEST_H #define TEST_H diff --git a/source/title.h b/source/title.h index 3804726..99103be 100644 --- a/source/title.h +++ b/source/title.h @@ -2,12 +2,12 @@ #include #include "const.h" -#include "utils.h" -#include "sprite.h" -#include "screen.h" -#include "asset.h" -#include "text.h" -#include "jail_audio.h" +#include "utils\asset.h" +#include "utils\jail_audio.h" +#include "utils\screen.h" +#include "utils\sprite.h" +#include "utils\text.h" +#include "utils\utils.h" #include #ifndef TITLE_H diff --git a/source/animatedsprite.cpp b/source/utils/animatedsprite.cpp similarity index 100% rename from source/animatedsprite.cpp rename to source/utils/animatedsprite.cpp diff --git a/source/animatedsprite.h b/source/utils/animatedsprite.h similarity index 96% rename from source/animatedsprite.h rename to source/utils/animatedsprite.h index 1a32623..f707a37 100644 --- a/source/animatedsprite.h +++ b/source/utils/animatedsprite.h @@ -1,74 +1,74 @@ -#pragma once - -#include -#include "movingsprite.h" -#include -#include -#include -#include - -#ifndef ANIMATEDSPRITE_H -#define ANIMATEDSPRITE_H - -// Clase AnimatedSprite -class AnimatedSprite : public MovingSprite -{ -private: - struct t_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 currentFrame; // Frame actual - int counter; // Contador para las animaciones - }; - std::vector animation; // Vector con las diferentes animaciones - int currentAnimation; // Animacion activa - -public: - // Constructor - AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = ""); - - // Destructor - ~AnimatedSprite(); - - // Calcula el frame correspondiente a la animación actual - void animate(); - - // Establece el frame actual de la animación - void setCurrentFrame(int num); - - // Establece el valor del contador - void setAnimationCounter(std::string name, int num); - - // Establece la velocidad de una animación - void setAnimationSpeed(std::string name, int speed); - - // Establece el frame al que vuelve la animación al finalizar - void setAnimationLoop(std::string name, int loop); - - // Establece el valor de la variable - void setAnimationCompleted(std::string name, bool value); - - // Comprueba si ha terminado la animación - bool animationIsCompleted(); - - // Devuelve el rectangulo de una animación y frame concreto - SDL_Rect getAnimationClip(std::string name, Uint8 index); - - // Obtiene el indice de la animación a partir del nombre - int getIndex(std::string name); - - // Carga la animación desde un fichero - bool load(std::string filePath); - - // Establece la animacion actual - void setCurrentAnimation(std::string name = "default"); - - // Actualiza las variables del objeto - void update(); -}; - +#pragma once + +#include +#include "movingsprite.h" +#include +#include +#include +#include + +#ifndef ANIMATEDSPRITE_H +#define ANIMATEDSPRITE_H + +// Clase AnimatedSprite +class AnimatedSprite : public MovingSprite +{ +private: + struct t_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 currentFrame; // Frame actual + int counter; // Contador para las animaciones + }; + std::vector animation; // Vector con las diferentes animaciones + int currentAnimation; // Animacion activa + +public: + // Constructor + AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = ""); + + // Destructor + ~AnimatedSprite(); + + // Calcula el frame correspondiente a la animación actual + void animate(); + + // Establece el frame actual de la animación + void setCurrentFrame(int num); + + // Establece el valor del contador + void setAnimationCounter(std::string name, int num); + + // Establece la velocidad de una animación + void setAnimationSpeed(std::string name, int speed); + + // Establece el frame al que vuelve la animación al finalizar + void setAnimationLoop(std::string name, int loop); + + // Establece el valor de la variable + void setAnimationCompleted(std::string name, bool value); + + // Comprueba si ha terminado la animación + bool animationIsCompleted(); + + // Devuelve el rectangulo de una animación y frame concreto + SDL_Rect getAnimationClip(std::string name, Uint8 index); + + // Obtiene el indice de la animación a partir del nombre + int getIndex(std::string name); + + // Carga la animación desde un fichero + bool load(std::string filePath); + + // Establece la animacion actual + void setCurrentAnimation(std::string name = "default"); + + // Actualiza las variables del objeto + void update(); +}; + #endif \ No newline at end of file diff --git a/source/asset.cpp b/source/utils/asset.cpp similarity index 100% rename from source/asset.cpp rename to source/utils/asset.cpp diff --git a/source/asset.h b/source/utils/asset.h similarity index 100% rename from source/asset.h rename to source/utils/asset.h diff --git a/source/debug.cpp b/source/utils/debug.cpp similarity index 100% rename from source/debug.cpp rename to source/utils/debug.cpp diff --git a/source/debug.h b/source/utils/debug.h similarity index 98% rename from source/debug.h rename to source/utils/debug.h index c17e623..09de276 100644 --- a/source/debug.h +++ b/source/utils/debug.h @@ -1,13 +1,13 @@ #pragma once #include -#include "const.h" -#include "utils.h" -#include "screen.h" +#include "../const.h" #include "asset.h" +#include "screen.h" #include "text.h" -#include +#include "utils.h" #include +#include #ifndef DEBUG_H #define DEBUG_H diff --git a/source/input.cpp b/source/utils/input.cpp similarity index 100% rename from source/input.cpp rename to source/utils/input.cpp diff --git a/source/input.h b/source/utils/input.h similarity index 96% rename from source/input.h rename to source/utils/input.h index d656ddf..464e084 100644 --- a/source/input.h +++ b/source/utils/input.h @@ -1,90 +1,90 @@ -#pragma once - -#include -#include -#include - -#ifndef INPUT_H -#define INPUT_H - -#define INPUT_NULL 0 -#define INPUT_UP 1 -#define INPUT_DOWN 2 -#define INPUT_LEFT 3 -#define INPUT_RIGHT 4 -#define INPUT_ACCEPT 5 -#define INPUT_CANCEL 6 -#define INPUT_BUTTON_1 7 -#define INPUT_BUTTON_2 8 -#define INPUT_BUTTON_3 9 -#define INPUT_BUTTON_4 10 -#define INPUT_BUTTON_5 11 -#define INPUT_BUTTON_6 12 -#define INPUT_BUTTON_7 13 -#define INPUT_BUTTON_8 14 -#define INPUT_BUTTON_PAUSE 15 -#define INPUT_BUTTON_ESCAPE 16 - -#define REPEAT_TRUE true -#define REPEAT_FALSE false - -#define INPUT_USE_KEYBOARD 0 -#define INPUT_USE_GAMECONTROLLER 1 -#define INPUT_USE_ANY 2 - -// Clase Input -class Input -{ -private: - struct keyBindings_t - { - Uint8 scancode; // Scancode asociado - bool active; // Indica si está activo - }; - - struct GameControllerBindings_t - { - SDL_GameControllerButton button; // GameControllerButton asociado - bool active; // Indica si está activo - }; - - keyBindings_t keyBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos - GameControllerBindings_t gameControllerBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos - std::vector connectedControllers; // Vector con todos los mandos conectados - std::vector controllerNames; // Vector con los nombres de los mandos - int numGamepads; // Numero de mandos conectados - std::string dbPath; // Ruta al archivo gamecontrollerdb.txt - - // Comprueba si hay un mando conectado - bool discoverGameController(); - -public: - // Constructor - Input(std::string file); - - // Destructor - ~Input(); - - // Asigna uno de los posibles inputs a una tecla del teclado - void bindKey(Uint8 input, SDL_Scancode code); - - // Asigna uno de los posibles inputs a un botón del mando - void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button); - - // Comprueba si un input esta activo - bool checkInput(Uint8 input, bool repeat, int device = INPUT_USE_ANY, int index = 0); - - // Comprueba si hay almenos un input activo - bool checkAnyInput(int device = INPUT_USE_ANY, int index = 0); - - // Comprueba si hay algun mando conectado - bool gameControllerFound(); - - // Obten el numero de mandos conectados - int getNumControllers(); - - // Obten el nombre de un mando de juego - std::string getControllerName(int index); -}; - -#endif +#pragma once + +#include +#include +#include + +#ifndef INPUT_H +#define INPUT_H + +#define INPUT_NULL 0 +#define INPUT_UP 1 +#define INPUT_DOWN 2 +#define INPUT_LEFT 3 +#define INPUT_RIGHT 4 +#define INPUT_ACCEPT 5 +#define INPUT_CANCEL 6 +#define INPUT_BUTTON_1 7 +#define INPUT_BUTTON_2 8 +#define INPUT_BUTTON_3 9 +#define INPUT_BUTTON_4 10 +#define INPUT_BUTTON_5 11 +#define INPUT_BUTTON_6 12 +#define INPUT_BUTTON_7 13 +#define INPUT_BUTTON_8 14 +#define INPUT_BUTTON_PAUSE 15 +#define INPUT_BUTTON_ESCAPE 16 + +#define REPEAT_TRUE true +#define REPEAT_FALSE false + +#define INPUT_USE_KEYBOARD 0 +#define INPUT_USE_GAMECONTROLLER 1 +#define INPUT_USE_ANY 2 + +// Clase Input +class Input +{ +private: + struct keyBindings_t + { + Uint8 scancode; // Scancode asociado + bool active; // Indica si está activo + }; + + struct GameControllerBindings_t + { + SDL_GameControllerButton button; // GameControllerButton asociado + bool active; // Indica si está activo + }; + + keyBindings_t keyBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos + GameControllerBindings_t gameControllerBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos + std::vector connectedControllers; // Vector con todos los mandos conectados + std::vector controllerNames; // Vector con los nombres de los mandos + int numGamepads; // Numero de mandos conectados + std::string dbPath; // Ruta al archivo gamecontrollerdb.txt + + // Comprueba si hay un mando conectado + bool discoverGameController(); + +public: + // Constructor + Input(std::string file); + + // Destructor + ~Input(); + + // Asigna uno de los posibles inputs a una tecla del teclado + void bindKey(Uint8 input, SDL_Scancode code); + + // Asigna uno de los posibles inputs a un botón del mando + void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button); + + // Comprueba si un input esta activo + bool checkInput(Uint8 input, bool repeat, int device = INPUT_USE_ANY, int index = 0); + + // Comprueba si hay almenos un input activo + bool checkAnyInput(int device = INPUT_USE_ANY, int index = 0); + + // Comprueba si hay algun mando conectado + bool gameControllerFound(); + + // Obten el numero de mandos conectados + int getNumControllers(); + + // Obten el nombre de un mando de juego + std::string getControllerName(int index); +}; + +#endif diff --git a/source/jail_audio.cpp b/source/utils/jail_audio.cpp similarity index 100% rename from source/jail_audio.cpp rename to source/utils/jail_audio.cpp diff --git a/source/jail_audio.h b/source/utils/jail_audio.h similarity index 100% rename from source/jail_audio.h rename to source/utils/jail_audio.h diff --git a/source/ltexture.cpp b/source/utils/ltexture.cpp similarity index 95% rename from source/ltexture.cpp rename to source/utils/ltexture.cpp index f6afbbb..09b3e1c 100644 --- a/source/ltexture.cpp +++ b/source/utils/ltexture.cpp @@ -1,186 +1,186 @@ - -#include "ltexture.h" -#define STB_IMAGE_IMPLEMENTATION -#include "stb_image.h" - -// Constructor -LTexture::LTexture(SDL_Renderer *renderer, std::string path) -{ - // Copia punteros - this->renderer = renderer; - this->path = path; - - // Inicializa - texture = nullptr; - width = 0; - height = 0; - - // Carga el fichero en la textura - if (path != "") - { - loadFromFile(path, renderer); - } -} - -// Destructor -LTexture::~LTexture() -{ - // Libera memoria - unload(); -} - -// Carga una imagen desde un fichero -bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) -{ - int req_format = STBI_rgb_alpha; - int width, height, orig_format; - unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); - if (data == nullptr) - { - SDL_Log("Loading image failed: %s", stbi_failure_reason()); - exit(1); - } - - int depth, pitch; - Uint32 pixel_format; - if (req_format == STBI_rgb) - { - depth = 24; - pitch = 3 * width; // 3 bytes por pixel * pixels per linea - pixel_format = SDL_PIXELFORMAT_RGB24; - } - else - { // STBI_rgb_alpha (RGBA) - depth = 32; - pitch = 4 * width; - pixel_format = SDL_PIXELFORMAT_RGBA32; - } - - // Limpia - unload(); - - // La textura final - SDL_Texture *newTexture = nullptr; - - // Carga la imagen desde una ruta específica - SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format); - if (loadedSurface == nullptr) - { - printf("Unable to load image %s!\n", path.c_str()); - } - else - { - // Crea la textura desde los pixels de la surface - newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface); - if (newTexture == nullptr) - { - printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); - } - else - { - // Obtiene las dimensiones de la imagen - this->width = loadedSurface->w; - this->height = loadedSurface->h; - } - - // Elimina la textura cargada - SDL_FreeSurface(loadedSurface); - } - - // Return success - texture = newTexture; - return texture != nullptr; -} - -// Crea una textura en blanco -bool LTexture::createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess access) -{ - // Crea una textura sin inicializar - texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, access, width, height); - if (texture == nullptr) - { - printf("Unable to create blank texture! SDL Error: %s\n", SDL_GetError()); - } - else - { - this->width = width; - this->height = height; - } - - return texture != nullptr; -} - -// Libera la memoria de la textura -void LTexture::unload() -{ - // Libera la textura si existe - if (texture != nullptr) - { - SDL_DestroyTexture(texture); - texture = nullptr; - width = 0; - height = 0; - } -} - -// Establece el color para la modulacion -void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue) -{ - SDL_SetTextureColorMod(texture, red, green, blue); -} - -// Establece el blending -void LTexture::setBlendMode(SDL_BlendMode blending) -{ - SDL_SetTextureBlendMode(texture, blending); -} - -// Establece el alpha para la modulación -void LTexture::setAlpha(Uint8 alpha) -{ - SDL_SetTextureAlphaMod(texture, alpha); -} - -// Renderiza la textura en un punto específico -void LTexture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) -{ - // Establece el destini de renderizado en la pantalla - SDL_Rect renderQuad = {x, y, width, height}; - - // Obtiene las dimesiones del clip de renderizado - if (clip != nullptr) - { - renderQuad.w = clip->w; - renderQuad.h = clip->h; - } - - renderQuad.w = renderQuad.w * zoomW; - renderQuad.h = renderQuad.h * zoomH; - - // Renderiza a pantalla - SDL_RenderCopyEx(renderer, texture, clip, &renderQuad, angle, center, flip); -} - -// Establece la textura como objetivo de renderizado -void LTexture::setAsRenderTarget(SDL_Renderer *renderer) -{ - SDL_SetRenderTarget(renderer, texture); -} - -// Obtiene el ancho de la imagen -int LTexture::getWidth() -{ - return width; -} - -// Obtiene el alto de la imagen -int LTexture::getHeight() -{ - return height; -} - -// Recarga la textura -bool LTexture::reLoad() -{ - return loadFromFile(path, renderer); + +#include "ltexture.h" +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +// Constructor +LTexture::LTexture(SDL_Renderer *renderer, std::string path) +{ + // Copia punteros + this->renderer = renderer; + this->path = path; + + // Inicializa + texture = nullptr; + width = 0; + height = 0; + + // Carga el fichero en la textura + if (path != "") + { + loadFromFile(path, renderer); + } +} + +// Destructor +LTexture::~LTexture() +{ + // Libera memoria + unload(); +} + +// Carga una imagen desde un fichero +bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) +{ + int req_format = STBI_rgb_alpha; + int width, height, orig_format; + unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); + if (data == nullptr) + { + SDL_Log("Loading image failed: %s", stbi_failure_reason()); + exit(1); + } + + int depth, pitch; + Uint32 pixel_format; + if (req_format == STBI_rgb) + { + depth = 24; + pitch = 3 * width; // 3 bytes por pixel * pixels per linea + pixel_format = SDL_PIXELFORMAT_RGB24; + } + else + { // STBI_rgb_alpha (RGBA) + depth = 32; + pitch = 4 * width; + pixel_format = SDL_PIXELFORMAT_RGBA32; + } + + // Limpia + unload(); + + // La textura final + SDL_Texture *newTexture = nullptr; + + // Carga la imagen desde una ruta específica + SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format); + if (loadedSurface == nullptr) + { + printf("Unable to load image %s!\n", path.c_str()); + } + else + { + // Crea la textura desde los pixels de la surface + newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface); + if (newTexture == nullptr) + { + printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); + } + else + { + // Obtiene las dimensiones de la imagen + this->width = loadedSurface->w; + this->height = loadedSurface->h; + } + + // Elimina la textura cargada + SDL_FreeSurface(loadedSurface); + } + + // Return success + texture = newTexture; + return texture != nullptr; +} + +// Crea una textura en blanco +bool LTexture::createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess access) +{ + // Crea una textura sin inicializar + texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, access, width, height); + if (texture == nullptr) + { + printf("Unable to create blank texture! SDL Error: %s\n", SDL_GetError()); + } + else + { + this->width = width; + this->height = height; + } + + return texture != nullptr; +} + +// Libera la memoria de la textura +void LTexture::unload() +{ + // Libera la textura si existe + if (texture != nullptr) + { + SDL_DestroyTexture(texture); + texture = nullptr; + width = 0; + height = 0; + } +} + +// Establece el color para la modulacion +void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue) +{ + SDL_SetTextureColorMod(texture, red, green, blue); +} + +// Establece el blending +void LTexture::setBlendMode(SDL_BlendMode blending) +{ + SDL_SetTextureBlendMode(texture, blending); +} + +// Establece el alpha para la modulación +void LTexture::setAlpha(Uint8 alpha) +{ + SDL_SetTextureAlphaMod(texture, alpha); +} + +// Renderiza la textura en un punto específico +void LTexture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) +{ + // Establece el destini de renderizado en la pantalla + SDL_Rect renderQuad = {x, y, width, height}; + + // Obtiene las dimesiones del clip de renderizado + if (clip != nullptr) + { + renderQuad.w = clip->w; + renderQuad.h = clip->h; + } + + renderQuad.w = renderQuad.w * zoomW; + renderQuad.h = renderQuad.h * zoomH; + + // Renderiza a pantalla + SDL_RenderCopyEx(renderer, texture, clip, &renderQuad, angle, center, flip); +} + +// Establece la textura como objetivo de renderizado +void LTexture::setAsRenderTarget(SDL_Renderer *renderer) +{ + SDL_SetRenderTarget(renderer, texture); +} + +// Obtiene el ancho de la imagen +int LTexture::getWidth() +{ + return width; +} + +// Obtiene el alto de la imagen +int LTexture::getHeight() +{ + return height; +} + +// Recarga la textura +bool LTexture::reLoad() +{ + return loadFromFile(path, renderer); } \ No newline at end of file diff --git a/source/ltexture.h b/source/utils/ltexture.h similarity index 96% rename from source/ltexture.h rename to source/utils/ltexture.h index 2272f94..cb065ce 100644 --- a/source/ltexture.h +++ b/source/utils/ltexture.h @@ -1,61 +1,61 @@ -#pragma once - -#include -#include -#include - -#ifndef LTEXTURE_H -#define LTEXTURE_H - -// Clase LTexture -class LTexture -{ -private: - SDL_Texture *texture; // La textura - SDL_Renderer *renderer; // Renderizador donde dibujar la textura - int width; // Ancho de la imagen - int height; // Alto de la imagen - std::string path; // Ruta de la imagen de la textura - -public: - // Constructor - LTexture(SDL_Renderer *renderer, std::string path = ""); - - // Destructor - ~LTexture(); - - // Carga una imagen desde un fichero - bool loadFromFile(std::string path, SDL_Renderer *renderer); - - // Crea una textura en blanco - bool createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); - - // Libera la memoria de la textura - void unload(); - - // Establece el color para la modulacion - void setColor(Uint8 red, Uint8 green, Uint8 blue); - - // Establece el blending - void setBlendMode(SDL_BlendMode blending); - - // Establece el alpha para la modulación - void setAlpha(Uint8 alpha); - - // Renderiza la textura en un punto específico - void render(SDL_Renderer *renderer, 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); - - // Establece la textura como objetivo de renderizado - void setAsRenderTarget(SDL_Renderer *renderer); - - // Obtiene el ancho de la imagen - int getWidth(); - - // Obtiene el alto de la imagen - int getHeight(); - - // Recarga la textura - bool reLoad(); -}; - -#endif +#pragma once + +#include +#include +#include + +#ifndef LTEXTURE_H +#define LTEXTURE_H + +// Clase LTexture +class LTexture +{ +private: + SDL_Texture *texture; // La textura + SDL_Renderer *renderer; // Renderizador donde dibujar la textura + int width; // Ancho de la imagen + int height; // Alto de la imagen + std::string path; // Ruta de la imagen de la textura + +public: + // Constructor + LTexture(SDL_Renderer *renderer, std::string path = ""); + + // Destructor + ~LTexture(); + + // Carga una imagen desde un fichero + bool loadFromFile(std::string path, SDL_Renderer *renderer); + + // Crea una textura en blanco + bool createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); + + // Libera la memoria de la textura + void unload(); + + // Establece el color para la modulacion + void setColor(Uint8 red, Uint8 green, Uint8 blue); + + // Establece el blending + void setBlendMode(SDL_BlendMode blending); + + // Establece el alpha para la modulación + void setAlpha(Uint8 alpha); + + // Renderiza la textura en un punto específico + void render(SDL_Renderer *renderer, 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); + + // Establece la textura como objetivo de renderizado + void setAsRenderTarget(SDL_Renderer *renderer); + + // Obtiene el ancho de la imagen + int getWidth(); + + // Obtiene el alto de la imagen + int getHeight(); + + // Recarga la textura + bool reLoad(); +}; + +#endif diff --git a/source/utils/menu.cpp b/source/utils/menu.cpp new file mode 100644 index 0000000..a2a5df2 --- /dev/null +++ b/source/utils/menu.cpp @@ -0,0 +1,890 @@ +#include "../const.h" +#include "menu.h" + +// Constructor +Menu::Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file) +{ + this->renderer = renderer; + this->asset = asset; + this->input = input; + + soundMove = nullptr; + soundAccept = nullptr; + soundCancel = nullptr; + + init(); + if (file != "") + { + load(file); + } + reorganize(); +} + +Menu::~Menu() +{ + renderer = nullptr; + asset = nullptr; + input = nullptr; + + if (soundMove) + { + JA_DeleteSound(soundMove); + } + + if (soundAccept) + { + JA_DeleteSound(soundAccept); + } + + if (soundCancel) + { + JA_DeleteSound(soundCancel); + } + + if (text != nullptr) + { + delete text; + } +} + +// Carga la configuración del menu desde un archivo de texto +bool Menu::load(std::string file_path) +{ + // Indicador de éxito en la carga + bool success = true; + + // Indica si se ha creado ya el objeto de texto + bool textAllocated = false; + + std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); + std::string line; + std::ifstream file(file_path); + + // El fichero se puede abrir + if (file.good()) + { + // Procesa el fichero linea a linea + printf("Reading file %s\n", filename.c_str()); + while (std::getline(file, line)) + { + if (line == "[item]") + { + item_t item; + item.label = ""; + item.hPaddingDown = 1; + item.selectable = true; + item.greyed = false; + item.linkedDown = false; + + do + { + + std::getline(file, line); + + // Encuentra la posición del caracter '=' + int pos = line.find("="); + + // Procesa las dos subcadenas + if (!setItem(&item, line.substr(0, pos), line.substr(pos + 1, line.length()))) + { + printf("Warning: file %s\n, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); + success = false; + } + + } while (line != "[/item]"); + + addItem(item.label, item.hPaddingDown, item.selectable, item.greyed, item.linkedDown); + } + + // En caso contrario se parsea el fichero para buscar las variables y los valores + else + { + // Encuentra la posición del caracter '=' + int pos = line.find("="); + // Procesa las dos subcadenas + if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) + { + printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); + success = false; + } + + // Crea el objeto text tan pronto como se pueda. Necesario para añadir items + if (font_png != "" && font_txt != "" && !textAllocated) + { + text = new Text(asset->get(font_png), asset->get(font_txt), renderer); + textAllocated = true; + } + } + } + + // Cierra el fichero + printf("Closing file %s\n\n", filename.c_str()); + file.close(); + } + // El fichero no se puede abrir + else + { + printf("Warning: Unable to open %s file\n", filename.c_str()); + success = false; + } + + return success; +} + +// Asigna variables a partir de dos cadenas +bool Menu::setItem(item_t *item, std::string var, std::string value) +{ + // Indicador de éxito en la asignación + bool success = true; + + if (var == "text") + { + item->label = value; + } + + else if (var == "hPaddingDown") + { + item->hPaddingDown = std::stoi(value); + } + + else if (var == "selectable") + { + item->selectable = value == "true" ? true : false; + } + + else if (var == "greyed") + { + item->greyed = value == "true" ? true : false; + } + + else if (var == "linkedDown") + { + item->linkedDown = value == "true" ? true : false; + } + + else if ((var == "") || (var == "[/item]")) + { + } + else + { + success = false; + } + + return success; +} + +// Asigna variables a partir de dos cadenas +bool Menu::setVars(std::string var, std::string value) +{ + // Indicador de éxito en la asignación + bool success = true; + + if (var == "font_png") + { + font_png = value; + } + + else if (var == "font_txt") + { + font_txt = value; + } + + else if (var == "sound_cancel") + { + soundCancel = JA_LoadSound(asset->get(value).c_str()); + } + + else if (var == "sound_accept") + { + soundAccept = JA_LoadSound(asset->get(value).c_str()); + } + + else if (var == "sound_move") + { + soundMove = JA_LoadSound(asset->get(value).c_str()); + } + + else if (var == "name") + { + name = value; + } + + else if (var == "x") + { + x = std::stoi(value); + } + + else if (var == "centerX") + { + centerX = std::stoi(value); + } + + else if (var == "centerY") + { + centerY = std::stoi(value); + } + + else if (var == "y") + { + y = std::stoi(value); + } + + else if (var == "backgroundType") + { + backgroundType = std::stoi(value); + } + + else if (var == "backgroundColor") + { + // Se introducen los valores separados por comas en un vector + std::stringstream ss(value); + std::string tmp; + getline(ss, tmp, ','); + rectBG.color.r = std::stoi(tmp); + getline(ss, tmp, ','); + rectBG.color.g = std::stoi(tmp); + getline(ss, tmp, ','); + rectBG.color.b = std::stoi(tmp); + getline(ss, tmp, ','); + rectBG.a = std::stoi(tmp); + } + + else if (var == "selector_color") + { + // Se introducen los valores separados por comas en un vector + std::stringstream ss(value); + std::string tmp; + getline(ss, tmp, ','); + selector.color.r = std::stoi(tmp); + getline(ss, tmp, ','); + selector.color.g = std::stoi(tmp); + getline(ss, tmp, ','); + selector.color.b = std::stoi(tmp); + getline(ss, tmp, ','); + selector.a = std::stoi(tmp); + } + + else if (var == "selector_text_color") + { + // Se introducen los valores separados por comas en un vector + std::stringstream ss(value); + std::string tmp; + getline(ss, tmp, ','); + selector.itemColor.r = std::stoi(tmp); + getline(ss, tmp, ','); + selector.itemColor.g = std::stoi(tmp); + getline(ss, tmp, ','); + selector.itemColor.b = std::stoi(tmp); + } + + else if (var == "areElementsCenteredOnX") + { + areElementsCenteredOnX = value == "true" ? true : false; + } + + else if (var == "isCenteredOnX") + { + isCenteredOnX = value == "true" ? true : false; + } + + else if (var == "isCenteredOnY") + { + isCenteredOnY = value == "true" ? true : false; + } + + else if (var == "defaultActionWhenCancel") + { + defaultActionWhenCancel = std::stoi(value); + } + + else if (var == "") + { + } + + else + { + success = false; + } + + return success; +} + +// Inicializa las variables +void Menu::init() +{ + // Inicia variables + name = ""; + selector.index = 0; + itemSelected = MENU_NO_OPTION; + x = 0; + y = 0; + rectBG.rect = {0, 0, 0, 0}; + rectBG.color = {0, 0, 0}; + rectBG.a = 0; + backgroundType = MENU_BACKGROUND_SOLID; + isCenteredOnX = false; + isCenteredOnY = false; + areElementsCenteredOnX = false; + centerX = 0; + centerY = 0; + widestItem = 0; + colorGreyed = {128, 128, 128}; + defaultActionWhenCancel = 0; + font_png = ""; + font_txt = ""; + + // Selector + selector.originY = 0; + selector.targetY = 0; + selector.despY = 0; + selector.originH = 0; + selector.targetH = 0; + selector.incH = 0; + selector.y = 0.0f; + selector.h = 0.0f; + selector.numJumps = 8; + selector.moving = false; + selector.resizing = false; + selector.rect = {0, 0, 0, 0}; + selector.color = {0, 0, 0}; + selector.itemColor = {0, 0, 0}; + selector.a = 255; +} + +// Carga los ficheros de audio +void Menu::loadAudioFile(std::string file, int sound) +{ + switch (sound) + { + case SOUND_ACCEPT: + soundAccept = JA_LoadSound(file.c_str()); + break; + + case SOUND_CANCEL: + soundCancel = JA_LoadSound(file.c_str()); + break; + + case SOUND_MOVE: + soundMove = JA_LoadSound(file.c_str()); + break; + + default: + break; + } +} + +// Obtiene el nombre del menu +std::string Menu::getName() +{ + return name; +} + +// Obtiene el valor de la variable +int Menu::getItemSelected() +{ + // Al llamar a esta funcion, se obtiene el valor y se borra + const int temp = itemSelected; + itemSelected = MENU_NO_OPTION; + return temp; +} + +// Actualiza la posicion y el estado del selector +void Menu::updateSelector() +{ + if (selector.moving) + { + // Calcula el desplazamiento en Y + selector.y += selector.despY; + if (selector.despY > 0) // Va hacia abajo + { + if (selector.y > selector.targetY) // Ha llegado al destino + { + selector.originY = selector.y = selector.targetY; + selector.moving = false; + } + } + if (selector.despY < 0) // Va hacia arriba + { + if (selector.y < selector.targetY) // Ha llegado al destino + { + selector.originY = selector.y = selector.targetY; + selector.moving = false; + } + } + selector.rect.y = int(selector.y); + } + else + { + selector.rect.y = int(selector.y); + } + + if (selector.resizing) + { + // Calcula el incremento en H + selector.h += selector.incH; + if (selector.incH > 0) // Crece + { + if (selector.h > selector.targetH) // Ha llegado al destino + { + // selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); + selector.originH = selector.h = selector.targetH; + selector.resizing = false; + } + } + if (selector.incH < 0) // Decrece + { + if (selector.h < selector.targetH) // Ha llegado al destino + { + // selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); + selector.originH = selector.h = selector.targetH; + selector.resizing = false; + } + } + selector.rect.h = int(selector.h); + } + else + { + selector.rect.h = getSelectorHeight(selector.index); + } +} + +// Coloca el selector en una posición específica +void Menu::setSelectorPos(int index) +{ + if (index < (int)item.size()) + { + selector.index = index; + selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y; + selector.rect.w = rectBG.rect.w; + selector.rect.x = rectBG.rect.x; + selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); + selector.moving = false; + selector.resizing = false; + } +} + +// Obtiene la anchura del elemento más ancho del menu +int Menu::getWidestItem() +{ + int result = 0; + + // Obtenemos la anchura del item mas ancho + for (auto &i : item) + { + result = std::max(result, i.rect.w); + } + + return result; +} + +// Deja el menu apuntando al primer elemento +void Menu::reset() +{ + itemSelected = MENU_NO_OPTION; + selector.index = 0; + selector.originY = selector.targetY = selector.y = item[0].rect.y; + selector.originH = selector.targetH = item[0].rect.h; + selector.moving = false; + selector.resizing = false; +} + +// Actualiza el menu para recolocarlo correctamente y establecer el tamaño +void Menu::reorganize() +{ + setRectSize(); + + if (isCenteredOnX) + { + centerMenuOnX(centerX); + } + + if (isCenteredOnY) + { + centerMenuOnY(centerY); + } + + if (areElementsCenteredOnX) + { + centerMenuElementsOnX(); + } +} + +// Deja el menu apuntando al siguiente elemento +bool Menu::increaseSelectorIndex() +{ + // Obten las coordenadas del elemento actual + selector.y = selector.originY = item[selector.index].rect.y; + selector.h = selector.originH = getSelectorHeight(selector.index); + + // Calcula cual es el siguiente elemento + ++selector.index %= item.size(); + while (!item[selector.index].selectable) + { + ++selector.index %= item.size(); + } + + // Establece las coordenadas y altura de destino + selector.targetY = item[selector.index].rect.y; + selector.despY = (selector.targetY - selector.originY) / selector.numJumps; + + selector.targetH = getSelectorHeight(selector.index); + selector.incH = (selector.targetH - selector.originH) / selector.numJumps; + + selector.moving = true; + if (selector.incH != 0) + { + selector.resizing = true; + } + + return true; +} + +// Deja el menu apuntando al elemento anterior +bool Menu::decreaseSelectorIndex() +{ + // Obten las coordenadas del elemento actual + selector.y = selector.originY = item[selector.index].rect.y; + selector.h = selector.originH = getSelectorHeight(selector.index); + + // Calcula cual es el siguiente elemento + if (selector.index == 0) + { + selector.index = item.size(); + } + else + { + selector.index--; + } + + while (!item[selector.index].selectable) + { + if (selector.index == 0) + { + selector.index = item.size(); + } + else + { + selector.index--; + } + } + + // Establece las coordenadas y altura de destino + selector.targetY = item[selector.index].rect.y; + selector.despY = (selector.targetY - selector.originY) / selector.numJumps; + + selector.targetH = getSelectorHeight(selector.index); + selector.incH = (selector.targetH - selector.originH) / selector.numJumps; + + selector.moving = true; + if (selector.incH != 0) + { + selector.resizing = true; + } + + return true; +} + +// Actualiza la logica del menu +void Menu::update() +{ + checkInput(); + updateSelector(); +} + +// Pinta el menu en pantalla +void Menu::render() +{ + // Rendereritza el fondo del menu + if (backgroundType == MENU_BACKGROUND_SOLID) + { + SDL_SetRenderDrawColor(renderer, rectBG.color.r, rectBG.color.g, rectBG.color.b, rectBG.a); + SDL_RenderFillRect(renderer, &rectBG.rect); + } + + // Renderiza el rectangulo del selector + const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1}; + // temp.y--; + // temp.h++; + SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a); + SDL_RenderFillRect(renderer, &temp); + + // Renderiza el borde del fondo + if (backgroundType == MENU_BACKGROUND_SOLID) + { + SDL_SetRenderDrawColor(renderer, rectBG.color.r, rectBG.color.g, rectBG.color.b, 255); + SDL_RenderDrawRect(renderer, &rectBG.rect); + } + + // Renderiza el texto + for (int i = 0; i < (int)item.size(); ++i) + { + if (i == selector.index) + { + const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b}; + text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color); + } + else if (item[i].selectable) + { + text->write(item[i].rect.x, item[i].rect.y, item[i].label); + } + else if (item[i].greyed) + { + text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed); + } + else + // No seleccionable + { + if ((item[i].linkedUp) && (i == selector.index + 1)) + { + const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b}; + text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color); + } + else // No enlazado con el de arriba + { + text->write(item[i].rect.x, item[i].rect.y, item[i].label); + } + } + } +} + +// Establece el rectangulo de fondo del menu y el selector +void Menu::setRectSize() +{ + rectBG.rect.w = findWidth() + text->getCharacterSize(); + rectBG.rect.h = findHeight() + text->getCharacterSize(); + + // La posición X es la del menú menos medio caracter + rectBG.rect.x = x - (text->getCharacterSize() / 2); + + // La posición Y es la del menu menos la altura de medio caracter + rectBG.rect.y = y - (text->getCharacterSize() / 2); + + // Establecemos los valores del rectangulo del selector a partir de los valores del rectangulo de fondo + setSelectorPos(selector.index); +} + +// Establece el color del rectangulo de fondo +void Menu::setBackgroundColor(color_t color, int alpha) +{ + rectBG.color = color; + rectBG.a = alpha; +} + +// Establece el color del rectangulo del selector +void Menu::setSelectorColor(color_t color, int alpha) +{ + selector.color = color; + selector.a = alpha; +} + +// Establece el color del texto del selector +void Menu::setSelectorTextColor(color_t color) +{ + selector.itemColor = color; +} + +// Centra el menu respecto un punto en el eje X +void Menu::centerMenuOnX(int value) +{ + isCenteredOnX = true; + centerX = value; + + // Establece la nueva posición centrada en funcion del elemento más ancho + x = (value) - (findWidth() / 2); + + // Reposiciona los elementos del menu + for (auto &i : item) + { + i.rect.x = x; + } + + // Recalcula el rectangulo de fondo + setRectSize(); +} + +// Centra el menu respecto un punto en el eje Y +void Menu::centerMenuOnY(int value) +{ + isCenteredOnY = true; + centerY = value; + + // Establece la nueva posición centrada en funcion del elemento más ancho + y = (value) - (findHeight() / 2); + + // Reposiciona los elementos del menu + replaceElementsOnY(); + + // Recalcula el rectangulo de fondo + setRectSize(); +} + +// Centra los elementos del menu en el eje X +void Menu::centerMenuElementsOnX() +{ + areElementsCenteredOnX = true; + + for (auto &i : item) + { + i.rect.x = (centerX - (i.rect.w / 2)); + } +} + +// Añade un item al menu +void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool greyed, bool linkedDown) +{ + item_t temp; + // Si es el primer item coge la posición en el eje Y del propio menu + if (item.size() == 0) + { + temp.rect.y = y; + } + else + // En caso contrario, coge la posición en el eje Y a partir del elemento anterior + { + temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown; + } + + temp.rect.x = x; + temp.hPaddingDown = hPaddingDown; + temp.selectable = selectable; + temp.greyed = greyed; + temp.linkedDown = linkedDown; + + item.push_back(temp); + setItemCaption(item.size() - 1, text); + + if (item.size() > 0) + { + if (item[item.size() - 1].linkedDown) + { + item[item.size()].linkedUp = true; + } + } + + centerX = x + (findWidth() / 2); + reorganize(); +} + +// Cambia el texto de un item +void Menu::setItemCaption(int index, std::string text) +{ + item[index].label = text; + item[index].rect.w = this->text->lenght(item[index].label); + item[index].rect.h = this->text->getCharacterSize(); + reorganize(); + + const std::string texto = item[index].label + ":" + std::to_string(item[index].rect.w); + printf("Adding menu item -> %s\n", texto.c_str()); +} + +// Establece el indice del itemm que se usará por defecto al cancelar el menu +void Menu::setDefaultActionWhenCancel(int item) +{ + defaultActionWhenCancel = item; +} + +// Gestiona la entrada de teclado y mando durante el menu +void Menu::checkInput() +{ + if (input->checkInput(INPUT_UP, REPEAT_FALSE)) + { + if (decreaseSelectorIndex()) + { + if (soundMove) + { + JA_PlaySound(soundMove); + } + } + } + + if (input->checkInput(INPUT_DOWN, REPEAT_FALSE)) + { + if (increaseSelectorIndex()) + { + if (soundMove) + { + JA_PlaySound(soundMove); + } + } + } + + if (input->checkInput(INPUT_ACCEPT, REPEAT_FALSE)) + { + itemSelected = selector.index; + if (soundAccept) + { + JA_PlaySound(soundAccept); + } + } + + if (input->checkInput(INPUT_CANCEL, REPEAT_FALSE)) + { + itemSelected = defaultActionWhenCancel; + if (soundCancel) + { + JA_PlaySound(soundCancel); + } + } +} + +// Calcula el ancho del menu +int Menu::findWidth() +{ + return getWidestItem(); +} + +// Calcula el alto del menu +int Menu::findHeight() +{ + int height = 0; + + // Obtenemos la altura de la suma de alturas de los items + for (auto &i : item) + { + height += i.rect.h + i.hPaddingDown; + } + + return height - item.back().hPaddingDown; +} + +// Recoloca los elementos del menu en el eje Y +void Menu::replaceElementsOnY() +{ + item[0].rect.y = y; + + for (int i = 1; i < (int)item.size(); i++) + { + item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown; + } +} + +// Establece el estado seleccionable de un item +void Menu::setSelectable(int index, bool value) +{ + item[index].selectable = value; +} + +// Establece el estado agrisado de un item +void Menu::setGreyed(int index, bool value) +{ + item[index].greyed = value; +} + +// Establece el estado de enlace de un item +void Menu::setLinkedDown(int index, bool value) +{ + item[index].linkedDown = value; +} + +// Calcula la altura del selector +int Menu::getSelectorHeight(int value) +{ + if (item[value].linkedDown) + { + return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h; + } + else + { + return item[value].rect.h; + } +} \ No newline at end of file diff --git a/source/utils/menu.h b/source/utils/menu.h new file mode 100644 index 0000000..d3fb7fa --- /dev/null +++ b/source/utils/menu.h @@ -0,0 +1,214 @@ +#pragma once + +#include +#include "asset.h" +#include "input.h" +#include "jail_audio.h" +#include "sprite.h" +#include "text.h" +#include "utils.h" +#include +#include +#include + +#ifndef MENU_H +#define MENU_H + +// Tipos de fondos para el menu +#define MENU_BACKGROUND_TRANSPARENT 0 +#define MENU_BACKGROUND_SOLID 1 + +// Tipos de archivos de audio +#define SOUND_ACCEPT 0 +#define SOUND_MOVE 1 +#define SOUND_CANCEL 2 + +// Opciones de menu +#define MENU_NO_OPTION -1 + +// Clase Menu +class Menu +{ +private: + struct rectangle_t + { + SDL_Rect rect; // Rectangulo + color_t color; // Color + int a; // Transparencia + }; + + struct item_t + { + std::string label; // Texto + SDL_Rect rect; // Rectangulo que delimita el elemento + int hPaddingDown; // Espaciado bajo el elemento + bool selectable; // Indica si se puede seleccionar + bool greyed; // Indica si ha de aparecer con otro color mas oscuro + bool linkedDown; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector + bool linkedUp; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector + }; + + struct selector_t + { + float originY; // Coordenada de origen + float targetY; // Coordenada de destino + float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps + bool moving; // Indica si el selector está avanzando hacia el destino + float originH; // Altura de origen + float targetH; // Altura de destino + float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto + bool resizing; // Indica si el selector está cambiando de tamaño + float y; // Coordenada actual, usado para el desplazamiento + float h; // Altura actual, usado para el cambio de tamaño + int numJumps; // Numero de pasos preestablecido para llegar al destino + int index; // Elemento del menu que tiene el foco + SDL_Rect rect; // Rectangulo del selector + color_t color; // Color del selector + color_t itemColor; // Color del item + int a; // Cantidad de transparencia para el rectangulo del selector + }; + + std::string name; // Nombre del menu + int x; // Posición en el eje X de la primera letra del primer elemento + int y; // Posición en el eje Y de la primera letra del primer elemento + int h; // Altura del menu + int w; // Anchura del menu + int itemSelected; // Índice del item del menu que ha sido seleccionado + int defaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu + int backgroundType; // Tipo de fondo para el menu + int centerX; // Centro del menu en el eje X + int centerY; // Centro del menu en el eje Y + bool isCenteredOnX; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje X + bool isCenteredOnY; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje Y + bool areElementsCenteredOnX; // Variable para saber si los elementos van centrados en el eje X + int widestItem; // Anchura del elemento más ancho + JA_Sound soundAccept; // Sonido al aceptar o elegir una opción del menu + JA_Sound soundCancel; // Sonido al cancelar el menu + JA_Sound soundMove; // Sonido al mover el selector + SDL_Renderer *renderer; // Puntero al renderizador de la ventana + Text *text; // Texto para poder escribir los items del menu + Input *input; // Gestor de eventos de entrada de teclado o gamepad + Asset *asset; // Objeto para gestionar los ficheros de recursos + color_t colorGreyed; // Color para los elementos agrisados + rectangle_t rectBG; // Rectangulo de fondo del menu + std::vector item; // Estructura para cada elemento del menu + selector_t selector; // Variables para pintar el selector del menu + std::string font_png; + std::string font_txt; + + // Carga la configuración del menu desde un archivo de texto + bool load(std::string file_path); + + // Asigna variables a partir de dos cadenas + bool setVars(std::string var, std::string value); + + // Asigna variables a partir de dos cadenas + bool setItem(item_t *item, std::string var, std::string value); + + // Inicializa las variables + void init(); + + // Establece el rectangulo de fondo del menu + void setRectSize(); + + // Actualiza el menu para recolocarlo correctamente y establecer el tamaño + void reorganize(); + + // Deja el menu apuntando al siguiente elemento + bool increaseSelectorIndex(); + + // Deja el menu apuntando al elemento anterior + bool decreaseSelectorIndex(); + + // Actualiza la posicion y el estado del selector + void updateSelector(); + + // Obtiene la anchura del elemento más ancho del menu + int getWidestItem(); + + // Gestiona la entrada de teclado y mando durante el menu + void checkMenuInput(Menu *menu); + + // Calcula el ancho del menu + int findWidth(); + + // Calcula el alto del menu + int findHeight(); + + // Recoloca los elementos del menu en el eje Y + void replaceElementsOnY(); + + // Calcula la altura del selector + int getSelectorHeight(int value); + +public: + // Constructor + Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file=""); + + // Destructor + ~Menu(); + + // Carga los ficheros de audio + void loadAudioFile(std::string file, int sound); + + // Obtiene el nombre del menu + std::string getName(); + + // Obtiene el valor de la variable + int getItemSelected(); + + // Deja el menu apuntando al primer elemento + void reset(); + + // Gestiona la entrada de teclado y mando durante el menu + void checkInput(); + + // Actualiza la logica del menu + void update(); + + // Pinta el menu en pantalla + void render(); + + // Establece el color del rectangulo de fondo + void setBackgroundColor(color_t color, int alpha); + + // Establece el color del rectangulo del selector + void setSelectorColor(color_t color, int alpha); + + // Establece el color del texto del selector + void setSelectorTextColor(color_t color); + + // Centra el menu respecto a un punto en el eje X + void centerMenuOnX(int value); + + // Centra el menu respecto a un punto en el eje Y + void centerMenuOnY(int value); + + // Centra los elementos del menu en el eje X + void centerMenuElementsOnX(); + + // Añade un item al menu + void addItem(std::string text, int hPaddingDown = 1, bool selectable = true, bool greyed = false, bool linkedDown = false); + + // Cambia el texto de un item + void setItemCaption(int index, std::string text); + + // Establece el indice del item que se usará por defecto al cancelar el menu + void setDefaultActionWhenCancel(int item); + + // Coloca el selector en una posición específica + void setSelectorPos(int index); + + // Establece el estado seleccionable de un item + void setSelectable(int index, bool value); + + // Establece el estado agrisado de un item + void setGreyed(int index, bool value); + + // Establece el estado de enlace de un item + void setLinkedDown(int index, bool value); + + // hacer procedimientos para establecer el titulo, la x, la y, la tipografia y el tipo de fondo +}; + +#endif diff --git a/source/movingsprite.cpp b/source/utils/movingsprite.cpp similarity index 100% rename from source/movingsprite.cpp rename to source/utils/movingsprite.cpp diff --git a/source/movingsprite.h b/source/utils/movingsprite.h similarity index 96% rename from source/movingsprite.h rename to source/utils/movingsprite.h index aeedcab..9da69a3 100644 --- a/source/movingsprite.h +++ b/source/utils/movingsprite.h @@ -1,173 +1,173 @@ -#pragma once - -#include -#include "sprite.h" - -#ifndef MOVINGSPRITE_H -#define MOVINGSPRITE_H - -// Clase MovingSprite. Añade posicion y velocidad en punto flotante -class MovingSprite : public Sprite -{ -protected: - float x; // Posición en el eje X - float y; // Posición en el eje Y - - float xPrev; // Posición anterior en el eje X - float yPrev; // Posición anterior en el eje Y - - float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - - float ax; // Aceleración en el eje X. Variación de la velocidad - float ay; // Aceleración en el eje Y. Variación de la velocidad - - float zoomW; // Zoom aplicado a la anchura - float zoomH; // Zoom aplicado a la altura - - double angle; // Angulo para dibujarlo - bool rotateEnabled; // Indica si ha de rotar - int rotateSpeed; // Velocidad de giro - double rotateAmount; // Cantidad de grados a girar en cada iteración - int counter; // Contador interno - SDL_Point center; // Centro de rotación - SDL_RendererFlip currentFlip; // Indica como se voltea el sprite - -public: - // Constructor - MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); - - // Destructor - ~MovingSprite(); - - // Mueve el sprite - void move(); - - // Rota el sprite - void rotate(); - - // Actualiza las variables internas del objeto - void update(); - - // Reinicia todas las variables - void clear(); - - // Muestra el sprite por pantalla - void render(); - - // Obten el valor de la variable - float getPosX(); - - // Obten el valor de la variable - float getPosY(); - - // Obten el valor de la variable - float getVelX(); - - // Obten el valor de la variable - float getVelY(); - - // Obten el valor de la variable - float getAccelX(); - - // Obten el valor de la variable - float getAccelY(); - - // Obten el valor de la variable - float getZoomW(); - - // Obten el valor de la variable - float getZoomH(); - - // Obten el valor de la variable - double getAngle(); - - // Obtiene el valor de la variable - bool getRotate(); - - // Obtiene el valor de la variable - Uint16 getRotateSpeed(); - - // Establece la posición del objeto - void setPos(SDL_Rect rect); - - // Establece el valor de la variable - void setPosX(float value); - - // Establece el valor de la variable - void setPosY(float value); - - // Establece el valor de la variable - void setVelX(float value); - - // Establece el valor de la variable - void setVelY(float value); - - // Establece el valor de la variable - void setAccelX(float value); - - // Establece el valor de la variable - void setAccelY(float value); - - // Establece el valor de la variable - void setZoomW(float value); - - // Establece el valor de la variable - void setZoomH(float value); - - // Establece el valor de la variable - void setAngle(double vaue); - - // Incrementa el valor de la variable - void incAngle(double value); - - // Decrementa el valor de la variable - void decAngle(double value); - - // Establece el valor de la variable - void setRotate(bool value); - - // Establece el valor de la variable - void setRotateSpeed(int value); - - // Establece el valor de la variable - void setRotateAmount(double value); - - // Quita el efecto de rotación y deja el sprite en su angulo inicial. - void disableRotate(); - - // Cambia el sentido de la rotación - void switchRotate(); - - // Establece el valor de la variable - void setFlip(SDL_RendererFlip flip); - - // Gira el sprite horizontalmente - void flip(); - - // Obtiene el valor de la variable - SDL_RendererFlip getFlip(); - - // Devuelve el rectangulo donde está el sprite - SDL_Rect getRect(); - - // Establece los valores de posición y tamaño del sprite - void setRect(SDL_Rect rect); - - // Deshace el último movimiento - void undoMove(); - - // Deshace el último movimiento en el eje X - void undoMoveX(); - - // Deshace el último movimiento en el eje Y - void undoMoveY(); - - // Pone a cero las velocidades de desplacamiento - void clearVel(); - - // Devuelve el incremento en el eje X en pixels - int getIncX(); -}; - -#endif +#pragma once + +#include +#include "sprite.h" + +#ifndef MOVINGSPRITE_H +#define MOVINGSPRITE_H + +// Clase MovingSprite. Añade posicion y velocidad en punto flotante +class MovingSprite : public Sprite +{ +protected: + float x; // Posición en el eje X + float y; // Posición en el eje Y + + float xPrev; // Posición anterior en el eje X + float yPrev; // Posición anterior en el eje Y + + float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + + float ax; // Aceleración en el eje X. Variación de la velocidad + float ay; // Aceleración en el eje Y. Variación de la velocidad + + float zoomW; // Zoom aplicado a la anchura + float zoomH; // Zoom aplicado a la altura + + double angle; // Angulo para dibujarlo + bool rotateEnabled; // Indica si ha de rotar + int rotateSpeed; // Velocidad de giro + double rotateAmount; // Cantidad de grados a girar en cada iteración + int counter; // Contador interno + SDL_Point center; // Centro de rotación + SDL_RendererFlip currentFlip; // Indica como se voltea el sprite + +public: + // Constructor + MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); + + // Destructor + ~MovingSprite(); + + // Mueve el sprite + void move(); + + // Rota el sprite + void rotate(); + + // Actualiza las variables internas del objeto + void update(); + + // Reinicia todas las variables + void clear(); + + // Muestra el sprite por pantalla + void render(); + + // Obten el valor de la variable + float getPosX(); + + // Obten el valor de la variable + float getPosY(); + + // Obten el valor de la variable + float getVelX(); + + // Obten el valor de la variable + float getVelY(); + + // Obten el valor de la variable + float getAccelX(); + + // Obten el valor de la variable + float getAccelY(); + + // Obten el valor de la variable + float getZoomW(); + + // Obten el valor de la variable + float getZoomH(); + + // Obten el valor de la variable + double getAngle(); + + // Obtiene el valor de la variable + bool getRotate(); + + // Obtiene el valor de la variable + Uint16 getRotateSpeed(); + + // Establece la posición del objeto + void setPos(SDL_Rect rect); + + // Establece el valor de la variable + void setPosX(float value); + + // Establece el valor de la variable + void setPosY(float value); + + // Establece el valor de la variable + void setVelX(float value); + + // Establece el valor de la variable + void setVelY(float value); + + // Establece el valor de la variable + void setAccelX(float value); + + // Establece el valor de la variable + void setAccelY(float value); + + // Establece el valor de la variable + void setZoomW(float value); + + // Establece el valor de la variable + void setZoomH(float value); + + // Establece el valor de la variable + void setAngle(double vaue); + + // Incrementa el valor de la variable + void incAngle(double value); + + // Decrementa el valor de la variable + void decAngle(double value); + + // Establece el valor de la variable + void setRotate(bool value); + + // Establece el valor de la variable + void setRotateSpeed(int value); + + // Establece el valor de la variable + void setRotateAmount(double value); + + // Quita el efecto de rotación y deja el sprite en su angulo inicial. + void disableRotate(); + + // Cambia el sentido de la rotación + void switchRotate(); + + // Establece el valor de la variable + void setFlip(SDL_RendererFlip flip); + + // Gira el sprite horizontalmente + void flip(); + + // Obtiene el valor de la variable + SDL_RendererFlip getFlip(); + + // Devuelve el rectangulo donde está el sprite + SDL_Rect getRect(); + + // Establece los valores de posición y tamaño del sprite + void setRect(SDL_Rect rect); + + // Deshace el último movimiento + void undoMove(); + + // Deshace el último movimiento en el eje X + void undoMoveX(); + + // Deshace el último movimiento en el eje Y + void undoMoveY(); + + // Pone a cero las velocidades de desplacamiento + void clearVel(); + + // Devuelve el incremento en el eje X en pixels + int getIncX(); +}; + +#endif diff --git a/source/screen.cpp b/source/utils/screen.cpp similarity index 100% rename from source/screen.cpp rename to source/utils/screen.cpp diff --git a/source/screen.h b/source/utils/screen.h similarity index 100% rename from source/screen.h rename to source/utils/screen.h diff --git a/source/sprite.cpp b/source/utils/sprite.cpp similarity index 100% rename from source/sprite.cpp rename to source/utils/sprite.cpp diff --git a/source/sprite.h b/source/utils/sprite.h similarity index 96% rename from source/sprite.h rename to source/utils/sprite.h index 96aeeba..c9e53ce 100644 --- a/source/sprite.h +++ b/source/utils/sprite.h @@ -1,99 +1,99 @@ -#pragma once - -#include -#include "ltexture.h" - -#ifndef SPRITE_H -#define SPRITE_H - -// Clase sprite -class Sprite -{ -protected: - int x; // Posición en el eje X donde dibujar el sprite - int y; // Posición en el eje Y donde dibujar el sprite - int w; // Ancho del sprite - int h; // Alto del sprite - - SDL_Renderer *renderer; // Puntero al renderizador de la ventana - LTexture *texture; // Textura donde estan todos los dibujos del sprite - SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla - - bool enabled; // Indica si el sprite esta habilitado - -public: - // Constructor - Sprite(int x = 0, int y = 0, int w = 0, int h = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); - Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer); - - // Destructor - ~Sprite(); - - // Muestra el sprite por pantalla - void render(); - - // Obten el valor de la variable - int getPosX(); - - // Obten el valor de la variable - int getPosY(); - - // Obten el valor de la variable - int getWidth(); - - // Obten el valor de la variable - int getHeight(); - - // Establece la posición del objeto - void setPos(SDL_Rect rect); - - // Establece el valor de la variable - void setPosX(int x); - - // Establece el valor de la variable - void setPosY(int y); - - // Incrementa el valor de la variable - void incPosX(int value); - - // Incrementa el valor de la variable - void incPosY(int value); - - // Establece el valor de la variable - void setWidth(int w); - - // Establece el valor de la variable - void setHeight(int h); - - // Obten el valor de la variable - SDL_Rect getSpriteClip(); - - // Establece el valor de la variable - void setSpriteClip(SDL_Rect rect); - - // Establece el valor de la variable - void setSpriteClip(int x, int y, int w, int h); - - // Obten el valor de la variable - LTexture *getTexture(); - - // Establece el valor de la variable - void setTexture(LTexture *texture); - - // Establece el valor de la variable - void setRenderer(SDL_Renderer *renderer); - - // Establece el valor de la variable - void setEnabled(bool value); - - // Comprueba si el objeto está habilitado - bool isEnabled(); - - // Devuelve el rectangulo donde está el sprite - SDL_Rect getRect(); - - // Establece los valores de posición y tamaño del sprite - void setRect(SDL_Rect rect); -}; - -#endif +#pragma once + +#include +#include "ltexture.h" + +#ifndef SPRITE_H +#define SPRITE_H + +// Clase sprite +class Sprite +{ +protected: + int x; // Posición en el eje X donde dibujar el sprite + int y; // Posición en el eje Y donde dibujar el sprite + int w; // Ancho del sprite + int h; // Alto del sprite + + SDL_Renderer *renderer; // Puntero al renderizador de la ventana + LTexture *texture; // Textura donde estan todos los dibujos del sprite + SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla + + bool enabled; // Indica si el sprite esta habilitado + +public: + // Constructor + Sprite(int x = 0, int y = 0, int w = 0, int h = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); + Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer); + + // Destructor + ~Sprite(); + + // Muestra el sprite por pantalla + void render(); + + // Obten el valor de la variable + int getPosX(); + + // Obten el valor de la variable + int getPosY(); + + // Obten el valor de la variable + int getWidth(); + + // Obten el valor de la variable + int getHeight(); + + // Establece la posición del objeto + void setPos(SDL_Rect rect); + + // Establece el valor de la variable + void setPosX(int x); + + // Establece el valor de la variable + void setPosY(int y); + + // Incrementa el valor de la variable + void incPosX(int value); + + // Incrementa el valor de la variable + void incPosY(int value); + + // Establece el valor de la variable + void setWidth(int w); + + // Establece el valor de la variable + void setHeight(int h); + + // Obten el valor de la variable + SDL_Rect getSpriteClip(); + + // Establece el valor de la variable + void setSpriteClip(SDL_Rect rect); + + // Establece el valor de la variable + void setSpriteClip(int x, int y, int w, int h); + + // Obten el valor de la variable + LTexture *getTexture(); + + // Establece el valor de la variable + void setTexture(LTexture *texture); + + // Establece el valor de la variable + void setRenderer(SDL_Renderer *renderer); + + // Establece el valor de la variable + void setEnabled(bool value); + + // Comprueba si el objeto está habilitado + bool isEnabled(); + + // Devuelve el rectangulo donde está el sprite + SDL_Rect getRect(); + + // Establece los valores de posición y tamaño del sprite + void setRect(SDL_Rect rect); +}; + +#endif diff --git a/source/stb_image.h b/source/utils/stb_image.h similarity index 100% rename from source/stb_image.h rename to source/utils/stb_image.h diff --git a/source/stb_vorbis.c b/source/utils/stb_vorbis.c similarity index 100% rename from source/stb_vorbis.c rename to source/utils/stb_vorbis.c diff --git a/source/text.cpp b/source/utils/text.cpp similarity index 99% rename from source/text.cpp rename to source/utils/text.cpp index 7bcd656..b0b232b 100644 --- a/source/text.cpp +++ b/source/utils/text.cpp @@ -1,4 +1,3 @@ - #include "text.h" #include #include diff --git a/source/text.h b/source/utils/text.h similarity index 96% rename from source/text.h rename to source/utils/text.h index fc32787..d3ac42f 100644 --- a/source/text.h +++ b/source/utils/text.h @@ -1,71 +1,72 @@ -#pragma once - -#include "sprite.h" -#include "utils.h" - -#ifndef TEXT_H -#define TEXT_H - -#define TXT_COLOR 1 -#define TXT_SHADOW 2 -#define TXT_CENTER 4 -#define TXT_STROKE 8 - -// Clase texto. Pinta texto en pantalla a partir de un bitmap -class Text -{ -private: - Sprite *sprite; // Objeto con los graficos para el texto - - struct Offset - { - int x; - int y; - int w; - }; - Offset offset[128]; // Vector con las posiciones y ancho de cada letra - - int boxWidth; // Anchura de la caja de cada caracter en el png - int boxHeight; // Altura de la caja de cada caracter en el png - std::string file; // Fichero con los descriptores de la fuente - LTexture *texture; // Textura con los bitmaps del texto - - // Inicializador - void init(); - - // Inicializa el vector de offsets desde un fichero - void initOffsetFromFile(); - -public: - // Constructor - Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer); - - // Destructor - ~Text(); - - // Escribe el texto en pantalla - void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); - - // Escribe el texto con colores - void writeColored(int x, int y, std::string text, color_t color, int kerning = 1, int lenght = -1); - - // Escribe el texto con sombra - void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1); - - // Escribe el texto centrado en un punto x - void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); - - // Escribe texto con extras - void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, color_t textColor = {255, 255, 255}, Uint8 shadowDistance = 1, color_t shadowColor = {0, 0, 0}, int lenght = -1); - - // Obtiene la longitud en pixels de una cadena - int lenght(std::string text, int kerning = 1); - - // Devuelve el valor de la variable - int getCharacterSize(); - - // Recarga la textura - void reLoadTexture(); -}; - -#endif +#pragma once + +#include +#include "sprite.h" +#include "utils.h" + +#ifndef TEXT_H +#define TEXT_H + +#define TXT_COLOR 1 +#define TXT_SHADOW 2 +#define TXT_CENTER 4 +#define TXT_STROKE 8 + +// Clase texto. Pinta texto en pantalla a partir de un bitmap +class Text +{ +private: + Sprite *sprite; // Objeto con los graficos para el texto + + struct Offset + { + int x; + int y; + int w; + }; + Offset offset[128]; // Vector con las posiciones y ancho de cada letra + + int boxWidth; // Anchura de la caja de cada caracter en el png + int boxHeight; // Altura de la caja de cada caracter en el png + std::string file; // Fichero con los descriptores de la fuente + LTexture *texture; // Textura con los bitmaps del texto + + // Inicializador + void init(); + + // Inicializa el vector de offsets desde un fichero + void initOffsetFromFile(); + +public: + // Constructor + Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer); + + // Destructor + ~Text(); + + // Escribe el texto en pantalla + void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); + + // Escribe el texto con colores + void writeColored(int x, int y, std::string text, color_t color, int kerning = 1, int lenght = -1); + + // Escribe el texto con sombra + void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1); + + // Escribe el texto centrado en un punto x + void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); + + // Escribe texto con extras + void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, color_t textColor = {255, 255, 255}, Uint8 shadowDistance = 1, color_t shadowColor = {0, 0, 0}, int lenght = -1); + + // Obtiene la longitud en pixels de una cadena + int lenght(std::string text, int kerning = 1); + + // Devuelve el valor de la variable + int getCharacterSize(); + + // Recarga la textura + void reLoadTexture(); +}; + +#endif diff --git a/source/utils.cpp b/source/utils/utils.cpp similarity index 100% rename from source/utils.cpp rename to source/utils/utils.cpp diff --git a/source/utils.h b/source/utils/utils.h similarity index 100% rename from source/utils.h rename to source/utils/utils.h