Skip to content

Instantly share code, notes, and snippets.

@macalinao
Created May 13, 2014 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macalinao/c01f3c0076dc96afa744 to your computer and use it in GitHub Desktop.
Save macalinao/c01f3c0076dc96afa744 to your computer and use it in GitHub Desktop.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.og_mc.mattsponge;
import com.google.common.base.Stopwatch;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
/**
*
* @author ian
*/
public class BlockFinder {
public static Set<Block> findNearbyBlocks(Location l, Material m, int radius) {
Stopwatch s = new Stopwatch();
s.start();
World w = l.getWorld();
int origX = l.getBlockX();
int origZ = l.getBlockZ();
int origChunkX = origX >> 4;
int origChunkZ = origZ >> 4;
int minX = origX - radius;
int maxX = origX + radius;
int minZ = origZ - radius;
int maxZ = origZ + radius;
int radSq = radius * radius;
int chunkRadSq = (radius >> 4) * (radius >> 4);
int minChunkX = minX >> 4;
int maxChunkX = maxX >> 4;
int minChunkZ = minZ >> 4;
int maxChunkZ = maxZ >> 4;
// Find eligible blocks
Set<Block> found = new HashSet<>();
for (int chunkX = minChunkX; chunkX < maxChunkX; chunkX++) {
for (int chunkZ = minChunkZ; chunkZ < maxChunkZ; chunkZ++) {
int diffChunkX = chunkX - origChunkX;
int diffChunkZ = chunkZ - origChunkZ;
int originChunkDistSq = diffChunkX * diffChunkX + diffChunkZ * diffChunkZ;
if (originChunkDistSq > chunkRadSq) {
continue;
}
Chunk c = w.getChunkAt(chunkX, chunkZ);
// Loop through xz
chunkLoop:
for (int x = 0; x < 15; x++) {
for (int z = 0; z < 15; z++) {
int wx = (chunkX << 4) | x;
int wz = (chunkZ << 4) | z;
int diffX = wx - origX;
int diffZ = wz - origZ;
int originDistSq = diffX * diffX + diffZ * diffZ;
if (originDistSq > radSq) {
continue;
}
for (int y = 0; y < 256; y++) {
Block block = c.getBlock(x, y, z);
if (m.ordinal() == block.getTypeId()) {
found.add(block);
break chunkLoop;
}
}
}
}
}
}
s.stop();
System.out.println("elapsed " + s.elapsedMillis() + "; radius " + radius);
return found;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment