StatusDisplay.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package me.km.networking;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.function.Supplier;
  4. import net.minecraft.network.PacketBuffer;
  5. import net.minecraftforge.fml.network.NetworkEvent;
  6. public class StatusDisplay
  7. {
  8. // 1 - add - index, text
  9. // 2 - remove - index
  10. // 3 - clear
  11. private byte action;
  12. private byte index;
  13. private int time;
  14. private String text;
  15. public StatusDisplay()
  16. {
  17. action = -1;
  18. index = -1;
  19. text = "";
  20. }
  21. public StatusDisplay(byte action, byte index, int time, String text)
  22. {
  23. this.action = action;
  24. this.index = index;
  25. this.time = time;
  26. if(text.length() > 32)
  27. {
  28. this.text = text.substring(0, 32);
  29. }
  30. else
  31. {
  32. this.text = text;
  33. }
  34. }
  35. public StatusDisplay(byte action, byte index, String text)
  36. {
  37. this(action, index, Integer.MAX_VALUE, text);
  38. }
  39. public static void writeBytes(StatusDisplay sd, PacketBuffer buf)
  40. {
  41. buf.writeByte(sd.action);
  42. buf.writeByte(sd.index);
  43. buf.writeInt(sd.time);
  44. byte[] b = sd.text.getBytes(StandardCharsets.UTF_8);
  45. buf.writeInt(b.length);
  46. buf.writeBytes(b);
  47. }
  48. public static StatusDisplay fromBytes(PacketBuffer buf)
  49. {
  50. StatusDisplay sd = new StatusDisplay();
  51. sd.action = buf.readByte();
  52. sd.index = buf.readByte();
  53. sd.time = buf.readInt();
  54. int length = buf.readInt();
  55. sd.text = buf.readBytes(length).toString(StandardCharsets.UTF_8);
  56. return sd;
  57. }
  58. public static void handle(StatusDisplay sd, Supplier<NetworkEvent.Context> context)
  59. {
  60. context.get().enqueueWork(() ->
  61. {
  62. switch(sd.action)
  63. {
  64. case 1:
  65. StatusDisplayGui.INSTANCE.add(sd.index, sd.time, sd.text);
  66. break;
  67. case 2:
  68. StatusDisplayGui.INSTANCE.remove(sd.index);
  69. break;
  70. case 3:
  71. StatusDisplayGui.INSTANCE.clear();
  72. break;
  73. }
  74. });
  75. context.get().setPacketHandled(true);
  76. }
  77. }