Skip to content

Instantly share code, notes, and snippets.

@iam4722202468
Created November 2, 2021 23:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iam4722202468/a9a5f43093ffc6972ed7e501d29880a0 to your computer and use it in GitHub Desktop.
Save iam4722202468/a9a5f43093ffc6972ed7e501d29880a0 to your computer and use it in GitHub Desktop.
Minestom Lighting
public void updateLighting(Pos pos, Short level) {
if (pos.blockY() < 0)
return;
int section = pos.blockY() / 16;
int sectionY = pos.blockY() % 16;
int chunkX = pos.blockX() / 16;
int sectionX = pos.blockX() % 16;
int chunkZ = pos.blockZ() / 16;
int sectionZ = pos.blockZ() % 16;
if (getChunkX() == chunkX && getChunkZ() == chunkZ) {
byte[] lightLevels = this.getSection(section).getBlockLight();
if (sectionZ < 0)
sectionZ += 16;
if (sectionX < 0)
sectionX += 16;
boolean isLower = sectionX % 2 == 0;
int toSet = (sectionX + 16 * (sectionY * 16 + sectionZ))/2;
if (lightLevels.length == 0) {
lightLevels = new byte[2048];
this.getSection(section).setSkyLight(lightLevels);
}
if (isLower) {
lightLevels[toSet] |= level.byteValue();
} else {
lightLevels[toSet] |= level.byteValue() << 4;
}
this.getSection(section).setBlockLight(lightLevels);
}
}
HashMap<Pos, Short> lightPositions = new HashMap<>();
System.out.println("Generating lighting");
chunks.forEach((chunk) -> {
chunk.getSections().forEach((sectionId, section) -> {
section.setSkyLight(new byte[2048]);
});
int posX = chunk.getChunkX();
int posZ = chunk.getChunkZ();
for (int x = 0; x < 16; ++x)
for (int y = 0; y < 256; ++y)
for (int z = 0; z < 16; ++z) {
Block b = chunk.getBlock(x,y,z);
if (b.compare(Block.LIGHT)) {
Pos currentPos = new Pos(x + posX*16, y, z + posZ * 16);
short level = Short.parseShort(b.getProperty("level"));
// if (level == 15)
// level = 23;
int powLevel = level*level;
// Add light to currentPos and surrounding areas
for (int levelX = -level; levelX < level; ++levelX) {
int powX = levelX*levelX;
for (int levelY = -level; levelY < level; ++levelY) {
int powY = levelY*levelY;
for (int levelZ = -level; levelZ < level; ++levelZ) {
int powZ = levelZ*levelZ;
if (powX + powY + powZ > powLevel)
continue;
Pos updatedPos = currentPos.add(levelX, levelY, levelZ);
short foundLevel = lightPositions.getOrDefault(updatedPos, (short) 0);
double distance = currentPos.distance(updatedPos);
// Make sure we're within a sphere
if (distance < level) {
short newLevel = (short) (level - distance);
if (newLevel > 15)
newLevel = 15;
if (newLevel < foundLevel)
newLevel = foundLevel;
lightPositions.put(updatedPos, newLevel);
}
}
}
}
}
}
});
System.out.println("Placing lighting");
lightPositions.forEach((pos, level) -> {
int chunkX = pos.blockX() / 16;
int chunkZ = pos.blockZ() / 16;
((DynamicChunk)instance.getChunk(chunkX, chunkZ)).updateLighting(pos, level);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment