Jump to content

[1.12.2] Reversing a Crafting Recipe on Mined


ChampionAsh5357

Recommended Posts

I've recently taken the task of trying to create an uncrafting enchantment where a block is mined and then disassembles itself according to its crafting recipe. I've created the code that allows this to work, however, there are a few problems I can't seem to figure out. First, the items outputted don't always come out in the correct amounts. For example, mining a diamond block outputs three stacks instead of just nine diamonds. This occurs semi-randomly based on the number of items. Second, some blocks when broken throw an ArrayOutOfBoundsException such as the chest when breaking. I'm not sure how this is possible as the index pulled out of the getMatchingStacks is only as large as the size of the array. If you could provide a solution to either problem, it would be greatly appreciated.

 

Here's the code:

Spoiler

@SubscribeEvent
    public static void onBlockHarvested(BlockEvent.HarvestDropsEvent event) {
        Block block = event.getState().getBlock();
        if(event.getHarvester() != null && !event.isSilkTouching()) {
            if(EnchantmentHelper.getEnchantmentLevel(CustomEnchantments.UNCRAFTING, event.getHarvester().getHeldItemMainhand()) > 0) {
                Item item = Item.getItemFromBlock(block);
                ItemStack stack = ItemStack.EMPTY;
                if(item == null) return;
                if(item.getHasSubtypes()) stack = new ItemStack(item, 1, block.damageDropped(event.getState()));
                else stack = new ItemStack(item, 1, 0);
                
                for(Iterator<IRecipe> it= GameRegistry.findRegistry(IRecipe.class).getValuesCollection().iterator(); it.hasNext(); ) {
                    IRecipe recipe = it.next();
                    if(ItemStack.areItemsEqual(stack, recipe.getRecipeOutput())) {
                        event.getDrops().clear();
                        for(Ingredient ingredient : recipe.getIngredients()) {
                            event.getDrops().add(ingredient.getMatchingStacks()[(new Random()).nextInt(ingredient.getMatchingStacks().length)]);
                        }
                        break;
                    }
                }
            }
        }
    }

 

Link to comment
Share on other sites

19 hours ago, diesieben07 said:

You can call Block#getPickBlock, that should give you the best possible result.

That would make sense, I'm assuming that the RayTraceResult can just be gathered by the position of the block and a insignificant EnumFacing.

 

19 hours ago, diesieben07 said:

getRecipeOutput is not guaranteed to be correct, or even present at all. The only way to correctly determine a recipe's output is to call IRecipe#getCraftingResult, which requires the actual inputs.

Can that be obtained by going through getIngredients()? Otherwise, I do not know how to get an instance of InventoryCrafting for the IRecipe.

 

19 hours ago, diesieben07 said:

Just comparing the Item and damage value (which is what areItemsEqual does) is not enough.

Switching to ItemStack#areItemStacksEqual then.

 

19 hours ago, diesieben07 said:

As for your error: Please show the actual stack trace. Like you said, this should not be possible.

Spoiler

[16:42:18] [Server thread/ERROR] [FML]: Index: 1 Listeners:
[16:42:18] [Server thread/ERROR] [FML]: 0: NORMAL
[16:42:18] [Server thread/ERROR] [FML]: 1: ASM: class com.championash5357.custom.client.event.CustomEvents onBlockHarvested(Lnet/minecraftforge/event/world/BlockEvent$HarvestDropsEvent;)V
[16:42:18] [Server thread/FATAL] [minecraft/MinecraftServer]: Error executing task
java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: bound must be positive
    at java.util.concurrent.FutureTask.report(Unknown Source) ~[?:1.8.0_201]
    at java.util.concurrent.FutureTask.get(Unknown Source) ~[?:1.8.0_201]
    at net.minecraft.util.Util.runTask(Util.java:54) [Util.class:?]
    at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:798) [MinecraftServer.class:?]
    at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:743) [MinecraftServer.class:?]
    at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:192) [IntegratedServer.class:?]
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:592) [MinecraftServer.class:?]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_201]
Caused by: java.lang.IllegalArgumentException: bound must be positive
    at java.util.Random.nextInt(Unknown Source) ~[?:1.8.0_201]
    at com.championash5357.custom.client.event.CustomEvents.onBlockHarvested(CustomEvents.java:257) ~[CustomEvents.class:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler_31_CustomEvents_onBlockHarvested_HarvestDropsEvent.invoke(.dynamic) ~[?:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:90) ~[ASMEventHandler.class:?]
    at net.minecraftforge.fml.common.eventhandler.EventBus.post(EventBus.java:182) ~[EventBus.class:?]
    at net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(ForgeEventFactory.java:321) ~[ForgeEventFactory.class:?]
    at net.minecraft.block.Block.dropBlockAsItemWithChance(Block.java:721) ~[Block.class:?]
    at net.minecraft.block.Block.dropBlockAsItem(Block.java:710) ~[Block.class:?]
    at net.minecraft.block.Block.harvestBlock(Block.java:929) ~[Block.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.tryHarvestBlock(PlayerInteractionManager.java:353) ~[PlayerInteractionManager.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.blockRemoving(PlayerInteractionManager.java:261) ~[PlayerInteractionManager.class:?]
    at net.minecraft.network.NetHandlerPlayServer.processPlayerDigging(NetHandlerPlayServer.java:732) ~[NetHandlerPlayServer.class:?]
    at net.minecraft.network.play.client.CPacketPlayerDigging.processPacket(CPacketPlayerDigging.java:56) ~[CPacketPlayerDigging.class:?]
    at net.minecraft.network.play.client.CPacketPlayerDigging.processPacket(CPacketPlayerDigging.java:12) ~[CPacketPlayerDigging.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:21) ~[PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_201]
    at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_201]
    at net.minecraft.util.Util.runTask(Util.java:53) ~[Util.class:?]
    ... 5 more
[16:42:34] [Server thread/ERROR] [FML]: Exception caught during firing event net.minecraftforge.event.world.BlockEvent$HarvestDropsEvent@38d72c8e:
java.lang.IllegalArgumentException: bound must be positive
    at java.util.Random.nextInt(Unknown Source) ~[?:1.8.0_201]
    at com.championash5357.custom.client.event.CustomEvents.onBlockHarvested(CustomEvents.java:257) ~[CustomEvents.class:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler_31_CustomEvents_onBlockHarvested_HarvestDropsEvent.invoke(.dynamic) ~[?:?]
    at net.minecraftforge.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:90) ~[ASMEventHandler.class:?]
    at net.minecraftforge.fml.common.eventhandler.EventBus.post(EventBus.java:182) [EventBus.class:?]
    at net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(ForgeEventFactory.java:321) [ForgeEventFactory.class:?]
    at net.minecraft.block.Block.dropBlockAsItemWithChance(Block.java:721) [Block.class:?]
    at net.minecraft.block.Block.dropBlockAsItem(Block.java:710) [Block.class:?]
    at net.minecraft.block.Block.harvestBlock(Block.java:929) [Block.class:?]
    at net.minecraft.block.BlockContainer.harvestBlock(BlockContainer.java:92) [BlockContainer.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.tryHarvestBlock(PlayerInteractionManager.java:353) [PlayerInteractionManager.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.blockRemoving(PlayerInteractionManager.java:261) [PlayerInteractionManager.class:?]
    at net.minecraft.network.NetHandlerPlayServer.processPlayerDigging(NetHandlerPlayServer.java:732) [NetHandlerPlayServer.class:?]
    at net.minecraft.network.play.client.CPacketPlayerDigging.processPacket(CPacketPlayerDigging.java:56) [CPacketPlayerDigging.class:?]
    at net.minecraft.network.play.client.CPacketPlayerDigging.processPacket(CPacketPlayerDigging.java:12) [CPacketPlayerDigging.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:21) [PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_201]
    at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_201]
    at net.minecraft.util.Util.runTask(Util.java:53) [Util.class:?]
    at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:798) [MinecraftServer.class:?]
    at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:743) [MinecraftServer.class:?]
    at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:192) [IntegratedServer.class:?]
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:592) [MinecraftServer.class:?]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_201]

The line referred to is "ItemStack ing = ingredient.getMatchingStacks()[(new Random()).nextInt(ingredient.getMatchingStacks().length)];" I misread the error. Apologies. Fixed the issue.

 

Here is the rearranged code (getRecipeOutput not changed yet as for lack of knowledge of how to):

Spoiler

                ItemStack stack = block.getPickBlock(event.getState(), new RayTraceResult(new Vec3d(event.getPos().getX(), event.getPos().getY(), event.getPos().getZ()), EnumFacing.NORTH), event.getWorld(), event.getPos(), event.getHarvester());
                List<ItemStack> drops = Lists.newArrayList();
                
                for(Iterator<IRecipe> it= GameRegistry.findRegistry(IRecipe.class).getValuesCollection().iterator(); it.hasNext(); ) {
                    IRecipe recipe = it.next();
                    if(ItemStack.areItemStacksEqual(stack, recipe.getRecipeOutput())) {
                        event.getDrops().clear();
                        for(Ingredient ingredient : recipe.getIngredients()) {

                            if(ingredient.getMatchingStacks().length == 0) continue;
                            ItemStack ing = ingredient.getMatchingStacks()[(new Random()).nextInt(ingredient.getMatchingStacks().length)];
                            boolean is_drop = false;
                            for(ItemStack drop : drops) {
                                if(ItemStack.areItemsEqual(drop, ing) && drop.getCount() != drop.getMaxStackSize()) {
                                    is_drop = true;
                                    drop.grow(1);
                                }
                            }
                            if(!is_drop) drops.add(ing);
                        }
                        for(ItemStack drop : drops) {
                            event.getDrops().add(drop);
                        }
                        break;
                    }
                }

 

Edited by ChampionAsh5357
Link to comment
Share on other sites

7 hours ago, diesieben07 said:

Like I said, you would need to have the inputs that were originally used to craft the item that was just mined. But that's impossible to keep track of.

 

getRecipeOutput will work for some things, but it might produce strange results for others.

The issue is here that getRecipeOutput() will work for and Shaped or Shapeless recipe defined in the json files since they all have getRecipeOutput() as the main output. Anything pertaining to banners would not work with the current setup due to patterns. That would require complete markings of all banner inputs with IRecipe which I don't believe is possible without freezing or lagging out the game. If we were to ignore those custom IRecipes, that would just make it impossible to uncraft anything customly defined. However, this still leaves the question of multiblock structures being mined. The bed, for example, should output its contents but instead returns the block itself.

Link to comment
Share on other sites

After further research, it seems as there 4 3 main problems excluding the banner nbt one.

1. The piston if mined when extended at the head will drop the block and the uncrafted recipe.

2. The bed drops the block instead of the recipe.

3. The shulker box drops the block with the items still inside instead of the recipe.

4. There seems to be some sort of item duplication that increases over each block mined with recipes having more than one of the same block.

The first three seem to originate from Block#dropBlockAsItemWithChance while I can't seem to find the cause of the fourth problem.

Edited by ChampionAsh5357
Found the issue and resolved it for the item dupe.
Link to comment
Share on other sites

On 8/4/2019 at 5:46 AM, diesieben07 said:

Like I said, you cannot use block drops. They are highly inaccurate (diamond ore drops diamonds instead of diamond ore blocks). You need to use getPickBlock.

If you looked at the above code, you can see that I have been using Block#getPickBlock since you've suggested it. The issue is with actual Minecraft programming itself it seems as the Bed (BlockBed) and Shulker Box (BlockShulkerBox) has no call to triggering the BlockEvent#HarvestDropsEvent within it. For the Piston Extension (BlockPistonMoving or BlockPistonExtension), it calls the command twice first dropping the block and then the recipe. The reason why I mentioned Block#dropBlockAsItemWithChance is because that is the only place the trigger fires when a block is broken in this way. The other trigger provides no use. The above three classes do not have access to the trigger or accesses it abnormally.

Edited by ChampionAsh5357
Link to comment
Share on other sites

I was able to find a decomposition using BannerPattern and EnumDyeColor by reading the nbt. However, the same issue as before persists where HarvestDropsEvent is not triggered. The other three mentioned above do not seem to not trigger the event either. I'm not exactly sure where the method needed to use it was overwritten, but the trigger is never called to allow the event to happen at least in these four cases.

Edited by ChampionAsh5357
Link to comment
Share on other sites

Okay, I've managed to work around three of the four blocks using event canceling and triggering the HarvestDropsEvent in the BreakEvent. However, I still haven't managed to get the shulker box to disappear without having it drop its item. Is there any way to set a block to air within BreakEvent without having it drop its item?

Link to comment
Share on other sites

6 hours ago, diesieben07 said:

You would have to empty the shulker box inventory before breaking the block.

I've already tried that, but your tip gave me the solution. I had to remove the tile entity before setting the block to air and canceling since the shulker box only drops in the normal way as long as the tile entity exists. I just have to create a player capability to allow storage of blocks to reverse recipes with more than one output. Thank you for the all the help you have provided.

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.