Guest User

z-curve order c++ code

a guest
Nov 1st, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. // SOURCE : https://raw.githubusercontent.com/EPCCed/2019-04-16-ModernCpp/master/exercises/morton-order/bits.hpp
  2.  
  3. #ifndef MORTON_BITS_HPP
  4. #define MORTON_BITS_HPP
  5. #include <cstdint>
  6.  
  7. namespace morton {
  8.   // Go from bit pattern like
  9.   //       abcd
  10.   // to:
  11.   //   0a0b0c0d
  12.   inline uint64_t split(const uint32_t a) {
  13.     uint64_t x = a;
  14.     x = (x | x << 16) & 0x0000ffff0000ffffUL;
  15.     x = (x | x <<  8) & 0x00ff00ff00ff00ffUL;
  16.     x = (x | x <<  4) & 0x0f0f0f0f0f0f0f0fUL;
  17.     x = (x | x <<  2) & 0x3333333333333333UL;
  18.     x = (x | x <<  1) & 0x5555555555555555UL;
  19.     return x;
  20.   }
  21.  
  22.   // Reverse the above
  23.   inline uint32_t pack(const uint64_t z) {
  24.     uint64_t x = z;
  25.     x &= 0x5555555555555555UL;
  26.     x = x >> 1 | x;
  27.     x &= 0x3333333333333333UL;
  28.     x = x >> 2 | x;
  29.     x &= 0x0f0f0f0f0f0f0f0fUL;
  30.     x = x >> 4 | x;
  31.     x &= 0x00ff00ff00ff00ffUL;
  32.     x = x >> 8 | x;
  33.     x &= 0x0000ffff0000ffffUL;
  34.     x = x >> 16| x;
  35.     return x;
  36.   }
  37.  
  38.   // Compute the 2d Morton code for a pair of indices
  39.   inline uint64_t encode(const uint32_t x, const uint32_t y) {
  40.     return split(x) | split(y) << 1;
  41.   }
  42.  
  43.   // Compute the 2 indices from a Morton index
  44.   inline void decode(const uint64_t z, uint32_t& x, uint32_t& y) {
  45.     uint64_t i = z;
  46.     x = pack(i);
  47.     uint64_t j = z >> 1;
  48.     y = pack(j);
  49.   }
  50.  
  51.   const uint64_t odd_bit_mask = 0x5555555555555555UL;
  52.   const uint64_t even_bit_mask = 0xaaaaaaaaaaaaaaaaUL;
  53.  
  54.   // Move from (i, j) -> (i - 1, j)
  55.   inline uint64_t dec_x(const uint64_t z) {
  56.     return (((z & odd_bit_mask) - 1) & odd_bit_mask) | (z & even_bit_mask);
  57.   }
  58.   // Move from (i, j) -> (i + 1, j)
  59.   inline uint64_t inc_x(const uint64_t z) {
  60.     return (((z | even_bit_mask) + 1) & odd_bit_mask) | (z & even_bit_mask);
  61.   }
  62.  
  63.   // Move from (i, j) -> (i, j - 1)
  64.   inline uint64_t dec_y(const uint64_t z) {
  65.     return (z & odd_bit_mask) | (((z & even_bit_mask) - 1) & even_bit_mask);
  66.   }
  67.   // Move from (i, j) -> (i, j + 1)
  68.   inline uint64_t inc_y(const uint64_t z) {
  69.     return (z & odd_bit_mask) | (((z | odd_bit_mask) + 1) & even_bit_mask);
  70.   }
  71.  
  72. }
  73. #endif
  74.  
Add Comment
Please, Sign In to add comment