Search in sources :

Example 31 with IEnergyContainer

use of mekanism.api.energy.IEnergyContainer in project Mekanism by mekanism.

the class ItemElectricBow method releaseUsing.

@Override
public void releaseUsing(@Nonnull ItemStack stack, @Nonnull World world, @Nonnull LivingEntity entityLiving, int timeLeft) {
    if (entityLiving instanceof PlayerEntity) {
        PlayerEntity player = (PlayerEntity) entityLiving;
        // Vanilla diff - Get the energy container, because if something went wrong, and we don't have one then we can exit early
        IEnergyContainer energyContainer = null;
        boolean fireState = getFireState(stack);
        if (!player.isCreative()) {
            energyContainer = StorageUtils.getEnergyContainer(stack, 0);
            FloatingLong energyNeeded = fireState ? MekanismConfig.gear.electricBowEnergyUsageFire.get() : MekanismConfig.gear.electricBowEnergyUsage.get();
            if (energyContainer == null || energyContainer.extract(energyNeeded, Action.SIMULATE, AutomationType.MANUAL).smallerThan(energyNeeded)) {
                return;
            }
        }
        boolean infinity = player.isCreative() || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.INFINITY_ARROWS, stack) > 0;
        ItemStack ammo = player.getProjectile(stack);
        int charge = ForgeEventFactory.onArrowLoose(stack, world, player, getUseDuration(stack) - timeLeft, !ammo.isEmpty() || infinity);
        if (charge < 0) {
            return;
        }
        if (!ammo.isEmpty() || infinity) {
            float velocity = getPowerForTime(charge);
            if (velocity < 0.1) {
                return;
            }
            if (ammo.isEmpty()) {
                ammo = new ItemStack(Items.ARROW);
            }
            boolean noConsume = player.isCreative() || (ammo.getItem() instanceof ArrowItem && ((ArrowItem) ammo.getItem()).isInfinite(ammo, stack, player));
            if (!world.isClientSide) {
                ArrowItem arrowitem = (ArrowItem) (ammo.getItem() instanceof ArrowItem ? ammo.getItem() : Items.ARROW);
                AbstractArrowEntity arrowEntity = arrowitem.createArrow(world, ammo, player);
                arrowEntity = customArrow(arrowEntity);
                arrowEntity.shootFromRotation(player, player.xRot, player.yRot, 0, 3 * velocity, 1);
                if (velocity == 1) {
                    arrowEntity.setCritArrow(true);
                }
                int power = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.POWER_ARROWS, stack);
                if (power > 0) {
                    arrowEntity.setBaseDamage(arrowEntity.getBaseDamage() + 0.5 * power + 0.5);
                }
                int punch = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.PUNCH_ARROWS, stack);
                if (punch > 0) {
                    arrowEntity.setKnockback(punch);
                }
                // Vanilla diff - set it on fire if the bow's mode is set to fire, even if there is no flame enchantment
                if (fireState || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.FLAMING_ARROWS, stack) > 0) {
                    arrowEntity.setSecondsOnFire(100);
                }
                // Vanilla diff - Instead of damaging the item we remove energy from it
                if (!player.isCreative() && energyContainer != null) {
                    energyContainer.extract(fireState ? MekanismConfig.gear.electricBowEnergyUsageFire.get() : MekanismConfig.gear.electricBowEnergyUsage.get(), Action.EXECUTE, AutomationType.MANUAL);
                }
                if (noConsume || player.isCreative() && (ammo.getItem() == Items.SPECTRAL_ARROW || ammo.getItem() == Items.TIPPED_ARROW)) {
                    arrowEntity.pickup = AbstractArrowEntity.PickupStatus.CREATIVE_ONLY;
                }
                world.addFreshEntity(arrowEntity);
            }
            world.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.ARROW_SHOOT, SoundCategory.PLAYERS, 1, 1.0F / (random.nextFloat() * 0.4F + 1.2F) + velocity * 0.5F);
            if (!noConsume && !player.isCreative()) {
                ammo.shrink(1);
                if (ammo.isEmpty()) {
                    player.inventory.removeItem(ammo);
                }
            }
            player.awardStat(Stats.ITEM_USED.get(this));
        }
    }
}
Also used : FloatingLong(mekanism.api.math.FloatingLong) IEnergyContainer(mekanism.api.energy.IEnergyContainer) ArrowItem(net.minecraft.item.ArrowItem) ItemStack(net.minecraft.item.ItemStack) PlayerEntity(net.minecraft.entity.player.PlayerEntity) AbstractArrowEntity(net.minecraft.entity.projectile.AbstractArrowEntity)

Example 32 with IEnergyContainer

use of mekanism.api.energy.IEnergyContainer in project Mekanism by mekanism.

the class GuiPortableTeleporter method addGuiElements.

@Override
protected void addGuiElements() {
    super.addGuiElements();
    addButton(new GuiTeleporterStatus(this, () -> getFrequency() != null, menu::getStatus));
    addButton(new GuiVerticalPowerBar(this, new IBarInfoHandler() {

        @Override
        public ITextComponent getTooltip() {
            IEnergyContainer container = StorageUtils.getEnergyContainer(menu.getStack(), 0);
            return container == null ? EnergyDisplay.ZERO.getTextComponent() : EnergyDisplay.of(container).getTextComponent();
        }

        @Override
        public double getLevel() {
            IEnergyContainer container = StorageUtils.getEnergyContainer(menu.getStack(), 0);
            return container == null ? 0 : container.getEnergy().divideToLevel(container.getMaxEnergy());
        }
    }, 158, 26));
    teleportButton = addButton(new TranslationButton(this, 42, 147, 92, 20, MekanismLang.BUTTON_TELEPORT, () -> {
        TeleporterFrequency frequency = getFrequency();
        if (frequency != null && menu.getStatus() == 1) {
            // This should always be true if the teleport button is active, but validate it just in case
            ClientTickHandler.portableTeleport(getMinecraft().player, menu.getHand(), frequency.getIdentity());
            getMinecraft().player.closeContainer();
        } else {
            // If something did go wrong make the teleport button not able to be pressed
            teleportButton.active = false;
        }
    }));
    // Teleporter button starts as deactivated until we have a frequency get synced
    teleportButton.active = false;
    addButton(new GuiFrequencySelector<>(this, 14));
}
Also used : IBarInfoHandler(mekanism.client.gui.element.bar.GuiBar.IBarInfoHandler) IEnergyContainer(mekanism.api.energy.IEnergyContainer) TranslationButton(mekanism.client.gui.element.button.TranslationButton) TeleporterFrequency(mekanism.common.content.teleporter.TeleporterFrequency) GuiTeleporterStatus(mekanism.client.gui.element.custom.GuiTeleporterStatus) GuiVerticalPowerBar(mekanism.client.gui.element.bar.GuiVerticalPowerBar)

Example 33 with IEnergyContainer

use of mekanism.api.energy.IEnergyContainer in project Mekanism by mekanism.

the class ItemConfigurator method useOn.

@Nonnull
@Override
public ActionResultType useOn(ItemUseContext context) {
    PlayerEntity player = context.getPlayer();
    World world = context.getLevel();
    if (!world.isClientSide && player != null) {
        BlockPos pos = context.getClickedPos();
        Direction side = context.getClickedFace();
        ItemStack stack = context.getItemInHand();
        TileEntity tile = WorldUtils.getTileEntity(world, pos);
        ConfiguratorMode mode = getMode(stack);
        if (mode.isConfigurating()) {
            // Configurate
            TransmissionType transmissionType = Objects.requireNonNull(mode.getTransmission(), "Configurating state requires transmission type");
            if (tile instanceof ISideConfiguration && ((ISideConfiguration) tile).getConfig().supports(transmissionType)) {
                ISideConfiguration config = (ISideConfiguration) tile;
                ConfigInfo info = config.getConfig().getConfig(transmissionType);
                if (info != null) {
                    RelativeSide relativeSide = RelativeSide.fromDirections(config.getDirection(), side);
                    DataType dataType = info.getDataType(relativeSide);
                    if (!player.isShiftKeyDown()) {
                        player.sendMessage(MekanismUtils.logFormat(MekanismLang.CONFIGURATOR_VIEW_MODE.translate(transmissionType, dataType.getColor(), dataType, dataType.getColor().getColoredName())), Util.NIL_UUID);
                    } else if (SecurityUtils.canAccess(player, tile)) {
                        if (!player.isCreative()) {
                            IEnergyContainer energyContainer = StorageUtils.getEnergyContainer(stack, 0);
                            FloatingLong energyPerConfigure = MekanismConfig.gear.configuratorEnergyPerConfigure.get();
                            if (energyContainer == null || energyContainer.extract(energyPerConfigure, Action.SIMULATE, AutomationType.MANUAL).smallerThan(energyPerConfigure)) {
                                return ActionResultType.FAIL;
                            }
                            energyContainer.extract(energyPerConfigure, Action.EXECUTE, AutomationType.MANUAL);
                        }
                        DataType old = dataType;
                        dataType = info.incrementDataType(relativeSide);
                        if (dataType != old) {
                            player.sendMessage(MekanismUtils.logFormat(MekanismLang.CONFIGURATOR_TOGGLE_MODE.translate(transmissionType, dataType.getColor(), dataType, dataType.getColor().getColoredName())), Util.NIL_UUID);
                            config.getConfig().sideChanged(transmissionType, relativeSide);
                        }
                    } else {
                        SecurityUtils.displayNoAccess(player);
                    }
                }
                return ActionResultType.SUCCESS;
            }
            if (SecurityUtils.canAccess(player, tile)) {
                Optional<IConfigurable> capability = CapabilityUtils.getCapability(tile, Capabilities.CONFIGURABLE_CAPABILITY, side).resolve();
                if (capability.isPresent()) {
                    IConfigurable config = capability.get();
                    if (player.isShiftKeyDown()) {
                        return config.onSneakRightClick(player, side);
                    }
                    return config.onRightClick(player, side);
                }
            } else {
                SecurityUtils.displayNoAccess(player);
                return ActionResultType.SUCCESS;
            }
        } else if (mode == ConfiguratorMode.EMPTY) {
            // Empty
            if (tile instanceof IMekanismInventory) {
                IMekanismInventory inv = (IMekanismInventory) tile;
                if (inv.hasInventory()) {
                    if (SecurityUtils.canAccess(player, tile)) {
                        boolean creative = player.isCreative();
                        IEnergyContainer energyContainer = creative ? null : StorageUtils.getEnergyContainer(stack, 0);
                        if (!creative && energyContainer == null) {
                            return ActionResultType.FAIL;
                        }
                        // TODO: Switch this to items being handled by TileEntityMekanism, energy handled here (via lambdas?)
                        FloatingLong energyPerItemDump = MekanismConfig.gear.configuratorEnergyPerItem.get();
                        for (IInventorySlot inventorySlot : inv.getInventorySlots(null)) {
                            if (!inventorySlot.isEmpty()) {
                                if (!creative) {
                                    if (energyContainer.extract(energyPerItemDump, Action.SIMULATE, AutomationType.MANUAL).smallerThan(energyPerItemDump)) {
                                        break;
                                    }
                                    energyContainer.extract(energyPerItemDump, Action.EXECUTE, AutomationType.MANUAL);
                                }
                                Block.popResource(world, pos, inventorySlot.getStack().copy());
                                inventorySlot.setEmpty();
                            }
                        }
                        return ActionResultType.SUCCESS;
                    } else {
                        SecurityUtils.displayNoAccess(player);
                        return ActionResultType.FAIL;
                    }
                }
            }
        } else if (mode == ConfiguratorMode.ROTATE) {
            // Rotate
            if (tile instanceof TileEntityMekanism) {
                if (SecurityUtils.canAccess(player, tile)) {
                    TileEntityMekanism tileMekanism = (TileEntityMekanism) tile;
                    if (Attribute.get(tileMekanism.getBlockType(), AttributeStateFacing.class).canRotate()) {
                        if (!player.isShiftKeyDown()) {
                            tileMekanism.setFacing(side);
                        } else if (player.isShiftKeyDown()) {
                            tileMekanism.setFacing(side.getOpposite());
                        }
                    }
                } else {
                    SecurityUtils.displayNoAccess(player);
                }
            }
            return ActionResultType.SUCCESS;
        } else if (mode == ConfiguratorMode.WRENCH) {
            // Wrench
            return ActionResultType.PASS;
        }
    }
    return ActionResultType.PASS;
}
Also used : IInventorySlot(mekanism.api.inventory.IInventorySlot) TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) World(net.minecraft.world.World) ConfigInfo(mekanism.common.tile.component.config.ConfigInfo) Direction(net.minecraft.util.Direction) IConfigurable(mekanism.api.IConfigurable) ConfiguratorMode(mekanism.common.item.ItemConfigurator.ConfiguratorMode) AttributeStateFacing(mekanism.common.block.attribute.AttributeStateFacing) PlayerEntity(net.minecraft.entity.player.PlayerEntity) TileEntity(net.minecraft.tileentity.TileEntity) FloatingLong(mekanism.api.math.FloatingLong) IEnergyContainer(mekanism.api.energy.IEnergyContainer) TransmissionType(mekanism.common.lib.transmitter.TransmissionType) RelativeSide(mekanism.api.RelativeSide) DataType(mekanism.common.tile.component.config.DataType) IMekanismInventory(mekanism.api.inventory.IMekanismInventory) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) ISideConfiguration(mekanism.common.tile.interfaces.ISideConfiguration) Nonnull(javax.annotation.Nonnull)

Example 34 with IEnergyContainer

use of mekanism.api.energy.IEnergyContainer in project Mekanism by mekanism.

the class ItemRobit method useOn.

@Nonnull
@Override
public ActionResultType useOn(ItemUseContext context) {
    PlayerEntity player = context.getPlayer();
    if (player == null) {
        return ActionResultType.PASS;
    }
    World world = context.getLevel();
    BlockPos pos = context.getClickedPos();
    TileEntityMekanism chargepad = WorldUtils.getTileEntity(TileEntityChargepad.class, world, pos);
    if (chargepad != null) {
        if (!chargepad.getActive()) {
            if (!world.isClientSide) {
                ItemStack stack = context.getItemInHand();
                EntityRobit robit = EntityRobit.create(world, pos.getX() + 0.5, pos.getY() + 0.1, pos.getZ() + 0.5);
                if (robit == null) {
                    return ActionResultType.FAIL;
                }
                robit.setHome(chargepad.getTileCoord());
                IEnergyContainer energyContainer = StorageUtils.getEnergyContainer(stack, 0);
                if (energyContainer != null) {
                    robit.getEnergyContainer().setEnergy(energyContainer.getEnergy());
                }
                UUID ownerUUID = getOwnerUUID(stack);
                if (ownerUUID == null) {
                    robit.setOwnerUUID(player.getUUID());
                    // If the robit doesn't already have an owner, make sure we portray this
                    Mekanism.packetHandler.sendToAll(new PacketSecurityUpdate(player.getUUID(), null));
                } else {
                    robit.setOwnerUUID(ownerUUID);
                }
                robit.setInventory(getInventory(stack));
                robit.setCustomName(getRobitName(stack));
                robit.setSecurityMode(getSecurity(stack));
                robit.setSkin(getRobitSkin(stack), player);
                world.addFreshEntity(robit);
                stack.shrink(1);
            }
            return ActionResultType.SUCCESS;
        }
    }
    return ActionResultType.PASS;
}
Also used : TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) IEnergyContainer(mekanism.api.energy.IEnergyContainer) EntityRobit(mekanism.common.entity.EntityRobit) BlockPos(net.minecraft.util.math.BlockPos) World(net.minecraft.world.World) ItemStack(net.minecraft.item.ItemStack) UUID(java.util.UUID) PacketSecurityUpdate(mekanism.common.network.to_client.PacketSecurityUpdate) PlayerEntity(net.minecraft.entity.player.PlayerEntity) Nonnull(javax.annotation.Nonnull)

Aggregations

IEnergyContainer (mekanism.api.energy.IEnergyContainer)34 FloatingLong (mekanism.api.math.FloatingLong)26 BlockPos (net.minecraft.util.math.BlockPos)13 PlayerEntity (net.minecraft.entity.player.PlayerEntity)12 ItemStack (net.minecraft.item.ItemStack)12 Nonnull (javax.annotation.Nonnull)10 Direction (net.minecraft.util.Direction)8 World (net.minecraft.world.World)8 BlockState (net.minecraft.block.BlockState)6 ServerPlayerEntity (net.minecraft.entity.player.ServerPlayerEntity)6 ArrayList (java.util.ArrayList)5 List (java.util.List)4 Map (java.util.Map)4 Nullable (javax.annotation.Nullable)4 TileEntityMekanism (mekanism.common.tile.base.TileEntityMekanism)4 TileEntity (net.minecraft.tileentity.TileEntity)4 SyncableFloatingLong (mekanism.common.inventory.container.sync.SyncableFloatingLong)3 EnumMap (java.util.EnumMap)2 HashMap (java.util.HashMap)2 Set (java.util.Set)2