| 1 | package net.minecraft.world.level.storage.loot.functions;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.DataResult;
|
| 5 | import com.mojang.serialization.MapCodec;
|
| 6 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 7 | import java.util.Optional;
|
| 8 | import net.minecraft.core.Holder;
|
| 9 | import net.minecraft.core.component.DataComponents;
|
| 10 | import net.minecraft.world.item.ItemStack;
|
| 11 | import net.minecraft.world.item.component.SeededContainerLoot;
|
| 12 | import net.minecraft.world.level.storage.loot.LootContext;
|
| 13 | import net.minecraft.world.level.storage.loot.LootTable;
|
| 14 | import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
| 15 |
|
| 16 | public class SetContainerLootTable extends LootItemConditionalFunction {
|
| 17 | public static final Codec<Holder.Reference<LootTable>> ID_ONLY_CODEC = LootTable.CODEC
|
| 18 | .comapFlatMap(
|
| 19 | holder -> holder instanceof Holder.Reference<LootTable> tag ? DataResult.success(tag) : DataResult.error(() -> "Only tag names supported"),
|
| 20 | holder -> (Holder<LootTable>)holder
|
| 21 | );
|
| 22 | public static final MapCodec<SetContainerLootTable> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 23 | i -> commonFields(i)
|
| 24 | .and(i.group(ID_ONLY_CODEC.fieldOf("loot_table_id").forGetter(f -> f.lootTableId), Codec.LONG.optionalFieldOf("seed", 0L).forGetter(f -> f.seed)))
|
| 25 | .apply(i, SetContainerLootTable::new)
|
| 26 | );
|
| 27 | private final Holder.Reference<LootTable> lootTableId;
|
| 28 | private final long seed;
|
| 29 |
|
| 30 | private SetContainerLootTable(final Optional<Holder<LootItemCondition>> condition, final Holder.Reference<LootTable> lootTableId, final long seed) {
|
| 31 | super(condition);
|
| 32 | this.lootTableId = lootTableId;
|
| 33 | this.seed = seed;
|
| 34 | }
|
| 35 |
|
| 36 | @Override
|
| 37 | public MapCodec<SetContainerLootTable> codec() {
|
| 38 | return MAP_CODEC;
|
| 39 | }
|
| 40 |
|
| 41 | @Override
|
| 42 | public ItemStack run(final ItemStack itemStack, final LootContext context) {
|
| 43 | if (itemStack.isEmpty()) {
|
| 44 | return itemStack;
|
| 45 | }
|
| 46 |
|
| 47 | itemStack.set(DataComponents.CONTAINER_LOOT, new SeededContainerLoot(this.lootTableId.key(), this.seed));
|
| 48 | return itemStack;
|
| 49 | }
|
| 50 |
|
| 51 | public static LootItemConditionalFunction.Builder<?> withLootTable(final Holder.Reference<LootTable> value) {
|
| 52 | return simpleBuilder(conditions -> new SetContainerLootTable(conditions, value, 0L));
|
| 53 | }
|
| 54 |
|
| 55 | public static LootItemConditionalFunction.Builder<?> withLootTable(final Holder.Reference<LootTable> value, final long seed) {
|
| 56 | return simpleBuilder(conditions -> new SetContainerLootTable(conditions, value, seed));
|
| 57 | }
|
| 58 | }
|
| 59 |
|