| 1 | package net.minecraft.world.level.storage.loot.functions;
|
| 2 |
|
| 3 | import com.mojang.serialization.MapCodec;
|
| 4 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 5 | import java.util.Optional;
|
| 6 | import net.minecraft.core.Holder;
|
| 7 | import net.minecraft.core.HolderSet;
|
| 8 | import net.minecraft.core.component.DataComponents;
|
| 9 | import net.minecraft.core.registries.Registries;
|
| 10 | import net.minecraft.core.registries.codec.RegistryCodecs;
|
| 11 | import net.minecraft.world.item.ItemStack;
|
| 12 | import net.minecraft.world.item.alchemy.Potion;
|
| 13 | import net.minecraft.world.item.alchemy.PotionContents;
|
| 14 | import net.minecraft.world.level.storage.loot.LootContext;
|
| 15 | import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
| 16 |
|
| 17 | public class SetRandomPotionFunction extends LootItemConditionalFunction {
|
| 18 | public static final MapCodec<SetRandomPotionFunction> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 19 | i -> commonFields(i)
|
| 20 | .and(RegistryCodecs.holderSet(Registries.POTION).optionalFieldOf("options").forGetter(f -> f.options))
|
| 21 | .apply(i, SetRandomPotionFunction::new)
|
| 22 | );
|
| 23 | private final Optional<HolderSet<Potion>> options;
|
| 24 |
|
| 25 | private SetRandomPotionFunction(final Optional<Holder<LootItemCondition>> condition, final Optional<HolderSet<Potion>> options) {
|
| 26 | super(condition);
|
| 27 | this.options = options;
|
| 28 | }
|
| 29 |
|
| 30 | @Override
|
| 31 | public MapCodec<SetRandomPotionFunction> codec() {
|
| 32 | return MAP_CODEC;
|
| 33 | }
|
| 34 |
|
| 35 | @Override
|
| 36 | public ItemStack run(final ItemStack itemStack, final LootContext context) {
|
| 37 | Optional<? extends Holder<Potion>> potion;
|
| 38 | if (this.options.isPresent()) {
|
| 39 | potion = this.options.get().getRandomElement(context.getRandom());
|
| 40 | } else {
|
| 41 | potion = context.getLevel().registryAccess().lookupOrThrow(Registries.POTION).getRandom(context.getRandom());
|
| 42 | }
|
| 43 |
|
| 44 | if (potion.isPresent()) {
|
| 45 | itemStack.update(DataComponents.POTION_CONTENTS, PotionContents.EMPTY, potion.get(), PotionContents::withPotion);
|
| 46 | }
|
| 47 |
|
| 48 | return itemStack;
|
| 49 | }
|
| 50 |
|
| 51 | public static LootItemConditionalFunction.Builder<?> fromTagKey(final HolderSet<Potion> tagKey) {
|
| 52 | return simpleBuilder(conditions -> new SetRandomPotionFunction(conditions, Optional.of(tagKey)));
|
| 53 | }
|
| 54 | }
|
| 55 |
|