Jump to content

Reading values in Container after Network Packet is always 0


whereisthemonkey

Recommended Posts

Hello everyone,

 

After digging through numerous threads I achieved to update a value in my TileEntity when the user clicks a Button in a GUI.

I also managed to synchronize the client and server side (using a simple println in tick, which prints the same value in both cases)

 

Unfortunately, when reading the data again in the Screen and Container class, the value does not change and stays 0.

Could someone please point me in the right direction?

 

My TileEntity:

package com.wthemonkey.me.technicality.tiles;

import com.wthemonkey.me.technicality.Technicality;
import com.wthemonkey.me.technicality.blocks.connection.Connection;
import com.wthemonkey.me.technicality.blocks.machines.MetalTable;
import com.wthemonkey.me.technicality.container.ContainerMetalTable;
import com.wthemonkey.me.technicality.data.recipes.TechnicalityRecipe;
import com.wthemonkey.me.technicality.items.tools.ToolType;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.IIntArray;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

import java.util.Objects;

import static com.wthemonkey.me.technicality.data.Register.TILES;

@MethodsReturnNonnullByDefault
@Mod.EventBusSubscriber(modid = Technicality.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class MetalTableTile extends IConsumer.ConsumerImplementation {

    @SuppressWarnings("ConstantConditions")
    public static final RegistryObject<TileEntityType<MetalTableTile>> METAL_TABLE_TILE = TILES.register("machine_table_metal", () ->
        TileEntityType.Builder.create(MetalTableTile::new, MetalTable.METAL_TABLE.get()).build(null));

    protected final IIntArray tableData = new IIntArray() {
        public int get(int index) {
            switch(index) {
                case 0:
                    return MetalTableTile.this.getCurrentExtractTime();
                case 1:
                    return MetalTableTile.this.getMaxExtractTime();
                case 2:
                    return MetalTableTile.this.packet.getTotalConsumption();
                case 3:
                    return MetalTableTile.this.getNeededPower();
                case 4:
                    return MetalTableTile.this.toolType.getId();
                default:
                    return 0;
            }
        }

        public void set(int index, int value) {
            switch(index) {
                case 4:
                    MetalTableTile.this.toolType = ToolType.fromID(value);
                    //Notify client as well
                    Objects.requireNonNull(getWorld()).notifyBlockUpdate(pos, getBlockState(), getBlockState(), Constants.BlockFlags.RERENDER_MAIN_THREAD);
                default:
                    break;
            }
        }

        public int size() {
            return 5;
        }
    };

    private ToolType toolType;

    protected MetalTableTile() {
        super(3, TechnicalityRecipe.METAL_TABLE_RECIPE_TYPE, METAL_TABLE_TILE.get());

        toolType = ToolType.FLATTENING_HAMMER;
    }

    @Override
    protected ITextComponent getDefaultName() {
        return new TranslationTextComponent("container." + Technicality.MOD_ID + ".machine_extractor");
    }

    @Override
    @ParametersAreNonnullByDefault
    protected Container createMenu(int windowID, PlayerInventory player) {
        return new ContainerMetalTable(windowID, player, this, this.tableData);
    }

    @Nullable
    @Override
    @ParametersAreNonnullByDefault
    public Container createMenu(int windowID, PlayerInventory playerInv, PlayerEntity p_createMenu_3_) {
        return new ContainerMetalTable(windowID, playerInv, this, this.tableData);
    }

    @Override
    public void tick() {
        super.tick();

        //Technicality.LOGGER.info(toolType); --> this is the same
    }

    @Override
    @Nullable
    public SUpdateTileEntityPacket getUpdatePacket() {
        return new SUpdateTileEntityPacket(this.pos, 3, this.getUpdateTag());
    }

    @Override
    public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
        super.onDataPacket(net, pkt);
        handleUpdateTag(pkt.getNbtCompound());
    }

    @Override
    public CompoundNBT getUpdateTag() {
        return this.write(new CompoundNBT());
    }

    @Override
    @ParametersAreNonnullByDefault
    public void read(CompoundNBT compound) {
        super.read(compound);

        MetalTableTile.this.toolType = ToolType.fromID(compound.getInt("ToolType"));
    }

    @Override
    @ParametersAreNonnullByDefault
    public CompoundNBT write(CompoundNBT compound) {
        super.write(compound);

        compound.putInt("ToolType", MetalTableTile.this.toolType.getId());

        return compound;
    }

}

 

My Container:

(The reading of getCurrentToolType() is always 0)

(Also the function #setCurrentToolType() is called fine via a package)

package com.wthemonkey.me.technicality.container;

import com.wthemonkey.me.technicality.Technicality;
import com.wthemonkey.me.technicality.container.slot.EnergyStorageSlot;
import com.wthemonkey.me.technicality.container.slot.RecipeInputSlot;
import com.wthemonkey.me.technicality.container.slot.TechnicalityResultSlot;
import com.wthemonkey.me.technicality.data.recipes.TechnicalityRecipe;
import com.wthemonkey.me.technicality.items.tools.ToolType;
import com.wthemonkey.me.technicality.tiles.IProvider;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.util.IIntArray;
import net.minecraft.util.IntArray;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod;

import static com.wthemonkey.me.technicality.data.Register.CONTAINERS;

@MethodsReturnNonnullByDefault
@Mod.EventBusSubscriber(modid = Technicality.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class ContainerMetalTable extends CommonContainer {

    public static final RegistryObject<ContainerType<ContainerMetalTable>> METAL_TABLE_CONTAINER = CONTAINERS.register("metal_table_container", () ->
        new ContainerType<>(ContainerMetalTable::new));

    private final IIntArray dataArray;

    protected final IRecipeType<? extends TechnicalityRecipe> recipeType = TechnicalityRecipe.METAL_TABLE_RECIPE_TYPE;

    //Server constructor
    public ContainerMetalTable(int id, PlayerInventory playerInventoryIn, IInventory tableInventory, IIntArray dataArray) {
        super(METAL_TABLE_CONTAINER.get(), id, tableInventory);

        assertInventorySize(tableInventory, 3);
        assertIntArraySize(dataArray, 5);

        this.dataArray = dataArray;

        this.addSlot(new RecipeInputSlot(playerInventoryIn.player.world, recipeType, inventory, 0, 62, 24));
        this.addSlot(new TechnicalityResultSlot(playerInventoryIn.player, inventory, 1, 134, 42));
        this.addSlot(new EnergyStorageSlot(inventory, 2, 62, 60));

        bindPlayerInventory(playerInventoryIn);

        this.trackIntArray(dataArray);
    }

    // Client Constructor
    public ContainerMetalTable(final int windowID, final PlayerInventory playerInv) {
        this(windowID, playerInv, new Inventory(3), new IntArray(5));
    }

    @OnlyIn(Dist.CLIENT)
    public int getCurrentInput() {
        return this.dataArray.get(2);
    }

    @OnlyIn(Dist.CLIENT)
    public int getNeededInput() {
        return this.dataArray.get(3);
    }

    @OnlyIn(Dist.CLIENT)
    public float getPowerPercentage() {
        return Math.min(1.0F, (float) getCurrentInput() / (float) getNeededInput()) * 100.0F;
    }

    public String getPowerPercentageFormatted() {
        return IProvider.PERCENTAGE_FORMAT.format(getPowerPercentage());
    }

    @OnlyIn(Dist.CLIENT)
    public float getProgressionScaled() {
        return Math.min(1.0F, (float) dataArray.get(0) / (float) dataArray.get(1));
    }

    @OnlyIn(Dist.CLIENT)
    public int getCurrentToolType() {
        return dataArray.get(4);
    }

    public void setCurrentToolType(ToolType toolType) {
        dataArray.set(4, toolType.getId());
    }

    @Override
    protected int maxTransferSlot() {
        //Prevent charging and output from being shift-clicked
        return 0;
    }

}

 

My Screen:

package com.wthemonkey.me.technicality.client.gui;

import com.mojang.blaze3d.systems.RenderSystem;
import com.wthemonkey.me.technicality.Technicality;
import com.wthemonkey.me.technicality.client.TechnicalityPacketHandler;
import com.wthemonkey.me.technicality.container.ContainerMetalTable;
import com.wthemonkey.me.technicality.items.tools.ToolType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.widget.button.AbstractButton;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

public class ScreenMetalTable extends ContainerScreen<ContainerMetalTable> {

    //TODO: Different processing types

    private ToolType type;

    private static final ResourceLocation TEXTURE = new ResourceLocation(Technicality.MOD_ID,
        "textures/gui/metal_table_container.png");

    public ScreenMetalTable(ContainerMetalTable screenContainer, PlayerInventory inv, ITextComponent titleIn) {
        super(screenContainer, inv, titleIn);

        this.guiLeft = 0;
        this.guiTop = 0;
        this.xSize = 176;
        this.ySize = 166;

        type = ToolType.fromID(screenContainer.getCurrentToolType());
    }

    @Override
    protected void init() {
        super.init();

        this.addButton(new ToolTypeButton(this.guiLeft + 93, this.guiTop + 57));
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
        RenderSystem.color4f(1.0f, 1.0f, 1.0f, 1.0f);
        assert this.minecraft != null;
        this.minecraft.getTextureManager().bindTexture(TEXTURE);
        this.blit(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize);

        final int renderHeight = (int) (14.0F * container.getPowerPercentage());
        this.blit(this.guiLeft + 66, this.guiTop + 43, 176, 0, 7, renderHeight);

        /*
         * start_x, start_y, pos_x, pos_y, width, height
         */
        final int renderWidth = (int) (38.0F * container.getProgressionScaled());
        this.blit(this.guiLeft + 85, this.guiTop + 46, 183, 0, renderWidth, 8);
    }

    @Override
    protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
        super.drawGuiContainerForegroundLayer(mouseX, mouseY);

        final int titleWidth = this.font.getStringWidth(this.title.getFormattedText());
        final int titleX = (this.xSize - titleWidth) / 2;
        this.font.drawString(this.title.getFormattedText(), titleX, 6.0f, 0x404040);

        this.font.drawString(new TranslationTextComponent("data.input_percent", container.getPowerPercentageFormatted())
            .getFormattedText(), 8.0f, 25.0f, 0x404040);

        for (Widget widget : this.buttons) {
            if (widget.isHovered()) {
                widget.renderToolTip(mouseX - this.guiLeft, mouseY - this.guiTop);
                break;
            }
        }
    }

    @Override
    public void render(int mouseX, int mouseY, float partialTicks) {
        this.renderBackground();
        super.render(mouseX, mouseY, partialTicks);
        this.renderHoveredToolTip(mouseX, mouseY);
    }

    @OnlyIn(Dist.CLIENT)
    public class ToolTypeButton extends AbstractButton {

        public ToolTypeButton(int xIn, int yIn) {
            super(xIn, yIn, 22, 22, "");
        }

        @Override
        public void renderButton(int p_renderButton_1_, int p_renderButton_2_, float p_renderButton_3_) {
            Minecraft.getInstance().getTextureManager().bindTexture(TEXTURE);
            RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);

            /*
             * start_x, start_y, pos_x, pos_y, width, height
             */
            final int resWidth = ScreenMetalTable.this.type.getId() * getWidth();
            this.blit(this.x, this.y, resWidth, 166, getWidth(), getHeight());
        }

        @Override
        public void onPress() {
            int id = ScreenMetalTable.this.type.getId() + 1;
            if (id >= ToolType.values().length) id = 0;
            ScreenMetalTable.this.type = ToolType.fromID(id);

            //Send update via packet
            TechnicalityPacketHandler.sendToolUpdateToServer(container, ScreenMetalTable.this.type);

            Technicality.LOGGER.info("Changed tool type to: " + ScreenMetalTable.this.type);
        }

    }

}

 

Kind regards

Edited by whereisthemonkey
Link to comment
Share on other sites

I assume that the value does not update when you reopen the gui. This is a shortcoming of IntReferenceHolder as it doesn't sync values on initial load if the holder isn't created when the container is opened. To counteract this, you would need to update the value, mark the holder as dirty, and update the value back to its intended value so it can be synced to the client on container open.

 

Also, I would recommend redoing your code again at some point as a good bit of what you've shown is outdated, shouldn't be used, or redundant.

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Hey. I created shield mod like kaupenjoe did on his course but blocking animation doesn't work. Forge 1.20.1. Here's some information: Mod structure image and code: https://ibb.co/z5Y1G26 https://www.online-java.com/crhUHmPoJt
    • i was playing forge modded singleplayer server then i added optifine to mods but it crashed with optifine is there anything to do without deleting optifine  crash report: https://paste.ee/p/Z13LO
    • package com.projectmushroom.lavapotions.item; import java.util.List;   import com.projectmushroom.lavapotions.LavaPotions;   import net.minecraft.core.BlockPos; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.stats.Stats; import net.minecraft.tags.FluidTags; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.AreaEffectCloud; import net.minecraft.world.entity.boss.enderdragon.EnderDragon; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemUtils; import net.minecraft.world.item.Items; import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.item.alchemy.Potions; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult;   public class ReinforcedBottle extends Item { public ReinforcedBottle(Item.Properties p_40648_) { super(p_40648_); }   public InteractionResultHolder<ItemStack> use(Level p_40656_, Player p_40657_, InteractionHand p_40658_) { List<AreaEffectCloud> list = p_40656_.getEntitiesOfClass(AreaEffectCloud.class, p_40657_.getBoundingBox().inflate(2.0D), (p_40650_) -> { return p_40650_ != null && p_40650_.isAlive() && p_40650_.getOwner() instanceof EnderDragon; }); ItemStack itemstack = p_40657_.getItemInHand(p_40658_); if (!list.isEmpty()) { AreaEffectCloud areaeffectcloud = list.get(0); areaeffectcloud.setRadius(areaeffectcloud.getRadius() - 0.5F); p_40656_.playSound((Player)null, p_40657_.getX(), p_40657_.getY(), p_40657_.getZ(), SoundEvents.BOTTLE_FILL_DRAGONBREATH, SoundSource.NEUTRAL, 1.0F, 1.0F); p_40656_.gameEvent(p_40657_, GameEvent.FLUID_PICKUP, p_40657_.blockPosition()); return InteractionResultHolder.sidedSuccess(this.turnBottleIntoItem(itemstack, p_40657_, new ItemStack(Items.DRAGON_BREATH)), p_40656_.isClientSide()); } else { HitResult hitresult = getPlayerPOVHitResult(p_40656_, p_40657_, ClipContext.Fluid.SOURCE_ONLY); if (hitresult.getType() == HitResult.Type.MISS) { return InteractionResultHolder.pass(itemstack); } else { if (hitresult.getType() == HitResult.Type.BLOCK) { BlockPos blockpos = ((BlockHitResult)hitresult).getBlockPos(); if (!p_40656_.mayInteract(p_40657_, blockpos)) { return InteractionResultHolder.pass(itemstack); }   if (p_40656_.getFluidState(blockpos).is(FluidTags.LAVA)) { p_40656_.playSound(p_40657_, p_40657_.getX(), p_40657_.getY(), p_40657_.getZ(), SoundEvents.BOTTLE_FILL, SoundSource.NEUTRAL, 1.0F, 1.0F); p_40656_.gameEvent(p_40657_, GameEvent.FLUID_PICKUP, blockpos); return InteractionResultHolder.sidedSuccess(this.turnBottleIntoItem(itemstack, p_40657_,(new ItemStack(LavaPotions.REINFORCED_BOTTLE), .LAVA)), p_40656_.isClientSide()); } } return InteractionResultHolder.pass(itemstack); } } }   protected ItemStack turnBottleIntoItem(ItemStack p_40652_, Player p_40653_, ItemStack p_40654_) { p_40653_.awardStat(Stats.ITEM_USED.get(this)); return ItemUtils.createFilledResult(p_40652_, p_40653_, p_40654_); } }   This is what I have so far, it's pretty much just the waterbottle code but I'm just trying to figure out how to get it to pick up lava rather than water
    • I never started my own server manually but I follow every single step i saw in a youtube video.
  • Topics

×
×
  • Create New...

Important Information

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