| 1 | package net.minecraft.network.chat.contents.data;
|
| 2 |
|
| 3 | import com.mojang.brigadier.StringReader;
|
| 4 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 5 | import com.mojang.serialization.Codec;
|
| 6 | import com.mojang.serialization.MapCodec;
|
| 7 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 8 | import java.util.stream.Stream;
|
| 9 | import net.minecraft.commands.CommandSourceStack;
|
| 10 | import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
|
| 11 | import net.minecraft.commands.arguments.coordinates.Coordinates;
|
| 12 | import net.minecraft.core.BlockPos;
|
| 13 | import net.minecraft.nbt.CompoundTag;
|
| 14 | import net.minecraft.server.level.ServerLevel;
|
| 15 | import net.minecraft.util.CompilableString;
|
| 16 | import net.minecraft.world.level.block.entity.BlockEntity;
|
| 17 |
|
| 18 | public record BlockDataSource(CompilableString<Coordinates> coordinates) implements DataSource {
|
| 19 | public static final Codec<CompilableString<Coordinates>> BLOCK_POS_CODEC = CompilableString.codec(new CompilableString.CommandParserHelper<Coordinates>() {
|
| 20 | protected Coordinates parse(final StringReader reader) throws CommandSyntaxException {
|
| 21 | return BlockPosArgument.blockPos().parse(reader);
|
| 22 | }
|
| 23 |
|
| 24 | @Override
|
| 25 | protected String errorMessage(final String original, final CommandSyntaxException exception) {
|
| 26 | return "Invalid coordinates path: " + original + ": " + exception.getMessage();
|
| 27 | }
|
| 28 | });
|
| 29 | public static final MapCodec<BlockDataSource> MAP_CODEC = RecordCodecBuilder.mapCodec(
|
| 30 | i -> i.group(BLOCK_POS_CODEC.fieldOf("block").forGetter(BlockDataSource::coordinates)).apply(i, BlockDataSource::new)
|
| 31 | );
|
| 32 |
|
| 33 | @Override
|
| 34 | public Stream<CompoundTag> getData(final CommandSourceStack sender) {
|
| 35 | ServerLevel level = sender.getLevel();
|
| 36 | BlockPos pos = this.coordinates.compiled().getBlockPos(sender);
|
| 37 | if (level.isLoaded(pos)) {
|
| 38 | BlockEntity entity = level.getBlockEntity(pos);
|
| 39 | if (entity != null) {
|
| 40 | return Stream.of(entity.saveWithFullMetadata(sender.registryAccess()));
|
| 41 | }
|
| 42 | }
|
| 43 |
|
| 44 | return Stream.empty();
|
| 45 | }
|
| 46 |
|
| 47 | @Override
|
| 48 | public MapCodec<BlockDataSource> codec() {
|
| 49 | return MAP_CODEC;
|
| 50 | }
|
| 51 | }
|
| 52 |
|