Search code examples
c++bit-manipulationquadtreeoctree

Next iteration in z-order curve


I am building a quadtree using the techniques described in this wikipedia article. I am storing the coordinates in an 2- or 3-dimansional array.

boost::array<unsigned int, 2 /* 3 */> coord;

I need a method to calculate the coordinates of the next box in z-order. It would work by interleaving the bits, increasing by one and than deinterleaving, but this gets very complicated. I hope there is an implementation similar to the cmp_zorder(...) methon in the article wich works without interleaving the bits.


Solution

  • Ok here's the "mutilated" addition algorithm, x and y are inputs as well as outputs, and it is assumed that the lowest order bit in the interleaved coordinate would be x (the same as in the wikipedia article)

    int carry = 1;
    do
    {
        int newcarry = x & carry;
        x ^= carry;
        carry = newcarry;
        newcarry = (y & carry) << 1;
        y ^= carry;
        carry = newcarry;
    } while (carry != 0);
    

    I did test it, but only a little.