Jump to content

[1.16.5] when I Open Gui, packet reading Out of index error occured


Recommended Posts

Posted

i create gui and gui container with mcreator, but it dosen't work in multiplayer sever with 

Spoiler

Error executing task on Server
java.lang.IndexOutOfBoundsException: readerIndex(9) + length(4) exceeds writerIndex(9): PooledUnsafeDirectByteBuf(ridx: 9, widx: 9, cap: 9)
    at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1405) ~[netty-all-4.1.25.Final.jar:4.1.25.Final]
    at io.netty.buffer.AbstractByteBuf.readInt(AbstractByteBuf.java:786) ~[netty-all-4.1.25.Final.jar:4.1.25.Final]
    at net.minecraft.network.PacketBuffer.readInt(PacketBuffer.java:789) ~[forge-1.16.5-36.2.34_mapped_official_1.16.5-recomp.jar:?]
    at net.mcreator.edelcash.gui.TrantradeGui$GuiContainerMod$ButtonPressedMessage.<init>(TrantradeGui.java:309) ~[main/:?]
    at net.minecraftforge.fml.network.simple.IndexedMessageCodec.lambda$tryDecode$0(IndexedMessageCodec.java:120) ~[forge-1.16.5-36.2.34_mapped_official_1.16.5-recomp.jar:?]
    at java.util.Optional.map(Optional.java:215) ~[?:1.8.0_351]

 

and my container code

Spoiler
public class TrantradeGui extends EdelcashModElements.ModElement {
    public static HashMap guistate = new HashMap();
    private static ContainerType<GuiContainerMod> containerType = null;

    public TrantradeGui(EdelcashModElements instance) {
        super(instance, 6);
        LOGGER.info("init Transaction GUI");
        containerType = new ContainerType<>(new GuiContainerModFactory());
        FMLJavaModLoadingContext.get().getModEventBus().register(new ContainerRegisterHandler());
        elements.addNetworkMessage(GuiContainerMod.ButtonPressedMessage.class, GuiContainerMod.ButtonPressedMessage::buffer, GuiContainerMod.ButtonPressedMessage::new,
                GuiContainerMod.ButtonPressedMessage::handler);
        elements.addNetworkMessage(GuiContainerMod.GUISlotChangedMessage.class, GuiContainerMod.GUISlotChangedMessage::buffer, GuiContainerMod.GUISlotChangedMessage::new,
                GuiContainerMod.GUISlotChangedMessage::handler);
    }

    private static class ContainerRegisterHandler {
        @SubscribeEvent
        public void registerContainer(RegistryEvent.Register<ContainerType<?>> event) {
            event.getRegistry().register(containerType.setRegistryName("trantrade"));
        }
    }

    @OnlyIn(Dist.CLIENT)
    @Override
    public void initElements() {
        DeferredWorkQueue.runLater(() -> ScreenManager.register(containerType, TrantradeGuiWindow::new));
    }

    public static class GuiContainerModFactory implements IContainerFactory<GuiContainerMod> {
        @Override
        public GuiContainerMod create(int id, PlayerInventory inv, PacketBuffer extraData) {
            return new GuiContainerMod(id, inv, extraData);
        }
    }

    public static class GuiContainerMod extends Container implements Supplier<Map<Integer, Slot>> {
        World world;
        PlayerEntity entity;
        int x, y, z;
        private IItemHandler internal;
        private final Map<Integer, Slot> customSlots = new HashMap<>();
        private boolean bound = false;

        public GuiContainerMod(int id, PlayerInventory inv, PacketBuffer extraData) {
            super(containerType, id);
            this.entity = inv.player;
            this.world = inv.player.level;
            this.internal = new ItemStackHandler(3);
            BlockPos pos = null;
            if (extraData != null) {
                pos = extraData.readBlockPos();
                this.x = pos.getX();
                this.y = pos.getY();
                this.z = pos.getZ();
            }else if (pos != null) {
                if (extraData.readableBytes() == 1) { // bound to item
                    byte hand = extraData.readByte();
                    ItemStack itemstack;
                    if (hand == 0)
                        itemstack = this.entity.getItemInHand(Hand.MAIN_HAND);
                    else
                        itemstack = this.entity.getItemInHand(Hand.OFF_HAND);
                    itemstack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).ifPresent(capability -> {
                        this.internal = capability;
                        this.bound = true;
                    });
                }
            }
            this.customSlots.put(0, this.addSlot(new SlotItemHandler(internal, 0, 107, 9) {
                @Override
                public boolean mayPickup(PlayerEntity player) {
                    return true;
                }

                @Override
                public ItemStack onTake(PlayerEntity entity, ItemStack stack) {
                    GuiContainerMod.this.slotChanged(0, 1, 0);
                    return super.onTake(entity, stack);
                }

                @Override
                public boolean mayPlace(ItemStack stack) {
                    return false;
                }
            }));
            this.customSlots.put(1, this.addSlot(new SlotItemHandler(internal, 1, 107, 29) {
                @Override
                public boolean mayPickup(PlayerEntity player) {
                    return true;
                }

                @Override
                public ItemStack onTake(PlayerEntity entity, ItemStack stack) {
                    GuiContainerMod.this.slotChanged(1, 1, 0);
                    return super.onTake(entity, stack);
                }

                @Override
                public boolean mayPlace(ItemStack stack) {
                    return false;
                }
            }));
            this.customSlots.put(2, this.addSlot(new SlotItemHandler(internal, 2, 107, 49) {
                @Override
                public boolean mayPickup(PlayerEntity player) {
                    return true;
                }

                @Override
                public ItemStack onTake(PlayerEntity entity, ItemStack stack) {
                    GuiContainerMod.this.slotChanged(2, 1, 0);
                    return super.onTake(entity, stack);
                }

                @Override
                public boolean mayPlace(ItemStack stack) {
                    return false;
                }
            }));
            int si;
            int sj;
            for (si = 0; si < 3; ++si)
                for (sj = 0; sj < 9; ++sj)
                    this.addSlot(new Slot(inv, sj + (si + 1) * 9, 13 + 8 + sj * 18, -6 + 84 + si * 18));
            for (si = 0; si < 9; ++si)
                this.addSlot(new Slot(inv, si, 13 + 8 + si * 18, -6 + 142));
            if (world.isClientSide) {
                render_cash(this, entity);
            }
        }

        public Map<Integer, Slot> get() {
            return customSlots;
        }

        @Override
        public boolean stillValid(PlayerEntity player) {
            return true;
        }

        @Override
        public ItemStack quickMoveStack(PlayerEntity playerIn, int index) {
            ItemStack itemstack = ItemStack.EMPTY;
            Slot slot = (Slot) this.slots.get(index);
            if (slot != null && slot.getItem().getCount() > 1) {
                ItemStack itemstack1 = slot.getItem();
                itemstack = itemstack1.copy();
                if (index < 3) {
                    if (this.moveItemStack(itemstack1, 3, this.slots.size(), true)) {
                        return ItemStack.EMPTY;
                    }
                } else if (this.moveItemStack(itemstack1, 0, 3, false)) {
                    if (index < 3 + 27) {
                        if (this.moveItemStack(itemstack1, 3 + 27, this.slots.size(), true)) {
                            return ItemStack.EMPTY;
                        }
                    } else {
                        if (this.moveItemStack(itemstack1, 3, 3 + 27, false)) {
                            return ItemStack.EMPTY;
                        }
                    }
                    return ItemStack.EMPTY;
                }
                if (itemstack1.getCount() == 0) {
                    slot.set(ItemStack.EMPTY);
                }
                if (itemstack1.getCount() == itemstack.getCount()) {
                    return ItemStack.EMPTY;
                }
                slot.onTake(playerIn, itemstack1);
            }
            return itemstack;
        }

        protected boolean moveItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection) {
            boolean flag = false;
            int i = startIndex;
            if (reverseDirection) {
                i = endIndex - 1;
            }
            if (stack.isStackable()) {
                while (!stack.isEmpty()) {
                    if (reverseDirection) {
                        if (i < startIndex) {
                            break;
                        }
                    } else if (i >= endIndex) {
                        break;
                    }
                    Slot slot = this.slots.get(i);
                    ItemStack itemstack = slot.getItem();
                    if (slot.mayPlace(itemstack) && !itemstack.isEmpty() && consideredTheSameItem(stack, itemstack)) {
                        int j = itemstack.getCount() + stack.getCount();
                        int maxSize = Math.min(slot.getMaxStackSize(), stack.getMaxStackSize());
                        if (j <= maxSize) {
                            stack.setCount(0);
                            itemstack.setCount(j);
                            slot.set(itemstack);
                            flag = true;
                        } else if (itemstack.getCount() < maxSize) {
                            stack.shrink(maxSize - itemstack.getCount());
                            itemstack.setCount(maxSize);
                            slot.set(itemstack);
                            flag = true;
                        }
                    }
                    if (reverseDirection) {
                        --i;
                    } else {
                        ++i;
                    }
                }
            }
            if (!stack.isEmpty()) {
                if (reverseDirection) {
                    i = endIndex - 1;
                } else {
                    i = startIndex;
                }
                while (true) {
                    if (reverseDirection) {
                        if (i < startIndex) {
                            break;
                        }
                    } else if (i >= endIndex) {
                        break;
                    }
                    Slot slot1 = this.slots.get(i);
                    ItemStack itemstack1 = slot1.getItem();
                    if (itemstack1.isEmpty() && slot1.mayPlace(stack)) {
                        if (stack.getCount() > slot1.getMaxStackSize()) {
                            slot1.set(stack.split(slot1.getMaxStackSize()));
                        } else {
                            slot1.set(stack.split(stack.getCount()));
                        }
                        slot1.setChanged();
                        flag = true;
                        break;
                    }
                    if (reverseDirection) {
                        --i;
                    } else {
                        ++i;
                    }
                }
            }
            return true;
        }

        @Override
        public void removed(PlayerEntity playerIn) {
            super.removed(playerIn);
        }

        private void slotChanged(int slotid, int ctype, int meta) {
            if (this.world != null && this.world.isClientSide()) {
                EdelcashMod.PACKET_HANDLER.sendToServer(new GUISlotChangedMessage(slotid, x, y, z, ctype, meta));
                handleSlotAction(entity, slotid, ctype, meta, x, y, z);
            }
        }
        public static class ButtonPressedMessage {
            int buttonID, x, y, z;

            public ButtonPressedMessage(PacketBuffer buffer) {
                this.buttonID = buffer.readInt();
                this.x = buffer.readInt();
                this.y = buffer.readInt();
                this.z = buffer.readInt();
            }

            public ButtonPressedMessage(int buttonID, int x, int y, int z) {
                this.buttonID = buttonID;
                this.x = x;
                this.y = y;
                this.z = z;
            }

            public static void buffer(ButtonPressedMessage message, PacketBuffer buffer) {
                buffer.writeInt(message.buttonID);
                buffer.writeInt(message.x);
                buffer.writeInt(message.y);
                buffer.writeInt(message.z);
            }
            public static void handler(ButtonPressedMessage message, Supplier<NetworkEvent.Context> contextSupplier) {
                NetworkEvent.Context context = contextSupplier.get();
                context.enqueueWork(() -> {
                    PlayerEntity entity = context.getSender();
                    int buttonID = message.buttonID;
                    int x = message.x;
                    int y = message.y;
                    int z = message.z;
                    handleButtonAction(entity, buttonID, x, y, z);
                });
                context.setPacketHandled(true);
            }
        }

        public static class GUISlotChangedMessage {
            int slotID, x, y, z, changeType, meta;

            public GUISlotChangedMessage(int slotID, int x, int y, int z, int changeType, int meta) {
                this.slotID = slotID;
                this.x = x;
                this.y = y;
                this.z = z;
                this.changeType = changeType;
                this.meta = meta;
            }

            public GUISlotChangedMessage(PacketBuffer buffer) {
                this.slotID = buffer.readInt();
                this.x = buffer.readInt();
                this.y = buffer.readInt();
                this.z = buffer.readInt();
                this.changeType = buffer.readInt();
                this.meta = buffer.readInt();
            }

            public static void buffer(GUISlotChangedMessage message, PacketBuffer buffer) {
                buffer.writeInt(message.slotID);
                buffer.writeInt(message.x);
                buffer.writeInt(message.y);
                buffer.writeInt(message.z);
                buffer.writeInt(message.changeType);
                buffer.writeInt(message.meta);
            }

            public static void handler(GUISlotChangedMessage message, Supplier<NetworkEvent.Context> contextSupplier) {
                NetworkEvent.Context context = contextSupplier.get();
                context.enqueueWork(() -> {
                    PlayerEntity entity = context.getSender();
                    int slotID = message.slotID;
                    int changeType = message.changeType;
                    int meta = message.meta;
                    int x = message.x;
                    int y = message.y;
                    int z = message.z;
                    handleSlotAction(entity, slotID, changeType, meta, x, y, z);
                });
                context.setPacketHandled(true);
            }
        }
    }



    static void handleButtonAction(PlayerEntity entity, int buttonID, int x, int y, int z) {
        World world = entity.level;
        // security measure to prevent arbitrary chunk generation
        if (!world.isLoaded(new BlockPos(x, y, z)))
            return;
    }
    @OnlyIn(Dist.CLIENT)
    private static void render_cash(GuiContainerMod container, PlayerEntity player) {
        BankAccount targetAccount = PixelmonCommandUtils.require(BankAccountProxy.getBankAccount(player.getUUID()), "pixelmon.command.general.invalidplayer");
        if (targetAccount.getBalance().intValue() > 10000) {
            container.setItem(0, new ItemStack(BronzedelItem.block));
            container.setItem(1, new ItemStack(SilveredelItem.block));
            container.setItem(2, new ItemStack(GoldedelItem.block));
        }
        if (targetAccount.getBalance().intValue() < 10000) {
            container.setItem(0, new ItemStack(BronzedelItem.block));
            container.setItem(1, new ItemStack(SilveredelItem.block));
            container.setItem(2, ItemStack.EMPTY);
        }
        if (targetAccount.getBalance().intValue() < 1000) {
            container.setItem(0, new ItemStack(BronzedelItem.block));
            container.setItem(1, ItemStack.EMPTY);
            container.setItem(2, ItemStack.EMPTY);
        }
        if (targetAccount.getBalance().intValue() < 100) {
            container.setItem(0, ItemStack.EMPTY);
            container.setItem(1, ItemStack.EMPTY);
            container.setItem(2, ItemStack.EMPTY);
        }

    }

    private static void handleSlotAction(PlayerEntity entity, int slotID, int changeType, int meta, int x, int y, int z) {
        BankAccount targetAccount = PixelmonCommandUtils.require(BankAccountProxy.getBankAccount(entity.getUUID()), "pixelmon.command.general.invalidplayer");
        if (entity.level.isClientSide) {
            if (changeType == 1) {
                targetAccount.setBalance(targetAccount.getBalance().intValue() - 10 * Math.pow(10, slotID + 1));
            }
        }
        render_cash((GuiContainerMod) entity.containerMenu, entity);
    }
}

 

 

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

    • Hi,  I'm using Forge 47.3.0 for Minecraft 1.20.1 I apologise if this is obvious I am very new to modding for Minecraft. I sucessfully made a mod that launched without errors or crashes (without it doing anything) but in order to add the features I need, I need to add "Custom Portal API [Forge]" as a dependency. However no matter the way I've tried to acheive this, it crashes. I am pretty sure it's not the way I'm putting it in the repositories, the dependencies or the way I'm refrencing it, as I've a hundred diffrent combinations and multiple Maven methods. And on all those diffrent variations I still get this crash: pastebin.com/UhumzZCZ Any tips would be invaluable as I've been loosing my mind over this!
    • Hi, i'm really having problems trying to set the texture to my custom item. I thought i'm doing everything correctly, but all i see is the missing texture block for my item. I am trying this for over a week now and getting really frustrated. The only time i could make the texture work, was when i used an older Forge version (52.0.1) for Minecraft (1.21.4). Was there a fundamental change for textures and models somewhere between versions that i'm missing? I started with Forge 54.1.0 and had this problem, so in my frustration i tried many things: Upgrading to Forge 54.1.1, created multiple new projects, workspaces, redownloaded everything and setting things up multiple times, as it was suggested in an older thread. Therea are no errors in the console logs, but maybe i'm blind, so i pasted the console logs to pastebin anyway: https://pastebin.com/zAM8RiUN The only time i see an error is when i change the models JSON file to an incorrect JSON which makes sense and that suggests to me it is actually reading the JSON file.   I set the github repository to public, i would be so thankful if anyone could take a look and tell me what i did wrong: https://github.com/xLorkin/teleport_pug_forge   As a note: i'm pretty new to modding, this is my first mod ever. But i'm used to programming. I had some up and downs, but through reading the documentation, using google and experimenting, i could solve all other problems. I only started modding for Minecraft because my son is such a big fan and wanted this mod.
    • Please read the FAQ (link in orange bar at top of page), and post logs as described there.
    • Hello fellow Minecrafters! I recently returned to Minecraft and realized I needed a wiki that displays basic information easily and had great user navigation. That’s why I decided to build: MinecraftSearch — a site by a Minecraft fan, for Minecraft fans. Key Features So Far Straight-to-the-Point Info: No extra fluff; just the essentials on items, mobs, recipes, loot and more. Clean & Intuitive Layout: Easy navigation so you spend less time scrolling and more time playing. Optimized Search: Search for anything—items, mobs, blocks—and get results instantly. What I’m Thinking of Adding More data/information: Catch chances for fishing rod, traveling villager trades, biomes info and a lot more. The website is still under development and need a lot more data added. Community Contributions: Potential for user-uploaded tips for items/mobs/blocks in the future. Feature Requests Welcome: Your ideas could shape how the wiki evolves! You can see my roadmap at the About page https://minecraftsearch.com/about I’d love for you to check out MinecraftSearch and see if it helps you find the info you need faster. Feedback is crucial—I want to develop this further based on what the community needs most, so please let me know what you think. Thanks, and happy crafting!
    • Instructions on how to install newer Java can be found in the FAQ
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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