Jump to content

[1.12.1]TileEntity how do I sync data between server and client


GiantNuker

Recommended Posts

Hi, I'm still working on the portals for my botania addon, This time, the problem is that data is not syncing between the server and client. when I activate a portal - you can go through it, but none of the animations show up.

here is my source code:

Spoiler

package mods.giantnuker.botaniatweaks.tile;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Nonnull;

import mods.giantnuker.backslash.RandUtil;
import mods.giantnuker.backslash.block.Schematic;
import mods.giantnuker.backslash.block.Schematic.StatePos;
import mods.giantnuker.backslash.block.SchematicUtil;
import mods.giantnuker.botaniatweaks.BTConfig;
import mods.giantnuker.botaniatweaks.BTMod;
import mods.giantnuker.botaniatweaks.block.BlockPortalCore;
import mods.giantnuker.javautil.Pair;
import mods.giantnuker.javautil.PairList;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
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.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeChunkManager;
import vazkii.botania.api.state.BotaniaStateProps;
import vazkii.botania.api.state.enums.AlfPortalState;
import vazkii.botania.api.state.enums.LivingRockVariant;
import vazkii.botania.api.state.enums.LivingWoodVariant;
import vazkii.botania.api.wand.IWandBindable;
import vazkii.botania.client.core.handler.HUDHandler;
import vazkii.botania.common.Botania;
import vazkii.botania.common.block.ModBlocks;

public class TilePortalCore extends TilePylonUser implements ITickable, IWandBindable {
	public BlockPos boundTo;
	public AlfPortalState state = AlfPortalState.OFF;
	public static ForgeChunkManager.Ticket chunkloadTicket;
	public int ticksOpen;
	public List<Entity> inPortal = new ArrayList();
	public boolean depower;
	public static final Schematic shape = new Schematic().add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
			new BlockPos(-1, 0, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(1, 0, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(2, 1, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(-2, 1, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(2, 3, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(-2, 3, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(-1, 4, 0))
			.add(ModBlocks.livingrock.getDefaultState().withProperty(BotaniaStateProps.LIVINGROCK_VARIANT, LivingRockVariant.BRICK), 
					new BlockPos(1, 4, 0))
			.add(ModBlocks.dreamwood.getDefaultState().withProperty(BotaniaStateProps.LIVINGWOOD_VARIANT, LivingWoodVariant.FRAMED), 
					new BlockPos(-2, 2, 0))
			.add(ModBlocks.dreamwood.getDefaultState().withProperty(BotaniaStateProps.LIVINGWOOD_VARIANT, LivingWoodVariant.FRAMED), 
					new BlockPos(2, 2, 0))
			.add(ModBlocks.dreamwood.getDefaultState().withProperty(BotaniaStateProps.LIVINGWOOD_VARIANT, LivingWoodVariant.PATTERN_FRAMED), 
					new BlockPos(0, 4, 0))
			.add(BTMod.dreamyPortal.getDefaultState(), new BlockPos(0, 0, 0))
			.add(SchematicUtil.getRect(Blocks.AIR.getDefaultState(), new BlockPos(2, 2, 0)).modToPos(new BlockPos(-1, 1, 0)))
			.cleanup();
	@Override
	public void update() {
		if (world.getBlockState(getPos()) == null) return;
		if (this.getStateByShape() == AlfPortalState.OFF) {
			severConnection();
			if (getBound() != null)getBound().severConnection();
			return;
		}
		updateState();
		if(state == AlfPortalState.OFF) {
			ticksOpen = 0;
			pylon_act = TileCrystalPylon.EnumActivation.OFF;
		} else if (depower) {
			if (getBound() != null)getBound().depower = true;
			if (ticksOpen > 100) ticksOpen = 100;
			if (ticksOpen < 40 && pylon_act != TileCrystalPylon.EnumActivation.CHANNEL_IN) {
				pylon_act = TileCrystalPylon.EnumActivation.CHANNEL_IN;
				updatePylons();
			}
			giveMana(BTConfig.portalInitCost / 150);
			ticksOpen--;
			if (ticksOpen <= 0) {
				if (pylon_act != TileCrystalPylon.EnumActivation.OFF) {
					pylon_act = TileCrystalPylon.EnumActivation.OFF;
					updatePylons();
				}
				depower = false;
				setState(true, false);
				chunkload(false);
			}
		} else if (ticksOpen < 80) {
			if (ticksOpen < 1)world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.ENTITY_GUARDIAN_ATTACK, SoundCategory.BLOCKS, 5, 5, true);
			if (ticksOpen < 40 && pylon_act != TileCrystalPylon.EnumActivation.CHANNEL_OUT) {
				pylon_act = TileCrystalPylon.EnumActivation.CHANNEL_OUT;
				updatePylons();
			} else if (ticksOpen > 40 && pylon_act != TileCrystalPylon.EnumActivation.CHANNEL_LIGHTSWIRL_OUT) {
				pylon_act = TileCrystalPylon.EnumActivation.CHANNEL_LIGHTSWIRL_OUT;
				updatePylons();
			}
			ticksOpen++;
			int use = useMana(BTConfig.portalInitCost / 80);
			if (use > 0) {
				pylon_act = TileCrystalPylon.EnumActivation.OFF;
				updatePylons();
				for (int i = 0; i < 10; i++) {
					blockParticle();
				}
			}
		} else {
			state = getStateByShape();
			if (pylon_act != TileCrystalPylon.EnumActivation.SWIRLING_OUT) {
				pylon_act = TileCrystalPylon.EnumActivation.SWIRLING_OUT;
				updatePylons();
			}
			ticksOpen++;
			if (getBound() == null) {
				severConnection();
				setState(false, false);
				return;
			} else {
				List<Entity> ents = world.getEntitiesWithinAABB(Entity.class, getTeleportAABB());
				List<Entity> entsp = world.getEntitiesWithinAABB(Entity.class, getTeleportAABB());
				List<Entity> a = new ArrayList();
				a.addAll(inPortal);
				for (Entity e : a) {
					if (!entsp.contains(e)) inPortal.remove(e);
				}
				if (ents.size() > 0) updatePylons();
				for (Entity e : ents) {
					if (inPortal.contains(e)) continue;
					double x = (e.posX
							- pos.getX())
							+ boundTo.getX(),
							y = (e.posY - pos.getY()) + boundTo.getY(),
							z = (e.posZ - pos.getZ()) + boundTo.getZ();
					AxisAlignedBB aabb = e.getEntityBoundingBox();
					int charge = (int) (((aabb.maxX - aabb.minX) * BTConfig.portalEntityBBBCost) + ((aabb.maxZ - aabb.minZ) * BTConfig.portalEntityBBBCost) + ((aabb.maxY - aabb.minY) * BTConfig.portalEntityBBBCost) + (RandUtil.getDistance(pos, boundTo) * BTConfig.portalPerBlockCost));
					System.out.println("chg " + charge + " dst " + RandUtil.getDistance(pos, boundTo));
					if (getUseableMana() >= charge) {
						useMana(charge);
						e.setPositionAndUpdate(x, y, z);
						inPortal.add(e);
						getBound().inPortal.add(e);
					}
				}
			}
		}
	}
	public TilePortalCore getBound() {
		if (boundTo == null) return null;
		return (TilePortalCore) world.getTileEntity(boundTo);
	}
	@Override
	public AxisAlignedBB getRenderBoundingBox() {
		return super.getRenderBoundingBox().grow(4);
	}
	public AxisAlignedBB getPortalAABB() {
		AxisAlignedBB aabb = new AxisAlignedBB(-1.5, 1, 0, 2.5, 4, 1);
		if(state == AlfPortalState.ON_X)
			aabb = new AxisAlignedBB(0, 1, -1.5, 1, 4, 2.5);

		return aabb;
	}
	public AxisAlignedBB getTeleportAABB() {
		AxisAlignedBB aabb = new AxisAlignedBB(pos.add(-1, 1, 0), pos.add(2, 4, 1));
		if(state == AlfPortalState.ON_X)
			aabb = new AxisAlignedBB(pos.add(0, 1, -1), pos.add(1, 4, 2));

		return aabb;
	}
	public AlfPortalState getStateByShape() {
		Map<EnumFacing, Schematic> m = shape.createRotations();
		Schematic shapeX = m.get(EnumFacing.SOUTH);
		shapeX.modToPos(pos);
		Schematic shapeZ = m.get(EnumFacing.EAST);
		shapeZ.modToPos(pos);
		int states = 0;
		for (StatePos s : shapeX.states) {
			if (s.state.equals(world.getBlockState(s.pos))) states++;
			else if(s.state.getBlock() == BTMod.dreamyPortal) states++;
		}
		if (states == shapeX.states.size()) return AlfPortalState.ON_X;
		states = 0;
		for (StatePos s : shapeZ.states) {
			if (s.state == world.getBlockState(s.pos)) states++;
			else if(s.state.getBlock() == BTMod.dreamyPortal) states++;
		}
		if (states == shapeZ.states.size()) return AlfPortalState.ON_Z;
		return AlfPortalState.OFF;
	}
	public boolean onWanded(boolean sneaking) {
		boolean bound = world.getBlockState(getPos()).getValue(BlockPortalCore.BOUND);
		if(bound && state == AlfPortalState.OFF && !sneaking) {
			chunkload(true);
						updatePylons();
						if (getUseableMana() < BTConfig.portalInitCost) {
							blockParticle();
							return true;
						}
					state = getStateByShape();
					getBound().state = getBound().getStateByShape();
					return true;
		} else if(bound && state == AlfPortalState.OFF && sneaking) {
			severConnection();
			return true;
		} else if(bound && (state == AlfPortalState.ON_X || state == AlfPortalState.ON_Z) && sneaking) {
			depower = true;
			return true;
		}
		return false;
	}
	
	private void blockParticle() {
		Botania.proxy.wispFX(pos.getX(), pos.getY(), pos.getZ(), 200, 200, 200, 1 + new Random().nextInt(3), 0, 0.5F, 0);
	}
	public void renderHUD(Minecraft mc, ScaledResolution res, World world, BlockPos pos) {
		int color = new Color(90, 205, 116).getRGB();
		String text = I18n.format(BTMod.dreamyPortal.getUnlocalizedName() + ".name");
		int x = res.getScaledWidth() / 2 - mc.fontRenderer.getStringWidth(text) / 2;
		int y = res.getScaledHeight() / 2;
		x = res.getScaledWidth() / 2 - mc.fontRenderer.getStringWidth(text) / 2;
		y -= 1;
		mc.fontRenderer.drawString(text, x, y, color);
		color = Color.BLUE.getRGB();
		text = I18n.format(BTMod.MODID + ".text.unbound");
		if (boundTo != null) {
			text = I18n.format(BTMod.MODID + ".text.bound");
			text += " X:" + boundTo.getX();
			text += " Y:" + boundTo.getY();
			text += " Z:" + boundTo.getZ();
		}
		y += 20;
		x = res.getScaledWidth() / 2 - mc.fontRenderer.getStringWidth(text) / 2;
		y -= 1;
		mc.fontRenderer.drawString(text, x, y, color);
		color = Color.GREEN.getRGB();
		if (state == AlfPortalState.OFF) {
			HUDHandler.renderManaBar(x, y + 20, color, 1F, getUseableMana(), BTConfig.portalInitCost);
		}
	}
	@Override
	public BlockPos getBinding() {
		return boundTo;
	}
	@Override
	public boolean canSelect(EntityPlayer player, ItemStack wand, BlockPos pos, EnumFacing side) {
		return player.getEntityWorld().getBlockState(pos) == BTMod.dreamyPortal.getDefaultState() && ((TilePortalCore)world.getTileEntity(pos)).getStateByShape() != AlfPortalState.OFF;
	}
	@Override
	public boolean bindTo(EntityPlayer player, ItemStack wand, BlockPos pos, EnumFacing side) {
		if (canSelect(player, wand, pos, side)) {
			boundTo = pos;
			chunkload(true);
			getBound().chunkload(true);
			setState(true, false);
			NBTTagCompound nbt = world.getTileEntity(this.boundTo).writeToNBT(new NBTTagCompound());
			getBound().setState(boundTo != null, false);
			getBound().boundTo = this.pos;
			markDirty();
			getBound().markDirty();
			chunkload(false);
			getBound().chunkload(false);
			return true;
		}
		return false;
	}
	
	public void chunkload(boolean load) {
		//if (!world.isRemote && chunkloadTicket != null) {
		//	if (load) {
		//		ForgeChunkManager.forceChunk(chunkloadTicket, new ChunkPos(pos));
		//	}
		//	else ForgeChunkManager.unforceChunk(chunkloadTicket, new ChunkPos(pos));
		//}
	}
	
	@Nonnull
	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
		super.writeToNBT(nbt);
		if (boundTo != null) {
			nbt.setInteger("bindX", boundTo.getX());
			nbt.setInteger("bindY", boundTo.getY());
			nbt.setInteger("bindZ", boundTo.getZ());
			nbt.setBoolean("bound", true);
		}
		
		nbt.setInteger("state", state.ordinal());
		nbt.setInteger("time", ticksOpen);
		nbt.setBoolean("depower", depower);
		return nbt;
	}
	
	@Nonnull
	public void readFromNBTB(NBTTagCompound nbt) {
		if (nbt.getBoolean("bound")) boundTo = new BlockPos(nbt.getInteger("bindX"), nbt.getInteger("bindY"), nbt.getInteger("bindZ"));
		state = AlfPortalState.values()[nbt.getInteger("state")];
		ticksOpen = nbt.getInteger("time");
		depower = nbt.getBoolean("depower");
	}
	@Nonnull
	@Override
	public void readFromNBT(NBTTagCompound nbt) {
		super.readFromNBT(nbt);
		readFromNBTB(nbt);
		
	}
	public void breakBlock() {
		if (pylon_act != TileCrystalPylon.EnumActivation.OFF) {
			pylon_act = TileCrystalPylon.EnumActivation.OFF;
			updatePylons();
		}
		chunkload(false);
		
		if (getBound() == null) return;
		getBound().chunkload(false);
		if (world.getBlockState(boundTo).getBlock() == BTMod.dreamyPortal) {
			setState(false, false);
		}
	}
	
	public void severConnection() {
		setState(false, false);
		updatePylons();
		boundTo = null;
		if (getBound() == null) return;
		getBound().chunkload(false);
		if (world.getBlockState(boundTo).getBlock() == BTMod.dreamyPortal) {
			setState(false, false);
			getBound().updatePylons();
		}
	}
	
	public void setState(boolean bound, boolean on) {
		world.setBlockState(pos, BTMod.dreamyPortal.getDefaultState()
				.withProperty(BlockPortalCore.BOUND, bound)
				.withProperty(BlockPortalCore.ON, on));
		((TilePortalCore) world.getTileEntity(pos)).readFromNBTB(this.writeToNBT(new NBTTagCompound()));
	}
	
	public void updateState() {
		if (world.getBlockState(pos).getValue(BlockPortalCore.BOUND) != (getBound() != null) ||
			world.getBlockState(pos).getValue(BlockPortalCore.ON) != (state != AlfPortalState.OFF))
			setState(getBound() != null, state != AlfPortalState.OFF);
		else if (getBound() != null && getBound().state != state) {
			state = getBound().state;
			updateState();
		} else if (getBound() != null && getBound().getBound() == null) {
			boundTo = null;
			updateState();
		}
	}
	
	
	@Override
	public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) {
		super.onDataPacket(net, packet);
		readFromNBT(packet.getNbtCompound());
		updatePylons();
	}
}

 

What I think is happening is, mana is handled on the server(I think) so there will never be any on the client, right?

Do I need to notify every client when a portal activates/deactivates?

What do I have to do?

 

If you can tell me Thanks! :D

Link to comment
Share on other sites

12 minutes ago, GiantNuker said:

Do I need to notify every client when a portal activates/deactivates?

Yes, you should notify it every time something client-related changes.

Call World::notifyBlockUpdate with the current blockstate for both old and new for that.

Edited by Abastro

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Link to comment
Share on other sites

6 minutes ago, Abastro said:

Yes, you should notify it every time something client-related changes.

Call World::notifyBlockUpdate with the current blockstate for both old and new for that.

Thanks, I thought I had to send a packet to every client player :) 

EDIT: Trying to update the TE, not the block.

Edited by GiantNuker
Link to comment
Share on other sites

I'm not sure about the intricacies of botania, but if you want to update other client-rendering things like having particles on tile entities usually you need a packet. 

 

You want to write two messages. 

 

1. A message notifying the players in the area that the portal is active. (Which will then client-side show the particles.)

2. A message notifying the server that the player wants to recieve an update on whether the portal is active or not.

 

then in the custom TileEntity class you do something like.

 

    @Override
    public void onLoad() {
        if (worldObj.isRemote) {
            Your update message
        }
    }

to tell the client you want the portal active. 

 

When your block activates you want to make a sendToAllAround message that tells people around it that the portal is active. 

 

If you'd add that then players who walk from afar and load your TE will know the portal is active, and players who are near when it activates will know it's active. You don't have to send a packet with every particle, just tell the client it's active and make it use particles from there. 

Link to comment
Share on other sites

9 minutes ago, oldcheese said:

I'm not sure about the intricacies of botania, but if you want to update other client-rendering things like having particles on tile entities usually you need a packet. 

 

You want to write two messages. 

 

1. A message notifying the players in the area that the portal is active. (Which will then client-side show the particles.)

2. A message notifying the server that the player wants to recieve an update on whether the portal is active or not.

 

then in the custom TileEntity class you do something like.

 


    @Override
    public void onLoad() {
        if (worldObj.isRemote) {
            Your update message
        }
    }

to tell the client you want the portal active. 

 

When your block activates you want to make a sendToAllAround message that tells people around it that the portal is active. 

 

If you'd add that then players who walk from afar and load your TE will know the portal is active, and players who are near when it activates will know it's active. You don't have to send a packet with every particle, just tell the client it's active and make it use particles from there. 

I want to send it when the state updates.

Link to comment
Share on other sites

Christ. This isn't that complicated folks.

 

Step 1: Override these methods

Step 2: Call these methods whenever the data changes and the client needs to know about 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

  • 8 months later...
On 9/22/2017 at 9:15 PM, Draco18s said:

Christ. This isn't that complicated folks.

 

Step 1: Override these methods

Step 2: Call these methods whenever the data changes and the client needs to know about it

Hello, I have similar problem with client server synchronization, it's just I want to update energy in my TE to client every tick, but I do not find there code can update custom data in TE.

Link to comment
Share on other sites

25 minutes ago, Ice2670 said:

Hello, I have similar problem with client server synchronization, it's just I want to update energy in my TE to client every tick, but I do not find there code can update custom data in TE.

Don't bump an over-half-year-old thread. Just make your own issue thread with what you've tried.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Link to comment
Share on other sites

2 minutes ago, Abastro said:

Don't bump an over-half-year-old thread. Just make your own issue thread with what you've tried.

^^^ Very good advice, please never comment on existing threads with a new issue.

 

33 minutes ago, Ice2670 said:

Hello, I have similar problem with client server synchronization, it's just I want to update energy in my TE to client every tick, but I do not find there code can update custom data in TE.

@Ice2670 Since you haven't made a new thread yet, and this is a common issue, I'll show how I do it. This is my personal preference, and it works well for me, feel free to adapt it. My personal preference is to have a superclass that handles all my syncing & capability stuff and have all my TileEntities extend it. My class is called TileEntityBase and you can view it here. It is adapted from canitzp's mod MetalWorks.

The actual Syncing packets are registered here, and the class is here.

To get my energy capability I simply Override getEnergy() in my superclass.

You can see an examples of how I use TileEntityBase here, here and here.

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

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



×
×
  • Create New...

Important Information

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