Jump to content

[1.9] Changing state of block 'resets' TileEntity attached to it


DARKHAWX

Recommended Posts

Hi there,

 

So I have a tile entity that upon 'crafting' will execute a countdown from 200 to 0, decreasing by one each time the tile entity is updated. At certain intervals through this countdown I change the blockstate of the attached block. However it appears that in doing so it will also 'reset' the countdown.

 

TileEntity:

 

package com.darkhawx.planck.main.tileEntities;

import com.darkhawx.planck.api.crafting.RecipeAltar;
import com.darkhawx.planck.main.blocks.BlockAltar;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import java.util.ArrayList;
import java.util.List;

public class TileAltar extends TileEntity implements ITickable {

    private List<ItemStack> items = new ArrayList<>();
    private ItemStack output;
    private int craftingTime;
    private boolean crafting;
    private float bloodAmount;

    public boolean isRecipe = false;

    public void update() {
        if (!worldObj.isRemote) {
            this.isRecipe = isRecipe();
            if (this.isRecipe) {
                //Something?
            }

            if (this.crafting) {
                this.craftingTime = 201;
                this.crafting = false;
            }
            else if (this.craftingTime < 0) {
                this.craftingTime = 0;
            } else if (this.craftingTime > 0) {
                switch (this.craftingTime) {
                    case 1:
                        BlockAltar.setState(worldObj, getPos(), BlockAltar.EnumAltarState.INACTIVE);
                        finishCraft(worldObj, getPos(), this);
                        System.out.println("inactive");
                        break;
                    case 25:
                        BlockAltar.setState(worldObj, getPos(), BlockAltar.EnumAltarState.END);
                        System.out.println("end");
                        break;
                    case 125:
                        BlockAltar.setState(worldObj, getPos(), BlockAltar.EnumAltarState.CRAFTING);
                        System.out.println("crafting");
                        break;
                    case 200:
                        BlockAltar.setState(worldObj, getPos(), BlockAltar.EnumAltarState.BLOOD);
                        System.out.println("blood");
                        break;
                }
                this.craftingTime--;
                System.out.println("CraftingTime: " + this.craftingTime);
            }
        }
    }

    public boolean isRecipe() {
        output = RecipeAltar.checkRecipe(items);
        if (output != null) {
            return true;
        }
        return false;
    }


    public static void craft(World worldIn, BlockPos pos, TileAltar altar) {
        if (altar.craftingTime == 0 && !altar.crafting) {
            System.out.println("blood: " + altar.bloodAmount);
            if (altar.bloodAmount >= altar.getRecipe().getBlood()) {
                System.out.println("craft");
                altar.crafting = true;
            }
        }
    }

    private static void finishCraft(World worldIn, BlockPos pos, TileAltar altar) {
        if (altar.getOutput() != null) {
            System.out.println("crafted");
            altar.bloodAmount = 0;
            altar.markDirty();
            if (!worldIn.isRemote) {
                EntityItem entity = new EntityItem(worldIn, pos.getX() + 0.5D, (double) pos.getY() + 1.1D, (double) pos.getZ() + 0.5D, altar.getOutput());
                entity.setVelocity(0.0D, 0.0D, 0.0D);
                worldIn.spawnEntityInWorld(entity);
            }
            altar.items.clear();
        }
    }

    public static boolean addItem(World worldObj, ItemStack item, TileAltar altar) {
        if (item != null) {
            altar.markDirty();

            if (worldObj != null) {
                IBlockState state = worldObj.getBlockState(altar.getPos());
                worldObj.notifyBlockUpdate(altar.getPos(), state, state, 3);
            }

            if (altar.items.size() <  {
                altar.items.add(item);
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    private void addItem(ItemStack item) {
        markDirty();
        worldObj.notifyBlockUpdate(this.getPos(), worldObj.getBlockState(this.getPos()), worldObj.getBlockState(this.getPos()), 3);
        if (items.size() <  {
            items.add(item);
        }
    }

    public static void removeItems(World worldIn, BlockPos pos, TileAltar altar) {
        System.out.println("removed");
        altar.markDirty();
        if (altar.getItems().size() != 0) {
            if (!worldIn.isRemote) {
                for (ItemStack item : altar.getItems()) {
                    EntityItem entity = new EntityItem(worldIn, pos.getX() + 0.5D, (double) pos.getY() + 1.1D, (double) pos.getZ() + 0.5D, item);
                    worldIn.spawnEntityInWorld(entity);
                }
            }
            altar.items.clear();
        }
    }

    public static void removeLastItem(World worldIn, BlockPos pos, TileAltar altar) {
        altar.markDirty();
        if (altar.getItems().size() != 0) {
            if (!worldIn.isRemote) {
                ItemStack item = altar.getItems().get(altar.getItems().size());
                EntityItem entity = new EntityItem(worldIn, pos.getX() + 0.5D, (double) pos.getY() + 1.1D, (double) pos.getZ() + 0.5D, item);
                worldIn.spawnEntityInWorld(entity);
            }
            altar.items.remove(altar.items.size());
        }
    }

//    @Override
//    public NBTTagCompound getUpdateTag() {
//        // getUpdateTag() is called whenever the chunkdata is sent to the
//        // client. In contrast getUpdatePacket() is called when the tile entity
//        // itself wants to sync to the client. In many cases you want to send
//        // over the same information in getUpdateTag() as in getUpdatePacket().
//        return writeToNBT(new NBTTagCompound());
//    }
//
//    @Override
//    public SPacketUpdateTileEntity getUpdatePacket() {
//        // Prepare a packet for syncing our TE to the client. Since we only have to sync the stack
//        // and that's all we have we just write our entire NBT here. If you have a complex
//        // tile entity that doesn't need to have all information on the client you can write
//        // a more optimal NBT here.
//        NBTTagCompound nbtTag = new NBTTagCompound();
//        this.writeToNBT(nbtTag);
//        return new SPacketUpdateTileEntity(getPos(), 1, nbtTag);
//    }

    public boolean isCrafting() {
        return this.craftingTime >= 0;
    }

    public List<ItemStack> getItems() {return this.items;}

    public ItemStack getOutput() {return this.output;}

    public float getBlood() {return this.bloodAmount;}

    public RecipeAltar getRecipe() {
        return RecipeAltar.getRecipe(items);
    }

    public int getCraftingTime() {
        return this.craftingTime;
    }

    public void addBlood(float bloodAmount) {
        this.bloodAmount += bloodAmount;
    }

    public static float getBloodForEntity(EntityLivingBase entity) {
        return entity.getMaxHealth() * 10.0F;
    }

    @Override
    public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) {
        // Here we get the packet from the server and read it into our client side tile entity
        this.readFromNBT(packet.getNbtCompound());
    }

    @Override
    public void readFromNBT(NBTTagCompound compound) {
        super.readFromNBT(compound);
        for (int i = 0; i < 8; i++) {
            if (compound.hasKey("input" + i)) {
                addItem(ItemStack.loadItemStackFromNBT(compound.getCompoundTag("input" + i)));
                //items.add(i, ItemStack.loadItemStackFromNBT(compound.getCompoundTag("input" + i)));
            }
        }
    }

    @Override
    public void writeToNBT(NBTTagCompound compound) {
        super.writeToNBT(compound);
        for (int i = 0; i < 8; i++) {
            if (items.size() > i) {
                NBTTagCompound tagCompound = new NBTTagCompound();
                ItemStack item = items.get(i);
                item.writeToNBT(tagCompound);
                compound.setTag("input" + i, tagCompound);
            }
        }
    }
}

 

 

How would I go about preventing this?

 

 

P.S: The items that have been currently added to the TE are rendered above it. Due to the way my code is setup it turns out that the finishCraft() method only gets ran server side (a tile entities worldObj is not remote), which means to the client the items haven't disappeared. How would I go about rectifying this? Would modifying the way data is stored in the nbt work? Or would I need to somehow tell the client that the items have disappeared?

 

P.P.S: The commented out NBT related methods were taken from some random tutorial ages ago. They seem to have some relevance to syncing data between client and server, however they are outdated and do not work.

No signature for you!

Link to comment
Share on other sites

override

doesRefresh

and return false.

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

Override

TileEntity#shouldRefresh

to return

oldState.getBlock() != newSate.getBlock()

. This way the

TileEntity

will only be recreated when the

Block

changes.

 

P.S: The items that have been currently added to the TE are rendered above it. Due to the way my code is setup it turns out that the finishCraft() method only gets ran server side (a tile entities worldObj is not remote), which means to the client the items haven't disappeared. How would I go about rectifying this? Would modifying the way data is stored in the nbt work? Or would I need to somehow tell the client that the items have disappeared?

 

P.P.S: The commented out NBT related methods were taken from some random tutorial ages ago. They seem to have some relevance to syncing data between client and server, however they are outdated and do not work.

 

The commented out methods aren't outdated, they're for 1.9.4.

 

If the client needs some data from the

TileEntity

to render your block, send it in the update (a.k.a description) packet.

 

In 1.9, override

TileEntity#getDescriptionPacket

to write the data that needs syncing to a compound tag and then create and return an

SPacketUpdateTileEntity

with the position and NBT. Override

TileEntity#onDataPacket

to read from the packet's NBT.

 

In 1.9.4, override

TileEntity#getUpdateTag

to write the data that needs syncing to a compound tag and return it. Override

TileEntity#getUpdatePacket

to create and return an

SPacketUpdateTileEntity

with the position and update tag. Override

TileEntity#onDataPacket

to read from the packet's NBT.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

override

doesRefresh

and return false.

Uh-oh, then the TE might never go away even when it should. I think Choonster is on the right track, and for some kinds of mods, one might even want more conditions controlling whether to replace the TE.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Link to comment
Share on other sites

Override

TileEntity#shouldRefresh

to return

oldState.getBlock() != newSate.getBlock()

. This way the

TileEntity

will only be recreated when the

Block

changes.

 

P.S: The items that have been currently added to the TE are rendered above it. Due to the way my code is setup it turns out that the finishCraft() method only gets ran server side (a tile entities worldObj is not remote), which means to the client the items haven't disappeared. How would I go about rectifying this? Would modifying the way data is stored in the nbt work? Or would I need to somehow tell the client that the items have disappeared?

 

P.P.S: The commented out NBT related methods were taken from some random tutorial ages ago. They seem to have some relevance to syncing data between client and server, however they are outdated and do not work.

 

The commented out methods aren't outdated, they're for 1.9.4.

 

If the client needs some data from the

TileEntity

to render your block, send it in the update (a.k.a description) packet.

 

In 1.9, override

TileEntity#getDescriptionPacket

to write the data that needs syncing to a compound tag and then create and return an

SPacketUpdateTileEntity

with the position and NBT. Override

TileEntity#onDataPacket

to read from the packet's NBT.

 

In 1.9.4, override

TileEntity#getUpdateTag

to write the data that needs syncing to a compound tag and return it. Override

TileEntity#getUpdatePacket

to create and return an

SPacketUpdateTileEntity

with the position and update tag. Override

TileEntity#onDataPacket

to read from the packet's NBT.

 

Thanks!

No signature for you!

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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I have done this now but have got the error:   'food(net.minecraft.world.food.FoodProperties)' in 'net.minecraft.world.item.Item.Properties' cannot be applied to                '(net.minecraftforge.registries.RegistryObject<net.minecraft.world.item.Item>)' public static final RegistryObject<Item> LEMON_JUICE = ITEMS.register( "lemon_juice", () -> new Item( new HoneyBottleItem.Properties().stacksTo(1).food( (new FoodProperties.Builder()) .nutrition(3) .saturationMod(0.25F) .effect(() -> new MobEffectInstance(MobEffects.DAMAGE_RESISTANCE, 1500), 0.01f ) .build() ) )); The code above is from the ModFoods class, the one below from the ModItems class. public static final RegistryObject<Item> LEMON_JUICE = ITEMS.register("lemon_juice", () -> new Item(new Item.Properties().food(ModFoods.LEMON_JUICE)));   I shall keep going between them to try and figure out the cause. I am sorry if this is too much for you to help with, though I thank you greatly for your patience and all the effort you have put in to help me.
    • I have been following these exact tutorials for quite a while, I must agree that they are amazing and easy to follow. I have registered the item in the ModFoods class, I tried to do it in ModItems (Where all the items should be registered) but got errors, I think I may need to revert this and figure it out from there. Once again, thank you for your help! 👍 Just looking back, I have noticed in your code you added ITEMS.register, which I am guessing means that they are being registered in ModFoods, I shall go through the process of trial and error to figure this out.
    • ♈+2349027025197ஜ Are you a pastor, business man or woman, politician, civil engineer, civil servant, security officer, entrepreneur, Job seeker, poor or rich Seeking how to join a brotherhood for protection and wealth here’s is your opportunity, but you should know there’s no ritual without repercussions but with the right guidance and support from this great temple your destiny is certain to be changed for the better and equally protected depending if you’re destined for greatness Call now for enquiry +2349027025197☎+2349027025197₩™ I want to join ILLUMINATI occult without human sacrificeGREATORLDRADO BROTHERHOOD OCCULT , Is The Club of the Riches and Famous; is the world oldest and largest fraternity made up of 3 Millions Members. We are one Family under one father who is the Supreme Being. In Greatorldrado BROTHERHOOD we believe that we were born in paradise and no member should struggle in this world. Hence all our new members are given Money Rewards once they join in order to upgrade their lifestyle.; interested viewers should contact us; on. +2349027025197 ۝ஐℰ+2349027025197 ₩Greatorldrado BROTHERHOOD OCCULT IS A SACRED FRATERNITY WITH A GRAND LODGE TEMPLE SITUATED IN G.R.A PHASE 1 PORT HARCOURT NIGERIA, OUR NUMBER ONE OBLIGATION IS TO MAKE EVERY INITIATE MEMBER HERE RICH AND FAMOUS IN OTHER RISE THE POWERS OF GUARDIANS OF AGE+. +2349027025197   SEARCHING ON HOW TO JOIN THE Greatorldrado BROTHERHOOD MONEY RITUAL OCCULT IS NOT THE PROBLEM BUT MAKE SURE YOU'VE THOUGHT ABOUT IT VERY WELL BEFORE REACHING US HERE BECAUSE NOT EVERYONE HAS THE HEART TO DO WHAT IT TAKES TO BECOME ONE OF US HERE, BUT IF YOU THINK YOU'RE SERIOUS MINDED AND READY TO RUN THE SPIRITUAL RACE OF LIFE IN OTHER TO ACQUIRE ALL YOU NEED HERE ON EARTH CONTACT SPIRITUAL GRANDMASTER NOW FOR INQUIRY +2349027025197   +2349027025197 Are you a pastor, business man or woman, politician, civil engineer, civil servant, security officer, entrepreneur, Job seeker, poor or rich Seeking how to join
    • Hi, I'm trying to use datagen to create json files in my own mod. This is my ModRecipeProvider class. public class ModRecipeProvider extends RecipeProvider implements IConditionBuilder { public ModRecipeProvider(PackOutput pOutput) { super(pOutput); } @Override protected void buildRecipes(Consumer<FinishedRecipe> pWriter) { ShapedRecipeBuilder.shaped(RecipeCategory.MISC, ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()) .pattern("SSS") .pattern("SSS") .pattern("SSS") .define('S', ModItems.COMPRESSED_DIAMOND.get()) .unlockedBy(getHasName(ModItems.COMPRESSED_DIAMOND.get()), has(ModItems.COMPRESSED_DIAMOND.get())) .save(pWriter); ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, ModItems.COMPRESSED_DIAMOND.get(),9) .requires(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()) .unlockedBy(getHasName(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()), has(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get())) .save(pWriter); ShapedRecipeBuilder.shaped(RecipeCategory.MISC, ModItems.COMPRESSED_DIAMOND.get()) .pattern("SSS") .pattern("SSS") .pattern("SSS") .define('S', Blocks.DIAMOND_BLOCK) .unlockedBy(getHasName(ModItems.COMPRESSED_DIAMOND.get()), has(ModItems.COMPRESSED_DIAMOND.get())) .save(pWriter); } } When I try to run the runData client, it shows an error:  Caused by: java.lang.IllegalStateException: Duplicate recipe compressed:compressed_diamond I know that it's caused by the fact that there are two recipes for the ModItems.COMPRESSED_DIAMOND. But I need both of these recipes, because I need a way to craft ModItems.COMPRESSED_DIAMOND_BLOCK and restore 9 diamond blocks from ModItems.COMPRESSED_DIAMOND. Is there a way to solve this?
  • Topics

×
×
  • Create New...

Important Information

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