| 1 | package net.minecraft.world.level.storage.loot.providers.nbt;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.MapCodec;
|
| 5 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 6 | import java.util.Set;
|
| 7 | import net.minecraft.advancements.predicates.NbtPredicate;
|
| 8 | import net.minecraft.nbt.Tag;
|
| 9 | import net.minecraft.util.context.ContextKey;
|
| 10 | import net.minecraft.world.entity.Entity;
|
| 11 | import net.minecraft.world.level.block.entity.BlockEntity;
|
| 12 | import net.minecraft.world.level.storage.loot.LootContext;
|
| 13 | import net.minecraft.world.level.storage.loot.LootContextArg;
|
| 14 | import org.jspecify.annotations.Nullable;
|
| 15 |
|
| 16 | public class ContextNbtProvider implements NbtProvider {
|
| 17 | private static final Codec<LootContextArg<Tag>> GETTER_CODEC = LootContextArg.createArgCodec(
|
| 18 | builder -> builder.anyBlockEntity(ContextNbtProvider.BlockEntitySource::new).anyEntity(ContextNbtProvider.EntitySource::new)
|
| 19 | );
|
| 20 | public static final MapCodec<ContextNbtProvider> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 21 | i -> i.group(GETTER_CODEC.fieldOf("target").forGetter(p -> p.source)).apply(i, ContextNbtProvider::new)
|
| 22 | );
|
| 23 | public static final Codec<ContextNbtProvider> INLINE_CODEC = GETTER_CODEC.xmap(ContextNbtProvider::new, p -> p.source);
|
| 24 | private final LootContextArg<Tag> source;
|
| 25 |
|
| 26 | private ContextNbtProvider(final LootContextArg<Tag> source) {
|
| 27 | this.source = source;
|
| 28 | }
|
| 29 |
|
| 30 | @Override
|
| 31 | public MapCodec<ContextNbtProvider> codec() {
|
| 32 | return MAP_CODEC;
|
| 33 | }
|
| 34 |
|
| 35 | @Override
|
| 36 | public @Nullable Tag get(final LootContext context) {
|
| 37 | return this.source.get(context);
|
| 38 | }
|
| 39 |
|
| 40 | @Override
|
| 41 | public Set<ContextKey<?>> getReferencedContextParams() {
|
| 42 | return Set.of(this.source.contextParam());
|
| 43 | }
|
| 44 |
|
| 45 | public static NbtProvider forContextEntity(final LootContext.EntityTarget source) {
|
| 46 | return new ContextNbtProvider(new ContextNbtProvider.EntitySource(source.contextParam()));
|
| 47 | }
|
| 48 |
|
| 49 | private record BlockEntitySource(ContextKey<? extends BlockEntity> contextParam) implements LootContextArg.Getter<BlockEntity, Tag> {
|
| 50 | public Tag get(final BlockEntity blockEntity) {
|
| 51 | return blockEntity.saveWithFullMetadata(blockEntity.getLevel().registryAccess());
|
| 52 | }
|
| 53 | }
|
| 54 |
|
| 55 | private record EntitySource(ContextKey<? extends Entity> contextParam) implements LootContextArg.Getter<Entity, Tag> {
|
| 56 | public Tag get(final Entity entity) {
|
| 57 | return NbtPredicate.getEntityTagToCompare(entity);
|
| 58 | }
|
| 59 | }
|
| 60 | }
|
| 61 |
|