Created
July 26, 2016 23:37
-
-
Save Ethan-Bierlein/d26236aa6920e1958226668e930a8eff to your computer and use it in GitHub Desktop.
This file contains 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
/// <summary> | |
/// Generate the appropriate lighting for each voxel based on the voxel | |
/// data itself as a whole. | |
/// </summary> | |
public void GenerateVoxelLighting() | |
{ | |
// Fill the top layer of voxels with full lighting values to | |
// simulate sunlight hitting the top of the voxel data. | |
for(int x = 0; x < this.Width; x++) | |
{ | |
for(int z = 0; z < this.Depth; z++) | |
{ | |
Voxel currentVoxel = this.FetchVoxel(x, this.Height - 1, z); | |
currentVoxel.Lighting = 16; | |
this.SetVoxel(currentVoxel, x, this.Height - 1, z); | |
} | |
} | |
// Iterate downwards over the entire array of voxel | |
// data and determine the lighting values for the current | |
// voxel based on it's neighbors on the voxel layer | |
// above it. | |
for(int y = this.Height - 2; y >= 0; y--) | |
{ | |
// Fill the current layer with "base" lighting values. The "base" lighting | |
// values are determined using the transparency of the voxel itself with | |
// the formula "16 - transparency". | |
for(int x = 0; x < this.Width; x++) | |
{ | |
for(int z = 0; z < this.Depth; z++) | |
{ | |
Voxel currentVoxel = this.FetchVoxel(x, y, z); | |
currentVoxel.Lighting = (byte)(16 - currentVoxel.Transparency); | |
this.SetVoxel(currentVoxel, x, y, z); | |
} | |
} | |
// Fill the current layer with updated lighting values which are determined | |
// based on the neighbors of the voxels in the layer above. | |
for(int x = 0; x < this.Width; x++) | |
{ | |
for(int z = 0; z < this.Height; z++) | |
{ | |
Voxel currentVoxel = this.FetchVoxel(x, y, z); | |
Voxel currentVoxelUp = this.FetchVoxel(x, y + 1, z); | |
Voxel currentVoxelNorth = this.FetchVoxel(x, y, z + 1); | |
Voxel currentVoxelSouth = this.FetchVoxel(x, y, z - 1); | |
Voxel currentVoxelEast = this.FetchVoxel(x + 1, y, z); | |
Voxel currentVoxelWest = this.FetchVoxel(x - 1, y, z); | |
byte maxLightingValue = new byte[6] | |
{ | |
currentVoxel.Lighting, | |
currentVoxelUp.Lighting, | |
currentVoxelNorth.Lighting, | |
currentVoxelSouth.Lighting, | |
currentVoxelEast.Lighting, | |
currentVoxelWest.Lighting | |
}.Max(); | |
if(maxLightingValue == currentVoxelUp.Lighting) | |
{ | |
currentVoxel.Lighting = maxLightingValue; | |
this.SetVoxel(currentVoxel, x, y, z); | |
} | |
else | |
{ | |
currentVoxel.Lighting = (byte)MathHelper.Clamp(maxLightingValue - 1, 0, 16); | |
this.SetVoxel(currentVoxel, x, y, z); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment