| 1 | package net.minecraft.world.entity;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import java.util.EnumMap;
|
| 5 | import java.util.Map;
|
| 6 | import java.util.Objects;
|
| 7 | import java.util.Map.Entry;
|
| 8 | import net.minecraft.world.entity.item.ItemEntity;
|
| 9 | import net.minecraft.world.item.ItemStack;
|
| 10 |
|
| 11 | public class EntityEquipment {
|
| 12 | public static final Codec<EntityEquipment> CODEC = Codec.unboundedMap(EquipmentSlot.CODEC, ItemStack.CODEC).xmap(items -> {
|
| 13 | EnumMap<EquipmentSlot, ItemStack> map = new EnumMap<>(EquipmentSlot.class);
|
| 14 | map.putAll((Map<? extends EquipmentSlot, ? extends ItemStack>)items);
|
| 15 | return new EntityEquipment(map);
|
| 16 | }, equipment -> {
|
| 17 | Map<EquipmentSlot, ItemStack> items = new EnumMap<>(equipment.items);
|
| 18 | items.values().removeIf(ItemStack::isEmpty);
|
| 19 | return items;
|
| 20 | });
|
| 21 | private final EnumMap<EquipmentSlot, ItemStack> items;
|
| 22 |
|
| 23 | private EntityEquipment(final EnumMap<EquipmentSlot, ItemStack> items) {
|
| 24 | this.items = items;
|
| 25 | }
|
| 26 |
|
| 27 | public EntityEquipment() {
|
| 28 | this(new EnumMap<>(EquipmentSlot.class));
|
| 29 | }
|
| 30 |
|
| 31 | public ItemStack set(final EquipmentSlot slot, final ItemStack itemStack) {
|
| 32 | return Objects.requireNonNullElse(this.items.put(slot, itemStack), ItemStack.EMPTY);
|
| 33 | }
|
| 34 |
|
| 35 | public ItemStack get(final EquipmentSlot slot) {
|
| 36 | return this.items.getOrDefault(slot, ItemStack.EMPTY);
|
| 37 | }
|
| 38 |
|
| 39 | public boolean isEmpty() {
|
| 40 | for (ItemStack item : this.items.values()) {
|
| 41 | if (!item.isEmpty()) {
|
| 42 | return false;
|
| 43 | }
|
| 44 | }
|
| 45 |
|
| 46 | return true;
|
| 47 | }
|
| 48 |
|
| 49 | public void tick(final Entity owner) {
|
| 50 | for (Entry<EquipmentSlot, ItemStack> entry : this.items.entrySet()) {
|
| 51 | ItemStack item = entry.getValue();
|
| 52 | if (!item.isEmpty()) {
|
| 53 | item.inventoryTick(owner.level(), owner, entry.getKey());
|
| 54 | }
|
| 55 | }
|
| 56 | }
|
| 57 |
|
| 58 | public void setAll(final EntityEquipment equipment) {
|
| 59 | this.items.clear();
|
| 60 | this.items.putAll(equipment.items);
|
| 61 | }
|
| 62 |
|
| 63 | public void dropAll(final LivingEntity dropper) {
|
| 64 | for (ItemStack item : this.items.values()) {
|
| 65 | ItemEntity drop = dropper.createItemStackToDrop(item, true, false);
|
| 66 | if (drop != null) {
|
| 67 | dropper.level().addFreshEntity(drop);
|
| 68 | }
|
| 69 | }
|
| 70 |
|
| 71 | this.clear();
|
| 72 | }
|
| 73 |
|
| 74 | public void clear() {
|
| 75 | this.items.replaceAll((s, v) -> ItemStack.EMPTY);
|
| 76 | }
|
| 77 | }
|
| 78 |
|