My 3D game world is stored in a flat array of bytes. The world is 1024 x 1024 in width/length and 256 high. So the array is 268435456 bytes long. To access the array I use an index pointer calculated like so :
WORLD_WIDTH_SHIFT = 10;
WORLD_HEIGHT_SHIFT = 8;
indexPointer = (((Px << WORLD_WIDTH_SHIFT) + Pz) << WORLD_HEIGHT_SHIFT) + Py;
I navigate around the array during processing by adding predefined constants to the index value for performance reasons. A move west (positive x-axis) is achieved like so:
WEST = WORLD_WIDTH * WORLD_HEIGHT;
NORTH = WORLD_HEIGHT;
SOUTH = -WORLD_HEIGHT;
WEST = WORLD_WIDTH * WORLD_HEIGHT;
EAST = -WORLD_WIDTH * WORLD_HEIGHT;
UP = 1;
DOWN = -1;
indexPointer += WEST;
To prevent the index going out of range and to what I stupidly thought would achieve wrapping I added a bit mask to the result:
WORLD_ARRAY_SIZE = WORLD_WIDTH * WORLD_WIDTH * WORLD_HEIGHT;
WORLD_ARRAY_SIZE_MASK = WORLD_ARRAY_SIZE - 1;
WEST = WORLD_WIDTH * WORLD_HEIGHT;
indexPointer = (indexPointer + WEST) & WORLD_ARRAY_SIZE_MASK;
This works fine on the x-axis above but on the z-axis (north-south) the wrapping as I discovered after giving it some thought is obviously not going to work. Correct me if I'm wrong but I need a way to perform a bit mask on the bits that represent the z coordinate within indexPointer. First 8 bits are the height, next 10 bits are z coord and final 10 bits are x coord. Is there a way to perform this without extracting the 10 bits into a separate field then performing the addition and mask and then having to reconstruct the final pointer ?