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.
Note: Your post will require moderator approval before it will be visible.

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

    • Hello. I decided to try to make a mod, but for some reason I stumbled at the very beginning. How do I register a block for it to appear in the inventory? It seems that I'm trying to do it according to the manual, but only the procedure for registering new blocks is described there. So I made a mod class. I registered the registration, but when I install it into the game, I do not see my block in the intent. And I will also be grateful if you give a link to some kind of detailed manual. So that step by step it was described how what can be created. Thanks.   @Mod("examplemod") public class ExampleMod { // Directly reference a log4j logger. private static final Logger LOGGER = LogManager.getLogger(); private static final String MODID = "0.1"; private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID); public static final RegistryObject<Block> MyBlock = BLOCKS.register("mysuperblockreg", () -> new SuperBlock(BlockBehaviour.Properties.of(Material.WOOD).lightLevel((s) -> { return 1; }).sound(SoundType.WOOD))); public ExampleMod() { // Register the setup method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // Register the enqueueIMC method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // Register the processIMC method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus()); // Register ourselves for server and other game events we are interested in MinecraftForge.EVENT_BUS.register(this); } private void setup(final FMLCommonSetupEvent event) { // some preinit code LOGGER.info("HELLO FROM PREINIT"); LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName()); } private void enqueueIMC(final InterModEnqueueEvent event) { // some example code to dispatch IMC to another mod InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world"; }); } private void processIMC(final InterModProcessEvent event) { // some example code to receive and process InterModComms from other mods LOGGER.info("Got IMC {}", event.getIMCStream().map(m -> m.messageSupplier().get()).collect(Collectors.toList())); } // You can use SubscribeEvent and let the Event Bus discover methods to call @SubscribeEvent public void onServerStarting(FMLServerStartingEvent event) { // do something when the server starts LOGGER.info("HELLO from server starting"); } // You can use EventBusSubscriber to automatically subscribe events on the // contained class (this is subscribing to the MOD // Event bus for receiving Registry Events) @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public static class RegistryEvents { @SubscribeEvent public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) { // register a new block here LOGGER.info("HELLO from Register Block"); } } }  
    • I'm probably really stupid but how do I fix this error. It happens whenever I try to startup Minecraft forge 1.8.9 recommended [19:13:10 ERROR]: Gave up trying to download https://maven.minecraftforge.net/jline/jline/2.13/jline-2.13.jar for job 'Version & Libraries' [19:13:10 ERROR]: Job 'Version & Libraries' finished with 1 failure(s)! (took 0:00:13.982)   How do I fix this?
    • Override attackEntityFrom and do checks there, for example DamageSource#isProjectile. Or check how Enderman does it.
    • Hey, I just started modding, and especially texturing, so I'm still new to all of this. I thought a fun thing to do would be to turn the world to glass (turn blocks such as grass and stone and ores etc..) to have the grass texture, so the world would be glass. Seemed kinda fun. So I just copy-pasted the glass texture into my pack, renamed it to stone, and ran into a problem. It is rendering the glass texture, but is not transparent. Its just grey on the inside, with the glass textures on the side. I am completely lost as of what to do. Does anyone have a solution ? thank you
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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