下面列出了怎么用org.bukkit.Chunk的API类实例代码及写法,或者点击链接到github查看源代码。
@EventHandler
public void onUnload(ChunkUnloadEvent event) {
Chunk unloadedChunk = event.getChunk();
for (Entity entity : unloadedChunk.getEntities()) {
if (entity instanceof LivingEntity) {
Object handle = BukkitUnwrapper.getInstance().unwrap(entity);
if (handle instanceof ControllableEntityHandle) {
ControllableEntity controllableEntity = ((ControllableEntityHandle) handle).getControllableEntity();
if (controllableEntity != null && controllableEntity.isSpawned()) {
this.SPAWN_QUEUE.add(new EntityChunkData(controllableEntity, entity.getLocation()));
controllableEntity.despawn(DespawnReason.CHUNK_UNLOAD);
}
}
}
}
}
public static void handleToFromEvent(@Nonnull BlockFromToEvent e) {
if (e.isCancelled()) return;
// Only continue if we should stop the spread from the config.
if (!config.getBool("protection", "blockFluidSpreadIntoClaims")) return;
// If the block isn't water or lava, we don't protect it.
Material blockType = e.getBlock().getType();
if (blockType != Material.WATER && blockType != Material.LAVA) return;
Chunk from = e.getBlock().getChunk();
Chunk to = e.getToBlock().getChunk();
// If the from and to chunks have the same owner or if the to chunk is
// unclaimed, the flow is allowed.
final ChunkHandler CHUNK = ClaimChunk.getInstance().getChunkHandler();
if (getChunksSameOwner(CHUNK, from, to) || !CHUNK.isClaimed(to)) return;
// Cancel the flow
e.setCancelled(true);
}
@Override
@SuppressWarnings("unchecked")
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
types = (Expression<? extends EntityData<?>>) exprs[0];
if (matchedPattern % 2 == 0) {
for (EntityData<?> d : ((Literal<EntityData<?>>) types).getAll()) {
if (d.isPlural().isFalse() || d.isPlural().isUnknown() && !StringUtils.startsWithIgnoreCase(parseResult.expr, "all"))
return false;
}
}
isUsingRadius = matchedPattern >= 2;
if (isUsingRadius) {
radius = (Expression<Number>) exprs[exprs.length - 2];
center = (Expression<Location>) exprs[exprs.length - 1];
} else {
if (parseResult.mark == 1) {
chunks = (Expression<Chunk>) exprs[2];
} else {
worlds = (Expression<World>) exprs[1];
}
}
if (types instanceof Literal && ((Literal<EntityData<?>>) types).getAll().length == 1)
returnType = ((Literal<EntityData<?>>) types).getSingle().getType();
return true;
}
/**
* Unloads (deactivates) all shopkeepers in the given chunk.
*
* @param chunk
* the chunk
* @return the number of shops in the affected chunk
*/
int unloadShopkeepersInChunk(Chunk chunk) {
assert chunk != null;
int affectedShops = 0;
List<Shopkeeper> shopkeepers = this.getShopkeepersInChunk(new ChunkData(chunk));
if (shopkeepers != null) {
affectedShops = shopkeepers.size();
Log.debug("Unloading " + affectedShops + " shopkeepers in chunk " + chunk.getX() + "," + chunk.getZ());
for (Shopkeeper shopkeeper : shopkeepers) {
// inform shopkeeper about chunk unload:
shopkeeper.onChunkUnload();
// skip shopkeepers which are kept active all the time (ex. sign, citizens shops):
if (!shopkeeper.needsSpawning()) continue;
// deactivate:
this.deactivateShopkeeper(shopkeeper, false);
}
}
return affectedShops;
}
@EventHandler(priority = EventPriority.NORMAL)
public void OnBlockFormEvent (BlockFormEvent event) {
/* Disable cobblestone generators. */
if (ItemManager.getId(event.getNewState()) == CivData.COBBLESTONE) {
ItemManager.setTypeId(event.getNewState(), CivData.GRAVEL);
return;
}
Chunk spreadChunk = event.getNewState().getChunk();
coord.setX(spreadChunk.getX());
coord.setZ(spreadChunk.getZ());
coord.setWorldname(spreadChunk.getWorld().getName());
TownChunk tc = CivGlobal.getTownChunk(coord);
if (tc == null) {
return;
}
if (tc.perms.isFire() == false) {
if(event.getNewState().getType() == Material.FIRE) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockChange(BlockTransformEvent event) {
Match match = PGM.get().getMatchManager().getMatch(event.getWorld());
// Dont carry over old chunks into a new match
if (match == null || match.isFinished()) return;
Chunk chunk = event.getOldState().getChunk();
ChunkVector chunkVector = ChunkVector.of(chunk);
if (!chunkSnapshots.containsKey(chunkVector)) {
match.getLogger().fine("Copying chunk at " + chunkVector);
ChunkSnapshot chunkSnapshot = chunk.getChunkSnapshot();
chunkSnapshot.updateBlock(
event
.getOldState()); // ChunkSnapshot is very likely to have the post-event state already,
// so we have to correct it
chunkSnapshots.put(chunkVector, chunkSnapshot);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onWorldUnload(WorldUnloadEvent e) {
// FIXME: 24/11/2019 It's not necessary but ok.
// This is a workaround, because I don't get parsed chunk events when a
// world unloads, I think...
// So manually tell all of these shops they're unloaded.
for (final Chunk chunk : e.getWorld().getLoadedChunks()) {
final Map<Location, Shop> inChunk = plugin.getShopManager().getShops(chunk);
if (inChunk == null) {
continue;
}
for (final Shop shop : inChunk.values()) {
if (shop.isLoaded()) { //Don't unload already unloaded shops.
shop.onUnload();
}
}
}
}
private void chunkLoadPostProcess(net.minecraft.world.chunk.Chunk chunk, int x, int z) {
if (chunk != null) {
world.theChunkProviderServer.loadedChunkHashMap_KC.add(LongHash.toLong(x, z), chunk); // Passes to chunkt_TH
world.theChunkProviderServer.loadedChunks.add(chunk); // Cauldron - vanilla compatibility
chunk.onChunkLoad();
if (!chunk.isTerrainPopulated && world.theChunkProviderServer.chunkExists(x + 1, z + 1) && world.theChunkProviderServer.chunkExists(x, z + 1) && world.theChunkProviderServer.chunkExists(x + 1, z)) {
world.theChunkProviderServer.populate(world.theChunkProviderServer, x, z);
}
if (world.theChunkProviderServer.chunkExists(x - 1, z) && !world.theChunkProviderServer.provideChunk(x - 1, z).isTerrainPopulated && world.theChunkProviderServer.chunkExists(x - 1, z + 1) && world.theChunkProviderServer.chunkExists(x, z + 1) && world.theChunkProviderServer.chunkExists(x - 1, z)) {
world.theChunkProviderServer.populate(world.theChunkProviderServer, x - 1, z);
}
if (world.theChunkProviderServer.chunkExists(x, z - 1) && !world.theChunkProviderServer.provideChunk(x, z - 1).isTerrainPopulated && world.theChunkProviderServer.chunkExists(x + 1, z - 1) && world.theChunkProviderServer.chunkExists(x, z - 1) && world.theChunkProviderServer.chunkExists(x + 1, z)) {
world.theChunkProviderServer.populate(world.theChunkProviderServer, x, z - 1);
}
if (world.theChunkProviderServer.chunkExists(x - 1, z - 1) && !world.theChunkProviderServer.provideChunk(x - 1, z - 1).isTerrainPopulated && world.theChunkProviderServer.chunkExists(x - 1, z - 1) && world.theChunkProviderServer.chunkExists(x, z - 1) && world.theChunkProviderServer.chunkExists(x - 1, z)) {
world.theChunkProviderServer.populate(world.theChunkProviderServer, x - 1, z - 1);
}
}
}
@Override
public void populate(World world, Random random, Chunk chunk){
for (int x = 1; x < 15; x++) {
for (int z = 1; z < 15; z++) {
Block block = chunk.getBlock(x, 1, z);
Biome replacementBiome = getReplacementBiome(block.getBiome());
if (UhcCore.getVersion() < 16){
if (replacementBiome != null) {
block.setBiome(replacementBiome);
}
}else {
for (int y = 0; y < 200; y++) {
block = chunk.getBlock(x, y, z);
if (replacementBiome != null) {
block.setBiome(replacementBiome);
}
}
}
}
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
final Chunk chunk = event.getChunk();
Bukkit.getScheduler().runTask(GameHandler.getGameHandler().getPlugin(), new Runnable() {
@Override
public void run() {
for (Block block36 : chunk.getBlocks(Material.getMaterial(36))) {
block36.setType(Material.AIR);
block36.setMetadata("block36", new FixedMetadataValue(GameHandler.getGameHandler().getPlugin(), true));
}
for (Block door : chunk.getBlocks(Material.IRON_DOOR_BLOCK)) {
if (door.getRelative(BlockFace.DOWN).getType() != Material.IRON_DOOR_BLOCK
&& door.getRelative(BlockFace.UP).getType() != Material.IRON_DOOR_BLOCK)
door.setType(Material.BARRIER);
}
}
});
}
private int distance(Object from, Object to) {
if (is11600) {
String name1 = ((WorldDataServer) ((net.minecraft.server.v1_16_R1.Chunk) from).world.getWorldData()).getName();
String name2 = ((WorldDataServer) ((net.minecraft.server.v1_16_R1.Chunk) to).world.getWorldData()).getName();
if (!name1.equals(name2)) {
return 100;
}
} else {
if (!((net.minecraft.server.v1_14_R1.Chunk) from).world.getWorldData().getName().equals(((net.minecraft.server.v1_14_R1.Chunk) to).world.getWorldData().getName())) {
return 100;
}
}
double var2 = ((net.minecraft.server.v1_14_R1.Chunk) to).getPos().x - ((net.minecraft.server.v1_14_R1.Chunk) from).getPos().x;
double var4 = ((net.minecraft.server.v1_14_R1.Chunk) to).getPos().z - ((net.minecraft.server.v1_14_R1.Chunk) from).getPos().z;
return (int) Math.sqrt(var2 * var2 + var4 * var4);
}
@Override
public boolean doUnloadChunkFlagCheck(org.bukkit.World world, Chunk chunk)
{
for (ProtectedRegion region : this.getRegionContainer().get(world).getApplicableRegions(new ProtectedCuboidRegion("UnloadChunkFlagTester", BlockVector3.at(chunk.getX() * 16, 0, chunk.getZ() * 16), BlockVector3.at(chunk.getX() * 16 + 15, 256, chunk.getZ() * 16 + 15))))
{
if (region.getFlag(Flags.CHUNK_UNLOAD) == State.DENY)
{
if (WorldGuardSevenCommunicator.supportsForceLoad)
{
chunk.setForceLoaded(true);
chunk.load(true);
return true;
}
return false;
}
}
return true;
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
Chunk chunk = event.getChunk();
if (chunk == null || !chunk.isLoaded()) {
return;
}
Collection<Hologram> holograms = plugin.getHologramManager().getActiveHolograms().values();
for (Hologram holo : holograms) {
int chunkX = (int) Math.floor(holo.getLocation().getBlockX() / 16.0D);
int chunkZ = (int) Math.floor(holo.getLocation().getBlockZ() / 16.0D);
if (chunkX == chunk.getX() && chunkZ == chunk.getZ()) {
plugin.getServer().getScheduler().runTaskLater(plugin, holo::spawn, 10L);
}
}
}
/**
* Removes all unnamed {@link Monster}'s at the given {@link Location}.
* @param target Location to remove unnamed monsters.
*/
public void removeCreatures(@Nullable final Location target) {
if (!Settings.island_removeCreaturesByTeleport || target == null || target.getWorld() == null) {
return;
}
final int px = target.getBlockX();
final int py = target.getBlockY();
final int pz = target.getBlockZ();
for (int x = -1; x <= 1; ++x) {
for (int z = -1; z <= 1; ++z) {
Chunk chunk = target.getWorld().getChunkAt(
new Location(target.getWorld(), (px + x * 16), py, (pz + z * 16)));
Arrays.stream(chunk.getEntities())
.filter(entity -> entity instanceof Monster)
.filter(entity -> entity.getCustomName() == null)
.forEach(Entity::remove);
}
}
}
public static boolean isChunkInArea(Chunk l, Location p1, Location p2) {
if (!p1.getWorld().equals(l.getWorld())) {
return false;
}
Chunk min = new Location(p1.getWorld(), Math.min(p1.getX(), p2.getX()), Math.min(p1.getY(), p2.getY()),
Math.min(p1.getZ(), p2.getZ())).getChunk();
Chunk max = new Location(p1.getWorld(), Math.max(p1.getX(), p2.getX()), Math.max(p1.getY(), p2.getY()),
Math.max(p1.getZ(), p2.getZ())).getChunk();
return (min.getX() <= l.getX() && min.getZ() <= l.getZ() && max.getX() >= l.getX() && max.getZ() >= l.getZ());
}
@SuppressWarnings("deprecation")
@Override
public void completeOption() {
Vote weather = gameMap.getWeatherOption().getVoted();
WeatherType w = WeatherType.CLEAR;
if (weather != Vote.WEATHERSUN) {
w = WeatherType.DOWNFALL;
}
if (weather == Vote.WEATHERTHUNDER) {
gameMap.setThunderStorm(true);
gameMap.setNextStrike(Util.get().getRandomNum(3, 20));
gameMap.setStrikeCounter(0);
} else if (weather == Vote.WEATHERSNOW) {
World world = gameMap.getAlivePlayers().get(0).getWorld();
for (int x = -200; x < 200; x++) {
for (int z = -200; z < 200; z++) {
if (SkyWarsReloaded.getNMS().getVersion() < 13) {
world.setBiome(x, z, Biome.valueOf("ICE_MOUNTAINS"));
} else {
world.setBiome(x, z, Biome.SNOWY_TUNDRA);
}
}
}
List<Chunk> chunks = Util.get().getChunks(world);
for (Chunk chunk: chunks) {
world.refreshChunk(chunk.getX(), chunk.getZ());
}
}
for (Player player: gameMap.getAllPlayers()) {
player.setPlayerWeather(w);
}
}
public void updateChunks(World world, List<Chunk> chunks) {
for (Chunk currentChunk: chunks) {
net.minecraft.server.v1_8_R2.World mcWorld = ((CraftChunk) currentChunk).getHandle().world;
for (EntityHuman eh : (List<EntityHuman>) mcWorld.players) {
EntityPlayer ep = (EntityPlayer) eh;
ep.chunkCoordIntPairQueue.add(new ChunkCoordIntPair(currentChunk.getX(), currentChunk.getZ()));
}
}
}
public static WorldData fromWorld(World world) {
String worldName = world.getName();
int tileEntities = 0;
for (Chunk loadedChunk : world.getLoadedChunks()) {
tileEntities += loadedChunk.getTileEntities().length;
}
int entities = world.getEntities().size();
int chunks = world.getLoadedChunks().length;
return new WorldData(worldName, chunks, tileEntities, entities);
}
public static boolean getCanEdit(@Nonnull Chunk chunk, @Nonnull UUID plyEditor) {
// Don't block editing in worlds for which ClaimChunk has been disabled
if (config.getList("chunks", "disabledWorlds").contains(chunk.getWorld().getName())) {
return true;
}
// If the user is an admin, they have permission to override chunk claims.
if (Utils.hasAdmin(Bukkit.getPlayer(plyEditor))) {
return true;
}
// Glboal chunk handler
final ChunkHandler CHUNK = ClaimChunk.getInstance().getChunkHandler();
// This chunk's owner
final UUID PLY_OWNER = CHUNK.getOwner(chunk);
// If the chunk isn't claimed, users can't edit if the server has
// protections in unclaiemd chunks.
if (PLY_OWNER == null) {
return !blockUnclaimedChunk(chunk.getWorld().getName());
}
// If the player is the owner, they can edit it. Obviously.
if (PLY_OWNER.equals(plyEditor)) {
return true;
}
// Check if the chunk is owned by an offline player and if players
// should be allowed to edit in chunks with offline owners.
boolean isOfflineAndUnprotected = config.getBool("protection", "disableOfflineProtect")
&& Bukkit.getPlayer(PLY_OWNER) == null;
// If the player has access or if the server allows editing offline
// players' chunks, this player can edit.
return ClaimChunk.getInstance().getPlayerHandler().hasAccess(PLY_OWNER, plyEditor) || isOfflineAndUnprotected;
}
@Deprecated
public boolean unloadChunk(final String world, final Chunk chunk) {
net.minecraft.server.v1_12_R1.Chunk c = ((CraftChunk) chunk).getHandle();
c.mustSave = false;
if (chunk.isLoaded()) {
chunk.unload(false, false);
}
return true;
}
@EventHandler
public static void onChunkUnload(ChunkUnloadEvent event) {
Chunk chunk = event.getChunk();
long pair = MathMan.pairInt(chunk.getX(), chunk.getZ());
Long lastLoad = keepLoaded.get(pair);
if (lastLoad != null) {
if (Fawe.get().getTimer().getTickStart() - lastLoad < 10000) {
event.setCancelled(true);
} else {
keepLoaded.remove(pair);
}
}
}
@Override
public void populate(World world, Random random, Chunk chunk){
for (int x = 1; x < 15; x++) {
for (int z = 1; z < 15; z++) {
Block block = world.getHighestBlockAt(chunk.getBlock(x, 0, z).getLocation());
Block below = block.getRelative(BlockFace.DOWN);
if (percentage > random.nextInt(100) && (below.getType() == Material.SAND || below.getType() == Material.GRASS)){
Material water = UniversalMaterial.STATIONARY_WATER.getType();
if (
below.getRelative(BlockFace.NORTH).getType() == water ||
below.getRelative(BlockFace.EAST).getType() == water ||
below.getRelative(BlockFace.SOUTH).getType() == water ||
below.getRelative(BlockFace.WEST).getType() == water
){
if (block.getType() == Material.AIR){
int height = random.nextInt(3)+1;
Location location = block.getLocation();
while (height > 0){
world.getBlockAt(location).setType(UniversalMaterial.SUGAR_CANE_BLOCK.getType());
location = location.add(0, 1, 0);
height--;
}
}
}
}
}
}
}
public GoldenPipe(DuctType ductType, BlockLocation blockLoc, World world, Chunk chunk, DuctSettingsInventory settingsInv, GlobalDuctManager globalDuctManager, ItemDistributorService itemDistributor) {
super(ductType, blockLoc, world, chunk, settingsInv, globalDuctManager, itemDistributor);
itemFilters = new ItemFilter[Color.values().length];
for (int i = 0; i < Color.values().length; i++) {
itemFilters[i] = new ItemFilter();
}
}
@Override
public ChunkSection[] getCachedSections(World world, int cx, int cz) {
net.minecraft.server.v1_10_R1.Chunk chunk = ((org.bukkit.craftbukkit.v1_10_R1.CraftWorld) world).getHandle().getChunkProviderServer().getChunkIfLoaded(cx, cz);
if (chunk != null) {
return chunk.getSections();
}
return null;
}
public void loadChunks() {
int minX = (int) Math.floor(this.minCorner.getX());
int maxX = (int) Math.ceil(this.maxCorner.getX());
int minZ = (int) Math.floor(this.minCorner.getZ());
int maxZ = (int) Math.ceil(this.maxCorner.getZ());
for (int x = minX; x <= maxX; x += Region.CHUNK_SIZE) {
for (int z = minZ; z <= maxZ; z += Region.CHUNK_SIZE) {
Chunk chunk = this.world.getChunkAt(x, z);
if (!chunk.isLoaded()) {
chunk.load();
}
}
}
}
private void showTitle(Player player, Chunk newChunk) {
// Get the UUID of the new chunk owner
UUID newOwner = claimChunk.getChunkHandler().getOwner(newChunk.getWorld(), newChunk.getX(),
newChunk.getZ());
// Check if this player doesn't own the new chunk
if (newOwner != null && !player.getUniqueId().equals(newOwner)) {
// Get the name of the chunks for the owner of this chunk and display it
PlayerHandler ph = claimChunk.getPlayerHandler();
String newName = ph.getChunkName(newOwner);
String text = ((newName == null)
? claimChunk.getMessages().unknownChunkOwner // Something probably went wrong with the PlayerHandler
: claimChunk.getMessages().chunkOwner.replace("%%PLAYER%%", newName));
showTitleRaw(true, player, text);
// Send a message to the chunk owner if possible
if (ph.hasAlerts(newOwner)) {
Player owner = Bukkit.getPlayer(newOwner);
if (owner != null) {
if (owner.canSee(player)
|| !claimChunk.chConfig().getBool("chunks", "hideAlertsForVanishedPlayers")) {
showTitleRaw(false, owner, claimChunk.getMessages().playerEnterChunk.replace("%%PLAYER%%", player.getDisplayName()));
}
}
}
} else {
// This chunk is owned by this player
showTitleRaw(true, player, claimChunk.getMessages().chunkSelf);
}
}
@EventHandler (priority = EventPriority.MONITOR)
public void onChunkLoad(ChunkLoadEvent event) {
Chunk chunk = event.getChunk();
// Other plugins could call this event wrongly, check if the chunk is actually loaded.
if (chunk.isLoaded()) {
// In case another plugin loads the chunk asynchronously always make sure to load the holograms on the main thread.
if (Bukkit.isPrimaryThread()) {
processChunkLoad(chunk);
} else {
Bukkit.getScheduler().runTask(HolographicDisplays.getInstance(), () -> processChunkLoad(chunk));
}
}
}
public void setBiome(int x, int z, Biome bio) {
net.minecraft.world.biome.BiomeGenBase bb = CraftBlock.biomeToBiomeBase(bio);
if (this.world.blockExists(x, 0, z)) {
net.minecraft.world.chunk.Chunk chunk = this.world.getChunkFromBlockCoords(x, z);
if (chunk != null) {
byte[] biomevals = chunk.getBiomeArray();
biomevals[((z & 0xF) << 4) | (x & 0xF)] = (byte)bb.biomeID;
}
}
}
@EventHandler(ignoreCancelled = true)
public void onChunkUnloadEvent(ChunkUnloadEvent event)
{
World world = event.getWorld();
Chunk chunk = event.getChunk();
if (!this.plugin.getWorldGuardCommunicator().doUnloadChunkFlagCheck(world, chunk))
{
event.setCancelled(true);
}
}
static boolean _isAllowedClaim(ClaimChunk claimChunk, Chunk chunk) {
try {
// Generate a region in the given chunk to get all intersecting regions
int bx = chunk.getX() << 4;
int bz = chunk.getZ() << 4;
BlockVector3 pt1 = BlockVector3.at(bx, 0, bz);
BlockVector3 pt2 = BlockVector3.at(bx + 15, 256, bz + 15);
ProtectedCuboidRegion region = new ProtectedCuboidRegion("_", pt1, pt2);
RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(chunk.getWorld()));
// No regions in this world, claiming should be determined by the config
if (regionManager == null) {
return claimChunk.chConfig().getBool("worldguard", "allowClaimingInNonGuardedWorlds");
}
// If any regions in the given chunk deny chunk claiming, false is returned
for (ProtectedRegion regionIn : regionManager.getApplicableRegions(region)) {
StateFlag.State flag = regionIn.getFlag(FLAG_CHUNK_CLAIM);
if (flag == StateFlag.State.DENY) return false;
}
// No objections
return true;
} catch (Exception e) {
e.printStackTrace();
}
// An error occurred, better to be on the safe side so false is returned
return false;
}