Java Code Examples for net.minecraftforge.fluids.capability.IFluidHandler#drain()

The following examples show how to use net.minecraftforge.fluids.capability.IFluidHandler#drain() . 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: MetaTileEntityPump.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void tryPumpFirstBlock() {
    BlockPos fluidBlockPos = fluidSourceBlocks.poll();
    if (fluidBlockPos == null) return;
    IBlockState blockHere = getWorld().getBlockState(fluidBlockPos);
    if (blockHere.getBlock() instanceof BlockLiquid ||
        blockHere.getBlock() instanceof IFluidBlock) {
        IFluidHandler fluidHandler = FluidUtil.getFluidHandler(getWorld(), fluidBlockPos, null);
        FluidStack drainStack = fluidHandler.drain(Integer.MAX_VALUE, false);
        if (drainStack != null && exportFluids.fill(drainStack, false) == drainStack.amount) {
            exportFluids.fill(drainStack, true);
            fluidHandler.drain(drainStack.amount, true);
            this.fluidSourceBlocks.remove(fluidBlockPos);
            energyContainer.changeEnergy(-GTValues.V[getTier()]);
        }
    }
}
 
Example 2
Source File: CoverPump.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static int moveHandlerFluids(IFluidHandler sourceHandler, IFluidHandler destHandler, int transferLimit, Predicate<FluidStack> fluidFilter) {
    int fluidLeftToTransfer = transferLimit;
    for (IFluidTankProperties tankProperties : sourceHandler.getTankProperties()) {
        FluidStack currentFluid = tankProperties.getContents();
        if (currentFluid == null || currentFluid.amount == 0 || !fluidFilter.test(currentFluid)) continue;
        currentFluid.amount = fluidLeftToTransfer;
        FluidStack fluidStack = sourceHandler.drain(currentFluid, false);
        if (fluidStack == null || fluidStack.amount == 0) continue;
        int canInsertAmount = destHandler.fill(fluidStack, false);
        if (canInsertAmount > 0) {
            fluidStack.amount = canInsertAmount;
            fluidStack = sourceHandler.drain(fluidStack, true);
            if (fluidStack != null && fluidStack.amount > 0) {
                destHandler.fill(fluidStack, true);

                fluidLeftToTransfer -= fluidStack.amount;
                if (fluidLeftToTransfer == 0) break;
            }
        }
    }
    return transferLimit - fluidLeftToTransfer;
}
 
Example 3
Source File: TileEntityEnderFurnace.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Uses one dose (1000 mB) of fluid fuel, returns the amount of burn time that was gained from it.
 * @param stack
 * @return burn time gained, in ticks
 */
private static int consumeFluidFuelDosage(ItemStack stack)
{
    if (itemContainsFluidFuel(stack) == false)
    {
        return 0;
    }

    // All the null checks happened already in itemContainsFluidFuel()
    IFluidHandler handler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);

    // Consume max 1000 mB per use.
    FluidStack fluidStack = handler.drain(new FluidStack(FluidRegistry.LAVA, Fluid.BUCKET_VOLUME), true);

    //System.out.printf("consumeFluidFuelDosageFluidCapability: %s - %d\n", (fluidStack != null ? fluidStack.getFluid().getName() : "null"), fluidStack != null ? fluidStack.amount : 0);
    // 1.5 times vanilla lava fuel value (150 items per bucket)
    return fluidStack != null ? (fluidStack.amount * 15 * COOKTIME_DEFAULT / 100) : 0;
}
 
Example 4
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 5
Source File: SingleFluidBucketFillHandler.java    From OpenModsLib with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGH)
public void onBucketFill(FillBucketEvent evt) {
	if (evt.getResult() != Result.DEFAULT) return;

	if (evt.getEmptyBucket().getItem() != EMPTY_BUCKET) return;

	final RayTraceResult target = evt.getTarget();
	if (target == null || target.typeOfHit != RayTraceResult.Type.BLOCK) return;

	final TileEntity te = evt.getWorld().getTileEntity(target.getBlockPos());
	if (te == null) return;

	if (te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, target.sideHit)) {
		final IFluidHandler source = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, target.sideHit);

		final FluidStack drained = source.drain(containedFluid, false);
		if (containedFluid.isFluidStackIdentical(drained)) {
			source.drain(containedFluid, true);
			evt.setFilledBucket(filledBucket.copy());
			evt.setResult(Result.ALLOW);
		}
	}
}
 
Example 6
Source File: GenericTank.java    From OpenModsLib with MIT License 6 votes vote down vote up
private int fillInternal(World world, BlockPos coord, EnumFacing side, int maxDrain) {
	final TileEntity otherTank = BlockUtils.getTileInDirection(world, coord, side);

	final EnumFacing drainSide = side.getOpposite();
	final IFluidHandler handler = CompatibilityUtils.getFluidHandler(otherTank, drainSide);

	if (handler != null) {
		final FluidStack drained = handler.drain(maxDrain, false);
		if (drained != null && filter.canAcceptFluid(drained)) {
			final int filled = fill(drained, true);
			if (filled > 0) {
				handler.drain(filled, true);
				return filled;
			}
		}
	}

	return 0;
}
 
Example 7
Source File: MetaTileEntityPump.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkFluidBlockAt(BlockPos pumpHeadPos, BlockPos checkPos) {
    IBlockState blockHere = getWorld().getBlockState(checkPos);
    boolean shouldCheckNeighbours = isStraightInPumpRange(checkPos);

    if (blockHere.getBlock() instanceof BlockLiquid ||
        blockHere.getBlock() instanceof IFluidBlock) {
        IFluidHandler fluidHandler = FluidUtil.getFluidHandler(getWorld(), checkPos, null);
        FluidStack drainStack = fluidHandler.drain(Integer.MAX_VALUE, false);
        if (drainStack != null && drainStack.amount > 0) {
            this.fluidSourceBlocks.add(checkPos);
        }
        shouldCheckNeighbours = true;
    }

    if (shouldCheckNeighbours) {
        int maxPumpRange = getMaxPumpRange();
        for (EnumFacing facing : EnumFacing.VALUES) {
            BlockPos offsetPos = checkPos.offset(facing);
            if (offsetPos.distanceSq(pumpHeadPos) > maxPumpRange * maxPumpRange)
                continue; //do not add blocks outside bounds
            if (!fluidSourceBlocks.contains(offsetPos) &&
                !blocksToCheck.contains(offsetPos)) {
                this.blocksToCheck.add(offsetPos);
            }
        }
    }
}
 
Example 8
Source File: PlungerBehaviour.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) {
    TileEntity tileEntity = world.getTileEntity(pos);
    if (tileEntity == null) {
        return EnumActionResult.PASS;
    }
    IFluidHandler fluidHandler = tileEntity.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side);
    if (fluidHandler == null) {
        return EnumActionResult.PASS;
    }
    ItemStack toolStack = player.getHeldItem(hand);
    boolean isShiftClick = player.isSneaking();
    IFluidHandler handlerToRemoveFrom = isShiftClick ?
        (fluidHandler instanceof FluidHandlerProxy ? ((FluidHandlerProxy) fluidHandler).input : null) :
        (fluidHandler instanceof FluidHandlerProxy ? ((FluidHandlerProxy) fluidHandler).output : fluidHandler);

    if (handlerToRemoveFrom != null && GTUtility.doDamageItem(toolStack, cost, false)) {
        if (!world.isRemote) {
            FluidStack drainStack = handlerToRemoveFrom.drain(1000, true);
            int amountOfFluid = drainStack == null ? 0 : drainStack.amount;
            if (amountOfFluid > 0) {
                player.playSound(SoundEvents.ENTITY_SLIME_SQUISH, 1.0f, amountOfFluid / 1000.0f);
            }
        }
        return EnumActionResult.SUCCESS;
    }
    return EnumActionResult.PASS;
}
 
Example 9
Source File: TileEnderTank.java    From EnderStorage with MIT License 5 votes vote down vote up
private void ejectLiquid() {
    IFluidHandler source = getStorage();
    for (Direction side : Direction.BY_INDEX) {
        IFluidHandler dest = capCache.getCapabilityOr(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side, EmptyFluidHandler.INSTANCE);
        FluidStack drain = source.drain(100, IFluidHandler.FluidAction.SIMULATE);
        if (!drain.isEmpty()) {
            int qty = dest.fill(drain, IFluidHandler.FluidAction.EXECUTE);
            if (qty > 0) {
                source.drain(qty, IFluidHandler.FluidAction.EXECUTE);
            }
        }
    }
}
 
Example 10
Source File: TileFluidTank.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@Override
public FluidStack drain(int maxDrain, boolean doDrain) {
	IFluidHandler handler = this.getFluidTankInDirection(EnumFacing.UP);

	FluidStack stack = null;
	if(handler != null && handler.getTankProperties()[0].getContents() != null && 
			fluidTank.getFluid() != null && fluidTank.getFluid().getFluid() ==
			handler.getTankProperties()[0].getContents().getFluid()) {

		stack = handler.drain(maxDrain, doDrain);
	}
	if(stack != null)
		return stack;

	FluidStack stack2 = super.drain(maxDrain - (stack != null ? stack.amount : 0), doDrain);

	if(stack != null && stack2 != null)
		stack2.amount += stack.amount;

	
	if(stack2 != null && doDrain) {
		fluidChanged = true;
	}
	checkForUpdate();
	
	
	return stack2;
}
 
Example 11
Source File: TileRocketFluidLoader.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@Override
public void update() {
	//Move a stack of items
	if(!world.isRemote && rocket != null) {

		boolean isAllowToOperate = (inputstate == RedstoneState.OFF || isStateActive(inputstate, getStrongPowerForSides(world, getPos())));

		List<TileEntity> tiles = rocket.storage.getFluidTiles();
		boolean rocketContainsItems = false;

		//Function returns if something can be moved
		for(TileEntity tile : tiles) {
			IFluidHandler handler = (IFluidHandler)tile;

			//See if we have anything to fill because redstone output
			FluidStack stack = handler.drain(1, false);
			if(stack == null || handler.fill(stack, false) > 0)
				rocketContainsItems = true;

			if(isAllowToOperate) {
				stack = fluidTank.drain(fluidTank.getCapacity(), false);
				if(stack != null && stack.amount > 0)
					fluidTank.drain(handler.fill(stack, true), true);
			}
		}

		//Update redstone state
		setRedstoneState(!rocketContainsItems);

	}
}
 
Example 12
Source File: TileRocketFluidUnloader.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@Override
public void update() {

	//Move a stack of items
	if( !world.isRemote && rocket != null ) {

		boolean isAllowToOperate = (inputstate == RedstoneState.OFF || isStateActive(inputstate, getStrongPowerForSides(world, getPos())));

		List<TileEntity> tiles = rocket.storage.getFluidTiles();
		boolean rocketContainsItems = false;
		//Function returns if something can be moved
		for(TileEntity tile : tiles) {
			IFluidHandler handler = (IFluidHandler)tile;

			if(handler.drain( 1, false) != null)
				rocketContainsItems = true;

			if(isAllowToOperate) {
				FluidStack stack = fluidTank.getFluid();
				if(stack == null) {
					this.fill(handler.drain(fluidTank.getCapacity(), true), true);
				}
				else {
					stack = stack.copy();
					stack.amount = fluidTank.getCapacity() - fluidTank.getFluidAmount();

					if(stack.amount != 0) {
						this.fill(handler.drain( stack, true), true);
					}
				}
			}
		}

		//Update redstone state
		setRedstoneState(!rocketContainsItems);

	}
}
 
Example 13
Source File: TileRollingMachine.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@Override
public boolean canProcessRecipe(IRecipe recipe) {
	if(!fluidInPorts.isEmpty()) {
		IFluidHandler fluidHandler = fluidInPorts.get(0);
		FluidStack fluid;
		if(fluidHandler == null || (fluid = fluidHandler.drain(new FluidStack(FluidRegistry.WATER, 100), false)) == null 
				|| fluid.amount != 100)
			return false;
	}

	return super.canProcessRecipe(recipe);
}
 
Example 14
Source File: ItemEnderBucket.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public FluidStack getFluid(ItemStack stack, @Nullable EntityPlayer player)
{
    NBTTagCompound nbt = stack.getTagCompound();

    if (nbt == null)
    {
        return null;
    }

    // The Bucket has been linked to a tank
    if (LinkMode.fromStack(stack) == LinkMode.ENABLED)
    {
        if (OwnerData.canAccessSelectedModule(stack, ModuleType.TYPE_LINKCRYSTAL, player) == false)
        {
            return null;
        }

        IFluidHandler handler = this.getLinkedTank(stack);

        if (handler != null)
        {
            FluidStack fluidStack = handler.drain(Integer.MAX_VALUE, false);

            // Cache the fluid stack into the link crystal's NBT for easier/faster access for tooltip and rendering stuffs
            this.cacheFluid(stack, fluidStack);

            return fluidStack;
        }

        return null;
    }

    // Not linked to a tank, get the internal FluidStack
    if (nbt.hasKey("Fluid", Constants.NBT.TAG_COMPOUND))
    {
        return FluidStack.loadFluidStackFromNBT(nbt.getCompoundTag("Fluid"));
    }

    return null;
}
 
Example 15
Source File: ContainerBucketFillHandler.java    From OpenModsLib with MIT License 5 votes vote down vote up
@SubscribeEvent
public void onBucketFill(FillBucketEvent evt) {
	if (evt.getResult() != Result.DEFAULT) return;

	if (evt.getEmptyBucket().getItem() != EMPTY_BUCKET) return;

	final RayTraceResult target = evt.getTarget();
	if (target == null || target.typeOfHit != RayTraceResult.Type.BLOCK) return;

	final TileEntity te = evt.getWorld().getTileEntity(target.getBlockPos());
	if (te == null) return;

	if (!canFill(evt.getWorld(), target.getBlockPos(), te)) { return; }

	if (te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, target.sideHit)) {
		final IFluidHandler source = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, target.sideHit);

		final FluidStack fluidInContainer = source.drain(Fluid.BUCKET_VOLUME, false);

		if (fluidInContainer != null) {
			final ItemStack filledBucket = getFilledBucket(fluidInContainer);
			if (!filledBucket.isEmpty()) {
				final IFluidHandlerItem container = FluidUtil.getFluidHandler(filledBucket);
				if (container != null) {
					final FluidStack fluidInBucket = container.drain(Integer.MAX_VALUE, false);
					if (fluidInBucket != null && fluidInBucket.isFluidStackIdentical(source.drain(fluidInBucket, false))) {
						source.drain(fluidInBucket, true);
						evt.setFilledBucket(filledBucket.copy());
						evt.setResult(Result.ALLOW);
					}
				}
			}
		}
	}
}
 
Example 16
Source File: ItemEnderBucket.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
public int getCapacity(ItemStack stack, @Nullable EntityPlayer player)
{
    if (LinkMode.fromStack(stack) == LinkMode.DISABLED)
    {
        return Configs.enderBucketCapacity;
    }

    // Linked to a tank

    if (OwnerData.canAccessSelectedModule(stack, ModuleType.TYPE_LINKCRYSTAL, player) == false)
    {
        return 0;
    }

    TargetData targetData = this.getLinkedTankTargetData(stack);
    IFluidHandler handler = this.getLinkedTank(stack);

    if (targetData != null && handler != null)
    {
        IFluidTankProperties[] tank = handler.getTankProperties();

        // If we have tank info, it is the easiest and simplest way to get the tank capacity
        if (tank != null && tank.length > 0 && tank[0] != null)
        {
            return tank[0].getCapacity();
        }

        // No tank info available, get the capacity via simulating filling

        FluidStack fluidStack = handler.drain(Integer.MAX_VALUE, false);

        // Tank has fluid
        if (fluidStack != null)
        {
            FluidStack fs = fluidStack.copy();
            fs.amount = Integer.MAX_VALUE;

            // Filled amount plus existing amount
            return handler.fill(fs, false) + fluidStack.amount;
        }
        // Tank has no fluid
        else
        {
            // Since we have no fluid stored, get the capacity via simulating filling water into the tank
            return handler.fill(new FluidStack(FluidRegistry.WATER, Integer.MAX_VALUE), false);
        }
    }

    return 0;
}