Search in sources :

Example 16 with BlockData

use of org.bukkit.block.data.BlockData in project Prism-Bukkit by prism.

the class Preview method cancel_preview.

@Override
public void cancel_preview() {
    if (player == null) {
        return;
    }
    if (!blockStateChanges.isEmpty()) {
        // pull all players that are part of this preview
        final List<CommandSender> previewPlayers = parameters.getSharedPlayers();
        previewPlayers.add(player);
        for (final BlockStateChange u : blockStateChanges) {
            Location loc = u.getOriginalBlock().getLocation();
            BlockData data = u.getOriginalBlock().getBlockData();
            for (final CommandSender sharedPlayer : previewPlayers) {
                if (sharedPlayer instanceof Player) {
                    EntityUtils.sendBlockChange((Player) sharedPlayer, loc, data);
                }
            }
        }
    }
    Prism.messenger.sendMessage(sender, Prism.messenger.playerHeaderMsg(Il8nHelper.getMessage("preview-cancel")));
}
Also used : Player(org.bukkit.entity.Player) BlockStateChange(me.botsko.prism.api.BlockStateChange) CommandSender(org.bukkit.command.CommandSender) BlockData(org.bukkit.block.data.BlockData) Location(org.bukkit.Location)

Example 17 with BlockData

use of org.bukkit.block.data.BlockData in project Prism-Bukkit by prism.

the class BlockAction method handleApply.

/**
 * The BlockState object is modified by this method.
 *
 * @param block            Block
 * @param originalBlock    BlockState
 * @param parameters       QueryParameters
 * @param cancelIfBadPlace cancelIfBadPlace
 * @return ChangeResult.
 */
@NotNull
private ChangeResult handleApply(final Block block, final BlockState originalBlock, final PrismParameters parameters, final boolean cancelIfBadPlace) {
    BlockState state = block.getState();
    // So this will ensure the head of the bed is broken when removing the bed during rollback.
    if (MaterialTag.BEDS.isTagged(state.getType())) {
        state = Utilities.getSiblingForDoubleLengthBlock(state).getState();
    }
    switch(getMaterial()) {
        case LILY_PAD:
            // If restoring a lily pad, check that block below is water.
            // Be sure it's set to stationary water so the lily pad will stay
            final Block below = block.getRelative(BlockFace.DOWN);
            if (below.getType().equals(WATER) || below.getType().equals(AIR)) {
                below.setType(WATER);
            } else {
                // Prism.debug("Lilypad skipped because no water exists below.");
                return new ChangeResultImpl(ChangeResultType.SKIPPED, null);
            }
            break;
        case NETHER_PORTAL:
            // Only way to restore a nether portal is to set it on fire.
            final Block obsidian = Utilities.getFirstBlockOfMaterialBelow(OBSIDIAN, block.getLocation());
            if (obsidian != null) {
                final Block above = obsidian.getRelative(BlockFace.UP);
                if (!(above.getType() == NETHER_PORTAL)) {
                    above.setType(FIRE);
                    return new ChangeResultImpl(ChangeResultType.APPLIED, null);
                }
            }
            break;
        case JUKEBOX:
            setBlockData(Bukkit.createBlockData(JUKEBOX));
            break;
        default:
            break;
    }
    state.setType(getMaterial());
    state.setBlockData(getBlockData());
    state.update(true);
    BlockState newState = block.getState();
    BlockActionData blockActionData = getActionData();
    if (blockActionData != null) {
        if ((getMaterial() == PLAYER_HEAD || getMaterial() == PLAYER_WALL_HEAD) && blockActionData instanceof SkullActionData) {
            return handleSkulls(block, blockActionData, originalBlock);
        }
        if (Tag.BANNERS.isTagged(getMaterial()) && blockActionData instanceof BannerActionData) {
            return handleBanners(block, blockActionData, originalBlock);
        }
        if (getMaterial() == SPAWNER && blockActionData instanceof SpawnerActionData) {
            final SpawnerActionData s = (SpawnerActionData) blockActionData;
            // Set spawner data
            ((CreatureSpawner) newState).setDelay(s.getDelay());
            ((CreatureSpawner) newState).setSpawnedType(s.getEntityType());
        }
        if (getMaterial() == COMMAND_BLOCK && blockActionData instanceof CommandActionData) {
            final CommandActionData c = (CommandActionData) blockActionData;
            ((CommandBlock) newState).setCommand(c.command);
        }
        if (newState instanceof Nameable && blockActionData.customName != null && !blockActionData.customName.equals("")) {
            ((Nameable) newState).setCustomName(blockActionData.customName);
        }
        if (parameters.getProcessType() == PrismProcessType.ROLLBACK && Tag.SIGNS.isTagged(getMaterial()) && blockActionData instanceof SignActionData) {
            final SignActionData s = (SignActionData) blockActionData;
            // https://snowy-evening.com/botsko/prism/455/
            if (newState instanceof Sign) {
                if (s.lines != null) {
                    for (int i = 0; i < s.lines.length; ++i) {
                        ((Sign) newState).setLine(i, s.lines[i]);
                    }
                }
            }
        }
    } else {
        Prism.debug("BlockAction Data was null with " + parameters.toString());
    }
    // -----------------------------
    // Sibling logic marker
    // If the material is a crop that needs soil, we must restore the soil
    // This may need to go before setting the block, but I prefer the BlockUtil logic to use materials.
    BlockState sibling = null;
    if (Utilities.materialRequiresSoil(getMaterial())) {
        sibling = block.getRelative(BlockFace.DOWN).getState();
        if (cancelIfBadPlace && !MaterialTag.SOIL_CANDIDATES.isTagged(sibling.getType())) {
            Prism.debug(parameters.getProcessType().name() + " skipped due to lack of soil for " + getMaterial().name());
            return new ChangeResultImpl(ChangeResultType.SKIPPED, null);
        }
        sibling.setType(FARMLAND);
    }
    // Chest sides can be broken independently, ignore them
    if (newState.getType() != CHEST && newState.getType() != TRAPPED_CHEST) {
        final Block s = Utilities.getSiblingForDoubleLengthBlock(state);
        if (s != null) {
            sibling = s.getState();
            if (cancelIfBadPlace && !Utilities.isAcceptableForBlockPlace(sibling.getType())) {
                Prism.debug(parameters.getProcessType().name() + " skipped due to lack of wrong sibling type for " + getMaterial().name());
                return new ChangeResultImpl(ChangeResultType.SKIPPED, null);
            }
            sibling.setType(block.getType());
            BlockData siblingData = getBlockData().clone();
            if (siblingData instanceof Bed) {
                // We always log the foot
                ((Bed) siblingData).setPart(Part.HEAD);
            } else if (siblingData instanceof Bisected) {
                // We always log the bottom
                ((Bisected) siblingData).setHalf(Half.TOP);
            }
            sibling.setBlockData(siblingData);
        }
    }
    boolean physics = !parameters.hasFlag(Flag.NO_PHYS);
    newState.update(true, physics);
    if (sibling != null) {
        sibling.update(true, physics);
    }
    return new ChangeResultImpl(ChangeResultType.APPLIED, new BlockStateChangeImpl(originalBlock, state));
}
Also used : Bed(org.bukkit.block.data.type.Bed) CommandBlock(org.bukkit.block.CommandBlock) CreatureSpawner(org.bukkit.block.CreatureSpawner) Nameable(org.bukkit.Nameable) BlockState(org.bukkit.block.BlockState) BlockStateChangeImpl(me.botsko.prism.events.BlockStateChangeImpl) Block(org.bukkit.block.Block) CommandBlock(org.bukkit.block.CommandBlock) Sign(org.bukkit.block.Sign) ChangeResultImpl(me.botsko.prism.appliers.ChangeResultImpl) BlockData(org.bukkit.block.data.BlockData) Bisected(org.bukkit.block.data.Bisected) NotNull(org.jetbrains.annotations.NotNull)

Example 18 with BlockData

use of org.bukkit.block.data.BlockData in project Prism-Bukkit by prism.

the class PrismPlayerEvents method onPlayerBucketEmpty.

/**
 * PlayerBucketEmptyEvent.
 *
 * @param event PlayerBucketEmptyEvent
 */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) {
    final Player player = event.getPlayer();
    String cause;
    Material newMat;
    Block spot = event.getBlockClicked().getRelative(event.getBlockFace());
    switch(event.getBucket()) {
        case LAVA_BUCKET:
            cause = "lava-bucket";
            newMat = Material.LAVA;
            break;
        case TROPICAL_FISH_BUCKET:
        case SALMON_BUCKET:
        case PUFFERFISH_BUCKET:
        case WATER_BUCKET:
        default:
            cause = "water-bucket";
            newMat = Material.WATER;
            break;
    }
    if (!Prism.getIgnore().event(cause, player)) {
        return;
    }
    BlockData oldData = spot.getBlockData();
    BlockData newData = Bukkit.createBlockData(newMat);
    BlockData clickedData = event.getBlockClicked().getBlockData();
    // TODO If "Lavalogged" blocks become a thing, please revisit.
    if (clickedData instanceof Waterlogged && event.getBucket() != Material.LAVA) {
        Waterlogged wl = (Waterlogged) clickedData;
        if (!wl.isWaterlogged()) {
            spot = event.getBlockClicked();
            newMat = spot.getType();
            oldData = wl;
            newData = wl.clone();
            ((Waterlogged) newData).setWaterlogged(true);
            cause = "water-bucket";
        }
    }
    RecordingQueue.addToQueue(ActionFactory.createBlockChange(cause, spot.getLocation(), spot.getType(), oldData, newMat, newData, player));
    if (plugin.getConfig().getBoolean("prism.alerts.uses.lava") && event.getBucket() == Material.LAVA_BUCKET && !player.hasPermission("prism.alerts.use.lavabucket.ignore") && !player.hasPermission("prism.alerts.ignore")) {
        plugin.useMonitor.alertOnItemUse(player, "poured lava", "prism.alerts.use.lavabucket");
    }
}
Also used : Player(org.bukkit.entity.Player) Block(org.bukkit.block.Block) Material(org.bukkit.Material) Waterlogged(org.bukkit.block.data.Waterlogged) BlockData(org.bukkit.block.data.BlockData) EventHandler(org.bukkit.event.EventHandler)

Example 19 with BlockData

use of org.bukkit.block.data.BlockData in project Prism-Bukkit by prism.

the class SqlSelectQueryBuilder method executeSelect.

@Override
public QueryResult executeSelect(TimeTaken eventTimer) {
    final List<Handler> actions = new ArrayList<>();
    // Build conditions based off final args
    final String query = getQuery(parameters, shouldGroup);
    eventTimer.recordTimedEvent("query started");
    try (Connection conn = Prism.getPrismDataSource().getDataSource().getConnection();
        PreparedStatement s = conn.prepareStatement(query);
        ResultSet rs = s.executeQuery()) {
        RecordingManager.failedDbConnectionCount = 0;
        eventTimer.recordTimedEvent("query returned, building results");
        Map<Integer, String> worldsInverse = new HashMap<>();
        for (final Entry<String, Integer> entry : Prism.prismWorlds.entrySet()) {
            worldsInverse.put(entry.getValue(), entry.getKey());
        }
        while (rs.next()) {
            if (rs.getString(3) == null) {
                continue;
            }
            // Convert action ID to name
            // Performance-wise this is a lot faster than table joins
            // and the cache data should always be available
            int actionId = rs.getInt(3);
            String actionName = "";
            for (final Entry<String, Integer> entry : Prism.prismActions.entrySet()) {
                if (entry.getValue() == actionId) {
                    actionName = entry.getKey();
                }
            }
            if (actionName.isEmpty()) {
                Prism.warn("Record contains action ID that doesn't exist in cache: " + actionId + ", cacheSize=" + Prism.prismActions.size());
                continue;
            }
            // Get the action handler
            final ActionTypeImpl actionType = Prism.getActionRegistry().getAction(actionName);
            if (actionType == null) {
                continue;
            }
            long rowId = 0;
            try {
                final Handler baseHandler = Prism.getHandlerRegistry().create(actionType.getHandler());
                // Convert world ID to name
                // Performance-wise this is typically a lot faster than
                // table joins
                rowId = rs.getLong(1);
                // Set all shared values
                baseHandler.setActionType(actionType);
                baseHandler.setId(rowId);
                baseHandler.setUnixEpoch(rs.getLong(2));
                String worldName = worldsInverse.getOrDefault(rs.getInt(5), "");
                baseHandler.setWorld(Bukkit.getWorld(worldName));
                baseHandler.setX(rs.getInt(6));
                baseHandler.setY(rs.getInt(7));
                baseHandler.setZ(rs.getInt(8));
                int blockId = rs.getInt(9);
                int blockSubId = rs.getInt(10);
                int oldBlockId = rs.getInt(11);
                int oldBlockSubId = rs.getInt(12);
                String extraData = rs.getString(13);
                boolean validBlockId = false;
                boolean validOldBlockId = false;
                MaterialState current = Prism.getItems().idsToMaterial(blockId, blockSubId, false);
                if (current != null) {
                    ItemStack item = current.asItem();
                    BlockData block = current.asBlockData();
                    if (block != null) {
                        validBlockId = true;
                        baseHandler.setMaterial(block.getMaterial());
                        baseHandler.setBlockData(block);
                        baseHandler.setDurability((short) 0);
                    } else if (item != null) {
                        validBlockId = true;
                        baseHandler.setMaterial(item.getType());
                        BlockData newData;
                        try {
                            newData = Bukkit.createBlockData(item.getType());
                        } catch (IllegalArgumentException e) {
                            // This exception occurs, for example, with "ItemStack{DIAMOND_LEGGINGS x 1}"
                            Prism.debug("IllegalArgumentException for record #" + rowId + " calling createBlockData for " + item.toString());
                            newData = null;
                        }
                        baseHandler.setBlockData(newData);
                        baseHandler.setDurability((short) ItemUtils.getItemDamage(item));
                    }
                }
                MaterialState old = Prism.getItems().idsToMaterial(oldBlockId, oldBlockSubId, false);
                if (old != null) {
                    ItemStack oldItem = old.asItem();
                    BlockData oldBlock = old.asBlockData();
                    validOldBlockId = true;
                    if (oldBlock != null) {
                        baseHandler.setOldMaterial(oldBlock.getMaterial());
                        baseHandler.setOldBlockData(oldBlock);
                        baseHandler.setOldDurability((short) 0);
                    } else {
                        baseHandler.setOldMaterial(oldItem.getType());
                        baseHandler.setOldBlockData(Bukkit.createBlockData(oldItem.getType()));
                        baseHandler.setOldDurability((short) ItemUtils.getItemDamage(oldItem));
                    }
                }
                if (!validBlockId && !validOldBlockId) {
                    // Entry could not be converted to a block or an item
                    boolean logWarning;
                    // The current item is likely a spawn or death event for an entity, for example, a cow or horse
                    logWarning = blockId != 0 || oldBlockId != 0 || extraData == null || !extraData.contains("entity_name");
                    if (logWarning) {
                        String itemMetadataDesc;
                        if (extraData == null) {
                            itemMetadataDesc = "";
                        } else {
                            itemMetadataDesc = ", metadata=" + extraData;
                        }
                        if (blockId > 0) {
                            Prism.warn("Unable to convert record #" + rowId + " to material: " + "block_id=" + blockId + ", block_subid=" + blockSubId + itemMetadataDesc);
                        } else if (oldBlockId > 0) {
                            Prism.warn("Unable to convert record #" + rowId + " to material: " + "old_block_id=" + oldBlockId + ", old_block_subid=" + oldBlockSubId + itemMetadataDesc);
                        } else {
                            Prism.warn("Unable to convert record #" + rowId + " to material: " + "block_id=0, old_block_id=0" + itemMetadataDesc);
                        }
                    }
                }
                // data
                try {
                    baseHandler.deserialize(extraData);
                } catch (JsonSyntaxException e) {
                    if (Prism.isDebug()) {
                        Prism.warn("Deserialization Error: " + e.getLocalizedMessage(), e);
                    }
                }
                // player
                baseHandler.setSourceName(rs.getString(4));
                // player_uuid
                try {
                    // Calls UUID.fromString, must handle potential exceptions
                    OfflinePlayer offline = Bukkit.getOfflinePlayer(SqlPlayerIdentificationHelper.uuidFromDbString(rs.getString(14)));
                    // Fake player
                    if (offline.hasPlayedBefore()) {
                        baseHandler.setUuid(offline.getUniqueId());
                    }
                } catch (IllegalArgumentException | NullPointerException e) {
                // Not a valid uuid
                }
                // Set aggregate counts if a lookup
                int aggregated = 0;
                if (shouldGroup) {
                    aggregated = rs.getInt(15);
                }
                baseHandler.setAggregateCount(aggregated);
                actions.add(baseHandler);
            } catch (final SQLException e) {
                Prism.warn("Ignoring data from record #" + rowId + " because it caused an error:", e);
            }
        }
    } catch (NullPointerException e) {
        if (RecordingManager.failedDbConnectionCount == 0) {
            Prism.log("Prism database error. Connection missing. Leaving actions to log in queue.");
            Prism.debug(e.getMessage());
        }
        RecordingManager.failedDbConnectionCount++;
        return new QueryResult(actions, parameters);
    } catch (SQLException e) {
        Prism.getPrismDataSource().handleDataSourceException(e);
    }
    return new QueryResult(actions, parameters);
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) QueryResult(me.botsko.prism.actionlibs.QueryResult) ResultSet(java.sql.ResultSet) OfflinePlayer(org.bukkit.OfflinePlayer) BlockData(org.bukkit.block.data.BlockData) Connection(java.sql.Connection) Handler(me.botsko.prism.api.actions.Handler) PreparedStatement(java.sql.PreparedStatement) JsonSyntaxException(com.google.gson.JsonSyntaxException) ItemStack(org.bukkit.inventory.ItemStack) ActionTypeImpl(me.botsko.prism.actionlibs.ActionTypeImpl) MaterialState(me.botsko.prism.api.objects.MaterialState)

Example 20 with BlockData

use of org.bukkit.block.data.BlockData in project Minigames by AddstarMC.

the class TestHelper method createSignBlock.

public static BlockMock createSignBlock(Map<Integer, String> lines, WorldMock world) {
    MaterialData data = new MaterialData(Material.OAK_SIGN, (byte) 0);
    MockSign sign = new MockSign(data, true);
    for (Map.Entry<Integer, String> e : lines.entrySet()) {
        sign.setLine(e.getKey(), e.getValue());
    }
    BlockData bData = new BlockData() {

        @Override
        public Material getMaterial() {
            return Material.OAK_SIGN;
        }

        @Override
        public String getAsString() {
            return null;
        }

        @Override
        public String getAsString(boolean b) {
            return "SIGN";
        }

        @Override
        public BlockData merge(BlockData blockData) {
            return this;
        }

        @Override
        public boolean matches(BlockData blockData) {
            return true;
        }

        @Override
        public BlockData clone() {
            return this;
        }
    };
    return new SignBlockMock(Material.OAK_SIGN, new Location(world, 10, 40, 10), sign, bData);
}
Also used : SignBlockMock(au.com.mineauz.minigames.objects.SignBlockMock) MaterialData(org.bukkit.material.MaterialData) BlockData(org.bukkit.block.data.BlockData) MockSign(au.com.mineauz.minigames.objects.MockSign) Location(org.bukkit.Location)

Aggregations

BlockData (org.bukkit.block.data.BlockData)34 Block (org.bukkit.block.Block)10 MaterialTag (com.denizenscript.denizen.objects.MaterialTag)8 Location (org.bukkit.Location)7 MinigamePlayer (au.com.mineauz.minigames.objects.MinigamePlayer)3 ArrayList (java.util.ArrayList)3 Material (org.bukkit.Material)3 BlockState (org.bukkit.block.BlockState)3 Lightable (org.bukkit.block.data.Lightable)3 ItemStack (org.bukkit.inventory.ItemStack)3 LocationTag (com.denizenscript.denizen.objects.LocationTag)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 MaterialState (me.botsko.prism.api.objects.MaterialState)2 BlockStateChangeImpl (me.botsko.prism.events.BlockStateChangeImpl)2 Bisected (org.bukkit.block.data.Bisected)2 Bed (org.bukkit.block.data.type.Bed)2 Player (org.bukkit.entity.Player)2