Jump to content

[1.20.4] player.containerMenu (InventoryMenu or CraftingMenu class) crafting slots item insertion


Recommended Posts

Hi,

Full context, in case of oversight from me: using a @SubscribeEvent for ItemCraftedEvent, I am trying to implement a crafting system for 'carving', where I have tools that are tagged with 'can_carve' and items that are tagged with 'carveable'. A simple example here is a wooden handle item, which I have a recipe that uses a carving tool (I've tagged axes and a custom tool) and  a branch item. I have this working to the degree of recipe functionality, hooking into the crafting event, and even duplicating the event carving tool, then damaging it, before reinserting it into the player's inventory. This is fully functioning.

My subscriber looks like this:

 @SubscribeEvent
    public void itemCrafted(ItemCraftedEvent event) {
        Player player = event.getEntity();
        if (!player.level().isClientSide()) {
            if (new ItemStack(event.getCrafting().getItem(), 1).is(ModTags.Items.CARVED_ITEM)) {
                ItemStack carvingTool = new ItemStack(Blocks.AIR, 1);
                int itemIndex = 0;
                for (int i = 0; i < event.getInventory().getContainerSize(); i++) {
                    ItemStack thisItem = event.getInventory().getItem(i);
                    if (thisItem.is(ModTags.Items.CAN_CARVE)) {
                        carvingTool = thisItem;
                        itemIndex = i;
                        break;
                    }
                }
                ItemStack newTool =  new ItemStack(carvingTool.getItem(), 1); // make copy of tool, ...
                newTool.hurtAndBreak(carvingTool.getDamageValue() + 1, player, entity -> entity.broadcastBreakEvent(EquipmentSlot.MAINHAND)); // ... then damage it, and ...
                player.getInventory().setItem(1, newTool); // reinsert it into the player's inventory (this presently overwrites whatever is in the slot, as this is not the final intended implementation)

                if (player.containerMenu.getClass() == CraftingMenu.class) { // using crafting table:
                    // TODO
                } else if (player.containerMenu.getClass() == InventoryMenu.class) { // using inventory crafting
					// TODO
                }
            }
        }
    }

I have only been developing mods for minecraft for a (relatively) short period (a couple months), and so it is quite possible I have made a 'high level' error i.e., one alternative implementation I have considered is overriding the onCraftedBy() method in a custom item class. I am unsure if this is the most appropriate place in the eventbus to perform this method.

In the code I have provided, you can see the lines where I currently generate the carvingTool, damage it, and then re-insert it into the player's inventory. Under this, I have created a if/else-if block for the two crafting interfaces, as I imagine some nuances exist in the implementation difference. But in essence, I am trying to map the stored itemIndex to the crafting grid, and to insert the newTool instance into the grid at this position.

I have tried a variety of commands commands to attempt this, in no particular order:

// (containerMenu|inventoryMenu) denotes one or the other

// I assume one of these can be used to perform the insertion, but none appear to work:
player.(containerMenu|inventoryMenu).setItem(1, player.inventoryMenu.getStateId(), newTool);
player.(containerMenu|inventoryMenu).getSlot(1).set(newTool);
player.(containerMenu|inventoryMenu).getItems().set(1, newTool);

// I assume a command may be needed to reload the crafting grid contents for the player, but none appear to work:
player.inventoryMenu.getCraftSlots().setItem(0, newTool);
player.(containerMenu|inventoryMenu).broadcastChanges();
player.(containerMenu|inventoryMenu).broadcastFullState();
player.(containerMenu|inventoryMenu).getSlot(1).setChanged();

Hoping to receive guidance on how to achieve this result.

Thanks

Link to comment
Share on other sites

  • 2 weeks later...
Posted (edited)

After much experimentation I finally realised why this doesn't work and how to fix it.
The critical component to understand here, is that ItemCraftedEvent is called before the crafting ingredients are purged from the crafting slots; this all happens in ResultSlot.java's onTake method:

Spoiler
public void onTake(Player p_150638_, ItemStack p_150639_) {
  this.checkTakeAchievements(p_150639_);
  net.minecraftforge.common.ForgeHooks.setCraftingPlayer(p_150638_);
  NonNullList<ItemStack> nonnulllist = p_150638_.level().getRecipeManager().getRemainingItemsFor(RecipeType.CRAFTING, this.craftSlots, p_150638_.level());
  net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null);
  for(int i = 0; i < nonnulllist.size(); ++i) {
    ItemStack itemstack = this.craftSlots.getItem(i);
    ItemStack itemstack1 = nonnulllist.get(i);
    if (!itemstack.isEmpty()) {
      this.craftSlots.removeItem(i, 1);
      itemstack = this.craftSlots.getItem(i);
    }

    if (!itemstack1.isEmpty()) {
      if (itemstack.isEmpty()) {
        this.craftSlots.setItem(i, itemstack1);
      } else if (ItemStack.isSameItemSameTags(itemstack, itemstack1)) {
        itemstack1.grow(itemstack.getCount());
        this.craftSlots.setItem(i, itemstack1);
      } else if (!this.player.getInventory().add(itemstack1)) {
        this.player.drop(itemstack1, false);
      }
    }
  }

}

We can see here the first line fires checkTakeAchievements, this is what fires the ItemCraftedEvent (after a few method calls). Then we can see the purge behaviour. I worked around this by creating a CarverItem class, which uses hasCraftingRemainingItem and getCraftingRemainingItem to hook into ResultSlot.onTake:

Spoiler
package net.deddybones.deddymod.item.custom;

import net.minecraft.world.item.AxeItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Tier;

public class CarverItem extends AxeItem {
    public CarverItem(Tier p_40521_, float p_40522_, float p_40523_, Properties p_40524_) {
        super(p_40521_, p_40522_, p_40523_, p_40524_);
    }

    @Override
    public boolean hasCraftingRemainingItem(ItemStack itemStack) {
        return itemStack.getDamageValue() < itemStack.getMaxDamage();
    }

    @Override
    public ItemStack getCraftingRemainingItem(ItemStack itemStack) {
        return (itemStack.getDamageValue() < itemStack.getMaxDamage()) ? itemStack.copy() : ItemStack.EMPTY;
    }
}

Now, I reconstruct my ItemCraftedEvent handler, and using some smart tags (which I omit for brevity), I handle two cases:
1. When crafting a carved item, I damage the tool used in the recipe
2. When crafting a carving tool from a repair recipe, I manually purge the input tools as with the new CarverItem class, as otherwise items would be duplicated
 

Spoiler
public boolean isRepairRecipe(Player player, Level level) {
        CraftingContainer craftingSlots;
        if (player.containerMenu.getClass() == InventoryMenu.class) {
            InventoryMenu iMenu = (InventoryMenu) player.containerMenu;
            craftingSlots = iMenu.getCraftSlots();
        } else {
            CraftingMenu cMenu = (CraftingMenu) player.containerMenu;
            NonNullList<ItemStack> craftingSlotContents = cMenu.slots.subList(1, 10).stream().map(Slot::getItem)
                    .collect(Collectors.toCollection(NonNullList::create));
            craftingSlots = new TransientCraftingContainer(cMenu, 3, 3, craftingSlotContents);
        }
        List<RecipeHolder<CraftingRecipe>> recipeList = level.getRecipeManager().getRecipesFor(RecipeType.CRAFTING, craftingSlots, level);
        return recipeList.get(0).id().toString().equals("minecraft:repair_item");
    }

    @SubscribeEvent
    public void itemCrafted(ItemCraftedEvent event) {
        Level level = event.getEntity().level();
        Player player = event.getEntity();
        if (!level.isClientSide()) {

            int startInd    = 1;
            int endInd      = (player.containerMenu.getClass() == InventoryMenu.class) ? 4 : 9;

            ItemStack craftingOutput = event.getCrafting();
            if (craftingOutput.is(ModTags.Items.CARVED_ITEM)) { // Check if we're performing a carving:
                for (int i = startInd; i <= endInd; i++) {
                    ItemStack thisItem = player.containerMenu.slots.get(i).getItem();
                    if (thisItem.is(ModTags.Items.CAN_CARVE)) {
                        thisItem.hurt(1, player.getRandom(), player instanceof ServerPlayer ? (ServerPlayer) player : null);
                        return;
                    }
                }
            } else if (craftingOutput.is(ModTags.Items.CAN_CARVE)) { // Check if we're crafting a carver:
                if (! isRepairRecipe(player, level)) return;
                // past this point for repair recipes; we need to manually purge the input tools
                // because CarverItem will remain by default
                int toolsFound = 0;
                for (int i = startInd; i <= endInd; i++) {
                    ItemStack thisItem = player.containerMenu.slots.get(i).getItem();
                    if (thisItem.is(craftingOutput.getItem())) {
                        player.containerMenu.slots.get(i).set(ItemStack.EMPTY);
                        toolsFound++;
                        if (toolsFound > 1) return;
                    }
                }
            }
        }
    }

This has now greatly improved implementation, beyond my expectations, for the standard crafting table and the user's inventory crafting grid. A user can now click or shift-click 'carve' items, with no duplication or issues that I have spotted so far.
 

Edited by deddybones
I keep accidentally posting early whilst trying to add new line; I have now completed the response.
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.