Search in sources :

Example 16 with InventoryHolder

use of org.bukkit.inventory.InventoryHolder in project Denizen-For-Bukkit by DenizenScript.

the class BukkitWorldScriptHelper method inventoryClickEvent.

/////////////////////
//   INVENTORY EVENTS
/////////////////
// <--[language]
// @Name Inventory Actions
// @Group Useful Lists
// @Description
// Used by some inventory world events to describe the action of the inventory event.
//
// Actions, as described by the bukkit javadocs:
// CLONE_STACK
// A max-size stack of the clicked item is put on the cursor.
// COLLECT_TO_CURSOR
// The inventory is searched for the same material, and they are put on the cursor up to
//      m@material.max_stack_size.
// DROP_ALL_CURSOR
// The entire cursor item is dropped.
// DROP_ALL_SLOT
// The entire clicked slot is dropped.
// DROP_ONE_CURSOR
// One item is dropped from the cursor.
// DROP_ONE_SLOT
// One item is dropped from the clicked slot.
// HOTBAR_MOVE_AND_READD
// The clicked item is moved to the hotbar, and the item currently there is re-added to the
//      player's inventory.
// HOTBAR_SWAP
// The clicked slot and the picked hotbar slot are swapped.
// MOVE_TO_OTHER_INVENTORY
// The item is moved to the opposite inventory if a space is found.
// NOTHING
// Nothing will happen from the click.
// PICKUP_ALL
// All of the items on the clicked slot are moved to the cursor.
// PICKUP_HALF
// Half of the items on the clicked slot are moved to the cursor.
// PICKUP_ONE
// One of the items on the clicked slot are moved to the cursor.
// PICKUP_SOME
// Some of the items on the clicked slot are moved to the cursor.
// PLACE_ALL
// All of the items on the cursor are moved to the clicked slot.
// PLACE_ONE
// A single item from the cursor is moved to the clicked slot.
// PLACE_SOME
// Some of the items from the cursor are moved to the clicked slot (usually up to the max stack size).
// SWAP_WITH_CURSOR
// The clicked item and the cursor are exchanged.
// UNKNOWN
// An unrecognized ClickType.
//
// -->
// <--[event]
// @Events
// player clicks in inventory
// player (<click type>) clicks (<item>) (in <inventory>) (with <item>)
// player (<click type>) clicks (<material>) (in <inventory>) (with <item>)
// player (<click type>) clicks (<item>) (in <inventory>) (with <material>)
// player (<click type>) clicks (<material>) (in <inventory>) (with <material>)
//
// @Regex ^on player( [^\s]+)? clicks [^\s]+( in [^\s]+)?( with [^\s]+)?$
//
// @Triggers when a player clicks in an inventory.
// @Context
// <context.item> returns the dItem the player has clicked on.
// <context.inventory> returns the dInventory.
// <context.cursor_item> returns the item the Player is clicking with.
// <context.click> returns an Element with the name of the click type.
// <context.slot_type> returns an Element with the name of the slot type that was clicked.
// <context.slot> returns an Element with the number of the slot that was clicked.
// <context.raw_slot> returns an Element with the raw number of the slot that was clicked.
// <context.is_shift_click> returns true if 'shift' was used while clicking.
// <context.action> returns the inventory_action. See <@link language Inventory Actions>.
// <context.hotbar_button> returns an Element of the button pressed as a number, or 0 if no number button was pressed.
//
// @Determine
// "CANCELLED" to stop the player from clicking.
//
// -->
@EventHandler
public void inventoryClickEvent(InventoryClickEvent event) {
    // TODO: make this a script event...
    Map<String, dObject> context = new HashMap<String, dObject>();
    dItem item = new dItem(Material.AIR);
    dItem holding;
    dInventory inventory = dInventory.mirrorBukkitInventory(event.getInventory());
    final dPlayer player = dEntity.getPlayerFrom((Player) event.getWhoClicked());
    String type = event.getInventory().getType().name();
    String click = event.getClick().name();
    String slotType = event.getSlotType().name();
    List<String> events = new ArrayList<String>();
    events.add("player clicks in inventory");
    events.add("player clicks in " + type);
    events.add("player clicks in " + inventory.identifySimple());
    String interaction = "player " + click + " clicks ";
    events.add(interaction + "in inventory");
    events.add(interaction + "in " + type);
    events.add(interaction + "in " + inventory.identifySimple());
    if (event.getCursor() != null) {
        holding = new dItem(event.getCursor());
        context.put("cursor_item", holding);
        events.add(interaction + "in inventory with " + holding.identifySimple());
        events.add(interaction + "in " + type + " with " + holding.identifySimple());
        events.add(interaction + "in " + inventory.identifySimple() + " with " + holding.identifySimple());
        events.add(interaction + "in inventory with " + holding.identifyMaterial());
        events.add(interaction + "in " + type + " with " + holding.identifyMaterial());
        events.add(interaction + "in " + inventory.identifySimple() + " with " + holding.identifyMaterial());
        events.add("player clicks in inventory with " + holding.identifySimple());
        events.add("player clicks in " + type + " with " + holding.identifySimple());
        events.add("player clicks in " + inventory.identifySimple() + " with " + holding.identifySimple());
        events.add("player clicks in inventory with " + holding.identifyMaterial());
        events.add("player clicks in " + type + " with " + holding.identifyMaterial());
        events.add("player clicks in " + inventory.identifySimple() + " with " + holding.identifyMaterial());
    }
    if (event.getCurrentItem() != null) {
        item = new dItem(event.getCurrentItem());
        events.add("player clicks " + item.identifySimple() + " in inventory");
        events.add(interaction + item.identifySimple() + " in inventory");
        events.add("player clicks " + item.identifySimple() + " in " + type);
        events.add(interaction + item.identifySimple() + " in " + type);
        events.add("player clicks " + item.identifySimple() + " in " + inventory.identifySimple());
        events.add(interaction + item.identifySimple() + " in " + inventory.identifySimple());
        events.add("player clicks " + item.identifyMaterial() + " in inventory");
        events.add(interaction + item.identifyMaterial() + " in inventory");
        events.add("player clicks " + item.identifyMaterial() + " in " + type);
        events.add(interaction + item.identifyMaterial() + " in " + type);
        events.add("player clicks " + item.identifyMaterial() + " in " + inventory.identifySimple());
        events.add(interaction + item.identifyMaterial() + " in " + inventory.identifySimple());
        if (event.getCursor() != null) {
            holding = new dItem(event.getCursor());
            final String[] itemStrings = new String[] { item.identifySimple(), item.identifyMaterial() };
            final String[] inventoryStrings = new String[] { "inventory", type, inventory.identifySimple() };
            final String[] holdingStrings = new String[] { holding.identifySimple(), holding.identifyMaterial() };
            for (String itemString : itemStrings) {
                for (String inventoryString : inventoryStrings) {
                    for (String holdingString : holdingStrings) {
                        String fullString = itemString + " in " + inventoryString + " with " + holdingString;
                        events.add("player clicks " + fullString);
                        events.add(interaction + fullString);
                    }
                }
            }
        }
    }
    context.put("item", item);
    context.put("inventory", inventory);
    context.put("click", new Element(click));
    context.put("slot_type", new Element(slotType));
    context.put("slot", new Element(event.getSlot() + 1));
    context.put("raw_slot", new Element(event.getRawSlot() + 1));
    context.put("is_shift_click", new Element(event.isShiftClick()));
    context.put("action", new Element(event.getAction().name()));
    context.put("hotbar_button", new Element(event.getHotbarButton() + 1));
    String determination = doEvents(events, null, player, context, true);
    if (determination.toUpperCase().startsWith("CANCELLED")) {
        event.setCancelled(true);
        final InventoryHolder holder = event.getInventory().getHolder();
        new BukkitRunnable() {

            @Override
            public void run() {
                player.getPlayerEntity().updateInventory();
                if (holder != null && holder instanceof Player) {
                    ((Player) holder).updateInventory();
                }
            }
        }.runTaskLater(DenizenAPI.getCurrentInstance(), 1);
    }
}
Also used : Player(org.bukkit.entity.Player) HashMap(java.util.HashMap) Element(net.aufdemrand.denizencore.objects.Element) ArrayList(java.util.ArrayList) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) net.aufdemrand.denizencore.objects.dObject(net.aufdemrand.denizencore.objects.dObject) InventoryHolder(org.bukkit.inventory.InventoryHolder) EventHandler(org.bukkit.event.EventHandler)

Example 17 with InventoryHolder

use of org.bukkit.inventory.InventoryHolder in project Denizen-For-Bukkit by DenizenScript.

the class dLocation method getAttribute.

@Override
public String getAttribute(Attribute attribute) {
    if (attribute == null) {
        return null;
    }
    // -->
    if (attribute.startsWith("above")) {
        return new dLocation(this.clone().add(0, 1, 0)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("below")) {
        return new dLocation(this.clone().add(0, -1, 0)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("block")) {
        return new dLocation(getWorld(), getBlockX(), getBlockY(), getBlockZ()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("center")) {
        return new dLocation(getWorld(), getBlockX() + 0.5, getBlockY() + 0.5, getBlockZ() + 0.5).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("highest")) {
        return new dLocation(getWorld().getHighestBlockAt(this).getLocation().add(0, -1, 0)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("base_color")) {
        DyeColor color = ((Banner) getBlock().getState()).getBaseColor();
        return new Element(color != null ? color.name() : "BLACK").getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("has_inventory")) {
        return new Element(getBlock().getState() instanceof InventoryHolder).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("inventory")) {
        dObject obj = Element.handleNull(identify() + ".inventory", getInventory(), "dInventory", attribute.hasAlternative());
        return obj == null ? null : obj.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("material")) {
        return dMaterial.getMaterialFrom(getBlock().getType(), getBlock().getData()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("patterns")) {
        dList list = new dList();
        for (org.bukkit.block.banner.Pattern pattern : ((Banner) getBlock().getState()).getPatterns()) {
            list.add(pattern.getColor().name() + "/" + pattern.getPattern().name());
        }
        return list.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("head_rotation")) {
        return new Element(getSkullRotation(((Skull) getBlock().getState()).getRotation()) + 1).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("switched")) {
        Material type = getBlock().getType();
        if (type == Material.IRON_DOOR_BLOCK || type == Material.WOODEN_DOOR || type == Material.DARK_OAK_DOOR || type == Material.BIRCH_DOOR || type == Material.ACACIA_DOOR || type == Material.JUNGLE_DOOR || type == Material.SPRUCE_DOOR) {
            Location location = this;
            int data = getBlock().getData();
            if (data >= 8) {
                location = clone().add(0, -1, 0);
            }
            return new Element((location.getBlock().getData() & 0x4) > 0).getAttribute(attribute.fulfill(1));
        } else if (type == Material.TRAP_DOOR || type == Material.IRON_TRAPDOOR) {
            return new Element((getBlock().getData() & 0x4) > 0).getAttribute(attribute.fulfill(1));
        } else {
            return new Element((getBlock().getData() & 0x8) > 0).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("sign_contents")) {
        if (getBlock().getState() instanceof Sign) {
            return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines())).getAttribute(attribute.fulfill(1));
        } else {
            return null;
        }
    }
    // -->
    if (attribute.startsWith("spawner_type")) {
        if (getBlock().getState() instanceof CreatureSpawner) {
            return new dEntity(DenizenEntityType.getByName(((CreatureSpawner) getBlock().getState()).getSpawnedType().name())).getAttribute(attribute.fulfill(1));
        } else {
            return null;
        }
    }
    // -->
    if (attribute.startsWith("drops")) {
        Collection<ItemStack> its = getBlock().getDrops();
        dList list = new dList();
        for (ItemStack it : its) {
            list.add(new dItem(it).identify());
        }
        return list.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("skull_type")) {
        BlockState blockState = getBlock().getState();
        if (blockState instanceof Skull) {
            String t = ((Skull) blockState).getSkullType().name();
            return new Element(t).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("skull_name")) {
        BlockState blockState = getBlock().getState();
        if (blockState instanceof Skull) {
            PlayerProfile profile = NMSHandler.getInstance().getBlockHelper().getPlayerProfile((Skull) blockState);
            String n = profile.getName();
            if (n == null) {
                n = ((Skull) blockState).getOwningPlayer().getName();
            }
            return new Element(n).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("skull_skin")) {
        BlockState blockState = getBlock().getState();
        if (blockState instanceof Skull) {
            PlayerProfile profile = NMSHandler.getInstance().getBlockHelper().getPlayerProfile((Skull) blockState);
            String name = profile.getName();
            UUID uuid = profile.getUniqueId();
            String texture = profile.getTexture();
            attribute = attribute.fulfill(1);
            // -->
            if (attribute.startsWith("full")) {
                return new Element((uuid != null ? uuid : name != null ? name : null) + (texture != null ? "|" + texture : "")).getAttribute(attribute.fulfill(1));
            }
            return new Element(uuid != null ? uuid.toString() : name != null ? name : null).getAttribute(attribute);
        } else {
            return null;
        }
    }
    // -->
    if (attribute.startsWith("simple.formatted")) {
        return new Element("X '" + getBlockX() + "', Y '" + getBlockY() + "', Z '" + getBlockZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("simple")) {
        if (getWorld() == null) {
            return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()).getAttribute(attribute.fulfill(1));
        } else {
            return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ() + "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("precise_impact_normal")) {
        int range = attribute.getIntContext(1);
        if (range < 1) {
            range = 200;
        }
        double xzLen = Math.cos((getPitch() % 360) * (Math.PI / 180));
        double nx = xzLen * Math.sin(-getYaw() * (Math.PI / 180));
        double ny = Math.sin(getPitch() * (Math.PI / 180));
        double nz = xzLen * Math.cos(getYaw() * (Math.PI / 180));
        Location location = NMSHandler.getInstance().getEntityHelper().getImpactNormal(this, new org.bukkit.util.Vector(nx, -ny, nz), range);
        if (location != null) {
            return new dLocation(location).getAttribute(attribute.fulfill(1));
        } else {
            return null;
        }
    }
    // -->
    if (attribute.startsWith("precise_cursor_on")) {
        int range = attribute.getIntContext(1);
        if (range < 1) {
            range = 200;
        }
        double xzLen = Math.cos((getPitch() % 360) * (Math.PI / 180));
        double nx = xzLen * Math.sin(-getYaw() * (Math.PI / 180));
        double ny = Math.sin(getPitch() * (Math.PI / 180));
        double nz = xzLen * Math.cos(getYaw() * (Math.PI / 180));
        Location location = NMSHandler.getInstance().getEntityHelper().rayTrace(this, new org.bukkit.util.Vector(nx, -ny, nz), range);
        if (location != null) {
            return new dLocation(location).getAttribute(attribute.fulfill(1));
        } else {
            return null;
        }
    }
    // -->
    if (attribute.startsWith("points_between")) {
        dLocation target = dLocation.valueOf(attribute.getContext(1));
        if (target == null) {
            return null;
        }
        attribute = attribute.fulfill(1);
        // <--[tag]
        // @attribute <l@location.points_between[<location>].distance[<#.#>]>
        // @returns dList(dLocation)
        // @description
        // Finds all locations between this location and another, separated by the specified distance each.
        // -->
        double rad = 1d;
        if (attribute.startsWith("distance")) {
            rad = attribute.getDoubleContext(1);
            attribute = attribute.fulfill(1);
        }
        dList list = new dList();
        org.bukkit.util.Vector rel = target.toVector().subtract(this.toVector());
        double len = rel.length();
        rel = rel.multiply(1d / len);
        for (double i = 0d; i < len; i += rad) {
            list.add(new dLocation(this.clone().add(rel.clone().multiply(i))).identify());
        }
        return list.getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("facing_blocks")) {
        int range = attribute.getIntContext(1);
        if (range < 1) {
            range = 100;
        }
        dList list = new dList();
        BlockIterator iterator = new BlockIterator(this, 0, range);
        while (iterator.hasNext()) {
            list.add(new dLocation(iterator.next().getLocation()).identify());
        }
        return list.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("line_of_sight") && attribute.hasContext(1)) {
        dLocation location = dLocation.valueOf(attribute.getContext(1));
        if (location != null) {
            return new Element(NMSHandler.getInstance().getEntityHelper().canTrace(getWorld(), toVector(), location.toVector())).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("direction.vector")) {
        double xzLen = Math.cos((getPitch() % 360) * (Math.PI / 180));
        double nx = xzLen * Math.sin(-getYaw() * (Math.PI / 180));
        double ny = Math.sin(getPitch() * (Math.PI / 180));
        double nz = xzLen * Math.cos(getYaw() * (Math.PI / 180));
        return new dLocation(getWorld(), nx, -ny, nz).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("direction")) {
        // Get the cardinal direction from this location to another
        if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
            // Subtract this location's vector from the other location's vector,
            // not the other way around
            dLocation target = dLocation.valueOf(attribute.getContext(1));
            attribute = attribute.fulfill(1);
            EntityHelper entityHelper = NMSHandler.getInstance().getEntityHelper();
            // -->
            if (attribute.startsWith("yaw")) {
                return new Element(entityHelper.normalizeYaw(entityHelper.getYaw(target.toVector().subtract(this.toVector()).normalize()))).getAttribute(attribute.fulfill(1));
            } else {
                return new Element(entityHelper.getCardinal(entityHelper.getYaw(target.toVector().subtract(this.toVector()).normalize()))).getAttribute(attribute);
            }
        } else // Get a cardinal direction from this location's yaw
        {
            return new Element(NMSHandler.getInstance().getEntityHelper().getCardinal(getYaw())).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("face") && attribute.hasContext(1)) {
        Location two = dLocation.valueOf(attribute.getContext(1));
        return new dLocation(NMSHandler.getInstance().getEntityHelper().faceLocation(this, two)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("facing")) {
        if (attribute.hasContext(1)) {
            // The default number of degrees if there is no degrees attribute
            int degrees = 45;
            // The attribute to fulfill from
            int attributePos = 1;
            // -->
            if (attribute.getAttribute(2).startsWith("degrees") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) {
                degrees = attribute.getIntContext(2);
                attributePos++;
            }
            if (dLocation.matches(attribute.getContext(1))) {
                return new Element(NMSHandler.getInstance().getEntityHelper().isFacingLocation(this, dLocation.valueOf(attribute.getContext(1)), degrees)).getAttribute(attribute.fulfill(attributePos));
            } else if (dEntity.matches(attribute.getContext(1))) {
                return new Element(NMSHandler.getInstance().getEntityHelper().isFacingLocation(this, dEntity.valueOf(attribute.getContext(1)).getBukkitEntity().getLocation(), degrees)).getAttribute(attribute.fulfill(attributePos));
            }
        }
    }
    // -->
    if (attribute.startsWith("pitch")) {
        return new Element(getPitch()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("with_pose")) {
        String context = attribute.getContext(1);
        Float pitch = 0f;
        Float yaw = 0f;
        if (dEntity.matches(context)) {
            dEntity ent = dEntity.valueOf(context);
            if (ent.isSpawned()) {
                pitch = ent.getBukkitEntity().getLocation().getPitch();
                yaw = ent.getBukkitEntity().getLocation().getYaw();
            }
        } else if (context.split(",").length == 2) {
            String[] split = context.split(",");
            pitch = Float.valueOf(split[0]);
            yaw = Float.valueOf(split[1]);
        }
        dLocation loc = dLocation.valueOf(identify());
        loc.setPitch(pitch);
        loc.setYaw(yaw);
        return loc.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("yaw.simple")) {
        float yaw = NMSHandler.getInstance().getEntityHelper().normalizeYaw(getYaw());
        if (yaw < 45) {
            return new Element("South").getAttribute(attribute.fulfill(2));
        } else if (yaw < 135) {
            return new Element("West").getAttribute(attribute.fulfill(2));
        } else if (yaw < 225) {
            return new Element("North").getAttribute(attribute.fulfill(2));
        } else if (yaw < 315) {
            return new Element("East").getAttribute(attribute.fulfill(2));
        } else {
            return new Element("South").getAttribute(attribute.fulfill(2));
        }
    }
    // -->
    if (attribute.startsWith("yaw.raw")) {
        return new Element(getYaw()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("yaw")) {
        return new Element(NMSHandler.getInstance().getEntityHelper().normalizeYaw(getYaw())).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("rotate_around_x") && attribute.hasContext(1)) {
        double angle = attribute.getDoubleContext(1);
        double cos = Math.cos(angle);
        double sin = Math.sin(angle);
        double y = (getY() * cos) - (getZ() * sin);
        double z = (getY() * sin) + (getZ() * cos);
        Location location = clone();
        location.setY(y);
        location.setZ(z);
        return new dLocation(location).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("rotate_around_y") && attribute.hasContext(1)) {
        double angle = attribute.getDoubleContext(1);
        double cos = Math.cos(angle);
        double sin = Math.sin(angle);
        double x = (getX() * cos) + (getZ() * sin);
        double z = (getX() * -sin) + (getZ() * cos);
        Location location = clone();
        location.setX(x);
        location.setZ(z);
        return new dLocation(location).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("rotate_around_z") && attribute.hasContext(1)) {
        double angle = attribute.getDoubleContext(1);
        double cos = Math.cos(angle);
        double sin = Math.sin(angle);
        double x = (getX() * cos) - (getY() * sin);
        double y = (getZ() * sin) + (getY() * cos);
        Location location = clone();
        location.setX(x);
        location.setY(y);
        return new dLocation(location).getAttribute(attribute.fulfill(1));
    }
    if (attribute.matches("find") || attribute.startsWith("nearest")) {
        attribute.fulfill(1);
        // -->
        if (attribute.startsWith("blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) {
            ArrayList<dLocation> found = new ArrayList<dLocation>();
            int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
            List<dMaterial> materials = new ArrayList<dMaterial>();
            if (attribute.hasContext(1)) {
                materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
            }
            // Avoid NPE from invalid materials
            if (materials == null) {
                return null;
            }
            int max = Settings.blockTagsMaxBlocks();
            int index = 0;
            attribute.fulfill(2);
            Location tstart = getBlock().getLocation();
            double tstartY = tstart.getY();
            fullloop: for (int x = -(radius); x <= radius; x++) {
                for (int y = -(radius); y <= radius; y++) {
                    double newY = y + tstartY;
                    if (newY < 0 || newY > 255) {
                        continue;
                    }
                    for (int z = -(radius); z <= radius; z++) {
                        index++;
                        if (index > max) {
                            break fullloop;
                        }
                        if (Utilities.checkLocation(this, tstart.clone().add(x + 0.5, y + 0.5, z + 0.5), radius)) {
                            if (!materials.isEmpty()) {
                                for (dMaterial material : materials) {
                                    if (material.hasData() && material.getData() != 0) {
                                        // TODO: less arbitrary matching
                                        if (material.matchesMaterialData(tstart.clone().add(x, y, z).getBlock().getState().getData())) {
                                            found.add(new dLocation(tstart.clone().add(x, y, z)));
                                        }
                                    } else if (material.getMaterial() == tstart.clone().add(x, y, z).getBlock().getType()) {
                                        found.add(new dLocation(tstart.clone().add(x, y, z)));
                                    }
                                }
                            } else {
                                found.add(new dLocation(tstart.clone().add(x, y, z)));
                            }
                        }
                    }
                }
            }
            Collections.sort(found, new Comparator<dLocation>() {

                @Override
                public int compare(dLocation loc1, dLocation loc2) {
                    return dLocation.this.compare(loc1, loc2);
                }
            });
            return new dList(found).getAttribute(attribute);
        } else // -->
        if (attribute.startsWith("surface_blocks") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) {
            ArrayList<dLocation> found = new ArrayList<dLocation>();
            double radius = aH.matchesDouble(attribute.getContext(2)) ? attribute.getDoubleContext(2) : 10;
            List<dMaterial> materials = new ArrayList<dMaterial>();
            if (attribute.hasContext(1)) {
                materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
            }
            // Avoid NPE from invalid materials
            if (materials == null) {
                return null;
            }
            int max = Settings.blockTagsMaxBlocks();
            int index = 0;
            attribute.fulfill(2);
            Location loc = getBlock().getLocation().add(0.5f, 0.5f, 0.5f);
            fullloop: for (double x = -(radius); x <= radius; x++) {
                for (double y = -(radius); y <= radius; y++) {
                    for (double z = -(radius); z <= radius; z++) {
                        index++;
                        if (index > max) {
                            break fullloop;
                        }
                        if (Utilities.checkLocation(loc, getBlock().getLocation().add(x + 0.5, y + 0.5, z + 0.5), radius)) {
                            Location l = getBlock().getLocation().clone().add(x, y, z);
                            if (!materials.isEmpty()) {
                                for (dMaterial material : materials) {
                                    if (material.matchesMaterialData(getBlock().getLocation().clone().add(x, y, z).getBlock().getType().getNewData(getBlock().getLocation().clone().add(x, y, z).getBlock().getData()))) {
                                        if (l.clone().add(0, 1, 0).getBlock().getType() == Material.AIR && l.clone().add(0, 2, 0).getBlock().getType() == Material.AIR && l.getBlock().getType() != Material.AIR) {
                                            found.add(new dLocation(getBlock().getLocation().clone().add(x + 0.5, y, z + 0.5)));
                                        }
                                    }
                                }
                            } else {
                                if (l.clone().add(0, 1, 0).getBlock().getType() == Material.AIR && l.clone().add(0, 2, 0).getBlock().getType() == Material.AIR && l.getBlock().getType() != Material.AIR) {
                                    found.add(new dLocation(getBlock().getLocation().clone().add(x + 0.5, y, z + 0.5)));
                                }
                            }
                        }
                    }
                }
            }
            Collections.sort(found, new Comparator<dLocation>() {

                @Override
                public int compare(dLocation loc1, dLocation loc2) {
                    return dLocation.this.compare(loc1, loc2);
                }
            });
            return new dList(found).getAttribute(attribute);
        } else // -->
        if (attribute.startsWith("players") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) {
            ArrayList<dPlayer> found = new ArrayList<dPlayer>();
            double radius = aH.matchesDouble(attribute.getContext(2)) ? attribute.getDoubleContext(2) : 10;
            attribute.fulfill(2);
            for (Player player : Bukkit.getOnlinePlayers()) {
                if (!player.isDead() && Utilities.checkLocation(this, player.getLocation(), radius)) {
                    found.add(new dPlayer(player));
                }
            }
            Collections.sort(found, new Comparator<dPlayer>() {

                @Override
                public int compare(dPlayer pl1, dPlayer pl2) {
                    return dLocation.this.compare(pl1.getLocation(), pl2.getLocation());
                }
            });
            return new dList(found).getAttribute(attribute);
        } else // -->
        if (attribute.startsWith("npcs") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) {
            ArrayList<dNPC> found = new ArrayList<dNPC>();
            double radius = aH.matchesDouble(attribute.getContext(2)) ? attribute.getDoubleContext(2) : 10;
            attribute.fulfill(2);
            for (dNPC npc : DenizenAPI.getSpawnedNPCs()) {
                if (Utilities.checkLocation(this.getBlock().getLocation(), npc.getLocation(), radius)) {
                    found.add(npc);
                }
            }
            Collections.sort(found, new Comparator<dNPC>() {

                @Override
                public int compare(dNPC npc1, dNPC npc2) {
                    return dLocation.this.compare(npc1.getLocation(), npc2.getLocation());
                }
            });
            return new dList(found).getAttribute(attribute);
        } else // -->
        if (attribute.startsWith("entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) {
            dList ent_list = new dList();
            if (attribute.hasContext(1)) {
                ent_list = dList.valueOf(attribute.getContext(1));
            }
            ArrayList<dEntity> found = new ArrayList<dEntity>();
            double radius = aH.matchesDouble(attribute.getContext(2)) ? attribute.getDoubleContext(2) : 10;
            attribute.fulfill(2);
            for (Entity entity : getWorld().getEntities()) {
                if (Utilities.checkLocation(this, entity.getLocation(), radius)) {
                    dEntity current = new dEntity(entity);
                    if (!ent_list.isEmpty()) {
                        for (String ent : ent_list) {
                            if (current.comparedTo(ent)) {
                                found.add(current);
                                break;
                            }
                        }
                    } else {
                        found.add(current);
                    }
                }
            }
            Collections.sort(found, new Comparator<dEntity>() {

                @Override
                public int compare(dEntity ent1, dEntity ent2) {
                    return dLocation.this.compare(ent1.getLocation(), ent2.getLocation());
                }
            });
            return new dList(found).getAttribute(attribute);
        } else // -->
        if (attribute.startsWith("living_entities") && attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2)) {
            ArrayList<dEntity> found = new ArrayList<dEntity>();
            double radius = aH.matchesDouble(attribute.getContext(2)) ? attribute.getDoubleContext(2) : 10;
            attribute.fulfill(2);
            for (Entity entity : getWorld().getEntities()) {
                if (entity instanceof LivingEntity && Utilities.checkLocation(this, entity.getLocation(), radius)) {
                    found.add(new dEntity(entity));
                }
            }
            Collections.sort(found, new Comparator<dEntity>() {

                @Override
                public int compare(dEntity ent1, dEntity ent2) {
                    return dLocation.this.compare(ent1.getLocation(), ent2.getLocation());
                }
            });
            return new dList(found).getAttribute(attribute);
        }
    }
    // -->
    if (attribute.startsWith("find_path") && attribute.hasContext(1)) {
        dLocation two = dLocation.valueOf(attribute.getContext(1));
        if (two == null) {
            return null;
        }
        List<dLocation> locs = PathFinder.getPath(this, two);
        dList list = new dList();
        for (dLocation loc : locs) {
            list.add(loc.identify());
        }
        return list.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("formatted.citizens")) {
        return new Element(getX() + ":" + getY() + ":" + getZ() + ":" + getWorld().getName()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("formatted")) {
        return new Element("X '" + getX() + "', Y '" + getY() + "', Z '" + getZ() + "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("chunk") || attribute.startsWith("get_chunk")) {
        return new dChunk(this).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("raw")) {
        dLocation rawLocation = new dLocation(this);
        rawLocation.setRaw(true);
        return rawLocation.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("world")) {
        return dWorld.mirrorBukkitWorld(getWorld()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("x")) {
        return new Element(getX()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("y")) {
        return new Element(getY()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("z")) {
        return new Element(getZ()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("notable_name")) {
        String notname = NotableManager.getSavedId(this);
        if (notname == null) {
            return null;
        }
        return new Element(notname).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("add") && attribute.hasContext(1)) {
        // TODO: Just dLocation.valueOf?
        String[] ints = attribute.getContext(1).replace("l@", "").split(",", 4);
        if (ints.length >= 3) {
            if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0])) && (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1])) && (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
                return new dLocation(this.clone().add(Double.valueOf(ints[0]), Double.valueOf(ints[1]), Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
            }
        } else if (dLocation.matches(attribute.getContext(1))) {
            return new dLocation(this.clone().add(dLocation.valueOf(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("sub") && attribute.hasContext(1)) {
        // TODO: Just dLocation.valueOf?
        String[] ints = attribute.getContext(1).replace("l@", "").split(",", 4);
        if (ints.length == 3 || ints.length == 4) {
            if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0])) && (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1])) && (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
                return new dLocation(this.clone().subtract(Double.valueOf(ints[0]), Double.valueOf(ints[1]), Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
            }
        } else if (dLocation.matches(attribute.getContext(1))) {
            return new dLocation(this.clone().subtract(dLocation.valueOf(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("mul") && attribute.hasContext(1)) {
        return new dLocation(this.clone().multiply(Double.parseDouble(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("div") && attribute.hasContext(1)) {
        return new dLocation(this.clone().multiply(1D / Double.parseDouble(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("normalize")) {
        double len = Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2) + Math.pow(getZ(), 2));
        if (len == 0) {
            return this.getAttribute(attribute.fulfill(1));
        } else {
            return new dLocation(this.clone().multiply(1D / len)).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("vector_length")) {
        return new Element(Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2) + Math.pow(getZ(), 2))).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("distance_squared") && attribute.hasContext(1)) {
        if (dLocation.matches(attribute.getContext(1))) {
            dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
            if (!getWorld().getName().equalsIgnoreCase(toLocation.getWorld().getName())) {
                if (!attribute.hasAlternative()) {
                    dB.echoError("Can't measure distance between two different worlds!");
                }
                return null;
            }
            return new Element(this.distanceSquared(toLocation)).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("distance") && attribute.hasContext(1)) {
        if (dLocation.matches(attribute.getContext(1))) {
            dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
            // -->
            if (attribute.getAttribute(2).startsWith("horizontal")) {
                // -->
                if (attribute.getAttribute(3).startsWith("multiworld")) {
                    return new Element(Math.sqrt(Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))).getAttribute(attribute.fulfill(3));
                } else if (this.getWorld() == toLocation.getWorld()) {
                    return new Element(Math.sqrt(Math.pow(this.getX() - toLocation.getX(), 2) + Math.pow(this.getZ() - toLocation.getZ(), 2))).getAttribute(attribute.fulfill(2));
                }
            } else // -->
            if (attribute.getAttribute(2).startsWith("vertical")) {
                // -->
                if (attribute.getAttribute(3).startsWith("multiworld")) {
                    return new Element(Math.abs(this.getY() - toLocation.getY())).getAttribute(attribute.fulfill(3));
                } else if (this.getWorld() == toLocation.getWorld()) {
                    return new Element(Math.abs(this.getY() - toLocation.getY())).getAttribute(attribute.fulfill(2));
                }
            }
            if (!getWorld().getName().equalsIgnoreCase(toLocation.getWorld().getName())) {
                if (!attribute.hasAlternative()) {
                    dB.echoError("Can't measure distance between two different worlds!");
                }
                return null;
            } else {
                return new Element(this.distance(toLocation)).getAttribute(attribute.fulfill(1));
            }
        }
    }
    // -->
    if (attribute.startsWith("is_within") && attribute.hasContext(1)) {
        if (dEllipsoid.matches(attribute.getContext(1))) {
            dEllipsoid ellipsoid = dEllipsoid.valueOf(attribute.getContext(1));
            if (ellipsoid != null) {
                return new Element(ellipsoid.contains(this)).getAttribute(attribute.fulfill(1));
            }
        } else {
            dCuboid cuboid = dCuboid.valueOf(attribute.getContext(1));
            if (cuboid != null) {
                return new Element(cuboid.isInsideCuboid(this)).getAttribute(attribute.fulfill(1));
            }
        }
    }
    // -->
    if (attribute.startsWith("biome.formatted")) {
        return new Element(CoreUtilities.toLowerCase(getBlock().getBiome().name()).replace('_', ' ')).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("biome")) {
        return new dBiome(getBlock().getBiome()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("cuboids")) {
        List<dCuboid> cuboids = dCuboid.getNotableCuboidsContaining(this);
        dList cuboid_list = new dList();
        for (dCuboid cuboid : cuboids) {
            cuboid_list.add(cuboid.identify());
        }
        return cuboid_list.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("ellipsoids")) {
        List<dEllipsoid> ellipsoids = dEllipsoid.getNotableEllipsoidsContaining(this);
        dList ellipsoid_list = new dList();
        for (dEllipsoid ellipsoid : ellipsoids) {
            ellipsoid_list.add(ellipsoid.identify());
        }
        return ellipsoid_list.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_liquid")) {
        return new Element(getBlock().isLiquid()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("light.from_blocks") || attribute.startsWith("light.blocks")) {
        return new Element(getBlock().getLightFromBlocks()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("light.from_sky") || attribute.startsWith("light.sky")) {
        return new Element(getBlock().getLightFromSky()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("light")) {
        return new Element(getBlock().getLightLevel()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("power")) {
        return new Element(getBlock().getBlockPower()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("type")) {
        return new Element("Location").getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("command_block_name") && getBlock().getType() == Material.COMMAND) {
        return new Element(((CommandBlock) getBlock().getState()).getName()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("command_block") && getBlock().getType() == Material.COMMAND) {
        return new Element(((CommandBlock) getBlock().getState()).getCommand()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("furnace_burn_time")) {
        return new Element(((Furnace) getBlock().getState()).getBurnTime()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("furnace_cook_time")) {
        return new Element(((Furnace) getBlock().getState()).getCookTime()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("attached_to")) {
        BlockFace face = BlockFace.SELF;
        MaterialData data = getBlock().getState().getData();
        if (data instanceof Attachable) {
            face = ((Attachable) data).getAttachedFace();
        }
        if (face != BlockFace.SELF) {
            return new dLocation(getBlock().getRelative(face).getLocation()).getAttribute(attribute.fulfill(1));
        }
    }
    // Iterate through this object's properties' attributes
    for (Property property : PropertyParser.getProperties(this)) {
        String returned = property.getAttribute(attribute);
        if (returned != null) {
            return returned;
        }
    }
    return new Element(identify()).getAttribute(attribute);
}
Also used : Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) Comparator(java.util.Comparator) Player(org.bukkit.entity.Player) PlayerProfile(net.aufdemrand.denizen.nms.util.PlayerProfile) DyeColor(org.bukkit.DyeColor) java.util(java.util) MaterialData(org.bukkit.material.MaterialData) ItemStack(org.bukkit.inventory.ItemStack) BlockIterator(org.bukkit.util.BlockIterator) LivingEntity(org.bukkit.entity.LivingEntity) InventoryHolder(org.bukkit.inventory.InventoryHolder) Property(net.aufdemrand.denizencore.objects.properties.Property) EntityHelper(net.aufdemrand.denizen.nms.interfaces.EntityHelper) Material(org.bukkit.Material) Vector(org.bukkit.util.Vector) Attachable(org.bukkit.material.Attachable) Location(org.bukkit.Location)

Example 18 with InventoryHolder

use of org.bukkit.inventory.InventoryHolder in project Towny by ElgarL.

the class TownyRegenAPI method regenChunk.

/**
	 * Regenerate the chunk the player is stood in and store the block data so it can be undone later.
	 * 
	 * @param player
	 */
public static void regenChunk(Player player) {
    try {
        Coord coord = Coord.parseCoord(player);
        World world = player.getWorld();
        Chunk chunk = world.getChunkAt(player.getLocation());
        int maxHeight = world.getMaxHeight();
        Object[][][] snapshot = new Object[16][maxHeight][16];
        for (int x = 0; x < 16; x++) {
            for (int z = 0; z < 16; z++) {
                for (int y = 0; y < maxHeight; y++) {
                    //Current block to save
                    BlockState state = chunk.getBlock(x, y, z).getState();
                    if (state instanceof org.bukkit.block.Sign) {
                        BlockSign sign = new BlockSign(BukkitTools.getTypeId(state), BukkitTools.getDataData(state), ((org.bukkit.block.Sign) state).getLines());
                        sign.setLocation(state.getLocation());
                        snapshot[x][y][z] = sign;
                    } else if (state instanceof CreatureSpawner) {
                        BlockMobSpawner spawner = new BlockMobSpawner(((CreatureSpawner) state).getSpawnedType());
                        spawner.setLocation(state.getLocation());
                        spawner.setDelay(((CreatureSpawner) state).getDelay());
                        snapshot[x][y][z] = spawner;
                    } else if ((state instanceof InventoryHolder) && !(state instanceof Player)) {
                        BlockInventoryHolder holder = new BlockInventoryHolder(BukkitTools.getTypeId(state), BukkitTools.getDataData(state), ((InventoryHolder) state).getInventory().getContents());
                        holder.setLocation(state.getLocation());
                        snapshot[x][y][z] = holder;
                    } else {
                        snapshot[x][y][z] = new BlockObject(BukkitTools.getTypeId(state), BukkitTools.getDataData(state), state.getLocation());
                    }
                }
            }
        }
        TownyUniverse.getDataSource().getResident(player.getName()).addUndo(snapshot);
        Bukkit.getWorld(player.getWorld().getName()).regenerateChunk(coord.getX(), coord.getZ());
    } catch (NotRegisteredException e) {
    // Failed to get resident
    }
}
Also used : Player(org.bukkit.entity.Player) BlockInventoryHolder(com.palmergames.bukkit.towny.regen.block.BlockInventoryHolder) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) World(org.bukkit.World) Chunk(org.bukkit.Chunk) CreatureSpawner(org.bukkit.block.CreatureSpawner) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) Coord(com.palmergames.bukkit.towny.object.Coord) BlockMobSpawner(com.palmergames.bukkit.towny.regen.block.BlockMobSpawner) BlockState(org.bukkit.block.BlockState) BlockSign(com.palmergames.bukkit.towny.regen.block.BlockSign) BlockObject(com.palmergames.bukkit.towny.regen.block.BlockObject) Sign(org.bukkit.block.Sign) BlockSign(com.palmergames.bukkit.towny.regen.block.BlockSign) InventoryHolder(org.bukkit.inventory.InventoryHolder) BlockInventoryHolder(com.palmergames.bukkit.towny.regen.block.BlockInventoryHolder) BlockObject(com.palmergames.bukkit.towny.regen.block.BlockObject)

Example 19 with InventoryHolder

use of org.bukkit.inventory.InventoryHolder in project Towny by ElgarL.

the class TownyRegenAPI method regenUndo.

/**
	 * Restore the relevant chunk using the snapshot data stored in the resident
	 * object.
	 * 
	 * @param snapshot
	 * @param resident
	 */
public static void regenUndo(Object[][][] snapshot, Resident resident) {
    BlockObject key = ((BlockObject) snapshot[0][0][0]);
    World world = key.getLocation().getWorld();
    Chunk chunk = key.getLocation().getChunk();
    int maxHeight = world.getMaxHeight();
    for (int x = 0; x < 16; x++) {
        for (int z = 0; z < 16; z++) {
            for (int y = 0; y < maxHeight; y++) {
                // Snapshot data we need to update the world.
                Object state = snapshot[x][y][z];
                // The block we will be updating
                Block block = chunk.getBlock(x, y, z);
                if (state instanceof BlockSign) {
                    BlockSign signData = (BlockSign) state;
                    BukkitTools.setTypeIdAndData(block, signData.getTypeId(), signData.getData(), false);
                    Sign sign = (Sign) block.getState();
                    int i = 0;
                    for (String line : signData.getLines()) sign.setLine(i++, line);
                    sign.update(true);
                } else if (state instanceof BlockMobSpawner) {
                    BlockMobSpawner spawnerData = (BlockMobSpawner) state;
                    BukkitTools.setTypeIdAndData(block, spawnerData.getTypeId(), spawnerData.getData(), false);
                    ((CreatureSpawner) block.getState()).setSpawnedType(spawnerData.getSpawnedType());
                    ((CreatureSpawner) block.getState()).setDelay(spawnerData.getDelay());
                } else if ((state instanceof BlockInventoryHolder) && !(state instanceof Player)) {
                    BlockInventoryHolder containerData = (BlockInventoryHolder) state;
                    BukkitTools.setTypeIdAndData(block, containerData.getTypeId(), containerData.getData(), false);
                    // Container to receive the inventory
                    InventoryHolder container = (InventoryHolder) block.getState();
                    // Contents we are respawning.						
                    if (containerData.getItems().length > 0)
                        container.getInventory().setContents(containerData.getItems());
                } else {
                    BlockObject blockData = (BlockObject) state;
                    BukkitTools.setTypeIdAndData(block, blockData.getTypeId(), blockData.getData(), false);
                }
            }
        }
    }
    TownyMessaging.sendMessage(BukkitTools.getPlayerExact(resident.getName()), TownySettings.getLangString("msg_undo_complete"));
}
Also used : BlockInventoryHolder(com.palmergames.bukkit.towny.regen.block.BlockInventoryHolder) Player(org.bukkit.entity.Player) World(org.bukkit.World) Chunk(org.bukkit.Chunk) BlockMobSpawner(com.palmergames.bukkit.towny.regen.block.BlockMobSpawner) BlockSign(com.palmergames.bukkit.towny.regen.block.BlockSign) Block(org.bukkit.block.Block) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) BlockObject(com.palmergames.bukkit.towny.regen.block.BlockObject) Sign(org.bukkit.block.Sign) BlockSign(com.palmergames.bukkit.towny.regen.block.BlockSign) InventoryHolder(org.bukkit.inventory.InventoryHolder) BlockInventoryHolder(com.palmergames.bukkit.towny.regen.block.BlockInventoryHolder) BlockObject(com.palmergames.bukkit.towny.regen.block.BlockObject)

Example 20 with InventoryHolder

use of org.bukkit.inventory.InventoryHolder in project Minigames by AddstarMC.

the class RecorderData method addBlock.

public BlockData addBlock(BlockState block, MinigamePlayer modifier) {
    BlockData bdata = new BlockData(block, modifier);
    String sloc = String.valueOf(bdata.getLocation().getBlockX()) + ":" + bdata.getLocation().getBlockY() + ":" + bdata.getLocation().getBlockZ();
    if (!blockdata.containsKey(sloc)) {
        if (block.getType() == Material.CHEST) {
            Chest chest = (Chest) block;
            if (chest.getInventory().getSize() > 27) {
                Location loc = block.getLocation().clone();
                boolean isRight = false;
                BlockFace dir = ((org.bukkit.material.Chest) chest.getData()).getFacing();
                BlockData secondChest = null;
                //West = -z; East = +z; North = +x; South = -x;
                if (dir == BlockFace.NORTH) {
                    loc.setX(loc.getX() + 1);
                    if (loc.getBlock().getType() == Material.CHEST) {
                        isRight = true;
                    }
                    secondChest = addBlock(loc.getBlock().getState(), modifier);
                } else if (dir == BlockFace.SOUTH) {
                    loc.setX(loc.getX() - 1);
                    if (loc.getBlock().getType() == Material.CHEST) {
                        isRight = true;
                    }
                    secondChest = addBlock(loc.getBlock().getState(), modifier);
                } else if (dir == BlockFace.WEST) {
                    loc.setZ(loc.getZ() - 1);
                    if (loc.getBlock().getType() == Material.CHEST) {
                        isRight = true;
                    }
                    secondChest = addBlock(loc.getBlock().getState(), modifier);
                } else if (dir == BlockFace.EAST) {
                    loc.setZ(loc.getZ() + 1);
                    if (loc.getBlock().getType() == Material.CHEST) {
                        isRight = true;
                    }
                    secondChest = addBlock(loc.getBlock().getState(), modifier);
                }
                if (!isRight) {
                    ItemStack[] items = new ItemStack[chest.getInventory().getContents().length];
                    for (int i = 0; i < items.length; i++) {
                        if (chest.getInventory().getContents()[i] != null)
                            items[i] = chest.getInventory().getContents()[i].clone();
                    }
                    bdata.setItems(items);
                    if (minigame.isRandomizeChests())
                        bdata.randomizeContents(minigame.getMinChestRandom(), minigame.getMaxChestRandom());
                } else {
                    if (secondChest.getItems() == null) {
                        ItemStack[] items = new ItemStack[chest.getInventory().getContents().length];
                        for (int i = 0; i < items.length; i++) {
                            if (chest.getInventory().getContents()[i] != null)
                                items[i] = chest.getInventory().getContents()[i].clone();
                        }
                        secondChest.setItems(items);
                        if (minigame.isRandomizeChests())
                            secondChest.randomizeContents(minigame.getMinChestRandom(), minigame.getMaxChestRandom());
                    }
                }
            } else {
                ItemStack[] items = new ItemStack[chest.getInventory().getContents().length];
                for (int i = 0; i < items.length; i++) {
                    if (chest.getInventory().getContents()[i] != null)
                        items[i] = chest.getInventory().getContents()[i].clone();
                }
                bdata.setItems(items);
                if (minigame.isRandomizeChests())
                    bdata.randomizeContents(minigame.getMinChestRandom(), minigame.getMaxChestRandom());
            }
        } else if (block instanceof InventoryHolder) {
            InventoryHolder inv = (InventoryHolder) block;
            ItemStack[] items = new ItemStack[inv.getInventory().getContents().length];
            for (int i = 0; i < items.length; i++) {
                if (inv.getInventory().getContents()[i] != null)
                    items[i] = inv.getInventory().getContents()[i].clone();
            }
            bdata.setItems(items);
        } else if (block.getType() == Material.FLOWER_POT) {
            bdata.setSpecialData("contents", block.getData());
        }
        blockdata.put(sloc, bdata);
        return bdata;
    } else {
        if (block.getType() != Material.CHEST || !blockdata.get(sloc).hasRandomized())
            blockdata.get(sloc).setModifier(modifier);
        return blockdata.get(sloc);
    }
}
Also used : Chest(org.bukkit.block.Chest) BlockFace(org.bukkit.block.BlockFace) ItemStack(org.bukkit.inventory.ItemStack) InventoryHolder(org.bukkit.inventory.InventoryHolder) Location(org.bukkit.Location)

Aggregations

InventoryHolder (org.bukkit.inventory.InventoryHolder)23 Player (org.bukkit.entity.Player)9 ItemStack (org.bukkit.inventory.ItemStack)9 Inventory (org.bukkit.inventory.Inventory)8 EventHandler (org.bukkit.event.EventHandler)7 Location (org.bukkit.Location)5 Sign (org.bukkit.block.Sign)4 HashMap (java.util.HashMap)3 Block (org.bukkit.block.Block)3 BlockState (org.bukkit.block.BlockState)3 Jukebox (org.bukkit.block.Jukebox)3 BlockInventoryHolder (com.palmergames.bukkit.towny.regen.block.BlockInventoryHolder)2 BlockMobSpawner (com.palmergames.bukkit.towny.regen.block.BlockMobSpawner)2 BlockObject (com.palmergames.bukkit.towny.regen.block.BlockObject)2 BlockSign (com.palmergames.bukkit.towny.regen.block.BlockSign)2 ArrayList (java.util.ArrayList)2 Comparator (java.util.Comparator)2 Element (net.aufdemrand.denizencore.objects.Element)2 Chunk (org.bukkit.Chunk)2 Material (org.bukkit.Material)2