Posted April 30, 20205 yr Client/server sync will be the death of me. I have a block with a tile entity, and a tile entity renderer bound to it. This tile entity has a single item stack as a pseudo-inventory and a fillLevel property. The renderer is supposed to render the item stack (if it's not empty) and then render another block inside this block with a state determined by the fillLevel. At one point, it was mostly working, except that after putting an item in, when the tick method would finish processing it and clear the item (set its item stack to an empty one), it would continue rendering the item. In my attempts to fix that, I somehow broke it more: now it won't render the fillLevel block anymore, either! Debug output from within the TER's render method runs, so it's definitely bound correctly; it just prints out the full item stack even after it should be cleared, which is why I thought (and still think) it's a server/client sync issue. What I don't understand is that if I remove the item "manually" (i.e. on a block activation), it correctly stops rendering, but if the tick method clears the item (using the same method as block activation does!), then it doesn't update. I've been debugging it for days, and I'm not getting anywhere. I discovered that the getUpdateTag and handleUpdateTag methods (which I thought were the bases of client/server sync) are only getting called once when the block is placed and then never again, even as methods are called that update the items or fillLevel. I even created a utility method that calls World#markAndNotifyBlock as well as marking the tile entity dirty -- I thought for SURE that would force a sync -- and it did nothing. Can someone please help me figure out where I'm going wrong? Below are my block, tile entity, renderer, and update helper classes (any questions about other classes referenced, please feel free to ask). ScarletAlchemyHelpers.java public class ScarletAlchemyHelpers { public static void updateTileEntity(TileEntity te) { World world = te.getWorld(); BlockState state = te.getBlockState(); BlockPos pos = te.getPos(); world.markAndNotifyBlock(pos, world.getChunk(pos.getX(), pos.getZ()), state, state, 3); te.markDirty(); } } ScarletCondenserTileEntity.java public class ScarletCondenserTileEntity extends TileEntity implements ITickableTileEntity, ISidedInventory { protected int fillLevel = 0; protected ItemStack inventory = ItemStack.EMPTY; public static final int MAX_FILL = 90; public ScarletCondenserTileEntity() { super(ScarletCondenserBlock.teType); } @Override @Nullable public SUpdateTileEntityPacket getUpdatePacket() { CompoundNBT nbtTagCompound = new CompoundNBT(); this.write(nbtTagCompound); return new SUpdateTileEntityPacket(this.pos, 42, nbtTagCompound); } @Override public void onDataPacket(NetworkManager network, SUpdateTileEntityPacket packet) { this.read(packet.getNbtCompound()); } @Override public CompoundNBT getUpdateTag() { CompoundNBT nbtTagCompound = new CompoundNBT(); this.write(nbtTagCompound); return nbtTagCompound; } @Override public void handleUpdateTag(CompoundNBT tag) { this.read(tag); } @Override public void read(CompoundNBT compound) { this.pos = new BlockPos(compound.getInt("x"), compound.getInt("y"), compound.getInt("z")); this.fillLevel = compound.getInt("fillLevel"); this.inventory = ItemStack.read(compound.getCompound("Item")); } @Override public CompoundNBT write(CompoundNBT compound) { ResourceLocation resourcelocation = TileEntityType.getId(this.getType()); if (resourcelocation == null) { throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!"); } else { compound.putString("id", resourcelocation.toString()); compound.putInt("x", this.pos.getX()); compound.putInt("y", this.pos.getY()); compound.putInt("z", this.pos.getZ()); compound.putInt("fillLevel", this.fillLevel); CompoundNBT item = new CompoundNBT(); compound.put("Item", this.inventory.write(item)); return compound; } } public int getFillLevel() { return this.fillLevel; } public int addSmoke(int amount) { int result = Math.min(amount, MAX_FILL - this.fillLevel); this.fillLevel += result; return result; } public int removeSmoke(int amount) { int result = Math.min(amount, this.fillLevel); this.fillLevel -= result; return result; } public int getSmokeState() { if (this.fillLevel <= 0) { return -1; } float smokeAge = 3.0f - (float) this.fillLevel * 3.0f / (float) MAX_FILL; return MathHelper.floor(smokeAge); } protected void collectSmoke(int amount) { Stream<BlockPos> surroundings = BlockPos.getAllInBox(this.pos.add(-1, -1, -1), this.pos.add(1, 1, 1)) .map(BlockPos::toImmutable); int realAmount = Math.min(MAX_FILL - this.fillLevel, amount); List<BlockPos> posList = surroundings.collect(Collectors.toList()); for (BlockPos bPos : posList) { if (bPos.equals(this.pos)) { continue; } TileEntity te = this.world.getTileEntity(bPos); if (!(te instanceof ISASmokeProvider)) { continue; } ISASmokeProvider provider = (ISASmokeProvider) te; if (realAmount > 0) { int taken = provider.removeSmoke(realAmount); realAmount -= taken; this.fillLevel += taken; } } } @Override public void tick() { // FIXME: Fill level and empty state not reflected in renderer :( if (!this.isEmpty()) { Pair<Integer, ItemStack> bestRecipe = ScarletCondenserRecipes.getMostExpensive(this.inventory); if (bestRecipe != null) { if (this.fillLevel < MAX_FILL) { this.collectSmoke(1); ScarletAlchemyHelpers.updateTileEntity(this); } if (this.fillLevel >= MAX_FILL) { int amountUsed = bestRecipe.getLeft(); if (this.inventory.getCount() > amountUsed) { this.inventory.shrink(amountUsed); } else { this.clear(); } this.getWorld().addEntity(new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, bestRecipe.getRight())); this.fillLevel -= MAX_FILL; ScarletAlchemyHelpers.updateTileEntity(this); } } } } @Override public int getSizeInventory() { return 1; } @Override public boolean isEmpty() { return this.inventory == null || this.inventory.isEmpty(); } @Override public ItemStack getStackInSlot(int index) { if (index != 0) { return ItemStack.EMPTY; } return this.inventory; } @Override public ItemStack decrStackSize(int index, int count) { if (index != 0) { return ItemStack.EMPTY; } this.inventory.shrink(count); return this.inventory; } @Override public ItemStack removeStackFromSlot(int index) { if (index != 0) { return ItemStack.EMPTY; } ItemStack temp = this.inventory; this.inventory = ItemStack.EMPTY; ScarletAlchemyHelpers.updateTileEntity(this); return temp; } @Override public void setInventorySlotContents(int index, ItemStack stack) { if (index == 0) { this.inventory = stack.copy(); ScarletAlchemyHelpers.updateTileEntity(this); } } public boolean addItem(ItemStack stack, PlayerEntity player) { Item item = stack.getItem(); if (!ScarletCondenserRecipes.hasRecipe(item)) { if (item == Items.AIR && !this.isEmpty() && player.isCrouching()) { World world = this.getWorld(); BlockPos pos = this.getPos(); world.addEntity( new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, this.inventory)); this.fillLevel = 0; this.clear(); ScarletAlchemyHelpers.updateTileEntity(this); return true; } return false; } else if (this.canInsertItem(0, stack, Direction.NORTH)) { ItemStack current = stack.copy(); current.grow(this.inventory.getCount()); this.setInventorySlotContents(0, current); if (!player.isCreative()) { stack.shrink(stack.getCount()); } ScarletAlchemyHelpers.updateTileEntity(this); return true; } return false; } @Override public boolean isUsableByPlayer(PlayerEntity player) { return true; } @Override public void clear() { this.inventory = ItemStack.EMPTY; ScarletAlchemyHelpers.updateTileEntity(this); } @Override public CompoundNBT serializeNBT() { return this.write(new CompoundNBT()); } @Override public void deserializeNBT(CompoundNBT nbt) { this.read(nbt); ; } @Override public int[] getSlotsForFace(Direction side) { return new int[] { 0 }; } @Override public boolean canInsertItem(int index, ItemStack itemStackIn, Direction direction) { if (index != 0) { return false; } if (this.isEmpty()) { return true; } int maxSize = this.inventory.getMaxStackSize(); return itemStackIn.isItemEqual(this.inventory) && itemStackIn.getCount() + this.inventory.getCount() <= maxSize; } @Override public boolean canExtractItem(int index, ItemStack stack, Direction direction) { if (index != 0) { return false; } return !this.isEmpty() && ItemStack.areItemStacksEqual(this.inventory, stack); } } ScarletCondenserTileEntityRenderer.java public class ScarletCondenserTileEntityRenderer extends TileEntityRenderer<ScarletCondenserTileEntity> { ItemEntity itemEnt = new ItemEntity(null, 0, 0, 0, ItemStack.EMPTY); double rotation = 0.0f; public ScarletCondenserTileEntityRenderer(TileEntityRendererDispatcher rendererDispatcherIn) { super(rendererDispatcherIn); } @Override public void render(ScarletCondenserTileEntity tileEntity, float partialTicks, MatrixStack matrixStack, IRenderTypeBuffer buffer, int combinedLight, int combinedOverlay) { matrixStack.push(); if (!tileEntity.isEmpty()) { // Logger.getLogger(ScarletAlchemy.MOD_ID).log(Level.WARNING, "THEDEBUGGER_RENDERER: Not empty = " + tileEntity.getStackInSlot(0)); matrixStack.push(); itemEnt.setWorld(tileEntity.getWorld()); itemEnt.setItem(tileEntity.getStackInSlot(0)); rotation = MathHelper.wrapDegrees(rotation + 0.025); matrixStack.translate(0.5d, 0.3d, 0.5d); matrixStack.rotate(Vector3f.YP.rotation((float) rotation)); Minecraft.getInstance().getRenderManager().getRenderer(itemEnt).render(itemEnt, 0.0f, partialTicks, matrixStack, buffer, combinedLight); matrixStack.pop(); } matrixStack.scale(0.98f, 0.98f, 0.98f); matrixStack.translate(0.01f, 0.01f, 0.01f); int smokeStateAge = tileEntity.getSmokeState(); if (smokeStateAge >= 0) { BlockState smokeState = ScarletAlchemyBlocks.scarlet_smoke.getDefaultState().with(ScarletSmokeBlock.AGE, smokeStateAge); Minecraft.getInstance().getBlockRendererDispatcher().renderBlock(smokeState, matrixStack, buffer, combinedLight, combinedOverlay, null); } matrixStack.pop(); } } ScarletCondenserBlock.java public class ScarletCondenserBlock extends Block implements SABlock, SATileEntityProvider, ISidedInventoryProvider { protected SABlockAbilities blockAbilities = new SABlockAbilities(this); public static TileEntityType<ScarletCondenserTileEntity> teType; public ScarletCondenserBlock() { super(Block.Properties.create(Material.GLASS).sound(SoundType.GLASS).notSolid()); this.setRegistryName(new ResourceLocation(ScarletAlchemy.MOD_ID, "scarlet_condenser")); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Override public boolean hasBlockItem() { return this.blockAbilities.hasBlockItem(); } @Override public BlockItem createBlockItem() { return this.blockAbilities.createBlockItem(new Item.Properties().maxStackSize(64)); } @Override public void registerItem(IForgeRegistry<Item> reg) { this.blockAbilities.registerItem(reg); } @OnlyIn(Dist.CLIENT) public float getAmbientOcclusionLightValue(BlockState state, IBlockReader worldIn, BlockPos pos) { return 1.0F; } public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) { return true; } public boolean causesSuffocation(BlockState p_229869_1_, IBlockReader p_229869_2_, BlockPos p_229869_3_) { return false; } public boolean isNormalCube(BlockState state, IBlockReader worldIn, BlockPos pos) { return false; } @Override public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) { TileEntity te = world.getTileEntity(pos); if (!(te instanceof ScarletCondenserTileEntity)) { return ActionResultType.PASS; } ScarletCondenserTileEntity scTileEntity = (ScarletCondenserTileEntity) te; ItemStack stack = player.getHeldItem(hand); if (scTileEntity.addItem(stack, player)) { return ActionResultType.CONSUME; } return ActionResultType.PASS; } @Override public void registerTileEntity(IForgeRegistry<TileEntityType<? extends TileEntity>> reg) { teType = TileEntityType.Builder.create(() -> new ScarletCondenserTileEntity(), this).build(null); teType.setRegistryName(this.getRegistryName()); reg.register(teType); } @Override public TileEntity createTileEntity(final BlockState state, final IBlockReader world) { return new ScarletCondenserTileEntity(); } @Override public ISidedInventory createInventory(BlockState state, IWorld world, BlockPos pos) { TileEntity te = world.getTileEntity(pos); if (te != null && te instanceof ScarletCondenserTileEntity) { return (ScarletCondenserTileEntity) te; } return null; } } Whatever Minecraft needs, it is most likely not yet another tool tier.
April 30, 20205 yr 1 hour ago, diesieben07 said: Before you do anything else: Stop using IInventory.It is old and deprecated. Use IItemHandler. @diesieben07 IItemHandler is not a suitable replacement for IInventory if you are using a GUI - where you have container Slots which needs to communicate with the parent TileEntity (via markDirty()). I think there is nothing wrong with IInventory if you use it properly. IItemHandler has some useful methods but is not intended to be a drop in replacement for IInventory. @IceMetalPunkYou might find these working examples helpful https://github.com/TheGreyGhost/MinecraftByExample mbe20, mbe21 for synchronising tileentity data mbe30 for containers -TGG
April 30, 20205 yr Slot.onSlotChanged calls IInventory.markDirty, but SlotItemHandler doesn't. This means that the parent TileEntity isn't informed when a slot has poked around in the container. I presume that this is important because Vanilla does a lot of it from a variety of places. I agree with your comments about capability, composition vs inheritance, and that you can use IItemHandler for a lot more than just TileEntity-based containers. The only reason I see not to use it is communication back to the parent TileEntity which it doesn't do properly. Perhaps this could be addressed by modifying or extending SlotItemHandler to give it a lambda function for dirty notification, but this is currently not the case and it's not clear that ItemStackHandler.onContentsChanged is called in all cases that Slot.onSlotChanged is called.
April 30, 20205 yr When I search for Slot#onSlotChanged I find it being called from two important vanilla base classes Slot class: putStack and onTake Container class: slotClick and mergeItemStack Perhaps I'll try modifying SlotItemHandler to perform the notification via onSlotChanged and see if it makes any practical difference vs onContentsChanged. The other callbacks in IInventory don't appear to be important unless you're extending vanilla containers. -TGG
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.