afegida cache a resource manager per evitar accessos a disc

This commit is contained in:
2026-03-11 18:59:56 +01:00
parent a65544e8b3
commit b79f1c3424
4 changed files with 31 additions and 11 deletions

View File

@@ -282,6 +282,13 @@ bool Engine::initialize(int width, int height, int zoom, bool fullscreen, AppMod
// No es crítico, continuar sin logo
app_logo_.reset();
}
// Precalentar caché: shapes PNG (evitar I/O en primera activación de PNG_SHAPE)
{
unsigned char* tmp = nullptr; size_t tmp_size = 0;
ResourceManager::loadResource("shapes/jailgames.png", tmp, tmp_size);
delete[] tmp;
}
}
return success;

View File

@@ -3,9 +3,11 @@
#include <iostream>
#include <fstream>
#include <cstring>
// Inicializar el puntero estático
// Inicializar estáticos
ResourcePack* ResourceManager::resourcePack_ = nullptr;
std::map<std::string, std::vector<unsigned char>> ResourceManager::cache_;
bool ResourceManager::init(const std::string& packFilePath) {
// Si ya estaba inicializado, liberar primero
@@ -29,6 +31,7 @@ bool ResourceManager::init(const std::string& packFilePath) {
}
void ResourceManager::shutdown() {
cache_.clear();
if (resourcePack_ != nullptr) {
delete resourcePack_;
resourcePack_ = nullptr;
@@ -39,36 +42,41 @@ bool ResourceManager::loadResource(const std::string& resourcePath, unsigned cha
data = nullptr;
size = 0;
// 1. Intentar cargar desde pack (si está disponible)
// 1. Consultar caché en RAM (sin I/O)
auto it = cache_.find(resourcePath);
if (it != cache_.end()) {
size = it->second.size();
data = new unsigned char[size];
std::memcpy(data, it->second.data(), size);
return true;
}
// 2. Intentar cargar desde pack (si está disponible)
if (resourcePack_ != nullptr) {
ResourcePack::ResourceData packData = resourcePack_->loadResource(resourcePath);
if (packData.data != nullptr) {
cache_[resourcePath] = std::vector<unsigned char>(packData.data, packData.data + packData.size);
data = packData.data;
size = packData.size;
return true;
}
}
// 2. Fallback: cargar desde disco
// 3. Fallback: cargar desde disco
std::ifstream file(resourcePath, std::ios::binary | std::ios::ate);
if (!file) {
// Intentar con "data/" como prefijo si no se encontró
std::string dataPath = "data/" + resourcePath;
file.open(dataPath, std::ios::binary | std::ios::ate);
if (!file) {
return false;
}
if (!file) { return false; }
}
// Obtener tamaño del archivo
size = static_cast<size_t>(file.tellg());
file.seekg(0, std::ios::beg);
// Alocar buffer y leer
data = new unsigned char[size];
file.read(reinterpret_cast<char*>(data), size);
file.close();
// Guardar en caché
cache_[resourcePath] = std::vector<unsigned char>(data, data + size);
return true;
}

View File

@@ -1,5 +1,6 @@
#pragma once
#include <map>
#include <string>
#include <vector>
@@ -79,4 +80,7 @@ private:
// Instancia del pack (nullptr si no está cargado)
static ResourcePack* resourcePack_;
// Caché en RAM para evitar I/O repetido en el bucle principal
static std::map<std::string, std::vector<unsigned char>> cache_;
};