arreglos d'estil en source/core/resources

This commit is contained in:
2025-11-18 12:41:30 +01:00
parent 4477cc4bbc
commit b7db34cdf7
9 changed files with 135 additions and 295 deletions

View File

@@ -7,10 +7,10 @@
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <utility> #include <utility>
#include "external/fkyaml_node.hpp" // Para fkyaml::node
#include "core/rendering/surface.hpp" // Para Surface #include "core/rendering/surface.hpp" // Para Surface
#include "core/resources/resource_cache.hpp" // Para Resource #include "core/resources/resource_cache.hpp" // Para Resource
#include "core/resources/resource_helper.hpp" // Para ResourceHelper #include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "external/fkyaml_node.hpp" // Para fkyaml::node
#include "utils/utils.hpp" // Para printWithDots #include "utils/utils.hpp" // Para printWithDots
// Helper: Convierte un nodo YAML de frames (array) a vector de SDL_FRect // Helper: Convierte un nodo YAML de frames (array) a vector de SDL_FRect
@@ -105,8 +105,7 @@ auto SurfaceAnimatedSprite::loadAnimationsFromYAML(const std::string& file_path,
frame_width, frame_width,
frame_height, frame_height,
frames_per_row, frames_per_row,
max_tiles max_tiles);
);
} }
animations.push_back(animation); animations.push_back(animation);
@@ -125,7 +124,7 @@ auto SurfaceAnimatedSprite::loadAnimationsFromYAML(const std::string& file_path,
} }
// Constructor con bytes YAML del cache (parsing lazy) // Constructor con bytes YAML del cache (parsing lazy)
SurfaceAnimatedSprite::SurfaceAnimatedSprite(const ResourceAnimation& cached_data) { SurfaceAnimatedSprite::SurfaceAnimatedSprite(const AnimationResource& cached_data) {
// Parsear YAML desde los bytes cargados en cache // Parsear YAML desde los bytes cargados en cache
std::string yaml_content(cached_data.yaml_data.begin(), cached_data.yaml_data.end()); std::string yaml_content(cached_data.yaml_data.begin(), cached_data.yaml_data.end());
@@ -190,8 +189,7 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(const ResourceAnimation& cached_dat
frame_width, frame_width,
frame_height, frame_height,
frames_per_row, frames_per_row,
max_tiles max_tiles);
);
} }
animations_.push_back(animation); animations_.push_back(animation);
@@ -216,7 +214,6 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(const ResourceAnimation& cached_dat
} }
} }
// Obtiene el indice de la animación a partir del nombre // Obtiene el indice de la animación a partir del nombre
auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int { auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int {
auto index = -1; auto index = -1;

View File

@@ -10,7 +10,7 @@
#include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite #include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite
class Surface; class Surface;
struct ResourceAnimation; // Forward declaration struct AnimationResource; // Forward declaration
class SurfaceAnimatedSprite : public SurfaceMovingSprite { class SurfaceAnimatedSprite : public SurfaceMovingSprite {
public: public:
@@ -31,7 +31,7 @@ class SurfaceAnimatedSprite : public SurfaceMovingSprite {
static auto loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr<Surface>& surface, float& frame_width, float& frame_height) -> std::vector<AnimationData>; // Carga las animaciones desde fichero YAML static auto loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr<Surface>& surface, float& frame_width, float& frame_height) -> std::vector<AnimationData>; // Carga las animaciones desde fichero YAML
// Constructores // Constructores
explicit SurfaceAnimatedSprite(const ResourceAnimation& cached_data); // Constructor con datos pre-cargados del cache explicit SurfaceAnimatedSprite(const AnimationResource& cached_data); // Constructor con datos pre-cargados del cache
~SurfaceAnimatedSprite() override = default; // Destructor ~SurfaceAnimatedSprite() override = default; // Destructor

View File

@@ -148,7 +148,7 @@ auto Cache::getText(const std::string& name) -> std::shared_ptr<Text> {
} }
// Obtiene los datos de animación parseados a partir de un nombre // Obtiene los datos de animación parseados a partir de un nombre
auto Cache::getAnimationData(const std::string& name) -> const ResourceAnimation& { auto Cache::getAnimationData(const std::string& name) -> const AnimationResource& {
auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; }); auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; });
if (it != animations_.end()) { if (it != animations_.end()) {
@@ -172,7 +172,7 @@ auto Cache::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
} }
// Obtiene todas las habitaciones // Obtiene todas las habitaciones
auto Cache::getRooms() -> std::vector<ResourceRoom>& { auto Cache::getRooms() -> std::vector<RoomResource>& {
return rooms_; return rooms_;
} }
@@ -197,7 +197,7 @@ void Cache::loadSounds() {
sound = JA_LoadSound(l.c_str()); sound = JA_LoadSound(l.c_str());
} }
sounds_.emplace_back(name, sound); sounds_.emplace_back(SoundResource{name, sound});
printWithDots("Sound : ", name, "[ LOADED ]"); printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress(); updateLoadingProgress();
} }
@@ -224,7 +224,7 @@ void Cache::loadMusics() {
music = JA_LoadMusic(l.c_str()); music = JA_LoadMusic(l.c_str());
} }
musics_.emplace_back(name, music); musics_.emplace_back(MusicResource{name, music});
printWithDots("Music : ", name, "[ LOADED ]"); printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress(1); updateLoadingProgress(1);
} }
@@ -238,7 +238,7 @@ void Cache::loadSurfaces() {
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
surfaces_.emplace_back(name, std::make_shared<Surface>(l)); surfaces_.emplace_back(SurfaceResource{name, std::make_shared<Surface>(l)});
surfaces_.back().surface->setTransparentColor(0); surfaces_.back().surface->setTransparentColor(0);
updateLoadingProgress(); updateLoadingProgress();
} }
@@ -261,7 +261,7 @@ void Cache::loadPalettes() {
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
palettes_.emplace_back(name, readPalFile(l)); palettes_.emplace_back(ResourcePalette{name, readPalFile(l)});
updateLoadingProgress(); updateLoadingProgress();
} }
} }
@@ -274,7 +274,7 @@ void Cache::loadTextFiles() {
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
text_files_.emplace_back(name, Text::loadTextFile(l)); text_files_.emplace_back(TextFileResource{name, Text::loadTextFile(l)});
updateLoadingProgress(); updateLoadingProgress();
} }
} }
@@ -291,7 +291,7 @@ void Cache::loadAnimations() {
// Cargar bytes del archivo YAML sin parsear (carga lazy) // Cargar bytes del archivo YAML sin parsear (carga lazy)
auto yaml_bytes = Helper::loadFile(l); auto yaml_bytes = Helper::loadFile(l);
animations_.emplace_back(name, yaml_bytes); animations_.emplace_back(AnimationResource{name, yaml_bytes});
printWithDots("Animation : ", name, "[ LOADED ]"); printWithDots("Animation : ", name, "[ LOADED ]");
updateLoadingProgress(); updateLoadingProgress();
} }
@@ -305,7 +305,7 @@ void Cache::loadRooms() {
for (const auto& l : list) { for (const auto& l : list) {
auto name = getFileName(l); auto name = getFileName(l);
rooms_.emplace_back(name, std::make_shared<Room::Data>(Room::loadYAML(l))); rooms_.emplace_back(RoomResource{name, std::make_shared<Room::Data>(Room::loadYAML(l))});
printWithDots("Room : ", name, "[ LOADED ]"); printWithDots("Room : ", name, "[ LOADED ]");
updateLoadingProgress(); updateLoadingProgress();
} }
@@ -313,15 +313,9 @@ void Cache::loadRooms() {
void Cache::createText() { void Cache::createText() {
struct ResourceInfo { struct ResourceInfo {
std::string key; // Identificador del recurso std::string key{}; // Identificador del recurso
std::string texture_file; // Nombre del archivo de textura std::string texture_file{}; // Nombre del archivo de textura
std::string text_file; // Nombre del archivo de texto std::string text_file{}; // Nombre del archivo de texto
// Constructor para facilitar la creación de objetos ResourceInfo
ResourceInfo(std::string k, std::string t_file, std::string txt_file)
: key(std::move(k)),
texture_file(std::move(t_file)),
text_file(std::move(txt_file)) {}
}; };
std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n'; std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n';
@@ -334,7 +328,7 @@ void Cache::createText() {
{"8bithud", "8bithud.gif", "8bithud.txt"}}; {"8bithud", "8bithud.gif", "8bithud.txt"}};
for (const auto& res_info : resources) { for (const auto& res_info : resources) {
texts_.emplace_back(res_info.key, std::make_shared<Text>(getSurface(res_info.texture_file), getTextFile(res_info.text_file))); texts_.emplace_back(TextResource{res_info.key, std::make_shared<Text>(getSurface(res_info.texture_file), getTextFile(res_info.text_file))});
printWithDots("Text : ", res_info.key, "[ DONE ]"); printWithDots("Text : ", res_info.key, "[ DONE ]");
} }
} }
@@ -374,13 +368,13 @@ void Cache::calculateTotal() {
List::Type::ANIMATION, List::Type::ANIMATION,
List::Type::ROOM}; List::Type::ROOM};
size_t total = 0; int total = 0;
for (const auto& asset_type : asset_types) { for (const auto& asset_type : asset_types) {
auto list = List::get()->getListByType(asset_type); auto list = List::get()->getListByType(asset_type);
total += list.size(); total += list.size();
} }
count_ = ResourceCount(total, 0); count_ = ResourceCount{total, 0};
} }
// Muestra el progreso de carga // Muestra el progreso de carga

View File

@@ -13,107 +13,78 @@ struct JA_Music_t; // lines 11-11
struct JA_Sound_t; // lines 12-12 struct JA_Sound_t; // lines 12-12
// Estructura para almacenar ficheros de sonido y su nombre // Estructura para almacenar ficheros de sonido y su nombre
struct ResourceSound { struct SoundResource {
std::string name; // Nombre del sonido std::string name{}; // Nombre del sonido
JA_Sound_t* sound; // Objeto con el sonido JA_Sound_t* sound{nullptr}; // Objeto con el sonido
// Constructor
ResourceSound(std::string name, JA_Sound_t* sound)
: name(std::move(name)),
sound(sound) {}
}; };
// Estructura para almacenar ficheros musicales y su nombre // Estructura para almacenar ficheros musicales y su nombre
struct ResourceMusic { struct MusicResource {
std::string name; // Nombre de la musica std::string name{}; // Nombre de la musica
JA_Music_t* music; // Objeto con la música JA_Music_t* music{nullptr}; // Objeto con la música
// Constructor
ResourceMusic(std::string name, JA_Music_t* music)
: name(std::move(name)),
music(music) {}
}; };
// Estructura para almacenar objetos Surface y su nombre // Estructura para almacenar objetos Surface y su nombre
struct ResourceSurface { struct SurfaceResource {
std::string name; // Nombre de la surface std::string name{}; // Nombre de la surface
std::shared_ptr<Surface> surface; // Objeto con la surface std::shared_ptr<Surface> surface{}; // Objeto con la surface
// Constructor
ResourceSurface(std::string name, std::shared_ptr<Surface> surface)
: name(std::move(name)),
surface(std::move(std::move(surface))) {}
}; };
// Estructura para almacenar objetos Palette y su nombre // Estructura para almacenar objetos Palette y su nombre
struct ResourcePalette { struct ResourcePalette {
std::string name; // Nombre de la surface std::string name{}; // Nombre de la surface
Palette palette; // Paleta Palette palette{}; // Paleta
// Constructor
ResourcePalette(std::string name, const Palette& palette)
: name(std::move(name)),
palette(palette) {}
}; };
// Estructura para almacenar ficheros TextFile y su nombre // Estructura para almacenar ficheros TextFile y su nombre
struct ResourceTextFile { struct TextFileResource {
std::string name; // Nombre del fichero std::string name{}; // Nombre del fichero
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto std::shared_ptr<Text::File> text_file{}; // Objeto con los descriptores de la fuente de texto
// Constructor
ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file)
: name(std::move(name)),
text_file(std::move(std::move(text_file))) {}
}; };
// Estructura para almacenar objetos Text y su nombre // Estructura para almacenar objetos Text y su nombre
struct ResourceText { struct TextResource {
std::string name; // Nombre del objeto std::string name{}; // Nombre del objeto
std::shared_ptr<Text> text; // Objeto std::shared_ptr<Text> text{}; // Objeto
// Constructor
ResourceText(std::string name, std::shared_ptr<Text> text)
: name(std::move(name)),
text(std::move(std::move(text))) {}
}; };
// Estructura para almacenar ficheros animaciones y su nombre // Estructura para almacenar ficheros animaciones y su nombre
struct ResourceAnimation { struct AnimationResource {
std::string name; // Nombre del fichero std::string name{}; // Nombre del fichero
std::vector<uint8_t> yaml_data; // Bytes del archivo YAML sin parsear std::vector<uint8_t> yaml_data{}; // Bytes del archivo YAML sin parsear
// Constructor
ResourceAnimation(std::string name, std::vector<uint8_t> yaml_data)
: name(std::move(name)),
yaml_data(std::move(yaml_data)) {}
}; };
// Estructura para almacenar habitaciones y su nombre // Estructura para almacenar habitaciones y su nombre
struct ResourceRoom { struct RoomResource {
std::string name; // Nombre de la habitación std::string name{}; // Nombre de la habitación
std::shared_ptr<Room::Data> room; // Habitación std::shared_ptr<Room::Data> room{}; // Habitación
// Constructor
ResourceRoom(std::string name, std::shared_ptr<Room::Data> room)
: name(std::move(name)),
room(std::move(std::move(room))) {}
}; };
namespace Resource {
class Cache {
public:
static void init(); // Inicialización singleton
static void destroy(); // Destrucción singleton
static auto get() -> Cache*; // Acceso al singleton
auto getSound(const std::string& name) -> JA_Sound_t*; // Getters de recursos
auto getMusic(const std::string& name) -> JA_Music_t*;
auto getSurface(const std::string& name) -> std::shared_ptr<Surface>;
auto getPalette(const std::string& name) -> Palette;
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>;
auto getText(const std::string& name) -> std::shared_ptr<Text>;
auto getAnimationData(const std::string& name) -> const AnimationResource&;
auto getRoom(const std::string& name) -> std::shared_ptr<Room::Data>;
auto getRooms() -> std::vector<RoomResource>&;
void reload(); // Recarga todos los recursos
private:
// Estructura para llevar la cuenta de los recursos cargados // Estructura para llevar la cuenta de los recursos cargados
struct ResourceCount { struct ResourceCount {
int total; // Número total de recursos int total{0}; // Número total de recursos
int loaded; // Número de recursos cargados int loaded{0}; // Número de recursos cargados
// Constructor
ResourceCount()
: total(0),
loaded(0) {}
// Constructor
ResourceCount(int total, int loaded)
: total(total),
loaded(loaded) {}
// Añade una cantidad a los recursos cargados // Añade una cantidad a los recursos cargados
void add(int amount) { void add(int amount) {
@@ -126,120 +97,47 @@ struct ResourceCount {
} }
}; };
namespace Resource { // Métodos de carga de recursos
class Cache {
private:
// [SINGLETON] Objeto cache privado para Don Melitón
static Cache* cache;
std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las musicas
std::vector<ResourceSurface> surfaces_; // Vector con las surfaces
std::vector<ResourcePalette> palettes_; // Vector con las paletas
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
std::vector<ResourceText> texts_; // Vector con los objetos de texto
std::vector<ResourceAnimation> animations_; // Vector con las animaciones
std::vector<ResourceRoom> rooms_; // Vector con las habitaciones
ResourceCount count_; // Contador de recursos
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
// Carga los sonidos
void loadSounds(); void loadSounds();
// Carga las musicas
void loadMusics(); void loadMusics();
// Carga las surfaces
void loadSurfaces(); void loadSurfaces();
// Carga las paletas
void loadPalettes(); void loadPalettes();
// Carga los ficheros de texto
void loadTextFiles(); void loadTextFiles();
// Carga las animaciones
void loadAnimations(); void loadAnimations();
// Carga las habitaciones
void loadRooms(); void loadRooms();
// Crea los objetos de texto
void createText(); void createText();
// Vacia todos los vectores de recursos // Métodos de limpieza
void clear(); void clear();
// Carga todos los recursos
void load();
// Vacía el vector de sonidos
void clearSounds(); void clearSounds();
// Vacía el vector de musicas
void clearMusics(); void clearMusics();
// Calcula el numero de recursos para cargar // Métodos de gestión de carga
void load();
void calculateTotal(); void calculateTotal();
// Muestra el progreso de carga
void renderProgress(); void renderProgress();
// Comprueba los eventosstatic
static void checkEvents(); static void checkEvents();
// Actualiza el progreso de carga
void updateLoadingProgress(int steps = 5); void updateLoadingProgress(int steps = 5);
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos cache desde fuera // Constructor y destructor
// Constructor
Cache(); Cache();
// Destructor
~Cache() = default; ~Cache() = default;
public: // Singleton instance
// [SINGLETON] Crearemos el objeto cache con esta función estática static Cache* cache;
static void init();
// [SINGLETON] Destruiremos el objeto cache con esta función estática // Variables miembro
static void destroy(); std::vector<SoundResource> sounds_{}; // Vector con los sonidos
std::vector<MusicResource> musics_{}; // Vector con las musicas
std::vector<SurfaceResource> surfaces_{}; // Vector con las surfaces
std::vector<ResourcePalette> palettes_{}; // Vector con las paletas
std::vector<TextFileResource> text_files_{}; // Vector con los ficheros de texto
std::vector<TextResource> texts_{}; // Vector con los objetos de texto
std::vector<AnimationResource> animations_{}; // Vector con las animaciones
std::vector<RoomResource> rooms_{}; // Vector con las habitaciones
// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él ResourceCount count_{}; // Contador de recursos
static auto get() -> Cache*; std::shared_ptr<Text> loading_text_{}; // Texto para la pantalla de carga
// Obtiene el sonido a partir de un nombre
auto getSound(const std::string& name) -> JA_Sound_t*;
// Obtiene la música a partir de un nombre
auto getMusic(const std::string& name) -> JA_Music_t*;
// Obtiene la surface a partir de un nombre
auto getSurface(const std::string& name) -> std::shared_ptr<Surface>;
// Obtiene la paleta a partir de un nombre
auto getPalette(const std::string& name) -> Palette;
// Obtiene el fichero de texto a partir de un nombre
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>;
// Obtiene el objeto de texto a partir de un nombre
auto getText(const std::string& name) -> std::shared_ptr<Text>;
// Obtiene los bytes YAML de animación a partir de un nombre (parsing lazy)
auto getAnimationData(const std::string& name) -> const ResourceAnimation&;
// Obtiene la habitación a partir de un nombre
auto getRoom(const std::string& name) -> std::shared_ptr<Room::Data>;
// Obtiene todas las habitaciones
auto getRooms() -> std::vector<ResourceRoom>&;
// Recarga todos los recursos
void reload();
}; };
} // namespace Resource } // namespace Resource

View File

@@ -1,8 +1,7 @@
// resource_helper.hpp // resource_helper.hpp
// Helper functions for resource loading (bridge to pack system) // Helper functions for resource loading (bridge to pack system)
#ifndef RESOURCE_HELPER_HPP #pragma once
#define RESOURCE_HELPER_HPP
#include <cstdint> #include <cstdint>
#include <string> #include <string>
@@ -37,5 +36,3 @@ auto shouldUseResourcePack(const std::string& filepath) -> bool;
auto isPackLoaded() -> bool; auto isPackLoaded() -> bool;
} // namespace Resource::Helper } // namespace Resource::Helper
#endif // RESOURCE_HELPER_HPP

View File

@@ -1,8 +1,7 @@
// resource_loader.hpp // resource_loader.hpp
// Singleton resource loader for managing pack and filesystem access // Singleton resource loader for managing pack and filesystem access
#ifndef RESOURCE_LOADER_HPP #pragma once
#define RESOURCE_LOADER_HPP
#include <memory> #include <memory>
#include <string> #include <string>
@@ -15,35 +14,21 @@ namespace Resource {
// Singleton class for loading resources from pack or filesystem // Singleton class for loading resources from pack or filesystem
class Loader { class Loader {
public: public:
// Get singleton instance static auto get() -> Loader&; // Singleton instance access
static auto get() -> Loader&;
// Initialize with a pack file (optional) auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool; // Initialize loader with pack file
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool;
// Load a resource (tries pack first, then filesystem if fallback enabled) auto loadResource(const std::string& filename) -> std::vector<uint8_t>; // Load resource data
auto loadResource(const std::string& filename) -> std::vector<uint8_t>; auto resourceExists(const std::string& filename) -> bool; // Check resource availability
// Check if a resource exists [[nodiscard]] auto isPackLoaded() const -> bool; // Pack status queries
auto resourceExists(const std::string& filename) -> bool;
// Check if pack is loaded
[[nodiscard]] auto isPackLoaded() const -> bool;
// Get pack statistics
[[nodiscard]] auto getPackResourceCount() const -> size_t; [[nodiscard]] auto getPackResourceCount() const -> size_t;
[[nodiscard]] auto validatePack() const -> bool; // Validate pack integrity
[[nodiscard]] auto loadAssetsConfig() const -> std::string; // Load assets.yaml from pack
// Validate pack integrity (checksum) void shutdown(); // Cleanup
[[nodiscard]] auto validatePack() const -> bool;
// Load assets.yaml from pack (for release builds) Loader(const Loader&) = delete; // Deleted copy/move constructors
[[nodiscard]] auto loadAssetsConfig() const -> std::string;
// Cleanup
void shutdown();
// Disable copy/move
Loader(const Loader&) = delete;
auto operator=(const Loader&) -> Loader& = delete; auto operator=(const Loader&) -> Loader& = delete;
Loader(Loader&&) = delete; Loader(Loader&&) = delete;
auto operator=(Loader&&) -> Loader& = delete; auto operator=(Loader&&) -> Loader& = delete;
@@ -52,18 +37,12 @@ class Loader {
Loader() = default; Loader() = default;
~Loader() = default; ~Loader() = default;
// Load from filesystem static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>; // Filesystem helpers
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>;
// Check if file exists on filesystem
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool; static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
// Member data std::unique_ptr<Pack> resource_pack_; // Member variables
std::unique_ptr<Pack> resource_pack_;
bool fallback_to_files_{true}; bool fallback_to_files_{true};
bool initialized_{false}; bool initialized_{false};
}; };
} // namespace Resource } // namespace Resource
#endif // RESOURCE_LOADER_HPP

View File

@@ -64,11 +64,12 @@ auto Pack::addFile(const std::string& filepath, const std::string& pack_name)
return false; return false;
} }
ResourceEntry entry; ResourceEntry entry{
entry.filename = pack_name; .filename = pack_name,
entry.offset = data_.size(); .offset = data_.size(),
entry.size = file_data.size(); .size = file_data.size(),
entry.checksum = calculateChecksum(file_data); .checksum = calculateChecksum(file_data)
};
// Append file data to the data block // Append file data to the data block
data_.insert(data_.end(), file_data.begin(), file_data.end()); data_.insert(data_.end(), file_data.begin(), file_data.end());
@@ -200,7 +201,7 @@ auto Pack::loadPack(const std::string& pack_file) -> bool {
file.read(filename.data(), name_len); file.read(filename.data(), name_len);
// Read entry data // Read entry data
ResourceEntry entry; ResourceEntry entry{};
entry.filename = filename; entry.filename = filename;
file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset)); file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset));
file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size)); file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));

View File

@@ -1,9 +1,7 @@
// resource_pack.hpp // resource_pack.hpp
// Resource pack file format and management for JailDoctor's Dilemma // Resource pack file format and management for JailDoctor's Dilemma
// Based on Coffee Crisis Arcade Edition resource pack system
#ifndef RESOURCE_PACK_HPP #pragma once
#define RESOURCE_PACK_HPP
#include <array> #include <array>
#include <cstdint> #include <cstdint>
@@ -15,10 +13,10 @@ namespace Resource {
// Entry metadata for each resource in the pack // Entry metadata for each resource in the pack
struct ResourceEntry { struct ResourceEntry {
std::string filename; // Relative path within pack std::string filename{}; // Relative path within pack
uint64_t offset; // Byte offset in data block uint64_t offset{0}; // Byte offset in data block
uint64_t size; // Size in bytes uint64_t size{0}; // Size in bytes
uint32_t checksum; // CRC32 checksum for verification uint32_t checksum{0}; // CRC32 checksum for verification
}; };
// Resource pack file format // Resource pack file format
@@ -30,65 +28,41 @@ class Pack {
Pack() = default; Pack() = default;
~Pack() = default; ~Pack() = default;
// Disable copy/move Pack(const Pack&) = delete; // Deleted copy/move constructors
Pack(const Pack&) = delete;
auto operator=(const Pack&) -> Pack& = delete; auto operator=(const Pack&) -> Pack& = delete;
Pack(Pack&&) = delete; Pack(Pack&&) = delete;
auto operator=(Pack&&) -> Pack& = delete; auto operator=(Pack&&) -> Pack& = delete;
// Add a single file to the pack auto addFile(const std::string& filepath, const std::string& pack_name) -> bool; // Building packs
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool; auto addDirectory(const std::string& dir_path, const std::string& base_path = "") -> bool;
// Add all files from a directory recursively auto savePack(const std::string& pack_file) -> bool; // Pack I/O
auto addDirectory(const std::string& dir_path, const std::string& base_path = "")
-> bool;
// Save the pack to a file
auto savePack(const std::string& pack_file) -> bool;
// Load a pack from a file
auto loadPack(const std::string& pack_file) -> bool; auto loadPack(const std::string& pack_file) -> bool;
// Get a resource by name auto getResource(const std::string& filename) -> std::vector<uint8_t>; // Resource access
auto getResource(const std::string& filename) -> std::vector<uint8_t>;
// Check if a resource exists
auto hasResource(const std::string& filename) const -> bool; auto hasResource(const std::string& filename) const -> bool;
// Get list of all resources
auto getResourceList() const -> std::vector<std::string>; auto getResourceList() const -> std::vector<std::string>;
// Check if pack is loaded auto isLoaded() const -> bool { return loaded_; } // Status queries
auto isLoaded() const -> bool { return loaded_; }
// Get pack statistics
auto getResourceCount() const -> size_t { return resources_.size(); } auto getResourceCount() const -> size_t { return resources_.size(); }
auto getDataSize() const -> size_t { return data_.size(); } auto getDataSize() const -> size_t { return data_.size(); }
auto calculatePackChecksum() const -> uint32_t; // Validation
// Calculate overall pack checksum (for validation)
auto calculatePackChecksum() const -> uint32_t;
private: private:
static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'}; static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'}; // Pack format constants
static constexpr uint32_t VERSION = 1; static constexpr uint32_t VERSION = 1;
static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024"; static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024";
// Calculate CRC32 checksum static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t; // Utility methods
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
// XOR encryption/decryption static void encryptData(std::vector<uint8_t>& data, const std::string& key); // Encryption/decryption
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
static void decryptData(std::vector<uint8_t>& data, const std::string& key); static void decryptData(std::vector<uint8_t>& data, const std::string& key);
// Read file from disk static auto readFile(const std::string& filepath) -> std::vector<uint8_t>; // File I/O
static auto readFile(const std::string& filepath) -> std::vector<uint8_t>;
// Member data std::unordered_map<std::string, ResourceEntry> resources_{}; // Member variables
std::unordered_map<std::string, ResourceEntry> resources_; std::vector<uint8_t> data_{}; // Encrypted data block
std::vector<uint8_t> data_; // Encrypted data block
bool loaded_{false}; bool loaded_{false};
}; };
} // namespace Resource } // namespace Resource
#endif // RESOURCE_PACK_HPP

View File

@@ -1,3 +1,3 @@
/home/sergio/gitea/jaildoctors_dilemma/source/utils/utils.hpp:8:1: error: syntax error [syntaxError] source/core/resources/resource_pack.cpp:19:18: style: Consider using std::accumulate algorithm instead of a raw loop. [useStlAlgorithm]
enum class PaletteColor : Uint8 { checksum = ((checksum << 5) + checksum) + byte;
^ ^