Java Code Examples for net.minecraft.item.ItemStack#getCapability()

The following examples show how to use net.minecraft.item.ItemStack#getCapability() . 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: ElectricStats.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onUpdate(ItemStack itemStack, Entity entity) {
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if(!entity.world.isRemote && entity instanceof EntityPlayer && electricItem != null &&
        electricItem.canProvideChargeExternally() &&
        isInDishargeMode(itemStack) && electricItem.getCharge() > 0L) {

        EntityPlayer entityPlayer = (EntityPlayer) entity;
        InventoryPlayer inventoryPlayer = entityPlayer.inventory;
        long transferLimit = electricItem.getTransferLimit();

        for(int i = 0; i < inventoryPlayer.getSizeInventory(); i++) {
            ItemStack itemInSlot = inventoryPlayer.getStackInSlot(i);
            IElectricItem slotElectricItem = itemInSlot.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
            if(slotElectricItem != null && !slotElectricItem.canProvideChargeExternally()) {

                long chargedAmount = chargeElectricItem(transferLimit, electricItem, slotElectricItem);
                if(chargedAmount > 0L) {
                    transferLimit -= chargedAmount;
                    if(transferLimit == 0L) break;
                }
            }
        }
    }
}
 
Example 2
Source File: GTUtility.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Applies specific amount of damage to item, either to durable items (which implement IDamagableItem)
 * or to electric items, which have capability IElectricItem
 * Damage amount is equal to EU amount used for electric items
 *
 * @return if damage was applied successfully
 */
//TODO get rid of that
public static boolean doDamageItem(ItemStack itemStack, int vanillaDamage, boolean simulate) {
    Item item = itemStack.getItem();
    if (item instanceof IToolItem) {
        //if item implements IDamagableItem, it manages it's own durability itself
        IToolItem damagableItem = (IToolItem) item;
        return damagableItem.damageItem(itemStack, vanillaDamage, simulate);

    } else if (itemStack.hasCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null)) {
        //if we're using electric item, use default energy multiplier for textures
        IElectricItem capability = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
        int energyNeeded = vanillaDamage * ConfigHolder.energyUsageMultiplier;
        //noinspection ConstantConditions
        return capability.discharge(energyNeeded, Integer.MAX_VALUE, true, false, simulate) == energyNeeded;

    } else if (itemStack.isItemStackDamageable()) {
        if (!simulate && itemStack.attemptDamageItem(vanillaDamage, new Random(), null)) {
            //if we can't accept more damage, just shrink stack and mark it as broken
            //actually we would play broken animation here, but we don't have an entity who holds item
            itemStack.shrink(1);
        }
        return true;
    }
    return false;
}
 
Example 3
Source File: TileEntityEnderFurnace.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if the given ItemStack contains a valid fluid fuel source for the furnace.
 * Valid fuels are currently just lava.
 * @param stack
 * @return
 */
private static boolean itemContainsFluidFuel(ItemStack stack)
{
    if (stack.isEmpty() || stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null) == false)
    {
        return false;
    }

    IFluidHandler handler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);

    if (handler == null)
    {
        return false;
    }

    FluidStack fluidStack = handler.drain(Fluid.BUCKET_VOLUME, false);
    //System.out.printf("itemContainsFluidFuelFluidCapability: %s - %d\n", (fluidStack != null ? fluidStack.getFluid().getName() : "null"), fluidStack != null ? fluidStack.amount : 0);

    if (fluidStack == null || fluidStack.amount <= 0)
    {
        return false;
    }

    return fluidStack.getFluid() == FluidRegistry.LAVA;
}
 
Example 4
Source File: ElectricStats.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int getMaxStackSize(ItemStack itemStack, int defaultValue) {
    ElectricItem electricItem = (ElectricItem) itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if (electricItem == null || electricItem.getCharge() == 0) {
        return defaultValue;
    }
    return 1;
}
 
Example 5
Source File: ElectricStats.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
    ItemStack itemStack = player.getHeldItem(hand);
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if(electricItem != null && electricItem.canProvideChargeExternally() && player.isSneaking()) {
        if(!world.isRemote) {
            boolean isInDischargeMode = isInDishargeMode(itemStack);
            String locale = "metaitem.electric.discharge_mode." + (isInDischargeMode ? "disabled" : "enabled");
            player.sendStatusMessage(new TextComponentTranslation(locale), true);
            setInDischargeMode(itemStack, !isInDischargeMode);
        }
        return ActionResult.newResult(EnumActionResult.SUCCESS, itemStack);
    }
    return ActionResult.newResult(EnumActionResult.PASS, itemStack);
}
 
Example 6
Source File: ScannerBehavior.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean dischargeItem(ItemStack itemStack, long amount, boolean simulate) {
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if (electricItem == null) {
        return false;
    }
    long dischargeAmount = amount * costPerUseTick;
    return electricItem.discharge(dischargeAmount, Integer.MAX_VALUE, true, false, simulate) >= dischargeAmount;
}
 
Example 7
Source File: DefaultSubItemHandler.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void getSubItems(ItemStack itemStack, CreativeTabs creativeTab, NonNullList<ItemStack> subItems) {
    subItems.add(itemStack.copy());
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if (electricItem != null) {
        electricItem.charge(Long.MAX_VALUE, Integer.MAX_VALUE, true, false);
        subItems.add(itemStack);
    }
    if (creativeTab == CreativeTabs.SEARCH) {
        if (itemStack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) {
            addFluidContainerVariants(itemStack, subItems);
        }
    }
}
 
Example 8
Source File: MetaItem.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ItemStack getChargedStackWithOverride(IElectricItem source) {
    ItemStack itemStack = getStackForm(1);
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if (electricItem == null) {
        throw new IllegalStateException("Not an electric item.");
    }
    if (!(electricItem instanceof ElectricItem)) {
        throw new IllegalStateException("Only standard ElectricItem implementation supported, but this item uses " + electricItem.getClass());
    }
    ((ElectricItem) electricItem).setMaxChargeOverride(source.getMaxCharge());
    long charge = source.discharge(Long.MAX_VALUE, Integer.MAX_VALUE, true, false, true);
    electricItem.charge(charge, Integer.MAX_VALUE, true, false);
    return itemStack;
}
 
Example 9
Source File: ClientProxy.java    From Signals with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z){
    TileEntity te = y >= 0 ? world.getTileEntity(new BlockPos(x, y, z)) : null;
    Entity entity = y == -1 ? world.getEntityByID(x) : null;
    switch(EnumGuiId.values()[ID]){
        case STATION_MARKER:
            return new GuiStationMarker((TileEntityStationMarker)te);
        case MINECART_DESTINATION:
            return new GuiMinecart(player.inventory, (EntityMinecart)entity, z == 1);
        case NETWORK_CONTROLLER:
            return new GuiNetworkController();
        case SELECT_DESTINATION_PROVIDER:
            return new GuiSelectDestinationProvider(te);
        case ITEM_HANDLER_DESTINATION:
            return new GuiItemHandlerDestination(te);
        case CART_HOPPER:
            return new GuiCartHopper((TileEntityCartHopper)te);
        case RAIL_LINK:
            return new GuiRailLink((TileEntityRailLink)te);
        case TICKET_DESTINATION:
            ItemStack stack = player.getHeldItemMainhand();
            CapabilityMinecartDestination accessor = stack.getCapability(CapabilityMinecartDestination.INSTANCE, null);
            if(accessor == null) return null;
            ItemTicket.readNBTIntoCap(stack);
            return new GuiTicket(new Container(){
                @Override
                public boolean canInteractWith(EntityPlayer playerIn){
                    return true;
                }
            }, accessor, stack.getDisplayName());
        default:
            throw new IllegalStateException("No Gui for gui id: " + ID);
    }
}
 
Example 10
Source File: MetaTileEntityTransformer.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean onRightClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing, CuboidRayTraceResult hitResult) {
    ItemStack itemStack = playerIn.getHeldItem(hand);
    if(!itemStack.isEmpty() && itemStack.hasCapability(GregtechCapabilities.CAPABILITY_MALLET, null)) {
        ISoftHammerItem softHammerItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_MALLET, null);

        if (getWorld().isRemote) {
            return true;
        }
        if(!softHammerItem.damageItem(DamageValues.DAMAGE_FOR_SOFT_HAMMER, false)) {
            return false;
        }

        if (isTransformUp) {
            setTransformUp(false);
            playerIn.sendMessage(new TextComponentTranslation("gregtech.machine.transformer.message_transform_down",
                energyContainer.getInputVoltage(), energyContainer.getInputAmperage(), energyContainer.getOutputVoltage(), energyContainer.getOutputAmperage()));
            return true;
        } else {
            setTransformUp(true);
            playerIn.sendMessage(new TextComponentTranslation("gregtech.machine.transformer.message_transform_up",
                energyContainer.getInputVoltage(), energyContainer.getInputAmperage(), energyContainer.getOutputVoltage(), energyContainer.getOutputAmperage()));
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: MetaItem.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Attempts to get an electric item variant with override of max charge
 *
 * @param maxCharge new max charge of this electric item
 * @return item stack with given max charge
 * @throws java.lang.IllegalStateException if this item is not electric item or uses custom implementation
 */
public ItemStack getMaxChargeOverrideStack(long maxCharge) {
    ItemStack itemStack = getStackForm(1);
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if (electricItem == null) {
        throw new IllegalStateException("Not an electric item.");
    }
    if (!(electricItem instanceof ElectricItem)) {
        throw new IllegalStateException("Only standard ElectricItem implementation supported, but this item uses " + electricItem.getClass());
    }
    ((ElectricItem) electricItem).setMaxChargeOverride(maxCharge);
    return itemStack;
}
 
Example 12
Source File: ToolChainsawMV.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getBrokenStack(ItemStack stack) {
    IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    return MetaItems.POWER_UNIT_MV.getChargedStackWithOverride(electricItem);
}
 
Example 13
Source File: ToolJackHammer.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getBrokenStack(ItemStack stack) {
    IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    return MetaItems.JACKHAMMER_BASE.getChargedStackWithOverride(electricItem);
}
 
Example 14
Source File: ToolWrenchMV.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getBrokenStack(ItemStack stack) {
    IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    return MetaItems.POWER_UNIT_MV.getChargedStackWithOverride(electricItem);
}
 
Example 15
Source File: ToolDrillMV.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getBrokenStack(ItemStack stack) {
    IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    return MetaItems.POWER_UNIT_MV.getChargedStackWithOverride(electricItem);
}
 
Example 16
Source File: ItemSpaceChest.java    From AdvancedRocketry with MIT License 4 votes vote down vote up
/**
 * Increments air in the suit by amt
 * @param stack the item stack to operate on
 * @param amt amount of air by which to decrement
 * @return The amount of air inserted into the suit
 */
@Override
public int increment(ItemStack stack, int amt) {

	if(stack.hasTagCompound()) {
		EmbeddedInventory inv = new EmbeddedInventory(getNumSlots(stack));
		inv.readFromNBT(stack.getTagCompound());
		List<ItemStack> list = new LinkedList<ItemStack>();

		for(int i = 0; i < inv.getSizeInventory(); i++) {
			if(!inv.getStackInSlot(i).isEmpty()) {
				
				if( i < 2 && inv.getStackInSlot(i).hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, EnumFacing.UP)) {
					list.add(inv.getStackInSlot(i));
				}
				else if(FluidUtils.containsFluid(inv.getStackInSlot(i))) {
					
					FluidStack fstack = FluidUtils.getFluidForItem(inv.getStackInSlot(i));
					if(fstack != null && FluidUtils.areFluidsSameType(fstack.getFluid(), AdvancedRocketryFluids.fluidOxygen))
						list.add(inv.getStackInSlot(i));
				}
				
			}
		}


		int amtDrained = amt;
		//At this point the list contains ONLY capable items
		for(ItemStack component : list) {
				IFluidHandlerItem fHandler = component.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, EnumFacing.UP);
				FluidStack fluidStack = fHandler.getTankProperties()[0].getContents();

				if(fluidStack == null || FluidUtils.areFluidsSameType(fluidStack.getFluid(), AdvancedRocketryFluids.fluidOxygen))
					amtDrained -= fHandler.fill(new FluidStack(AdvancedRocketryFluids.fluidOxygen, amtDrained), true);

				if(amtDrained == 0)
					break;
			
		}

		saveEmbeddedInventory(stack, inv);

		return amt - amtDrained;
	}

	return 0;

	/*NBTTagCompound nbt;
	if(stack.hasTagCompound()) {
		nbt = stack.getTagCompound();
	}
	else {
		nbt = new NBTTagCompound();
	}

	int prevAmt = nbt.getInteger("air");
	int newAmt = Math.min(prevAmt + amt, getMaxAir());
	nbt.setInteger("air", newAmt);
	stack.setTagCompound(nbt);

	return newAmt - prevAmt;*/
}
 
Example 17
Source File: ToolChainsawLV.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public ItemStack getBrokenStack(ItemStack stack) {
    IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    return MetaItems.POWER_UNIT_LV.getChargedStackWithOverride(electricItem);
}
 
Example 18
Source File: IPearlBelt.java    From Wizardry with GNU Lesser General Public License v3.0 4 votes vote down vote up
default IItemHandler getBeltPearls(ItemStack stack) {
	return stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
}
 
Example 19
Source File: ItemRelayWire.java    From Valkyrien-Skies with Apache License 2.0 4 votes vote down vote up
@Override
public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos,
    EnumHand hand,
    EnumFacing facing, float hitX, float hitY, float hitZ) {
    IBlockState clickedState = worldIn.getBlockState(pos);
    Block block = clickedState.getBlock();
    TileEntity currentTile = worldIn.getTileEntity(pos);
    ItemStack stack = player.getHeldItem(hand);

    if (currentTile instanceof IVSNodeProvider && !worldIn.isRemote) {
        ICapabilityLastRelay inst = stack
            .getCapability(ValkyrienSkiesControl.lastRelayCapability, null);
        if (inst != null) {
            if (!inst.hasLastRelay()) {
                inst.setLastRelay(pos);
                // Draw a wire in the player's hand after this
            } else {
                BlockPos lastPos = inst.getLastRelay();
                double distanceSq = lastPos.distanceSq(pos);
                TileEntity lastPosTile = worldIn.getTileEntity(lastPos);
                // System.out.println(lastPos.toString());

                if (!lastPos.equals(pos) && lastPosTile != null && currentTile != null) {
                    if (distanceSq < VSConfig.relayWireLength * VSConfig.relayWireLength) {
                        IVSNode lastPosNode = ((IVSNodeProvider) lastPosTile).getNode();
                        IVSNode currentPosNode = ((IVSNodeProvider) currentTile).getNode();
                        if (lastPosNode != null && currentPosNode != null) {
                            if (currentPosNode.isLinkedToNode(lastPosNode)) {
                                player.sendMessage(
                                    new TextComponentString("These nodes are already linked!"));
                            } else if (currentPosNode.canLinkToOtherNode(lastPosNode)) {
                                currentPosNode.makeConnection(lastPosNode);
                                stack.damageItem(1, player);
                            } else {
                                // Tell the player what they did wrong
                                player.sendMessage(new TextComponentString(TextFormatting.RED +
                                    I18n.format("message.vs_control.error_relay_wire_limit", VSConfig.networkRelayLimit)));
                            }
                            inst.setLastRelay(null);
                        }
                    } else {
                        player.sendMessage(
                            new TextComponentString(TextFormatting.RED +
                                I18n.format("message.vs_control.error_relay_wire_length")));
                        inst.setLastRelay(null);
                    }
                } else {
                    inst.setLastRelay(pos);
                }
            }
        }
    }

    if (currentTile instanceof IVSNodeProvider) {
        return EnumActionResult.SUCCESS;
    }

    return EnumActionResult.PASS;
}
 
Example 20
Source File: RecipeMapFluidCanner.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
public Recipe findRecipe(long voltage, List<ItemStack> inputs, List<FluidStack> fluidInputs, int outputFluidTankCapacity) {
    Recipe recipe = super.findRecipe(voltage, inputs, fluidInputs, outputFluidTankCapacity);
    if (inputs.size() == 0 || inputs.get(0).isEmpty() || recipe != null)
        return recipe;

    // Fail early if input isn't a fluid container
    if (!inputs.get(0).hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null))
        return null;

    // Make a copy to use for creating recipes
    ItemStack inputStack = inputs.get(0).copy();
    inputStack.setCount(1);

    // Make another copy to use for draining and filling
    ItemStack fluidHandlerItemStack = inputStack.copy();
    IFluidHandlerItem fluidHandlerItem = fluidHandlerItemStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null);
    if (fluidHandlerItem == null)
        return null;

    FluidStack containerFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, true);
    if (containerFluid != null) {
        //if we actually drained something, then it's draining recipe
        return recipeBuilder()
            //we can reuse recipe as long as input container stack fully matches our one
            .inputs(new CountableIngredient(new NBTIngredient(inputStack), 1))
            .outputs(fluidHandlerItem.getContainer())
            .fluidOutputs(containerFluid)
            .duration(Math.max(16, containerFluid.amount / 64)).EUt(4)
            .build().getResult();
    }

    //if we didn't drain anything, try filling container
    if (!fluidInputs.isEmpty() && fluidInputs.get(0) != null) {
        FluidStack inputFluid = fluidInputs.get(0).copy();
        inputFluid.amount = fluidHandlerItem.fill(inputFluid, true);
        if (inputFluid.amount > 0) {
            return recipeBuilder()
                //we can reuse recipe as long as input container stack fully matches our one
                .inputs(new CountableIngredient(new NBTIngredient(inputStack), 1))
                .fluidInputs(inputFluid)
                .outputs(fluidHandlerItem.getContainer())
                .duration(Math.max(16, inputFluid.amount / 64)).EUt(4)
                .build().getResult();
        }
    }
    return null;
}