PlayerDisplay.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package me.km.networking;
  2. import io.netty.buffer.ByteBuf;
  3. import java.nio.charset.StandardCharsets;
  4. import net.minecraft.client.Minecraft;
  5. import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
  6. import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
  7. import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
  8. public class PlayerDisplay implements IMessage
  9. {
  10. // 1 - add - index, text
  11. // 2 - remove - index
  12. // 3 - clear
  13. private byte action;
  14. private byte index;
  15. private String text;
  16. public PlayerDisplay()
  17. {
  18. action = -1;
  19. index = -1;
  20. text = "";
  21. }
  22. public PlayerDisplay(byte action, byte index, String text)
  23. {
  24. this.action = action;
  25. this.index = index;
  26. if(text.length() > 32)
  27. {
  28. this.text = text.substring(0, 32);
  29. }
  30. else
  31. {
  32. this.text = text;
  33. }
  34. }
  35. @Override
  36. public void fromBytes(ByteBuf buf)
  37. {
  38. action = buf.readByte();
  39. index = buf.readByte();
  40. int length = buf.readInt();
  41. text = buf.readBytes(length).toString(StandardCharsets.UTF_8);
  42. }
  43. @Override
  44. public void toBytes(ByteBuf buf)
  45. {
  46. buf.writeByte(action);
  47. buf.writeByte(index);
  48. byte[] b = text.getBytes(StandardCharsets.UTF_8);
  49. buf.writeInt(b.length);
  50. buf.writeBytes(b);
  51. }
  52. public static class Handler implements IMessageHandler<PlayerDisplay, IMessage>
  53. {
  54. @Override
  55. public IMessage onMessage(PlayerDisplay message, MessageContext ctx)
  56. {
  57. Minecraft mc = net.minecraft.client.Minecraft.getMinecraft();
  58. mc.addScheduledTask(() ->
  59. {
  60. switch(message.action)
  61. {
  62. case 1:
  63. PlayerDisplayGui.INSTANCE.add(message.index, message.text);
  64. break;
  65. case 2:
  66. PlayerDisplayGui.INSTANCE.remove(message.index);
  67. break;
  68. case 3:
  69. PlayerDisplayGui.INSTANCE.clear();
  70. break;
  71. }
  72. });
  73. return null;
  74. }
  75. }
  76. }