Search in sources :

Example 1 with Items

use of net.minecraft.world.item.Items in project MinecraftForge by MinecraftForge.

the class FluidUtil method interactWithFluidHandler.

/**
 * Used to handle the common case of a player holding a fluid item and right-clicking on a fluid handler.
 * First it tries to fill the item from the handler,
 * if that action fails then it tries to drain the item into the handler.
 * Automatically updates the item in the player's hand and stashes any extra items created.
 *
 * @param player  The player doing the interaction between the item and fluid handler.
 * @param hand    The player's hand that is holding an item that should interact with the fluid handler.
 * @param handler The fluid handler.
 * @return true if the interaction succeeded and updated the item held by the player, false otherwise.
 */
public static boolean interactWithFluidHandler(@Nonnull Player player, @Nonnull InteractionHand hand, @Nonnull IFluidHandler handler) {
    Preconditions.checkNotNull(player);
    Preconditions.checkNotNull(hand);
    Preconditions.checkNotNull(handler);
    ItemStack heldItem = player.getItemInHand(hand);
    if (!heldItem.isEmpty()) {
        return player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).map(playerInventory -> {
            FluidActionResult fluidActionResult = tryFillContainerAndStow(heldItem, handler, playerInventory, Integer.MAX_VALUE, player, true);
            if (!fluidActionResult.isSuccess()) {
                fluidActionResult = tryEmptyContainerAndStow(heldItem, handler, playerInventory, Integer.MAX_VALUE, player, true);
            }
            if (fluidActionResult.isSuccess()) {
                player.setItemInHand(hand, fluidActionResult.getResult());
                return true;
            }
            return false;
        }).orElse(false);
    }
    return false;
}
Also used : SoundSource(net.minecraft.sounds.SoundSource) IItemHandler(net.minecraftforge.items.IItemHandler) Items(net.minecraft.world.item.Items) FluidBlockWrapper(net.minecraftforge.fluids.capability.wrappers.FluidBlockWrapper) BucketPickup(net.minecraft.world.level.block.BucketPickup) LiquidBlockContainer(net.minecraft.world.level.block.LiquidBlockContainer) Direction(net.minecraft.core.Direction) BlockState(net.minecraft.world.level.block.state.BlockState) BlockWrapper(net.minecraftforge.fluids.capability.wrappers.BlockWrapper) LazyOptional(net.minecraftforge.common.util.LazyOptional) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Fluid(net.minecraft.world.level.material.Fluid) Fluids(net.minecraft.world.level.material.Fluids) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) IFluidHandler(net.minecraftforge.fluids.capability.IFluidHandler) CapabilityFluidHandler(net.minecraftforge.fluids.capability.CapabilityFluidHandler) BlockHitResult(net.minecraft.world.phys.BlockHitResult) BlockEntity(net.minecraft.world.level.block.entity.BlockEntity) BucketPickupHandlerWrapper(net.minecraftforge.fluids.capability.wrappers.BucketPickupHandlerWrapper) Material(net.minecraft.world.level.material.Material) Player(net.minecraft.world.entity.player.Player) BlockPos(net.minecraft.core.BlockPos) Vec3(net.minecraft.world.phys.Vec3) SoundEvent(net.minecraft.sounds.SoundEvent) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) IFluidHandlerItem(net.minecraftforge.fluids.capability.IFluidHandlerItem) BlockPlaceContext(net.minecraft.world.item.context.BlockPlaceContext) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Block(net.minecraft.world.level.block.Block) BucketItem(net.minecraft.world.item.BucketItem) ItemStack(net.minecraft.world.item.ItemStack) InteractionHand(net.minecraft.world.InteractionHand) Level(net.minecraft.world.level.Level) ItemStack(net.minecraft.world.item.ItemStack)

Example 2 with Items

use of net.minecraft.world.item.Items in project MinecraftForge by MinecraftForge.

the class LazyCapabilitiesOnItemsTest method onCommonSetup.

private void onCommonSetup(FMLCommonSetupEvent event) {
    try {
        final Field supportsFlagField = CapabilityProvider.class.getDeclaredField("SUPPORTS_LAZY_CAPABILITIES");
        supportsFlagField.setAccessible(true);
        supportsFlagField.set(null, false);
        final Stopwatch timer = Stopwatch.createUnstarted();
        final IEventBus bus = MinecraftForge.EVENT_BUS;
        final ResourceLocation testCapId = new ResourceLocation(MOD_ID, "test");
        final Consumer<AttachCapabilitiesEvent<ItemStack>> capAttachmentHandler = e -> {
            // Example capability we make everything a bucket :D
            e.addCapability(testCapId, new FluidHandlerItemStackSimple(e.getObject(), SAMPLE_SIZE));
        };
        // Warmup:
        for (int i = 0; i < (SAMPLE_SIZE); i++) {
            WARMUP_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        // /First test: SAMPLE_SIZE itemstacks which do not have a capability attached.
        timer.start();
        for (int i = 0; i < SAMPLE_SIZE; i++) {
            NO_CAPS_DISABLED_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.stop();
        final long simpleNoCapsLazyDisabledElapsed = timer.elapsed(TimeUnit.MICROSECONDS);
        timer.reset();
        // /Second test: SAMPLE_SIZE itemstacks with a capability attached.
        bus.addGenericListener(ItemStack.class, capAttachmentHandler);
        // Warmup:
        for (int i = 0; i < (SAMPLE_SIZE); i++) {
            WARMUP_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.start();
        for (int i = 0; i < SAMPLE_SIZE; i++) {
            WITH_CAPS_DISABLED_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.stop();
        final long withCapsLazyDisabledElapsed = timer.elapsed(TimeUnit.MICROSECONDS);
        timer.reset();
        bus.unregister(capAttachmentHandler);
        // /Third test: SAMPLE_SIZE itemstacks which do not have a capability attached.
        supportsFlagField.set(null, true);
        // Warmup:
        for (int i = 0; i < (SAMPLE_SIZE); i++) {
            WARMUP_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.start();
        for (int i = 0; i < SAMPLE_SIZE; i++) {
            NO_CAPS_ENABLED_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.stop();
        final long simpleNoCapsLazyEnabledElapsed = timer.elapsed(TimeUnit.MICROSECONDS);
        timer.reset();
        // /Fourth test: SAMPLE_SIZE itemstacks with a capability attached.
        bus.addGenericListener(ItemStack.class, capAttachmentHandler);
        // Warmup:
        for (int i = 0; i < (SAMPLE_SIZE); i++) {
            WARMUP_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.start();
        for (int i = 0; i < SAMPLE_SIZE; i++) {
            WITH_CAPS_ENABLED_RESULTS.add(new ItemStack(Items.WATER_BUCKET));
        }
        timer.stop();
        final long withCapsLazyEnabledElapsed = timer.elapsed(TimeUnit.MICROSECONDS);
        timer.reset();
        bus.unregister(capAttachmentHandler);
        TextTable table = new TextTable(Lists.newArrayList(column("Test type", TextTable.Alignment.LEFT), column("Total time", TextTable.Alignment.CENTER)));
        table.add("Lazy: Disabled / Caps: None", simpleNoCapsLazyDisabledElapsed + " ms.");
        table.add("Lazy: Disabled / Caps: One", withCapsLazyDisabledElapsed + " ms.");
        table.add("Lazy: Enabled  / Caps: None", simpleNoCapsLazyEnabledElapsed + " ms.");
        table.add("Lazy: Enabled  / Caps: One", withCapsLazyEnabledElapsed + " ms.");
        final String[] resultData = table.build("\n").split("\n");
        for (final String line : resultData) {
            LOGGER.warn(line);
        }
    } catch (NoSuchFieldException | IllegalAccessException e) {
        LOGGER.error("Failed to run capabilities on items test!");
        throw new IllegalStateException(e);
    }
}
Also used : ResourceLocation(net.minecraft.resources.ResourceLocation) TextTable(net.minecraftforge.common.util.TextTable) Items(net.minecraft.world.item.Items) FluidHandlerItemStackSimple(net.minecraftforge.fluids.capability.templates.FluidHandlerItemStackSimple) Stopwatch(com.google.common.base.Stopwatch) TextTable.column(net.minecraftforge.common.util.TextTable.column) AttachCapabilitiesEvent(net.minecraftforge.event.AttachCapabilitiesEvent) Field(java.lang.reflect.Field) IEventBus(net.minecraftforge.eventbus.api.IEventBus) ArrayList(java.util.ArrayList) FMLJavaModLoadingContext(net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MinecraftForge(net.minecraftforge.common.MinecraftForge) List(java.util.List) Lists(com.google.common.collect.Lists) FMLCommonSetupEvent(net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent) Logger(org.apache.logging.log4j.Logger) Mod(net.minecraftforge.fml.common.Mod) ItemStack(net.minecraft.world.item.ItemStack) CapabilityProvider(net.minecraftforge.common.capabilities.CapabilityProvider) LogManager(org.apache.logging.log4j.LogManager) Stopwatch(com.google.common.base.Stopwatch) FluidHandlerItemStackSimple(net.minecraftforge.fluids.capability.templates.FluidHandlerItemStackSimple) AttachCapabilitiesEvent(net.minecraftforge.event.AttachCapabilitiesEvent) Field(java.lang.reflect.Field) ResourceLocation(net.minecraft.resources.ResourceLocation) TextTable(net.minecraftforge.common.util.TextTable) ItemStack(net.minecraft.world.item.ItemStack) IEventBus(net.minecraftforge.eventbus.api.IEventBus)

Aggregations

ItemStack (net.minecraft.world.item.ItemStack)2 Items (net.minecraft.world.item.Items)2 Preconditions (com.google.common.base.Preconditions)1 Stopwatch (com.google.common.base.Stopwatch)1 Lists (com.google.common.collect.Lists)1 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Optional (java.util.Optional)1 TimeUnit (java.util.concurrent.TimeUnit)1 Consumer (java.util.function.Consumer)1 Nonnull (javax.annotation.Nonnull)1 Nullable (javax.annotation.Nullable)1 BlockPos (net.minecraft.core.BlockPos)1 Direction (net.minecraft.core.Direction)1 ResourceLocation (net.minecraft.resources.ResourceLocation)1 SoundEvent (net.minecraft.sounds.SoundEvent)1 SoundSource (net.minecraft.sounds.SoundSource)1 InteractionHand (net.minecraft.world.InteractionHand)1 Player (net.minecraft.world.entity.player.Player)1