Refactoring completo: migrar main.cpp a Engine class

 Características principales:
- Encapsulación completa de variables globales en Engine class
- main.cpp simplificado: 580+ líneas → 15 líneas
- Eliminados problemas de orden de declaración de funciones

🔧 Correcciones aplicadas:
- Colores degradado SUNSET restaurados al original
- Inicialización pelotas: velocidad lateral y posición corregidas
- Textos en MAYÚSCULAS con singular/plural correcto ("1 PELOTA"/"X PELOTAS")
- Uso correcto de changeGravityDirection() para reset de gravedad
- Funciones dbgtxt marcadas como inline para evitar múltiples definiciones

📁 Estructura final:
- engine.h/cpp: Clase Engine con toda la lógica encapsulada
- main.cpp: Interfaz mínima con Engine
- main_old.cpp: Eliminado (ya no necesario)
- CMakeLists.txt: Actualizado para excluir archivos obsoletos

🧪 Testing: Compilación exitosa, funcionalidad restaurada completamente

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-09-18 17:33:53 +02:00
parent cada46f732
commit 19e1c414c2
6 changed files with 415 additions and 628 deletions

View File

@@ -16,8 +16,9 @@ if (NOT SDL3_FOUND)
message(FATAL_ERROR "SDL3 no encontrado. Por favor, verifica su instalación.") message(FATAL_ERROR "SDL3 no encontrado. Por favor, verifica su instalación.")
endif() endif()
# Archivos fuente # Archivos fuente (excluir main_old.cpp)
file(GLOB SOURCE_FILES source/*.cpp source/external/*.cpp) file(GLOB SOURCE_FILES source/*.cpp source/external/*.cpp)
list(REMOVE_ITEM SOURCE_FILES "${CMAKE_SOURCE_DIR}/source/main_old.cpp")
# Comprobar si se encontraron archivos fuente # Comprobar si se encontraron archivos fuente
if(NOT SOURCE_FILES) if(NOT SOURCE_FILES)

View File

@@ -84,54 +84,412 @@ void Engine::shutdown() {
// Métodos privados - esqueleto básico por ahora // Métodos privados - esqueleto básico por ahora
void Engine::calculateDeltaTime() { void Engine::calculateDeltaTime() {
// TODO: Implementar cálculo de delta time Uint64 current_time = SDL_GetTicks();
// En el primer frame, inicializar el tiempo anterior
if (last_frame_time_ == 0) {
last_frame_time_ = current_time;
delta_time_ = 1.0f / 60.0f; // Asumir 60 FPS para el primer frame
return;
}
// Calcular delta time en segundos
delta_time_ = (current_time - last_frame_time_) / 1000.0f;
last_frame_time_ = current_time;
// Limitar delta time para evitar saltos grandes (pausa larga, depuración, etc.)
if (delta_time_ > 0.05f) { // Máximo 50ms (20 FPS mínimo)
delta_time_ = 1.0f / 60.0f; // Fallback a 60 FPS
}
} }
void Engine::update() { void Engine::update() {
// TODO: Implementar lógica de actualización // Calcular FPS
fps_frame_count_++;
Uint64 current_time = SDL_GetTicks();
if (current_time - fps_last_time_ >= 1000) // Actualizar cada segundo
{
fps_current_ = fps_frame_count_;
fps_frame_count_ = 0;
fps_last_time_ = current_time;
fps_text_ = "FPS: " + std::to_string(fps_current_);
}
// ¡DELTA TIME! Actualizar física siempre, usando tiempo transcurrido
for (auto &ball : balls_) {
ball->update(delta_time_); // Pasar delta time a cada pelota
}
// Actualizar texto (sin cambios en la lógica)
if (show_text_) {
show_text_ = !(SDL_GetTicks() - text_init_time_ > TEXT_DURATION);
}
} }
void Engine::handleEvents() { void Engine::handleEvents() {
// TODO: Implementar manejo de eventos SDL_Event event;
while (SDL_PollEvent(&event)) {
// Salir del bucle si se detecta una petición de cierre
if (event.type == SDL_EVENT_QUIT) {
should_exit_ = true;
break;
}
// Procesar eventos de teclado
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) {
switch (event.key.key) {
case SDLK_ESCAPE:
should_exit_ = true;
break;
case SDLK_SPACE:
pushUpBalls();
break;
case SDLK_G:
switchBallsGravity();
break;
// Controles de dirección de gravedad con teclas de cursor
case SDLK_UP:
changeGravityDirection(GravityDirection::UP);
break;
case SDLK_DOWN:
changeGravityDirection(GravityDirection::DOWN);
break;
case SDLK_LEFT:
changeGravityDirection(GravityDirection::LEFT);
break;
case SDLK_RIGHT:
changeGravityDirection(GravityDirection::RIGHT);
break;
case SDLK_V:
toggleVSync();
break;
case SDLK_H:
show_debug_ = !show_debug_;
break;
case SDLK_T:
// Ciclar al siguiente tema
current_theme_ = static_cast<ColorTheme>((static_cast<int>(current_theme_) + 1) % 4);
initBalls(scenario_); // Regenerar bolas con nueva paleta
break;
case SDLK_F1:
current_theme_ = ColorTheme::SUNSET;
initBalls(scenario_);
break;
case SDLK_F2:
current_theme_ = ColorTheme::OCEAN;
initBalls(scenario_);
break;
case SDLK_F3:
current_theme_ = ColorTheme::NEON;
initBalls(scenario_);
break;
case SDLK_F4:
current_theme_ = ColorTheme::FOREST;
initBalls(scenario_);
break;
case SDLK_1:
scenario_ = 0;
initBalls(scenario_);
break;
case SDLK_2:
scenario_ = 1;
initBalls(scenario_);
break;
case SDLK_3:
scenario_ = 2;
initBalls(scenario_);
break;
case SDLK_4:
scenario_ = 3;
initBalls(scenario_);
break;
case SDLK_5:
scenario_ = 4;
initBalls(scenario_);
break;
case SDLK_6:
scenario_ = 5;
initBalls(scenario_);
break;
case SDLK_7:
scenario_ = 6;
initBalls(scenario_);
break;
case SDLK_8:
scenario_ = 7;
initBalls(scenario_);
break;
}
}
}
} }
void Engine::render() { void Engine::render() {
// TODO: Implementar renderizado // Renderizar fondo degradado en lugar de color sólido
renderGradientBackground();
// Limpiar batches del frame anterior
batch_vertices_.clear();
batch_indices_.clear();
// Recopilar datos de todas las bolas para batch rendering
for (auto &ball : balls_) {
// En lugar de ball->render(), obtener datos para batch
SDL_FRect pos = ball->getPosition();
Color color = ball->getColor();
addSpriteToBatch(pos.x, pos.y, pos.w, pos.h, color.r, color.g, color.b);
}
// Renderizar todas las bolas en una sola llamada
if (!batch_vertices_.empty()) {
SDL_RenderGeometry(renderer_, texture_->getSDLTexture(), batch_vertices_.data(), static_cast<int>(batch_vertices_.size()), batch_indices_.data(), static_cast<int>(batch_indices_.size()));
}
if (show_text_) {
dbg_print(text_pos_, 8, text_.c_str(), 255, 255, 255);
// Mostrar nombre del tema en castellano debajo del número de pelotas
std::string theme_names_es[] = {"ATARDECER", "OCEANO", "NEON", "BOSQUE"};
std::string theme_name = theme_names_es[static_cast<int>(current_theme_)];
int theme_text_width = static_cast<int>(theme_name.length() * 8); // 8 píxeles por carácter
int theme_x = (SCREEN_WIDTH - theme_text_width) / 2; // Centrar horizontalmente
// Colores acordes a cada tema
int theme_colors[][3] = {
{255, 140, 60}, // ATARDECER: Naranja cálido
{80, 200, 255}, // OCEANO: Azul océano
{255, 60, 255}, // NEON: Magenta brillante
{100, 255, 100} // BOSQUE: Verde natural
};
int theme_idx = static_cast<int>(current_theme_);
dbg_print(theme_x, 24, theme_name.c_str(), theme_colors[theme_idx][0], theme_colors[theme_idx][1], theme_colors[theme_idx][2]);
}
// Debug display (solo si está activado con tecla H)
if (show_debug_) {
// Mostrar contador de FPS en esquina superior derecha
int fps_text_width = static_cast<int>(fps_text_.length() * 8); // 8 píxeles por carácter
int fps_x = SCREEN_WIDTH - fps_text_width - 8; // 8 píxeles de margen
dbg_print(fps_x, 8, fps_text_.c_str(), 255, 255, 0); // Amarillo para distinguir
// Mostrar estado V-Sync en esquina superior izquierda
dbg_print(8, 8, vsync_text_.c_str(), 0, 255, 255); // Cian para distinguir
// Debug: Mostrar valores de la primera pelota (si existe)
if (!balls_.empty()) {
// Línea 1: Gravedad (solo números enteros)
int grav_int = static_cast<int>(balls_[0]->getGravityForce());
std::string grav_text = "GRAV " + std::to_string(grav_int);
dbg_print(8, 24, grav_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 2: Velocidad Y (solo números enteros)
int vy_int = static_cast<int>(balls_[0]->getVelocityY());
std::string vy_text = "VY " + std::to_string(vy_int);
dbg_print(8, 32, vy_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 3: Estado superficie
std::string surface_text = balls_[0]->isOnSurface() ? "SURFACE YES" : "SURFACE NO";
dbg_print(8, 40, surface_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 4: Coeficiente de rebote (loss)
float loss_val = balls_[0]->getLossCoefficient();
std::string loss_text = "LOSS " + std::to_string(loss_val).substr(0, 4); // Solo 2 decimales
dbg_print(8, 48, loss_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 5: Dirección de gravedad
std::string gravity_dir_text = "GRAVITY " + gravityDirectionToString(current_gravity_);
dbg_print(8, 56, gravity_dir_text.c_str(), 255, 255, 0); // Amarillo para dirección
}
// Debug: Mostrar tema actual
std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"};
std::string theme_text = "THEME " + theme_names[static_cast<int>(current_theme_)];
dbg_print(8, 64, theme_text.c_str(), 255, 255, 128); // Amarillo claro para tema
}
SDL_RenderPresent(renderer_);
} }
void Engine::initBalls(int value) { void Engine::initBalls(int value) {
// TODO: Implementar inicialización de pelotas // Limpiar las bolas actuales
balls_.clear();
// Resetear gravedad al estado por defecto (DOWN) al cambiar escenario
changeGravityDirection(GravityDirection::DOWN);
// Crear las bolas según el escenario
for (int i = 0; i < test_.at(value); ++i) {
const int SIGN = ((rand() % 2) * 2) - 1; // Genera un signo aleatorio (+ o -)
const float X = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4); // Posición inicial en X
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGN; // Velocidad en X
const float VY = ((rand() % 60) - 30) * 0.1f; // Velocidad en Y
// Seleccionar color de la paleta del tema actual
ThemeColors &theme = themes_[static_cast<int>(current_theme_)];
int color_index = rand() % 8; // 8 colores por tema
const Color COLOR = {theme.ball_colors[color_index][0],
theme.ball_colors[color_index][1],
theme.ball_colors[color_index][2]};
balls_.emplace_back(std::make_unique<Ball>(X, VX, VY, COLOR, texture_, current_gravity_));
}
setText(); // Actualiza el texto
} }
void Engine::setText() { void Engine::setText() {
// TODO: Implementar texto int num_balls = test_.at(scenario_);
if (num_balls == 1) {
text_ = "1 PELOTA";
} else {
text_ = std::to_string(num_balls) + " PELOTAS";
}
text_pos_ = (SCREEN_WIDTH - static_cast<int>(text_.length() * 8)) / 2; // Centrar texto
show_text_ = true;
text_init_time_ = SDL_GetTicks();
} }
void Engine::pushUpBalls() { void Engine::pushUpBalls() {
// TODO: Implementar impulso de pelotas for (auto &ball : balls_) {
const int SIGNO = ((rand() % 2) * 2) - 1;
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGNO;
const float VY = ((rand() % 40) * 0.1f) + 5;
ball->modVel(VX, -VY); // Modifica la velocidad de la bola
}
} }
void Engine::switchBallsGravity() { void Engine::switchBallsGravity() {
// TODO: Implementar cambio de gravedad for (auto &ball : balls_) {
ball->switchGravity();
}
} }
void Engine::changeGravityDirection(GravityDirection direction) { void Engine::changeGravityDirection(GravityDirection direction) {
// TODO: Implementar cambio de dirección current_gravity_ = direction;
for (auto &ball : balls_) {
ball->setGravityDirection(direction);
}
} }
void Engine::toggleVSync() { void Engine::toggleVSync() {
// TODO: Implementar toggle V-Sync vsync_enabled_ = !vsync_enabled_;
vsync_text_ = vsync_enabled_ ? "VSYNC ON" : "VSYNC OFF";
// Aplicar el cambio de V-Sync al renderizador
SDL_SetRenderVSync(renderer_, vsync_enabled_ ? 1 : 0);
} }
std::string Engine::gravityDirectionToString(GravityDirection direction) const { std::string Engine::gravityDirectionToString(GravityDirection direction) const {
// TODO: Implementar conversión a string switch (direction) {
return "DOWN"; case GravityDirection::DOWN: return "DOWN";
case GravityDirection::UP: return "UP";
case GravityDirection::LEFT: return "LEFT";
case GravityDirection::RIGHT: return "RIGHT";
default: return "UNKNOWN";
}
} }
void Engine::renderGradientBackground() { void Engine::renderGradientBackground() {
// TODO: Implementar fondo degradado // Crear quad de pantalla completa con degradado
SDL_Vertex bg_vertices[4];
// Obtener colores del tema actual
ThemeColors &theme = themes_[static_cast<int>(current_theme_)];
float top_r = theme.bg_top_r;
float top_g = theme.bg_top_g;
float top_b = theme.bg_top_b;
float bottom_r = theme.bg_bottom_r;
float bottom_g = theme.bg_bottom_g;
float bottom_b = theme.bg_bottom_b;
// Vértice superior izquierdo
bg_vertices[0].position = {0, 0};
bg_vertices[0].tex_coord = {0.0f, 0.0f};
bg_vertices[0].color = {top_r, top_g, top_b, 1.0f};
// Vértice superior derecho
bg_vertices[1].position = {SCREEN_WIDTH, 0};
bg_vertices[1].tex_coord = {1.0f, 0.0f};
bg_vertices[1].color = {top_r, top_g, top_b, 1.0f};
// Vértice inferior derecho
bg_vertices[2].position = {SCREEN_WIDTH, SCREEN_HEIGHT};
bg_vertices[2].tex_coord = {1.0f, 1.0f};
bg_vertices[2].color = {bottom_r, bottom_g, bottom_b, 1.0f};
// Vértice inferior izquierdo
bg_vertices[3].position = {0, SCREEN_HEIGHT};
bg_vertices[3].tex_coord = {0.0f, 1.0f};
bg_vertices[3].color = {bottom_r, bottom_g, bottom_b, 1.0f};
// Índices para 2 triángulos
int bg_indices[6] = {0, 1, 2, 2, 3, 0};
// Renderizar sin textura (nullptr)
SDL_RenderGeometry(renderer_, nullptr, bg_vertices, 4, bg_indices, 6);
} }
void Engine::addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b) { void Engine::addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b) {
// TODO: Implementar batch rendering int vertex_index = static_cast<int>(batch_vertices_.size());
// Crear 4 vértices para el quad (2 triángulos)
SDL_Vertex vertices[4];
// Convertir colores de int (0-255) a float (0.0-1.0)
float rf = r / 255.0f;
float gf = g / 255.0f;
float bf = b / 255.0f;
// Vértice superior izquierdo
vertices[0].position = {x, y};
vertices[0].tex_coord = {0.0f, 0.0f};
vertices[0].color = {rf, gf, bf, 1.0f};
// Vértice superior derecho
vertices[1].position = {x + w, y};
vertices[1].tex_coord = {1.0f, 0.0f};
vertices[1].color = {rf, gf, bf, 1.0f};
// Vértice inferior derecho
vertices[2].position = {x + w, y + h};
vertices[2].tex_coord = {1.0f, 1.0f};
vertices[2].color = {rf, gf, bf, 1.0f};
// Vértice inferior izquierdo
vertices[3].position = {x, y + h};
vertices[3].tex_coord = {0.0f, 1.0f};
vertices[3].color = {rf, gf, bf, 1.0f};
// Añadir vértices al batch
for (int i = 0; i < 4; i++) {
batch_vertices_.push_back(vertices[i]);
}
// Añadir índices para 2 triángulos
batch_indices_.push_back(vertex_index + 0);
batch_indices_.push_back(vertex_index + 1);
batch_indices_.push_back(vertex_index + 2);
batch_indices_.push_back(vertex_index + 2);
batch_indices_.push_back(vertex_index + 3);
batch_indices_.push_back(vertex_index + 0);
} }

View File

@@ -11,9 +11,8 @@
#include <vector> // for vector #include <vector> // for vector
#include "defines.h" // for GravityDirection, ColorTheme #include "defines.h" // for GravityDirection, ColorTheme
#include "ball.h" // for Ball
class Ball; #include "external/texture.h" // for Texture
class Texture;
class Engine { class Engine {
public: public:
@@ -57,6 +56,33 @@ private:
// Sistema de temas // Sistema de temas
ColorTheme current_theme_ = ColorTheme::SUNSET; ColorTheme current_theme_ = ColorTheme::SUNSET;
// Estructura de tema de colores
struct ThemeColors {
float bg_top_r, bg_top_g, bg_top_b;
float bg_bottom_r, bg_bottom_g, bg_bottom_b;
int ball_colors[8][3];
};
// Temas de colores definidos
ThemeColors themes_[4] = {
// SUNSET: Naranjas, rojos, amarillos, rosas
{180.0f / 255.0f, 140.0f / 255.0f, 100.0f / 255.0f, // Fondo superior (naranja suave)
40.0f / 255.0f, 20.0f / 255.0f, 60.0f / 255.0f, // Fondo inferior (púrpura oscuro)
{{255, 140, 0}, {255, 69, 0}, {255, 215, 0}, {255, 20, 147}, {255, 99, 71}, {255, 165, 0}, {255, 192, 203}, {220, 20, 60}}},
// OCEAN: Azules, turquesas, blancos
{100.0f / 255.0f, 150.0f / 255.0f, 200.0f / 255.0f, // Fondo superior (azul cielo)
20.0f / 255.0f, 40.0f / 255.0f, 80.0f / 255.0f, // Fondo inferior (azul marino)
{{0, 191, 255}, {0, 255, 255}, {32, 178, 170}, {176, 224, 230}, {70, 130, 180}, {0, 206, 209}, {240, 248, 255}, {64, 224, 208}}},
// NEON: Cian, magenta, verde lima, amarillo vibrante
{20.0f / 255.0f, 20.0f / 255.0f, 40.0f / 255.0f, // Fondo superior (negro azulado)
0.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, // Fondo inferior (negro)
{{0, 255, 255}, {255, 0, 255}, {50, 205, 50}, {255, 255, 0}, {255, 20, 147}, {0, 255, 127}, {138, 43, 226}, {255, 69, 0}}},
// FOREST: Verdes, marrones, amarillos otoño
{144.0f / 255.0f, 238.0f / 255.0f, 144.0f / 255.0f, // Fondo superior (verde claro)
101.0f / 255.0f, 67.0f / 255.0f, 33.0f / 255.0f, // Fondo inferior (marrón tierra)
{{34, 139, 34}, {107, 142, 35}, {154, 205, 50}, {255, 215, 0}, {210, 180, 140}, {160, 82, 45}, {218, 165, 32}, {50, 205, 50}}}
};
// Batch rendering // Batch rendering
std::vector<SDL_Vertex> batch_vertices_; std::vector<SDL_Vertex> batch_vertices_;
std::vector<int> batch_indices_; std::vector<int> batch_indices_;

View File

@@ -5,7 +5,7 @@ SDL_Texture* dbg_tex = nullptr;
SDL_Renderer* dbg_ren = nullptr; SDL_Renderer* dbg_ren = nullptr;
} // namespace } // namespace
void dbg_init(SDL_Renderer* renderer) { inline void dbg_init(SDL_Renderer* renderer) {
dbg_ren = renderer; dbg_ren = renderer;
Uint8 font[448] = {0x42, 0x4D, 0xC0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00, 0x12, 0x0B, 0x00, 0x00, 0x12, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x18, 0xF3, 0x83, 0x83, 0xCF, 0x83, 0x87, 0x00, 0x00, 0xF3, 0x39, 0x39, 0xCF, 0x79, 0xF3, 0x00, 0x00, 0x01, 0xF9, 0x39, 0xCF, 0x61, 0xF9, 0x00, 0x00, 0x33, 0xF9, 0x03, 0xE7, 0x87, 0x81, 0x00, 0x00, 0x93, 0x03, 0x3F, 0xF3, 0x1B, 0x39, 0x00, 0x00, 0xC3, 0x3F, 0x9F, 0x39, 0x3B, 0x39, 0x00, 0x41, 0xE3, 0x03, 0xC3, 0x01, 0x87, 0x83, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xE7, 0x01, 0xC7, 0x81, 0x01, 0x83, 0x00, 0x00, 0xE7, 0x1F, 0x9B, 0xE7, 0x1F, 0x39, 0x00, 0x00, 0xE7, 0x8F, 0x39, 0xE7, 0x87, 0xF9, 0x00, 0x00, 0xC3, 0xC7, 0x39, 0xE7, 0xC3, 0xC3, 0x00, 0x00, 0x99, 0xE3, 0x39, 0xE7, 0xF1, 0xE7, 0x00, 0x00, 0x99, 0xF1, 0xB3, 0xC7, 0x39, 0xF3, 0x00, 0x00, 0x99, 0x01, 0xC7, 0xE7, 0x83, 0x81, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x83, 0xE7, 0x83, 0xEF, 0x39, 0x39, 0x00, 0x00, 0x39, 0xE7, 0x39, 0xC7, 0x11, 0x11, 0x00, 0x00, 0xF9, 0xE7, 0x39, 0x83, 0x01, 0x83, 0x00, 0x00, 0x83, 0xE7, 0x39, 0x11, 0x01, 0xC7, 0x00, 0x00, 0x3F, 0xE7, 0x39, 0x39, 0x29, 0x83, 0x00, 0x00, 0x33, 0xE7, 0x39, 0x39, 0x39, 0x11, 0x00, 0x00, 0x87, 0x81, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x39, 0x39, 0x83, 0x3F, 0x85, 0x31, 0x00, 0x00, 0x39, 0x31, 0x39, 0x3F, 0x33, 0x23, 0x00, 0x00, 0x29, 0x21, 0x39, 0x03, 0x21, 0x07, 0x00, 0x00, 0x01, 0x01, 0x39, 0x39, 0x39, 0x31, 0x00, 0x00, 0x01, 0x09, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0x11, 0x19, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0x39, 0x39, 0x83, 0x03, 0x83, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xC1, 0x39, 0x81, 0x83, 0x31, 0x01, 0x00, 0x00, 0x99, 0x39, 0xE7, 0x39, 0x23, 0x3F, 0x00, 0x00, 0x39, 0x39, 0xE7, 0xF9, 0x07, 0x3F, 0x00, 0x00, 0x31, 0x01, 0xE7, 0xF9, 0x0F, 0x3F, 0x00, 0x00, 0x3F, 0x39, 0xE7, 0xF9, 0x27, 0x3F, 0x00, 0x00, 0x9F, 0x39, 0xE7, 0xF9, 0x33, 0x3F, 0x00, 0x00, 0xC1, 0x39, 0x81, 0xF9, 0x39, 0x3F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x39, 0x03, 0xC3, 0x07, 0x01, 0x3F, 0x00, 0x00, 0x39, 0x39, 0x99, 0x33, 0x3F, 0x3F, 0x00, 0x00, 0x01, 0x39, 0x3F, 0x39, 0x3F, 0x3F, 0x00, 0x00, 0x39, 0x03, 0x3F, 0x39, 0x03, 0x03, 0x00, 0x00, 0x39, 0x39, 0x3F, 0x39, 0x3F, 0x3F, 0x00, 0x00, 0x93, 0x39, 0x99, 0x33, 0x3F, 0x3F, 0x00, 0x00, 0xC7, 0x03, 0xC3, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00}; Uint8 font[448] = {0x42, 0x4D, 0xC0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00, 0x12, 0x0B, 0x00, 0x00, 0x12, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x18, 0xF3, 0x83, 0x83, 0xCF, 0x83, 0x87, 0x00, 0x00, 0xF3, 0x39, 0x39, 0xCF, 0x79, 0xF3, 0x00, 0x00, 0x01, 0xF9, 0x39, 0xCF, 0x61, 0xF9, 0x00, 0x00, 0x33, 0xF9, 0x03, 0xE7, 0x87, 0x81, 0x00, 0x00, 0x93, 0x03, 0x3F, 0xF3, 0x1B, 0x39, 0x00, 0x00, 0xC3, 0x3F, 0x9F, 0x39, 0x3B, 0x39, 0x00, 0x41, 0xE3, 0x03, 0xC3, 0x01, 0x87, 0x83, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xE7, 0x01, 0xC7, 0x81, 0x01, 0x83, 0x00, 0x00, 0xE7, 0x1F, 0x9B, 0xE7, 0x1F, 0x39, 0x00, 0x00, 0xE7, 0x8F, 0x39, 0xE7, 0x87, 0xF9, 0x00, 0x00, 0xC3, 0xC7, 0x39, 0xE7, 0xC3, 0xC3, 0x00, 0x00, 0x99, 0xE3, 0x39, 0xE7, 0xF1, 0xE7, 0x00, 0x00, 0x99, 0xF1, 0xB3, 0xC7, 0x39, 0xF3, 0x00, 0x00, 0x99, 0x01, 0xC7, 0xE7, 0x83, 0x81, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x83, 0xE7, 0x83, 0xEF, 0x39, 0x39, 0x00, 0x00, 0x39, 0xE7, 0x39, 0xC7, 0x11, 0x11, 0x00, 0x00, 0xF9, 0xE7, 0x39, 0x83, 0x01, 0x83, 0x00, 0x00, 0x83, 0xE7, 0x39, 0x11, 0x01, 0xC7, 0x00, 0x00, 0x3F, 0xE7, 0x39, 0x39, 0x29, 0x83, 0x00, 0x00, 0x33, 0xE7, 0x39, 0x39, 0x39, 0x11, 0x00, 0x00, 0x87, 0x81, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x39, 0x39, 0x83, 0x3F, 0x85, 0x31, 0x00, 0x00, 0x39, 0x31, 0x39, 0x3F, 0x33, 0x23, 0x00, 0x00, 0x29, 0x21, 0x39, 0x03, 0x21, 0x07, 0x00, 0x00, 0x01, 0x01, 0x39, 0x39, 0x39, 0x31, 0x00, 0x00, 0x01, 0x09, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0x11, 0x19, 0x39, 0x39, 0x39, 0x39, 0x00, 0x00, 0x39, 0x39, 0x83, 0x03, 0x83, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xC1, 0x39, 0x81, 0x83, 0x31, 0x01, 0x00, 0x00, 0x99, 0x39, 0xE7, 0x39, 0x23, 0x3F, 0x00, 0x00, 0x39, 0x39, 0xE7, 0xF9, 0x07, 0x3F, 0x00, 0x00, 0x31, 0x01, 0xE7, 0xF9, 0x0F, 0x3F, 0x00, 0x00, 0x3F, 0x39, 0xE7, 0xF9, 0x27, 0x3F, 0x00, 0x00, 0x9F, 0x39, 0xE7, 0xF9, 0x33, 0x3F, 0x00, 0x00, 0xC1, 0x39, 0x81, 0xF9, 0x39, 0x3F, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x39, 0x03, 0xC3, 0x07, 0x01, 0x3F, 0x00, 0x00, 0x39, 0x39, 0x99, 0x33, 0x3F, 0x3F, 0x00, 0x00, 0x01, 0x39, 0x3F, 0x39, 0x3F, 0x3F, 0x00, 0x00, 0x39, 0x03, 0x3F, 0x39, 0x03, 0x03, 0x00, 0x00, 0x39, 0x39, 0x3F, 0x39, 0x3F, 0x3F, 0x00, 0x00, 0x93, 0x39, 0x99, 0x33, 0x3F, 0x3F, 0x00, 0x00, 0xC7, 0x03, 0xC3, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00};
@@ -55,7 +55,7 @@ void dbg_init(SDL_Renderer* renderer) {
} }
} }
void dbg_print(int x, int y, const char* text, Uint8 r, Uint8 g, Uint8 b) { inline void dbg_print(int x, int y, const char* text, Uint8 r, Uint8 g, Uint8 b) {
int cc = 0; int cc = 0;
SDL_SetTextureColorMod(dbg_tex, r, g, b); SDL_SetTextureColorMod(dbg_tex, r, g, b);
SDL_FRect src = {0, 0, 8, 8}; SDL_FRect src = {0, 0, 8, 8};

View File

@@ -1,598 +1,17 @@
#include <SDL3/SDL_error.h> // for SDL_GetError #include <iostream>
#include <SDL3/SDL_events.h> // for SDL_EventType, SDL_PollEvent, SDL_Event
#include <SDL3/SDL_init.h> // for SDL_Init, SDL_Quit, SDL_INIT_VIDEO
#include <SDL3/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_4, SDLK_5
#include <SDL3/SDL_render.h> // for SDL_SetRenderDrawColor, SDL_CreateRend...
#include <SDL3/SDL_stdinc.h> // for Uint64
#include <SDL3/SDL_timer.h> // for SDL_GetTicks
#include <SDL3/SDL_video.h> // for SDL_CreateWindow, SDL_DestroyWindow
#include <array> // for array #include "engine.h"
#include <cstdlib> // for rand, srand
#include <ctime> // for time
#include <iostream> // for basic_ostream, char_traits, operator<<
#include <memory> // for unique_ptr, shared_ptr, make_shared
#include <string> // for operator+, string, to_string
#include <vector> // for vector
#include "ball.h" // for Ball int main() {
#include "defines.h" // for SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_SIZE Engine engine;
#include "external/dbgtxt.h" // for dbg_init, dbg_print
#include "external/texture.h" // for Texture
// Variables globales if (!engine.initialize()) {
SDL_Window *window = nullptr; std::cout << "¡Error al inicializar el engine!" << std::endl;
SDL_Renderer *renderer = nullptr; return -1;
std::shared_ptr<Texture> texture = nullptr;
std::vector<std::unique_ptr<Ball>> balls;
std::array<int, 8> test = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
bool should_exit = false; // Controla si la aplicación debe cerrarse
// ticks eliminado - reemplazado por delta time system
int scenario = 0; // Escenario actual basado en el número de bolas
std::string text; // Texto a mostrar en pantalla
int text_pos = 0; // Posición del texto en la pantalla
bool show_text = true; // Determina si el texto se debe mostrar
Uint64 text_init_time = 0; // Temporizador para mostrar el texto
// Variables para contador de FPS
Uint64 fps_last_time = 0; // Último tiempo para cálculo de FPS
int fps_frame_count = 0; // Contador de frames
int fps_current = 0; // FPS actuales calculados
std::string fps_text = "FPS: 0"; // Texto del contador de FPS
// Variables para V-Sync
bool vsync_enabled = true; // Estado inicial del V-Sync (activado por defecto)
std::string vsync_text = "VSYNC ON"; // Texto del estado V-Sync
// Variables para Delta Time
Uint64 last_frame_time = 0; // Tiempo del último frame en milisegundos
float delta_time = 0.0f; // Tiempo transcurrido desde el último frame en segundos
// Variables para Debug Display
bool show_debug = false; // Debug display desactivado por defecto
// Variable para direcci\u00f3n de gravedad
GravityDirection current_gravity = GravityDirection::DOWN; // Gravedad inicial hacia abajo
// Sistema de temas de colores (enum movido a defines.h)
ColorTheme current_theme = ColorTheme::SUNSET;
std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"};
struct ThemeColors {
// Colores de fondo (superior -> inferior)
float bg_top_r, bg_top_g, bg_top_b;
float bg_bottom_r, bg_bottom_g, bg_bottom_b;
// Paletas de colores para bolas (RGB 0-255)
int ball_colors[8][3]; // 8 colores por tema
};
ThemeColors themes[4] = {
// SUNSET: Naranjas, rojos, amarillos, rosas
{180.0f / 255.0f, 140.0f / 255.0f, 100.0f / 255.0f, // Fondo superior (naranja suave)
40.0f / 255.0f,
20.0f / 255.0f,
60.0f / 255.0f, // Fondo inferior (púrpura oscuro)
{{255, 140, 0}, {255, 69, 0}, {255, 215, 0}, {255, 20, 147}, {255, 99, 71}, {255, 165, 0}, {255, 192, 203}, {220, 20, 60}}},
// OCEAN: Azules, cianes, verdes agua, blancos
{100.0f / 255.0f, 150.0f / 255.0f, 200.0f / 255.0f, // Fondo superior (azul cielo)
20.0f / 255.0f,
40.0f / 255.0f,
80.0f / 255.0f, // Fondo inferior (azul marino)
{{0, 191, 255}, {0, 255, 255}, {32, 178, 170}, {176, 224, 230}, {70, 130, 180}, {0, 206, 209}, {240, 248, 255}, {64, 224, 208}}},
// NEON: Cian, magenta, verde lima, amarillo vibrante
{20.0f / 255.0f, 20.0f / 255.0f, 40.0f / 255.0f, // Fondo superior (negro azulado)
0.0f / 255.0f,
0.0f / 255.0f,
0.0f / 255.0f, // Fondo inferior (negro)
{{0, 255, 255}, {255, 0, 255}, {50, 205, 50}, {255, 255, 0}, {255, 20, 147}, {0, 255, 127}, {138, 43, 226}, {255, 69, 0}}},
// FOREST: Verdes, marrones, amarillos otoño
{144.0f / 255.0f, 238.0f / 255.0f, 144.0f / 255.0f, // Fondo superior (verde claro)
101.0f / 255.0f,
67.0f / 255.0f,
33.0f / 255.0f, // Fondo inferior (marrón tierra)
{{34, 139, 34}, {107, 142, 35}, {154, 205, 50}, {255, 215, 0}, {210, 180, 140}, {160, 82, 45}, {218, 165, 32}, {50, 205, 50}}}};
// Variables para Batch Rendering
std::vector<SDL_Vertex> batch_vertices;
std::vector<int> batch_indices;
// Función para renderizar fondo degradado
void renderGradientBackground() {
// Crear quad de pantalla completa con degradado
SDL_Vertex bg_vertices[4];
// Obtener colores del tema actual
ThemeColors &theme = themes[static_cast<int>(current_theme)];
float top_r = theme.bg_top_r;
float top_g = theme.bg_top_g;
float top_b = theme.bg_top_b;
float bottom_r = theme.bg_bottom_r;
float bottom_g = theme.bg_bottom_g;
float bottom_b = theme.bg_bottom_b;
// Vértice superior izquierdo
bg_vertices[0].position = {0, 0};
bg_vertices[0].tex_coord = {0.0f, 0.0f};
bg_vertices[0].color = {top_r, top_g, top_b, 1.0f};
// Vértice superior derecho
bg_vertices[1].position = {SCREEN_WIDTH, 0};
bg_vertices[1].tex_coord = {1.0f, 0.0f};
bg_vertices[1].color = {top_r, top_g, top_b, 1.0f};
// Vértice inferior derecho
bg_vertices[2].position = {SCREEN_WIDTH, SCREEN_HEIGHT};
bg_vertices[2].tex_coord = {1.0f, 1.0f};
bg_vertices[2].color = {bottom_r, bottom_g, bottom_b, 1.0f};
// Vértice inferior izquierdo
bg_vertices[3].position = {0, SCREEN_HEIGHT};
bg_vertices[3].tex_coord = {0.0f, 1.0f};
bg_vertices[3].color = {bottom_r, bottom_g, bottom_b, 1.0f};
// Índices para 2 triángulos
int bg_indices[6] = {0, 1, 2, 2, 3, 0};
// Renderizar sin textura (nullptr)
SDL_RenderGeometry(renderer, nullptr, bg_vertices, 4, bg_indices, 6);
} }
// Función para añadir un sprite al batch engine.run();
void addSpriteToBatch(float x, float y, float w, float h, Uint8 r, Uint8 g, Uint8 b) { engine.shutdown();
int vertex_index = static_cast<int>(batch_vertices.size());
// Crear 4 vértices para el quad (2 triángulos)
SDL_Vertex vertices[4];
// Convertir colores de Uint8 (0-255) a float (0.0-1.0)
float rf = r / 255.0f;
float gf = g / 255.0f;
float bf = b / 255.0f;
// Vértice superior izquierdo
vertices[0].position = {x, y};
vertices[0].tex_coord = {0.0f, 0.0f};
vertices[0].color = {rf, gf, bf, 1.0f};
// Vértice superior derecho
vertices[1].position = {x + w, y};
vertices[1].tex_coord = {1.0f, 0.0f};
vertices[1].color = {rf, gf, bf, 1.0f};
// Vértice inferior derecho
vertices[2].position = {x + w, y + h};
vertices[2].tex_coord = {1.0f, 1.0f};
vertices[2].color = {rf, gf, bf, 1.0f};
// Vértice inferior izquierdo
vertices[3].position = {x, y + h};
vertices[3].tex_coord = {0.0f, 1.0f};
vertices[3].color = {rf, gf, bf, 1.0f};
// Añadir vértices al batch
for (int i = 0; i < 4; i++) {
batch_vertices.push_back(vertices[i]);
}
// Añadir índices para 2 triángulos (6 índices por sprite)
// Triángulo 1: 0,1,2
batch_indices.push_back(vertex_index + 0);
batch_indices.push_back(vertex_index + 1);
batch_indices.push_back(vertex_index + 2);
// Triángulo 2: 2,3,0
batch_indices.push_back(vertex_index + 2);
batch_indices.push_back(vertex_index + 3);
batch_indices.push_back(vertex_index + 0);
}
// Establece el texto en pantalla mostrando el número de bolas actuales
void setText() {
const std::string TEXT_NUMBER = test[scenario] == 1 ? " PELOTA" : " PELOTAS";
text = std::to_string(test[scenario]) + TEXT_NUMBER;
const int TEXT_SIZE = static_cast<int>(text.size() * 8);
text_pos = SCREEN_WIDTH / 2 - TEXT_SIZE / 2;
text_init_time = SDL_GetTicks();
show_text = true;
}
// Inicializa las bolas según el escenario seleccionado
void initBalls(int value) {
balls.clear();
// Resetear gravedad al estado por defecto (DOWN) al cambiar escenario
current_gravity = GravityDirection::DOWN;
for (int i = 0; i < test.at(value); ++i) {
const int SIGN = ((rand() % 2) * 2) - 1; // Genera un signo aleatorio (+ o -)
const float X = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4); // Posición inicial en X
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGN; // Velocidad en X
const float VY = ((rand() % 60) - 30) * 0.1f; // Velocidad en Y
// Seleccionar color de la paleta del tema actual
ThemeColors &theme = themes[static_cast<int>(current_theme)];
int color_index = rand() % 8; // 8 colores por tema
const Color COLOR = {theme.ball_colors[color_index][0],
theme.ball_colors[color_index][1],
theme.ball_colors[color_index][2]};
balls.emplace_back(std::make_unique<Ball>(X, VX, VY, COLOR, texture, current_gravity));
}
setText(); // Actualiza el texto
}
// Aumenta la velocidad vertical de las bolas "hacia arriba"
void pushUpBalls() {
for (auto &ball : balls) {
const int SIGNO = ((rand() % 2) * 2) - 1;
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGNO;
const float VY = ((rand() % 40) * 0.1f) + 5;
ball->modVel(VX, -VY); // Modifica la velocidad de la bola
}
}
// Cambia la gravedad de todas las bolas
void switchBallsGravity() {
for (auto &ball : balls) {
ball->switchGravity();
}
}
// Cambia la direcci\u00f3n de gravedad de todas las bolas
void changeGravityDirection(GravityDirection new_direction) {
current_gravity = new_direction;
for (auto &ball : balls) {
ball->setGravityDirection(new_direction);
}
}
// Convierte dirección de gravedad a texto para debug
std::string gravityDirectionToString(GravityDirection direction) {
switch (direction) {
case GravityDirection::DOWN: return "DOWN";
case GravityDirection::UP: return "UP";
case GravityDirection::LEFT: return "LEFT";
case GravityDirection::RIGHT: return "RIGHT";
default: return "UNKNOWN";
}
}
// Alterna el estado del V-Sync
void toggleVSync() {
vsync_enabled = !vsync_enabled;
vsync_text = vsync_enabled ? "VSYNC ON" : "VSYNC OFF";
// Aplicar el cambio de V-Sync al renderizador
SDL_SetRenderVSync(renderer, vsync_enabled ? 1 : 0);
}
// Calcula el delta time entre frames
void calculateDeltaTime() {
Uint64 current_time = SDL_GetTicks();
// En el primer frame, inicializar el tiempo anterior
if (last_frame_time == 0) {
last_frame_time = current_time;
delta_time = 1.0f / 60.0f; // Asumir 60 FPS para el primer frame
return;
}
// Calcular delta time en segundos
delta_time = (current_time - last_frame_time) / 1000.0f;
last_frame_time = current_time;
// Limitar delta time para evitar saltos grandes (pausa larga, depuración, etc.)
if (delta_time > 0.05f) // Máximo 50ms (20 FPS mínimo)
{
delta_time = 1.0f / 60.0f; // Usar 60 FPS como fallback
}
}
// Inicializa SDL y configura los componentes principales
bool init() {
bool success = true;
// Inicializa SDL
if (!SDL_Init(SDL_INIT_VIDEO)) {
std::cout << "¡SDL no se pudo inicializar! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
} else {
// Crear ventana principal
window = SDL_CreateWindow(WINDOW_CAPTION, SCREEN_WIDTH * WINDOW_SIZE, SCREEN_HEIGHT * WINDOW_SIZE, SDL_WINDOW_OPENGL);
if (window == nullptr) {
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
} else {
// Crear renderizador
renderer = SDL_CreateRenderer(window, nullptr);
if (renderer == nullptr) {
std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
} else {
// Establecer color inicial del renderizador
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
// Establecer tamaño lógico para el renderizado
SDL_SetRenderLogicalPresentation(renderer, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
// Configurar V-Sync inicial
SDL_SetRenderVSync(renderer, vsync_enabled ? 1 : 0);
}
}
}
// Inicializar otros componentes
texture = std::make_shared<Texture>(renderer, "data/ball.png");
// ticks eliminado - delta time system se inicializa automáticamente
srand(static_cast<unsigned>(time(nullptr)));
dbg_init(renderer);
initBalls(scenario);
return success;
}
// Limpia todos los recursos y cierra SDL
void close() {
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
// Verifica los eventos en la cola
void checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
// Evento de salida
if (event.type == SDL_EVENT_QUIT) {
should_exit = true;
break;
}
// Procesar eventos de teclado
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) {
switch (event.key.key) {
case SDLK_ESCAPE:
should_exit = true;
break;
case SDLK_SPACE:
pushUpBalls();
break;
case SDLK_G:
switchBallsGravity();
break;
// Controles de direcci\u00f3n de gravedad con teclas de cursor
case SDLK_UP:
changeGravityDirection(GravityDirection::UP);
break;
case SDLK_DOWN:
changeGravityDirection(GravityDirection::DOWN);
break;
case SDLK_LEFT:
changeGravityDirection(GravityDirection::LEFT);
break;
case SDLK_RIGHT:
changeGravityDirection(GravityDirection::RIGHT);
break;
case SDLK_V:
toggleVSync();
break;
case SDLK_H:
show_debug = !show_debug;
break;
case SDLK_T:
// Ciclar al siguiente tema
current_theme = static_cast<ColorTheme>((static_cast<int>(current_theme) + 1) % 4);
initBalls(scenario); // Regenerar bolas con nueva paleta
break;
case SDLK_F1:
current_theme = ColorTheme::SUNSET;
initBalls(scenario);
break;
case SDLK_F2:
current_theme = ColorTheme::OCEAN;
initBalls(scenario);
break;
case SDLK_F3:
current_theme = ColorTheme::NEON;
initBalls(scenario);
break;
case SDLK_F4:
current_theme = ColorTheme::FOREST;
initBalls(scenario);
break;
case SDLK_1:
scenario = 0;
initBalls(scenario);
break;
case SDLK_2:
scenario = 1;
initBalls(scenario);
break;
case SDLK_3:
scenario = 2;
initBalls(scenario);
break;
case SDLK_4:
scenario = 3;
initBalls(scenario);
break;
case SDLK_5:
scenario = 4;
initBalls(scenario);
break;
case SDLK_6:
scenario = 5;
initBalls(scenario);
break;
case SDLK_7:
scenario = 6;
initBalls(scenario);
break;
case SDLK_8:
scenario = 7;
initBalls(scenario);
break;
}
}
}
}
// Actualiza la lógica del juego
void update() {
// Calcular FPS
fps_frame_count++;
Uint64 current_time = SDL_GetTicks();
if (current_time - fps_last_time >= 1000) // Actualizar cada segundo
{
fps_current = fps_frame_count;
fps_frame_count = 0;
fps_last_time = current_time;
fps_text = "FPS: " + std::to_string(fps_current);
}
// ¡DELTA TIME! Actualizar física siempre, usando tiempo transcurrido
for (auto &ball : balls) {
ball->update(delta_time); // Pasar delta time a cada pelota
}
// Actualizar texto (sin cambios en la lógica)
if (show_text) {
show_text = !(SDL_GetTicks() - text_init_time > TEXT_DURATION);
}
}
// Renderiza el contenido en la pantalla
void render() {
// Renderizar fondo degradado en lugar de color sólido
renderGradientBackground();
// Limpiar batches del frame anterior
batch_vertices.clear();
batch_indices.clear();
// Recopilar datos de todas las bolas para batch rendering
for (auto &ball : balls) {
// En lugar de ball->render(), obtener datos para batch
SDL_FRect pos = ball->getPosition();
Color color = ball->getColor();
addSpriteToBatch(pos.x, pos.y, pos.w, pos.h, color.r, color.g, color.b);
}
// Renderizar todas las bolas en una sola llamada
if (!batch_vertices.empty()) {
SDL_RenderGeometry(renderer, texture->getSDLTexture(), batch_vertices.data(), static_cast<int>(batch_vertices.size()), batch_indices.data(), static_cast<int>(batch_indices.size()));
}
if (show_text) {
dbg_print(text_pos, 8, text.c_str(), 255, 255, 255);
// Mostrar nombre del tema en castellano debajo del número de pelotas
std::string theme_names_es[] = {"ATARDECER", "OCEANO", "NEON", "BOSQUE"};
std::string theme_name = theme_names_es[static_cast<int>(current_theme)];
int theme_text_width = static_cast<int>(theme_name.length() * 8); // 8 píxeles por carácter
int theme_x = (SCREEN_WIDTH - theme_text_width) / 2; // Centrar horizontalmente
// Colores acordes a cada tema
int theme_colors[][3] = {
{255, 140, 60}, // ATARDECER: Naranja cálido
{80, 200, 255}, // OCEANO: Azul océano
{255, 60, 255}, // NEON: Magenta brillante
{100, 255, 100} // BOSQUE: Verde natural
};
int theme_idx = static_cast<int>(current_theme);
dbg_print(theme_x, 24, theme_name.c_str(), theme_colors[theme_idx][0], theme_colors[theme_idx][1], theme_colors[theme_idx][2]);
}
// Debug display (solo si está activado con tecla H)
if (show_debug) {
// Mostrar contador de FPS en esquina superior derecha
int fps_text_width = static_cast<int>(fps_text.length() * 8); // 8 píxeles por carácter
int fps_x = SCREEN_WIDTH - fps_text_width - 8; // 8 píxeles de margen
dbg_print(fps_x, 8, fps_text.c_str(), 255, 255, 0); // Amarillo para distinguir
// Mostrar estado V-Sync en esquina superior izquierda
dbg_print(8, 8, vsync_text.c_str(), 0, 255, 255); // Cian para distinguir
// Debug: Mostrar valores de la primera pelota (si existe)
if (!balls.empty()) {
// Línea 1: Gravedad (solo números enteros)
int grav_int = static_cast<int>(balls[0]->getGravityForce());
std::string grav_text = "GRAV " + std::to_string(grav_int);
dbg_print(8, 24, grav_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 2: Velocidad Y (solo números enteros)
int vy_int = static_cast<int>(balls[0]->getVelocityY());
std::string vy_text = "VY " + std::to_string(vy_int);
dbg_print(8, 32, vy_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 3: Estado superficie
std::string surface_text = balls[0]->isOnSurface() ? "SURFACE YES" : "SURFACE NO";
dbg_print(8, 40, surface_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 4: Coeficiente de rebote (loss)
float loss_val = balls[0]->getLossCoefficient();
std::string loss_text = "LOSS " + std::to_string(loss_val).substr(0, 4); // Solo 2 decimales
dbg_print(8, 48, loss_text.c_str(), 255, 0, 255); // Magenta para debug
// Línea 5: Dirección de gravedad
std::string gravity_dir_text = "GRAVITY " + gravityDirectionToString(current_gravity);
dbg_print(8, 56, gravity_dir_text.c_str(), 255, 255, 0); // Amarillo para dirección
}
// Debug: Mostrar tema actual
std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"};
std::string theme_text = "THEME " + theme_names[static_cast<int>(current_theme)];
dbg_print(8, 64, theme_text.c_str(), 255, 255, 128); // Amarillo claro para tema
}
SDL_RenderPresent(renderer);
}
// Función principal
int main(int argc, char *args[]) {
if (!init()) {
std::cout << "Ocurrió un error durante la inicialización." << std::endl;
return 1;
}
while (!should_exit) {
// 1. Calcular delta time antes de actualizar la lógica
calculateDeltaTime();
// 2. Actualizar lógica del juego con delta time
update();
// 3. Procesar eventos de entrada
checkEvents();
// 4. Renderizar la escena
render();
}
close();
return 0; return 0;
} }

View File

@@ -1,17 +0,0 @@
#include <iostream>
#include "engine.h"
int main() {
Engine engine;
if (!engine.initialize()) {
std::cout << "¡Error al inicializar el engine!" << std::endl;
return -1;
}
engine.run();
engine.shutdown();
return 0;
}