org.bukkit.inventory.InventoryHolder Java Examples

The following examples show how to use org.bukkit.inventory.InventoryHolder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LWC.java    From Modern-LWC with MIT License 6 votes vote down vote up
/**
 * Merge inventories into one
 *
 * @param blocks
 * @return
 */
public ItemStack[] mergeInventories(List<Block> blocks) {
    ItemStack[] stacks = new ItemStack[54];
    int index = 0;

    try {
        for (Block block : blocks) {
            if (!(block.getState() instanceof InventoryHolder)) {
                continue;
            }

            InventoryHolder holder = (InventoryHolder) block.getState();
            Inventory inventory = holder.getInventory();

            // Add all the items from this inventory
            for (ItemStack stack : inventory.getContents()) {
                stacks[index] = stack;
                index++;
            }
        }
    } catch (Exception e) {
        return mergeInventories(blocks);
    }

    return stacks;
}
 
Example #2
Source File: BonusGoodie.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
public void setHolder(InventoryHolder holder) throws CivException {
	if (holder == null) {
		return;
	}
	
	if (holderStore == null) {
		if (holder instanceof Chest) {
			holderStore = new InventoryHolderStorage(((Chest)holder).getLocation());
		} else if (holder instanceof Player){
			holderStore = new InventoryHolderStorage((Player)holder);
		} else {
			throw new CivException("Invalid holder.");
		}
	} else {
		holderStore.setHolder(holder);
	}
	
	// If we have a holder, we cannot be on the ground or in a item frame.
	this.frameStore = null;
	this.item = null;
	
}
 
Example #3
Source File: InventoryHolderStorage.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
public void setHolder(InventoryHolder holder) throws CivException {
	if (holder instanceof Player) {
		Player player = (Player)holder;
		playerName = player.getName();
		blockLocation = null;
		return;
	} 
	
	if (holder instanceof Chest) {
		Chest chest = (Chest)holder;
		playerName = null;
		blockLocation = chest.getLocation();
		return;
	} 
	
	if (holder instanceof DoubleChest) {
		DoubleChest dchest = (DoubleChest)holder;
		playerName = null;
		blockLocation = dchest.getLocation();
		return;
	}
	
	throw new CivException("Invalid holder passed to set holder:"+holder.toString());
}
 
Example #4
Source File: Furnace_V1_7_R3.java    From AnnihilationPro with MIT License 6 votes vote down vote up
@Override
	public InventoryHolder getOwner()
	{
		//Bukkit.getLogger().info("getOwner");
//		int x = 0;
//		org.bukkit.block.Block b = this.world.getWorld().getBlockAt(x, 0, 0);
//		while(b != null && b.getType() != Material.AIR)
//			b = this.world.getWorld().getBlockAt(++x,0,0);
//		Furnace furnace = new CraftFurnace(b);
		furnace = new CraftFurnace(this.world.getWorld().getBlockAt(0, 0, 0));
		try
		{
			ReflectionUtil.setValue(furnace, "furnace", this);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return furnace;
	}
 
Example #5
Source File: Furnace_V1_8_R1.java    From AnnihilationPro with MIT License 6 votes vote down vote up
@Override
    public InventoryHolder getOwner()
    {
//		int x = 0;
//		org.bukkit.block.Block b = this.world.getWorld().getBlockAt(x, 0, 0);
//		while(b != null && b.getType() != Material.AIR)
//			b = this.world.getWorld().getBlockAt(++x,0,0);
//		Furnace furnace = new CraftFurnace(b);
        org.bukkit.block.Furnace furnace = new CraftFurnace(this.world.getWorld().getBlockAt(0, 0, 0));
        try
        {
            ReflectionUtil.setValue(furnace, "furnace", this);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return furnace;
    }
 
Example #6
Source File: ViewInventoryMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void showInventories(final ObserverInteractEvent event) {
    if(event.getClickType() != ClickType.RIGHT) return;
    if(event.getPlayer().isDead()) return;

    if(event.getClickedParticipant() != null) {
        event.setCancelled(true);
        if(canPreviewInventory(event.getPlayer(), event.getClickedParticipant())) {
            this.previewPlayerInventory(event.getPlayer().getBukkit(), event.getClickedParticipant().getInventory());
        }
    } else if(event.getClickedEntity() instanceof InventoryHolder && !(event.getClickedEntity() instanceof Player)) {
        event.setCancelled(true);
        this.previewInventory(event.getPlayer().getBukkit(), ((InventoryHolder) event.getClickedEntity()).getInventory());
    } else if(event.getClickedBlockState() instanceof InventoryHolder) {
        event.setCancelled(true);
        this.previewInventory(event.getPlayer().getBukkit(), ((InventoryHolder) event.getClickedBlockState()).getInventory());
    }
}
 
Example #7
Source File: FillListener.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Return a predicate that applies a Filter to the given InventoryHolder,
 * or null if the InventoryHolder is not something that we should be filling.
 */
private static @Nullable Predicate<Filter> passesFilter(InventoryHolder holder) {
    if(holder instanceof DoubleChest) {
        final DoubleChest doubleChest = (DoubleChest) holder;
        return filter -> !filter.denies((Chest) doubleChest.getLeftSide()) ||
                         !filter.denies((Chest) doubleChest.getRightSide());
    } else if(holder instanceof BlockState) {
        return filter -> !filter.denies((BlockState) holder);
    } else if(holder instanceof Player) {
        // This happens with crafting inventories, and possibly other transient inventory types
        // Pretty sure we never want to fill an inventory held by the player
        return null;
    } else if(holder instanceof Entity) {
        return filter -> !filter.denies(new EntityQuery((Entity) holder));
    } else {
        // If we're not sure what it is, don't fill it
        return null;
    }
}
 
Example #8
Source File: WoolMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler
public void handleWoolCrafting(PrepareItemCraftEvent event) {
  ItemStack result = event.getRecipe().getResult();
  InventoryHolder holder = event.getInventory().getHolder();

  if (holder instanceof Player) {
    MatchPlayer playerHolder = this.match.getPlayer((Player) holder);

    if (playerHolder != null && result != null && result.getType() == Material.WOOL) {
      for (MonumentWool wool : this.wools.values()) {
        if (wool.getDefinition().isObjectiveWool(result)) {
          if (!wool.getDefinition().isCraftable()) {
            playerHolder.sendWarning(
                TranslatableComponent.of("wool.craftingDisabled", wool.getComponentName()));
            event.getInventory().setResult(null);
          }
        }
      }
    }
  }
}
 
Example #9
Source File: ViewInventoryMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void showInventories(final ObserverInteractEvent event) {
  if (event.getClickType() != ClickType.RIGHT) return;
  if (event.getPlayer().isDead()) return;

  if (event.getClickedParticipant() != null) {
    event.setCancelled(true);
    if (canPreviewInventory(event.getPlayer(), event.getClickedParticipant())) {
      this.previewPlayerInventory(
          event.getPlayer().getBukkit(), event.getClickedParticipant().getInventory());
    }
  } else if (event.getClickedEntity() instanceof InventoryHolder
      && !(event.getClickedEntity() instanceof Player)) {
    event.setCancelled(true);
    this.previewInventory(
        event.getPlayer().getBukkit(),
        ((InventoryHolder) event.getClickedEntity()).getInventory());
  } else if (event.getClickedBlockState() instanceof InventoryHolder) {
    event.setCancelled(true);
    this.previewInventory(
        event.getPlayer().getBukkit(),
        ((InventoryHolder) event.getClickedBlockState()).getInventory());
  }
}
 
Example #10
Source File: DisplayProtectionListener.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void inventory(InventoryPickupItemEvent event) {
    ItemStack itemStack = event.getItem().getItemStack();
    if (DisplayItem.getNowUsing() != DisplayType.REALITEM) {
        return;
    }
    if (!DisplayItem.checkIsGuardItemStack(itemStack)) {
        return; // We didn't care that
    }
    @Nullable Location loc = event.getInventory().getLocation();
    @Nullable InventoryHolder holder = event.getInventory().getHolder();
    event.setCancelled(true);
    sendAlert(
            "[DisplayGuard] Something  "
                    + holder
                    + " at "
                    + loc
                    + " trying pickup the DisplayItem,  you should teleport to that location and to check detail..");
    Util.inventoryCheck(event.getInventory());
}
 
Example #11
Source File: WoolMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler
public void handleWoolCrafting(PrepareItemCraftEvent event) {
    ItemStack result = event.getRecipe().getResult();
    InventoryHolder holder = event.getInventory().getHolder();

    if (holder instanceof Player) {
        MatchPlayer playerHolder = this.match.getPlayer((Player) holder);

        if (playerHolder != null && result != null && result.getType() == Material.WOOL) {
            for(MonumentWool wool : this.wools) {
                if(wool.getDefinition().isObjectiveWool(result)) {
                    if(!wool.getDefinition().isCraftable()) {
                        playerHolder.sendMessage(ChatColor.RED + PGMTranslations.t("match.wool.craftDisabled", playerHolder, BukkitUtils.woolMessage(wool.getDyeColor())));
                        event.getInventory().setResult(null);
                    }
                }
            }
        }
    }
}
 
Example #12
Source File: ExprInventoryInfo.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Object[] get(Event e, Inventory[] source) {

	switch (type) {
		case HOLDER:
			return get(source, inv -> {
				InventoryHolder holder = inv.getHolder();
				if (holder instanceof BlockState) {
					return new BlockInventoryHolder((BlockState) holder);
				}
				return holder;
			});
		case ROWS:
			return get(source, inv -> inv.getSize() / 9);
		case VIEWERS:
			List<HumanEntity> viewers = new ArrayList<>();
			for (Inventory inventory : source) {
				viewers.addAll(inventory.getViewers());
			}
			return viewers.toArray(new HumanEntity[0]);
		default:
			return new Object[0];
	}

}
 
Example #13
Source File: Util.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the chest attached to the given chest. The given block must be a chest.
 *
 * @param b The chest to check.
 * @return the block which is also a chest and connected to b.
 */
@Nullable
public static Block getSecondHalf(@NotNull Block b) {
    BlockState state = b.getState();
    if (!(state instanceof Chest)) {
        return null;
    }
    Chest oneSideOfChest = (Chest) state;
    InventoryHolder chestHolder = oneSideOfChest.getInventory().getHolder();
    if (chestHolder instanceof DoubleChest) {
        DoubleChest doubleChest = (DoubleChest) chestHolder;
        InventoryHolder left = doubleChest.getLeftSide();
        InventoryHolder right = doubleChest.getRightSide();
        Chest leftC = (Chest) left;
        Chest rightC = (Chest) right;
        if (equalsBlockStateLocation(oneSideOfChest.getLocation(), Objects.requireNonNull(rightC).getLocation())) {
            return Objects.requireNonNull(leftC).getBlock();
        }
        if (equalsBlockStateLocation(oneSideOfChest.getLocation(), Objects.requireNonNull(leftC).getLocation())) {
            return rightC.getBlock();
        }
    }
    return null;
}
 
Example #14
Source File: GameMap.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
public void addChest(Chest chest, ChestPlacementType cpt) {
	ArrayList<CoordLoc> list;
	if (cpt == ChestPlacementType.NORMAL) {
		list = chests;
	} else {
		list = centerChests;
	}
	InventoryHolder ih = chest.getInventory().getHolder();
       if (ih instanceof DoubleChest) {
       	DoubleChest dc = (DoubleChest) ih;
		Chest left = (Chest) dc.getLeftSide();
		Chest right = (Chest) dc.getRightSide();
		CoordLoc locLeft = new CoordLoc(left.getX(), left.getY(), left.getZ());
		CoordLoc locRight = new CoordLoc(right.getX(), right.getY(), right.getZ());
		if (!(list.contains(locLeft) || list.contains(locRight))) {
			addChest(locLeft, cpt, true);
		}
       } else {
       	CoordLoc loc = new CoordLoc(chest.getX(), chest.getY(), chest.getZ());
           if (!list.contains(loc)){
			addChest(loc, cpt, true);
           }
       }
}
 
Example #15
Source File: ChunkEntry.java    From PlotMe-Core with GNU General Public License v3.0 5 votes vote down vote up
public void run() {
    ((BukkitWorld) world).getWorld().regenerateChunk(chunk.getX(), chunk.getZ());
    for (int x = 0; x < 16; ++x) {
        for (int y = 0; y < 256; ++y) {
            for (int z = 0; z < 16; ++z) {
                Vector pt = min.add(x, y, z);
                int index = y * 256 + z * 16 + x;
                int lowestX = Math.min(bottom.getBlockX() + 1, top.getBlockX() - 1);
                int highestX = Math.max(bottom.getBlockX() + 1, top.getBlockX() - 1);
                int lowestZ = Math.min(bottom.getBlockZ() - 1, top.getBlockZ() + 1);
                int highestZ = Math.max(bottom.getBlockZ() - 1, top.getBlockZ() + 1);

                boolean contains =
                        pt.getBlockX() >= lowestX && pt.getBlockX() <= highestX && pt.getBlockZ() >= lowestZ && pt.getBlockZ() <= highestZ;
                if (!contains) {
                    BukkitBlock block = ((BukkitBlock) materials[index]);
                    BukkitBlock blockAt = (BukkitBlock) world.getBlockAt(pt);
                    blockAt.setTypeIdAndData((short) block.getTypeId(), block.getData(), false);
                    if (block.getState() instanceof InventoryHolder) {
                        if (blockAt.getState() instanceof InventoryHolder) {
                            ((InventoryHolder) blockAt.getState()).getInventory()
                                    .setContents(((InventoryHolder) block.getState()).getInventory().getContents());
                        }
                    }
                }
            }
        }
    }
    world.refreshChunk(chunk.getX(), chunk.getZ());

}
 
Example #16
Source File: CarryingFilter.java    From CardinalPGM with MIT License 5 votes vote down vote up
@Override
public FilterState evaluate(final Object... objects) {
    for (Object object : objects) {
        if (object instanceof InventoryHolder) {
            for (ItemStack item : ((InventoryHolder) object).getInventory()) {
                if (item != null && this.item.isSimilar(item))
                    return ALLOW;
            }
            return DENY;
        }
    }
    return (getParent() == null ? ABSTAIN : getParent().evaluate(objects));
}
 
Example #17
Source File: FillListener.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
Stream<Inventory> inventories() {
    return Stream.concat(
        cache.region()
             .tileEntities(world)
             .filter(FillListener::isFillable)
             .filter(block -> !cache.filter().denies(block))
             .map(block -> ((InventoryHolder) block).getInventory()),
        cache.region()
             .entities(world)
             .filter(FillListener::isFillable)
             .filter(entity -> !cache.filter().denies(new EntityQuery(entity)))
             .map(entity -> ((InventoryHolder) entity).getInventory())
    );
}
 
Example #18
Source File: InventorySlot.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String toString(@Nullable Event e, boolean debug) {
	InventoryHolder holder = invi.getHolder();
	
	if (holder instanceof BlockState)
		holder = new BlockInventoryHolder((BlockState) holder);
	
	if (invi.getHolder() != null) {
		if (invi instanceof CraftingInventory) // 4x4 crafting grid is contained in player too!
			return "crafting slot " + index + " of " + Classes.toString(holder);
		
		return "inventory slot " + index + " of " + Classes.toString(holder);
	}
	return "inventory slot " + index + " of " + Classes.toString(invi);
}
 
Example #19
Source File: CargoUtils.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
static ItemStack withdraw(Block node, Block target, ItemStack template) {
    DirtyChestMenu menu = getChestMenu(target);

    if (menu == null) {
        if (hasInventory(target)) {
            BlockState state = target.getState();

            if (state instanceof InventoryHolder) {
                return withdrawFromVanillaInventory(node, template, ((InventoryHolder) state).getInventory());
            }
        }

        return null;
    }

    ItemStackWrapper wrapper = new ItemStackWrapper(template);

    for (int slot : menu.getPreset().getSlotsAccessedByItemTransport(menu, ItemTransportFlow.WITHDRAW, null)) {
        ItemStack is = menu.getItemInSlot(slot);

        if (SlimefunUtils.isItemSimilar(is, wrapper, true) && matchesFilter(node, is)) {
            if (is.getAmount() > template.getAmount()) {
                is.setAmount(is.getAmount() - template.getAmount());
                menu.replaceExistingItem(slot, is.clone());
                return template;
            }
            else {
                menu.replaceExistingItem(slot, null);
                return is;
            }
        }
    }

    return null;
}
 
Example #20
Source File: CraftInventory.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public InventoryHolder getHolder() {
    // Cauldron start - fixes openblocks AbstractMethodError
    try {
        return inventory.getOwner();
    } catch (AbstractMethodError e) {
        if (inventory instanceof net.minecraft.tileentity.TileEntity) {
            return CauldronUtils.getOwner((net.minecraft.tileentity.TileEntity)inventory);
        } else {
            return null;                
        }
    }
    // Cauldron end
}
 
Example #21
Source File: Shop.java    From ShopChest with MIT License 5 votes vote down vote up
/**
 * Runs everything that needs to be called synchronously in order 
 * to prepare creating the hologram.
 */
private PreCreateResult preCreateHologram() {
    plugin.debug("Creating hologram (#" + id + ")");

    InventoryHolder ih = getInventoryHolder();

    if (ih == null) return null;

    Chest[] chests = new Chest[2];
    BlockFace face;

    if (ih instanceof DoubleChest) {
        DoubleChest dc = (DoubleChest) ih;
        Chest r = (Chest) dc.getRightSide();
        Chest l = (Chest) dc.getLeftSide();

        chests[0] = r;
        chests[1] = l;
    } else {
        chests[0] = (Chest) ih;
    }

    if (Utils.getMajorVersion() < 13) {
        face = ((org.bukkit.material.Directional) chests[0].getData()).getFacing();
    } else {
        face = ((Directional) chests[0].getBlockData()).getFacing();
    }

    return new PreCreateResult(ih.getInventory(), chests, face);
}
 
Example #22
Source File: LWC.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Remove the inventory from a block
 *
 * @param block
 */
private void removeInventory(Block block) {
    if (block == null) {
        return;
    }

    if (!(block.getState() instanceof InventoryHolder)) {
        return;
    }

    InventoryHolder holder = (InventoryHolder) block.getState();
    holder.getInventory().clear();
}
 
Example #23
Source File: CraftInventoryCustom.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public MinecraftInventory(InventoryHolder owner, int size, String title) {
    Validate.notNull(title, "Title cannot be null");
    Validate.isTrue(title.length() <= 32, "Title cannot be longer than 32 characters");
    this.items = new net.minecraft.item.ItemStack[size];
    this.title = title;
    this.viewers = new ArrayList<HumanEntity>();
    this.owner = owner;
    this.type = InventoryType.CHEST;
}
 
Example #24
Source File: ExprInventory.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
	// if we're dealing with a loop of just this expression
	Node n = SkriptLogger.getNode();
	inLoop = n != null && ("loop " + parseResult.expr).equals(n.getKey());
	holders = (Expression<InventoryHolder>) exprs[0];
	return true;
}
 
Example #25
Source File: WoolMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onContainerPlace(BlockPlaceEvent event) {
    // Blacklist any placed container blocks
    if(event.getBlock().getState() instanceof InventoryHolder) {
        this.chests.put(((InventoryHolder) event.getBlock().getState()).getInventory(), false);
    }
}
 
Example #26
Source File: GuiListener.java    From IF with The Unlicense 5 votes vote down vote up
/**
 * Handles users picking up items while their bottom inventory is in use.
 *
 * @param event the event fired when an entity picks up an item
 * @since 0.6.1
 */
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onEntityPickupItem(@NotNull EntityPickupItemEvent event) {
    if (!(event.getEntity() instanceof HumanEntity)) {
        return;
    }

    InventoryHolder holder = ((HumanEntity) event.getEntity()).getOpenInventory().getTopInventory().getHolder();

    if (!(holder instanceof Gui)) {
        return;
    }

    Gui gui = (Gui) holder;

    if (gui.getState() != Gui.State.BOTTOM) {
        return;
    }

    int leftOver = gui.getHumanEntityCache().add((HumanEntity) event.getEntity(), event.getItem().getItemStack());

    if (leftOver == 0) {
        event.getItem().remove();
    } else {
        ItemStack itemStack = event.getItem().getItemStack();

        itemStack.setAmount(leftOver);

        event.getItem().setItemStack(itemStack);
    }

    event.setCancelled(true);
}
 
Example #27
Source File: InventoryGui.java    From InventoryGui with MIT License 5 votes vote down vote up
/**
 * Get the GUI registered to an InventoryHolder
 * @param holder    The InventoryHolder to get the GUI for
 * @return          The InventoryGui registered to it or <tt>null</tt> if none was registered to it
 */
public static InventoryGui get(InventoryHolder holder) {
    if (holder instanceof Entity) {
        return GUI_MAP.get(((Entity) holder).getUniqueId().toString());
    } else if (holder instanceof BlockState) {
        return GUI_MAP.get(((BlockState) holder).getLocation().toString());
    }
    return null;
}
 
Example #28
Source File: ShopUtils.java    From ShopChest with MIT License 5 votes vote down vote up
/**
 * Add a shop
 * @param shop Shop to add
 * @param addToDatabase Whether the shop should also be added to the database
 * @param callback Callback that - if succeeded - returns the ID the shop had or was given (as {@code int})
 */
public void addShop(Shop shop, boolean addToDatabase, Callback<Integer> callback) {
    InventoryHolder ih = shop.getInventoryHolder();
    plugin.debug("Adding shop... (#" + shop.getID() + ")");

    if (ih instanceof DoubleChest) {
        DoubleChest dc = (DoubleChest) ih;
        Chest r = (Chest) dc.getRightSide();
        Chest l = (Chest) dc.getLeftSide();

        plugin.debug("Added shop as double chest. (#" + shop.getID() + ")");

        shopLocation.put(r.getLocation(), shop);
        shopLocation.put(l.getLocation(), shop);
    } else {
        plugin.debug("Added shop as single chest. (#" + shop.getID() + ")");

        shopLocation.put(shop.getLocation(), shop);
    }

    if (addToDatabase) {
        if (shop.getShopType() != ShopType.ADMIN) {
            playerShopAmount.compute(shop.getVendor().getUniqueId(), (uuid, amount) -> amount == null ? new Counter(1) : amount.increment());
        }
        plugin.getShopDatabase().addShop(shop, callback);
    } else {
        if (callback != null) callback.callSyncResult(shop.getID());
    }

}
 
Example #29
Source File: RestorableBlock.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Wrap a block in a restorableblock object
 *
 * @param block
 * @return
 */
public static RestorableBlock wrapBlock(Block block) {
    if (block == null) {
        return null;
    }

    BlockCache blockCache = BlockCache.getInstance();
    RestorableBlock rblock = new RestorableBlock();
    rblock.id = blockCache.getBlockId(block);
    rblock.world = block.getWorld().getName();
    rblock.x = block.getX();
    rblock.y = block.getY();
    rblock.z = block.getZ();
    rblock.data = block.getData();

    BlockState state = block.getState();

    // Does it have an inventory? ^^
    if (state instanceof InventoryHolder) {
        Inventory inventory = ((InventoryHolder) state).getInventory();
        ItemStack[] stacks = inventory.getContents();

        for (int slot = 0; slot < stacks.length; slot++) {
            ItemStack stack = stacks[slot];

            if (stack == null) {
                continue; // don't waste space!
            }

            rblock.setSlot(slot, stack);
        }
    }

    return rblock;
}
 
Example #30
Source File: v1_14_R1.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setBlockFast(Block block, int blockId, byte data) {
    BlockState state = block.getState();
    if (state.getType().name().endsWith("AIR") && blockId == 0) return;
    if (state instanceof InventoryHolder) {
        ((InventoryHolder) state).getInventory().clear();
    }
    XMaterial material = XMaterial.requestOldXMaterial(blockId, (byte) 0);
    if (material != null && material.parseMaterial() != null) {
        block.setBlockData(IridiumSkyblock.getInstance().fromLegacy(material.parseMaterial(), data), false);
    }
}