Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.16.5] Custom Text Overlay not updating when playing on server


NindyBun
 Share

Recommended Posts

So I have a FontRenderer that displays the Fuel value of my tool, on a singleplayer world the text updates fine but once I go on the server the same text does not update. So I'm assuming that I would have to send the server packet to the client, problem is how would I do that if I need a ServerPlayerEntity.

My Font renderer:

https://github.com/NindyBun/BurnerGun_1.16.5/blob/master/src/main/java/com/nindybun/burnergun/client/renderer/FuelValueRenderer.java

package com.nindybun.burnergun.client.renderer;

import com.nindybun.burnergun.common.BurnerGun;
import com.nindybun.burnergun.common.items.upgrades.Upgrade;
import com.nindybun.burnergun.common.network.PacketHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.annotation.Nonnull;
import java.awt.*;

@Mod.EventBusSubscriber(modid = BurnerGun.MOD_ID, value = Dist.CLIENT)
public class FuelValueRenderer {
    private static final Logger LOGGER = LogManager.getLogger();
    private static final int base_buffer = com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun.base_use_buffer;
    private static final int base_heat_buffer = com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun.base_heat_buffer;
    @SubscribeEvent
    public static void renderOverlay(@Nonnull RenderGameOverlayEvent.Post event){
        if (event.getType() == RenderGameOverlayEvent.ElementType.ALL){
            ItemStack stack = ItemStack.EMPTY;
            PlayerEntity player = Minecraft.getInstance().player;
            if (player.getMainHandItem().getItem() instanceof com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun)
                stack = player.getMainHandItem();
            else if (player.getOffhandItem().getItem() instanceof com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun)
                stack = player.getOffhandItem();

            if (stack.getItem() instanceof com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun)
                renderFuel(event, stack);

        }

    }

    public static void renderFuel(RenderGameOverlayEvent event, ItemStack stack){
        FontRenderer fontRenderer = Minecraft.getInstance().font;
        IItemHandler handler = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).orElse(null);
        int level = stack.getTag().getInt("FuelValue");
        int hLevel = stack.getTag().getInt("HeatValue");
        Color color;
        if (level > base_buffer*3/4)
            color = Color.GREEN;
        else if (level > base_buffer*1/4 && level <= base_buffer*3/4)
            color = Color.ORANGE;
        else
            color = Color.RED;

        if (hLevel > base_heat_buffer*3/4)
            color = Color.RED;
        else if (hLevel > base_heat_buffer*1/4 && hLevel <= base_heat_buffer*3/4)
            color = Color.ORANGE;
        else
            color = Color.GREEN;
        //fontRenderer.drawString(event.getMatrixStack(), "Fuel level: "+level, 6, event.getWindow().getScaledHeight()-12, Color.WHITE.getRGB());
        if (!handler.getStackInSlot(0).getItem().equals(Upgrade.UNIFUEL.getCard().getItem())
            && !handler.getStackInSlot(0).getItem().equals(Upgrade.REACTOR.getCard().getItem())){
            fontRenderer.draw(event.getMatrixStack(), "Fuel level: ", 6, event.getWindow().getGuiScaledHeight()-12, Color.WHITE.getRGB());
            fontRenderer.draw(event.getMatrixStack(), level+"", 61, event.getWindow().getGuiScaledHeight()-12, color.getRGB());
        }else if (handler.getStackInSlot(0).getItem().equals(Upgrade.REACTOR.getCard().getItem())){
            double heat = (double)hLevel/base_heat_buffer*100;
            String heatString = heat+"";
            int deci = heatString.lastIndexOf(".");
            heatString = heatString.substring(0, deci+2);
            fontRenderer.draw(event.getMatrixStack(), "Heat level: ", 6, event.getWindow().getGuiScaledHeight()-12, Color.WHITE.getRGB());
            fontRenderer.draw(event.getMatrixStack(), heatString+"%", 61, event.getWindow().getGuiScaledHeight()-12, color.getRGB());
        }

    }
}

My packet handler

package com.nindybun.burnergun.common.network;

import com.nindybun.burnergun.common.BurnerGun;
import com.nindybun.burnergun.common.network.packets.PacketOpenAutoFuelGui;
import com.nindybun.burnergun.common.network.packets.PacketOpenBurnerGunGui;
import com.nindybun.burnergun.common.network.packets.PacketOpenTrashGui;
import com.nindybun.burnergun.common.network.packets.PacketOpenUpgradeBagGui;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;

public class PacketHandler {
    private static final String PROTOCOL_VERSION = "2";
    private static int index = 0;
    public static final SimpleChannel INSTANCE = NetworkRegistry.ChannelBuilder
            .named(new ResourceLocation(BurnerGun.MOD_ID, "main"))
            .clientAcceptedVersions(PROTOCOL_VERSION::equals)
            .serverAcceptedVersions(PROTOCOL_VERSION::equals)
            .networkProtocolVersion(() -> PROTOCOL_VERSION)
            .simpleChannel();

    public static void register(){
        int id = 0;
        INSTANCE.registerMessage(id++, PacketOpenBurnerGunGui.class, PacketOpenBurnerGunGui::encode, PacketOpenBurnerGunGui::decode, PacketOpenBurnerGunGui.Handler::handle);
        INSTANCE.registerMessage(id++, PacketOpenAutoFuelGui.class, PacketOpenAutoFuelGui::encode, PacketOpenAutoFuelGui::decode, PacketOpenAutoFuelGui.Handler::handle);
        INSTANCE.registerMessage(id++, PacketOpenTrashGui.class, PacketOpenTrashGui::encode, PacketOpenTrashGui::decode, PacketOpenTrashGui.Handler::handle);
        INSTANCE.registerMessage(id++, PacketOpenUpgradeBagGui.class, PacketOpenUpgradeBagGui::encode, PacketOpenUpgradeBagGui::decode, PacketOpenUpgradeBagGui.Handler::handle);

    }

    public static void sendTo(Object msg, ServerPlayerEntity player) {
        if (!(player instanceof FakePlayer))
            INSTANCE.sendTo(msg, player.connection.connection, NetworkDirection.PLAY_TO_CLIENT);
    }

    public static void sendToServer(Object msg){
        INSTANCE.sendToServer(msg);
    }

}

Yes I know, my coding is not the best looking.

Edited by NindyBun
Link to comment
Share on other sites

  • NindyBun changed the title to [1.16.5] Custom Text Overlay not updating when playing on server
Quote

PlayerEntity player = Minecraft.getInstance().player;

It might actually be this line that's causing the problem, but how else do I check if my itemstack is in a players hand so that I knows to draw the text?

Link to comment
Share on other sites

14 hours ago, NindyBun said:

It might actually be this line that's causing the problem, but how else do I check if my itemstack is in a players hand so that I knows to draw the text?

So I figured out that when I try to get the nbt tag in the RenderGameOverlayEvent it doesn't show the updated values, only the values made when the item was created. Therefore how would I get the current updated tag when playing on the dedicated server?

Link to comment
Share on other sites

18 hours ago, NindyBun said:

instanceof com.nindybun.burnergun.common.items.Burner_Gun.BurnerGun

You don't need a fully qualified name here if you just use an import statement.

21 minutes ago, NindyBun said:

Therefore how would I get the current updated tag when playing on the dedicated server?

You need to synchronize your data. Also, use a capability instead of NBTtags. NBT is for saving to disk, Capabilities are for runtime.

18 hours ago, NindyBun said:

IItemHandler handler = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).orElse(null);
int level = stack.getTag().getInt("FuelValue");

You aren't null-checking here. If you are absolutely sure your stack will have the capability, use orElseThrow(Exception). If you aren't sure, then use ifPresent(() -> {})

Edited by Draco18s

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

4 hours ago, Draco18s said:

You need to synchronize your data. Also, use a capability instead of NBTtags. NBT is for saving to disk, Capabilities are for runtime.

I've only ever used capability for messing with the itemstack's inventory so I don't exactly know how the process of using it for data goes, and I have read the documentation multiple times but I just can't wrap my head around it. To synchronize my data I would do that in the form of packets right? But what should I be sending and to where?

Link to comment
Share on other sites

Posted (edited)
1 hour ago, NindyBun said:

Nvm I got it working now

 

Scratch that. I have found one problem that is my fuel renderer is working as intended when the fuel level increases, but when it decreases the value doesn't change until I enter my world again. Why does that happen?

https://github.com/NindyBun/BurnerGun_1.16.5/blob/master/src/main/java/com/nindybun/burnergun/client/renderer/FuelValueRenderer.java#L63

Edited by NindyBun
Link to comment
Share on other sites

5 hours ago, NindyBun said:

Scratch that. I have found one problem that is my fuel renderer is working as intended when the fuel level increases, but when it decreases the value doesn't change until I enter my world again. Why does that happen?

https://github.com/NindyBun/BurnerGun_1.16.5/blob/master/src/main/java/com/nindybun/burnergun/client/renderer/FuelValueRenderer.java#L63

I continued messing with it and noticed that when the fuel value is above 500_000 which is half of the max buffer, the fuel renderer shows that it goes down, but when it gets below 500_000, I have to open my itemstack's gui to update it and I don't understand why it doesn't update by it self under 500_000.

Link to comment
Share on other sites

3 hours ago, NindyBun said:

https://github.com/NindyBun/BurnerGun_1.16.5/blob/master/src/main/java/com/nindybun/burnergun/common/network/packets/PacketFuelValue.java
 

Okay...I got the fuel renderer to work properly after fixing the get/readsharetag but now when I try to play on a dedicated server, the fuel renderer doesn't work, I don't know if my packet handler is right.

FINALLY, the whole problem was that I was accessing the wrong nbt tag in readShareTag this whole time.

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.

Guest
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.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • Hi i have a problem since 1.17.1 is "new" i'm not able to find the class net.minecraft.potion.Effect. And if i can't extend that class then i can't make my potion effect. So does anyone know where that class is ? and do you guys have a tutorial on how to make a potion effect in 1.16.5 or 1.17.1 because i can't find any tutorial about it. Thank you for helping!!!
    • Why the fak are you to-stringing that? if(source instanceof ImpactDamage) works just fine. You could also create single static instances of your new damage type and use things like ModDamageTypes.SLASHING and the == operator, like vanilla does. Your damage type instances have NO custom data in them at all, so you should just do that (yes I realize my own, very old, code is not following that). This is not how localization works. ItemStacks are never null. The player could be, though. Use ifPresent() instead. You should use the logger Forge provides you instead.
    • When an entity is attacked it has a few ticks of damage resistance during which time no further damage can be applied. You have to set Entity#invulnerableTime to 0 after applying the damage if you want further damage to apply on the same tick.
    • Thanks for the advice, I'm now able to get the events working to a degree. The issue I'm having now is this: I have a capability for both damage type and damage resistance. There are 3 new damage types that each have a corresponding resistance. Damage type capabilities are attached to weapons, while resistance capabilities are applied to entities. I use the following methods to apply extra damage types as well as calculate resistances. The problem is that when attacking an entity, only 1 instance of the new damage types is applied. As for the debugging messages, the 3 sendMessages are being sent in the extraDamage method. In the damageResistance method, only 1 System.out.println statement is being sent. Is there something to do with the way LivingHurtEvent works that only allowed 1 to be applied? package com.cwjn.hardstuckintegration.Events; import com.cwjn.hardstuckintegration.Capabilities.DamageTypes.CapabilityDamageTypes; import com.cwjn.hardstuckintegration.Capabilities.DamageTypes.IDamageTypes; import com.cwjn.hardstuckintegration.Capabilities.Resistances.CapabilityDamageResistance; import com.cwjn.hardstuckintegration.Capabilities.Resistances.IDamageResistance; import com.cwjn.hardstuckintegration.DamageTypes.ImpactDamage; import com.cwjn.hardstuckintegration.DamageTypes.NewType; import com.cwjn.hardstuckintegration.DamageTypes.PunctureDamage; import com.cwjn.hardstuckintegration.DamageTypes.SlashDamage; import com.cwjn.hardstuckintegration.HardstuckIntegration; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.Hand; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(modid = HardstuckIntegration.modID) public class DamageEvents { @SubscribeEvent public static void extraDamage(AttackEntityEvent event) { PlayerEntity player = event.getPlayer(); //player that is attacking Entity target = event.getTarget(); //target being attacked ItemStack item = player.getItemInHand(Hand.MAIN_HAND); //item used to attack if (item != null) { IDamageTypes damage = item.getCapability(CapabilityDamageTypes.DAMAGE_TYPES_CAPABILITY).orElse(null); //get the extra damage types if (damage != null) { float impactDamage = damage.getImpactDamage(); float slashDamage = damage.getSlashDamage(); //store the extra damage types float punctureDamage = damage.getPunctureDamage(); if (impactDamage > 0) { player.sendMessage(new TranslationTextComponent("TARGET ENTITY DEALT: " + impactDamage + " POINTS OF IMPACT DAMAGE"), player.getUUID()); target.hurt(new ImpactDamage(), impactDamage); //if the item has extra impact damage, hurt the target with an instance of impact damage } if (slashDamage > 0) { player.sendMessage(new TranslationTextComponent("TARGET ENTITY DEALT: " + slashDamage + " POINTS OF SLASH DAMAGE"), player.getUUID()); target.hurt(new SlashDamage(), slashDamage); //if the item has extra slash damage, hurt the target with an instance of slash damage } if (punctureDamage > 0) { player.sendMessage(new TranslationTextComponent("TARGET ENTITY DEALT: " + punctureDamage + " POINTS OF PUNCTURE DAMAGE"), player.getUUID()); target.hurt(new PunctureDamage(), punctureDamage); //if the item has extra puncture damage, hurt the target with an instance of puncture damage } } } } @SubscribeEvent public static void damageResistance(LivingHurtEvent event) { DamageSource source = event.getSource(); //source of damage if (source instanceof NewType) { //check if the source is a subclass of the new damage types added with this mod float amount = event.getAmount(); //get initial amount of new damage, before resistances LivingEntity target = event.getEntityLiving(); //target of damage float newDamage = amount; //variable to hold post-resistance calculation damage IDamageResistance res = target.getCapability(CapabilityDamageResistance.DAMAGE_RESISTANCE_CAPABILITY).orElse(null); //get target's resistances if (res != null) { float impactRes = res.getImpactResistance(); float slashRes = res.getSlashResistance(); //store the resistances float punctureRes = res.getPunctureResistance(); switch (((NewType) source).getSourceAsString()) { //get the the source of damage as a string case "slash": if (slashRes > 0) newDamage = (amount * (100 / (100 + slashRes))); //if the target has resistances, apply math to reduce damage. else if (slashRes < 0) newDamage = (amount * (2 - (100 / (100 - slashRes)))); //if the target has negative resistances, apply math to boost damage. else newDamage = amount; //if the target has no resistances, apply initial damage unchanged System.out.println("TARGET ENTITY TOOK: " + newDamage + " SLASH DAMAGE"); //used for debugging break; case "puncture": //same as case slash, but for puncture damage if (punctureRes > 0) newDamage = (amount * (100 / (100 + punctureRes))); else if (punctureRes < 0) newDamage = (amount * (2 - (100 / (100 - punctureRes)))); else newDamage = amount; System.out.println("TARGET ENTITY TOOK: " + newDamage + " PUNCTURE DAMAGE"); break; case "impact": //same as case slash, but for impact damage if (impactRes > 0) newDamage = (amount * (100 / (100 + impactRes))); else if (impactRes < 0) newDamage = (amount * (2 - (100 / (100 - impactRes)))); else newDamage = amount; System.out.println("TARGET ENTITY TOOK: " + newDamage + " IMPACT DAMAGE"); break; } } event.setAmount(newDamage); //apply post-resistance calculation damage to the event } } }  
    • This is not Multicraft support.
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.