database.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "database.h"
  17. #include "irrlichttypes.h"
  18. /****************
  19. * Black magic! *
  20. ****************
  21. * The position hashing is very messed up.
  22. * It's a lot more complicated than it looks.
  23. */
  24. static inline s16 unsigned_to_signed(u16 i, u16 max_positive)
  25. {
  26. if (i < max_positive) {
  27. return i;
  28. } else {
  29. return i - (max_positive * 2);
  30. }
  31. }
  32. // Modulo of a negative number does not work consistently in C
  33. static inline s64 pythonmodulo(s64 i, s16 mod)
  34. {
  35. if (i >= 0) {
  36. return i % mod;
  37. }
  38. return mod - ((-i) % mod);
  39. }
  40. s64 Database::getBlockAsInteger(const v3s16 pos) const
  41. {
  42. return (u64) pos.Z * 0x1000000 +
  43. (u64) pos.Y * 0x1000 +
  44. (u64) pos.X;
  45. }
  46. v3s16 Database::getIntegerAsBlock(s64 i) const
  47. {
  48. v3s16 pos;
  49. pos.X = unsigned_to_signed(pythonmodulo(i, 4096), 2048);
  50. i = (i - pos.X) / 4096;
  51. pos.Y = unsigned_to_signed(pythonmodulo(i, 4096), 2048);
  52. i = (i - pos.Y) / 4096;
  53. pos.Z = unsigned_to_signed(pythonmodulo(i, 4096), 2048);
  54. return pos;
  55. }