ja guarda la configuracio
This commit is contained in:
@@ -34,7 +34,9 @@ configure_file(${CMAKE_SOURCE_DIR}/source/project.h.in ${CMAKE_BINARY_DIR}/proje
|
||||
# --- LISTA DE FUENTES ---
|
||||
set(APP_SOURCES
|
||||
source/main.cpp
|
||||
source/core/system/director.cpp
|
||||
source/core/rendering/sdl_manager.cpp
|
||||
source/game/options.cpp
|
||||
source/game/joc_asteroides.cpp
|
||||
source/core/rendering/primitives.cpp
|
||||
)
|
||||
|
||||
@@ -3,210 +3,287 @@
|
||||
|
||||
#include "sdl_manager.hpp"
|
||||
#include "core/defaults.hpp"
|
||||
#include "game/options.hpp"
|
||||
#include "project.h"
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
|
||||
SDLManager::SDLManager()
|
||||
: finestra_(nullptr)
|
||||
, renderer_(nullptr)
|
||||
, current_width_(Defaults::Window::WIDTH)
|
||||
, current_height_(Defaults::Window::HEIGHT)
|
||||
, is_fullscreen_(false)
|
||||
, max_width_(1920)
|
||||
, max_height_(1080)
|
||||
{
|
||||
// Inicialitzar SDL3
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
||||
std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl;
|
||||
return;
|
||||
}
|
||||
: finestra_(nullptr), renderer_(nullptr),
|
||||
current_width_(Defaults::Window::WIDTH),
|
||||
current_height_(Defaults::Window::HEIGHT), is_fullscreen_(false),
|
||||
max_width_(1920), max_height_(1080) {
|
||||
// Inicialitzar SDL3
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
||||
std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcular mida màxima des del display
|
||||
calculateMaxWindowSize();
|
||||
// Calcular mida màxima des del display
|
||||
calculateMaxWindowSize();
|
||||
|
||||
// Construir títol dinàmic igual que en pollo
|
||||
std::string window_title = std::format("{} v{} ({})",
|
||||
Project::LONG_NAME,
|
||||
Project::VERSION,
|
||||
Project::COPYRIGHT
|
||||
);
|
||||
// Construir títol dinàmic igual que en pollo
|
||||
std::string window_title = std::format("{} v{} ({})", Project::LONG_NAME,
|
||||
Project::VERSION, Project::COPYRIGHT);
|
||||
|
||||
// Crear finestra CENTRADA (SDL ho fa automàticament amb CENTERED)
|
||||
finestra_ = SDL_CreateWindow(
|
||||
window_title.c_str(),
|
||||
current_width_,
|
||||
current_height_,
|
||||
SDL_WINDOW_RESIZABLE // Permetre resize manual també
|
||||
);
|
||||
// Crear finestra CENTRADA (SDL ho fa automàticament amb CENTERED)
|
||||
finestra_ =
|
||||
SDL_CreateWindow(window_title.c_str(), current_width_, current_height_,
|
||||
SDL_WINDOW_RESIZABLE // Permetre resize manual també
|
||||
);
|
||||
|
||||
if (!finestra_) {
|
||||
std::cerr << "Error creant finestra: " << SDL_GetError() << std::endl;
|
||||
SDL_Quit();
|
||||
return;
|
||||
}
|
||||
if (!finestra_) {
|
||||
std::cerr << "Error creant finestra: " << SDL_GetError() << std::endl;
|
||||
SDL_Quit();
|
||||
return;
|
||||
}
|
||||
|
||||
// IMPORTANT: Centrar explícitament la finestra
|
||||
SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
|
||||
// IMPORTANT: Centrar explícitament la finestra
|
||||
SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED,
|
||||
SDL_WINDOWPOS_CENTERED);
|
||||
|
||||
// Crear renderer amb acceleració
|
||||
renderer_ = SDL_CreateRenderer(finestra_, nullptr);
|
||||
// Crear renderer amb acceleració
|
||||
renderer_ = SDL_CreateRenderer(finestra_, nullptr);
|
||||
|
||||
if (!renderer_) {
|
||||
std::cerr << "Error creant renderer: " << SDL_GetError() << std::endl;
|
||||
SDL_DestroyWindow(finestra_);
|
||||
SDL_Quit();
|
||||
return;
|
||||
}
|
||||
if (!renderer_) {
|
||||
std::cerr << "Error creant renderer: " << SDL_GetError() << std::endl;
|
||||
SDL_DestroyWindow(finestra_);
|
||||
SDL_Quit();
|
||||
return;
|
||||
}
|
||||
|
||||
// CRÍTIC: Configurar viewport scaling
|
||||
updateLogicalPresentation();
|
||||
// CRÍTIC: Configurar viewport scaling
|
||||
updateLogicalPresentation();
|
||||
|
||||
std::cout << "SDL3 inicialitzat: " << current_width_ << "x" << current_height_
|
||||
<< " (logic: " << Defaults::Game::WIDTH << "x" << Defaults::Game::HEIGHT << ")" << std::endl;
|
||||
std::cout << "SDL3 inicialitzat: " << current_width_ << "x" << current_height_
|
||||
<< " (logic: " << Defaults::Game::WIDTH << "x"
|
||||
<< Defaults::Game::HEIGHT << ")" << std::endl;
|
||||
}
|
||||
|
||||
// Constructor amb configuració
|
||||
SDLManager::SDLManager(int width, int height, bool fullscreen)
|
||||
: finestra_(nullptr), renderer_(nullptr), current_width_(width),
|
||||
current_height_(height), is_fullscreen_(fullscreen), max_width_(1920),
|
||||
max_height_(1080) {
|
||||
// Inicialitzar SDL3
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
||||
std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
// Calcular mida màxima des del display
|
||||
calculateMaxWindowSize();
|
||||
|
||||
// Construir títol dinàmic
|
||||
std::string window_title = std::format("{} v{} ({})", Project::LONG_NAME,
|
||||
Project::VERSION, Project::COPYRIGHT);
|
||||
|
||||
// Configurar flags de la finestra
|
||||
SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE;
|
||||
if (is_fullscreen_) {
|
||||
flags = static_cast<SDL_WindowFlags>(flags | SDL_WINDOW_FULLSCREEN);
|
||||
}
|
||||
|
||||
// Crear finestra
|
||||
finestra_ = SDL_CreateWindow(window_title.c_str(), current_width_,
|
||||
current_height_, flags);
|
||||
|
||||
if (!finestra_) {
|
||||
std::cerr << "Error creant finestra: " << SDL_GetError() << std::endl;
|
||||
SDL_Quit();
|
||||
return;
|
||||
}
|
||||
|
||||
// Centrar explícitament la finestra (si no és fullscreen)
|
||||
if (!is_fullscreen_) {
|
||||
SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED,
|
||||
SDL_WINDOWPOS_CENTERED);
|
||||
}
|
||||
|
||||
// Crear renderer amb acceleració
|
||||
renderer_ = SDL_CreateRenderer(finestra_, nullptr);
|
||||
|
||||
if (!renderer_) {
|
||||
std::cerr << "Error creant renderer: " << SDL_GetError() << std::endl;
|
||||
SDL_DestroyWindow(finestra_);
|
||||
SDL_Quit();
|
||||
return;
|
||||
}
|
||||
|
||||
// Configurar viewport scaling
|
||||
updateLogicalPresentation();
|
||||
|
||||
std::cout << "SDL3 inicialitzat: " << current_width_ << "x" << current_height_
|
||||
<< " (logic: " << Defaults::Game::WIDTH << "x"
|
||||
<< Defaults::Game::HEIGHT << ")";
|
||||
if (is_fullscreen_) {
|
||||
std::cout << " [FULLSCREEN]";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
SDLManager::~SDLManager() {
|
||||
if (renderer_) {
|
||||
SDL_DestroyRenderer(renderer_);
|
||||
renderer_ = nullptr;
|
||||
}
|
||||
if (renderer_) {
|
||||
SDL_DestroyRenderer(renderer_);
|
||||
renderer_ = nullptr;
|
||||
}
|
||||
|
||||
if (finestra_) {
|
||||
SDL_DestroyWindow(finestra_);
|
||||
finestra_ = nullptr;
|
||||
}
|
||||
if (finestra_) {
|
||||
SDL_DestroyWindow(finestra_);
|
||||
finestra_ = nullptr;
|
||||
}
|
||||
|
||||
SDL_Quit();
|
||||
std::cout << "SDL3 netejat correctament" << std::endl;
|
||||
SDL_Quit();
|
||||
std::cout << "SDL3 netejat correctament" << std::endl;
|
||||
}
|
||||
|
||||
void SDLManager::calculateMaxWindowSize() {
|
||||
SDL_DisplayID display = SDL_GetPrimaryDisplay();
|
||||
const SDL_DisplayMode* mode = SDL_GetCurrentDisplayMode(display);
|
||||
SDL_DisplayID display = SDL_GetPrimaryDisplay();
|
||||
const SDL_DisplayMode *mode = SDL_GetCurrentDisplayMode(display);
|
||||
|
||||
if (mode) {
|
||||
// Deixar marge de 100px per a decoracions de l'OS
|
||||
max_width_ = mode->w - 100;
|
||||
max_height_ = mode->h - 100;
|
||||
std::cout << "Display detectat: " << mode->w << "x" << mode->h
|
||||
<< " (max finestra: " << max_width_ << "x" << max_height_ << ")" << std::endl;
|
||||
} else {
|
||||
// Fallback conservador
|
||||
max_width_ = 1920;
|
||||
max_height_ = 1080;
|
||||
std::cerr << "No s'ha pogut detectar el display, usant fallback: "
|
||||
<< max_width_ << "x" << max_height_ << std::endl;
|
||||
}
|
||||
if (mode) {
|
||||
// Deixar marge de 100px per a decoracions de l'OS
|
||||
max_width_ = mode->w - 100;
|
||||
max_height_ = mode->h - 100;
|
||||
std::cout << "Display detectat: " << mode->w << "x" << mode->h
|
||||
<< " (max finestra: " << max_width_ << "x" << max_height_ << ")"
|
||||
<< std::endl;
|
||||
} else {
|
||||
// Fallback conservador
|
||||
max_width_ = 1920;
|
||||
max_height_ = 1080;
|
||||
std::cerr << "No s'ha pogut detectar el display, usant fallback: "
|
||||
<< max_width_ << "x" << max_height_ << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void SDLManager::updateLogicalPresentation() {
|
||||
// AIXÒ ÉS LA MÀGIA: El joc SEMPRE dibuixa en 640x480,
|
||||
// SDL escala automàticament a la mida física de la finestra
|
||||
SDL_SetRenderLogicalPresentation(
|
||||
renderer_,
|
||||
Defaults::Game::WIDTH, // 640 (lògic)
|
||||
Defaults::Game::HEIGHT, // 480 (lògic)
|
||||
SDL_LOGICAL_PRESENTATION_LETTERBOX // Mantenir aspect ratio 4:3
|
||||
);
|
||||
// AIXÒ ÉS LA MÀGIA: El joc SEMPRE dibuixa en 640x480,
|
||||
// SDL escala automàticament a la mida física de la finestra
|
||||
SDL_SetRenderLogicalPresentation(
|
||||
renderer_,
|
||||
Defaults::Game::WIDTH, // 640 (lògic)
|
||||
Defaults::Game::HEIGHT, // 480 (lògic)
|
||||
SDL_LOGICAL_PRESENTATION_LETTERBOX // Mantenir aspect ratio 4:3
|
||||
);
|
||||
}
|
||||
|
||||
void SDLManager::increaseWindowSize() {
|
||||
if (is_fullscreen_) return; // No operar en fullscreen
|
||||
if (is_fullscreen_)
|
||||
return; // No operar en fullscreen
|
||||
|
||||
int new_width = current_width_ + Defaults::Window::SIZE_INCREMENT;
|
||||
int new_height = current_height_ + Defaults::Window::SIZE_INCREMENT;
|
||||
int new_width = current_width_ + Defaults::Window::SIZE_INCREMENT;
|
||||
int new_height = current_height_ + Defaults::Window::SIZE_INCREMENT;
|
||||
|
||||
// Clamp a màxim
|
||||
new_width = std::min(new_width, max_width_);
|
||||
new_height = std::min(new_height, max_height_);
|
||||
// Clamp a màxim
|
||||
new_width = std::min(new_width, max_width_);
|
||||
new_height = std::min(new_height, max_height_);
|
||||
|
||||
if (new_width != current_width_ || new_height != current_height_) {
|
||||
applyWindowSize(new_width, new_height);
|
||||
std::cout << "F2: Finestra augmentada a " << new_width << "x" << new_height << std::endl;
|
||||
}
|
||||
if (new_width != current_width_ || new_height != current_height_) {
|
||||
applyWindowSize(new_width, new_height);
|
||||
|
||||
// Persistir canvis a Options (es guardarà a config.yaml al tancar)
|
||||
Options::window.width = current_width_;
|
||||
Options::window.height = current_height_;
|
||||
|
||||
std::cout << "F2: Finestra augmentada a " << new_width << "x" << new_height
|
||||
<< std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void SDLManager::decreaseWindowSize() {
|
||||
if (is_fullscreen_) return;
|
||||
if (is_fullscreen_)
|
||||
return;
|
||||
|
||||
int new_width = current_width_ - Defaults::Window::SIZE_INCREMENT;
|
||||
int new_height = current_height_ - Defaults::Window::SIZE_INCREMENT;
|
||||
int new_width = current_width_ - Defaults::Window::SIZE_INCREMENT;
|
||||
int new_height = current_height_ - Defaults::Window::SIZE_INCREMENT;
|
||||
|
||||
// Clamp a mínim
|
||||
new_width = std::max(new_width, Defaults::Window::MIN_WIDTH);
|
||||
new_height = std::max(new_height, Defaults::Window::MIN_HEIGHT);
|
||||
// Clamp a mínim
|
||||
new_width = std::max(new_width, Defaults::Window::MIN_WIDTH);
|
||||
new_height = std::max(new_height, Defaults::Window::MIN_HEIGHT);
|
||||
|
||||
if (new_width != current_width_ || new_height != current_height_) {
|
||||
applyWindowSize(new_width, new_height);
|
||||
std::cout << "F1: Finestra reduïda a " << new_width << "x" << new_height << std::endl;
|
||||
}
|
||||
if (new_width != current_width_ || new_height != current_height_) {
|
||||
applyWindowSize(new_width, new_height);
|
||||
|
||||
// Persistir canvis a Options (es guardarà a config.yaml al tancar)
|
||||
Options::window.width = current_width_;
|
||||
Options::window.height = current_height_;
|
||||
|
||||
std::cout << "F1: Finestra reduïda a " << new_width << "x" << new_height
|
||||
<< std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void SDLManager::applyWindowSize(int new_width, int new_height) {
|
||||
// Obtenir posició actual ABANS del resize
|
||||
int old_x, old_y;
|
||||
SDL_GetWindowPosition(finestra_, &old_x, &old_y);
|
||||
// Obtenir posició actual ABANS del resize
|
||||
int old_x, old_y;
|
||||
SDL_GetWindowPosition(finestra_, &old_x, &old_y);
|
||||
|
||||
int old_width = current_width_;
|
||||
int old_height = current_height_;
|
||||
int old_width = current_width_;
|
||||
int old_height = current_height_;
|
||||
|
||||
// Actualitzar mida
|
||||
SDL_SetWindowSize(finestra_, new_width, new_height);
|
||||
current_width_ = new_width;
|
||||
current_height_ = new_height;
|
||||
// Actualitzar mida
|
||||
SDL_SetWindowSize(finestra_, new_width, new_height);
|
||||
current_width_ = new_width;
|
||||
current_height_ = new_height;
|
||||
|
||||
// CENTRADO INTEL·LIGENT (algoritme de pollo)
|
||||
// Calcular nova posició per mantenir la finestra centrada sobre si mateixa
|
||||
int delta_width = old_width - new_width;
|
||||
int delta_height = old_height - new_height;
|
||||
// CENTRADO INTEL·LIGENT (algoritme de pollo)
|
||||
// Calcular nova posició per mantenir la finestra centrada sobre si mateixa
|
||||
int delta_width = old_width - new_width;
|
||||
int delta_height = old_height - new_height;
|
||||
|
||||
int new_x = old_x + (delta_width / 2);
|
||||
int new_y = old_y + (delta_height / 2);
|
||||
int new_x = old_x + (delta_width / 2);
|
||||
int new_y = old_y + (delta_height / 2);
|
||||
|
||||
// Evitar que la finestra surti de la pantalla
|
||||
constexpr int TITLEBAR_HEIGHT = 35; // Alçada aproximada de la barra de títol
|
||||
new_x = std::max(new_x, 0);
|
||||
new_y = std::max(new_y, TITLEBAR_HEIGHT);
|
||||
// Evitar que la finestra surti de la pantalla
|
||||
constexpr int TITLEBAR_HEIGHT = 35; // Alçada aproximada de la barra de títol
|
||||
new_x = std::max(new_x, 0);
|
||||
new_y = std::max(new_y, TITLEBAR_HEIGHT);
|
||||
|
||||
SDL_SetWindowPosition(finestra_, new_x, new_y);
|
||||
SDL_SetWindowPosition(finestra_, new_x, new_y);
|
||||
|
||||
// NO cal actualitzar el logical presentation aquí,
|
||||
// SDL ho maneja automàticament
|
||||
// NO cal actualitzar el logical presentation aquí,
|
||||
// SDL ho maneja automàticament
|
||||
}
|
||||
|
||||
void SDLManager::toggleFullscreen() {
|
||||
is_fullscreen_ = !is_fullscreen_;
|
||||
SDL_SetWindowFullscreen(finestra_, is_fullscreen_);
|
||||
is_fullscreen_ = !is_fullscreen_;
|
||||
SDL_SetWindowFullscreen(finestra_, is_fullscreen_);
|
||||
|
||||
std::cout << "F3: Fullscreen " << (is_fullscreen_ ? "activat" : "desactivat") << std::endl;
|
||||
// Persistir canvis a Options (es guardarà a config.yaml al tancar)
|
||||
Options::window.fullscreen = is_fullscreen_;
|
||||
|
||||
// En fullscreen, SDL gestiona tot automàticament
|
||||
// En sortir, restaura la mida anterior
|
||||
std::cout << "F3: Fullscreen " << (is_fullscreen_ ? "activat" : "desactivat")
|
||||
<< std::endl;
|
||||
|
||||
// En fullscreen, SDL gestiona tot automàticament
|
||||
// En sortir, restaura la mida anterior
|
||||
}
|
||||
|
||||
bool SDLManager::handleWindowEvent(const SDL_Event& event) {
|
||||
if (event.type == SDL_EVENT_WINDOW_RESIZED) {
|
||||
// Usuari ha redimensionat manualment (arrossegar vora)
|
||||
// Actualitzar el nostre tracking
|
||||
SDL_GetWindowSize(finestra_, ¤t_width_, ¤t_height_);
|
||||
std::cout << "Finestra redimensionada manualment a "
|
||||
<< current_width_ << "x" << current_height_ << std::endl;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
bool SDLManager::handleWindowEvent(const SDL_Event &event) {
|
||||
if (event.type == SDL_EVENT_WINDOW_RESIZED) {
|
||||
// Usuari ha redimensionat manualment (arrossegar vora)
|
||||
// Actualitzar el nostre tracking
|
||||
SDL_GetWindowSize(finestra_, ¤t_width_, ¤t_height_);
|
||||
std::cout << "Finestra redimensionada manualment a " << current_width_
|
||||
<< "x" << current_height_ << std::endl;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SDLManager::neteja(uint8_t r, uint8_t g, uint8_t b) {
|
||||
if (!renderer_) return;
|
||||
if (!renderer_)
|
||||
return;
|
||||
|
||||
SDL_SetRenderDrawColor(renderer_, r, g, b, 255);
|
||||
SDL_RenderClear(renderer_);
|
||||
SDL_SetRenderDrawColor(renderer_, r, g, b, 255);
|
||||
SDL_RenderClear(renderer_);
|
||||
}
|
||||
|
||||
void SDLManager::presenta() {
|
||||
if (!renderer_) return;
|
||||
if (!renderer_)
|
||||
return;
|
||||
|
||||
SDL_RenderPresent(renderer_);
|
||||
SDL_RenderPresent(renderer_);
|
||||
}
|
||||
|
||||
@@ -9,41 +9,44 @@
|
||||
|
||||
class SDLManager {
|
||||
public:
|
||||
SDLManager();
|
||||
~SDLManager();
|
||||
SDLManager(); // Constructor per defecte (usa Defaults::)
|
||||
SDLManager(int width, int height,
|
||||
bool fullscreen); // Constructor amb configuració
|
||||
~SDLManager();
|
||||
|
||||
// No permetre còpia ni assignació
|
||||
SDLManager(const SDLManager&) = delete;
|
||||
SDLManager& operator=(const SDLManager&) = delete;
|
||||
// No permetre còpia ni assignació
|
||||
SDLManager(const SDLManager &) = delete;
|
||||
SDLManager &operator=(const SDLManager &) = delete;
|
||||
|
||||
// [NUEVO] Gestió de finestra dinàmica
|
||||
void increaseWindowSize(); // F2: +100px
|
||||
void decreaseWindowSize(); // F1: -100px
|
||||
void toggleFullscreen(); // F3
|
||||
bool handleWindowEvent(const SDL_Event& event); // Per a SDL_EVENT_WINDOW_RESIZED
|
||||
// [NUEVO] Gestió de finestra dinàmica
|
||||
void increaseWindowSize(); // F2: +100px
|
||||
void decreaseWindowSize(); // F1: -100px
|
||||
void toggleFullscreen(); // F3
|
||||
bool
|
||||
handleWindowEvent(const SDL_Event &event); // Per a SDL_EVENT_WINDOW_RESIZED
|
||||
|
||||
// Funcions principals (renderitzat)
|
||||
void neteja(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0);
|
||||
void presenta();
|
||||
// Funcions principals (renderitzat)
|
||||
void neteja(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0);
|
||||
void presenta();
|
||||
|
||||
// Getters
|
||||
SDL_Renderer* obte_renderer() { return renderer_; }
|
||||
// Getters
|
||||
SDL_Renderer *obte_renderer() { return renderer_; }
|
||||
|
||||
private:
|
||||
SDL_Window* finestra_;
|
||||
SDL_Renderer* renderer_;
|
||||
SDL_Window *finestra_;
|
||||
SDL_Renderer *renderer_;
|
||||
|
||||
// [NUEVO] Estat de la finestra
|
||||
int current_width_; // Mida física actual
|
||||
int current_height_;
|
||||
bool is_fullscreen_;
|
||||
int max_width_; // Calculat des del display
|
||||
int max_height_;
|
||||
// [NUEVO] Estat de la finestra
|
||||
int current_width_; // Mida física actual
|
||||
int current_height_;
|
||||
bool is_fullscreen_;
|
||||
int max_width_; // Calculat des del display
|
||||
int max_height_;
|
||||
|
||||
// [NUEVO] Funcions internes
|
||||
void calculateMaxWindowSize(); // Llegir resolució del display
|
||||
void applyWindowSize(int width, int height); // Canviar mida + centrar
|
||||
void updateLogicalPresentation(); // Actualitzar viewport
|
||||
// [NUEVO] Funcions internes
|
||||
void calculateMaxWindowSize(); // Llegir resolució del display
|
||||
void applyWindowSize(int width, int height); // Canviar mida + centrar
|
||||
void updateLogicalPresentation(); // Actualitzar viewport
|
||||
};
|
||||
|
||||
#endif // SDL_MANAGER_HPP
|
||||
|
||||
15659
source/external/fkyaml_node.hpp
vendored
Normal file
15659
source/external/fkyaml_node.hpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@@ -6,21 +6,21 @@
|
||||
// Permet usar Constants::MARGE_ESQ en lloc de Defaults::Game::MARGIN_LEFT
|
||||
|
||||
namespace Constants {
|
||||
// Marges de l'àrea de joc
|
||||
constexpr int MARGE_DALT = Defaults::Game::MARGIN_TOP;
|
||||
constexpr int MARGE_BAIX = Defaults::Game::MARGIN_BOTTOM;
|
||||
constexpr int MARGE_ESQ = Defaults::Game::MARGIN_LEFT;
|
||||
constexpr int MARGE_DRET = Defaults::Game::MARGIN_RIGHT;
|
||||
// Marges de l'àrea de joc
|
||||
constexpr int MARGE_DALT = Defaults::Game::MARGIN_TOP;
|
||||
constexpr int MARGE_BAIX = Defaults::Game::MARGIN_BOTTOM;
|
||||
constexpr int MARGE_ESQ = Defaults::Game::MARGIN_LEFT;
|
||||
constexpr int MARGE_DRET = Defaults::Game::MARGIN_RIGHT;
|
||||
|
||||
// Límits de polígons i objectes
|
||||
constexpr int MAX_IPUNTS = Defaults::Entities::MAX_IPUNTS;
|
||||
constexpr int MAX_ORNIS = Defaults::Entities::MAX_ORNIS;
|
||||
constexpr int MAX_BALES = Defaults::Entities::MAX_BALES;
|
||||
// Límits de polígons i objectes
|
||||
constexpr int MAX_IPUNTS = Defaults::Entities::MAX_IPUNTS;
|
||||
constexpr int MAX_ORNIS = Defaults::Entities::MAX_ORNIS;
|
||||
constexpr int MAX_BALES = Defaults::Entities::MAX_BALES;
|
||||
|
||||
// Velocitats (valors legacy del codi Pascal)
|
||||
constexpr int VELOCITAT = static_cast<int>(Defaults::Physics::ENEMY_SPEED);
|
||||
constexpr int VELOCITAT_MAX = static_cast<int>(Defaults::Physics::BULLET_SPEED);
|
||||
// Velocitats (valors legacy del codi Pascal)
|
||||
constexpr int VELOCITAT = static_cast<int>(Defaults::Physics::ENEMY_SPEED);
|
||||
constexpr int VELOCITAT_MAX = static_cast<int>(Defaults::Physics::BULLET_SPEED);
|
||||
|
||||
// Matemàtiques
|
||||
constexpr float PI = Defaults::Math::PI;
|
||||
}
|
||||
// Matemàtiques
|
||||
constexpr float PI = Defaults::Math::PI;
|
||||
} // namespace Constants
|
||||
|
||||
@@ -5,423 +5,419 @@
|
||||
#include "joc_asteroides.hpp"
|
||||
#include "core/rendering/primitives.hpp"
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
|
||||
JocAsteroides::JocAsteroides(SDL_Renderer* renderer)
|
||||
: renderer_(renderer), itocado_(0) {
|
||||
}
|
||||
JocAsteroides::JocAsteroides(SDL_Renderer *renderer)
|
||||
: renderer_(renderer), itocado_(0) {}
|
||||
|
||||
void JocAsteroides::inicialitzar() {
|
||||
// Inicialitzar generador de números aleatoris
|
||||
// Basat en el codi Pascal original: line 376
|
||||
std::srand(static_cast<unsigned>(std::time(nullptr)));
|
||||
// Inicialitzar generador de números aleatoris
|
||||
// Basat en el codi Pascal original: line 376
|
||||
std::srand(static_cast<unsigned>(std::time(nullptr)));
|
||||
|
||||
// Inicialització de la nau (triangle)
|
||||
// Basat en el codi Pascal original: lines 380-384
|
||||
nau_.p1.r = 12.0f;
|
||||
nau_.p1.angle = 3.0f * Constants::PI / 2.0f; // Apunta amunt (270°)
|
||||
// Inicialització de la nau (triangle)
|
||||
// Basat en el codi Pascal original: lines 380-384
|
||||
nau_.p1.r = 12.0f;
|
||||
nau_.p1.angle = 3.0f * Constants::PI / 2.0f; // Apunta amunt (270°)
|
||||
|
||||
nau_.p2.r = 12.0f;
|
||||
nau_.p2.angle = Constants::PI / 4.0f; // 45°
|
||||
nau_.p2.r = 12.0f;
|
||||
nau_.p2.angle = Constants::PI / 4.0f; // 45°
|
||||
|
||||
nau_.p3.r = 12.0f;
|
||||
nau_.p3.angle = (3.0f * Constants::PI) / 4.0f; // 135°
|
||||
nau_.p3.r = 12.0f;
|
||||
nau_.p3.angle = (3.0f * Constants::PI) / 4.0f; // 135°
|
||||
|
||||
nau_.angle = 0.0f;
|
||||
nau_.centre.x = 320.0f;
|
||||
nau_.centre.y = 240.0f;
|
||||
nau_.velocitat = 0.0f;
|
||||
nau_.angle = 0.0f;
|
||||
nau_.centre.x = 320.0f;
|
||||
nau_.centre.y = 240.0f;
|
||||
nau_.velocitat = 0.0f;
|
||||
|
||||
// Inicialitzar estat de col·lisió
|
||||
itocado_ = 0;
|
||||
// Inicialitzar estat de col·lisió
|
||||
itocado_ = 0;
|
||||
|
||||
// Inicialitzar enemics (ORNIs)
|
||||
// Basat en el codi Pascal original: line 386
|
||||
for (int i = 0; i < Constants::MAX_ORNIS; i++) {
|
||||
// Crear pentàgon regular (5 costats, radi 20)
|
||||
crear_poligon_regular(orni_[i], 5, 20.0f);
|
||||
// Inicialitzar enemics (ORNIs)
|
||||
// Basat en el codi Pascal original: line 386
|
||||
for (int i = 0; i < Constants::MAX_ORNIS; i++) {
|
||||
// Crear pentàgon regular (5 costats, radi 20)
|
||||
crear_poligon_regular(orni_[i], 5, 20.0f);
|
||||
|
||||
// Posició aleatòria dins de l'àrea de joc
|
||||
orni_[i].centre.x = static_cast<float>((std::rand() % 580) + 30); // 30-610
|
||||
orni_[i].centre.y = static_cast<float>((std::rand() % 420) + 30); // 30-450
|
||||
// Posició aleatòria dins de l'àrea de joc
|
||||
orni_[i].centre.x = static_cast<float>((std::rand() % 580) + 30); // 30-610
|
||||
orni_[i].centre.y = static_cast<float>((std::rand() % 420) + 30); // 30-450
|
||||
|
||||
// Angle aleatori
|
||||
orni_[i].angle = (std::rand() % 360) * Constants::PI / 180.0f;
|
||||
// Angle aleatori
|
||||
orni_[i].angle = (std::rand() % 360) * Constants::PI / 180.0f;
|
||||
|
||||
// Està actiu
|
||||
orni_[i].esta = true;
|
||||
}
|
||||
// Està actiu
|
||||
orni_[i].esta = true;
|
||||
}
|
||||
|
||||
// Inicialitzar bales
|
||||
// Basat en el codi Pascal original: inicialment inactives
|
||||
for (int i = 0; i < Constants::MAX_BALES; i++) {
|
||||
// Crear pentàgon petit (5 costats, radi 5)
|
||||
crear_poligon_regular(bales_[i], 5, 5.0f);
|
||||
// Inicialitzar bales
|
||||
// Basat en el codi Pascal original: inicialment inactives
|
||||
for (int i = 0; i < Constants::MAX_BALES; i++) {
|
||||
// Crear pentàgon petit (5 costats, radi 5)
|
||||
crear_poligon_regular(bales_[i], 5, 5.0f);
|
||||
|
||||
// Inicialment inactiva
|
||||
bales_[i].esta = false;
|
||||
}
|
||||
// Inicialment inactiva
|
||||
bales_[i].esta = false;
|
||||
}
|
||||
}
|
||||
|
||||
void JocAsteroides::actualitzar(float delta_time) {
|
||||
// Actualització de la física de la nau (TIME-BASED)
|
||||
// Basat en el codi Pascal original: lines 394-417
|
||||
// Convertit a time-based per ser independent del framerate
|
||||
// Actualització de la física de la nau (TIME-BASED)
|
||||
// Basat en el codi Pascal original: lines 394-417
|
||||
// Convertit a time-based per ser independent del framerate
|
||||
// Constants de física ara definides a core/defaults.hpp (Defaults::Physics)
|
||||
|
||||
// Constants de física (convertides des del Pascal original a ~20 FPS)
|
||||
constexpr float ROTATION_SPEED = 3.14f; // rad/s (0.157 rad/frame × 20 = 3.14 rad/s, ~180°/s)
|
||||
constexpr float ACCELERATION = 400.0f; // px/s² (0.2 u/frame × 20 × 100 = 400 px/s²)
|
||||
constexpr float MAX_VELOCITY = 120.0f; // px/s (6 u/frame × 20 = 120 px/s)
|
||||
constexpr float FRICTION = 20.0f; // px/s² (0.1 u/frame × 20 × 10 = 20 px/s²)
|
||||
// Obtenir estat actual del teclat (no events, sinó estat continu)
|
||||
const bool *keyboard_state = SDL_GetKeyboardState(nullptr);
|
||||
|
||||
// Obtenir estat actual del teclat (no events, sinó estat continu)
|
||||
const bool* keyboard_state = SDL_GetKeyboardState(nullptr);
|
||||
// Processar input continu (com teclapuls() del Pascal original)
|
||||
if (keyboard_state[SDL_SCANCODE_RIGHT]) {
|
||||
nau_.angle += Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
|
||||
// Processar input continu (com teclapuls() del Pascal original)
|
||||
if (keyboard_state[SDL_SCANCODE_RIGHT]) {
|
||||
nau_.angle += ROTATION_SPEED * delta_time;
|
||||
if (keyboard_state[SDL_SCANCODE_LEFT]) {
|
||||
nau_.angle -= Defaults::Physics::ROTATION_SPEED * delta_time;
|
||||
}
|
||||
|
||||
if (keyboard_state[SDL_SCANCODE_UP]) {
|
||||
if (nau_.velocitat < Defaults::Physics::MAX_VELOCITY) {
|
||||
nau_.velocitat += Defaults::Physics::ACCELERATION * delta_time;
|
||||
if (nau_.velocitat > Defaults::Physics::MAX_VELOCITY) {
|
||||
nau_.velocitat = Defaults::Physics::MAX_VELOCITY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (keyboard_state[SDL_SCANCODE_LEFT]) {
|
||||
nau_.angle -= ROTATION_SPEED * delta_time;
|
||||
// Calcular nova posició basada en velocitat i angle
|
||||
// S'usa (angle - PI/2) perquè angle=0 apunte cap amunt, no cap a la dreta
|
||||
// velocitat està en px/s, així que multipliquem per delta_time
|
||||
float dy = (nau_.velocitat * delta_time) *
|
||||
std::sin(nau_.angle - Constants::PI / 2.0f) +
|
||||
nau_.centre.y;
|
||||
float dx = (nau_.velocitat * delta_time) *
|
||||
std::cos(nau_.angle - Constants::PI / 2.0f) +
|
||||
nau_.centre.x;
|
||||
|
||||
// Boundary checking - només actualitzar si dins dels marges
|
||||
// Acumulació directa amb precisió subpíxel
|
||||
if (dy > Constants::MARGE_DALT && dy < Constants::MARGE_BAIX) {
|
||||
nau_.centre.y = dy;
|
||||
}
|
||||
|
||||
if (dx > Constants::MARGE_ESQ && dx < Constants::MARGE_DRET) {
|
||||
nau_.centre.x = dx;
|
||||
}
|
||||
|
||||
// Fricció - desacceleració gradual (time-based)
|
||||
if (nau_.velocitat > 0.1f) {
|
||||
nau_.velocitat -= Defaults::Physics::FRICTION * delta_time;
|
||||
if (nau_.velocitat < 0.0f) {
|
||||
nau_.velocitat = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
if (keyboard_state[SDL_SCANCODE_UP]) {
|
||||
if (nau_.velocitat < MAX_VELOCITY) {
|
||||
nau_.velocitat += ACCELERATION * delta_time;
|
||||
if (nau_.velocitat > MAX_VELOCITY) {
|
||||
nau_.velocitat = MAX_VELOCITY;
|
||||
}
|
||||
}
|
||||
// Actualitzar moviment i rotació dels enemics (ORNIs)
|
||||
// Basat en el codi Pascal original: lines 429-432
|
||||
for (auto &enemy : orni_) {
|
||||
if (enemy.esta) {
|
||||
// Moviment autònom (Fase 8)
|
||||
mou_orni(enemy, delta_time);
|
||||
|
||||
// Rotació visual (time-based: drotacio està en rad/s)
|
||||
enemy.rotacio += enemy.drotacio * delta_time;
|
||||
}
|
||||
}
|
||||
|
||||
// Calcular nova posició basada en velocitat i angle
|
||||
// S'usa (angle - PI/2) perquè angle=0 apunte cap amunt, no cap a la dreta
|
||||
// velocitat està en px/s, així que multipliquem per delta_time
|
||||
float dy = (nau_.velocitat * delta_time) * std::sin(nau_.angle - Constants::PI / 2.0f)
|
||||
+ nau_.centre.y;
|
||||
float dx = (nau_.velocitat * delta_time) * std::cos(nau_.angle - Constants::PI / 2.0f)
|
||||
+ nau_.centre.x;
|
||||
|
||||
// Boundary checking - només actualitzar si dins dels marges
|
||||
// Acumulació directa amb precisió subpíxel
|
||||
if (dy > Constants::MARGE_DALT && dy < Constants::MARGE_BAIX) {
|
||||
nau_.centre.y = dy;
|
||||
}
|
||||
|
||||
if (dx > Constants::MARGE_ESQ && dx < Constants::MARGE_DRET) {
|
||||
nau_.centre.x = dx;
|
||||
}
|
||||
|
||||
// Fricció - desacceleració gradual (time-based)
|
||||
if (nau_.velocitat > 0.1f) {
|
||||
nau_.velocitat -= FRICTION * delta_time;
|
||||
if (nau_.velocitat < 0.0f) {
|
||||
nau_.velocitat = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Actualitzar moviment i rotació dels enemics (ORNIs)
|
||||
// Basat en el codi Pascal original: lines 429-432
|
||||
for (auto& enemy : orni_) {
|
||||
if (enemy.esta) {
|
||||
// Moviment autònom (Fase 8)
|
||||
mou_orni(enemy, delta_time);
|
||||
|
||||
// Rotació visual (time-based: drotacio està en rad/s)
|
||||
enemy.rotacio += enemy.drotacio * delta_time;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualitzar moviment de bales (Fase 9)
|
||||
for (auto& bala : bales_) {
|
||||
if (bala.esta) {
|
||||
mou_bales(bala, delta_time);
|
||||
}
|
||||
// Actualitzar moviment de bales (Fase 9)
|
||||
for (auto &bala : bales_) {
|
||||
if (bala.esta) {
|
||||
mou_bales(bala, delta_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void JocAsteroides::dibuixar() {
|
||||
// Dibuixar la nau si no està en seqüència de mort
|
||||
if (itocado_ == 0) {
|
||||
// Escalar velocitat per l'efect visual (120 px/s → ~6 px d'efecte)
|
||||
// El codi Pascal original sumava velocitat (0-6) al radi per donar
|
||||
// sensació de "empenta". Ara velocitat està en px/s (0-120).
|
||||
float velocitat_visual = nau_.velocitat / 20.0f;
|
||||
rota_tri(nau_, nau_.angle, velocitat_visual, true);
|
||||
}
|
||||
// Dibuixar la nau si no està en seqüència de mort
|
||||
if (itocado_ == 0) {
|
||||
// Escalar velocitat per l'efect visual (120 px/s → ~6 px d'efecte)
|
||||
// El codi Pascal original sumava velocitat (0-6) al radi per donar
|
||||
// sensació de "empenta". Ara velocitat està en px/s (0-120).
|
||||
float velocitat_visual = nau_.velocitat / 20.0f;
|
||||
rota_tri(nau_, nau_.angle, velocitat_visual, true);
|
||||
}
|
||||
|
||||
// Dibuixar ORNIs (enemics)
|
||||
// Basat en el codi Pascal original: lines 429-432
|
||||
for (const auto& enemy : orni_) {
|
||||
if (enemy.esta) {
|
||||
rota_pol(enemy, enemy.rotacio, true);
|
||||
}
|
||||
// Dibuixar ORNIs (enemics)
|
||||
// Basat en el codi Pascal original: lines 429-432
|
||||
for (const auto &enemy : orni_) {
|
||||
if (enemy.esta) {
|
||||
rota_pol(enemy, enemy.rotacio, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuixar bales (Fase 9)
|
||||
for (const auto& bala : bales_) {
|
||||
if (bala.esta) {
|
||||
// Dibuixar com a pentàgon petit, sense rotació visual (sempre mateix angle)
|
||||
rota_pol(bala, 0.0f, true);
|
||||
}
|
||||
// Dibuixar bales (Fase 9)
|
||||
for (const auto &bala : bales_) {
|
||||
if (bala.esta) {
|
||||
// Dibuixar com a pentàgon petit, sense rotació visual (sempre mateix
|
||||
// angle)
|
||||
rota_pol(bala, 0.0f, true);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Dibuixar marges (Fase 11)
|
||||
// TODO: Dibuixar marges (Fase 11)
|
||||
}
|
||||
|
||||
void JocAsteroides::processar_input(const SDL_Event& event) {
|
||||
// Processament d'input per events puntuals (no continus)
|
||||
// L'input continu (fletxes) es processa en actualitzar() amb SDL_GetKeyboardState()
|
||||
void JocAsteroides::processar_input(const SDL_Event &event) {
|
||||
// Processament d'input per events puntuals (no continus)
|
||||
// L'input continu (fletxes) es processa en actualitzar() amb
|
||||
// SDL_GetKeyboardState()
|
||||
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_SPACE:
|
||||
// Disparar (Fase 9)
|
||||
// Basat en el codi Pascal original: crear bala en posició de la nau
|
||||
// El joc original només permetia 1 bala activa alhora
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_SPACE:
|
||||
// Disparar (Fase 9)
|
||||
// Basat en el codi Pascal original: crear bala en posició de la nau
|
||||
// El joc original només permetia 1 bala activa alhora
|
||||
|
||||
// Buscar primera bala inactiva
|
||||
for (auto& bala : bales_) {
|
||||
if (!bala.esta) {
|
||||
// Activar bala
|
||||
bala.esta = true;
|
||||
// Buscar primera bala inactiva
|
||||
for (auto &bala : bales_) {
|
||||
if (!bala.esta) {
|
||||
// Activar bala
|
||||
bala.esta = true;
|
||||
|
||||
// Posició inicial = centre de la nau
|
||||
bala.centre.x = nau_.centre.x;
|
||||
bala.centre.y = nau_.centre.y;
|
||||
// Posició inicial = centre de la nau
|
||||
bala.centre.x = nau_.centre.x;
|
||||
bala.centre.y = nau_.centre.y;
|
||||
|
||||
// Angle = angle de la nau (dispara en la direcció que apunta)
|
||||
bala.angle = nau_.angle;
|
||||
// Angle = angle de la nau (dispara en la direcció que apunta)
|
||||
bala.angle = nau_.angle;
|
||||
|
||||
// Velocitat alta (el joc Pascal original usava 7 px/frame)
|
||||
// 7 px/frame × 20 FPS = 140 px/s
|
||||
bala.velocitat = 140.0f;
|
||||
// Velocitat alta (el joc Pascal original usava 7 px/frame)
|
||||
// 7 px/frame × 20 FPS = 140 px/s
|
||||
bala.velocitat = 140.0f;
|
||||
|
||||
// Només una bala alhora (com el joc original)
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
// Només una bala alhora (com el joc original)
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Funcions de dibuix
|
||||
|
||||
bool JocAsteroides::linea(int x1, int y1, int x2, int y2, bool dibuixar) {
|
||||
// Algorisme de Bresenham per dibuixar línies
|
||||
// Basat en el codi Pascal original
|
||||
// Algorisme de Bresenham per dibuixar línies
|
||||
// Basat en el codi Pascal original
|
||||
|
||||
// Helper function: retorna el signe d'un nombre
|
||||
auto sign = [](int x) -> int {
|
||||
if (x < 0) return -1;
|
||||
if (x > 0) return 1;
|
||||
return 0;
|
||||
};
|
||||
// Helper function: retorna el signe d'un nombre
|
||||
auto sign = [](int x) -> int {
|
||||
if (x < 0)
|
||||
return -1;
|
||||
if (x > 0)
|
||||
return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
// Variables per a l'algorisme (no utilitzades fins Fase 10 - detecció de col·lisions)
|
||||
// int x = x1, y = y1;
|
||||
// int xs = x2 - x1;
|
||||
// int ys = y2 - y1;
|
||||
// int xm = sign(xs);
|
||||
// int ym = sign(ys);
|
||||
// xs = std::abs(xs);
|
||||
// ys = std::abs(ys);
|
||||
// Variables per a l'algorisme (no utilitzades fins Fase 10 - detecció de
|
||||
// col·lisions) int x = x1, y = y1; int xs = x2 - x1; int ys = y2 - y1; int xm
|
||||
// = sign(xs); int ym = sign(ys); xs = std::abs(xs); ys = std::abs(ys);
|
||||
|
||||
// Suprimir warning de variable no usada
|
||||
(void)sign;
|
||||
// Suprimir warning de variable no usada
|
||||
(void)sign;
|
||||
|
||||
// Detecció de col·lisió (TODO per Fase 10)
|
||||
// El codi Pascal original llegia pixels del framebuffer bit-packed
|
||||
// i comptava col·lisions. Per ara, usem SDL_RenderDrawLine i retornem false.
|
||||
bool colisio = false;
|
||||
// Detecció de col·lisió (TODO per Fase 10)
|
||||
// El codi Pascal original llegia pixels del framebuffer bit-packed
|
||||
// i comptava col·lisions. Per ara, usem SDL_RenderDrawLine i retornem false.
|
||||
bool colisio = false;
|
||||
|
||||
// Dibuixar amb SDL3 (més eficient que Bresenham píxel a píxel)
|
||||
if (dibuixar && renderer_) {
|
||||
SDL_SetRenderDrawColor(renderer_, 255, 255, 255, 255); // Blanc
|
||||
SDL_RenderLine(renderer_,
|
||||
static_cast<float>(x1),
|
||||
static_cast<float>(y1),
|
||||
static_cast<float>(x2),
|
||||
static_cast<float>(y2));
|
||||
}
|
||||
// Dibuixar amb SDL3 (més eficient que Bresenham píxel a píxel)
|
||||
if (dibuixar && renderer_) {
|
||||
SDL_SetRenderDrawColor(renderer_, 255, 255, 255, 255); // Blanc
|
||||
SDL_RenderLine(renderer_, static_cast<float>(x1), static_cast<float>(y1),
|
||||
static_cast<float>(x2), static_cast<float>(y2));
|
||||
}
|
||||
|
||||
// Algorisme de Bresenham original (conservat per a futura detecció de col·lisió)
|
||||
/*
|
||||
if (xs > ys) {
|
||||
// Línia plana (<45 graus)
|
||||
int count = -(xs / 2);
|
||||
while (x != x2) {
|
||||
count = count + ys;
|
||||
x = x + xm;
|
||||
if (count > 0) {
|
||||
y = y + ym;
|
||||
count = count - xs;
|
||||
}
|
||||
// Aquí aniria la detecció de col·lisió píxel a píxel
|
||||
}
|
||||
} else {
|
||||
// Línia pronunciada (>=45 graus)
|
||||
int count = -(ys / 2);
|
||||
while (y != y2) {
|
||||
count = count + xs;
|
||||
y = y + ym;
|
||||
if (count > 0) {
|
||||
x = x + xm;
|
||||
count = count - ys;
|
||||
}
|
||||
// Aquí aniria la detecció de col·lisió píxel a píxel
|
||||
}
|
||||
}
|
||||
*/
|
||||
// Algorisme de Bresenham original (conservat per a futura detecció de
|
||||
// col·lisió)
|
||||
/*
|
||||
if (xs > ys) {
|
||||
// Línia plana (<45 graus)
|
||||
int count = -(xs / 2);
|
||||
while (x != x2) {
|
||||
count = count + ys;
|
||||
x = x + xm;
|
||||
if (count > 0) {
|
||||
y = y + ym;
|
||||
count = count - xs;
|
||||
}
|
||||
// Aquí aniria la detecció de col·lisió píxel a píxel
|
||||
}
|
||||
} else {
|
||||
// Línia pronunciada (>=45 graus)
|
||||
int count = -(ys / 2);
|
||||
while (y != y2) {
|
||||
count = count + xs;
|
||||
y = y + ym;
|
||||
if (count > 0) {
|
||||
x = x + xm;
|
||||
count = count - ys;
|
||||
}
|
||||
// Aquí aniria la detecció de col·lisió píxel a píxel
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
return colisio;
|
||||
return colisio;
|
||||
}
|
||||
|
||||
void JocAsteroides::rota_tri(const Triangle& tri, float angul, float velocitat, bool dibuixar) {
|
||||
// Rotar i dibuixar triangle (nau)
|
||||
// Conversió de coordenades polars a cartesianes amb rotació
|
||||
// Basat en el codi Pascal original: lines 271-284
|
||||
void JocAsteroides::rota_tri(const Triangle &tri, float angul, float velocitat,
|
||||
bool dibuixar) {
|
||||
// Rotar i dibuixar triangle (nau)
|
||||
// Conversió de coordenades polars a cartesianes amb rotació
|
||||
// Basat en el codi Pascal original: lines 271-284
|
||||
|
||||
// Convertir cada punt polar a cartesià
|
||||
// x = (r + velocitat) * cos(angle_punt + angle_nau) + centre.x
|
||||
// y = (r + velocitat) * sin(angle_punt + angle_nau) + centre.y
|
||||
// Convertir cada punt polar a cartesià
|
||||
// x = (r + velocitat) * cos(angle_punt + angle_nau) + centre.x
|
||||
// y = (r + velocitat) * sin(angle_punt + angle_nau) + centre.y
|
||||
|
||||
int x1 = static_cast<int>(std::round(
|
||||
(tri.p1.r + velocitat) * std::cos(tri.p1.angle + angul)
|
||||
)) + tri.centre.x;
|
||||
int x1 = static_cast<int>(std::round((tri.p1.r + velocitat) *
|
||||
std::cos(tri.p1.angle + angul))) +
|
||||
tri.centre.x;
|
||||
|
||||
int y1 = static_cast<int>(std::round(
|
||||
(tri.p1.r + velocitat) * std::sin(tri.p1.angle + angul)
|
||||
)) + tri.centre.y;
|
||||
int y1 = static_cast<int>(std::round((tri.p1.r + velocitat) *
|
||||
std::sin(tri.p1.angle + angul))) +
|
||||
tri.centre.y;
|
||||
|
||||
int x2 = static_cast<int>(std::round(
|
||||
(tri.p2.r + velocitat) * std::cos(tri.p2.angle + angul)
|
||||
)) + tri.centre.x;
|
||||
int x2 = static_cast<int>(std::round((tri.p2.r + velocitat) *
|
||||
std::cos(tri.p2.angle + angul))) +
|
||||
tri.centre.x;
|
||||
|
||||
int y2 = static_cast<int>(std::round(
|
||||
(tri.p2.r + velocitat) * std::sin(tri.p2.angle + angul)
|
||||
)) + tri.centre.y;
|
||||
int y2 = static_cast<int>(std::round((tri.p2.r + velocitat) *
|
||||
std::sin(tri.p2.angle + angul))) +
|
||||
tri.centre.y;
|
||||
|
||||
int x3 = static_cast<int>(std::round(
|
||||
(tri.p3.r + velocitat) * std::cos(tri.p3.angle + angul)
|
||||
)) + tri.centre.x;
|
||||
int x3 = static_cast<int>(std::round((tri.p3.r + velocitat) *
|
||||
std::cos(tri.p3.angle + angul))) +
|
||||
tri.centre.x;
|
||||
|
||||
int y3 = static_cast<int>(std::round(
|
||||
(tri.p3.r + velocitat) * std::sin(tri.p3.angle + angul)
|
||||
)) + tri.centre.y;
|
||||
int y3 = static_cast<int>(std::round((tri.p3.r + velocitat) *
|
||||
std::sin(tri.p3.angle + angul))) +
|
||||
tri.centre.y;
|
||||
|
||||
// Dibuixar les 3 línies que formen el triangle
|
||||
linea(x1, y1, x2, y2, dibuixar);
|
||||
linea(x1, y1, x3, y3, dibuixar);
|
||||
linea(x3, y3, x2, y2, dibuixar);
|
||||
// Dibuixar les 3 línies que formen el triangle
|
||||
linea(x1, y1, x2, y2, dibuixar);
|
||||
linea(x1, y1, x3, y3, dibuixar);
|
||||
linea(x3, y3, x2, y2, dibuixar);
|
||||
}
|
||||
|
||||
void JocAsteroides::rota_pol(const Poligon& pol, float angul, bool dibuixar) {
|
||||
// Rotar i dibuixar polígon (enemics i bales)
|
||||
// Conversió de coordenades polars a cartesianes amb rotació
|
||||
// Basat en el codi Pascal original: lines 286-296
|
||||
void JocAsteroides::rota_pol(const Poligon &pol, float angul, bool dibuixar) {
|
||||
// Rotar i dibuixar polígon (enemics i bales)
|
||||
// Conversió de coordenades polars a cartesianes amb rotació
|
||||
// Basat en el codi Pascal original: lines 286-296
|
||||
|
||||
// Array temporal per emmagatzemar punts convertits a cartesianes
|
||||
std::array<Punt, Constants::MAX_IPUNTS> xy;
|
||||
// Array temporal per emmagatzemar punts convertits a cartesianes
|
||||
std::array<Punt, Constants::MAX_IPUNTS> xy;
|
||||
|
||||
// Convertir cada punt polar a cartesià
|
||||
for (uint8_t i = 0; i < pol.n; i++) {
|
||||
xy[i].x = static_cast<int>(std::round(
|
||||
pol.ipuntx[i].r * std::cos(pol.ipuntx[i].angle + angul)
|
||||
)) + pol.centre.x;
|
||||
// Convertir cada punt polar a cartesià
|
||||
for (uint8_t i = 0; i < pol.n; i++) {
|
||||
xy[i].x = static_cast<int>(std::round(
|
||||
pol.ipuntx[i].r * std::cos(pol.ipuntx[i].angle + angul))) +
|
||||
pol.centre.x;
|
||||
|
||||
xy[i].y = static_cast<int>(std::round(
|
||||
pol.ipuntx[i].r * std::sin(pol.ipuntx[i].angle + angul)
|
||||
)) + pol.centre.y;
|
||||
}
|
||||
xy[i].y = static_cast<int>(std::round(
|
||||
pol.ipuntx[i].r * std::sin(pol.ipuntx[i].angle + angul))) +
|
||||
pol.centre.y;
|
||||
}
|
||||
|
||||
// Dibuixar línies entre punts consecutius
|
||||
for (uint8_t i = 0; i < pol.n - 1; i++) {
|
||||
linea(xy[i].x, xy[i].y, xy[i + 1].x, xy[i + 1].y, dibuixar);
|
||||
}
|
||||
// Dibuixar línies entre punts consecutius
|
||||
for (uint8_t i = 0; i < pol.n - 1; i++) {
|
||||
linea(xy[i].x, xy[i].y, xy[i + 1].x, xy[i + 1].y, dibuixar);
|
||||
}
|
||||
|
||||
// Tancar el polígon (últim punt → primer punt)
|
||||
linea(xy[pol.n - 1].x, xy[pol.n - 1].y, xy[0].x, xy[0].y, dibuixar);
|
||||
// Tancar el polígon (últim punt → primer punt)
|
||||
linea(xy[pol.n - 1].x, xy[pol.n - 1].y, xy[0].x, xy[0].y, dibuixar);
|
||||
}
|
||||
|
||||
void JocAsteroides::mou_orni(Poligon& orni, float delta_time) {
|
||||
// Moviment autònom d'ORNI (enemic pentàgon)
|
||||
// Basat EXACTAMENT en el codi Pascal original: ASTEROID.PAS lines 279-293
|
||||
//
|
||||
// IMPORTANT: El Pascal original NO té canvi aleatori continu!
|
||||
// Només ajusta l'angle quan toca una paret.
|
||||
void JocAsteroides::mou_orni(Poligon &orni, float delta_time) {
|
||||
// Moviment autònom d'ORNI (enemic pentàgon)
|
||||
// Basat EXACTAMENT en el codi Pascal original: ASTEROID.PAS lines 279-293
|
||||
//
|
||||
// IMPORTANT: El Pascal original NO té canvi aleatori continu!
|
||||
// Només ajusta l'angle quan toca una paret.
|
||||
|
||||
// Calcular nova posició PROPUESTA (time-based, però lògica Pascal)
|
||||
// velocitat ja està en px/s (40 px/s), multiplicar per delta_time
|
||||
float velocitat_efectiva = orni.velocitat * delta_time;
|
||||
// Calcular nova posició PROPUESTA (time-based, però lògica Pascal)
|
||||
// velocitat ja està en px/s (40 px/s), multiplicar per delta_time
|
||||
float velocitat_efectiva = orni.velocitat * delta_time;
|
||||
|
||||
// Calcular desplaçament (angle-PI/2 perquè angle=0 apunta amunt)
|
||||
float dy = velocitat_efectiva * std::sin(orni.angle - Constants::PI / 2.0f);
|
||||
float dx = velocitat_efectiva * std::cos(orni.angle - Constants::PI / 2.0f);
|
||||
// Calcular desplaçament (angle-PI/2 perquè angle=0 apunta amunt)
|
||||
float dy = velocitat_efectiva * std::sin(orni.angle - Constants::PI / 2.0f);
|
||||
float dx = velocitat_efectiva * std::cos(orni.angle - Constants::PI / 2.0f);
|
||||
|
||||
float new_y = orni.centre.y + dy;
|
||||
float new_x = orni.centre.x + dx;
|
||||
float new_y = orni.centre.y + dy;
|
||||
float new_x = orni.centre.x + dx;
|
||||
|
||||
// Lògica Pascal: Actualitza Y si dins, sinó ajusta angle aleatòriament
|
||||
// if (dy>marge_dalt) and (dy<marge_baix) then orni.centre.y:=round(Dy)
|
||||
// else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1);
|
||||
if (new_y > Constants::MARGE_DALT && new_y < Constants::MARGE_BAIX) {
|
||||
orni.centre.y = new_y;
|
||||
} else {
|
||||
// Pequeño ajuste aleatorio: (random(256)/512)*(random(3)-1)
|
||||
// random(256) = 0..255, /512 = 0..0.498
|
||||
// random(3) = 0,1,2, -1 = -1,0,1
|
||||
// Resultado: ±0.5 rad aprox
|
||||
float rand1 = (static_cast<float>(std::rand() % 256) / 512.0f);
|
||||
int rand2 = (std::rand() % 3) - 1; // -1, 0, o 1
|
||||
orni.angle += rand1 * static_cast<float>(rand2);
|
||||
}
|
||||
// Lògica Pascal: Actualitza Y si dins, sinó ajusta angle aleatòriament
|
||||
// if (dy>marge_dalt) and (dy<marge_baix) then orni.centre.y:=round(Dy)
|
||||
// else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1);
|
||||
if (new_y > Constants::MARGE_DALT && new_y < Constants::MARGE_BAIX) {
|
||||
orni.centre.y = new_y;
|
||||
} else {
|
||||
// Pequeño ajuste aleatorio: (random(256)/512)*(random(3)-1)
|
||||
// random(256) = 0..255, /512 = 0..0.498
|
||||
// random(3) = 0,1,2, -1 = -1,0,1
|
||||
// Resultado: ±0.5 rad aprox
|
||||
float rand1 = (static_cast<float>(std::rand() % 256) / 512.0f);
|
||||
int rand2 = (std::rand() % 3) - 1; // -1, 0, o 1
|
||||
orni.angle += rand1 * static_cast<float>(rand2);
|
||||
}
|
||||
|
||||
// Lògica Pascal: Actualitza X si dins, sinó ajusta angle aleatòriament
|
||||
// if (dx>marge_esq) and (dx<marge_dret) then orni.centre.x:=round(Dx)
|
||||
// else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1);
|
||||
if (new_x > Constants::MARGE_ESQ && new_x < Constants::MARGE_DRET) {
|
||||
orni.centre.x = new_x;
|
||||
} else {
|
||||
float rand1 = (static_cast<float>(std::rand() % 256) / 512.0f);
|
||||
int rand2 = (std::rand() % 3) - 1;
|
||||
orni.angle += rand1 * static_cast<float>(rand2);
|
||||
}
|
||||
// Lògica Pascal: Actualitza X si dins, sinó ajusta angle aleatòriament
|
||||
// if (dx>marge_esq) and (dx<marge_dret) then orni.centre.x:=round(Dx)
|
||||
// else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1);
|
||||
if (new_x > Constants::MARGE_ESQ && new_x < Constants::MARGE_DRET) {
|
||||
orni.centre.x = new_x;
|
||||
} else {
|
||||
float rand1 = (static_cast<float>(std::rand() % 256) / 512.0f);
|
||||
int rand2 = (std::rand() % 3) - 1;
|
||||
orni.angle += rand1 * static_cast<float>(rand2);
|
||||
}
|
||||
|
||||
// Nota: La rotació visual (orni.rotacio += orni.drotacio) ja es fa a actualitzar()
|
||||
// Nota: La rotació visual (orni.rotacio += orni.drotacio) ja es fa a
|
||||
// actualitzar()
|
||||
}
|
||||
|
||||
void JocAsteroides::mou_bales(Poligon& bala, float delta_time) {
|
||||
// Moviment rectilini de la bala
|
||||
// Basat en el codi Pascal original: procedure mou_bales
|
||||
void JocAsteroides::mou_bales(Poligon &bala, float delta_time) {
|
||||
// Moviment rectilini de la bala
|
||||
// Basat en el codi Pascal original: procedure mou_bales
|
||||
|
||||
// Calcular nova posició (moviment polar time-based)
|
||||
// velocitat ja està en px/s (140 px/s), només cal multiplicar per delta_time
|
||||
float velocitat_efectiva = bala.velocitat * delta_time;
|
||||
// Calcular nova posició (moviment polar time-based)
|
||||
// velocitat ja està en px/s (140 px/s), només cal multiplicar per delta_time
|
||||
float velocitat_efectiva = bala.velocitat * delta_time;
|
||||
|
||||
// Calcular desplaçament (angle-PI/2 perquè angle=0 apunta amunt)
|
||||
float dy = velocitat_efectiva * std::sin(bala.angle - Constants::PI / 2.0f);
|
||||
float dx = velocitat_efectiva * std::cos(bala.angle - Constants::PI / 2.0f);
|
||||
// Calcular desplaçament (angle-PI/2 perquè angle=0 apunta amunt)
|
||||
float dy = velocitat_efectiva * std::sin(bala.angle - Constants::PI / 2.0f);
|
||||
float dx = velocitat_efectiva * std::cos(bala.angle - Constants::PI / 2.0f);
|
||||
|
||||
// Acumulació directa amb precisió subpíxel
|
||||
bala.centre.y += dy;
|
||||
bala.centre.x += dx;
|
||||
// Acumulació directa amb precisió subpíxel
|
||||
bala.centre.y += dy;
|
||||
bala.centre.x += dx;
|
||||
|
||||
// Desactivar si surt dels marges (no rebota com els ORNIs)
|
||||
if (bala.centre.x < Constants::MARGE_ESQ || bala.centre.x > Constants::MARGE_DRET ||
|
||||
bala.centre.y < Constants::MARGE_DALT || bala.centre.y > Constants::MARGE_BAIX) {
|
||||
bala.esta = false;
|
||||
}
|
||||
// Desactivar si surt dels marges (no rebota com els ORNIs)
|
||||
if (bala.centre.x < Constants::MARGE_ESQ ||
|
||||
bala.centre.x > Constants::MARGE_DRET ||
|
||||
bala.centre.y < Constants::MARGE_DALT ||
|
||||
bala.centre.y > Constants::MARGE_BAIX) {
|
||||
bala.esta = false;
|
||||
}
|
||||
}
|
||||
|
||||
void JocAsteroides::tocado() {
|
||||
// TODO: Implementar seqüència de mort
|
||||
// TODO: Implementar seqüència de mort
|
||||
}
|
||||
|
||||
@@ -5,42 +5,43 @@
|
||||
#ifndef JOC_ASTEROIDES_HPP
|
||||
#define JOC_ASTEROIDES_HPP
|
||||
|
||||
#include "core/types.hpp"
|
||||
#include "game/constants.hpp"
|
||||
#include <SDL3/SDL.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include "core/types.hpp"
|
||||
#include "game/constants.hpp"
|
||||
|
||||
// Classe principal del joc
|
||||
class JocAsteroides {
|
||||
public:
|
||||
JocAsteroides(SDL_Renderer* renderer);
|
||||
~JocAsteroides() = default;
|
||||
JocAsteroides(SDL_Renderer *renderer);
|
||||
~JocAsteroides() = default;
|
||||
|
||||
void inicialitzar();
|
||||
void actualitzar(float delta_time);
|
||||
void dibuixar();
|
||||
void processar_input(const SDL_Event& event);
|
||||
void inicialitzar();
|
||||
void actualitzar(float delta_time);
|
||||
void dibuixar();
|
||||
void processar_input(const SDL_Event &event);
|
||||
|
||||
private:
|
||||
SDL_Renderer* renderer_;
|
||||
SDL_Renderer *renderer_;
|
||||
|
||||
// Estat del joc
|
||||
Triangle nau_;
|
||||
std::array<Poligon, Constants::MAX_ORNIS> orni_;
|
||||
std::array<Poligon, Constants::MAX_BALES> bales_;
|
||||
Poligon chatarra_cosmica_;
|
||||
uint16_t itocado_;
|
||||
// Estat del joc
|
||||
Triangle nau_;
|
||||
std::array<Poligon, Constants::MAX_ORNIS> orni_;
|
||||
std::array<Poligon, Constants::MAX_BALES> bales_;
|
||||
Poligon chatarra_cosmica_;
|
||||
uint16_t itocado_;
|
||||
|
||||
// Funcions de dibuix
|
||||
bool linea(int x1, int y1, int x2, int y2, bool dibuixar);
|
||||
void rota_tri(const Triangle& tri, float angul, float velocitat, bool dibuixar);
|
||||
void rota_pol(const Poligon& pol, float angul, bool dibuixar);
|
||||
// Funcions de dibuix
|
||||
bool linea(int x1, int y1, int x2, int y2, bool dibuixar);
|
||||
void rota_tri(const Triangle &tri, float angul, float velocitat,
|
||||
bool dibuixar);
|
||||
void rota_pol(const Poligon &pol, float angul, bool dibuixar);
|
||||
|
||||
// Moviment
|
||||
void mou_orni(Poligon& orni, float delta_time);
|
||||
void mou_bales(Poligon& bala, float delta_time);
|
||||
void tocado();
|
||||
// Moviment
|
||||
void mou_orni(Poligon &orni, float delta_time);
|
||||
void mou_bales(Poligon &bala, float delta_time);
|
||||
void tocado();
|
||||
};
|
||||
|
||||
#endif // JOC_ASTEROIDES_HPP
|
||||
|
||||
298
source/game/options.cpp
Normal file
298
source/game/options.cpp
Normal file
@@ -0,0 +1,298 @@
|
||||
#include "options.hpp"
|
||||
#include "../core/defaults.hpp"
|
||||
#include "../external/fkyaml_node.hpp"
|
||||
#include "project.h"
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace Options {
|
||||
|
||||
// Inicialitzar opcions amb valors per defecte de Defaults::
|
||||
void init() {
|
||||
#ifdef _DEBUG
|
||||
console = true;
|
||||
#else
|
||||
console = false;
|
||||
#endif
|
||||
|
||||
// Window
|
||||
window.width = Defaults::Window::WIDTH;
|
||||
window.height = Defaults::Window::HEIGHT;
|
||||
window.fullscreen = false;
|
||||
window.size_increment = Defaults::Window::SIZE_INCREMENT;
|
||||
|
||||
// Physics
|
||||
physics.rotation_speed = Defaults::Physics::ROTATION_SPEED;
|
||||
physics.acceleration = Defaults::Physics::ACCELERATION;
|
||||
physics.max_velocity = Defaults::Physics::MAX_VELOCITY;
|
||||
physics.friction = Defaults::Physics::FRICTION;
|
||||
physics.enemy_speed = Defaults::Physics::ENEMY_SPEED;
|
||||
physics.bullet_speed = Defaults::Physics::BULLET_SPEED;
|
||||
|
||||
// Gameplay
|
||||
gameplay.max_enemies = Defaults::Entities::MAX_ORNIS;
|
||||
gameplay.max_bullets = Defaults::Entities::MAX_BALES;
|
||||
|
||||
// Version
|
||||
version = std::string(Project::VERSION);
|
||||
}
|
||||
|
||||
// Establir la ruta del fitxer de configuració
|
||||
void setConfigFile(const std::string &path) { config_file_path = path; }
|
||||
|
||||
// Funcions auxiliars per carregar seccions del YAML
|
||||
|
||||
static void loadWindowConfigFromYaml(const fkyaml::node &yaml) {
|
||||
if (yaml.contains("window")) {
|
||||
const auto &win = yaml["window"];
|
||||
|
||||
if (win.contains("width")) {
|
||||
try {
|
||||
auto val = win["width"].get_value<int>();
|
||||
window.width = (val >= Defaults::Window::MIN_WIDTH)
|
||||
? val
|
||||
: Defaults::Window::WIDTH;
|
||||
} catch (...) {
|
||||
window.width = Defaults::Window::WIDTH;
|
||||
}
|
||||
}
|
||||
|
||||
if (win.contains("height")) {
|
||||
try {
|
||||
auto val = win["height"].get_value<int>();
|
||||
window.height = (val >= Defaults::Window::MIN_HEIGHT)
|
||||
? val
|
||||
: Defaults::Window::HEIGHT;
|
||||
} catch (...) {
|
||||
window.height = Defaults::Window::HEIGHT;
|
||||
}
|
||||
}
|
||||
|
||||
if (win.contains("fullscreen")) {
|
||||
try {
|
||||
window.fullscreen = win["fullscreen"].get_value<bool>();
|
||||
} catch (...) {
|
||||
window.fullscreen = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (win.contains("size_increment")) {
|
||||
try {
|
||||
auto val = win["size_increment"].get_value<int>();
|
||||
window.size_increment =
|
||||
(val > 0) ? val : Defaults::Window::SIZE_INCREMENT;
|
||||
} catch (...) {
|
||||
window.size_increment = Defaults::Window::SIZE_INCREMENT;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void loadPhysicsConfigFromYaml(const fkyaml::node &yaml) {
|
||||
if (yaml.contains("physics")) {
|
||||
const auto &phys = yaml["physics"];
|
||||
|
||||
if (phys.contains("rotation_speed")) {
|
||||
try {
|
||||
auto val = phys["rotation_speed"].get_value<float>();
|
||||
physics.rotation_speed =
|
||||
(val > 0) ? val : Defaults::Physics::ROTATION_SPEED;
|
||||
} catch (...) {
|
||||
physics.rotation_speed = Defaults::Physics::ROTATION_SPEED;
|
||||
}
|
||||
}
|
||||
|
||||
if (phys.contains("acceleration")) {
|
||||
try {
|
||||
auto val = phys["acceleration"].get_value<float>();
|
||||
physics.acceleration =
|
||||
(val > 0) ? val : Defaults::Physics::ACCELERATION;
|
||||
} catch (...) {
|
||||
physics.acceleration = Defaults::Physics::ACCELERATION;
|
||||
}
|
||||
}
|
||||
|
||||
if (phys.contains("max_velocity")) {
|
||||
try {
|
||||
auto val = phys["max_velocity"].get_value<float>();
|
||||
physics.max_velocity =
|
||||
(val > 0) ? val : Defaults::Physics::MAX_VELOCITY;
|
||||
} catch (...) {
|
||||
physics.max_velocity = Defaults::Physics::MAX_VELOCITY;
|
||||
}
|
||||
}
|
||||
|
||||
if (phys.contains("friction")) {
|
||||
try {
|
||||
auto val = phys["friction"].get_value<float>();
|
||||
physics.friction = (val > 0) ? val : Defaults::Physics::FRICTION;
|
||||
} catch (...) {
|
||||
physics.friction = Defaults::Physics::FRICTION;
|
||||
}
|
||||
}
|
||||
|
||||
if (phys.contains("enemy_speed")) {
|
||||
try {
|
||||
auto val = phys["enemy_speed"].get_value<float>();
|
||||
physics.enemy_speed = (val > 0) ? val : Defaults::Physics::ENEMY_SPEED;
|
||||
} catch (...) {
|
||||
physics.enemy_speed = Defaults::Physics::ENEMY_SPEED;
|
||||
}
|
||||
}
|
||||
|
||||
if (phys.contains("bullet_speed")) {
|
||||
try {
|
||||
auto val = phys["bullet_speed"].get_value<float>();
|
||||
physics.bullet_speed =
|
||||
(val > 0) ? val : Defaults::Physics::BULLET_SPEED;
|
||||
} catch (...) {
|
||||
physics.bullet_speed = Defaults::Physics::BULLET_SPEED;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void loadGameplayConfigFromYaml(const fkyaml::node &yaml) {
|
||||
if (yaml.contains("gameplay")) {
|
||||
const auto &game = yaml["gameplay"];
|
||||
|
||||
if (game.contains("max_enemies")) {
|
||||
try {
|
||||
auto val = game["max_enemies"].get_value<int>();
|
||||
gameplay.max_enemies =
|
||||
(val > 0 && val <= 50) ? val : Defaults::Entities::MAX_ORNIS;
|
||||
} catch (...) {
|
||||
gameplay.max_enemies = Defaults::Entities::MAX_ORNIS;
|
||||
}
|
||||
}
|
||||
|
||||
if (game.contains("max_bullets")) {
|
||||
try {
|
||||
auto val = game["max_bullets"].get_value<int>();
|
||||
gameplay.max_bullets =
|
||||
(val > 0 && val <= 10) ? val : Defaults::Entities::MAX_BALES;
|
||||
} catch (...) {
|
||||
gameplay.max_bullets = Defaults::Entities::MAX_BALES;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carregar configuració des del fitxer YAML
|
||||
auto loadFromFile() -> bool {
|
||||
const std::string CONFIG_VERSION = std::string(Project::VERSION);
|
||||
|
||||
std::ifstream file(config_file_path);
|
||||
if (!file.good()) {
|
||||
// El fitxer no existeix → crear-ne un de nou amb valors per defecte
|
||||
if (console) {
|
||||
std::cout << "Fitxer de config no trobat, creant-ne un de nou: "
|
||||
<< config_file_path << '\n';
|
||||
}
|
||||
saveToFile();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Llegir tot el contingut del fitxer
|
||||
std::string content((std::istreambuf_iterator<char>(file)),
|
||||
std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
try {
|
||||
// Parsejar YAML
|
||||
auto yaml = fkyaml::node::deserialize(content);
|
||||
|
||||
// Validar versió
|
||||
if (yaml.contains("version")) {
|
||||
version = yaml["version"].get_value<std::string>();
|
||||
}
|
||||
|
||||
if (CONFIG_VERSION != version) {
|
||||
// Versió incompatible → regenerar config
|
||||
if (console) {
|
||||
std::cout << "Versió de config incompatible (esperada: "
|
||||
<< CONFIG_VERSION << ", trobada: " << version
|
||||
<< "), regenerant config\n";
|
||||
}
|
||||
init();
|
||||
saveToFile();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Carregar seccions
|
||||
loadWindowConfigFromYaml(yaml);
|
||||
loadPhysicsConfigFromYaml(yaml);
|
||||
loadGameplayConfigFromYaml(yaml);
|
||||
|
||||
if (console) {
|
||||
std::cout << "Config carregada correctament des de: " << config_file_path
|
||||
<< '\n';
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (const fkyaml::exception &e) {
|
||||
// Error de parsejat YAML → regenerar config
|
||||
if (console) {
|
||||
std::cerr << "Error parsejant YAML: " << e.what() << '\n';
|
||||
std::cerr << "Creant config nou amb valors per defecte\n";
|
||||
}
|
||||
init();
|
||||
saveToFile();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Guardar configuració al fitxer YAML
|
||||
auto saveToFile() -> bool {
|
||||
std::ofstream file(config_file_path);
|
||||
if (!file.is_open()) {
|
||||
if (console) {
|
||||
std::cerr << "No s'ha pogut obrir el fitxer de config per escriure: "
|
||||
<< config_file_path << '\n';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Escriure manualment per controlar format i comentaris
|
||||
file << "# Orni Attack - Fitxer de Configuració\n";
|
||||
file << "# Auto-generat. Les edicions manuals es preserven si són "
|
||||
"vàlides.\n\n";
|
||||
|
||||
file << "version: \"" << Project::VERSION << "\"\n\n";
|
||||
|
||||
file << "# FINESTRA\n";
|
||||
file << "window:\n";
|
||||
file << " width: " << window.width << "\n";
|
||||
file << " height: " << window.height << "\n";
|
||||
file << " fullscreen: " << (window.fullscreen ? "true" : "false") << "\n";
|
||||
file << " size_increment: " << window.size_increment << "\n\n";
|
||||
|
||||
file << "# FÍSICA (tots els valors en px/s, rad/s, etc.)\n";
|
||||
file << "physics:\n";
|
||||
file << " rotation_speed: " << physics.rotation_speed << " # rad/s\n";
|
||||
file << " acceleration: " << physics.acceleration << " # px/s²\n";
|
||||
file << " max_velocity: " << physics.max_velocity << " # px/s\n";
|
||||
file << " friction: " << physics.friction << " # px/s²\n";
|
||||
file << " enemy_speed: " << physics.enemy_speed
|
||||
<< " # unitats/frame\n";
|
||||
file << " bullet_speed: " << physics.bullet_speed
|
||||
<< " # unitats/frame\n\n";
|
||||
|
||||
file << "# GAMEPLAY\n";
|
||||
file << "gameplay:\n";
|
||||
file << " max_enemies: " << gameplay.max_enemies << "\n";
|
||||
file << " max_bullets: " << gameplay.max_bullets << "\n";
|
||||
|
||||
file.close();
|
||||
|
||||
if (console) {
|
||||
std::cout << "Config guardada a: " << config_file_path << '\n';
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Options
|
||||
48
source/game/options.hpp
Normal file
48
source/game/options.hpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Options {
|
||||
|
||||
// Estructures de configuració
|
||||
|
||||
struct Window {
|
||||
int width{640};
|
||||
int height{480};
|
||||
bool fullscreen{false};
|
||||
int size_increment{100}; // Increment per F1/F2
|
||||
};
|
||||
|
||||
struct Physics {
|
||||
float rotation_speed{3.14f}; // rad/s
|
||||
float acceleration{400.0f}; // px/s²
|
||||
float max_velocity{120.0f}; // px/s
|
||||
float friction{20.0f}; // px/s²
|
||||
float enemy_speed{2.0f}; // unitats/frame
|
||||
float bullet_speed{6.0f}; // unitats/frame
|
||||
};
|
||||
|
||||
struct Gameplay {
|
||||
int max_enemies{15};
|
||||
int max_bullets{3};
|
||||
};
|
||||
|
||||
// Variables globals (inline per evitar ODR violations)
|
||||
|
||||
inline std::string version{}; // Versió del config per validació
|
||||
inline bool console{false}; // Eixida de debug
|
||||
inline Window window{};
|
||||
inline Physics physics{};
|
||||
inline Gameplay gameplay{};
|
||||
|
||||
inline std::string config_file_path{}; // Establert per setConfigFile()
|
||||
|
||||
// Funcions públiques
|
||||
|
||||
void init(); // Inicialitzar amb valors per defecte
|
||||
void setConfigFile(
|
||||
const std::string &path); // Establir ruta del fitxer de config
|
||||
auto loadFromFile() -> bool; // Carregar config YAML
|
||||
auto saveToFile() -> bool; // Guardar config YAML
|
||||
|
||||
} // namespace Options
|
||||
89
source/legacy/asteroids.cpp
Executable file → Normal file
89
source/legacy/asteroids.cpp
Executable file → Normal file
@@ -1,6 +1,6 @@
|
||||
#include <SDL2/SDL.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#define MARGE_DALT 20
|
||||
#define MARGE_BAIX 460
|
||||
@@ -12,21 +12,17 @@
|
||||
#define VELOCITAT_MAX 6
|
||||
#define MAX_BALES 3
|
||||
|
||||
struct ipunt
|
||||
{
|
||||
struct ipunt {
|
||||
float r;
|
||||
float angle;
|
||||
};
|
||||
|
||||
struct punt
|
||||
{
|
||||
struct punt {
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
|
||||
|
||||
struct triangle
|
||||
{
|
||||
struct triangle {
|
||||
ipunt p1, p2, p3;
|
||||
punt centre;
|
||||
float angle;
|
||||
@@ -35,8 +31,7 @@ struct triangle
|
||||
|
||||
typedef std::vector<ipunt> ivector();
|
||||
|
||||
struct poligon
|
||||
{
|
||||
struct poligon {
|
||||
ivector *ipunts;
|
||||
ivector ipuntx;
|
||||
punt centre;
|
||||
@@ -63,15 +58,16 @@ std::vector<poligon> bales(MAX_BALES);
|
||||
virt : ^pvirt;
|
||||
|
||||
procedure volca;
|
||||
var i:word;
|
||||
var i : word;
|
||||
begin
|
||||
for i:=1 to 38400 do mem[$A000:i]:=mem[seg(virt^):i];
|
||||
end;
|
||||
|
||||
procedure crear_poligon_regular(var pol:poligon;n:byte;r:real);
|
||||
var i:word;act,interval:real;aux:ipunt;
|
||||
begin
|
||||
{getmem(pol.ipunts,{n*464000);}
|
||||
procedure crear_poligon_regular(var pol : poligon; n : byte; r : real);
|
||||
var i : word;
|
||||
act, interval : real;
|
||||
aux : ipunt;
|
||||
begin {getmem(pol.ipunts,{n*464000);}
|
||||
interval:=2*pi/n;
|
||||
act:=0;
|
||||
for i:=0 to n-1 do begin
|
||||
@@ -388,7 +384,8 @@ begin
|
||||
rota_pol(pol,0,1);
|
||||
instalarkb;
|
||||
repeat
|
||||
{ rota_tri(nau,nau.angle,nau.velocitat,0);}
|
||||
{
|
||||
rota_tri(nau, nau.angle, nau.velocitat, 0);}
|
||||
clsvirt;
|
||||
|
||||
if teclapuls(KEYarrowright) then nau.angle:=nau.angle+0.157079632;
|
||||
@@ -415,17 +412,20 @@ begin
|
||||
if (dx>MARGE_ESQ) and (dx<MARGE_DRET) then
|
||||
nau.centre.x:=Dx;
|
||||
if (nau.velocitat>0.1) then nau.velocitat:=nau.velocitat-0.1;
|
||||
{ dist:=distancia(nau.centre,pol.centre);
|
||||
diferencia(pol.centre,nau.centre,puntaux);
|
||||
if dist<(pol.ipuntx[1].r+30) then begin
|
||||
nau.centre.x:=nau.centre.x
|
||||
+round(dist*cos(angle(puntaux)+0.031415));
|
||||
nau.centre.y:=nau.centre.y
|
||||
+round(dist*sin(angle(puntaux)+0.031415));
|
||||
end;}
|
||||
{ for i:=1 to 5 do begin
|
||||
rota_pol(orni[i],ang,0);
|
||||
end;}
|
||||
{
|
||||
dist:
|
||||
= distancia(nau.centre, pol.centre);
|
||||
diferencia(pol.centre, nau.centre, puntaux);
|
||||
if dist
|
||||
< (pol.ipuntx[1].r + 30) then begin nau.centre.x
|
||||
: = nau.centre.x + round(dist * cos(angle(puntaux) + 0.031415));
|
||||
nau.centre.y
|
||||
: = nau.centre.y + round(dist * sin(angle(puntaux) + 0.031415));
|
||||
end;}
|
||||
{ for
|
||||
i:
|
||||
= 1 to 5 do begin rota_pol(orni[i], ang, 0);
|
||||
end;}
|
||||
for i:=1 to MAX_ORNIS do begin
|
||||
mou_orni(orni[i]);
|
||||
rota_pol(orni[i],orni[i].rotacio,1);
|
||||
@@ -439,14 +439,27 @@ begin
|
||||
end;
|
||||
waitretrace;
|
||||
volca;
|
||||
{ if aux=1 then begin {gotoxy(0,0);write('tocado')tocado;delay(200);end;}
|
||||
gotoxy(50,24);
|
||||
write('<EFBFBD> Visente i Sergi');
|
||||
gotoxy(50,25);
|
||||
write('<EFBFBD>ETA 2.2 2/6/99');
|
||||
until teclapuls(keyesc);
|
||||
desinstalarkb;
|
||||
ang:=0;
|
||||
repeat waitretrace;rota_pol(pol,ang,0); ang:=ang+0.031415 ;rota_pol(pol,ang,1);until keypressed;
|
||||
text;
|
||||
end.
|
||||
{
|
||||
if aux
|
||||
= 1 then begin {
|
||||
gotoxy(0, 0);
|
||||
write('tocado') tocado;
|
||||
delay(200);
|
||||
end;
|
||||
}
|
||||
gotoxy(50, 24);
|
||||
write('<EFBFBD> Visente i Sergi');
|
||||
gotoxy(50, 25);
|
||||
write('<EFBFBD>ETA 2.2 2/6/99');
|
||||
until teclapuls(keyesc);
|
||||
desinstalarkb;
|
||||
ang:
|
||||
= 0;
|
||||
repeat waitretrace;
|
||||
rota_pol(pol, ang, 0);
|
||||
ang:
|
||||
= ang + 0.031415;
|
||||
rota_pol(pol, ang, 1);
|
||||
until keypressed;
|
||||
text;
|
||||
end.
|
||||
@@ -2,79 +2,17 @@
|
||||
// © 1999 Visente i Sergi (versió Pascal)
|
||||
// © 2025 Port a C++20 amb SDL3
|
||||
|
||||
#include "core/rendering/sdl_manager.hpp"
|
||||
#include "game/joc_asteroides.hpp"
|
||||
#include "core/system/director.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
// Crear gestor SDL (finestra centrada 640x480 per defecte)
|
||||
SDLManager sdl;
|
||||
int main(int argc, char *argv[]) {
|
||||
// Convertir arguments a std::vector<std::string>
|
||||
std::vector<std::string> args(argv, argv + argc);
|
||||
|
||||
// Crear instància del joc
|
||||
JocAsteroides joc(sdl.obte_renderer());
|
||||
joc.inicialitzar();
|
||||
// Crear director (inicialitza sistema, opcions, configuració)
|
||||
Director director(args);
|
||||
|
||||
// Loop principal del joc
|
||||
SDL_Event event;
|
||||
bool running = true;
|
||||
|
||||
// Control de temps per delta_time
|
||||
Uint64 last_time = SDL_GetTicks();
|
||||
|
||||
while (running) {
|
||||
// Calcular delta_time real
|
||||
Uint64 current_time = SDL_GetTicks();
|
||||
float delta_time = (current_time - last_time) / 1000.0f; // Convertir ms a segons
|
||||
last_time = current_time;
|
||||
|
||||
// Limitar delta_time per evitar grans salts
|
||||
if (delta_time > 0.05f) { // Màxim 50ms (20 FPS mínim)
|
||||
delta_time = 0.05f;
|
||||
}
|
||||
|
||||
// Processar events SDL
|
||||
while (SDL_PollEvent(&event)) {
|
||||
// [NUEVO] Manejo de ventana ANTES de lógica del juego
|
||||
if (sdl.handleWindowEvent(event)) {
|
||||
continue; // Evento procesado, siguiente
|
||||
}
|
||||
|
||||
// [NUEVO] Teclas globales de ventana
|
||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_F1:
|
||||
sdl.decreaseWindowSize();
|
||||
continue;
|
||||
case SDLK_F2:
|
||||
sdl.increaseWindowSize();
|
||||
continue;
|
||||
case SDLK_F3:
|
||||
sdl.toggleFullscreen();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Procesamiento normal del juego
|
||||
joc.processar_input(event);
|
||||
|
||||
// Detectar tancament de finestra o ESC
|
||||
if (event.type == SDL_EVENT_QUIT ||
|
||||
(event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_ESCAPE)) {
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualitzar física del joc amb delta_time real
|
||||
joc.actualitzar(delta_time);
|
||||
|
||||
// Netejar pantalla (negre)
|
||||
sdl.neteja(0, 0, 0);
|
||||
|
||||
// Dibuixar joc
|
||||
joc.dibuixar();
|
||||
|
||||
// Presentar renderer (swap buffers)
|
||||
sdl.presenta();
|
||||
}
|
||||
|
||||
return 0;
|
||||
// Executar bucle principal del joc
|
||||
return director.run();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user