diff --git a/src/database/database.cpp b/src/database/database.cpp index 9182bbe95..9d3550432 100644 --- a/src/database/database.cpp +++ b/src/database/database.cpp @@ -7,48 +7,23 @@ /**************** - * Black magic! * - **************** - * The position hashing is very messed up. - * It's a lot more complicated than it looks. + * The position encoding is a bit messed up because negative + * values were not taken into account. + * But this also maps 0,0,0 to 0, which is nice, and we mostly + * need forward encoding in Luanti. */ - -static inline s16 unsigned_to_signed(u16 i, u16 max_positive) -{ - if (i < max_positive) { - return i; - } - - return i - (max_positive * 2); -} - - -// Modulo of a negative number does not work consistently in C -static inline s64 pythonmodulo(s64 i, s16 mod) -{ - if (i >= 0) { - return i % mod; - } - return mod - ((-i) % mod); -} - - s64 MapDatabase::getBlockAsInteger(const v3s16 &pos) { - return (u64) pos.Z * 0x1000000 + - (u64) pos.Y * 0x1000 + - (u64) pos.X; + return ((s64) pos.Z << 24) + ((s64) pos.Y << 12) + pos.X; } v3s16 MapDatabase::getIntegerAsBlock(s64 i) { - v3s16 pos; - pos.X = unsigned_to_signed(pythonmodulo(i, 4096), 2048); - i = (i - pos.X) / 4096; - pos.Y = unsigned_to_signed(pythonmodulo(i, 4096), 2048); - i = (i - pos.Y) / 4096; - pos.Z = unsigned_to_signed(pythonmodulo(i, 4096), 2048); - return pos; + // Offset so that all negative coordinates become non-negative + i = i + 0x800800800; + // Which is now easier to decode using simple bit masks: + return { (s16)( (i & 0xFFF) - 0x800), + (s16)(((i >> 12) & 0xFFF) - 0x800), + (s16)(((i >> 24) & 0xFFF) - 0x800) }; } -