From 1f3cf59c7f94fc8e0a0ffd2ecc635699164923a3 Mon Sep 17 00:00:00 2001 From: Erich Schubert Date: Tue, 25 Feb 2025 23:11:43 +0100 Subject: [PATCH] Clean up position encoding We can simply add 0x800800800 to the encoding, then use bit masking. This works because adding 0x800 maps -2048:2047 to 0x000:0xFFF. And 0x800800800 is (0x800 << 24 + 0x800 << 12 + 0x800) for x,y,z. After bitmasking, -0x800 restores the original value range. --- src/database/database.cpp | 47 +++++++++------------------------------ 1 file changed, 11 insertions(+), 36 deletions(-) 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) }; } -