| 1 | package net.minecraft.world.item.trading;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 5 | import java.util.Optional;
|
| 6 | import java.util.function.UnaryOperator;
|
| 7 | import net.minecraft.core.Holder;
|
| 8 | import net.minecraft.core.component.DataComponentExactPredicate;
|
| 9 | import net.minecraft.network.RegistryFriendlyByteBuf;
|
| 10 | import net.minecraft.network.codec.ByteBufCodecs;
|
| 11 | import net.minecraft.network.codec.StreamCodec;
|
| 12 | import net.minecraft.util.ExtraCodecs;
|
| 13 | import net.minecraft.world.item.Item;
|
| 14 | import net.minecraft.world.item.ItemStack;
|
| 15 | import net.minecraft.world.level.ItemLike;
|
| 16 |
|
| 17 | public record ItemCost(Holder<Item> item, int count, DataComponentExactPredicate components, ItemStack itemStack) {
|
| 18 | public static final Codec<ItemCost> CODEC = RecordCodecBuilder.create(
|
| 19 | i -> i.group(
|
| 20 | Item.CODEC.fieldOf("id").forGetter(ItemCost::item),
|
| 21 | ExtraCodecs.optionalAlwaysPresentFieldOf(ExtraCodecs.POSITIVE_INT, "count", 1).forGetter(ItemCost::count),
|
| 22 | DataComponentExactPredicate.CODEC.optionalFieldOf("components", DataComponentExactPredicate.EMPTY).forGetter(ItemCost::components)
|
| 23 | )
|
| 24 | .apply(i, ItemCost::new)
|
| 25 | );
|
| 26 | public static final StreamCodec<RegistryFriendlyByteBuf, ItemCost> STREAM_CODEC = StreamCodec.composite(
|
| 27 | Item.STREAM_CODEC, ItemCost::item, ByteBufCodecs.VAR_INT, ItemCost::count, DataComponentExactPredicate.STREAM_CODEC, ItemCost::components, ItemCost::new
|
| 28 | );
|
| 29 | public static final StreamCodec<RegistryFriendlyByteBuf, Optional<ItemCost>> OPTIONAL_STREAM_CODEC = STREAM_CODEC.apply(ByteBufCodecs::optional);
|
| 30 |
|
| 31 | public ItemCost(final ItemLike item) {
|
| 32 | this(item, 1);
|
| 33 | }
|
| 34 |
|
| 35 | public ItemCost(final ItemLike item, final int count) {
|
| 36 | this(item.asItem().builtInRegistryHolder(), count, DataComponentExactPredicate.EMPTY);
|
| 37 | }
|
| 38 |
|
| 39 | public ItemCost(final Holder<Item> item, final int count, final DataComponentExactPredicate components) {
|
| 40 | this(item, count, components, createStack(item, count, components));
|
| 41 | }
|
| 42 |
|
| 43 | public ItemCost withComponents(final UnaryOperator<DataComponentExactPredicate.Builder> components) {
|
| 44 | return new ItemCost(this.item, this.count, components.apply(DataComponentExactPredicate.builder()).build());
|
| 45 | }
|
| 46 |
|
| 47 | private static ItemStack createStack(final Holder<Item> item, final int count, final DataComponentExactPredicate components) {
|
| 48 | return new ItemStack(item, count, components.asPatch());
|
| 49 | }
|
| 50 |
|
| 51 | public boolean test(final ItemStack itemStack) {
|
| 52 | return itemStack.is(this.item) && this.components.test(itemStack);
|
| 53 | }
|
| 54 | }
|
| 55 |
|