@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); if (isDeathSign(block)) { BlockState state = block.getState(); Sign sign = (Sign) state; ItemStack stack = new ItemStack(Material.SIGN, 1); ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(DEATH_SIGN_ITEM_NAME); meta.setLore(Arrays.asList(sign.getLines())); stack.setItemMeta(meta); Player player = event.getPlayer(); World world = player.getWorld(); if (player.getGameMode() != GameMode.CREATIVE && world.isGameRule("doTileDrops")) { world.dropItemNaturally(block.getLocation(), stack); } // Manually handle the dropping event.setCancelled(true); block.setType(Material.AIR); state.update(); } }
@EventWrapper public void onBlockIgnite(final BlockIgniteEvent event) { // Flint & steel generates a BlockPlaceEvent if(event.getCause() == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) return; BlockState oldState = event.getBlock().getState(); BlockState newState = BlockStateUtils.cloneWithMaterial(event.getBlock(), Material.FIRE); ParticipantState igniter = null; if(event.getIgnitingEntity() != null) { // The player themselves using flint & steel, or any of // several types of owned entity starting or spreading a fire. igniter = entityResolver.getOwner(event.getIgnitingEntity()); } else if(event.getIgnitingBlock() != null) { // Fire, lava, or flint & steel in a dispenser igniter = blockResolver.getOwner(event.getIgnitingBlock()); } callEvent(event, oldState, newState, igniter); }
public String getCropState(BlockState blockState) { switch (blockState.getType()) { // .getBlock().getType()) { case COCOA: return ((CocoaPlant) blockState.getData()).getSize().toString(); case NETHER_WARTS: return ((NetherWarts) blockState.getData()).getState().toString(); case MELON_STEM: return (int) blockState.getBlock().getData() + ""; case PUMPKIN_STEM: return (int) blockState.getBlock().getData() + ""; case CACTUS: return null; case BROWN_MUSHROOM: return null; case RED_MUSHROOM: return null; case SUGAR_CANE_BLOCK: return null; default: //CropControl.getPlugin().debug("Unable to find CropState match for {0}", blockState); return ((Crops) blockState.getData()).getState().toString(); } }
/** * Prevents trees from growing outside of the protected area. * * @param e */ @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onTreeGrow(final StructureGrowEvent e) { if (DEBUG) { plugin.getLogger().info(e.getEventName()); } // Check world if (!Util.inWorld(e.getLocation())) { return; } // Check if this is on an island Island island = plugin.getIslands().getIslandAt(e.getLocation()); if (island == null || island.isSpawn()) { return; } Iterator<BlockState> it = e.getBlocks().iterator(); while (it.hasNext()) { BlockState b = it.next(); if (b.getType() == Material.LOG || b.getType() == Material.LOG_2 || b.getType() == Material.LEAVES || b.getType() == Material.LEAVES_2) { if (!island.onIsland(b.getLocation())) { it.remove(); } } } }
/** * Converts trees to gravel and glowstone * * @param e */ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onTreeGrow(final StructureGrowEvent e) { if (DEBUG) plugin.getLogger().info("DEBUG: " + e.getEventName()); if (!Settings.netherTrees) { return; } if (!Settings.netherGenerate || IslandWorld.getNetherWorld() == null) { return; } // Check world if (!e.getLocation().getWorld().equals(IslandWorld.getNetherWorld())) { return; } for (BlockState b : e.getBlocks()) { if (b.getType() == Material.LOG || b.getType() == Material.LOG_2) { b.setType(Material.GRAVEL); } else if (b.getType() == Material.LEAVES || b.getType() == Material.LEAVES_2) { b.setType(Material.GLOWSTONE); } } }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void checkItemFrameRotate(PlayerInteractEntityEvent event) { if(event.getRightClicked() instanceof ItemFrame) { ItemFrame itemFrame = (ItemFrame) event.getRightClicked(); if(itemFrame.getItem() != null) { // If frame contains an item, right-click will rotate it, which is handled as a "use" event this.handleUse(event, getHangingBlockState(itemFrame), this.match.getParticipant(event.getPlayer())); } else if(event.getPlayer().getItemInHand() != null) { // If the frame is empty and it's right clicked with an item, this will place the item in the frame, // which is handled as a "place" event, with the placed item as the block material BlockState blockState = BlockStateUtils.cloneWithMaterial(itemFrame.getLocation().getBlock(), event.getPlayer().getItemInHand().getData()); this.handleHangingPlace(event, blockState, event.getPlayer()); } } }
private void handleUse(Event event, BlockState blockState, MatchPlayer player) { if(!player.canInteract()) return; PlayerBlockEventQuery query = new PlayerBlockEventQuery(player, event, blockState); for(EventRule rule : this.ruleContext.get(EventRuleScope.USE)) { if(rule.region().contains(blockState)) { if(processQuery(rule, query)) { if(query.getEvent() instanceof PlayerInteractEvent && ((PlayerInteractEvent) query.getEvent()).isCancelled()) { PlayerInteractEvent pie = (PlayerInteractEvent) query.getEvent(); pie.setCancelled(false); pie.setUseItemInHand(Event.Result.ALLOW); pie.setUseInteractedBlock(Event.Result.DENY); if(rule.message() != null) { player.sendWarning(rule.message(), false); } } if(this.useRegionPriority) { break; } } } } }
public static void setTileEntityNBTTagCompound(BlockState tile, Object nbtTag) { Object pos = toBlockPosition(new BlockPos() { @Override public int getX() { return tile.getX(); } @Override public int getY() { return tile.getY(); } @Override public int getZ() { return tile.getZ(); } }); Object nmsWorld = getWorldServer(tile.getWorld()); if (nmsWorld == null || pos == null) return; Object nmsTile = getDeclaredMethod("getTileEntity", nmsWorld.getClass(), pos.getClass()).invoke(nmsWorld, true, pos); getDeclaredMethod("a", getNmsClass("TileEntity"), getNmsClass("NBTTagCompound")).invoke(nmsTile, true, nbtTag); }
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onBlockPlace(BlockPlaceEvent event) { ItemStack stack = event.getItemInHand(); BlockState state = event.getBlock().getState(); if (state instanceof Sign && stack.hasItemMeta()) { ItemMeta meta = stack.getItemMeta(); if (meta.hasDisplayName() && meta.getDisplayName().equals(DEATH_SIGN_ITEM_NAME)) { Sign sign = (Sign) state; List<String> lore = meta.getLore(); int count = 0; for (String loreLine : lore) { sign.setLine(count++, loreLine); if (count == 4) break; } sign.update(); //sign.setEditible(false); } } }
@EventHandler(ignoreCancelled=true, priority=EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); if (isEventSign(block)) { BlockState state = block.getState(); Sign sign = (Sign)state; ItemStack stack = new ItemStack(Material.SIGN, 1); ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(EVENT_SIGN_ITEM_NAME); meta.setLore(Arrays.asList(sign.getLines())); stack.setItemMeta(meta); Player player = event.getPlayer(); World world = player.getWorld(); Location blockLocation = block.getLocation(); if ((player.getGameMode() != GameMode.CREATIVE) && (world.isGameRule("doTileDrops"))) { world.dropItemNaturally(blockLocation, stack); } event.setCancelled(true); block.setType(Material.AIR); state.update(); } }
public static boolean placeStanding(Location location, BannerMeta meta) { Block block = location.getBlock(); block.setType(Material.STANDING_BANNER, false); final BlockState state = block.getState(); if(state instanceof Banner) { Banner banner = (Banner) block.getState(); applyToBlock(banner, meta); org.bukkit.material.Banner material = (org.bukkit.material.Banner) banner.getData(); material.setFacingDirection(BlockFaces.yawToFace(location.getYaw())); banner.setData(material); banner.update(true); return true; } return false; }
public boolean canRenew(BlockState original, BlockState current) { // Original block must be in the region and match the renewable filter if(!region.contains(original)) return false; BlockQuery originalQuery = new BlockQuery(original); if(!renewableBlocks.query(originalQuery).isAllowed()) return false; MaterialData originalMaterial = original.getMaterialData(); MaterialData currentMaterial = current.getMaterialData(); // If current material matches the original, block is already renewed if(originalMaterial.equals(currentMaterial)) return false; // If the original and current blocks are both shuffleable, block is already renewed if(shuffleableBlocks.query(originalQuery).isAllowed() && shuffleableBlocks.query(new BlockQuery(current)).isAllowed()) { return false; } // Otherwise, block is eligible to be renewed return true; }
@EventWrapper public void onBlockBurn(final BlockBurnEvent event) { Match match = PGM.getMatchManager().getMatch(event.getBlock().getWorld()); if(match == null) return; BlockState oldState = event.getBlock().getState(); BlockState newState = BlockStateUtils.toAir(oldState); MatchPlayerState igniterState = null; for(BlockFace face : NEIGHBORS) { Block neighbor = oldState.getBlock().getRelative(face); if(neighbor.getType() == Material.FIRE) { igniterState = blockResolver.getOwner(neighbor); if(igniterState != null) break; } } this.callEvent(event, oldState, newState, igniterState); }
boolean renew(BlockVector pos, MaterialData material) { // We need to do the entity check here rather than canRenew, because we are not // notified when entities move in our out of the way. if(!isClearOfEntities(pos)) return false; Location location = pos.toLocation(match.getWorld()); Block block = location.getBlock(); BlockState newState = location.getBlock().getState(); newState.setMaterialData(material); BlockRenewEvent event = new BlockRenewEvent(block, newState, this); match.callEvent(event); // Our own handler will get this and remove the block from the pool if(event.isCancelled()) return false; newState.update(true, true); if(definition.particles) { NMSHacks.playBlockBreakEffect(match.getWorld(), pos, material.getItemType()); } if(definition.sound) { NMSHacks.playBlockPlaceSound(match.getWorld(), pos, material.getItemType(), 1f); } return true; }
@EventHandler(ignoreCancelled=true, priority=EventPriority.HIGHEST) public void onBlockPlace(BlockPlaceEvent event) { ItemStack stack = event.getItemInHand(); BlockState state = event.getBlock().getState(); if (((state instanceof Sign)) && (stack.hasItemMeta())) { ItemMeta meta = stack.getItemMeta(); if ((meta.hasDisplayName()) && (meta.getDisplayName().equals(EVENT_SIGN_ITEM_NAME))) { Sign sign = (Sign)state; List<String> lore = meta.getLore(); int count = 0; for (String loreLine : lore) { sign.setLine(count++, loreLine); if (count == 4) { break; } } sign.update(); } } }
private void setBlockUpdate(Location location, Material material, BlockState blockState) { // Send to all web clients to let them know it changed using the "B," command int type = toWebBlockType(material, blockState); if (type == -1) { if (warnMissing) { webSocketServerThread.log(Level.WARNING, "Block type missing from blocks_to_web: " + material + " at " + location); } type = blocksToWebMissing; } int x = toWebLocationBlockX(location); int y = toWebLocationBlockY(location); int z = toWebLocationBlockZ(location); webSocketServerThread.broadcastLine("B,0,0,"+x+","+y+","+z+","+type); String blockDataCommand = this.getDataBlockUpdateCommand(location, material, blockState); if (blockDataCommand != null) { webSocketServerThread.broadcastLine(blockDataCommand); } webSocketServerThread.log(Level.FINEST, "notified block update: ("+x+","+y+","+z+") to "+type); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockChange(BlockTransformEvent event) { BlockState newState = event.getNewState(); Block block = newState.getBlock(); long pos = encodePos(block); // Only breaks are credited. Making a bridge fall by updating a block // does not credit you with breaking the bridge. ParticipantState breaker = event.isBreak() ? ParticipantBlockTransformEvent.getPlayerState(event) : null; if(!(event.getCause() instanceof BlockFallEvent)) { this.disturb(pos, newState, breaker); } for(BlockFace face : NEIGHBORS) { this.disturb(neighborPos(pos, face), block.getRelative(face).getState(), breaker); } }
private String getDataBlockUpdateCommand(Location location, Material material, BlockState blockState) { if (material == null || material == Material.AIR) return null; int light_level = toWebLighting(material, blockState); if (light_level != 0) { int x = toWebLocationBlockX(location); int y = toWebLocationBlockY(location); int z = toWebLocationBlockZ(location); return "L,0,0,"+x+","+y+","+z+"," + light_level; } if (material == Material.WALL_SIGN || material == Material.SIGN_POST) { Block block = location.getWorld().getBlockAt(location); if (blockState instanceof Sign) { Sign sign = (Sign) blockState; return getNotifySignChange(block.getLocation(), block.getType(), block.getState(), sign.getLines()); } } return null; }
@SuppressWarnings("deprecation") @EventWrapper public void onBlockFromTo(BlockFromToEvent event) { if(event.getToBlock().getType() != event.getBlock().getType()) { BlockState oldState = event.getToBlock().getState(); BlockState newState = event.getToBlock().getState(); newState.setType(event.getBlock().getType()); newState.setRawData(event.getBlock().getData()); // Check for lava ownership this.callEvent(event, oldState, newState, blockResolver.getOwner(event.getBlock())); } }
public WorldInfo(World world) { this.worldName = world.getName(); this.totalOnline = world.getPlayers().size(); for (Entity entity : world.getEntities()) { this.totalEntity++; if (entity instanceof Animals) { this.totalAnimals++; } else if (entity instanceof Monster) { this.totalMonsters++; } else if (entity instanceof Item) { this.totalDropItem++; } } for (Chunk loadedChunk : world.getLoadedChunks()) { this.totalChunk++; for (BlockState tiles : loadedChunk.getTileEntities()) { this.totalTiles++; if (tiles instanceof Hopper) { this.totalHopper++; } else if (tiles instanceof Chest) { this.totalChest++; } else if (tiles instanceof Dispenser) { this.totalDispenser++; } else if (tiles instanceof Dropper) { this.totalDropper++; } else if (tiles instanceof BrewingStand) { this.totalBrewingStand++; } } } }
@Nullable public static String getOutput(@Nullable Object object) { if (object == null) { return null; } if (object instanceof String) { return (String) object; } else if (object instanceof Collection) { return handleCollection((Collection) object); } else if (object instanceof Map) { return handleMap((Map) object); } else if (object.getClass().isArray()) { return handleArray(object); } else if (object instanceof OfflinePlayer) { return handleOfflinePlayer((OfflinePlayer) object); } else if (object instanceof BlockState) { return handleBlockState((BlockState) object); } else if (object instanceof Inventory) { return handleInventory((Inventory) object); } else if (object instanceof WorldBorder) { return handleWorldBorder((WorldBorder) object); } else if (object instanceof CommandSender) { return handleCommandSender((CommandSender) object); } else if (object instanceof Messenger) { return handleMessenger((Messenger) object); } else if (object instanceof HelpMap) { return handleHelpMap((HelpMap) object); } else { return String.valueOf(object); } }
@EventWrapper public void onBlockPistonExtend(final BlockPistonExtendEvent event) { Map<Block, BlockState> newStates = new HashMap<>(); // Add the arm of the piston, which will extend into the adjacent block. PistonExtensionMaterial pistonExtension = new PistonExtensionMaterial(Material.PISTON_EXTENSION); pistonExtension.setFacingDirection(event.getDirection()); BlockState pistonExtensionState = event.getBlock().getRelative(event.getDirection()).getState(); pistonExtensionState.setType(pistonExtension.getItemType()); pistonExtensionState.setData(pistonExtension); newStates.put(event.getBlock(), pistonExtensionState); this.onPistonMove(event, event.getBlocks(), newStates); }
public boolean setRawTypeIdAndData(int x, int y, int z, int type, int data) { BlockState state = world.getBlockAt(x, y, z).getState(); state.setTypeId(type); state.setData(new MaterialData(type, (byte) data)); blocks.add(state); return true; }
public int getTypeId(int x, int y, int z) { for (BlockState state : blocks) { if (state.getX() == x && state.getY() == y && state.getZ() == z) { return state.getTypeId(); } } return world.getBlockTypeIdAt(x, y, z); }
public boolean isEmpty(int x, int y, int z) { for (BlockState state : blocks) { if (state.getX() == x && state.getY() == y && state.getZ() == z) { return net.minecraft.block.Block.getBlockById(state.getTypeId()) == net.minecraft.init.Blocks.air; } } return world.getBlockAt(x, y, z).isEmpty(); }
private void handleHangingPlace(Event event, BlockState blockState, Entity placer) { IEventQuery query = makeBlockQuery(event, placer, blockState); for(EventRule rule : this.ruleContext.get(EventRuleScope.BLOCK_PLACE)) { if(rule.region().contains(blockState)) { if(processQuery(rule, query)) { sendCancelMessage(rule, query); if(this.useRegionPriority) break; } } } }
private void handleHangingBreak(Event event, Hanging hanging, Entity breaker) { BlockState blockState = getHangingBlockState(hanging); if(blockState == null) return; IEventQuery query = makeBlockQuery(event, breaker, blockState); for(EventRule rule : this.ruleContext.get(EventRuleScope.BLOCK_BREAK)) { if(rule.region().contains(blockState)) { if(processQuery(rule, query)) { sendCancelMessage(rule, query); if(this.useRegionPriority) break; } } } }
@EventHandler public void onSignElevator(PlayerInteractEvent e) { if (e.getClickedBlock() == null) { return; } Block block = e.getClickedBlock(); BlockState state = block.getState(); if (state instanceof Sign) { if(e.getAction() == Action.RIGHT_CLICK_BLOCK) { Sign sign = (Sign)state; double zdif = Math.abs(e.getPlayer().getLocation().getZ() - block.getLocation().getZ()); double xdif = Math.abs(e.getPlayer().getLocation().getX() - block.getLocation().getX()); String lineZero = sign.getLine(0); String lineOne = sign.getLine(1); if(ChatColor.stripColor(lineZero).equalsIgnoreCase("[Elevator]")) { if(zdif < 1.5D && xdif < 1.5D ) { if (ChatColor.stripColor(lineOne).equalsIgnoreCase("Up")) { e.getPlayer().teleport(this.teleportSpotUp(block.getLocation(), block.getLocation().getBlockY(), 254)); } if (ChatColor.stripColor(lineOne).equalsIgnoreCase("Down")) { e.getPlayer().teleport(this.teleportSpotDown(block.getLocation(), block.getLocation().getBlockY(), 1)); } } else { e.getPlayer().sendMessage(ChatColor.RED + "You must be standing next to the sign!"); } } e.setCancelled(true); return; } } }
@SuppressWarnings("deprecation") @EventWrapper public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) { Block block = event.getBlockClicked().getRelative(event.getBlockFace()); Material contents = Materials.materialInBucket(event.getBucket()); if(contents == null) { return; } BlockState newBlock = BlockStateUtils.cloneWithMaterial(block, contents); this.callEvent(event, block.getState(), newBlock, event.getPlayer()); }
private void replaceBlock(BlockDrops drops, Block block, MatchPlayer player) { if(drops.replacement != null) { EntityChangeBlockEvent event = new EntityChangeBlockEvent(player.getBukkit(), block, drops.replacement); getMatch().callEvent(event); if(!event.isCancelled()) { BlockState state = block.getState(); state.setType(drops.replacement.getItemType()); state.setData(drops.replacement); state.update(true, true); } } }
public void notifyBlockUpdate(Location location, Material material, BlockState blockState) { webSocketServerThread.log(Level.FINEST, "bukkit block at "+location+" was set to "+material); if (!withinSandboxRange(location)) { // Clients don't need to know about every block change on the server, only within the sandbox return; } setBlockUpdate(location, material, blockState); webSocketServerThread.broadcastLine("R,0,0"); }
private BlockTransformEvent callEvent(Event cause, BlockState oldState, BlockState newState, @Nullable MatchPlayerState player) { BlockTransformEvent event; if(player == null) { event = new BlockTransformEvent(cause, oldState, newState); } else if(player instanceof ParticipantState) { event = new ParticipantBlockTransformEvent(cause, oldState, newState, (ParticipantState) player); } else { event = new PlayerBlockTransformEvent(cause, oldState, newState, player); } callEvent(event); return event; }
boolean canRenew(BlockState currentState) { // Must not already be new if(isNew(currentState)) return false; // Must grow from an adjacent block that is renewed if(definition.growAdjacent && !hasNewNeighbor(currentState)) return false; // Current block must be replaceable if(!definition.replaceableBlocks.query(new BlockQuery(currentState)).isAllowed()) return false; return true; }
MaterialData sampleShuffledMaterial(BlockVector pos) { Random random = match.getRandom(); int range = SHUFFLE_SAMPLE_RANGE; int diameter = range * 2 + 1; for(int i = 0; i < SHUFFLE_SAMPLE_ITERATIONS; i++) { BlockState block = snapshot().getOriginalBlock(pos.getBlockX() + random.nextInt(diameter) - range, pos.getBlockY() + random.nextInt(diameter) - range, pos.getBlockZ() + random.nextInt(diameter) - range); if(definition.shuffleableBlocks.query(new BlockQuery(block)).isAllowed()) return block.getMaterialData(); } return null; }
@SuppressWarnings("deprecation") public BlockState getState(BlockVector pos) { int offset = this.offset(pos); BlockState state = pos.toLocation(this.world).getBlock().getState(); state.setTypeId(this.blockIds[offset]); state.setRawData(this.blockData[offset]); return state; }
public BlockState getNewState() { if(this.drops == null || this.drops.replacement == null) { return this.newState; } else { BlockState state = this.newState.getBlock().getState(); state.setType(this.drops.replacement.getItemType()); state.setData(this.drops.replacement); return state; } }
@EventHandler public void onLeverOrButton(PlayerInteractEvent event) { Block clickedBlock = event.getClickedBlock(); Player player = event.getPlayer(); if (clickedBlock == null) return; String chunk = clickedBlock.getLocation().getChunk().getX() + ";" + clickedBlock.getLocation().getChunk().getZ(); if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; if (!powerable.containsKey(clickedBlock.getWorld().getName())) return; if (powerable.get(clickedBlock.getWorld().getName()).getList(chunk).contains(clickedBlock.getLocation())) return; // We cancel; send smoke particles for button, and we just turn off the // lever (if it was, for some reason, on). if (clickedBlock.getType() == Material.STONE_BUTTON || clickedBlock.getType() == Material.WOOD_BUTTON) { clickedBlock.getWorld().spawnParticle(Particle.SMOKE_NORMAL, clickedBlock.getLocation().add(0.5, 1, 0.5), 7, 0, 0.2, 0, 0.03); player.sendMessage(MortuusTerraCore.NOTI_PREFIX + ChatColor.RED + " There is no generator in range!"); } else if (clickedBlock.getType() == Material.LEVER) { BlockState state = clickedBlock.getState(); Lever lever = (Lever) state.getData(); lever.setPowered(false); state.setData(lever); state.update(); clickedBlock.getWorld().spawnParticle(Particle.SMOKE_NORMAL, clickedBlock.getLocation().add(0.5, 1, 0.5), 7, 0, 0.2, 0, 0.03); player.sendMessage(MortuusTerraCore.NOTI_PREFIX + ChatColor.RED + " There is no generator in range!"); } }
private boolean isEventSign(Block block) { BlockState state = block.getState(); if ((state instanceof Sign)) { String[] lines = ((Sign)state).getLines(); return (lines.length > 0) && (lines[1] != null) && (lines[1].equals(ChatColor.DARK_PURPLE + "captured by")); } return false; }
/** * Creates an instance of the class. * * @param oldState State the destroyed block was in before broken * @param playerCause Player most responsible for the damage */ public DestroyableHealthChange(@Nonnull BlockState oldState, @Nonnull BlockState newState, @Nullable ParticipantState playerCause, int healthChange) { Preconditions.checkNotNull(oldState, "old block state"); this.oldState = oldState; this.newState = newState; this.playerCause = playerCause; this.healthChange = healthChange; }