corregits mes includes

llevats els errors en texture
This commit is contained in:
2025-10-15 09:14:30 +02:00
parent 78c5333144
commit 7c102e42cc
63 changed files with 1122 additions and 1621 deletions

View File

@@ -1,269 +1,236 @@
#include "s_animated_sprite.h"
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include <stdexcept> // Para runtime_error
#include "surface.h" // Para Surface
#include "utils.h" // Para printWithDots
#include "sprite/surface_animated_sprite.h"
#include <stddef.h> // Para size_t
#include <fstream> // Para basic_ostream, basic_istream, operator<<, basic...
#include <iostream> // Para cout, cerr
#include <sstream> // Para basic_stringstream
#include <stdexcept> // Para runtime_error
#include "surface.h" // Para Surface
#include "utils.h" // Para printWithDots
// Carga las animaciones en un vector(Animations) desde un fichero
Animations loadAnimationsFromFile(const std::string &file_path)
{
std::ifstream file(file_path);
if (!file)
{
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
Animations loadAnimationsFromFile(const std::string& file_path) {
std::ifstream file(file_path);
if (!file) {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
std::vector<std::string> buffer;
std::string line;
while (std::getline(file, line))
{
if (!line.empty())
buffer.push_back(line);
}
std::vector<std::string> buffer;
std::string line;
while (std::getline(file, line)) {
if (!line.empty())
buffer.push_back(line);
}
return buffer;
return buffer;
}
// Constructor
SAnimatedSprite::SAnimatedSprite(std::shared_ptr<Surface> surface, const std::string &file_path)
: SMovingSprite(surface)
{
// Carga las animaciones
if (!file_path.empty())
{
Animations v = loadAnimationsFromFile(file_path);
setAnimations(v);
}
SAnimatedSprite::SAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
: SMovingSprite(surface) {
// Carga las animaciones
if (!file_path.empty()) {
Animations v = loadAnimationsFromFile(file_path);
setAnimations(v);
}
}
// Constructor
SAnimatedSprite::SAnimatedSprite(std::shared_ptr<Surface> surface, const Animations &animations)
: SMovingSprite(surface)
{
if (!animations.empty())
{
setAnimations(animations);
}
SAnimatedSprite::SAnimatedSprite(std::shared_ptr<Surface> surface, const Animations& animations)
: SMovingSprite(surface) {
if (!animations.empty()) {
setAnimations(animations);
}
}
// Obtiene el indice de la animación a partir del nombre
int SAnimatedSprite::getIndex(const std::string &name)
{
auto index = -1;
int SAnimatedSprite::getIndex(const std::string& name) {
auto index = -1;
for (const auto &a : animations_)
{
index++;
if (a.name == name)
{
return index;
}
}
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
return -1;
for (const auto& a : animations_) {
index++;
if (a.name == name) {
return index;
}
}
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
return -1;
}
// Calcula el frame correspondiente a la animación
void SAnimatedSprite::animate()
{
if (animations_[current_animation_].speed == 0)
{
return;
}
void SAnimatedSprite::animate() {
if (animations_[current_animation_].speed == 0) {
return;
}
// Calcula el frame actual a partir del contador
animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].speed;
// Calcula el frame actual a partir del contador
animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].speed;
// Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop y coloca el nuevo frame
if (animations_[current_animation_].current_frame >= static_cast<int>(animations_[current_animation_].frames.size()))
{
if (animations_[current_animation_].loop == -1)
{ // Si no hay loop, deja el último frame
animations_[current_animation_].current_frame = animations_[current_animation_].frames.size();
animations_[current_animation_].completed = true;
}
else
{ // Si hay loop, vuelve al frame indicado
animations_[current_animation_].counter = 0;
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
}
}
// En caso contrario
else
{
// Escoge el frame correspondiente de la animación
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
// Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop y coloca el nuevo frame
if (animations_[current_animation_].current_frame >= static_cast<int>(animations_[current_animation_].frames.size())) {
if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame
animations_[current_animation_].current_frame = animations_[current_animation_].frames.size();
animations_[current_animation_].completed = true;
} else { // Si hay loop, vuelve al frame indicado
animations_[current_animation_].counter = 0;
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
}
}
// En caso contrario
else {
// Escoge el frame correspondiente de la animación
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
// Incrementa el contador de la animacion
animations_[current_animation_].counter++;
}
// Incrementa el contador de la animacion
animations_[current_animation_].counter++;
}
}
// Comprueba si ha terminado la animación
bool SAnimatedSprite::animationIsCompleted()
{
return animations_[current_animation_].completed;
bool SAnimatedSprite::animationIsCompleted() {
return animations_[current_animation_].completed;
}
// Establece la animacion actual
void SAnimatedSprite::setCurrentAnimation(const std::string &name)
{
const auto new_animation = getIndex(name);
if (current_animation_ != new_animation)
{
current_animation_ = new_animation;
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
}
void SAnimatedSprite::setCurrentAnimation(const std::string& name) {
const auto new_animation = getIndex(name);
if (current_animation_ != new_animation) {
current_animation_ = new_animation;
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
}
}
// Establece la animacion actual
void SAnimatedSprite::setCurrentAnimation(int index)
{
const auto new_animation = index;
if (current_animation_ != new_animation)
{
current_animation_ = new_animation;
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
}
void SAnimatedSprite::setCurrentAnimation(int index) {
const auto new_animation = index;
if (current_animation_ != new_animation) {
current_animation_ = new_animation;
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
}
}
// Actualiza las variables del objeto
void SAnimatedSprite::update()
{
animate();
SMovingSprite::update();
void SAnimatedSprite::update() {
animate();
SMovingSprite::update();
}
// Reinicia la animación
void SAnimatedSprite::resetAnimation()
{
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
void SAnimatedSprite::resetAnimation() {
animations_[current_animation_].current_frame = 0;
animations_[current_animation_].counter = 0;
animations_[current_animation_].completed = false;
}
// Carga la animación desde un vector de cadenas
void SAnimatedSprite::setAnimations(const Animations &animations)
{
int frame_width = 1;
int frame_height = 1;
int frames_per_row = 1;
int max_tiles = 1;
void SAnimatedSprite::setAnimations(const Animations& animations) {
int frame_width = 1;
int frame_height = 1;
int frames_per_row = 1;
int max_tiles = 1;
size_t index = 0;
while (index < animations.size())
{
std::string line = animations.at(index);
size_t index = 0;
while (index < animations.size()) {
std::string line = animations.at(index);
// Parsea el fichero para buscar variables y valores
if (line != "[animation]")
{
// Encuentra la posición del caracter '='
size_t pos = line.find("=");
// Parsea el fichero para buscar variables y valores
if (line != "[animation]") {
// Encuentra la posición del caracter '='
size_t pos = line.find("=");
// Procesa las dos subcadenas
if (pos != std::string::npos)
{
std::string key = line.substr(0, pos);
int value = std::stoi(line.substr(pos + 1));
if (key == "frame_width")
frame_width = value;
else if (key == "frame_height")
frame_height = value;
else
std::cout << "Warning: unknown parameter " << key << std::endl;
// Procesa las dos subcadenas
if (pos != std::string::npos) {
std::string key = line.substr(0, pos);
int value = std::stoi(line.substr(pos + 1));
if (key == "frame_width")
frame_width = value;
else if (key == "frame_height")
frame_height = value;
else
std::cout << "Warning: unknown parameter " << key << std::endl;
frames_per_row = surface_->getWidth() / frame_width;
const int w = surface_->getWidth() / frame_width;
const int h = surface_->getHeight() / frame_height;
max_tiles = w * h;
}
}
frames_per_row = surface_->getWidth() / frame_width;
const int w = surface_->getWidth() / frame_width;
const int h = surface_->getHeight() / frame_height;
max_tiles = w * h;
}
}
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
AnimationData animation;
do
{
index++;
line = animations.at(index);
size_t pos = line.find("=");
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") {
AnimationData animation;
do {
index++;
line = animations.at(index);
size_t pos = line.find("=");
if (pos != std::string::npos)
{
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
if (pos != std::string::npos) {
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
if (key == "name")
animation.name = value;
else if (key == "speed")
animation.speed = std::stoi(value);
else if (key == "loop")
animation.loop = std::stoi(value);
else if (key == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(value);
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ','))
{
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int num_tile = std::stoi(tmp);
if (num_tile <= max_tiles)
{
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
animation.frames.emplace_back(rect);
}
}
}
if (key == "name")
animation.name = value;
else if (key == "speed")
animation.speed = std::stoi(value);
else if (key == "loop")
animation.loop = std::stoi(value);
else if (key == "frames") {
// Se introducen los valores separados por comas en un vector
std::stringstream ss(value);
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ',')) {
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int num_tile = std::stoi(tmp);
if (num_tile <= max_tiles) {
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
animation.frames.emplace_back(rect);
}
}
}
else
std::cout << "Warning: unknown parameter " << key << std::endl;
}
} while (line != "[/animation]");
else
std::cout << "Warning: unknown parameter " << key << std::endl;
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animations_.emplace_back(animation);
}
// Añade la animación al vector de animaciones
animations_.emplace_back(animation);
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
}
// Pone un valor por defecto
setWidth(frame_width);
setHeight(frame_height);
// Pone un valor por defecto
setWidth(frame_width);
setHeight(frame_height);
}
// Establece el frame actual de la animación
void SAnimatedSprite::setCurrentAnimationFrame(int num)
{
// Descarta valores fuera de rango
if (num < 0 || num >= static_cast<int>(animations_[current_animation_].frames.size()))
{
num = 0;
}
void SAnimatedSprite::setCurrentAnimationFrame(int num) {
// Descarta valores fuera de rango
if (num < 0 || num >= static_cast<int>(animations_[current_animation_].frames.size())) {
num = 0;
}
// Cambia el valor de la variable
animations_[current_animation_].current_frame = num;
animations_[current_animation_].counter = 0;
// Cambia el valor de la variable
animations_[current_animation_].current_frame = num;
animations_[current_animation_].counter = 0;
// Escoge el frame correspondiente de la animación
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
// Escoge el frame correspondiente de la animación
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
}

View File

@@ -1,13 +1,13 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "s_moving_sprite.h" // Para SMovingSprite
class Surface; // lines 9-9
#include "sprite/surface_moving_sprite.h" // Para SMovingSprite
class Surface; // lines 9-9
struct AnimationData {
std::string name; // Nombre de la animacion

View File

@@ -1,102 +1,94 @@
#include "s_moving_sprite.h"
#include "surface.h" // Para Surface
#include "sprite/surface_moving_sprite.h"
#include "surface.h" // Para Surface
// Constructor
SMovingSprite::SMovingSprite(std::shared_ptr<Surface> surface, SDL_Rect pos, SDL_RendererFlip flip)
: SSprite(surface, pos),
x_(pos.x),
y_(pos.y),
flip_(flip) { SSprite::pos_ = pos; }
: SSprite(surface, pos),
x_(pos.x),
y_(pos.y),
flip_(flip) { SSprite::pos_ = pos; }
SMovingSprite::SMovingSprite(std::shared_ptr<Surface> surface, SDL_Rect pos)
: SSprite(surface, pos),
x_(pos.x),
y_(pos.y),
flip_(SDL_FLIP_NONE) { SSprite::pos_ = pos; }
: SSprite(surface, pos),
x_(pos.x),
y_(pos.y),
flip_(SDL_FLIP_NONE) { SSprite::pos_ = pos; }
SMovingSprite::SMovingSprite(std::shared_ptr<Surface> surface)
: SSprite(surface),
x_(0.0f),
y_(0.0f),
flip_(SDL_FLIP_NONE) { SSprite::clear(); }
: SSprite(surface),
x_(0.0f),
y_(0.0f),
flip_(SDL_FLIP_NONE) { SSprite::clear(); }
// Reinicia todas las variables
void SMovingSprite::clear()
{
x_ = 0.0f; // Posición en el eje X
y_ = 0.0f; // Posición en el eje Y
void SMovingSprite::clear() {
x_ = 0.0f; // Posición en el eje X
y_ = 0.0f; // Posición en el eje Y
vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
SSprite::clear();
SSprite::clear();
}
// Mueve el sprite
void SMovingSprite::move()
{
x_ += vx_;
y_ += vy_;
void SMovingSprite::move() {
x_ += vx_;
y_ += vy_;
vx_ += ax_;
vy_ += ay_;
vx_ += ax_;
vy_ += ay_;
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
}
// Actualiza las variables internas del objeto
void SMovingSprite::update()
{
move();
void SMovingSprite::update() {
move();
}
// Muestra el sprite por pantalla
void SMovingSprite::render()
{
surface_->render(pos_.x, pos_.y, &clip_, flip_);
void SMovingSprite::render() {
surface_->render(pos_.x, pos_.y, &clip_, flip_);
}
// Muestra el sprite por pantalla
void SMovingSprite::render(Uint8 source_color, Uint8 target_color)
{
surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_, flip_);
void SMovingSprite::render(Uint8 source_color, Uint8 target_color) {
surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_, flip_);
}
// Establece la posición y_ el tamaño del objeto
void SMovingSprite::setPos(SDL_Rect rect)
{
x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(rect.y);
void SMovingSprite::setPos(SDL_Rect rect) {
x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(rect.y);
pos_ = rect;
pos_ = rect;
}
// Establece el valor de las variables
void SMovingSprite::setPos(float x, float y)
{
x_ = x;
y_ = y;
void SMovingSprite::setPos(float x, float y) {
x_ = x;
y_ = y;
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
pos_.x = static_cast<int>(x_);
pos_.y = static_cast<int>(y_);
}
// Establece el valor de la variable
void SMovingSprite::setPosX(float value)
{
x_ = value;
pos_.x = static_cast<int>(x_);
void SMovingSprite::setPosX(float value) {
x_ = value;
pos_.x = static_cast<int>(x_);
}
// Establece el valor de la variable
void SMovingSprite::setPosY(float value)
{
y_ = value;
pos_.y = static_cast<int>(y_);
void SMovingSprite::setPosY(float value) {
y_ = value;
pos_.y = static_cast<int>(y_);
}

View File

@@ -1,13 +1,11 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect
#include <SDL3/SDL_render.h> // Para SDL_RendererFlip, SDL_FLIP_HORIZONTAL
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include "s_sprite.h" // Para SSprite
class Surface; // lines 8-8
#include "sprite/surface_sprite.h" // Para SSprite
class Surface; // lines 8-8
// Clase SMovingSprite. Añade movimiento y flip al sprite
class SMovingSprite : public SSprite {

View File

@@ -1,50 +1,46 @@
#include "s_sprite.h"
#include "surface.h" // Para Surface
#include "sprite/surface_sprite.h"
#include "surface.h" // Para Surface
// Constructor
SSprite::SSprite(std::shared_ptr<Surface> surface, int x, int y, int w, int h)
: surface_(surface),
pos_((SDL_Rect){x, y, w, h}),
clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
: surface_(surface),
pos_((SDL_Rect){x, y, w, h}),
clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
SSprite::SSprite(std::shared_ptr<Surface> surface, SDL_Rect rect)
: surface_(surface),
pos_(rect),
clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
: surface_(surface),
pos_(rect),
clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
SSprite::SSprite(std::shared_ptr<Surface> surface)
: surface_(surface),
pos_({0, 0, surface_->getWidth(), surface_->getHeight()}),
clip_(pos_) {}
: surface_(surface),
pos_({0, 0, surface_->getWidth(), surface_->getHeight()}),
clip_(pos_) {}
// Muestra el sprite por pantalla
void SSprite::render()
{
surface_->render(pos_.x, pos_.y, &clip_);
void SSprite::render() {
surface_->render(pos_.x, pos_.y, &clip_);
}
void SSprite::render(Uint8 source_color, Uint8 target_color)
{
surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_);
void SSprite::render(Uint8 source_color, Uint8 target_color) {
surface_->renderWithColorReplace(pos_.x, pos_.y, source_color, target_color, &clip_);
}
// Establece la posición del objeto
void SSprite::setPosition(int x, int y)
{
pos_.x = x;
pos_.y = y;
void SSprite::setPosition(int x, int y) {
pos_.x = x;
pos_.y = y;
}
// Establece la posición del objeto
void SSprite::setPosition(SDL_Point p)
{
pos_.x = p.x;
pos_.y = p.y;
void SSprite::setPosition(SDL_Point p) {
pos_.x = p.x;
pos_.y = p.y;
}
// Reinicia las variables a cero
void SSprite::clear()
{
pos_ = {0, 0, 0, 0};
clip_ = {0, 0, 0, 0};
void SSprite::clear() {
pos_ = {0, 0, 0, 0};
clip_ = {0, 0, 0, 0};
}

View File

@@ -1,7 +1,6 @@
#pragma once
#include <SDL3/SDL_rect.h> // Para SDL_Rect, SDL_Point
#include <SDL3/SDL_stdinc.h> // Para Uint8
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
class Surface; // lines 5-5