Last active
October 2, 2021 22:34
-
-
Save nomnomab/8722cb6ca0287b5d0b2bb186c8da19cb to your computer and use it in GitHub Desktop.
Handles converting between 1D, 2D, and 3D indexes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public readonly struct BitData { | |
public readonly int Size; | |
public readonly int BitSize; | |
public readonly int BitSizePow2; | |
public readonly int BitMask; | |
public BitData(uint size) { | |
BitSize = (int)Mathf.Sqrt(size); | |
Size = 1 << BitSize; | |
BitSizePow2 = BitSize * 2; | |
BitMask = Size - 1; | |
} | |
} | |
public static class PackedConvert { | |
public static Vector2Int Convert1Dto2D(BitData bitData, int index1D) { | |
return new Vector2Int( | |
index1D & bitData.BitMask, | |
(index1D >> bitData.BitSize) & bitData.BitMask | |
); | |
} | |
public static Vector3Int Convert1Dto3D(BitData bitData, int index1D) { | |
return new Vector3Int( | |
(index1D >> bitData.BitSizePow2) & bitData.BitMask, | |
(index1D >> bitData.BitSize) & bitData.BitMask, | |
index1D & bitData.BitMask | |
); | |
} | |
public static Vector3Int Convert1Dto3D(int index1D, int maxX, int maxY) { | |
return new Vector3Int( | |
index1D % maxX, | |
(index1D / maxX) % maxY, | |
index1D / (maxX * maxY) | |
); | |
} | |
public static int Convert2Dto1D(BitData bitData, Vector2Int index2D) { | |
return index2D.x | index2D.y << bitData.BitSize; | |
} | |
public static int Convert3Dto1D(BitData bitData, Vector3Int index3D) { | |
return index3D.z | (index3D.y << bitData.BitSize) | (index3D.x << bitData.BitSizePow2); | |
} | |
public static int Convert3Dto1D(Vector3Int index3D, int size) { | |
return index3D.x + index3D.y * size + index3D.z * size * size; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment