Files
orni-attack/source/core/resources/resource_loader.cpp
T
JailDesigner efbf2457a1 Lint: inicializadores + retornos const-ref + warnings preexistentes
Primera tanda mecánica sobre el lint pendiente. Arregla la causa raíz, no
silencia diagnósticos. Detalle por categoría:

- Uninit members (cppcheck warnings) → inicializadores en declaración:
  Bullet (esta_, owner_id_, grace_timer_), Enemy (drotacio_, rotacio_,
  esta_, type_, tracking_timer_, ship_position_, tracking_strength_,
  direction_change_timer_, timer_invulnerabilitat_), Ship (is_hit_,
  invulnerable_timer_), Shape (escala_defecte_) y TitleShip (todos los
  miembros del struct, que viven dentro de un std::array<,2>).

- returnByReference (cppcheck performance) → return const T&:
  Shape::getName, ResourceLoader::getBasePath. De paso, Shape::get_nom
  se renombra a getName y get_num_primitives a getNumPrimitives para
  cumplir la convención camelBack del proyecto (lint del .clang-tidy).

- useInitializationList (cppcheck performance) →
  Starfield::shape_estrella_ pasa a la lista de inicialización (reordenada
  según la declaración para no disparar -Wreorder-ctor).

- noExplicitConstructor (cppcheck style) → explicit en ctores de 1 arg:
  Bullet(Renderer*), Enemy(Renderer*), Ship(Renderer*,...) y VectorText(Renderer*).

- variableScope (cppcheck style) → en vector_text.cpp se elimina la
  variable 'c' intermedia y se usa el literal '\\xA9' directamente en el
  único punto donde se necesita.

- constParameterReference (cppcheck style) → drawScoreboardAnimated pasa
  el VectorText por const ref (la API render/renderCentered es const).

- Warnings preexistentes del compilador (resueltos de paso):
  - stage_config.hpp: stage_id <= 255 sobre uint8_t era siempre true; se
    elimina la comparación redundante y se explica con comentario.
  - director.cpp: 'struct stat st = {.st_dev = 0};' disparaba
    -Wmissing-field-initializers; pasa a 'struct stat st{};' (zero-init
    completo, robusto a las variantes específicas del SO).
  - game_scene.cpp: stepDeathSequence devolvía un bool [[nodiscard]] que
    el caller ignoraba; el valor era puramente interno. Cambiada la
    firma a void.

- cppcheck: añadido --suppress=useStlAlgorithm. Las 26 sugerencias
  'Consider using std::any_of/find_if/count_if' son cosméticas y no
  aportan claridad sobre las raw loops actuales.

- .clang-tidy de source/core/audio/ eliminado: deshabilitaba todos los
  checks en ese subdirectorio por dependencia de jail_audio.hpp, pero
  impedía ejecutar 'make tidy' (clang-tidy aborta con "no checks
  enabled" al primer archivo del directorio). El proyecto pasa a usar
  el mismo patrón de CCAE: solo source/external/ y source/legacy/
  quedan fuera del lint.

- lint-reports/ añadido a .gitignore. Carpeta donde 'make tidy' y
  'make cppcheck' vuelcan su salida completa para inspección posterior.

Build limpio, cero warnings activos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:29:36 +02:00

144 lines
4.0 KiB
C++

// resource_loader.cpp - Implementació del carregador de recursos
// © 2026 JailDesigner
#include "resource_loader.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
namespace Resource {
// Singleton
Loader& Loader::get() {
static Loader instance;
return instance;
}
// Inicialitzar el sistema de recursos
bool Loader::initialize(const std::string& pack_file, bool enable_fallback) {
fallback_enabled_ = enable_fallback;
// Intentar load el paquet
pack_ = std::make_unique<Pack>();
if (!pack_->loadPack(pack_file)) {
if (!fallback_enabled_) {
std::cerr << "[ResourceLoader] ERROR FATAL: No es pot load " << pack_file
<< " y el fallback está desactivat\n";
return false;
}
std::cout << "[ResourceLoader] Paquet no trobat, usant fallback al sistema de archivos\n";
pack_.reset(); // No hay paquet
return true;
}
std::cout << "[ResourceLoader] Paquet carregat: " << pack_file << "\n";
return true;
}
// Carregar un recurs
std::vector<uint8_t> Loader::loadResource(const std::string& filename) {
// Intentar load del paquet primer
if (pack_) {
if (pack_->hasResource(filename)) {
auto data = pack_->getResource(filename);
if (!data.empty()) {
return data;
}
std::cerr << "[ResourceLoader] Advertència: recurs buit al paquet: " << filename
<< "\n";
}
// Si no está al paquet y no hay fallback, falla
if (!fallback_enabled_) {
std::cerr << "[ResourceLoader] ERROR: Recurs no trobat al paquet i fallback desactivat: "
<< filename << "\n";
return {};
}
}
// Fallback al sistema de archivos
if (fallback_enabled_) {
return loadFromFilesystem(filename);
}
return {};
}
// Comprovar si existeix un recurs
bool Loader::resourceExists(const std::string& filename) {
// Comprovar al paquet
if (pack_ && pack_->hasResource(filename)) {
return true;
}
// Comprovar al sistema de archivos si está activat el fallback
if (fallback_enabled_) {
std::string fullpath = base_path_.empty() ? "data/" + filename : base_path_ + "/data/" + filename;
return std::filesystem::exists(fullpath);
}
return false;
}
// Validar el paquet
bool Loader::validatePack() {
if (!pack_) {
std::cerr << "[ResourceLoader] Advertència: no hay paquet carregat per validar\n";
return false;
}
return pack_->validatePack();
}
// Comprovar si hay paquet carregat
bool Loader::isPackLoaded() const {
return pack_ != nullptr;
}
// Establir la ruta base
void Loader::setBasePath(const std::string& path) {
base_path_ = path;
std::cout << "[ResourceLoader] Ruta base establerta: " << base_path_ << "\n";
}
// Obtenir la ruta base
auto Loader::getBasePath() const -> const std::string& {
return base_path_;
}
// Carregar des del sistema de archivos (fallback)
std::vector<uint8_t> Loader::loadFromFilesystem(const std::string& filename) {
// The filename is already normalized (e.g., "shapes/logo/letra_j.shp")
// We need to prepend base_path + "data/"
std::string fullpath;
if (base_path_.empty()) {
fullpath = "data/" + filename;
} else {
fullpath = base_path_ + "/data/" + filename;
}
std::ifstream file(fullpath, std::ios::binary | std::ios::ate);
if (!file) {
std::cerr << "[ResourceLoader] Error: no es pot obrir " << fullpath << "\n";
return {};
}
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
std::cerr << "[ResourceLoader] Error: no es pot llegir " << fullpath << "\n";
return {};
}
std::cout << "[ResourceLoader] Carregat des del sistema de archivos: " << fullpath << "\n";
return data;
}
} // namespace Resource