83 lines
2.3 KiB
C++
83 lines
2.3 KiB
C++
|
|
#include "remorse/flex_archive.h"
|
||
|
|
|
||
|
|
#include "remorse/file_system.h"
|
||
|
|
|
||
|
|
namespace remorse {
|
||
|
|
namespace {
|
||
|
|
|
||
|
|
constexpr u32 flexCountOffset = 0x54;
|
||
|
|
constexpr u32 flexTableOffset = 0x80;
|
||
|
|
constexpr u32 flexEntrySize = 8;
|
||
|
|
|
||
|
|
std::optional<u32> readU32Le(const std::vector<u8>& bytes, u32 offset)
|
||
|
|
{
|
||
|
|
if (offset + 4 > bytes.size()) {
|
||
|
|
return std::nullopt;
|
||
|
|
}
|
||
|
|
|
||
|
|
return static_cast<u32>(bytes[offset]) |
|
||
|
|
(static_cast<u32>(bytes[offset + 1]) << 8) |
|
||
|
|
(static_cast<u32>(bytes[offset + 2]) << 16) |
|
||
|
|
(static_cast<u32>(bytes[offset + 3]) << 24);
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace
|
||
|
|
|
||
|
|
std::optional<FlexArchive> loadFlexArchive(const std::filesystem::path& path)
|
||
|
|
{
|
||
|
|
auto bytes = readBinaryFile(path);
|
||
|
|
if (!bytes) {
|
||
|
|
return std::nullopt;
|
||
|
|
}
|
||
|
|
|
||
|
|
const auto entryCount = readU32Le(*bytes, flexCountOffset);
|
||
|
|
if (!entryCount) {
|
||
|
|
return std::nullopt;
|
||
|
|
}
|
||
|
|
|
||
|
|
const u32 tableEnd = flexTableOffset + (*entryCount * flexEntrySize);
|
||
|
|
if (tableEnd > bytes->size()) {
|
||
|
|
return std::nullopt;
|
||
|
|
}
|
||
|
|
|
||
|
|
FlexArchive archive;
|
||
|
|
archive.entryCount = *entryCount;
|
||
|
|
archive.bytes = *bytes;
|
||
|
|
|
||
|
|
for (u32 index = 0; index < archive.entryCount; ++index) {
|
||
|
|
const u32 tableOffset = flexTableOffset + (index * flexEntrySize);
|
||
|
|
const auto dataOffset = readU32Le(archive.bytes, tableOffset);
|
||
|
|
const auto dataSize = readU32Le(archive.bytes, tableOffset + 4);
|
||
|
|
if (!dataOffset || !dataSize) {
|
||
|
|
return std::nullopt;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (*dataOffset == 0 && *dataSize == 0) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if (*dataOffset == 0 || *dataSize == 0) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if (*dataOffset > archive.bytes.size() || *dataSize > archive.bytes.size() - *dataOffset) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
archive.populatedEntries.push_back(FlexEntry{index, *dataOffset, *dataSize});
|
||
|
|
}
|
||
|
|
|
||
|
|
return archive;
|
||
|
|
}
|
||
|
|
|
||
|
|
std::optional<std::vector<u8>> readFlexEntry(const FlexArchive& archive, u32 index)
|
||
|
|
{
|
||
|
|
for (const FlexEntry& entry : archive.populatedEntries) {
|
||
|
|
if (entry.index == index) {
|
||
|
|
const auto begin = archive.bytes.begin() + entry.offset;
|
||
|
|
const auto end = begin + entry.size;
|
||
|
|
return std::vector<u8>(begin, end);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return std::nullopt;
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace remorse
|