Jump to content

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


Recommended Posts

Posted (edited)

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
Posted

so if i open the chest then I can read it. i am looking into automating player actions to eventually include mining and chopping trees but I am just working on gearing up at the moment.

Posted

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

Posted

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.

Posted (edited)

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
Posted (edited)

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

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

Posted

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));
    }
}

 

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

    • that happens every time I enter a new dimension.
    • This is the last line before the crash: [ebwizardry]: Synchronising spell emitters for PixelTraveler But I have no idea what this means
    • What in particular? I barely used that mod this time around, and it's never been a problem in the past.
    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } } my entire project:https://github.com/kevin051606/DERP-Mod/tree/Derp-1.0-1.20
  • Topics

×
×
  • Create New...

Important Information

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