66 lines
2.3 KiB
C++
66 lines
2.3 KiB
C++
#include "core/resources/palette_loader.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <filesystem>
|
|
#include <sstream>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
|
|
#include "core/rendering/surface.hpp"
|
|
#include "core/resources/resource_helper.hpp"
|
|
|
|
namespace Resource::PaletteLoader {
|
|
|
|
auto parseJasc(const std::vector<std::uint8_t>& bytes) -> Palette {
|
|
std::string content(bytes.begin(), bytes.end());
|
|
std::istringstream stream(content);
|
|
std::string line;
|
|
|
|
// Capçalera: "JASC-PAL" / "0100" / count.
|
|
std::getline(stream, line);
|
|
if (!line.starts_with("JASC-PAL")) {
|
|
throw std::runtime_error("PaletteLoader: fitxer no és JASC-PAL");
|
|
}
|
|
std::getline(stream, line); // versió, ignorada per ara
|
|
std::getline(stream, line);
|
|
int declared_count = 0;
|
|
try {
|
|
declared_count = std::stoi(line);
|
|
} catch (...) {
|
|
throw std::runtime_error("PaletteLoader: count JASC-PAL invàlid");
|
|
}
|
|
|
|
Palette palette{};
|
|
const std::size_t MAX = std::min(static_cast<std::size_t>(declared_count), palette.size());
|
|
std::size_t i = 0;
|
|
while (i < MAX && std::getline(stream, line)) {
|
|
if (line.empty()) { continue; }
|
|
std::istringstream ls(line);
|
|
int r = 0;
|
|
int g = 0;
|
|
int b = 0;
|
|
ls >> r >> g >> b;
|
|
palette[i] = 0xFF000000U | (static_cast<std::uint32_t>(r & 0xFF) << 16) | (static_cast<std::uint32_t>(g & 0xFF) << 8) | static_cast<std::uint32_t>(b & 0xFF);
|
|
++i;
|
|
}
|
|
return palette;
|
|
}
|
|
|
|
auto loadFromFile(const std::string& file_path) -> Palette {
|
|
auto ext = std::filesystem::path(file_path).extension().string();
|
|
std::ranges::transform(ext, ext.begin(), [](unsigned char c) { return std::tolower(c); });
|
|
|
|
auto bytes = Resource::Helper::loadFile(file_path);
|
|
if (bytes.empty()) {
|
|
throw std::runtime_error("PaletteLoader: no s'ha pogut llegir " + file_path);
|
|
}
|
|
|
|
if (ext == ".pal") { return parseJasc(bytes); }
|
|
if (ext == ".gif") { return loadPaletteFromGif(file_path); }
|
|
throw std::runtime_error("PaletteLoader: format de paleta no suportat: " + ext);
|
|
}
|
|
|
|
} // namespace Resource::PaletteLoader
|