net.minestom.server.network.packet.server.play.EntityEquipmentPacket Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of minestom-snapshots Show documentation
Show all versions of minestom-snapshots Show documentation
1.20.4 Lightweight Minecraft server
package net.minestom.server.network.packet.server.play;
import net.kyori.adventure.text.Component;
import net.minestom.server.entity.EquipmentSlot;
import net.minestom.server.item.ItemComponent;
import net.minestom.server.item.ItemStack;
import net.minestom.server.network.NetworkBuffer;
import net.minestom.server.network.packet.server.ServerPacket;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.EnumMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static net.minestom.server.network.NetworkBuffer.BYTE;
import static net.minestom.server.network.NetworkBuffer.VAR_INT;
public record EntityEquipmentPacket(int entityId,
@NotNull Map equipments) implements ServerPacket.Play, ServerPacket.ComponentHolding {
public EntityEquipmentPacket {
equipments = Map.copyOf(equipments);
if (equipments.isEmpty())
throw new IllegalArgumentException("Equipments cannot be empty");
}
public static final NetworkBuffer.Type SERIALIZER = new NetworkBuffer.Type<>() {
@Override
public void write(@NotNull NetworkBuffer buffer, EntityEquipmentPacket value) {
buffer.write(VAR_INT, value.entityId);
int index = 0;
for (var entry : value.equipments.entrySet()) {
final boolean last = index++ == value.equipments.size() - 1;
byte slotEnum = (byte) entry.getKey().ordinal();
if (!last) slotEnum |= 0x80;
buffer.write(BYTE, slotEnum);
buffer.write(ItemStack.NETWORK_TYPE, entry.getValue());
}
}
@Override
public EntityEquipmentPacket read(@NotNull NetworkBuffer buffer) {
return new EntityEquipmentPacket(buffer.read(VAR_INT), readEquipments(buffer));
}
};
@Override
public @NotNull Collection components() {
return this.equipments.values()
.stream()
.map(item -> item.get(ItemComponent.CUSTOM_NAME))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public @NotNull ServerPacket copyWithOperator(@NotNull UnaryOperator operator) {
final var map = new EnumMap(EquipmentSlot.class);
this.equipments.forEach((key, value) -> map.put(key, value.with(ItemComponent.CUSTOM_NAME, operator)));
return new EntityEquipmentPacket(this.entityId, map);
}
private static Map readEquipments(@NotNull NetworkBuffer reader) {
Map equipments = new EnumMap<>(EquipmentSlot.class);
byte slot;
do {
slot = reader.read(BYTE);
equipments.put(EquipmentSlot.values()[slot & 0x7F], reader.read(ItemStack.NETWORK_TYPE));
} while ((slot & 0x80) == 0x80);
return equipments;
}
}