BlockStorage.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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) {
  7. maps.resize((size * size * height) / SEGMENT);
  8. }
  9. BlockId BlockStorage::get(int x, int y, int z) const {
  10. if(y < 0 || y >= height) {
  11. return y < 0;
  12. }
  13. x &= (size - 1);
  14. z &= (size - 1);
  15. int index = y * size * size + x * size + z;
  16. int segmentIndex = index >> SEGMENT_BITS;
  17. if(maps[segmentIndex] == nullptr) {
  18. return 0;
  19. }
  20. return maps[segmentIndex]->get(index & SEGMENT_MASK);
  21. }
  22. void BlockStorage::set(int x, int y, int z, BlockId id) {
  23. if(y < 0 || y >= height) {
  24. return;
  25. }
  26. x &= (size - 1);
  27. z &= (size - 1);
  28. int index = y * size * size + x * size + z;
  29. int segmentIndex = index >> SEGMENT_BITS;
  30. if(maps[segmentIndex] == nullptr) {
  31. if(id == 0) {
  32. return;
  33. }
  34. maps[segmentIndex] = new BlockMap(SEGMENT, 0);
  35. }
  36. maps[segmentIndex]->set(index & SEGMENT_MASK, id);
  37. }
  38. int BlockStorage::getSize() const {
  39. return size;
  40. }
  41. int BlockStorage::getHeight() const {
  42. return height;
  43. }