Jump to content

Recommended Posts

Posted

Hi,

 

im currently trying to sync a forge Energy Value between the server and client for gui porpuses.

I got the tip to do it like the Vanilla Furnace to cache the value in the container and override detectandsendChanges and updateProgressBar

I think im missing something obvious, because detectAndSendChanges doesnt even get called :/

This are the aprts of my container:

 

public class ContainerCharger extends Container
{
private TileEntityCharger te;	
private int energy;

public ContainerCharger(IInventory playerInventory, TileEntityCharger te)
{
	this.te = te;

	// This container references items out of our own inventory (the 9 slots we hold ourselves)
        // as well as the slots from the player inventory so that the user can transfer items between
        // both inventories. The two calls below make sure that slots are defined for both inventories.
        addOwnSlots();
        addPlayerSlots(playerInventory);
}

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

	for(int i = 0; i < this.listeners.size(); i++)
	{
		IContainerListener icontainerlistener = (IContainerListener)this.listeners.get(i);

		if(this.energy != te.getCapability(CapabilityEnergy.ENERGY, null).getEnergyStored())
		{
			icontainerlistener.sendProgressBarUpdate(this, this.energy, 
                                this.te.getCapability(CapabilityEnergy.ENERGY, null).getEnergyStored());
		}
	}		
	this.energy = this.te.getCapability(CapabilityEnergy.ENERGY, null).getEnergyStored();
}

@SideOnly(Side.CLIENT)
    public void updateProgressBar(int id, int data)
    {
        ((BaseEnergyStorage)this.te.getCapability(CapabilityEnergy.ENERGY, null)).setEnergyStored(data);
    }

Posted

Sorry for not giving all inormation, i dont really know what you all need for this:

GuiHandler:

public class GuiHandler implements IGuiHandler
{
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) 
{
	BlockPos pos = new BlockPos(x, y, z);
	switch(ID)
	{
		case 1:
		{
			TileEntity te = world.getTileEntity(pos);
	        if (te instanceof TileEntityCharger) 
	        {
	            return new ContainerCharger(player.inventory, (TileEntityCharger) te);
	        }
		}
		default:
		{
			return null;
		}
	}
}

@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
	BlockPos pos = new BlockPos(x, y, z);
	switch(ID)
	{
	case 1:
	{
		TileEntity te = world.getTileEntity(pos);
        if (te instanceof TileEntityCharger) 
        {
        	TileEntityCharger containerTileEntity = (TileEntityCharger) te;
            return new GuiCharger(containerTileEntity, new ContainerCharger(player.inventory, containerTileEntity));
        }
	}
	default:
	{
		return null;
	}
}
}
}

 

and the part of the BlockCharger:

 

public static final int GUI_ID = 1;

.....


@Override
    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side,
                float hitX, float hitY, float hitZ) 
{
        // Only execute on the server
        if (world.isRemote)
        {
            return true;
        }
        TileEntity te = world.getTileEntity(pos);
        if (!(te instanceof TileEntityCharger)) 
        {
            return false;
        }
        player.openGui(MattechBiogas.instance, GUI_ID, world, pos.getX(), pos.getY(), pos.getZ());
        return true;
    }

Posted

First the client and server values are still not synced, client is 0 server is like it should be.

And they i placed a logger in my override method and it didnt print anything :/

Posted

Here you go:

@Mod(modid = MattechBiogas.MODID, name = MattechBiogas.NAME, version = MattechBiogas.VERSION)
public class MattechBiogas
{
    public static final String MODID = "mattechbiogas";
    public static final String NAME = "Mattech Biogas";
    public static final String VERSION = "0.1";
    
    @Instance
    public static MattechBiogas instance = new MattechBiogas();
    
    @SidedProxy(clientSide="mattizin.mattechbiogas.proxy.ClientProxy", serverSide="mattizin.mattechbiogas.proxy.ServerProxy")
    public static CommonProxy proxy;
    
    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
    	proxy.preInit(event);
    }
    
    @EventHandler
    public void init(FMLInitializationEvent event)
    {
    	proxy.init(event);
    }
    
    @EventHandler
    public void postInit(FMLPostInitializationEvent event)
    {
    	proxy.postInit(event);
    }
}

 

public class BlockCharger extends BlockMattech implements ITileEntityProvider
{
public static final PropertyDirection FACING = PropertyDirection.create("facing");
public static final int GUI_ID = 1;

public BlockCharger()
{
	super(Material.IRON, "blockCharger");
	setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
}


@Override
    public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) 
{
        world.setBlockState(pos, state.withProperty(FACING, FacingUtil.getFacingFromEntity(pos, placer)), 2);
    }

@Override
    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side,
                float hitX, float hitY, float hitZ) 
{
        // Only execute on the server
        if (world.isRemote)
        {
            return true;
        }
        TileEntity te = world.getTileEntity(pos);
        if (!(te instanceof TileEntityCharger)) 
        {
            return false;
        }
        player.openGui(MattechBiogas.instance, GUI_ID, world, pos.getX(), pos.getY(), pos.getZ());
        return true;
    }

@Override
    public IBlockState getStateFromMeta(int meta) 
{
        return getDefaultState().withProperty(FACING, EnumFacing.getFront(meta & 7));
    }

    @Override
    public int getMetaFromState(IBlockState state) 
    {
        return state.getValue(FACING).getIndex();
    }

    @Override
    protected BlockStateContainer createBlockState() 
    {
        return new BlockStateContainer(this, FACING);
    }

//----START ITileEntityProvider---//
@Override
public TileEntity createNewTileEntity(World worldIn, int meta) 
{
		return new TileEntityCharger();
}
//----END ITileEntityProvider---//
}

Posted

i thought that is the purpose of proxys :o

Here you go:

public class CommonProxy 
{
public void preInit(FMLPreInitializationEvent event)
{
	ModBlocks.registerBlocks();
	ModItems.registerItems();
	ModTileEntities.registerTileEntities();
}

    public void init(FMLInitializationEvent event)
    {
    	NetworkRegistry.INSTANCE.registerGuiHandler(MattechBiogas.instance, new GuiHandler());
    }
    
    public void postInit(FMLPostInitializationEvent event)
    {
    	
    }
}

 

public class ClientProxy extends CommonProxy
{
@Override
public void preInit(FMLPreInitializationEvent event) 
{
	super.preInit(event); 

	MattechBiogasModelManager.registerBlockModels();
}

@Override
public void init(FMLInitializationEvent event) 
{
	super.init(event);
}

@Override
public void postInit(FMLPostInitializationEvent event) 
{
	super.postInit(event);
}
}

 

public class ServerProxy extends CommonProxy 
{
@Override
public void preInit(FMLPreInitializationEvent event) 
{
	super.preInit(event);
}

@Override
public void init(FMLInitializationEvent event) 
{
	super.init(event);
}

@Override
public void postInit(FMLPostInitializationEvent event) 
{
	super.postInit(event);
}
}

 

 

 

Does not implementing ITileEntityProvider change anything or is it just style wise?

Posted

i thought that is the purpose of proxys :o

 

No, the purpose of proxies is to allow for code that only exists on one side to have a place to live.

 

Predominantly you need:

CommonProxy: contains empty stub methods that do nothing

ClientProxy: contains all client-side-only code

 

The "server proxy" has no reason for existing at all because anything you might ever want to do there must happen on the client during SSP which in your proxy setup, won't happen.

 

Does not implementing ITileEntityProvider change anything or is it just style wise?

 

The methods that ITileEntityProvider declares are already declared in the Block class.

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.

Posted

This is my whole Container:

 

public class ContainerCharger extends Container
{
private TileEntityCharger te;	
private int energy;

public ContainerCharger(IInventory playerInventory, TileEntityCharger te)
{
	this.te = te;

	// This container references items out of our own inventory (the 9 slots we hold ourselves)
        // as well as the slots from the player inventory so that the user can transfer items between
        // both inventories. The two calls below make sure that slots are defined for both inventories.
        addOwnSlots();
        addPlayerSlots(playerInventory);
}

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

	for(int i = 0; i < this.listeners.size(); i++)
	{
		IContainerListener icontainerlistener = (IContainerListener)this.listeners.get(i);

		if(this.energy != te.getCapability(CapabilityEnergy.ENERGY, null).getEnergyStored())
		{
			icontainerlistener.sendProgressBarUpdate(this, this.energy, this.te.getCapability(CapabilityEnergy.ENERGY, null).getEnergyStored());
		}
	}		
	this.energy = this.te.getCapability(CapabilityEnergy.ENERGY, null).getEnergyStored();
}

@SideOnly(Side.CLIENT)
    public void updateProgressBar(int id, int data)
    {
        ((BaseEnergyStorage)this.te.getCapability(CapabilityEnergy.ENERGY, null)).setEnergyStored(data);
    }

private void addOwnSlots()
{
        IItemHandler itemHandler = this.te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);

        addSlotToContainer(new SlotItemHandler(itemHandler, 0, 64, 34));
        addSlotToContainer(new SlotOutput(itemHandler, 1, 100, 34));
    }

    private void addPlayerSlots(IInventory playerInventory) 
    {
        // Slots for the main inventory
        for (int row = 0; row < 3; ++row) 
        {
            for (int col = 0; col < 9; ++col) 
            {
                int x = 10 + col * 18;
                int y = row * 18 + 70;
                this.addSlotToContainer(new Slot(playerInventory, col + row * 9 + 10, x, y));
            }
        }
        // Slots for the hotbar
        for (int row = 0; row < 9; ++row)
        {
            int x = 10 + row * 18;
            int y = 58 + 70;
            this.addSlotToContainer(new Slot(playerInventory, row, x, y));
        }
    }	
    
    @Nullable
    @Override
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) 
    {
        ItemStack itemstack = null;
        Slot slot = this.inventorySlots.get(index);

        if (slot != null && slot.getHasStack()) 
        {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

            if (index < TileEntityCharger.SIZE) 
            {
                if (!this.mergeItemStack(itemstack1, TileEntityCharger.SIZE, this.inventorySlots.size(), true)) 
                {
                    return null;
                }
            } 
            else if (!this.mergeItemStack(itemstack1, 0, TileEntityCharger.SIZE, false)) 
            {
                return null;
            }
            if (itemstack1.stackSize == 0) 
            {
                slot.putStack(null);
            } else 
            {
                slot.onSlotChanged();
            }
        }
        return itemstack;
    }
    
@Override
public boolean canInteractWith(EntityPlayer playerIn) 
{
	return te.canInteractWith(playerIn);
}
}

 

the canInteractwith returns te.canInteractWith which is:

public boolean canInteractWith(EntityPlayer playerIn) 
{
    // If we are too far away from this tile entity you cannot use it
	return !isInvalid() && playerIn.getDistanceSq(pos.add(0.5D, 0.5D, 0.5D)) <= 64D;
}

Posted

Ok i solved it with just rewriting sendanddetectchanges and sendprogressbarUpdate from scratch.

Only thing i changed is to set the parameter "value to change" to 0 instead of the actual field that has to be changed.

I dont like the way vanilly does the progressbar things with hardcoded integers that describe the field of the te. Why do i want to do sth like this?

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

    • Ah, it appears I spoke too soon, I still need a little help here. I now have the forceloading working reliably.  However, I've realized it's not always the first tick that loads the entity.  I've seen it take anywhere from 2-20ish to actually go through, in which time my debugging has revealed that the chunk is loaded, but during which time calling  serverLevelIn.getEntity(uuidIn) returns a null result.  I suspect this has to do with queuing and how entities are loaded into the game.  While not optimal, it's acceptable, and I don't think there's a whole ton I can do to avoid it. However, my concern is that occasionally teleporting an entity in this manner causes a lag spike.  It's not every time and gives the appearance of being correlated with when other chunks are loading in.  It's also not typically a long spike, but can last a second or two, which is less than ideal.  The gist of how I'm summoning is here (although I've omitted some parts that weren't relevant.  The lag occurs before the actual summon so I'm pretty confident it's the loading, and not the actual summon call). ChunkPos chunkPos = new ChunkPos(entityPosIn); if (serverLevelIn.areEntitiesLoaded(chunkPos.toLong())) { boolean isSummoned = // The method I'm using for actual summoning is called here. Apart from a few checks, the bulk of it is shown later on. if (isSummoned) { // Code that runs here just notifies the player of the summon, clears it from the queue, and removes the forceload } } else { // I continue forcing the chunk until the summon succeeds, to make sure it isn't inadvertently cleared ForgeChunkManager.forceChunk(serverLevelIn, MODID, summonPosIn, chunkPos.x, chunkPos.z, true, true); } The summon code itself uses serverLevelIn.getEntity(uuidIn) to retrieve the entity, and moves it as such.  It is then moved thusly: if (entity.isAlive()) { entity.moveTo(posIn.getX(), posIn.getY(), posIn.getZ()); serverLevelIn.playSound(null, entity, SoundEvents.ENDERMAN_TELEPORT, SoundSource.NEUTRAL, 1.0F, 1.0F); return true; } I originally was calling .getEntity() more frequently and didn't have the check for whether or not entities were loaded in place to prevent unnecessary code calls, but even with those safety measures in place, the lag still persists.  Could this just be an issue with 1.18's lack of optimization in certain areas?  Is there anything I can do to mitigate it?  Is there a performance boosting mod I could recommend alongside my own to reduce the chunk loading lag? At the end of the day, it does work, and I'm putting measures in place to prevent players from abusing the system to cause lag (i.e. each player can only have one queued summon at a time-- trying to summon another replaces the first call).  It's also not an unacceptable level of lag, IMO, given the infrequency of such calls, and the fact that I'm providing the option to toggle off the feature if server admins don't want it used.  However, no amount of lag is ideal, so if possible I'd love to find a more elegant solution-- or at least a mod recommendation to help improve it. Thanks!
    • When i start my forge server its on but when i try to join its come a error Internal Exception: java.lang.OutOfMemoryError: Requested array size exceeds VM limit Server infos: Linux Minecraft version 1.20.1 -Xmx11G -Xms8G
    • Also add the latest.log from your logs-folder
    • Add the mods in groups
  • Topics

×
×
  • Create New...

Important Information

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