Skip to content

Instantly share code, notes, and snippets.

@Vercidium
Last active December 6, 2019 14:34
Show Gist options
  • Save Vercidium/09d27b1386e7c668edbee7beff20bcb5 to your computer and use it in GitHub Desktop.
Save Vercidium/09d27b1386e7c668edbee7beff20bcb5 to your computer and use it in GitHub Desktop.
byte[] fileData = r.ReadBytes(bytesRemaining);
var b = 0;
for (int x = 0; x < Constants.MapSizeX; x++)
{
int chunkX = x / Constants.ChunkSize;
for (int z = 0; z < Constants.MapSizeZ; z++)
{
int chunkZ = z / Constants.ChunkSize;
// Data inside each chunk is stored in a 1D array, so pre-calculate the horizontal array access here to avoid expensive % and * operations in the inner loops
int xzAccess = (x % Constants.ChunkSize) * Constants.ChunkSize + (z % Constants.ChunkSize) * Constants.ChunkSizeSquared;
// Map-Coordinate Y, tracks our vertical position in the column
int mapY = 0;
// Get the amount of block types in this column
byte columnCount = fileData[b++];
for (int i = 0; i < columnCount; i++)
{
// Get the block type and how tall this section of the column is
var type = fileData[b++];
byte amount = fileData[b++];
// If it's an empty column, there's no need to modify the chunk data.
if (type == 0)
{
mapY += amount;
continue;
}
int chunkY = mapY / Constants.ChunkSize;
// Get the chunk and initialise it if needed
ChunkBase c = m.chunks[chunkX, chunkY, chunkZ];
if (c == null)
c = m.InitChunk(chunkX, chunkY, chunkZ);
// Chunk-Coordinate Y
int yAccess = mapY % Constants.ChunkSize;
int top = mapY + amount;
for (int j = mapY; j < top; j++)
{
// If we have moved up into a new chunk
if (yAccess == Constants.ChunkSize)
{
chunkY++;
c = m.chunks[chunkX, chunkY, chunkZ];
if (c == null)
c = m.InitChunk(chunkX, chunkY, chunkZ);
yAccess = 0;
}
// Get a reference to the block and update it
ref var block = ref c.data[xzAccess + yAccess];
block.index = type;
block.health = 100;
yAccess++;
}
mapY += amount;
}
// Update the height map
m.maxY[x, z] = (byte)mapY;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment