fix(opatIO): fixed header packing bug

This commit is contained in:
2025-02-16 12:15:11 -05:00
parent ba98ff5b34
commit 5345b4c801
2 changed files with 29 additions and 0 deletions

View File

@@ -11,6 +11,26 @@
#include <limits> #include <limits>
#include <deque> #include <deque>
// Function to check system endianness
bool is_big_endian() {
uint16_t test = 0x1;
return reinterpret_cast<uint8_t*>(&test)[0] == 0;
}
// Generic function to swap bytes for any type
template <typename T>
T swap_bytes(T value) {
static_assert(std::is_trivially_copyable<T>::value, "swap_bytes only supports trivial types.");
T result;
uint8_t* src = reinterpret_cast<uint8_t*>(&value);
uint8_t* dest = reinterpret_cast<uint8_t*>(&result);
for (size_t i = 0; i < sizeof(T); i++) {
dest[i] = src[sizeof(T) - 1 - i];
}
return result;
}
// Constructor // Constructor
OpatIO::OpatIO() {} OpatIO::OpatIO() {}
@@ -57,6 +77,12 @@ void OpatIO::readHeader(std::ifstream &file) {
if (file.gcount() != sizeof(Header)) { if (file.gcount() != sizeof(Header)) {
throw std::runtime_error("Error reading header from file: " + filename); throw std::runtime_error("Error reading header from file: " + filename);
} }
if (is_big_endian()) {
header.version = swap_bytes(header.version);
header.numTables = swap_bytes(header.numTables);
header.indexOffset = swap_bytes(header.indexOffset);
}
} }
// Read the table index from the file // Read the table index from the file
@@ -67,6 +93,7 @@ void OpatIO::readTableIndex(std::ifstream &file) {
if (file.gcount() != static_cast<std::streamsize>(header.numTables * sizeof(TableIndex))) { if (file.gcount() != static_cast<std::streamsize>(header.numTables * sizeof(TableIndex))) {
throw std::runtime_error("Error reading table index from file: " + filename); throw std::runtime_error("Error reading table index from file: " + filename);
} }
buildTableIDToComposition(); buildTableIDToComposition();
} }

View File

@@ -9,6 +9,7 @@
#include <map> #include <map>
#include <utility> #include <utility>
#pragma pack(1)
struct Header { struct Header {
char magic[4]; char magic[4];
uint16_t version; uint16_t version;
@@ -21,6 +22,7 @@ struct Header {
char reserved[26]; char reserved[26];
}; };
#pragma pack()
struct TableIndex { struct TableIndex {
double X; double X;
double Z; double Z;