He fet un "manolete" i he pasat a c++ i smartpointers la cárrega de surfaces desde gif. Sembla que no ha petat res

Precárrega i asignació de paletes a les textures
Ara si algú toca una paleta, que siga conscient que la textura es compartida durant tot el joc
This commit is contained in:
2024-10-20 15:36:04 +02:00
parent cbc9b3f071
commit 848d61b5c0
24 changed files with 187 additions and 228 deletions

View File

Before

Width:  |  Height:  |  Size: 84 B

After

Width:  |  Height:  |  Size: 84 B

View File

Before

Width:  |  Height:  |  Size: 173 B

After

Width:  |  Height:  |  Size: 173 B

View File

Before

Width:  |  Height:  |  Size: 173 B

After

Width:  |  Height:  |  Size: 173 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 772 B

View File

Before

Width:  |  Height:  |  Size: 173 B

After

Width:  |  Height:  |  Size: 173 B

View File

Before

Width:  |  Height:  |  Size: 172 B

After

Width:  |  Height:  |  Size: 172 B

View File

Before

Width:  |  Height:  |  Size: 172 B

After

Width:  |  Height:  |  Size: 172 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 772 B

View File

Before

Width:  |  Height:  |  Size: 172 B

After

Width:  |  Height:  |  Size: 172 B

View File

Before

Width:  |  Height:  |  Size: 84 B

After

Width:  |  Height:  |  Size: 84 B

View File

@@ -436,19 +436,19 @@ void Director::setFileList()
Asset::get()->add(prefix + "/data/gfx/title/title_dust.ani", AssetType::ANIMATION); Asset::get()->add(prefix + "/data/gfx/title/title_dust.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/player/player1.gif", AssetType::BITMAP); Asset::get()->add(prefix + "/data/gfx/player/player1.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player1_pal1.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player1_one_coffee_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_pal2.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player1_two_coffee_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_pal3.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player1_all_white_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2.gif", AssetType::BITMAP); Asset::get()->add(prefix + "/data/gfx/player/player2.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player2_pal1.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player2_one_coffee_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_pal2.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player2_two_coffee_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_pal3.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player2_all_white_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player.ani", AssetType::ANIMATION); Asset::get()->add(prefix + "/data/gfx/player/player.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/player/player_power.gif", AssetType::BITMAP); Asset::get()->add(prefix + "/data/gfx/player/player_power.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player_power_pal.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player_power_blue_palette.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player_power.ani", AssetType::ANIMATION); Asset::get()->add(prefix + "/data/gfx/player/player_power.ani", AssetType::ANIMATION);
// Fuentes de texto // Fuentes de texto
@@ -463,7 +463,7 @@ void Director::setFileList()
Asset::get()->add(prefix + "/data/font/smb2_big.png", AssetType::BITMAP); Asset::get()->add(prefix + "/data/font/smb2_big.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/smb2_big.txt", AssetType::FONT); Asset::get()->add(prefix + "/data/font/smb2_big.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2.gif", AssetType::BITMAP); Asset::get()->add(prefix + "/data/font/smb2.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/smb2_pal1.gif", AssetType::PALETTE); Asset::get()->add(prefix + "/data/font/smb2_palette1.pal", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT); Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT);
// Textos // Textos

View File

@@ -347,13 +347,7 @@ void Game::loadMedia()
{ {
std::vector<std::shared_ptr<Texture>> player_texture; std::vector<std::shared_ptr<Texture>> player_texture;
player_texture.emplace_back(Resource::get()->getTexture("player1.gif")); player_texture.emplace_back(Resource::get()->getTexture("player1.gif"));
player_texture.back()->addPalette(asset_->get("player1_pal1.gif"));
player_texture.back()->addPalette(asset_->get("player1_pal2.gif"));
player_texture.back()->addPalette(asset_->get("player1_pal3.gif"));
player_texture.emplace_back(Resource::get()->getTexture("player_power.gif")); player_texture.emplace_back(Resource::get()->getTexture("player_power.gif"));
player_texture.back()->addPalette(asset_->get("player_power_pal.gif"));
player_textures_.push_back(player_texture); player_textures_.push_back(player_texture);
} }
@@ -361,14 +355,7 @@ void Game::loadMedia()
{ {
std::vector<std::shared_ptr<Texture>> player_texture; std::vector<std::shared_ptr<Texture>> player_texture;
player_texture.emplace_back(Resource::get()->getTexture("player2.gif")); player_texture.emplace_back(Resource::get()->getTexture("player2.gif"));
player_texture.back()->addPalette(asset_->get("player2_pal1.gif"));
player_texture.back()->addPalette(asset_->get("player2_pal2.gif"));
player_texture.back()->addPalette(asset_->get("player2_pal3.gif"));
player_texture.emplace_back(Resource::get()->getTexture("player_power.gif")); player_texture.emplace_back(Resource::get()->getTexture("player_power.gif"));
player_texture.back()->addPalette(asset_->get("player_power_pal.gif"));
player_texture.back()->setPalette(1);
player_textures_.push_back(player_texture); player_textures_.push_back(player_texture);
} }
@@ -1205,6 +1192,8 @@ void Game::renderItems()
// Devuelve un item al azar y luego segun sus probabilidades // Devuelve un item al azar y luego segun sus probabilidades
ItemType Game::dropItem() ItemType Game::dropItem()
{ {
return ItemType::COFFEE_MACHINE;
const auto lucky_number = rand() % 100; const auto lucky_number = rand() % 100;
const auto item = rand() % 6; const auto item = rand() % 6;

View File

@@ -347,7 +347,7 @@ void Player::update()
setAnimation(); setAnimation();
shiftColliders(); shiftColliders();
updateCooldown(); updateCooldown();
updatePowerUpCounter(); updatePowerUp();
updateInvulnerable(); updateInvulnerable();
updateContinueCounter(); updateContinueCounter();
updateEnterNameCounter(); updateEnterNameCounter();
@@ -578,7 +578,7 @@ void Player::updateInvulnerable()
{ {
if (invulnerable_counter_ > 0) if (invulnerable_counter_ > 0)
{ {
invulnerable_counter_--; --invulnerable_counter_;
invulnerable_counter_ % 8 > 3 ? player_sprite_->getTexture()->setPalette(coffees_) : player_sprite_->getTexture()->setPalette(3); invulnerable_counter_ % 8 > 3 ? player_sprite_->getTexture()->setPalette(coffees_) : player_sprite_->getTexture()->setPalette(3);
} }
else else
@@ -615,15 +615,13 @@ void Player::setPowerUpCounter(int value)
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updatePowerUpCounter() void Player::updatePowerUp()
{ {
if ((power_up_counter_ > 0) && (power_up_)) if (power_up_)
{ {
power_up_counter_--; --power_up_counter_;
} power_up_ = power_up_counter_ > 0;
else power_sprite_->getTexture()->setPalette(id_ - 1);
{
power_up_ = false;
} }
} }

View File

@@ -49,7 +49,7 @@ private:
SDL_Rect *play_area_; // Rectangulo con la zona de juego SDL_Rect *play_area_; // Rectangulo con la zona de juego
// Variables // Variables
int id_; // Numero de identificación para el jugador int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
float pos_x_; // Posicion en el eje X float pos_x_; // Posicion en el eje X
int pos_y_; // Posicion en el eje Y int pos_y_; // 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
@@ -245,7 +245,7 @@ public:
void setPowerUpCounter(int value); void setPowerUpCounter(int value);
// Actualiza el valor de la variable // Actualiza el valor de la variable
void updatePowerUpCounter(); void updatePowerUp();
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool hasExtraHit() const; bool hasExtraHit() const;

View File

@@ -34,6 +34,10 @@ Resource::Resource()
loadTextFiles(); loadTextFiles();
loadAnimations(); loadAnimations();
std::cout << "\n** RESOURCES LOADED" << std::endl; std::cout << "\n** RESOURCES LOADED" << std::endl;
std::cout << "\n** ADD PALETTES" << std::endl;
addPalettes();
std::cout << "\n** PALETTES ADDED" << std::endl;
} }
// Destructor // Destructor
@@ -220,3 +224,27 @@ void Resource::loadAnimations()
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
} }
} }
// Añade paletas a las texturas
void Resource::addPalettes()
{
// Jugador 1
std::cout << "\n>> PLAYER1" << std::endl;
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_one_coffee_palette.pal"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_two_coffee_palette.pal"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_all_white_palette.pal"));
// Jugador 2
std::cout << "\n>> PLAYER2" << std::endl;
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_one_coffee_palette.pal"));
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_two_coffee_palette.pal"));
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_all_white_palette.pal"));
// Player_power
std::cout << "\n>> PLAYER_POWER" << std::endl;
getTexture("player_power.gif")->addPaletteFromFile(Asset::get()->get("player_power_blue_palette.pal"));
// Fuentes
std::cout << "\n>> FONTS" << std::endl;
getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal"));
}

View File

@@ -91,6 +91,9 @@ private:
// Carga las animaciones // Carga las animaciones
void loadAnimations(); void loadAnimations();
// Añade paletas a las texturas
void addPalettes();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera
// Constructor // Constructor

View File

@@ -77,33 +77,8 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
return tf; return tf;
} }
// Constructor
Text::Text(const std::string &bitmap_file, const std::string &text_file, SDL_Renderer *renderer)
{
// Carga los offsets desde el fichero
auto tf = loadTextFile(text_file);
// Inicializa variables desde la estructura
box_height_ = tf->box_height;
box_width_ = tf->box_width;
for (int i = 0; i < 128; ++i)
{
offset_[i].x = tf->offset[i].x;
offset_[i].y = tf->offset[i].y;
offset_[i].w = tf->offset[i].w;
}
// Crea los objetos
texture_ = std::make_shared<Texture>(renderer, bitmap_file);
sprite_ = std::make_unique<Sprite>(texture_, (SDL_Rect){0, 0, box_width_, box_height_});
// Inicializa variables
fixed_width_ = false;
}
// Constructor // Constructor
Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file) Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file)
: texture_(texture)
{ {
// Carga los offsets desde el fichero // Carga los offsets desde el fichero
auto tf = loadTextFile(text_file); auto tf = loadTextFile(text_file);
@@ -127,7 +102,6 @@ Text::Text(std::shared_ptr<Texture> texture, const std::string &text_file)
// Constructor // Constructor
Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file) Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file)
: texture_(texture)
{ {
// Inicializa variables desde la estructura // Inicializa variables desde la estructura
box_height_ = text_file->box_height; box_height_ = text_file->box_height;
@@ -266,15 +240,3 @@ void Text::setFixedWidth(bool value)
{ {
fixed_width_ = value; fixed_width_ = value;
} }
// Carga una paleta de colores para el texto
void Text::addPalette(const std::string &path)
{
texture_->addPalette(path);
}
// Establece una paleta de colores para el texto
void Text::setPalette(int index)
{
texture_->setPalette(index);
}

View File

@@ -34,7 +34,6 @@ class Text
private: private:
// Objetos y punteros // Objetos y punteros
std::unique_ptr<Sprite> sprite_; // Objeto con los graficos para el texto std::unique_ptr<Sprite> sprite_; // Objeto con los graficos para el texto
std::shared_ptr<Texture> texture_; // Textura con los bitmaps del texto
// Variables // Variables
int box_width_; // Anchura de la caja de cada caracter en el png int box_width_; // Anchura de la caja de cada caracter en el png
@@ -44,7 +43,6 @@ private:
public: public:
// Constructor // Constructor
Text(const std::string &bitmap_file, const std::string &text_file, SDL_Renderer *renderer);
Text(std::shared_ptr<Texture> texture, const std::string &text_file); Text(std::shared_ptr<Texture> texture, const std::string &text_file);
Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file); Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file);
@@ -77,10 +75,4 @@ public:
// Establece si se usa un tamaño fijo de letra // Establece si se usa un tamaño fijo de letra
void setFixedWidth(bool value); void setFixedWidth(bool value);
// Carga una paleta de colores para el texto
void addPalette(const std::string &path);
// Establece una paleta de colores para el texto
void setPalette(int index);
}; };

View File

@@ -7,22 +7,22 @@
#include <stdio.h> // for fseek, fclose, fopen, fread, ftell, NULL #include <stdio.h> // for fseek, fclose, fopen, fread, ftell, NULL
#include <stdlib.h> // for malloc, free, exit #include <stdlib.h> // for malloc, free, exit
#include <iostream> // for basic_ostream, operator<<, cout, endl #include <iostream> // for basic_ostream, operator<<, cout, endl
#include <fstream>
#include <sstream>
#include "gif.c" // for LoadGif, LoadPalette #include "gif.c" // for LoadGif, LoadPalette
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" // for stbi_failure_reason, stbi_image_free #include "stb_image.h" // for stbi_failure_reason, stbi_image_free
// Constructor // Constructor
Texture::Texture(SDL_Renderer *renderer, const std::string &path) Texture::Texture(SDL_Renderer *renderer, const std::string &path)
: renderer_(renderer), path_(path) : texture_(nullptr),
renderer_(renderer),
surface_(nullptr),
width_(0),
height_(0),
path_(path),
current_palette_(0)
{ {
// Inicializa
surface_ = nullptr;
texture_ = nullptr;
width_ = 0;
height_ = 0;
paletteIndex_ = 0;
palettes_.clear();
// Carga el fichero en la textura // Carga el fichero en la textura
if (!path_.empty()) if (!path_.empty())
{ {
@@ -39,7 +39,7 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
else if (extension == "gif") else if (extension == "gif")
{ {
surface_ = loadSurface(path_); surface_ = loadSurface(path_);
addPalette(path_); addPaletteFromFile(path_);
setPaletteColor(0, 0, 0x00000000); setPaletteColor(0, 0, 0x00000000);
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
@@ -51,7 +51,9 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
// Destructor // Destructor
Texture::~Texture() Texture::~Texture()
{ {
unload(); unloadTexture();
unloadSurface();
palettes_.clear();
} }
// Carga una imagen desde un fichero // Carga una imagen desde un fichero
@@ -87,7 +89,7 @@ bool Texture::loadFromFile(const std::string &file_path)
} }
// Limpia // Limpia
unload(); unloadTexture();
// La textura final // La textura final
SDL_Texture *newTexture = nullptr; SDL_Texture *newTexture = nullptr;
@@ -142,7 +144,7 @@ bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL
} }
// Libera la memoria de la textura // Libera la memoria de la textura
void Texture::unload() void Texture::unloadTexture()
{ {
// Libera la textura // Libera la textura
if (texture_) if (texture_)
@@ -152,13 +154,6 @@ void Texture::unload()
width_ = 0; width_ = 0;
height_ = 0; height_ = 0;
} }
// Libera la surface
if (surface_)
{
deleteSurface(surface_);
surface_ = nullptr;
}
} }
// Establece el color para la modulacion // Establece el color para la modulacion
@@ -229,61 +224,56 @@ SDL_Texture *Texture::getSDLTexture()
return texture_; return texture_;
} }
// Crea una nueva surface // Desencadenar la superficie actual
/*Surface Texture::newSurface(int w, int h) void Texture::unloadSurface()
{ {
Surface surf = static_cast<Surface>(malloc(sizeof(surface_s))); surface_.reset(); // Resetea el shared_ptr
surf->w = w; width_ = 0;
surf->h = h; height_ = 0;
surf->data = static_cast<Uint8 *>(malloc(w * h));
return surf;
}*/
// Elimina una surface
void Texture::deleteSurface(Surface surface)
{
if (surface == nullptr)
{
return;
}
if (surface->data != nullptr)
{
free(surface->data);
}
free(surface);
} }
// Crea una surface desde un fichero .gif // Crea una surface desde un fichero .gif
Surface Texture::loadSurface(const std::string &file_name) std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path)
{ {
FILE *f = fopen(file_name.c_str(), "rb"); // Desencadenar la superficie actual
if (!f) unloadSurface();
// Abrir el archivo usando std::ifstream para manejo automático del recurso
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file)
{ {
return nullptr; std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path);
} }
fseek(f, 0, SEEK_END); // Obtener el tamaño del archivo
long size = ftell(f); std::streamsize size = file.tellg();
fseek(f, 0, SEEK_SET); file.seekg(0, std::ios::beg);
Uint8 *buffer = static_cast<Uint8 *>(malloc(size));
fread(buffer, size, 1, f);
fclose(f);
// Leer el contenido del archivo en un buffer
std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{
std::cerr << "Error al leer el fichero " << file_path << std::endl;
throw std::runtime_error("Error al leer el fichero: " + file_path);
}
// Cerrar el archivo (automáticamente manejado por std::ifstream)
file.close();
// Llamar a la función LoadGif
Uint16 w, h; Uint16 w, h;
Uint8 *pixels = LoadGif(buffer, &w, &h); Uint8 *rawPixels = LoadGif(buffer.data(), &w, &h);
if (pixels == nullptr) if (!rawPixels)
{ {
return nullptr; return nullptr;
} }
Surface surface = static_cast<Surface>(malloc(sizeof(surface_s))); // Crear un std::shared_ptr con std::make_shared para pixels
surface->w = w; auto pixels = std::shared_ptr<Uint8[]>(rawPixels, std::default_delete<Uint8[]>());
surface->h = h; auto surface = std::make_shared<Surface>(w, h, pixels);
surface->data = pixels;
free(buffer);
// Actualizar la anchura y altura
width_ = w; width_ = w;
height_ = h; height_ = h;
@@ -306,7 +296,7 @@ void Texture::flipSurface()
SDL_LockTexture(texture_, nullptr, reinterpret_cast<void **>(&pixels), &pitch); SDL_LockTexture(texture_, nullptr, reinterpret_cast<void **>(&pixels), &pitch);
for (int i = 0; i < width_ * height_; ++i) for (int i = 0; i < width_ * height_; ++i)
{ {
pixels[i] = palettes_[paletteIndex_][surface_->data[i]]; pixels[i] = palettes_[current_palette_][surface_->data[i]];
} }
SDL_UnlockTexture(texture_); SDL_UnlockTexture(texture_);
} }
@@ -318,14 +308,20 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color)
} }
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
std::vector<Uint32> Texture::loadPal(const std::string &file_name) std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
{ {
std::vector<Uint32> palette; std::vector<Uint32> palette;
FILE *f = fopen(file_name.c_str(), "rb"); FILE *f = fopen(file_path.c_str(), "rb");
if (!f) if (!f)
{ {
return palette; std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
else
{
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
printWithDots("Image : ", file_name, "[ LOADED ]");
} }
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
@@ -352,9 +348,9 @@ std::vector<Uint32> Texture::loadPal(const std::string &file_name)
} }
// Añade una paleta a la lista // Añade una paleta a la lista
void Texture::addPalette(const std::string &path) void Texture::addPaletteFromFile(const std::string &path)
{ {
palettes_.push_back(loadPal(path)); palettes_.emplace_back(loadPaletteFromFile(path));
setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000); setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000);
} }
@@ -363,7 +359,7 @@ void Texture::setPalette(int palette)
{ {
if (palette < (int)palettes_.size()) if (palette < (int)palettes_.size())
{ {
paletteIndex_ = palette; current_palette_ = palette;
flipSurface(); flipSurface();
} }
} }

View File

@@ -7,15 +7,18 @@
#include <SDL2/SDL_stdinc.h> // for Uint8, Uint32, Uint16 #include <SDL2/SDL_stdinc.h> // for Uint8, Uint32, Uint16
#include <string> // for string, basic_string #include <string> // for string, basic_string
#include <vector> // for vector #include <vector> // for vector
#include <memory>
// Definiciones de tipos // Definiciones de tipos
struct surface_s struct Surface
{ {
Uint8 *data; std::shared_ptr<Uint8[]> data;
Uint16 w, h; Uint16 w, h;
};
typedef struct surface_s *Surface; // Constructor
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels)
: data(pixels), w(width), h(height) {}
};
class Texture class Texture
{ {
@@ -23,29 +26,29 @@ private:
// Objetos y punteros // Objetos y punteros
SDL_Texture *texture_; // La textura SDL_Texture *texture_; // La textura
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
Surface surface_; // Surface para usar imagenes en formato gif con paleta std::shared_ptr<Surface> surface_; // Surface para usar imagenes en formato gif con paleta
// Variables // Variables
int width_; // Ancho de la imagen int width_; // Ancho de la imagen
int height_; // Alto de la imagen int height_; // Alto de la imagen
std::string path_; // Ruta de la imagen de la textura std::string path_; // Ruta de la imagen de la textura
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
int paletteIndex_; // Indice de la paleta en uso int current_palette_; // Indice de la paleta en uso
// Crea una nueva surface
//Surface newSurface(int w, int h);
// Elimina una surface
void deleteSurface(Surface surface);
// Crea una surface desde un fichero .gif // Crea una surface desde un fichero .gif
Surface loadSurface(const std::string &file_name); std::shared_ptr<Surface> loadSurface(const std::string &file_name);
// Vuelca la surface en la textura // Vuelca la surface en la textura
void flipSurface(); void flipSurface();
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
std::vector<Uint32> loadPal(const std::string &file_name); std::vector<Uint32> loadPaletteFromFile(const std::string &file_name);
// Libera la memoria de la textura
void unloadTexture();
// Desencadenar la superficie actual
void unloadSurface();
public: public:
// Constructor // Constructor
@@ -60,9 +63,6 @@ public:
// Crea una textura en blanco // Crea una textura en blanco
bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
// Libera la memoria de la textura
void unload();
// Establece el color para la modulacion // Establece el color para la modulacion
void setColor(Uint8 red, Uint8 green, Uint8 blue); void setColor(Uint8 red, Uint8 green, Uint8 blue);
@@ -91,7 +91,7 @@ public:
SDL_Texture *getSDLTexture(); SDL_Texture *getSDLTexture();
// Añade una paleta a la lista // Añade una paleta a la lista
void addPalette(const std::string &path); void addPaletteFromFile(const std::string &path);
// Establece un color de la paleta // Establece un color de la paleta
void setPaletteColor(int palette, int index, Uint32 color); void setPaletteColor(int palette, int index, Uint32 color);

View File

@@ -28,7 +28,7 @@ TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
// Inicializa los valores del vector con los valores del seno // Inicializa los valores del vector con los valores del seno
for (int i = 0; i < 360; ++i) for (int i = 0; i < 360; ++i)
{ {
sin_[i] = std::sinf(i * 3.14159f / 180.0f); // Convierte grados a radianes y calcula el seno sin_[i] = std::sin(i * 3.14159 / 180.0); // Convierte grados a radianes y calcula el seno
} }
} }

View File

@@ -36,7 +36,7 @@ private:
SDL_Rect pos_; // Posición y tamaño del mosaico SDL_Rect pos_; // Posición y tamaño del mosaico
int counter_; // Contador int counter_; // Contador
TiledBGMode mode_; // Tipo de movimiento del mosaico TiledBGMode mode_; // Tipo de movimiento del mosaico
float sin_[360]; // Vector con los valores del seno precalculados double sin_[360]; // Vector con los valores del seno precalculados
// Rellena la textura con el contenido // Rellena la textura con el contenido
void fillTexture(); void fillTexture();

View File

@@ -24,51 +24,43 @@ struct JA_Music_t; // lines 17-17
// Constructor // Constructor
Title::Title() Title::Title()
: text1_(std::make_unique<Text>(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt"))),
text2_(std::make_unique<Text>(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt"))),
fade_(std::make_unique<Fade>()),
tiled_bg_(std::make_unique<TiledBG>((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::RANDOM)),
game_logo_(std::make_unique<GameLogo>(param.game.game_area.center_x, param.title.title_c_c_position)),
mini_logo_texture_(Resource::get()->getTexture("logo_jailgames_mini.png")),
mini_logo_sprite_(std::make_unique<Sprite>(mini_logo_texture_, param.game.game_area.center_x - mini_logo_texture_->getWidth() / 2, 0, mini_logo_texture_->getWidth(), mini_logo_texture_->getHeight())),
define_buttons_(std::make_unique<DefineButtons>(std::move(text2_))),
counter_(0),
ticks_(0),
demo_(true),
next_section_(section::Name::GAME),
post_fade_(0),
num_controllers_(Input::get()->getNumControllers())
{ {
// Reserva memoria y crea los objetos // Configura objetos
fade_ = std::make_unique<Fade>();
text1_ = std::make_unique<Text>(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt"));
text1_->addPalette(Asset::get()->get("smb2_pal1.gif"));
text1_->setPalette(1);
text2_ = std::make_unique<Text>(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt"));
mini_logo_texture_ = Resource::get()->getTexture("logo_jailgames_mini.png");
mini_logo_sprite_ = std::make_unique<Sprite>(mini_logo_texture_, param.game.game_area.center_x - mini_logo_texture_->getWidth() / 2, 0, mini_logo_texture_->getWidth(), mini_logo_texture_->getHeight());
tiled_bg_ = std::make_unique<TiledBG>((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::RANDOM);
game_logo_ = std::make_unique<GameLogo>(param.game.game_area.center_x, param.title.title_c_c_position);
game_logo_->enable(); game_logo_->enable();
define_buttons_ = std::make_unique<DefineButtons>(std::move(text2_));
// Inicializa los valores
init();
}
// Inicializa los valores de las variables
void Title::init()
{
// Inicializa variables
section::options = section::Options::TITLE_1;
counter_ = 0;
next_section_ = section::Name::GAME;
post_fade_ = 0;
ticks_ = 0;
ticks_speed_ = 15;
fade_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_->setColor(fade_color.r, fade_color.g, fade_color.b);
fade_->setType(FadeType::RANDOM_SQUARE); fade_->setType(FadeType::RANDOM_SQUARE);
fade_->setPost(param.fade.post_duration); fade_->setPost(param.fade.post_duration);
demo_ = true; Resource::get()->getTexture("smb2.gif")->setPalette(1);
num_controllers_ = Input::get()->getNumControllers();
// Asigna valores a otras variables
section::options = section::Options::TITLE_1;
}
// Destructor
Title::~Title()
{
Resource::get()->getTexture("smb2.gif")->setPalette(0);
} }
// Actualiza las variables del objeto // Actualiza las variables del objeto
void Title::update() void Title::update()
{ {
// Calcula la lógica de los objetos // Calcula la lógica de los objetos
if (SDL_GetTicks() - ticks_ > ticks_speed_) if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
{ {
// Actualiza el contador de ticks_ // Actualiza el contador de ticks_
ticks_ = SDL_GetTicks(); ticks_ = SDL_GetTicks();

View File

@@ -42,29 +42,28 @@ constexpr bool ALLOW_TITLE_ANIMATION_SKIP = true;
class Title class Title
{ {
private: private:
// Objetos y punteros // Constantes
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa
std::unique_ptr<GameLogo> game_logo_; // Objeto para dibujar el logo con el título del juego
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
std::shared_ptr<Texture> mini_logo_texture_; // Textura con el logo de JailGames mini
std::unique_ptr<Sprite> mini_logo_sprite_; // Sprite con el logo de JailGames mini
// Objetos y punteros
std::unique_ptr<Text> text1_; // Objeto de texto para poder escribir textos en pantalla std::unique_ptr<Text> text1_; // Objeto de texto para poder escribir textos en pantalla
std::unique_ptr<Text> text2_; // Objeto de texto para poder escribir textos en pantalla std::unique_ptr<Text> text2_; // Objeto de texto para poder escribir textos en pantalla
std::unique_ptr<Fade> fade_; // Objeto para realizar fundidos en pantalla std::unique_ptr<Fade> fade_; // Objeto para realizar fundidos en pantalla
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
std::unique_ptr<GameLogo> game_logo_; // Objeto para dibujar el logo con el título del juego
std::shared_ptr<Texture> mini_logo_texture_; // Textura con el logo de JailGames mini
std::unique_ptr<Sprite> mini_logo_sprite_; // Sprite con el logo de JailGames mini
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
// Variable // Variable
int counter_; // Temporizador para la pantalla de titulo int counter_; // Temporizador para la pantalla de titulo
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
bool demo_; // Indica si el modo demo estará activo bool demo_; // Indica si el modo demo estará activo
section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
int post_fade_; // Opción a realizar cuando termina el fundido int post_fade_; // Opción a realizar cuando termina el fundido
int num_controllers_; // Número de mandos conectados int num_controllers_; // Número de mandos conectados
// Inicializa los valores de las variables
void init();
// Actualiza las variables del objeto // Actualiza las variables del objeto
void update(); void update();
@@ -91,7 +90,7 @@ public:
Title(); Title();
// Destructor // Destructor
~Title() = default; ~Title();
// Bucle para el titulo del juego // Bucle para el titulo del juego
void run(); void run();