Jump to content

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


Recommended Posts

Posted

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

  • 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:

  Reveal hidden contents

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:

  Reveal hidden contents

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
 

  Reveal hidden contents

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.

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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Hello All,  Relatively new to this and after playing for a few hours whenever someone enters the nether the entire server will crash and my friend and I are at a bit of a loss. Deleting player data solves the issues but it still persists whenever someone enters even after deleting the DIM-1 folder. Paste: https://pastebin.com/REbpJVqe Thanks!   -Mitchell
    • Add the crash-report or latest.log (logs-folder) with sites like https://mclo.gs/ and paste the link to it here  
    • Cracked Launchers are not supported
    • Hi, I have a problem in minecraft java (only in forge 1.20.1), When I start the game after a moment the game crashed with code 1 this only in forge 1.20.1 , I tried to reinstall java, Upgrade java to 17, update the drivers to the latest version, downgrade the drivers to the pervious version, deleting .minecraft and reinstall it , but none of these ways working.   here is the log:   [Launcher] Launching Minecraft... I'm hiding! mods after C:\Users\Windows\AppData\Roaming\.minecraft\mods\tl_skin_cape_forge_1.20_1.20.1-1.32.jar [InnerMinecraftServersImpl]  search changers of the servers read servers from servers.dat [] [InnerMinecraftServersImpl]  prepare inner servers save servers to servers.dat [Launcher] Game skin type: TLAUNCHER [Launcher] Starting Minecraft Forge 1.20.1... [Launcher] Launching in: C:\Users\Windows\AppData\Roaming\.minecraft Starting garbage collector: 96 / 227 MB Garbage collector completed: 60 / 214 MB [Launcher] Processing post-launch actions. Assist launch: true =============================================================================================== [05:29:03] [main/INFO]: ModLauncher running: args [--username, *********, --version, Forge 1.20.1, --gameDir, C:\Users\Windows\AppData\Roaming\.minecraft, --assetsDir, C:\Users\Windows\AppData\Roaming\.minecraft\assets, --assetIndex, 5, --uuid, *************************************, --accessToken, вќ„вќ„вќ„вќ„вќ„вќ„вќ„вќ„, --clientId, null, --xuid, null, --userType, mojang, --versionType, modified, --width, 925, --height, 530, --launchTarget, forgeclient, --fml.forgeVersion, 47.3.22, --fml.mcVersion, 1.20.1, --fml.forgeGroup, net.minecraftforge, --fml.mcpVersion, 20230612.114412] [05:29:04] [main/INFO]: ModLauncher 10.0.9+10.0.9+main.dcd20f30 starting: java version 17.0.12 by Oracle Corporation; OS Windows 10 arch amd64 version 10.0 [05:29:15] [main/INFO]: Loading ImmediateWindowProvider fmlearlywindow [05:29:24] [main/INFO]: Trying GL version 4.6 [05:29:60] [main/INFO]: Requested GL version 4.6 got version 4.6 [05:29:67] [main/INFO]: SpongePowered MIXIN Subsystem Version=0.8.5 Source=union:/C:/Users/Windows/AppData/Roaming/.minecraft/libraries/org/spongepowered/mixin/0.8.5/mixin-0.8.5.jar%23100!/ Service=ModLauncher Env=CLIENT FATAL ERROR in native method: Thread[pool-2-thread-1,5,main]: No context is current or a function that is not available in the current context was called. The JVM will abort execution.     at org.lwjgl.opengl.GL11C.nglGetString(org.lwjgl.opengl@3.3.1+7/Native Method)     at org.lwjgl.opengl.GL11C.glGetString(org.lwjgl.opengl@3.3.1+7/GL11C.java:978)     at net.minecraftforge.fml.earlydisplay.DisplayWindow.initRender(fmlearlydisplay@1.20.1-47.3.22/DisplayWindow.java:209)     at net.minecraftforge.fml.earlydisplay.DisplayWindow.lambda$start$5(fmlearlydisplay@1.20.1-47.3.22/DisplayWindow.java:292)     at net.minecraftforge.fml.earlydisplay.DisplayWindow$$Lambda$437/0x000001fab120a618.run(fmlearlydisplay@1.20.1-47.3.22/Unknown Source)     at java.util.concurrent.Executors$RunnableAdapter.call(java.base@17.0.12/Executors.java:539)     at java.util.concurrent.FutureTask.run(java.base@17.0.12/FutureTask.java:264)     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(java.base@17.0.12/ScheduledThreadPoolExecutor.java:304)     at java.util.concurrent.ThreadPoolExecutor.runWorker(java.base@17.0.12/ThreadPoolExecutor.java:1136)     at java.util.concurrent.ThreadPoolExecutor$Worker.run(java.base@17.0.12/ThreadPoolExecutor.java:635)     at java.lang.Thread.run(java.base@17.0.12/Thread.java:842) Here I am! [VersionManager] Refreshing versions locally... [VersionManager] Versions has been refreshed (6 ms) [Launcher] Launcher exited. [Launcher] Minecraft closed with exit code: 1 flush now [Launcher] [Crash] Signature "Bad video drivers" matches! [Crash] Signature "Bad video drivers" matches! [Launcher] [Crash] Crash has been recognized! [Crash] Crash has been recognized! flush now
  • Topics

×
×
  • Create New...

Important Information

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