namespace Voxel { public class Chunk { public readonly int Size = 16; public readonly int Height = 256; public readonly int PositionX; public readonly int PositionY; private Dictionary _blockData; private Blocks[] _blocks; public Chunk(int positionX, int positionY) { PositionX = positionX; PositionY = positionY; _blockData = new Dictionary(); _blocks = new Blocks[Size * Size * Height]; Initialize(); } public void SetBlock(int x, int y, int z, Blocks block) { int i = GetBlockIndex(x, y, z); _blocks[i] = block; } public void SetBlockIndex(int i, Blocks block) { _blocks[i] = block; } public Blocks GetBlock(int x, int y, int z) { int i = GetBlockIndex(x, y, z); return _blocks[i]; } public BlockData GetBlockData(int x, int y, int z) { return new BlockData(); } private void Initialize() { Random rng = new Random(); for (int i = 0; i < Size * Size * 16; i++) _blocks[i] = (Blocks)rng.Next(5); } // todo public (int x, int y, int z) IndexToPosition(int i) { int x = 0; int y = 0; int z = 0; return (x, y, z); } private int GetBlockIndex(int x, int y, int z) { return x + z * Size + y * Size * Size; } private static readonly (int dx, int dy, int dz)[] Offsets = new (int, int, int)[6] { ( 1, 0, 0), // +X (-1, 0, 0), // -X ( 0, 1, 0), // +Y ( 0, -1, 0), // -Y ( 0, 0, 1), // +Z ( 0, 0, -1) // -Z }; public ChunkMesh GetChunkMesh() { ChunkMesh chunkMesh = new ChunkMesh(Size * Size * Height / 2); // offsets table for (int x = 0; x < Size; x++) { for (int z = 0; z < Size; z++) { for (int y = 0; y < Height; y++) { for (byte face = 0; face < 6; face++) { int indexBase = y * Size * Size + z * Size + x; Blocks block = _blocks[indexBase]; if (block == Blocks.Air) continue; // ignore if air int nx = x + Offsets[face].dx; int ny = y + Offsets[face].dy; int nz = z + Offsets[face].dz; // check neighbor, ignore if at chunk edge if (nx >= 0 && nx < Size && ny >= 0 && ny < Height && nz >= 0 && nz < Size && _blocks[GetBlockIndex(nx, ny, nz)] != 0) continue; FaceData faceData = new FaceData(); faceData.Facing = (Orientation)face; faceData.Texture = BlockDefinitions.Blocks[block].FaceTextures[face]; faceData.X = (byte)x; faceData.Y = (byte)y; faceData.Z = (byte)z; chunkMesh.Faces.Add(faceData); } } } } return chunkMesh; } } }