BlockStorage.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "common/world/BlockStorage.h"
  2. static constexpr int SEGMENT_BITS = 6;
  3. static constexpr int SEGMENT = 1 << SEGMENT_BITS;
  4. static constexpr int SEGMENT_MASK = (1 << SEGMENT_BITS) - 1;
  5. BlockStorage::BlockStorage(int sizeBits, int heightBits)
  6. : size(1 << sizeBits), height(1 << heightBits), sizeMask(size - 1), maps((size * size * height) / SEGMENT) {
  7. }
  8. BlockId BlockStorage::get(int x, int y, int z) const {
  9. if(y < 0 || y >= height) {
  10. return 0;
  11. }
  12. x &= (size - 1);
  13. z &= (size - 1);
  14. int index = y * size * size + x * size + z;
  15. int segmentIndex = index >> SEGMENT_BITS;
  16. if(maps[segmentIndex] == nullptr) {
  17. return 0;
  18. }
  19. return maps[segmentIndex]->get(index & SEGMENT_MASK);
  20. }
  21. void BlockStorage::set(int x, int y, int z, BlockId id) {
  22. if(y < 0 || y >= height) {
  23. return;
  24. }
  25. x &= (size - 1);
  26. z &= (size - 1);
  27. int index = y * size * size + x * size + z;
  28. int segmentIndex = index >> SEGMENT_BITS;
  29. if(maps[segmentIndex] == nullptr) {
  30. if(id == 0) {
  31. return;
  32. }
  33. maps[segmentIndex] = new BlockMap(SEGMENT, 0);
  34. }
  35. maps[segmentIndex]->set(index & SEGMENT_MASK, id);
  36. }
  37. int BlockStorage::getSize() const {
  38. return size;
  39. }
  40. int BlockStorage::getHeight() const {
  41. return height;
  42. }