Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

how to get the inventory of a chest from the client side [Solved]


Oscar Ames
 Share

Recommended Posts

I am working in 1.17.1 and i am trying to read the contents of a chest from a client side mod. I have attempted to read the chest using 

((RandomizableContainerBlockEntity)Minecraft.getInstance().level.getBlockEntity(new BlockPos(1,1,1))).getItem(0);

this returns null since it is reading from the client side.

is there any way to get the inventory within a block without needing any server side code I was thinking of trying to catch the ClientboundContainerSetContentPacket but I have seen that is said not to be the best idea.

 

the overall project is to try to get the inventories within an area and then by sending packets to the server move the player in order to reequip with items from said chests.

 

here is my code so far I haven't implemented movement of the player yet i am just trying to move items between inventories.

 

ForgeEventHandeler.java

@Mod.EventBusSubscriber
public class ForgeEventHandler {

	private static ArrayList<BlockPos> homeBase = new ArrayList<BlockPos>();
	private static Boolean pressed = false;
	public static final KeyMapping keyBinding = new KeyMapping("pam SETUP", 79, "PAM");
	
    @SubscribeEvent
    public static void updatePlayer(TickEvent.PlayerTickEvent event) {
    	if(event.player.canEat(false)){
            for(ItemStack inventoryStack : event.player.getInventory().items){
            	if (inventoryStack.isEdible()) {
            		ForgeEventFactory.onItemUseStart(event.player, inventoryStack, 0);
                    ItemStack result = inventoryStack.getItem().finishUsingItem(inventoryStack, event.player.getCommandSenderWorld(), event.player);
                    ForgeEventFactory.onItemUseFinish(event.player, inventoryStack, 0, result);
                    if (!event.player.canEat(false)) {
                    	break;
                    }
            	}
            
            }
    	}
    	
    	if (keyBinding.isDown() && !pressed) {
    		pressed = true;
    		openBlock();	    	
    		
    		if(homeBase.size()==2) {
    			homeBase.clear();
    		}
    		
    		HitResult block =  Minecraft.getInstance().player.pick(20.0D, 0.0F, false);

            if(block.getType() == BlockHitResult.Type.BLOCK){
               BlockPos blockpos = ((BlockHitResult)block).getBlockPos();
               homeBase.add(blockpos);
               Minecraft.getInstance().getConnection().send(new ServerboundChatPacket("position set"));
             }
    		
    		if(homeBase.size()==2) {
    			int[] start ={(int)homeBase.get(0).get(Direction.Axis.X),(int)homeBase.get(0).get(Direction.Axis.Y),(int)homeBase.get(0).get(Direction.Axis.Z)};
    			int[] end ={ (int) homeBase.get(1).get(Direction.Axis.X),(int)homeBase.get(1).get(Direction.Axis.Y),(int)homeBase.get(1).get(Direction.Axis.Z)};
    			int[] diff = {end[0]-start[0],end[1]-start[1],end[2]-start[2]};
    			
    			for (int i=start[0]; i!=(end[0]+Integer.signum(diff[0])); i+=Integer.signum(diff[0])){
    				for (int j=start[1]; j!=(end[1]+Integer.signum(diff[1])); j+=Integer.signum(diff[1])){
    					for (int k=start[2]; k!=(end[2]+Integer.signum(diff[2])); k+=Integer.signum(diff[2])){ 
    						
    						System.out.println(i+","+j+","+k);
    						BlockPos posTemp = new BlockPos(i,j,k);
    						BlockEntity blockEntity = Minecraft.getInstance().level.getBlockEntity(posTemp);
    						if (blockEntity != null && blockEntity instanceof RandomizableContainerBlockEntity) {
    							/*add chest to a category of chests that best describes what is in it E.G tools, weapons, food*/
    						}
    					}
    				}
    			}
    		}
    	}
    	
    	if (!keyBinding.isDown()) {
    		pressed=false;
    	}
    	
    }
    
    
    @SubscribeEvent
    public static void setup(FMLClientSetupEvent event) {
    	ClientRegistry.registerKeyBinding(keyBinding);
    }
    
    @SuppressWarnings("resource")
	private static void openBlock(){
    	BlockHitResult hit = (BlockHitResult) Minecraft.getInstance().player.pick(20.0D, 0.0F, false);
		Minecraft.getInstance().getConnection().send(new ServerboundUseItemOnPacket(InteractionHand.MAIN_HAND,hit));
		
    }
}

 

exampemod.java

// The value here should match an entry in the META-INF/mods.toml file
@Mod("examplemod")
public class ExampleMod
{
    // Directly reference a log4j logger.
	
    public ExampleMod() {
        
    }

    
}

 

Edited by Oscar Ames
It has been solved
Link to comment
Share on other sites

i updated the getBlock function that opens the chest to add an attempt to detect the item in the 0 slot

private static void openBlock(){
    	BlockHitResult hit = (BlockHitResult) Minecraft.getInstance().player.pick(20.0D, 0.0F, false);
		Minecraft.getInstance().getConnection().send(new ServerboundUseItemOnPacket(InteractionHand.MAIN_HAND,hit));
		String item = ((RandomizableContainerBlockEntity)Minecraft.getInstance().level.getBlockEntity(hit.getBlockPos())).getItem(0).toString();
		System.out.println(item);
		
    }

this still returns

1 air

Link to comment
Share on other sites

It's almost like you didn't wait for the packet to go anywhere and get data back before you tried to query it...

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I changed the getBlock function to

private static void openBlock(){
    	BlockHitResult hit = (BlockHitResult) Minecraft.getInstance().player.pick(20.0D, 0.0F, false);
		Minecraft.getInstance().getConnection().send(new ServerboundUseItemOnPacket(InteractionHand.MAIN_HAND,hit));
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		BlockEntity entity = Minecraft.getInstance().level.getBlockEntity(hit.getBlockPos());
		if (entity != null && entity instanceof RandomizableContainerBlockEntity) {
			ItemStack item = ((RandomizableContainerBlockEntity)Minecraft.getInstance().level.getBlockEntity(hit.getBlockPos())).getItem(0);
			System.out.println(item);
		}
    }

I also removed anything beside getBlock() from within the keybinding.isDown() if statement

but I am still unable to get the items from a chest filled with stone

Edited by Oscar Ames
Link to comment
Share on other sites

This is not how you make a delay. You are blocking the entire game from running from 50 milliseconds.

This is also not how you wait for a packet to arrive, you can't just add random delay and hope it's long enough.

Once again this sounds like a cheat. Prove that you are not writing a cheat.

Link to comment
Share on other sites

I don't like mining and due to that i want to write a program that will mine for me on my world. i also play on a server with a friend who has allowed this automation. I would also like to use this type of automation to ferry and sort items from farms and such similar to how someone would implement the computercraft turtles or thaumcraft golems to automate a task.

i do see the point of view that this could be seen as a cheat to stop player grind on a server but other mods that I would like to make in the future like a item in chest finder for looking through messy bases or a full inventory swapper will need this mechanic as well.

I think seeing what items are in a chest while the client has said chest open shouldn't be that hard to accomplish.

 

if it means anything I do not intend for this mod to be a cheat and do not intend on distributing it on any website.

Edited by Oscar Ames
Link to comment
Share on other sites

8 hours ago, diesieben07 said:

This is also not how you wait for a packet to arrive, you can't just add random delay and hope it's long enough.

The email that only goes 500 miles.

  • Haha 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

22 minutes ago, diesieben07 said:

Classic.

Only ran into it recently, but it was so good.

Another classic.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

thankyou for your input. I grab the GUI object on the GuiOpenEvent and the on the world tick event i keep checking it until the inventory loads. this successfully grabs the chest inventory from the client side. here is my final code.

package com.example.examplemod;

import java.util.ArrayList;

import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ServerboundContainerClosePacket;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.*;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.GuiContainerEvent;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fmlclient.registry.ClientRegistry;

@Mod.EventBusSubscriber
public class ForgeEventHandler {

	private static ArrayList<BlockPos> homeBase = new ArrayList<BlockPos>();
	private static Boolean pressed = false;
	public static final KeyMapping keyBinding = new KeyMapping("pam SETUP", 79, "PAM");
	private static Screen GUI = null;
	
	@SubscribeEvent
    public static void setup(FMLClientSetupEvent event) {
    	ClientRegistry.registerKeyBinding(keyBinding);
    }
	
    @SubscribeEvent
    public static void updatePlayer(TickEvent.PlayerTickEvent event) {
    	/*if(event.player.canEat(false)){
            for(ItemStack inventoryStack : event.player.getInventory().items){
            	if (inventoryStack.isEdible()) {
            		ForgeEventFactory.onItemUseStart(event.player, inventoryStack, 0);
                    ItemStack result = inventoryStack.getItem().finishUsingItem(inventoryStack, event.player.getCommandSenderWorld(), event.player);
                    ForgeEventFactory.onItemUseFinish(event.player, inventoryStack, 0, result);
                    if (!event.player.canEat(false)) {
                    	break;
                    }
            	}
            
            }
    	}*/
    	
    	if (keyBinding.isDown() && !pressed) {
    		pressed = true;
    		
    		homeBase.add(((BlockHitResult) Minecraft.getInstance().player.pick(20.0D, 0.0F, false)).getBlockPos());
    		System.out.println("set postion");
    		
    		if (homeBase.size()>=2) {
    			System.out.println("opening container");
    			openBlock(detectContainers(homeBase).get(0));
    			homeBase.clear();
    		}
    	
    		if (!keyBinding.isDown()) {
    			pressed=false;
    		}
    	
    	}
    }
    
    @SubscribeEvent
    public static void updateWorld(TickEvent.WorldTickEvent event) {
    	if (GUI != null) {
    		if (GUI instanceof AbstractContainerScreen) {
    			AbstractContainerScreen container = ((AbstractContainerScreen)GUI);
    			NonNullList<Slot> slots = container.getMenu().slots;
    			for (int i=0; i<slots.size();i++) {
        			ItemStack temp = slots.get(i).getItem();
        			System.out.print(temp.getDisplayName().getString()+" | ");
    			}
    			System.out.println("");
    			GUI = null;

    		}
    	}
    }
    
    @SubscribeEvent
    public static void openChest(GuiOpenEvent event) {
    	GUI = event.getGui();
    }
    
    private static ArrayList<Vec3> detectContainers(ArrayList<BlockPos> homebase) {
    	ArrayList<Vec3> chests = new ArrayList<Vec3>();
    	
    	int x = homebase.get(1).getX()-homebase.get(0).getX();
		int y = homebase.get(1).getY()-homebase.get(0).getY();
		int z = homebase.get(1).getZ()-homebase.get(0).getZ();
		
		for (int i=homebase.get(0).getX();i!=homebase.get(1).getX();i+=Math.signum(x)) {
			for (int j=homebase.get(0).getY();j!=homebase.get(1).getY();j+=Math.signum(y)) {
				for (int k=homebase.get(0).getZ();k!=homebase.get(1).getZ();k+=Math.signum(z)) {
					
    				BlockEntity temp = Minecraft.getInstance().level.getBlockEntity(new BlockPos(i,j,k));
    				if (temp instanceof RandomizableContainerBlockEntity && !(temp instanceof HopperBlockEntity)) {
    					chests.add(new Vec3(i,j,k));
    				}
    			}
			}
		}
		return chests;
	}

	@SuppressWarnings("resource")
	private static void openBlock(Vec3 blockPos){
		/*BlockHitResult hit = new BlockHitResult(blockPos, Direction.DOWN, new BlockPos(blockPos), false);*/
    	BlockHitResult hit = (BlockHitResult) Minecraft.getInstance().player.pick(20.0D, 0.0F, false);
		Minecraft.getInstance().getConnection().send(new ServerboundUseItemOnPacket(InteractionHand.MAIN_HAND,hit));
    }
}

 

Link to comment
Share on other sites

  • Oscar Ames changed the title to how to get the inventory of a chest from the client side [Solved]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
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.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • Hi i'm currently working on an entity. I just i finished it but it won't spawn and i don't know why. I got this error : java.lang.NullPointerException: Cannot invoke "net.minecraft.world.entity.ai.attributes.AttributeSupplier.getValue(net.minecraft.world.entity.ai.attributes.Attribute)" because "this.supplier" is null at net.minecraft.world.entity.ai.attributes.AttributeMap.getValue(AttributeMap.java:65) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.LivingEntity.getAttributeValue(LivingEntity.java:1806) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.LivingEntity.getMaxHealth(LivingEntity.java:1571) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.LivingEntity.<init>(LivingEntity.java:230) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.Mob.<init>(Mob.java:112) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at com.armanse.dreamy.entity.SleepingPlayerEntity.<init>(SleepingPlayerEntity.java:16) ~[%2379!:?] at net.minecraft.world.entity.EntityType.create(EntityType.java:460) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.EntityType.lambda$create$1(EntityType.java:470) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at java.util.Optional.map(Optional.java:260) ~[?:?] at net.minecraft.world.entity.EntityType.create(EntityType.java:469) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.EntityType.loadStaticEntity(EntityType.java:552) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.world.entity.EntityType.loadEntityRecursive(EntityType.java:508) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.commands.SummonCommand.spawnEntity(SummonCommand.java:50) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.commands.SummonCommand.lambda$register$1(SummonCommand.java:34) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at com.mojang.brigadier.CommandDispatcher.execute(CommandDispatcher.java:263) ~[brigadier-1.0.18.jar%2341!:?] at net.minecraft.commands.Commands.performCommand(Commands.java:224) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.network.ServerGamePacketListenerImpl.handleCommand(ServerGamePacketListenerImpl.java:1130) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.network.ServerGamePacketListenerImpl.handleChat(ServerGamePacketListenerImpl.java:1109) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.network.ServerGamePacketListenerImpl.handleChat(ServerGamePacketListenerImpl.java:1095) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.network.protocol.game.ServerboundChatPacket.handle(ServerboundChatPacket.java:27) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.network.protocol.game.ServerboundChatPacket.handle(ServerboundChatPacket.java:6) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.network.protocol.PacketUtils.lambda$ensureRunningOnSameThread$0(PacketUtils.java:21) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.TickTask.run(TickTask.java:17) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.util.thread.BlockableEventLoop.doRunTask(BlockableEventLoop.java:139) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.util.thread.ReentrantBlockableEventLoop.doRunTask(ReentrantBlockableEventLoop.java:22) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.doRunTask(MinecraftServer.java:775) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.doRunTask(MinecraftServer.java:162) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.util.thread.BlockableEventLoop.pollTask(BlockableEventLoop.java:112) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.pollTaskInternal(MinecraftServer.java:758) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.pollTask(MinecraftServer.java:752) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.util.thread.BlockableEventLoop.managedBlock(BlockableEventLoop.java:122) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.waitUntilNextTick(MinecraftServer.java:738) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:687) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at net.minecraft.server.MinecraftServer.lambda$spin$2(MinecraftServer.java:258) ~[forge-1.17.1-37.0.103_mapped_official_1.17.1-recomp.jar%2375!:?] at java.lang.Thread.run(Thread.java:831) [?:?] I was wondering if the problem was with the attributes of the entity since it is mention at the top but i couldn't find the error (i'm a noob so that's kinda normal). Here is the code related to the attributes: @EventBusSubscriber(modid = DreamyMain.MOD_ID, bus = Bus.FORGE) public class ClientInitEvent { @SubscribeEvent public static final void entityAttributCreation(EntityAttributeCreationEvent event) { event.put(EntityInit.Entity.get(), Entity.createAttributes().build()); } @SubscribeEvent public static final void entityClientRederer(EntityRenderersEvent.RegisterRenderers event) { event.registerEntityRenderer(EntityInit.Entity.get(), Entity::new); } }   //IN The entity class public static AttributeSupplier.Builder createAttributes() { return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 20D).add(Attributes.MOVEMENT_SPEED, 0D); }  
    • I removed a bunch of mods that said other version than 1.16.5 seems to be working. Still its kinda weird because it clearly said that the "game version" was 1.16.5. Still not happy bout it  
    • From the looks of it LoomContainer still doesn't call onCraftMatrixChanged... What am i missing seriously?
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.