I’m skimming through a very popular game’s source code at the moment and I came across these variables inside of this class.
public static final BlockPos ORIGIN = new BlockPos(0, 0, 0); private static final int NUM_X_BITS = 1 + MathHelper.calculateLogBaseTwo(MathHelper.roundUpToPowerOfTwo(30000000)); private static final int NUM_Z_BITS = NUM_X_BITS; private static final int NUM_Y_BITS = 64 - NUM_X_BITS - NUM_Z_BITS; private static final int Y_SHIFT = 0 + NUM_Z_BITS; private static final int X_SHIFT = Y_SHIFT + NUM_Y_BITS; private static final long X_MASK = (1L << NUM_X_BITS) - 1L; private static final long Y_MASK = (1L << NUM_Y_BITS) - 1L; private static final long Z_MASK = (1L << NUM_Z_BITS) - 1L;
What is the point of initializing these this way instead of just calculating it once and initializing with the answer?
The point in initializing them this way is that it makes it clear to the reader where the values come from.
I can look at the code and see that it is creating bitmasks for 64 bit values with parts X,Y,Z where the X and Z values must hold at least 30,000,000 and that is using the remaining space for the Y values.
Imagine the code looked like this:
private static final long X_MASK = 335544321 private static final long Y_MASK = 16383 private static final long Z_MASK = 335544321
Would it be as clear what the values meant? Have you memorized what ‘2^25’ is, and even if you have, do you know why ‘2^25’ was chosen?