should prob put this on git sometime
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
#include <cassert>
|
||||
#include <fstream>
|
||||
#include <destrum/FS/AssetFS.h>
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
void AssetFS::Init(std::filesystem::path exeDir) {
|
||||
Mount("engine", exeDir / "assets/engine");
|
||||
Mount("game", exeDir / "assets/game");
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
void AssetFS::Mount(std::string scheme, std::filesystem::path root) {
|
||||
spdlog::debug("Mounting assetfs scheme '{}' to root '{}'", scheme, root.string());
|
||||
mounts.push_back({std::move(scheme), std::move(root)});
|
||||
}
|
||||
|
||||
std::vector<uint8_t> AssetFS::ReadBytes(std::string_view vpath) {
|
||||
assert(initialized && "AssetFS not initialized");
|
||||
// parse "engine://path/inside"
|
||||
auto pos = vpath.find("://");
|
||||
if (pos == std::string_view::npos) throw std::runtime_error("bad vpath");
|
||||
|
||||
std::string scheme(vpath.substr(0, pos));
|
||||
std::filesystem::path rel(std::string(vpath.substr(pos + 3)));
|
||||
|
||||
for (auto& m : mounts) {
|
||||
if (m.scheme == scheme) {
|
||||
auto full = m.root / rel;
|
||||
return ReadFile(full);
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("mount not found");
|
||||
}
|
||||
|
||||
std::filesystem::path AssetFS::GetFullPath(std::string_view vpath) const {
|
||||
assert(initialized && "AssetFS not initialized");
|
||||
// parse "engine://path/inside"
|
||||
auto pos = vpath.find("://");
|
||||
if (pos == std::string_view::npos) throw std::runtime_error("bad vpath");
|
||||
|
||||
std::string scheme(vpath.substr(0, pos));
|
||||
std::filesystem::path rel(std::string(vpath.substr(pos + 3)));
|
||||
|
||||
for (auto& m : mounts) {
|
||||
if (m.scheme == scheme) {
|
||||
auto full = m.root / rel;
|
||||
return full;
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("mount not found");
|
||||
}
|
||||
|
||||
std::vector<uint8_t> AssetFS::ReadFile(const std::filesystem::path& fullPath) {
|
||||
std::ifstream file(fullPath, std::ios::binary);
|
||||
if (!file) {
|
||||
throw std::runtime_error("failed to open file: " + fullPath.string());
|
||||
}
|
||||
|
||||
file.seekg(0, std::ios::end);
|
||||
std::streamsize size = file.tellg();
|
||||
file.seekg(0, std::ios::beg);
|
||||
std::vector<uint8_t> buffer(size);
|
||||
if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) {
|
||||
throw std::runtime_error("failed to read file: " + fullPath.string());
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
Reference in New Issue
Block a user