trurwsuieghfdskg

This commit is contained in:
2025-06-08 00:02:04 +09:00
commit 56c8ad5bc2
14172 changed files with 1139672 additions and 0 deletions

View File

@@ -0,0 +1,179 @@
package net.minecraft.commands;
import com.mojang.brigadier.exceptions.BuiltInExceptionProvider;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.network.chat.Component;
public class BrigadierExceptions implements BuiltInExceptionProvider {
private static final Dynamic2CommandExceptionType DOUBLE_TOO_SMALL = new Dynamic2CommandExceptionType((p_77203_, p_77204_) -> {
return Component.translatable("argument.double.low", p_77204_, p_77203_);
});
private static final Dynamic2CommandExceptionType DOUBLE_TOO_BIG = new Dynamic2CommandExceptionType((p_77198_, p_77199_) -> {
return Component.translatable("argument.double.big", p_77199_, p_77198_);
});
private static final Dynamic2CommandExceptionType FLOAT_TOO_SMALL = new Dynamic2CommandExceptionType((p_77191_, p_77192_) -> {
return Component.translatable("argument.float.low", p_77192_, p_77191_);
});
private static final Dynamic2CommandExceptionType FLOAT_TOO_BIG = new Dynamic2CommandExceptionType((p_77186_, p_77187_) -> {
return Component.translatable("argument.float.big", p_77187_, p_77186_);
});
private static final Dynamic2CommandExceptionType INTEGER_TOO_SMALL = new Dynamic2CommandExceptionType((p_77175_, p_77176_) -> {
return Component.translatable("argument.integer.low", p_77176_, p_77175_);
});
private static final Dynamic2CommandExceptionType INTEGER_TOO_BIG = new Dynamic2CommandExceptionType((p_77170_, p_77171_) -> {
return Component.translatable("argument.integer.big", p_77171_, p_77170_);
});
private static final Dynamic2CommandExceptionType LONG_TOO_SMALL = new Dynamic2CommandExceptionType((p_77165_, p_77166_) -> {
return Component.translatable("argument.long.low", p_77166_, p_77165_);
});
private static final Dynamic2CommandExceptionType LONG_TOO_BIG = new Dynamic2CommandExceptionType((p_77160_, p_77161_) -> {
return Component.translatable("argument.long.big", p_77161_, p_77160_);
});
private static final DynamicCommandExceptionType LITERAL_INCORRECT = new DynamicCommandExceptionType((p_77206_) -> {
return Component.translatable("argument.literal.incorrect", p_77206_);
});
private static final SimpleCommandExceptionType READER_EXPECTED_START_OF_QUOTE = new SimpleCommandExceptionType(Component.translatable("parsing.quote.expected.start"));
private static final SimpleCommandExceptionType READER_EXPECTED_END_OF_QUOTE = new SimpleCommandExceptionType(Component.translatable("parsing.quote.expected.end"));
private static final DynamicCommandExceptionType READER_INVALID_ESCAPE = new DynamicCommandExceptionType((p_77201_) -> {
return Component.translatable("parsing.quote.escape", p_77201_);
});
private static final DynamicCommandExceptionType READER_INVALID_BOOL = new DynamicCommandExceptionType((p_77196_) -> {
return Component.translatable("parsing.bool.invalid", p_77196_);
});
private static final DynamicCommandExceptionType READER_INVALID_INT = new DynamicCommandExceptionType((p_77189_) -> {
return Component.translatable("parsing.int.invalid", p_77189_);
});
private static final SimpleCommandExceptionType READER_EXPECTED_INT = new SimpleCommandExceptionType(Component.translatable("parsing.int.expected"));
private static final DynamicCommandExceptionType READER_INVALID_LONG = new DynamicCommandExceptionType((p_77184_) -> {
return Component.translatable("parsing.long.invalid", p_77184_);
});
private static final SimpleCommandExceptionType READER_EXPECTED_LONG = new SimpleCommandExceptionType(Component.translatable("parsing.long.expected"));
private static final DynamicCommandExceptionType READER_INVALID_DOUBLE = new DynamicCommandExceptionType((p_77173_) -> {
return Component.translatable("parsing.double.invalid", p_77173_);
});
private static final SimpleCommandExceptionType READER_EXPECTED_DOUBLE = new SimpleCommandExceptionType(Component.translatable("parsing.double.expected"));
private static final DynamicCommandExceptionType READER_INVALID_FLOAT = new DynamicCommandExceptionType((p_77168_) -> {
return Component.translatable("parsing.float.invalid", p_77168_);
});
private static final SimpleCommandExceptionType READER_EXPECTED_FLOAT = new SimpleCommandExceptionType(Component.translatable("parsing.float.expected"));
private static final SimpleCommandExceptionType READER_EXPECTED_BOOL = new SimpleCommandExceptionType(Component.translatable("parsing.bool.expected"));
private static final DynamicCommandExceptionType READER_EXPECTED_SYMBOL = new DynamicCommandExceptionType((p_77163_) -> {
return Component.translatable("parsing.expected", p_77163_);
});
private static final SimpleCommandExceptionType DISPATCHER_UNKNOWN_COMMAND = new SimpleCommandExceptionType(Component.translatable("command.unknown.command"));
private static final SimpleCommandExceptionType DISPATCHER_UNKNOWN_ARGUMENT = new SimpleCommandExceptionType(Component.translatable("command.unknown.argument"));
private static final SimpleCommandExceptionType DISPATCHER_EXPECTED_ARGUMENT_SEPARATOR = new SimpleCommandExceptionType(Component.translatable("command.expected.separator"));
private static final DynamicCommandExceptionType DISPATCHER_PARSE_EXCEPTION = new DynamicCommandExceptionType((p_77158_) -> {
return Component.translatable("command.exception", p_77158_);
});
public Dynamic2CommandExceptionType doubleTooLow() {
return DOUBLE_TOO_SMALL;
}
public Dynamic2CommandExceptionType doubleTooHigh() {
return DOUBLE_TOO_BIG;
}
public Dynamic2CommandExceptionType floatTooLow() {
return FLOAT_TOO_SMALL;
}
public Dynamic2CommandExceptionType floatTooHigh() {
return FLOAT_TOO_BIG;
}
public Dynamic2CommandExceptionType integerTooLow() {
return INTEGER_TOO_SMALL;
}
public Dynamic2CommandExceptionType integerTooHigh() {
return INTEGER_TOO_BIG;
}
public Dynamic2CommandExceptionType longTooLow() {
return LONG_TOO_SMALL;
}
public Dynamic2CommandExceptionType longTooHigh() {
return LONG_TOO_BIG;
}
public DynamicCommandExceptionType literalIncorrect() {
return LITERAL_INCORRECT;
}
public SimpleCommandExceptionType readerExpectedStartOfQuote() {
return READER_EXPECTED_START_OF_QUOTE;
}
public SimpleCommandExceptionType readerExpectedEndOfQuote() {
return READER_EXPECTED_END_OF_QUOTE;
}
public DynamicCommandExceptionType readerInvalidEscape() {
return READER_INVALID_ESCAPE;
}
public DynamicCommandExceptionType readerInvalidBool() {
return READER_INVALID_BOOL;
}
public DynamicCommandExceptionType readerInvalidInt() {
return READER_INVALID_INT;
}
public SimpleCommandExceptionType readerExpectedInt() {
return READER_EXPECTED_INT;
}
public DynamicCommandExceptionType readerInvalidLong() {
return READER_INVALID_LONG;
}
public SimpleCommandExceptionType readerExpectedLong() {
return READER_EXPECTED_LONG;
}
public DynamicCommandExceptionType readerInvalidDouble() {
return READER_INVALID_DOUBLE;
}
public SimpleCommandExceptionType readerExpectedDouble() {
return READER_EXPECTED_DOUBLE;
}
public DynamicCommandExceptionType readerInvalidFloat() {
return READER_INVALID_FLOAT;
}
public SimpleCommandExceptionType readerExpectedFloat() {
return READER_EXPECTED_FLOAT;
}
public SimpleCommandExceptionType readerExpectedBool() {
return READER_EXPECTED_BOOL;
}
public DynamicCommandExceptionType readerExpectedSymbol() {
return READER_EXPECTED_SYMBOL;
}
public SimpleCommandExceptionType dispatcherUnknownCommand() {
return DISPATCHER_UNKNOWN_COMMAND;
}
public SimpleCommandExceptionType dispatcherUnknownArgument() {
return DISPATCHER_UNKNOWN_ARGUMENT;
}
public SimpleCommandExceptionType dispatcherExpectedArgumentSeparator() {
return DISPATCHER_EXPECTED_ARGUMENT_SEPARATOR;
}
public DynamicCommandExceptionType dispatcherParseException() {
return DISPATCHER_PARSE_EXCEPTION;
}
}

View File

@@ -0,0 +1,62 @@
package net.minecraft.commands;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.flag.FeatureFlagSet;
public interface CommandBuildContext {
<T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_227134_);
static CommandBuildContext simple(final HolderLookup.Provider p_255702_, final FeatureFlagSet p_255968_) {
return new CommandBuildContext() {
public <T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_255791_) {
return p_255702_.lookupOrThrow(p_255791_).filterFeatures(p_255968_);
}
};
}
static CommandBuildContext.Configurable configurable(final RegistryAccess p_255925_, final FeatureFlagSet p_255945_) {
return new CommandBuildContext.Configurable() {
CommandBuildContext.MissingTagAccessPolicy missingTagAccessPolicy = CommandBuildContext.MissingTagAccessPolicy.FAIL;
public void missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy p_256626_) {
this.missingTagAccessPolicy = p_256626_;
}
public <T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_256616_) {
Registry<T> registry = p_255925_.registryOrThrow(p_256616_);
final HolderLookup.RegistryLookup<T> registrylookup = registry.asLookup();
final HolderLookup.RegistryLookup<T> registrylookup1 = registry.asTagAddingLookup();
HolderLookup.RegistryLookup<T> registrylookup2 = new HolderLookup.RegistryLookup.Delegate<T>() {
protected HolderLookup.RegistryLookup<T> parent() {
HolderLookup.RegistryLookup holderlookup$registrylookup;
switch (missingTagAccessPolicy) {
case FAIL:
holderlookup$registrylookup = registrylookup;
break;
case CREATE_NEW:
holderlookup$registrylookup = registrylookup1;
break;
default:
throw new IncompatibleClassChangeError();
}
return holderlookup$registrylookup;
}
};
return registrylookup2.filterFeatures(p_255945_);
}
};
}
public interface Configurable extends CommandBuildContext {
void missingTagAccessPolicy(CommandBuildContext.MissingTagAccessPolicy p_256669_);
}
public static enum MissingTagAccessPolicy {
CREATE_NEW,
FAIL;
}
}

View File

@@ -0,0 +1,172 @@
package net.minecraft.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import net.minecraft.Util;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.ServerFunctionManager;
public class CommandFunction {
private final CommandFunction.Entry[] entries;
final ResourceLocation id;
public CommandFunction(ResourceLocation p_77979_, CommandFunction.Entry[] p_77980_) {
this.id = p_77979_;
this.entries = p_77980_;
}
public ResourceLocation getId() {
return this.id;
}
public CommandFunction.Entry[] getEntries() {
return this.entries;
}
public static CommandFunction fromLines(ResourceLocation p_77985_, CommandDispatcher<CommandSourceStack> p_77986_, CommandSourceStack p_77987_, List<String> p_77988_) {
List<CommandFunction.Entry> list = Lists.newArrayListWithCapacity(p_77988_.size());
for(int i = 0; i < p_77988_.size(); ++i) {
int j = i + 1;
String s = p_77988_.get(i).trim();
StringReader stringreader = new StringReader(s);
if (stringreader.canRead() && stringreader.peek() != '#') {
if (stringreader.peek() == '/') {
stringreader.skip();
if (stringreader.peek() == '/') {
throw new IllegalArgumentException("Unknown or invalid command '" + s + "' on line " + j + " (if you intended to make a comment, use '#' not '//')");
}
String s1 = stringreader.readUnquotedString();
throw new IllegalArgumentException("Unknown or invalid command '" + s + "' on line " + j + " (did you mean '" + s1 + "'? Do not use a preceding forwards slash.)");
}
try {
ParseResults<CommandSourceStack> parseresults = p_77986_.parse(stringreader, p_77987_);
if (parseresults.getReader().canRead()) {
throw Commands.getParseException(parseresults);
}
list.add(new CommandFunction.CommandEntry(parseresults));
} catch (CommandSyntaxException commandsyntaxexception) {
throw new IllegalArgumentException("Whilst parsing command on line " + j + ": " + commandsyntaxexception.getMessage());
}
}
}
return new CommandFunction(p_77985_, list.toArray(new CommandFunction.Entry[0]));
}
public static class CacheableFunction {
public static final CommandFunction.CacheableFunction NONE = new CommandFunction.CacheableFunction((ResourceLocation)null);
@Nullable
private final ResourceLocation id;
private boolean resolved;
private Optional<CommandFunction> function = Optional.empty();
public CacheableFunction(@Nullable ResourceLocation p_77998_) {
this.id = p_77998_;
}
public CacheableFunction(CommandFunction p_77996_) {
this.resolved = true;
this.id = null;
this.function = Optional.of(p_77996_);
}
public Optional<CommandFunction> get(ServerFunctionManager p_78003_) {
if (!this.resolved) {
if (this.id != null) {
this.function = p_78003_.get(this.id);
}
this.resolved = true;
}
return this.function;
}
@Nullable
public ResourceLocation getId() {
return this.function.map((p_78001_) -> {
return p_78001_.id;
}).orElse(this.id);
}
}
public static class CommandEntry implements CommandFunction.Entry {
private final ParseResults<CommandSourceStack> parse;
public CommandEntry(ParseResults<CommandSourceStack> p_78006_) {
this.parse = p_78006_;
}
public void execute(ServerFunctionManager p_164879_, CommandSourceStack p_164880_, Deque<ServerFunctionManager.QueuedCommand> p_164881_, int p_164882_, int p_164883_, @Nullable ServerFunctionManager.TraceCallbacks p_164884_) throws CommandSyntaxException {
if (p_164884_ != null) {
String s = this.parse.getReader().getString();
p_164884_.onCommand(p_164883_, s);
int i = this.execute(p_164879_, p_164880_);
p_164884_.onReturn(p_164883_, s, i);
} else {
this.execute(p_164879_, p_164880_);
}
}
private int execute(ServerFunctionManager p_164876_, CommandSourceStack p_164877_) throws CommandSyntaxException {
return p_164876_.getDispatcher().execute(Commands.mapSource(this.parse, (p_242934_) -> {
return p_164877_;
}));
}
public String toString() {
return this.parse.getReader().getString();
}
}
@FunctionalInterface
public interface Entry {
void execute(ServerFunctionManager p_164885_, CommandSourceStack p_164886_, Deque<ServerFunctionManager.QueuedCommand> p_164887_, int p_164888_, int p_164889_, @Nullable ServerFunctionManager.TraceCallbacks p_164890_) throws CommandSyntaxException;
}
public static class FunctionEntry implements CommandFunction.Entry {
private final CommandFunction.CacheableFunction function;
public FunctionEntry(CommandFunction p_78019_) {
this.function = new CommandFunction.CacheableFunction(p_78019_);
}
public void execute(ServerFunctionManager p_164902_, CommandSourceStack p_164903_, Deque<ServerFunctionManager.QueuedCommand> p_164904_, int p_164905_, int p_164906_, @Nullable ServerFunctionManager.TraceCallbacks p_164907_) {
Util.ifElse(this.function.get(p_164902_), (p_164900_) -> {
CommandFunction.Entry[] acommandfunction$entry = p_164900_.getEntries();
if (p_164907_ != null) {
p_164907_.onCall(p_164906_, p_164900_.getId(), acommandfunction$entry.length);
}
int i = p_164905_ - p_164904_.size();
int j = Math.min(acommandfunction$entry.length, i);
for(int k = j - 1; k >= 0; --k) {
p_164904_.addFirst(new ServerFunctionManager.QueuedCommand(p_164903_, p_164906_ + 1, acommandfunction$entry[k]));
}
}, () -> {
if (p_164907_ != null) {
p_164907_.onCall(p_164906_, this.function.getId(), -1);
}
});
}
public String toString() {
return "function " + this.function.getId();
}
}
}

View File

@@ -0,0 +1,17 @@
package net.minecraft.commands;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.network.chat.Component;
public class CommandRuntimeException extends RuntimeException {
private final Component message;
public CommandRuntimeException(Component p_79225_) {
super(p_79225_.getString(), (Throwable)null, CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES, CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES);
this.message = p_79225_;
}
public Component getComponent() {
return this.message;
}
}

View File

@@ -0,0 +1,24 @@
package net.minecraft.commands;
import java.util.Map;
import javax.annotation.Nullable;
import net.minecraft.network.chat.PlayerChatMessage;
public interface CommandSigningContext {
CommandSigningContext ANONYMOUS = new CommandSigningContext() {
@Nullable
public PlayerChatMessage getArgument(String p_242898_) {
return null;
}
};
@Nullable
PlayerChatMessage getArgument(String p_230580_);
public static record SignedArguments(Map<String, PlayerChatMessage> arguments) implements CommandSigningContext {
@Nullable
public PlayerChatMessage getArgument(String p_242852_) {
return this.arguments.get(p_242852_);
}
}
}

View File

@@ -0,0 +1,34 @@
package net.minecraft.commands;
import net.minecraft.network.chat.Component;
public interface CommandSource {
CommandSource NULL = new CommandSource() {
public void sendSystemMessage(Component p_230799_) {
}
public boolean acceptsSuccess() {
return false;
}
public boolean acceptsFailure() {
return false;
}
public boolean shouldInformAdmins() {
return false;
}
};
void sendSystemMessage(Component p_230797_);
boolean acceptsSuccess();
boolean acceptsFailure();
boolean shouldInformAdmins();
default boolean alwaysAccepts() {
return false;
}
}

View File

@@ -0,0 +1,366 @@
package net.minecraft.commands;
import com.google.common.collect.Lists;
import com.mojang.brigadier.ResultConsumer;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.BinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.OutgoingChatMessage;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.Mth;
import net.minecraft.util.TaskChainer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public class CommandSourceStack implements SharedSuggestionProvider, net.minecraftforge.common.extensions.IForgeCommandSourceStack {
public static final SimpleCommandExceptionType ERROR_NOT_PLAYER = new SimpleCommandExceptionType(Component.translatable("permissions.requires.player"));
public static final SimpleCommandExceptionType ERROR_NOT_ENTITY = new SimpleCommandExceptionType(Component.translatable("permissions.requires.entity"));
public final CommandSource source;
private final Vec3 worldPosition;
private final ServerLevel level;
private final int permissionLevel;
private final String textName;
private final Component displayName;
private final MinecraftServer server;
private final boolean silent;
@Nullable
private final Entity entity;
@Nullable
private final ResultConsumer<CommandSourceStack> consumer;
private final EntityAnchorArgument.Anchor anchor;
private final Vec2 rotation;
private final CommandSigningContext signingContext;
private final TaskChainer chatMessageChainer;
private final IntConsumer returnValueConsumer;
public CommandSourceStack(CommandSource p_81302_, Vec3 p_81303_, Vec2 p_81304_, ServerLevel p_81305_, int p_81306_, String p_81307_, Component p_81308_, MinecraftServer p_81309_, @Nullable Entity p_81310_) {
this(p_81302_, p_81303_, p_81304_, p_81305_, p_81306_, p_81307_, p_81308_, p_81309_, p_81310_, false, (p_81361_, p_81362_, p_81363_) -> {
}, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(p_81309_), (p_280930_) -> {
});
}
protected CommandSourceStack(CommandSource p_282943_, Vec3 p_282023_, Vec2 p_282896_, ServerLevel p_282659_, int p_283075_, String p_282379_, Component p_282469_, MinecraftServer p_281590_, @Nullable Entity p_281515_, boolean p_282415_, @Nullable ResultConsumer<CommandSourceStack> p_282042_, EntityAnchorArgument.Anchor p_282332_, CommandSigningContext p_283585_, TaskChainer p_282376_, IntConsumer p_282226_) {
this.source = p_282943_;
this.worldPosition = p_282023_;
this.level = p_282659_;
this.silent = p_282415_;
this.entity = p_281515_;
this.permissionLevel = p_283075_;
this.textName = p_282379_;
this.displayName = p_282469_;
this.server = p_281590_;
this.consumer = p_282042_;
this.anchor = p_282332_;
this.rotation = p_282896_;
this.signingContext = p_283585_;
this.chatMessageChainer = p_282376_;
this.returnValueConsumer = p_282226_;
}
public CommandSourceStack withSource(CommandSource p_165485_) {
return this.source == p_165485_ ? this : new CommandSourceStack(p_165485_, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withEntity(Entity p_81330_) {
return this.entity == p_81330_ ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, p_81330_.getName().getString(), p_81330_.getDisplayName(), this.server, p_81330_, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withPosition(Vec3 p_81349_) {
return this.worldPosition.equals(p_81349_) ? this : new CommandSourceStack(this.source, p_81349_, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withRotation(Vec2 p_81347_) {
return this.rotation.equals(p_81347_) ? this : new CommandSourceStack(this.source, this.worldPosition, p_81347_, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> p_81335_) {
return Objects.equals(this.consumer, p_81335_) ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, p_81335_, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withCallback(ResultConsumer<CommandSourceStack> p_81337_, BinaryOperator<ResultConsumer<CommandSourceStack>> p_81338_) {
ResultConsumer<CommandSourceStack> resultconsumer = p_81338_.apply(this.consumer, p_81337_);
return this.withCallback(resultconsumer);
}
public CommandSourceStack withSuppressedOutput() {
return !this.silent && !this.source.alwaysAccepts() ? new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, true, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer) : this;
}
public CommandSourceStack withPermission(int p_81326_) {
return p_81326_ == this.permissionLevel ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, p_81326_, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withMaximumPermission(int p_81359_) {
return p_81359_ <= this.permissionLevel ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, p_81359_, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor p_81351_) {
return p_81351_ == this.anchor ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, p_81351_, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withLevel(ServerLevel p_81328_) {
if (p_81328_ == this.level) {
return this;
} else {
double d0 = DimensionType.getTeleportationScale(this.level.dimensionType(), p_81328_.dimensionType());
Vec3 vec3 = new Vec3(this.worldPosition.x * d0, this.worldPosition.y, this.worldPosition.z * d0);
return new CommandSourceStack(this.source, vec3, this.rotation, p_81328_, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, this.returnValueConsumer);
}
}
public CommandSourceStack facing(Entity p_81332_, EntityAnchorArgument.Anchor p_81333_) {
return this.facing(p_81333_.apply(p_81332_));
}
public CommandSourceStack facing(Vec3 p_81365_) {
Vec3 vec3 = this.anchor.apply(this);
double d0 = p_81365_.x - vec3.x;
double d1 = p_81365_.y - vec3.y;
double d2 = p_81365_.z - vec3.z;
double d3 = Math.sqrt(d0 * d0 + d2 * d2);
float f = Mth.wrapDegrees((float)(-(Mth.atan2(d1, d3) * (double)(180F / (float)Math.PI))));
float f1 = Mth.wrapDegrees((float)(Mth.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F);
return this.withRotation(new Vec2(f, f1));
}
public CommandSourceStack withSigningContext(CommandSigningContext p_230894_) {
return p_230894_ == this.signingContext ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, p_230894_, this.chatMessageChainer, this.returnValueConsumer);
}
public CommandSourceStack withChatMessageChainer(TaskChainer p_242228_) {
return p_242228_ == this.chatMessageChainer ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, p_242228_, this.returnValueConsumer);
}
public CommandSourceStack withReturnValueConsumer(IntConsumer p_282875_) {
return p_282875_ == this.returnValueConsumer ? this : new CommandSourceStack(this.source, this.worldPosition, this.rotation, this.level, this.permissionLevel, this.textName, this.displayName, this.server, this.entity, this.silent, this.consumer, this.anchor, this.signingContext, this.chatMessageChainer, p_282875_);
}
public Component getDisplayName() {
return this.displayName;
}
public String getTextName() {
return this.textName;
}
public boolean hasPermission(int p_81370_) {
return this.permissionLevel >= p_81370_;
}
public Vec3 getPosition() {
return this.worldPosition;
}
public ServerLevel getLevel() {
return this.level;
}
@Nullable
public Entity getEntity() {
return this.entity;
}
public Entity getEntityOrException() throws CommandSyntaxException {
if (this.entity == null) {
throw ERROR_NOT_ENTITY.create();
} else {
return this.entity;
}
}
public ServerPlayer getPlayerOrException() throws CommandSyntaxException {
Entity entity = this.entity;
if (entity instanceof ServerPlayer) {
return (ServerPlayer)entity;
} else {
throw ERROR_NOT_PLAYER.create();
}
}
@Nullable
public ServerPlayer getPlayer() {
Entity entity = this.entity;
ServerPlayer serverplayer1;
if (entity instanceof ServerPlayer serverplayer) {
serverplayer1 = serverplayer;
} else {
serverplayer1 = null;
}
return serverplayer1;
}
public boolean isPlayer() {
return this.entity instanceof ServerPlayer;
}
public Vec2 getRotation() {
return this.rotation;
}
public MinecraftServer getServer() {
return this.server;
}
public EntityAnchorArgument.Anchor getAnchor() {
return this.anchor;
}
public CommandSigningContext getSigningContext() {
return this.signingContext;
}
public TaskChainer getChatMessageChainer() {
return this.chatMessageChainer;
}
public IntConsumer getReturnValueConsumer() {
return this.returnValueConsumer;
}
public boolean shouldFilterMessageTo(ServerPlayer p_243268_) {
ServerPlayer serverplayer = this.getPlayer();
if (p_243268_ == serverplayer) {
return false;
} else {
return serverplayer != null && serverplayer.isTextFilteringEnabled() || p_243268_.isTextFilteringEnabled();
}
}
public void sendChatMessage(OutgoingChatMessage p_251464_, boolean p_252146_, ChatType.Bound p_250406_) {
if (!this.silent) {
ServerPlayer serverplayer = this.getPlayer();
if (serverplayer != null) {
serverplayer.sendChatMessage(p_251464_, p_252146_, p_250406_);
} else {
this.source.sendSystemMessage(p_250406_.decorate(p_251464_.content()));
}
}
}
public void sendSystemMessage(Component p_243331_) {
if (!this.silent) {
ServerPlayer serverplayer = this.getPlayer();
if (serverplayer != null) {
serverplayer.sendSystemMessage(p_243331_);
} else {
this.source.sendSystemMessage(p_243331_);
}
}
}
public void sendSuccess(Supplier<Component> p_288979_, boolean p_289007_) {
boolean flag = this.source.acceptsSuccess() && !this.silent;
boolean flag1 = p_289007_ && this.source.shouldInformAdmins() && !this.silent;
if (flag || flag1) {
Component component = p_288979_.get();
if (flag) {
this.source.sendSystemMessage(component);
}
if (flag1) {
this.broadcastToAdmins(component);
}
}
}
private void broadcastToAdmins(Component p_81367_) {
Component component = Component.translatable("chat.type.admin", this.getDisplayName(), p_81367_).withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC);
if (this.server.getGameRules().getBoolean(GameRules.RULE_SENDCOMMANDFEEDBACK)) {
for(ServerPlayer serverplayer : this.server.getPlayerList().getPlayers()) {
if (serverplayer != this.source && this.server.getPlayerList().isOp(serverplayer.getGameProfile())) {
serverplayer.sendSystemMessage(component);
}
}
}
if (this.source != this.server && this.server.getGameRules().getBoolean(GameRules.RULE_LOGADMINCOMMANDS)) {
this.server.sendSystemMessage(component);
}
}
public void sendFailure(Component p_81353_) {
if (this.source.acceptsFailure() && !this.silent) {
this.source.sendSystemMessage(Component.empty().append(p_81353_).withStyle(ChatFormatting.RED));
}
}
public void onCommandComplete(CommandContext<CommandSourceStack> p_81343_, boolean p_81344_, int p_81345_) {
if (this.consumer != null) {
this.consumer.onCommandComplete(p_81343_, p_81344_, p_81345_);
}
}
public Collection<String> getOnlinePlayerNames() {
return Lists.newArrayList(this.server.getPlayerNames());
}
public Collection<String> getAllTeams() {
return this.server.getScoreboard().getTeamNames();
}
public Stream<ResourceLocation> getAvailableSounds() {
return BuiltInRegistries.SOUND_EVENT.stream().map(SoundEvent::getLocation);
}
public Stream<ResourceLocation> getRecipeNames() {
return this.server.getRecipeManager().getRecipeIds();
}
public CompletableFuture<Suggestions> customSuggestion(CommandContext<?> p_212324_) {
return Suggestions.empty();
}
public CompletableFuture<Suggestions> suggestRegistryElements(ResourceKey<? extends Registry<?>> p_212330_, SharedSuggestionProvider.ElementSuggestionType p_212331_, SuggestionsBuilder p_212332_, CommandContext<?> p_212333_) {
return this.registryAccess().registry(p_212330_).map((p_212328_) -> {
this.suggestRegistryElements(p_212328_, p_212331_, p_212332_);
return p_212332_.buildFuture();
}).orElseGet(Suggestions::empty);
}
public Set<ResourceKey<Level>> levels() {
return this.server.levelKeys();
}
public RegistryAccess registryAccess() {
return this.server.registryAccess();
}
public FeatureFlagSet enabledFeatures() {
return this.level.enabledFeatures();
}
}

View File

@@ -0,0 +1,444 @@
package net.minecraft.commands;
import com.google.common.collect.Maps;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
import com.mojang.logging.LogUtils;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.ChatFormatting;
import net.minecraft.SharedConstants;
import net.minecraft.Util;
import net.minecraft.commands.synchronization.ArgumentTypeInfos;
import net.minecraft.commands.synchronization.ArgumentUtils;
import net.minecraft.commands.synchronization.SuggestionProviders;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.data.registries.VanillaRegistries;
import net.minecraft.gametest.framework.TestCommand;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.protocol.game.ClientboundCommandsPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.commands.AdvancementCommands;
import net.minecraft.server.commands.AttributeCommand;
import net.minecraft.server.commands.BanIpCommands;
import net.minecraft.server.commands.BanListCommands;
import net.minecraft.server.commands.BanPlayerCommands;
import net.minecraft.server.commands.BossBarCommands;
import net.minecraft.server.commands.ClearInventoryCommands;
import net.minecraft.server.commands.CloneCommands;
import net.minecraft.server.commands.DamageCommand;
import net.minecraft.server.commands.DataPackCommand;
import net.minecraft.server.commands.DeOpCommands;
import net.minecraft.server.commands.DebugCommand;
import net.minecraft.server.commands.DefaultGameModeCommands;
import net.minecraft.server.commands.DifficultyCommand;
import net.minecraft.server.commands.EffectCommands;
import net.minecraft.server.commands.EmoteCommands;
import net.minecraft.server.commands.EnchantCommand;
import net.minecraft.server.commands.ExecuteCommand;
import net.minecraft.server.commands.ExperienceCommand;
import net.minecraft.server.commands.FillBiomeCommand;
import net.minecraft.server.commands.FillCommand;
import net.minecraft.server.commands.ForceLoadCommand;
import net.minecraft.server.commands.FunctionCommand;
import net.minecraft.server.commands.GameModeCommand;
import net.minecraft.server.commands.GameRuleCommand;
import net.minecraft.server.commands.GiveCommand;
import net.minecraft.server.commands.HelpCommand;
import net.minecraft.server.commands.ItemCommands;
import net.minecraft.server.commands.JfrCommand;
import net.minecraft.server.commands.KickCommand;
import net.minecraft.server.commands.KillCommand;
import net.minecraft.server.commands.ListPlayersCommand;
import net.minecraft.server.commands.LocateCommand;
import net.minecraft.server.commands.LootCommand;
import net.minecraft.server.commands.MsgCommand;
import net.minecraft.server.commands.OpCommand;
import net.minecraft.server.commands.PardonCommand;
import net.minecraft.server.commands.PardonIpCommand;
import net.minecraft.server.commands.ParticleCommand;
import net.minecraft.server.commands.PerfCommand;
import net.minecraft.server.commands.PlaceCommand;
import net.minecraft.server.commands.PlaySoundCommand;
import net.minecraft.server.commands.PublishCommand;
import net.minecraft.server.commands.RecipeCommand;
import net.minecraft.server.commands.ReloadCommand;
import net.minecraft.server.commands.ReturnCommand;
import net.minecraft.server.commands.RideCommand;
import net.minecraft.server.commands.SaveAllCommand;
import net.minecraft.server.commands.SaveOffCommand;
import net.minecraft.server.commands.SaveOnCommand;
import net.minecraft.server.commands.SayCommand;
import net.minecraft.server.commands.ScheduleCommand;
import net.minecraft.server.commands.ScoreboardCommand;
import net.minecraft.server.commands.SeedCommand;
import net.minecraft.server.commands.SetBlockCommand;
import net.minecraft.server.commands.SetPlayerIdleTimeoutCommand;
import net.minecraft.server.commands.SetSpawnCommand;
import net.minecraft.server.commands.SetWorldSpawnCommand;
import net.minecraft.server.commands.SpawnArmorTrimsCommand;
import net.minecraft.server.commands.SpectateCommand;
import net.minecraft.server.commands.SpreadPlayersCommand;
import net.minecraft.server.commands.StopCommand;
import net.minecraft.server.commands.StopSoundCommand;
import net.minecraft.server.commands.SummonCommand;
import net.minecraft.server.commands.TagCommand;
import net.minecraft.server.commands.TeamCommand;
import net.minecraft.server.commands.TeamMsgCommand;
import net.minecraft.server.commands.TeleportCommand;
import net.minecraft.server.commands.TellRawCommand;
import net.minecraft.server.commands.TimeCommand;
import net.minecraft.server.commands.TitleCommand;
import net.minecraft.server.commands.TriggerCommand;
import net.minecraft.server.commands.WeatherCommand;
import net.minecraft.server.commands.WhitelistCommand;
import net.minecraft.server.commands.WorldBorderCommand;
import net.minecraft.server.commands.data.DataCommands;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.TagKey;
import net.minecraft.util.profiling.jfr.JvmProfiler;
import org.slf4j.Logger;
public class Commands {
private static final Logger LOGGER = LogUtils.getLogger();
public static final int LEVEL_ALL = 0;
public static final int LEVEL_MODERATORS = 1;
public static final int LEVEL_GAMEMASTERS = 2;
public static final int LEVEL_ADMINS = 3;
public static final int LEVEL_OWNERS = 4;
private final CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
public Commands(Commands.CommandSelection p_230943_, CommandBuildContext p_230944_) {
AdvancementCommands.register(this.dispatcher);
AttributeCommand.register(this.dispatcher, p_230944_);
ExecuteCommand.register(this.dispatcher, p_230944_);
BossBarCommands.register(this.dispatcher);
ClearInventoryCommands.register(this.dispatcher, p_230944_);
CloneCommands.register(this.dispatcher, p_230944_);
DamageCommand.register(this.dispatcher, p_230944_);
DataCommands.register(this.dispatcher);
DataPackCommand.register(this.dispatcher);
DebugCommand.register(this.dispatcher);
DefaultGameModeCommands.register(this.dispatcher);
DifficultyCommand.register(this.dispatcher);
EffectCommands.register(this.dispatcher, p_230944_);
EmoteCommands.register(this.dispatcher);
EnchantCommand.register(this.dispatcher, p_230944_);
ExperienceCommand.register(this.dispatcher);
FillCommand.register(this.dispatcher, p_230944_);
FillBiomeCommand.register(this.dispatcher, p_230944_);
ForceLoadCommand.register(this.dispatcher);
FunctionCommand.register(this.dispatcher);
GameModeCommand.register(this.dispatcher);
GameRuleCommand.register(this.dispatcher);
GiveCommand.register(this.dispatcher, p_230944_);
HelpCommand.register(this.dispatcher);
ItemCommands.register(this.dispatcher, p_230944_);
KickCommand.register(this.dispatcher);
KillCommand.register(this.dispatcher);
ListPlayersCommand.register(this.dispatcher);
LocateCommand.register(this.dispatcher, p_230944_);
LootCommand.register(this.dispatcher, p_230944_);
MsgCommand.register(this.dispatcher);
ParticleCommand.register(this.dispatcher, p_230944_);
PlaceCommand.register(this.dispatcher);
PlaySoundCommand.register(this.dispatcher);
ReloadCommand.register(this.dispatcher);
RecipeCommand.register(this.dispatcher);
ReturnCommand.register(this.dispatcher);
RideCommand.register(this.dispatcher);
SayCommand.register(this.dispatcher);
ScheduleCommand.register(this.dispatcher);
ScoreboardCommand.register(this.dispatcher);
SeedCommand.register(this.dispatcher, p_230943_ != Commands.CommandSelection.INTEGRATED);
SetBlockCommand.register(this.dispatcher, p_230944_);
SetSpawnCommand.register(this.dispatcher);
SetWorldSpawnCommand.register(this.dispatcher);
SpectateCommand.register(this.dispatcher);
SpreadPlayersCommand.register(this.dispatcher);
StopSoundCommand.register(this.dispatcher);
SummonCommand.register(this.dispatcher, p_230944_);
TagCommand.register(this.dispatcher);
TeamCommand.register(this.dispatcher);
TeamMsgCommand.register(this.dispatcher);
TeleportCommand.register(this.dispatcher);
TellRawCommand.register(this.dispatcher);
TimeCommand.register(this.dispatcher);
TitleCommand.register(this.dispatcher);
TriggerCommand.register(this.dispatcher);
WeatherCommand.register(this.dispatcher);
WorldBorderCommand.register(this.dispatcher);
if (JvmProfiler.INSTANCE.isAvailable()) {
JfrCommand.register(this.dispatcher);
}
if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) {
TestCommand.register(this.dispatcher);
SpawnArmorTrimsCommand.register(this.dispatcher);
}
if (p_230943_.includeDedicated) {
BanIpCommands.register(this.dispatcher);
BanListCommands.register(this.dispatcher);
BanPlayerCommands.register(this.dispatcher);
DeOpCommands.register(this.dispatcher);
OpCommand.register(this.dispatcher);
PardonCommand.register(this.dispatcher);
PardonIpCommand.register(this.dispatcher);
PerfCommand.register(this.dispatcher);
SaveAllCommand.register(this.dispatcher);
SaveOffCommand.register(this.dispatcher);
SaveOnCommand.register(this.dispatcher);
SetPlayerIdleTimeoutCommand.register(this.dispatcher);
StopCommand.register(this.dispatcher);
WhitelistCommand.register(this.dispatcher);
}
if (p_230943_.includeIntegrated) {
PublishCommand.register(this.dispatcher);
}
net.minecraftforge.event.ForgeEventFactory.onCommandRegister(this.dispatcher, p_230943_, p_230944_);
this.dispatcher.setConsumer((p_230954_, p_230955_, p_230956_) -> {
p_230954_.getSource().onCommandComplete(p_230954_, p_230955_, p_230956_);
p_230954_.getSource().onCommandComplete(p_230954_, p_230955_, p_230956_);
});
}
public static <S> ParseResults<S> mapSource(ParseResults<S> p_242928_, UnaryOperator<S> p_242890_) {
CommandContextBuilder<S> commandcontextbuilder = p_242928_.getContext();
CommandContextBuilder<S> commandcontextbuilder1 = commandcontextbuilder.withSource(p_242890_.apply(commandcontextbuilder.getSource()));
return new ParseResults<>(commandcontextbuilder1, p_242928_.getReader(), p_242928_.getExceptions());
}
public int performPrefixedCommand(CommandSourceStack p_230958_, String p_230959_) {
p_230959_ = p_230959_.startsWith("/") ? p_230959_.substring(1) : p_230959_;
return this.performCommand(this.dispatcher.parse(p_230959_, p_230958_), p_230959_);
}
public int performCommand(ParseResults<CommandSourceStack> p_242844_, String p_242841_) {
CommandSourceStack commandsourcestack = p_242844_.getContext().getSource();
commandsourcestack.getServer().getProfiler().push(() -> {
return "/" + p_242841_;
});
try {
try {
net.minecraftforge.event.CommandEvent event = new net.minecraftforge.event.CommandEvent(p_242844_);
if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) {
if (event.getException() instanceof Exception exception) {
throw exception;
} else if (event.getException() != null) {
com.google.common.base.Throwables.throwIfUnchecked(event.getException());
}
return 1;
}
return this.dispatcher.execute(event.getParseResults());
} catch (CommandRuntimeException commandruntimeexception) {
commandsourcestack.sendFailure(commandruntimeexception.getComponent());
return 0;
} catch (CommandSyntaxException commandsyntaxexception) {
commandsourcestack.sendFailure(ComponentUtils.fromMessage(commandsyntaxexception.getRawMessage()));
if (commandsyntaxexception.getInput() != null && commandsyntaxexception.getCursor() >= 0) {
int j = Math.min(commandsyntaxexception.getInput().length(), commandsyntaxexception.getCursor());
MutableComponent mutablecomponent1 = Component.empty().withStyle(ChatFormatting.GRAY).withStyle((p_82134_) -> {
return p_82134_.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + p_242841_));
});
if (j > 10) {
mutablecomponent1.append(CommonComponents.ELLIPSIS);
}
mutablecomponent1.append(commandsyntaxexception.getInput().substring(Math.max(0, j - 10), j));
if (j < commandsyntaxexception.getInput().length()) {
Component component = Component.literal(commandsyntaxexception.getInput().substring(j)).withStyle(ChatFormatting.RED, ChatFormatting.UNDERLINE);
mutablecomponent1.append(component);
}
mutablecomponent1.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
commandsourcestack.sendFailure(mutablecomponent1);
}
} catch (Exception exception) {
MutableComponent mutablecomponent = Component.literal(exception.getMessage() == null ? exception.getClass().getName() : exception.getMessage());
if (LOGGER.isDebugEnabled()) {
LOGGER.error("Command exception: /{}", p_242841_, exception);
StackTraceElement[] astacktraceelement = exception.getStackTrace();
for(int i = 0; i < Math.min(astacktraceelement.length, 3); ++i) {
mutablecomponent.append("\n\n").append(astacktraceelement[i].getMethodName()).append("\n ").append(astacktraceelement[i].getFileName()).append(":").append(String.valueOf(astacktraceelement[i].getLineNumber()));
}
}
commandsourcestack.sendFailure(Component.translatable("command.failed").withStyle((p_82137_) -> {
return p_82137_.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, mutablecomponent));
}));
if (SharedConstants.IS_RUNNING_IN_IDE) {
commandsourcestack.sendFailure(Component.literal(Util.describeError(exception)));
LOGGER.error("'/{}' threw an exception", p_242841_, exception);
}
return 0;
}
return 0;
} finally {
commandsourcestack.getServer().getProfiler().pop();
}
}
public void sendCommands(ServerPlayer p_82096_) {
Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> map = Maps.newHashMap();
RootCommandNode<SharedSuggestionProvider> rootcommandnode = new RootCommandNode<>();
map.put(this.dispatcher.getRoot(), rootcommandnode);
// FORGE: Use our own command node merging method to handle redirect nodes properly, see issue #7551
net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, p_82096_.createCommandSourceStack(), ctx -> 0, suggest -> SuggestionProviders.safelySwap((com.mojang.brigadier.suggestion.SuggestionProvider<SharedSuggestionProvider>) (com.mojang.brigadier.suggestion.SuggestionProvider<?>) suggest));
p_82096_.connection.send(new ClientboundCommandsPacket(rootcommandnode));
}
private void fillUsableCommands(CommandNode<CommandSourceStack> p_82113_, CommandNode<SharedSuggestionProvider> p_82114_, CommandSourceStack p_82115_, Map<CommandNode<CommandSourceStack>, CommandNode<SharedSuggestionProvider>> p_82116_) {
for(CommandNode<CommandSourceStack> commandnode : p_82113_.getChildren()) {
if (commandnode.canUse(p_82115_)) {
ArgumentBuilder<SharedSuggestionProvider, ?> argumentbuilder = (ArgumentBuilder)commandnode.createBuilder();
argumentbuilder.requires((p_82126_) -> {
return true;
});
if (argumentbuilder.getCommand() != null) {
argumentbuilder.executes((p_82102_) -> {
return 0;
});
}
if (argumentbuilder instanceof RequiredArgumentBuilder) {
RequiredArgumentBuilder<SharedSuggestionProvider, ?> requiredargumentbuilder = (RequiredArgumentBuilder)argumentbuilder;
if (requiredargumentbuilder.getSuggestionsProvider() != null) {
requiredargumentbuilder.suggests(SuggestionProviders.safelySwap(requiredargumentbuilder.getSuggestionsProvider()));
}
}
if (argumentbuilder.getRedirect() != null) {
argumentbuilder.redirect(p_82116_.get(argumentbuilder.getRedirect()));
}
CommandNode<SharedSuggestionProvider> commandnode1 = argumentbuilder.build();
p_82116_.put(commandnode, commandnode1);
p_82114_.addChild(commandnode1);
if (!commandnode.getChildren().isEmpty()) {
this.fillUsableCommands(commandnode, commandnode1, p_82115_, p_82116_);
}
}
}
}
public static LiteralArgumentBuilder<CommandSourceStack> literal(String p_82128_) {
return LiteralArgumentBuilder.literal(p_82128_);
}
public static <T> RequiredArgumentBuilder<CommandSourceStack, T> argument(String p_82130_, ArgumentType<T> p_82131_) {
return RequiredArgumentBuilder.argument(p_82130_, p_82131_);
}
public static Predicate<String> createValidator(Commands.ParseFunction p_82121_) {
return (p_82124_) -> {
try {
p_82121_.parse(new StringReader(p_82124_));
return true;
} catch (CommandSyntaxException commandsyntaxexception) {
return false;
}
};
}
public CommandDispatcher<CommandSourceStack> getDispatcher() {
return this.dispatcher;
}
@Nullable
public static <S> CommandSyntaxException getParseException(ParseResults<S> p_82098_) {
if (!p_82098_.getReader().canRead()) {
return null;
} else if (p_82098_.getExceptions().size() == 1) {
return p_82098_.getExceptions().values().iterator().next();
} else {
return p_82098_.getContext().getRange().isEmpty() ? CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(p_82098_.getReader()) : CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(p_82098_.getReader());
}
}
public static CommandBuildContext createValidationContext(final HolderLookup.Provider p_256243_) {
return new CommandBuildContext() {
public <T> HolderLookup<T> holderLookup(ResourceKey<? extends Registry<T>> p_256244_) {
final HolderLookup.RegistryLookup<T> registrylookup = p_256243_.lookupOrThrow(p_256244_);
return new HolderLookup.Delegate<T>(registrylookup) {
public Optional<HolderSet.Named<T>> get(TagKey<T> p_255936_) {
return Optional.of(this.getOrThrow(p_255936_));
}
public HolderSet.Named<T> getOrThrow(TagKey<T> p_255953_) {
Optional<HolderSet.Named<T>> optional = registrylookup.get(p_255953_);
return optional.orElseGet(() -> {
return HolderSet.emptyNamed(registrylookup, p_255953_);
});
}
};
}
};
}
public static void validate() {
CommandBuildContext commandbuildcontext = createValidationContext(VanillaRegistries.createLookup());
CommandDispatcher<CommandSourceStack> commanddispatcher = (new Commands(Commands.CommandSelection.ALL, commandbuildcontext)).getDispatcher();
RootCommandNode<CommandSourceStack> rootcommandnode = commanddispatcher.getRoot();
commanddispatcher.findAmbiguities((p_230947_, p_230948_, p_230949_, p_230950_) -> {
LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", commanddispatcher.getPath(p_230948_), commanddispatcher.getPath(p_230949_), p_230950_);
});
Set<ArgumentType<?>> set = ArgumentUtils.findUsedArgumentTypes(rootcommandnode);
Set<ArgumentType<?>> set1 = set.stream().filter((p_230961_) -> {
return !ArgumentTypeInfos.isClassRecognized(p_230961_.getClass());
}).collect(Collectors.toSet());
if (!set1.isEmpty()) {
LOGGER.warn("Missing type registration for following arguments:\n {}", set1.stream().map((p_230952_) -> {
return "\t" + p_230952_;
}).collect(Collectors.joining(",\n")));
throw new IllegalStateException("Unregistered argument types");
}
}
public static enum CommandSelection {
ALL(true, true),
DEDICATED(false, true),
INTEGRATED(true, false);
final boolean includeIntegrated;
final boolean includeDedicated;
private CommandSelection(boolean p_82151_, boolean p_82152_) {
this.includeIntegrated = p_82151_;
this.includeDedicated = p_82152_;
}
}
@FunctionalInterface
public interface ParseFunction {
void parse(StringReader p_82161_) throws CommandSyntaxException;
}
}

View File

@@ -0,0 +1,287 @@
package net.minecraft.commands;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.level.Level;
public interface SharedSuggestionProvider {
Collection<String> getOnlinePlayerNames();
default Collection<String> getCustomTabSugggestions() {
return this.getOnlinePlayerNames();
}
default Collection<String> getSelectedEntities() {
return Collections.emptyList();
}
Collection<String> getAllTeams();
Stream<ResourceLocation> getAvailableSounds();
Stream<ResourceLocation> getRecipeNames();
CompletableFuture<Suggestions> customSuggestion(CommandContext<?> p_212334_);
default Collection<SharedSuggestionProvider.TextCoordinates> getRelevantCoordinates() {
return Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_GLOBAL);
}
default Collection<SharedSuggestionProvider.TextCoordinates> getAbsoluteCoordinates() {
return Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_GLOBAL);
}
Set<ResourceKey<Level>> levels();
RegistryAccess registryAccess();
FeatureFlagSet enabledFeatures();
default void suggestRegistryElements(Registry<?> p_212336_, SharedSuggestionProvider.ElementSuggestionType p_212337_, SuggestionsBuilder p_212338_) {
if (p_212337_.shouldSuggestTags()) {
suggestResource(p_212336_.getTagNames().map(TagKey::location), p_212338_, "#");
}
if (p_212337_.shouldSuggestElements()) {
suggestResource(p_212336_.keySet(), p_212338_);
}
}
CompletableFuture<Suggestions> suggestRegistryElements(ResourceKey<? extends Registry<?>> p_212339_, SharedSuggestionProvider.ElementSuggestionType p_212340_, SuggestionsBuilder p_212341_, CommandContext<?> p_212342_);
boolean hasPermission(int p_82986_);
static <T> void filterResources(Iterable<T> p_82945_, String p_82946_, Function<T, ResourceLocation> p_82947_, Consumer<T> p_82948_) {
boolean flag = p_82946_.indexOf(58) > -1;
for(T t : p_82945_) {
ResourceLocation resourcelocation = p_82947_.apply(t);
if (flag) {
String s = resourcelocation.toString();
if (matchesSubStr(p_82946_, s)) {
p_82948_.accept(t);
}
} else if (matchesSubStr(p_82946_, resourcelocation.getNamespace()) || resourcelocation.getNamespace().equals("minecraft") && matchesSubStr(p_82946_, resourcelocation.getPath())) {
p_82948_.accept(t);
}
}
}
static <T> void filterResources(Iterable<T> p_82939_, String p_82940_, String p_82941_, Function<T, ResourceLocation> p_82942_, Consumer<T> p_82943_) {
if (p_82940_.isEmpty()) {
p_82939_.forEach(p_82943_);
} else {
String s = Strings.commonPrefix(p_82940_, p_82941_);
if (!s.isEmpty()) {
String s1 = p_82940_.substring(s.length());
filterResources(p_82939_, s1, p_82942_, p_82943_);
}
}
}
static CompletableFuture<Suggestions> suggestResource(Iterable<ResourceLocation> p_82930_, SuggestionsBuilder p_82931_, String p_82932_) {
String s = p_82931_.getRemaining().toLowerCase(Locale.ROOT);
filterResources(p_82930_, s, p_82932_, (p_82985_) -> {
return p_82985_;
}, (p_82917_) -> {
p_82931_.suggest(p_82932_ + p_82917_);
});
return p_82931_.buildFuture();
}
static CompletableFuture<Suggestions> suggestResource(Stream<ResourceLocation> p_205107_, SuggestionsBuilder p_205108_, String p_205109_) {
return suggestResource(p_205107_::iterator, p_205108_, p_205109_);
}
static CompletableFuture<Suggestions> suggestResource(Iterable<ResourceLocation> p_82927_, SuggestionsBuilder p_82928_) {
String s = p_82928_.getRemaining().toLowerCase(Locale.ROOT);
filterResources(p_82927_, s, (p_82966_) -> {
return p_82966_;
}, (p_82925_) -> {
p_82928_.suggest(p_82925_.toString());
});
return p_82928_.buildFuture();
}
static <T> CompletableFuture<Suggestions> suggestResource(Iterable<T> p_82934_, SuggestionsBuilder p_82935_, Function<T, ResourceLocation> p_82936_, Function<T, Message> p_82937_) {
String s = p_82935_.getRemaining().toLowerCase(Locale.ROOT);
filterResources(p_82934_, s, p_82936_, (p_82922_) -> {
p_82935_.suggest(p_82936_.apply(p_82922_).toString(), p_82937_.apply(p_82922_));
});
return p_82935_.buildFuture();
}
static CompletableFuture<Suggestions> suggestResource(Stream<ResourceLocation> p_82958_, SuggestionsBuilder p_82959_) {
return suggestResource(p_82958_::iterator, p_82959_);
}
static <T> CompletableFuture<Suggestions> suggestResource(Stream<T> p_82961_, SuggestionsBuilder p_82962_, Function<T, ResourceLocation> p_82963_, Function<T, Message> p_82964_) {
return suggestResource(p_82961_::iterator, p_82962_, p_82963_, p_82964_);
}
static CompletableFuture<Suggestions> suggestCoordinates(String p_82953_, Collection<SharedSuggestionProvider.TextCoordinates> p_82954_, SuggestionsBuilder p_82955_, Predicate<String> p_82956_) {
List<String> list = Lists.newArrayList();
if (Strings.isNullOrEmpty(p_82953_)) {
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates : p_82954_) {
String s = sharedsuggestionprovider$textcoordinates.x + " " + sharedsuggestionprovider$textcoordinates.y + " " + sharedsuggestionprovider$textcoordinates.z;
if (p_82956_.test(s)) {
list.add(sharedsuggestionprovider$textcoordinates.x);
list.add(sharedsuggestionprovider$textcoordinates.x + " " + sharedsuggestionprovider$textcoordinates.y);
list.add(s);
}
}
} else {
String[] astring = p_82953_.split(" ");
if (astring.length == 1) {
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates1 : p_82954_) {
String s1 = astring[0] + " " + sharedsuggestionprovider$textcoordinates1.y + " " + sharedsuggestionprovider$textcoordinates1.z;
if (p_82956_.test(s1)) {
list.add(astring[0] + " " + sharedsuggestionprovider$textcoordinates1.y);
list.add(s1);
}
}
} else if (astring.length == 2) {
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates2 : p_82954_) {
String s2 = astring[0] + " " + astring[1] + " " + sharedsuggestionprovider$textcoordinates2.z;
if (p_82956_.test(s2)) {
list.add(s2);
}
}
}
}
return suggest(list, p_82955_);
}
static CompletableFuture<Suggestions> suggest2DCoordinates(String p_82977_, Collection<SharedSuggestionProvider.TextCoordinates> p_82978_, SuggestionsBuilder p_82979_, Predicate<String> p_82980_) {
List<String> list = Lists.newArrayList();
if (Strings.isNullOrEmpty(p_82977_)) {
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates : p_82978_) {
String s = sharedsuggestionprovider$textcoordinates.x + " " + sharedsuggestionprovider$textcoordinates.z;
if (p_82980_.test(s)) {
list.add(sharedsuggestionprovider$textcoordinates.x);
list.add(s);
}
}
} else {
String[] astring = p_82977_.split(" ");
if (astring.length == 1) {
for(SharedSuggestionProvider.TextCoordinates sharedsuggestionprovider$textcoordinates1 : p_82978_) {
String s1 = astring[0] + " " + sharedsuggestionprovider$textcoordinates1.z;
if (p_82980_.test(s1)) {
list.add(s1);
}
}
}
}
return suggest(list, p_82979_);
}
static CompletableFuture<Suggestions> suggest(Iterable<String> p_82971_, SuggestionsBuilder p_82972_) {
String s = p_82972_.getRemaining().toLowerCase(Locale.ROOT);
for(String s1 : p_82971_) {
if (matchesSubStr(s, s1.toLowerCase(Locale.ROOT))) {
p_82972_.suggest(s1);
}
}
return p_82972_.buildFuture();
}
static CompletableFuture<Suggestions> suggest(Stream<String> p_82982_, SuggestionsBuilder p_82983_) {
String s = p_82983_.getRemaining().toLowerCase(Locale.ROOT);
p_82982_.filter((p_82975_) -> {
return matchesSubStr(s, p_82975_.toLowerCase(Locale.ROOT));
}).forEach(p_82983_::suggest);
return p_82983_.buildFuture();
}
static CompletableFuture<Suggestions> suggest(String[] p_82968_, SuggestionsBuilder p_82969_) {
String s = p_82969_.getRemaining().toLowerCase(Locale.ROOT);
for(String s1 : p_82968_) {
if (matchesSubStr(s, s1.toLowerCase(Locale.ROOT))) {
p_82969_.suggest(s1);
}
}
return p_82969_.buildFuture();
}
static <T> CompletableFuture<Suggestions> suggest(Iterable<T> p_165917_, SuggestionsBuilder p_165918_, Function<T, String> p_165919_, Function<T, Message> p_165920_) {
String s = p_165918_.getRemaining().toLowerCase(Locale.ROOT);
for(T t : p_165917_) {
String s1 = p_165919_.apply(t);
if (matchesSubStr(s, s1.toLowerCase(Locale.ROOT))) {
p_165918_.suggest(s1, p_165920_.apply(t));
}
}
return p_165918_.buildFuture();
}
static boolean matchesSubStr(String p_82950_, String p_82951_) {
for(int i = 0; !p_82951_.startsWith(p_82950_, i); ++i) {
i = p_82951_.indexOf(95, i);
if (i < 0) {
return false;
}
}
return true;
}
public static enum ElementSuggestionType {
TAGS,
ELEMENTS,
ALL;
public boolean shouldSuggestTags() {
return this == TAGS || this == ALL;
}
public boolean shouldSuggestElements() {
return this == ELEMENTS || this == ALL;
}
}
public static class TextCoordinates {
public static final SharedSuggestionProvider.TextCoordinates DEFAULT_LOCAL = new SharedSuggestionProvider.TextCoordinates("^", "^", "^");
public static final SharedSuggestionProvider.TextCoordinates DEFAULT_GLOBAL = new SharedSuggestionProvider.TextCoordinates("~", "~", "~");
public final String x;
public final String y;
public final String z;
public TextCoordinates(String p_82994_, String p_82995_, String p_82996_) {
this.x = p_82994_;
this.y = p_82995_;
this.z = p_82996_;
}
}
}

View File

@@ -0,0 +1,59 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.coordinates.WorldCoordinate;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth;
public class AngleArgument implements ArgumentType<AngleArgument.SingleAngle> {
private static final Collection<String> EXAMPLES = Arrays.asList("0", "~", "~-5");
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.angle.incomplete"));
public static final SimpleCommandExceptionType ERROR_INVALID_ANGLE = new SimpleCommandExceptionType(Component.translatable("argument.angle.invalid"));
public static AngleArgument angle() {
return new AngleArgument();
}
public static float getAngle(CommandContext<CommandSourceStack> p_83811_, String p_83812_) {
return p_83811_.getArgument(p_83812_, AngleArgument.SingleAngle.class).getAngle(p_83811_.getSource());
}
public AngleArgument.SingleAngle parse(StringReader p_83809_) throws CommandSyntaxException {
if (!p_83809_.canRead()) {
throw ERROR_NOT_COMPLETE.createWithContext(p_83809_);
} else {
boolean flag = WorldCoordinate.isRelative(p_83809_);
float f = p_83809_.canRead() && p_83809_.peek() != ' ' ? p_83809_.readFloat() : 0.0F;
if (!Float.isNaN(f) && !Float.isInfinite(f)) {
return new AngleArgument.SingleAngle(f, flag);
} else {
throw ERROR_INVALID_ANGLE.createWithContext(p_83809_);
}
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static final class SingleAngle {
private final float angle;
private final boolean isRelative;
SingleAngle(float p_83819_, boolean p_83820_) {
this.angle = p_83819_;
this.isRelative = p_83820_;
}
public float getAngle(CommandSourceStack p_83826_) {
return Mth.wrapDegrees(this.isRelative ? this.angle + p_83826_.getRotation().y : this.angle);
}
}
}

View File

@@ -0,0 +1,61 @@
package net.minecraft.commands.arguments;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nullable;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.MessageSignature;
import net.minecraft.network.chat.SignableCommand;
public record ArgumentSignatures(List<ArgumentSignatures.Entry> entries) {
public static final ArgumentSignatures EMPTY = new ArgumentSignatures(List.of());
private static final int MAX_ARGUMENT_COUNT = 8;
private static final int MAX_ARGUMENT_NAME_LENGTH = 16;
public ArgumentSignatures(FriendlyByteBuf p_231052_) {
this(p_231052_.<ArgumentSignatures.Entry, List<ArgumentSignatures.Entry>>readCollection(FriendlyByteBuf.limitValue(ArrayList::new, 8), ArgumentSignatures.Entry::new));
}
@Nullable
public MessageSignature get(String p_241493_) {
for(ArgumentSignatures.Entry argumentsignatures$entry : this.entries) {
if (argumentsignatures$entry.name.equals(p_241493_)) {
return argumentsignatures$entry.signature;
}
}
return null;
}
public void write(FriendlyByteBuf p_231062_) {
p_231062_.writeCollection(this.entries, (p_241214_, p_241215_) -> {
p_241215_.write(p_241214_);
});
}
public static ArgumentSignatures signCommand(SignableCommand<?> p_251621_, ArgumentSignatures.Signer p_248653_) {
List<ArgumentSignatures.Entry> list = p_251621_.arguments().stream().map((p_247962_) -> {
MessageSignature messagesignature = p_248653_.sign(p_247962_.value());
return messagesignature != null ? new ArgumentSignatures.Entry(p_247962_.name(), messagesignature) : null;
}).filter(Objects::nonNull).toList();
return new ArgumentSignatures(list);
}
public static record Entry(String name, MessageSignature signature) {
public Entry(FriendlyByteBuf p_241305_) {
this(p_241305_.readUtf(16), MessageSignature.read(p_241305_));
}
public void write(FriendlyByteBuf p_241403_) {
p_241403_.writeUtf(this.name, 16);
MessageSignature.write(p_241403_, this.signature);
}
}
@FunctionalInterface
public interface Signer {
@Nullable
MessageSignature sign(String p_241389_);
}
}

View File

@@ -0,0 +1,52 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
public class ColorArgument implements ArgumentType<ChatFormatting> {
private static final Collection<String> EXAMPLES = Arrays.asList("red", "green");
public static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_85470_) -> {
return Component.translatable("argument.color.invalid", p_85470_);
});
private ColorArgument() {
}
public static ColorArgument color() {
return new ColorArgument();
}
public static ChatFormatting getColor(CommandContext<CommandSourceStack> p_85467_, String p_85468_) {
return p_85467_.getArgument(p_85468_, ChatFormatting.class);
}
public ChatFormatting parse(StringReader p_85465_) throws CommandSyntaxException {
String s = p_85465_.readUnquotedString();
ChatFormatting chatformatting = ChatFormatting.getByName(s);
if (chatformatting != null && !chatformatting.isFormat()) {
return chatformatting;
} else {
throw ERROR_INVALID_VALUE.create(s);
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_85473_, SuggestionsBuilder p_85474_) {
return SharedSuggestionProvider.suggest(ChatFormatting.getNames(true, false), p_85474_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,47 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
public class ComponentArgument implements ArgumentType<Component> {
private static final Collection<String> EXAMPLES = Arrays.asList("\"hello world\"", "\"\"", "\"{\"text\":\"hello world\"}", "[\"\"]");
public static final DynamicCommandExceptionType ERROR_INVALID_JSON = new DynamicCommandExceptionType((p_87121_) -> {
return Component.translatable("argument.component.invalid", p_87121_);
});
private ComponentArgument() {
}
public static Component getComponent(CommandContext<CommandSourceStack> p_87118_, String p_87119_) {
return p_87118_.getArgument(p_87119_, Component.class);
}
public static ComponentArgument textComponent() {
return new ComponentArgument();
}
public Component parse(StringReader p_87116_) throws CommandSyntaxException {
try {
Component component = Component.Serializer.fromJson(p_87116_);
if (component == null) {
throw ERROR_INVALID_JSON.createWithContext(p_87116_, "empty");
} else {
return component;
}
} catch (Exception exception) {
String s = exception.getCause() != null ? exception.getCause().getMessage() : exception.getMessage();
throw ERROR_INVALID_JSON.createWithContext(p_87116_, s);
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,33 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
public class CompoundTagArgument implements ArgumentType<CompoundTag> {
private static final Collection<String> EXAMPLES = Arrays.asList("{}", "{foo=bar}");
private CompoundTagArgument() {
}
public static CompoundTagArgument compoundTag() {
return new CompoundTagArgument();
}
public static <S> CompoundTag getCompoundTag(CommandContext<S> p_87661_, String p_87662_) {
return p_87661_.getArgument(p_87662_, CompoundTag.class);
}
public CompoundTag parse(StringReader p_87659_) throws CommandSyntaxException {
return (new TagParser(p_87659_)).readStruct();
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,57 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
public class DimensionArgument implements ArgumentType<ResourceLocation> {
private static final Collection<String> EXAMPLES = Stream.of(Level.OVERWORLD, Level.NETHER).map((p_88814_) -> {
return p_88814_.location().toString();
}).collect(Collectors.toList());
private static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_88812_) -> {
return Component.translatable("argument.dimension.invalid", p_88812_);
});
public ResourceLocation parse(StringReader p_88807_) throws CommandSyntaxException {
return ResourceLocation.read(p_88807_);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_88817_, SuggestionsBuilder p_88818_) {
return p_88817_.getSource() instanceof SharedSuggestionProvider ? SharedSuggestionProvider.suggestResource(((SharedSuggestionProvider)p_88817_.getSource()).levels().stream().map(ResourceKey::location), p_88818_) : Suggestions.empty();
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static DimensionArgument dimension() {
return new DimensionArgument();
}
public static ServerLevel getDimension(CommandContext<CommandSourceStack> p_88809_, String p_88810_) throws CommandSyntaxException {
ResourceLocation resourcelocation = p_88809_.getArgument(p_88810_, ResourceLocation.class);
ResourceKey<Level> resourcekey = ResourceKey.create(Registries.DIMENSION, resourcelocation);
ServerLevel serverlevel = p_88809_.getSource().getServer().getLevel(resourcekey);
if (serverlevel == null) {
throw ERROR_INVALID_VALUE.create(resourcelocation);
} else {
return serverlevel;
}
}
}

View File

@@ -0,0 +1,94 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Maps;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import javax.annotation.Nullable;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
public class EntityAnchorArgument implements ArgumentType<EntityAnchorArgument.Anchor> {
private static final Collection<String> EXAMPLES = Arrays.asList("eyes", "feet");
private static final DynamicCommandExceptionType ERROR_INVALID = new DynamicCommandExceptionType((p_90357_) -> {
return Component.translatable("argument.anchor.invalid", p_90357_);
});
public static EntityAnchorArgument.Anchor getAnchor(CommandContext<CommandSourceStack> p_90354_, String p_90355_) {
return p_90354_.getArgument(p_90355_, EntityAnchorArgument.Anchor.class);
}
public static EntityAnchorArgument anchor() {
return new EntityAnchorArgument();
}
public EntityAnchorArgument.Anchor parse(StringReader p_90352_) throws CommandSyntaxException {
int i = p_90352_.getCursor();
String s = p_90352_.readUnquotedString();
EntityAnchorArgument.Anchor entityanchorargument$anchor = EntityAnchorArgument.Anchor.getByName(s);
if (entityanchorargument$anchor == null) {
p_90352_.setCursor(i);
throw ERROR_INVALID.createWithContext(p_90352_, s);
} else {
return entityanchorargument$anchor;
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_90360_, SuggestionsBuilder p_90361_) {
return SharedSuggestionProvider.suggest(EntityAnchorArgument.Anchor.BY_NAME.keySet(), p_90361_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static enum Anchor {
FEET("feet", (p_90389_, p_90390_) -> {
return p_90389_;
}),
EYES("eyes", (p_90382_, p_90383_) -> {
return new Vec3(p_90382_.x, p_90382_.y + (double)p_90383_.getEyeHeight(), p_90382_.z);
});
static final Map<String, EntityAnchorArgument.Anchor> BY_NAME = Util.make(Maps.newHashMap(), (p_90387_) -> {
for(EntityAnchorArgument.Anchor entityanchorargument$anchor : values()) {
p_90387_.put(entityanchorargument$anchor.name, entityanchorargument$anchor);
}
});
private final String name;
private final BiFunction<Vec3, Entity, Vec3> transform;
private Anchor(String p_90374_, BiFunction<Vec3, Entity, Vec3> p_90375_) {
this.name = p_90374_;
this.transform = p_90375_;
}
@Nullable
public static EntityAnchorArgument.Anchor getByName(String p_90385_) {
return BY_NAME.get(p_90385_);
}
public Vec3 apply(Entity p_90378_) {
return this.transform.apply(p_90378_.position(), p_90378_);
}
public Vec3 apply(CommandSourceStack p_90380_) {
Entity entity = p_90380_.getEntity();
return entity == null ? p_90380_.getPosition() : this.transform.apply(p_90380_.getPosition(), entity);
}
}
}

View File

@@ -0,0 +1,188 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Iterables;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
public class EntityArgument implements ArgumentType<EntitySelector> {
private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "@e", "@e[type=foo]", "dd12be42-52a9-4a91-a8a1-11c01849e498");
public static final SimpleCommandExceptionType ERROR_NOT_SINGLE_ENTITY = new SimpleCommandExceptionType(Component.translatable("argument.entity.toomany"));
public static final SimpleCommandExceptionType ERROR_NOT_SINGLE_PLAYER = new SimpleCommandExceptionType(Component.translatable("argument.player.toomany"));
public static final SimpleCommandExceptionType ERROR_ONLY_PLAYERS_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.player.entities"));
public static final SimpleCommandExceptionType NO_ENTITIES_FOUND = new SimpleCommandExceptionType(Component.translatable("argument.entity.notfound.entity"));
public static final SimpleCommandExceptionType NO_PLAYERS_FOUND = new SimpleCommandExceptionType(Component.translatable("argument.entity.notfound.player"));
public static final SimpleCommandExceptionType ERROR_SELECTORS_NOT_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.entity.selector.not_allowed"));
final boolean single;
final boolean playersOnly;
protected EntityArgument(boolean p_91447_, boolean p_91448_) {
this.single = p_91447_;
this.playersOnly = p_91448_;
}
public static EntityArgument entity() {
return new EntityArgument(true, false);
}
public static Entity getEntity(CommandContext<CommandSourceStack> p_91453_, String p_91454_) throws CommandSyntaxException {
return p_91453_.getArgument(p_91454_, EntitySelector.class).findSingleEntity(p_91453_.getSource());
}
public static EntityArgument entities() {
return new EntityArgument(false, false);
}
public static Collection<? extends Entity> getEntities(CommandContext<CommandSourceStack> p_91462_, String p_91463_) throws CommandSyntaxException {
Collection<? extends Entity> collection = getOptionalEntities(p_91462_, p_91463_);
if (collection.isEmpty()) {
throw NO_ENTITIES_FOUND.create();
} else {
return collection;
}
}
public static Collection<? extends Entity> getOptionalEntities(CommandContext<CommandSourceStack> p_91468_, String p_91469_) throws CommandSyntaxException {
return p_91468_.getArgument(p_91469_, EntitySelector.class).findEntities(p_91468_.getSource());
}
public static Collection<ServerPlayer> getOptionalPlayers(CommandContext<CommandSourceStack> p_91472_, String p_91473_) throws CommandSyntaxException {
return p_91472_.getArgument(p_91473_, EntitySelector.class).findPlayers(p_91472_.getSource());
}
public static EntityArgument player() {
return new EntityArgument(true, true);
}
public static ServerPlayer getPlayer(CommandContext<CommandSourceStack> p_91475_, String p_91476_) throws CommandSyntaxException {
return p_91475_.getArgument(p_91476_, EntitySelector.class).findSinglePlayer(p_91475_.getSource());
}
public static EntityArgument players() {
return new EntityArgument(false, true);
}
public static Collection<ServerPlayer> getPlayers(CommandContext<CommandSourceStack> p_91478_, String p_91479_) throws CommandSyntaxException {
List<ServerPlayer> list = p_91478_.getArgument(p_91479_, EntitySelector.class).findPlayers(p_91478_.getSource());
if (list.isEmpty()) {
throw NO_PLAYERS_FOUND.create();
} else {
return list;
}
}
public EntitySelector parse(StringReader p_91451_) throws CommandSyntaxException {
int i = 0;
EntitySelectorParser entityselectorparser = new EntitySelectorParser(p_91451_);
EntitySelector entityselector = entityselectorparser.parse();
if (entityselector.getMaxResults() > 1 && this.single) {
if (this.playersOnly) {
p_91451_.setCursor(0);
throw ERROR_NOT_SINGLE_PLAYER.createWithContext(p_91451_);
} else {
p_91451_.setCursor(0);
throw ERROR_NOT_SINGLE_ENTITY.createWithContext(p_91451_);
}
} else if (entityselector.includesEntities() && this.playersOnly && !entityselector.isSelfSelector()) {
p_91451_.setCursor(0);
throw ERROR_ONLY_PLAYERS_ALLOWED.createWithContext(p_91451_);
} else {
return entityselector;
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_91482_, SuggestionsBuilder p_91483_) {
S s = p_91482_.getSource();
if (s instanceof SharedSuggestionProvider sharedsuggestionprovider) {
StringReader stringreader = new StringReader(p_91483_.getInput());
stringreader.setCursor(p_91483_.getStart());
EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(sharedsuggestionprovider));
try {
entityselectorparser.parse();
} catch (CommandSyntaxException commandsyntaxexception) {
}
return entityselectorparser.fillSuggestions(p_91483_, (p_91457_) -> {
Collection<String> collection = sharedsuggestionprovider.getOnlinePlayerNames();
Iterable<String> iterable = (Iterable<String>)(this.playersOnly ? collection : Iterables.concat(collection, sharedsuggestionprovider.getSelectedEntities()));
SharedSuggestionProvider.suggest(iterable, p_91457_);
});
} else {
return Suggestions.empty();
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Info implements ArgumentTypeInfo<EntityArgument, EntityArgument.Info.Template> {
private static final byte FLAG_SINGLE = 1;
private static final byte FLAG_PLAYERS_ONLY = 2;
public void serializeToNetwork(EntityArgument.Info.Template p_231271_, FriendlyByteBuf p_231272_) {
int i = 0;
if (p_231271_.single) {
i |= 1;
}
if (p_231271_.playersOnly) {
i |= 2;
}
p_231272_.writeByte(i);
}
public EntityArgument.Info.Template deserializeFromNetwork(FriendlyByteBuf p_231282_) {
byte b0 = p_231282_.readByte();
return new EntityArgument.Info.Template((b0 & 1) != 0, (b0 & 2) != 0);
}
public void serializeToJson(EntityArgument.Info.Template p_231268_, JsonObject p_231269_) {
p_231269_.addProperty("amount", p_231268_.single ? "single" : "multiple");
p_231269_.addProperty("type", p_231268_.playersOnly ? "players" : "entities");
}
public EntityArgument.Info.Template unpack(EntityArgument p_231274_) {
return new EntityArgument.Info.Template(p_231274_.single, p_231274_.playersOnly);
}
public final class Template implements ArgumentTypeInfo.Template<EntityArgument> {
final boolean single;
final boolean playersOnly;
Template(boolean p_231290_, boolean p_231291_) {
this.single = p_231290_;
this.playersOnly = p_231291_;
}
public EntityArgument instantiate(CommandBuildContext p_231294_) {
return new EntityArgument(this.single, this.playersOnly);
}
public ArgumentTypeInfo<EntityArgument, ?> type() {
return Info.this;
}
}
}
}

View File

@@ -0,0 +1,52 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.GameType;
public class GameModeArgument implements ArgumentType<GameType> {
private static final Collection<String> EXAMPLES = Stream.of(GameType.SURVIVAL, GameType.CREATIVE).map(GameType::getName).collect(Collectors.toList());
private static final GameType[] VALUES = GameType.values();
private static final DynamicCommandExceptionType ERROR_INVALID = new DynamicCommandExceptionType((p_260119_) -> {
return Component.translatable("argument.gamemode.invalid", p_260119_);
});
public GameType parse(StringReader p_260111_) throws CommandSyntaxException {
String s = p_260111_.readUnquotedString();
GameType gametype = GameType.byName(s, (GameType)null);
if (gametype == null) {
throw ERROR_INVALID.createWithContext(p_260111_, s);
} else {
return gametype;
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_259767_, SuggestionsBuilder p_259515_) {
return p_259767_.getSource() instanceof SharedSuggestionProvider ? SharedSuggestionProvider.suggest(Arrays.stream(VALUES).map(GameType::getName), p_259515_) : Suggestions.empty();
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static GameModeArgument gameMode() {
return new GameModeArgument();
}
public static GameType getGameMode(CommandContext<CommandSourceStack> p_259927_, String p_260246_) throws CommandSyntaxException {
return p_259927_.getArgument(p_260246_, GameType.class);
}
}

View File

@@ -0,0 +1,111 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Lists;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
public class GameProfileArgument implements ArgumentType<GameProfileArgument.Result> {
private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "dd12be42-52a9-4a91-a8a1-11c01849e498", "@e");
public static final SimpleCommandExceptionType ERROR_UNKNOWN_PLAYER = new SimpleCommandExceptionType(Component.translatable("argument.player.unknown"));
public static Collection<GameProfile> getGameProfiles(CommandContext<CommandSourceStack> p_94591_, String p_94592_) throws CommandSyntaxException {
return p_94591_.getArgument(p_94592_, GameProfileArgument.Result.class).getNames(p_94591_.getSource());
}
public static GameProfileArgument gameProfile() {
return new GameProfileArgument();
}
public GameProfileArgument.Result parse(StringReader p_94586_) throws CommandSyntaxException {
if (p_94586_.canRead() && p_94586_.peek() == '@') {
EntitySelectorParser entityselectorparser = new EntitySelectorParser(p_94586_);
EntitySelector entityselector = entityselectorparser.parse();
if (entityselector.includesEntities()) {
throw EntityArgument.ERROR_ONLY_PLAYERS_ALLOWED.create();
} else {
return new GameProfileArgument.SelectorResult(entityselector);
}
} else {
int i = p_94586_.getCursor();
while(p_94586_.canRead() && p_94586_.peek() != ' ') {
p_94586_.skip();
}
String s = p_94586_.getString().substring(i, p_94586_.getCursor());
return (p_94595_) -> {
Optional<GameProfile> optional = p_94595_.getServer().getProfileCache().get(s);
return Collections.singleton(optional.orElseThrow(ERROR_UNKNOWN_PLAYER::create));
};
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_94598_, SuggestionsBuilder p_94599_) {
if (p_94598_.getSource() instanceof SharedSuggestionProvider) {
StringReader stringreader = new StringReader(p_94599_.getInput());
stringreader.setCursor(p_94599_.getStart());
EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader);
try {
entityselectorparser.parse();
} catch (CommandSyntaxException commandsyntaxexception) {
}
return entityselectorparser.fillSuggestions(p_94599_, (p_94589_) -> {
SharedSuggestionProvider.suggest(((SharedSuggestionProvider)p_94598_.getSource()).getOnlinePlayerNames(), p_94589_);
});
} else {
return Suggestions.empty();
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
@FunctionalInterface
public interface Result {
Collection<GameProfile> getNames(CommandSourceStack p_94602_) throws CommandSyntaxException;
}
public static class SelectorResult implements GameProfileArgument.Result {
private final EntitySelector selector;
public SelectorResult(EntitySelector p_94605_) {
this.selector = p_94605_;
}
public Collection<GameProfile> getNames(CommandSourceStack p_94607_) throws CommandSyntaxException {
List<ServerPlayer> list = this.selector.findPlayers(p_94607_);
if (list.isEmpty()) {
throw EntityArgument.NO_PLAYERS_FOUND.create();
} else {
List<GameProfile> list1 = Lists.newArrayList();
for(ServerPlayer serverplayer : list) {
list1.add(serverplayer.getGameProfile());
}
return list1;
}
}
}
}

View File

@@ -0,0 +1,37 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.serialization.Codec;
import java.util.Arrays;
import java.util.Locale;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.level.levelgen.Heightmap;
public class HeightmapTypeArgument extends StringRepresentableArgument<Heightmap.Types> {
private static final Codec<Heightmap.Types> LOWER_CASE_CODEC = StringRepresentable.fromEnumWithMapping(HeightmapTypeArgument::keptTypes, (p_275334_) -> {
return p_275334_.toLowerCase(Locale.ROOT);
});
private static Heightmap.Types[] keptTypes() {
return Arrays.stream(Heightmap.Types.values()).filter(Heightmap.Types::keepAfterWorldgen).toArray((p_275295_) -> {
return new Heightmap.Types[p_275295_];
});
}
private HeightmapTypeArgument() {
super(LOWER_CASE_CODEC, HeightmapTypeArgument::keptTypes);
}
public static HeightmapTypeArgument heightmap() {
return new HeightmapTypeArgument();
}
public static Heightmap.Types getHeightmap(CommandContext<CommandSourceStack> p_275445_, String p_275449_) {
return p_275445_.getArgument(p_275449_, Heightmap.Types.class);
}
protected String convertId(String p_275666_) {
return p_275666_.toLowerCase(Locale.ROOT);
}
}

View File

@@ -0,0 +1,204 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Lists;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandSigningContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.FilteredText;
public class MessageArgument implements SignedArgument<MessageArgument.Message> {
private static final Collection<String> EXAMPLES = Arrays.asList("Hello world!", "foo", "@e", "Hello @p :)");
public static MessageArgument message() {
return new MessageArgument();
}
public static Component getMessage(CommandContext<CommandSourceStack> p_96836_, String p_96837_) throws CommandSyntaxException {
MessageArgument.Message messageargument$message = p_96836_.getArgument(p_96837_, MessageArgument.Message.class);
return messageargument$message.resolveComponent(p_96836_.getSource());
}
public static void resolveChatMessage(CommandContext<CommandSourceStack> p_249433_, String p_248718_, Consumer<PlayerChatMessage> p_249460_) throws CommandSyntaxException {
MessageArgument.Message messageargument$message = p_249433_.getArgument(p_248718_, MessageArgument.Message.class);
CommandSourceStack commandsourcestack = p_249433_.getSource();
Component component = messageargument$message.resolveComponent(commandsourcestack);
CommandSigningContext commandsigningcontext = commandsourcestack.getSigningContext();
PlayerChatMessage playerchatmessage = commandsigningcontext.getArgument(p_248718_);
if (playerchatmessage != null) {
resolveSignedMessage(p_249460_, commandsourcestack, playerchatmessage.withUnsignedContent(component));
} else {
resolveDisguisedMessage(p_249460_, commandsourcestack, PlayerChatMessage.system(messageargument$message.text).withUnsignedContent(component));
}
}
private static void resolveSignedMessage(Consumer<PlayerChatMessage> p_250000_, CommandSourceStack p_252335_, PlayerChatMessage p_249420_) {
MinecraftServer minecraftserver = p_252335_.getServer();
CompletableFuture<FilteredText> completablefuture = filterPlainText(p_252335_, p_249420_);
CompletableFuture<Component> completablefuture1 = minecraftserver.getChatDecorator().decorate(p_252335_.getPlayer(), p_249420_.decoratedContent());
p_252335_.getChatMessageChainer().append((p_247979_) -> {
return CompletableFuture.allOf(completablefuture, completablefuture1).thenAcceptAsync((p_247970_) -> {
PlayerChatMessage playerchatmessage = p_249420_.withUnsignedContent(completablefuture1.join()).filter(completablefuture.join().mask());
p_250000_.accept(playerchatmessage);
}, p_247979_);
});
}
private static void resolveDisguisedMessage(Consumer<PlayerChatMessage> p_249162_, CommandSourceStack p_248759_, PlayerChatMessage p_252332_) {
MinecraftServer minecraftserver = p_248759_.getServer();
CompletableFuture<Component> completablefuture = minecraftserver.getChatDecorator().decorate(p_248759_.getPlayer(), p_252332_.decoratedContent());
p_248759_.getChatMessageChainer().append((p_247974_) -> {
return completablefuture.thenAcceptAsync((p_247965_) -> {
p_249162_.accept(p_252332_.withUnsignedContent(p_247965_));
}, p_247974_);
});
}
private static CompletableFuture<FilteredText> filterPlainText(CommandSourceStack p_252063_, PlayerChatMessage p_251184_) {
ServerPlayer serverplayer = p_252063_.getPlayer();
return serverplayer != null && p_251184_.hasSignatureFrom(serverplayer.getUUID()) ? serverplayer.getTextFilter().processStreamMessage(p_251184_.signedContent()) : CompletableFuture.completedFuture(FilteredText.passThrough(p_251184_.signedContent()));
}
public MessageArgument.Message parse(StringReader p_96834_) throws CommandSyntaxException {
return MessageArgument.Message.parseText(p_96834_, true);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Message {
final String text;
private final MessageArgument.Part[] parts;
public Message(String p_96844_, MessageArgument.Part[] p_96845_) {
this.text = p_96844_;
this.parts = p_96845_;
}
public String getText() {
return this.text;
}
public MessageArgument.Part[] getParts() {
return this.parts;
}
Component resolveComponent(CommandSourceStack p_232197_) throws CommandSyntaxException {
return this.toComponent(p_232197_, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(p_232197_));
}
public Component toComponent(CommandSourceStack p_96850_, boolean p_96851_) throws CommandSyntaxException {
if (this.parts.length != 0 && p_96851_) {
MutableComponent mutablecomponent = Component.literal(this.text.substring(0, this.parts[0].getStart()));
int i = this.parts[0].getStart();
for(MessageArgument.Part messageargument$part : this.parts) {
Component component = messageargument$part.toComponent(p_96850_);
if (i < messageargument$part.getStart()) {
mutablecomponent.append(this.text.substring(i, messageargument$part.getStart()));
}
if (component != null) {
mutablecomponent.append(component);
}
i = messageargument$part.getEnd();
}
if (i < this.text.length()) {
mutablecomponent.append(this.text.substring(i));
}
return mutablecomponent;
} else {
return Component.literal(this.text);
}
}
public static MessageArgument.Message parseText(StringReader p_96847_, boolean p_96848_) throws CommandSyntaxException {
String s = p_96847_.getString().substring(p_96847_.getCursor(), p_96847_.getTotalLength());
if (!p_96848_) {
p_96847_.setCursor(p_96847_.getTotalLength());
return new MessageArgument.Message(s, new MessageArgument.Part[0]);
} else {
List<MessageArgument.Part> list = Lists.newArrayList();
int i = p_96847_.getCursor();
while(true) {
int j;
EntitySelector entityselector;
while(true) {
if (!p_96847_.canRead()) {
return new MessageArgument.Message(s, list.toArray(new MessageArgument.Part[0]));
}
if (p_96847_.peek() == '@') {
j = p_96847_.getCursor();
try {
EntitySelectorParser entityselectorparser = new EntitySelectorParser(p_96847_);
entityselector = entityselectorparser.parse();
break;
} catch (CommandSyntaxException commandsyntaxexception) {
if (commandsyntaxexception.getType() != EntitySelectorParser.ERROR_MISSING_SELECTOR_TYPE && commandsyntaxexception.getType() != EntitySelectorParser.ERROR_UNKNOWN_SELECTOR_TYPE) {
throw commandsyntaxexception;
}
p_96847_.setCursor(j + 1);
}
} else {
p_96847_.skip();
}
}
list.add(new MessageArgument.Part(j - i, p_96847_.getCursor() - i, entityselector));
}
}
}
}
public static class Part {
private final int start;
private final int end;
private final EntitySelector selector;
public Part(int p_96856_, int p_96857_, EntitySelector p_96858_) {
this.start = p_96856_;
this.end = p_96857_;
this.selector = p_96858_;
}
public int getStart() {
return this.start;
}
public int getEnd() {
return this.end;
}
public EntitySelector getSelector() {
return this.selector;
}
@Nullable
public Component toComponent(CommandSourceStack p_96861_) throws CommandSyntaxException {
return EntitySelector.joinNames(this.selector.findEntities(p_96861_));
}
}
}

View File

@@ -0,0 +1,729 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Lists;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.nbt.CollectionTag;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.TagParser;
import net.minecraft.network.chat.Component;
import org.apache.commons.lang3.mutable.MutableBoolean;
public class NbtPathArgument implements ArgumentType<NbtPathArgument.NbtPath> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo.bar", "foo[0]", "[0]", "[]", "{foo=bar}");
public static final SimpleCommandExceptionType ERROR_INVALID_NODE = new SimpleCommandExceptionType(Component.translatable("arguments.nbtpath.node.invalid"));
public static final SimpleCommandExceptionType ERROR_DATA_TOO_DEEP = new SimpleCommandExceptionType(Component.translatable("arguments.nbtpath.too_deep"));
public static final DynamicCommandExceptionType ERROR_NOTHING_FOUND = new DynamicCommandExceptionType((p_99502_) -> {
return Component.translatable("arguments.nbtpath.nothing_found", p_99502_);
});
static final DynamicCommandExceptionType ERROR_EXPECTED_LIST = new DynamicCommandExceptionType((p_263253_) -> {
return Component.translatable("commands.data.modify.expected_list", p_263253_);
});
static final DynamicCommandExceptionType ERROR_INVALID_INDEX = new DynamicCommandExceptionType((p_263252_) -> {
return Component.translatable("commands.data.modify.invalid_index", p_263252_);
});
private static final char INDEX_MATCH_START = '[';
private static final char INDEX_MATCH_END = ']';
private static final char KEY_MATCH_START = '{';
private static final char KEY_MATCH_END = '}';
private static final char QUOTED_KEY_START = '"';
private static final char SINGLE_QUOTED_KEY_START = '\'';
public static NbtPathArgument nbtPath() {
return new NbtPathArgument();
}
public static NbtPathArgument.NbtPath getPath(CommandContext<CommandSourceStack> p_99499_, String p_99500_) {
return p_99499_.getArgument(p_99500_, NbtPathArgument.NbtPath.class);
}
public NbtPathArgument.NbtPath parse(StringReader p_99491_) throws CommandSyntaxException {
List<NbtPathArgument.Node> list = Lists.newArrayList();
int i = p_99491_.getCursor();
Object2IntMap<NbtPathArgument.Node> object2intmap = new Object2IntOpenHashMap<>();
boolean flag = true;
while(p_99491_.canRead() && p_99491_.peek() != ' ') {
NbtPathArgument.Node nbtpathargument$node = parseNode(p_99491_, flag);
list.add(nbtpathargument$node);
object2intmap.put(nbtpathargument$node, p_99491_.getCursor() - i);
flag = false;
if (p_99491_.canRead()) {
char c0 = p_99491_.peek();
if (c0 != ' ' && c0 != '[' && c0 != '{') {
p_99491_.expect('.');
}
}
}
return new NbtPathArgument.NbtPath(p_99491_.getString().substring(i, p_99491_.getCursor()), list.toArray(new NbtPathArgument.Node[0]), object2intmap);
}
private static NbtPathArgument.Node parseNode(StringReader p_99496_, boolean p_99497_) throws CommandSyntaxException {
Object object;
switch (p_99496_.peek()) {
case '"':
case '\'':
object = readObjectNode(p_99496_, p_99496_.readString());
break;
case '[':
p_99496_.skip();
int i = p_99496_.peek();
if (i == 123) {
CompoundTag compoundtag1 = (new TagParser(p_99496_)).readStruct();
p_99496_.expect(']');
object = new NbtPathArgument.MatchElementNode(compoundtag1);
} else if (i == 93) {
p_99496_.skip();
object = NbtPathArgument.AllElementsNode.INSTANCE;
} else {
int j = p_99496_.readInt();
p_99496_.expect(']');
object = new NbtPathArgument.IndexedElementNode(j);
}
break;
case '{':
if (!p_99497_) {
throw ERROR_INVALID_NODE.createWithContext(p_99496_);
}
CompoundTag compoundtag = (new TagParser(p_99496_)).readStruct();
object = new NbtPathArgument.MatchRootObjectNode(compoundtag);
break;
default:
object = readObjectNode(p_99496_, readUnquotedName(p_99496_));
}
return (NbtPathArgument.Node)object;
}
private static NbtPathArgument.Node readObjectNode(StringReader p_99493_, String p_99494_) throws CommandSyntaxException {
if (p_99493_.canRead() && p_99493_.peek() == '{') {
CompoundTag compoundtag = (new TagParser(p_99493_)).readStruct();
return new NbtPathArgument.MatchObjectNode(p_99494_, compoundtag);
} else {
return new NbtPathArgument.CompoundChildNode(p_99494_);
}
}
private static String readUnquotedName(StringReader p_99509_) throws CommandSyntaxException {
int i = p_99509_.getCursor();
while(p_99509_.canRead() && isAllowedInUnquotedName(p_99509_.peek())) {
p_99509_.skip();
}
if (p_99509_.getCursor() == i) {
throw ERROR_INVALID_NODE.createWithContext(p_99509_);
} else {
return p_99509_.getString().substring(i, p_99509_.getCursor());
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
private static boolean isAllowedInUnquotedName(char p_99489_) {
return p_99489_ != ' ' && p_99489_ != '"' && p_99489_ != '\'' && p_99489_ != '[' && p_99489_ != ']' && p_99489_ != '.' && p_99489_ != '{' && p_99489_ != '}';
}
static Predicate<Tag> createTagPredicate(CompoundTag p_99511_) {
return (p_99507_) -> {
return NbtUtils.compareNbt(p_99511_, p_99507_, true);
};
}
static class AllElementsNode implements NbtPathArgument.Node {
public static final NbtPathArgument.AllElementsNode INSTANCE = new NbtPathArgument.AllElementsNode();
private AllElementsNode() {
}
public void getTag(Tag p_99522_, List<Tag> p_99523_) {
if (p_99522_ instanceof CollectionTag) {
p_99523_.addAll((CollectionTag)p_99522_);
}
}
public void getOrCreateTag(Tag p_99528_, Supplier<Tag> p_99529_, List<Tag> p_99530_) {
if (p_99528_ instanceof CollectionTag<?> collectiontag) {
if (collectiontag.isEmpty()) {
Tag tag = p_99529_.get();
if (collectiontag.addTag(0, tag)) {
p_99530_.add(tag);
}
} else {
p_99530_.addAll(collectiontag);
}
}
}
public Tag createPreferredParentTag() {
return new ListTag();
}
public int setTag(Tag p_99525_, Supplier<Tag> p_99526_) {
if (!(p_99525_ instanceof CollectionTag<?> collectiontag)) {
return 0;
} else {
int i = collectiontag.size();
if (i == 0) {
collectiontag.addTag(0, p_99526_.get());
return 1;
} else {
Tag tag = p_99526_.get();
int j = i - (int)collectiontag.stream().filter(tag::equals).count();
if (j == 0) {
return 0;
} else {
collectiontag.clear();
if (!collectiontag.addTag(0, tag)) {
return 0;
} else {
for(int k = 1; k < i; ++k) {
collectiontag.addTag(k, p_99526_.get());
}
return j;
}
}
}
}
}
public int removeTag(Tag p_99520_) {
if (p_99520_ instanceof CollectionTag<?> collectiontag) {
int i = collectiontag.size();
if (i > 0) {
collectiontag.clear();
return i;
}
}
return 0;
}
}
static class CompoundChildNode implements NbtPathArgument.Node {
private final String name;
public CompoundChildNode(String p_99533_) {
this.name = p_99533_;
}
public void getTag(Tag p_99538_, List<Tag> p_99539_) {
if (p_99538_ instanceof CompoundTag) {
Tag tag = ((CompoundTag)p_99538_).get(this.name);
if (tag != null) {
p_99539_.add(tag);
}
}
}
public void getOrCreateTag(Tag p_99544_, Supplier<Tag> p_99545_, List<Tag> p_99546_) {
if (p_99544_ instanceof CompoundTag compoundtag) {
Tag tag;
if (compoundtag.contains(this.name)) {
tag = compoundtag.get(this.name);
} else {
tag = p_99545_.get();
compoundtag.put(this.name, tag);
}
p_99546_.add(tag);
}
}
public Tag createPreferredParentTag() {
return new CompoundTag();
}
public int setTag(Tag p_99541_, Supplier<Tag> p_99542_) {
if (p_99541_ instanceof CompoundTag compoundtag) {
Tag tag = p_99542_.get();
Tag tag1 = compoundtag.put(this.name, tag);
if (!tag.equals(tag1)) {
return 1;
}
}
return 0;
}
public int removeTag(Tag p_99536_) {
if (p_99536_ instanceof CompoundTag compoundtag) {
if (compoundtag.contains(this.name)) {
compoundtag.remove(this.name);
return 1;
}
}
return 0;
}
}
static class IndexedElementNode implements NbtPathArgument.Node {
private final int index;
public IndexedElementNode(int p_99549_) {
this.index = p_99549_;
}
public void getTag(Tag p_99554_, List<Tag> p_99555_) {
if (p_99554_ instanceof CollectionTag<?> collectiontag) {
int i = collectiontag.size();
int j = this.index < 0 ? i + this.index : this.index;
if (0 <= j && j < i) {
p_99555_.add(collectiontag.get(j));
}
}
}
public void getOrCreateTag(Tag p_99560_, Supplier<Tag> p_99561_, List<Tag> p_99562_) {
this.getTag(p_99560_, p_99562_);
}
public Tag createPreferredParentTag() {
return new ListTag();
}
public int setTag(Tag p_99557_, Supplier<Tag> p_99558_) {
if (p_99557_ instanceof CollectionTag<?> collectiontag) {
int i = collectiontag.size();
int j = this.index < 0 ? i + this.index : this.index;
if (0 <= j && j < i) {
Tag tag = collectiontag.get(j);
Tag tag1 = p_99558_.get();
if (!tag1.equals(tag) && collectiontag.setTag(j, tag1)) {
return 1;
}
}
}
return 0;
}
public int removeTag(Tag p_99552_) {
if (p_99552_ instanceof CollectionTag<?> collectiontag) {
int i = collectiontag.size();
int j = this.index < 0 ? i + this.index : this.index;
if (0 <= j && j < i) {
collectiontag.remove(j);
return 1;
}
}
return 0;
}
}
static class MatchElementNode implements NbtPathArgument.Node {
private final CompoundTag pattern;
private final Predicate<Tag> predicate;
public MatchElementNode(CompoundTag p_99566_) {
this.pattern = p_99566_;
this.predicate = NbtPathArgument.createTagPredicate(p_99566_);
}
public void getTag(Tag p_99575_, List<Tag> p_99576_) {
if (p_99575_ instanceof ListTag listtag) {
listtag.stream().filter(this.predicate).forEach(p_99576_::add);
}
}
public void getOrCreateTag(Tag p_99581_, Supplier<Tag> p_99582_, List<Tag> p_99583_) {
MutableBoolean mutableboolean = new MutableBoolean();
if (p_99581_ instanceof ListTag listtag) {
listtag.stream().filter(this.predicate).forEach((p_99571_) -> {
p_99583_.add(p_99571_);
mutableboolean.setTrue();
});
if (mutableboolean.isFalse()) {
CompoundTag compoundtag = this.pattern.copy();
listtag.add(compoundtag);
p_99583_.add(compoundtag);
}
}
}
public Tag createPreferredParentTag() {
return new ListTag();
}
public int setTag(Tag p_99578_, Supplier<Tag> p_99579_) {
int i = 0;
if (p_99578_ instanceof ListTag listtag) {
int j = listtag.size();
if (j == 0) {
listtag.add(p_99579_.get());
++i;
} else {
for(int k = 0; k < j; ++k) {
Tag tag = listtag.get(k);
if (this.predicate.test(tag)) {
Tag tag1 = p_99579_.get();
if (!tag1.equals(tag) && listtag.setTag(k, tag1)) {
++i;
}
}
}
}
}
return i;
}
public int removeTag(Tag p_99573_) {
int i = 0;
if (p_99573_ instanceof ListTag listtag) {
for(int j = listtag.size() - 1; j >= 0; --j) {
if (this.predicate.test(listtag.get(j))) {
listtag.remove(j);
++i;
}
}
}
return i;
}
}
static class MatchObjectNode implements NbtPathArgument.Node {
private final String name;
private final CompoundTag pattern;
private final Predicate<Tag> predicate;
public MatchObjectNode(String p_99588_, CompoundTag p_99589_) {
this.name = p_99588_;
this.pattern = p_99589_;
this.predicate = NbtPathArgument.createTagPredicate(p_99589_);
}
public void getTag(Tag p_99594_, List<Tag> p_99595_) {
if (p_99594_ instanceof CompoundTag) {
Tag tag = ((CompoundTag)p_99594_).get(this.name);
if (this.predicate.test(tag)) {
p_99595_.add(tag);
}
}
}
public void getOrCreateTag(Tag p_99600_, Supplier<Tag> p_99601_, List<Tag> p_99602_) {
if (p_99600_ instanceof CompoundTag compoundtag) {
Tag tag = compoundtag.get(this.name);
if (tag == null) {
Tag compoundtag1 = this.pattern.copy();
compoundtag.put(this.name, compoundtag1);
p_99602_.add(compoundtag1);
} else if (this.predicate.test(tag)) {
p_99602_.add(tag);
}
}
}
public Tag createPreferredParentTag() {
return new CompoundTag();
}
public int setTag(Tag p_99597_, Supplier<Tag> p_99598_) {
if (p_99597_ instanceof CompoundTag compoundtag) {
Tag tag = compoundtag.get(this.name);
if (this.predicate.test(tag)) {
Tag tag1 = p_99598_.get();
if (!tag1.equals(tag)) {
compoundtag.put(this.name, tag1);
return 1;
}
}
}
return 0;
}
public int removeTag(Tag p_99592_) {
if (p_99592_ instanceof CompoundTag compoundtag) {
Tag tag = compoundtag.get(this.name);
if (this.predicate.test(tag)) {
compoundtag.remove(this.name);
return 1;
}
}
return 0;
}
}
static class MatchRootObjectNode implements NbtPathArgument.Node {
private final Predicate<Tag> predicate;
public MatchRootObjectNode(CompoundTag p_99605_) {
this.predicate = NbtPathArgument.createTagPredicate(p_99605_);
}
public void getTag(Tag p_99610_, List<Tag> p_99611_) {
if (p_99610_ instanceof CompoundTag && this.predicate.test(p_99610_)) {
p_99611_.add(p_99610_);
}
}
public void getOrCreateTag(Tag p_99616_, Supplier<Tag> p_99617_, List<Tag> p_99618_) {
this.getTag(p_99616_, p_99618_);
}
public Tag createPreferredParentTag() {
return new CompoundTag();
}
public int setTag(Tag p_99613_, Supplier<Tag> p_99614_) {
return 0;
}
public int removeTag(Tag p_99608_) {
return 0;
}
}
public static class NbtPath {
private final String original;
private final Object2IntMap<NbtPathArgument.Node> nodeToOriginalPosition;
private final NbtPathArgument.Node[] nodes;
public NbtPath(String p_99623_, NbtPathArgument.Node[] p_99624_, Object2IntMap<NbtPathArgument.Node> p_99625_) {
this.original = p_99623_;
this.nodes = p_99624_;
this.nodeToOriginalPosition = p_99625_;
}
public List<Tag> get(Tag p_99639_) throws CommandSyntaxException {
List<Tag> list = Collections.singletonList(p_99639_);
for(NbtPathArgument.Node nbtpathargument$node : this.nodes) {
list = nbtpathargument$node.get(list);
if (list.isEmpty()) {
throw this.createNotFoundException(nbtpathargument$node);
}
}
return list;
}
public int countMatching(Tag p_99644_) {
List<Tag> list = Collections.singletonList(p_99644_);
for(NbtPathArgument.Node nbtpathargument$node : this.nodes) {
list = nbtpathargument$node.get(list);
if (list.isEmpty()) {
return 0;
}
}
return list.size();
}
private List<Tag> getOrCreateParents(Tag p_99651_) throws CommandSyntaxException {
List<Tag> list = Collections.singletonList(p_99651_);
for(int i = 0; i < this.nodes.length - 1; ++i) {
NbtPathArgument.Node nbtpathargument$node = this.nodes[i];
int j = i + 1;
list = nbtpathargument$node.getOrCreate(list, this.nodes[j]::createPreferredParentTag);
if (list.isEmpty()) {
throw this.createNotFoundException(nbtpathargument$node);
}
}
return list;
}
public List<Tag> getOrCreate(Tag p_99641_, Supplier<Tag> p_99642_) throws CommandSyntaxException {
List<Tag> list = this.getOrCreateParents(p_99641_);
NbtPathArgument.Node nbtpathargument$node = this.nodes[this.nodes.length - 1];
return nbtpathargument$node.getOrCreate(list, p_99642_);
}
private static int apply(List<Tag> p_99636_, Function<Tag, Integer> p_99637_) {
return p_99636_.stream().map(p_99637_).reduce(0, (p_99633_, p_99634_) -> {
return p_99633_ + p_99634_;
});
}
public static boolean isTooDeep(Tag p_263392_, int p_263386_) {
if (p_263386_ >= 512) {
return true;
} else {
if (p_263392_ instanceof CompoundTag) {
CompoundTag compoundtag = (CompoundTag)p_263392_;
for(String s : compoundtag.getAllKeys()) {
Tag tag = compoundtag.get(s);
if (tag != null && isTooDeep(tag, p_263386_ + 1)) {
return true;
}
}
} else if (p_263392_ instanceof ListTag) {
for(Tag tag1 : (ListTag)p_263392_) {
if (isTooDeep(tag1, p_263386_ + 1)) {
return true;
}
}
}
return false;
}
}
public int set(Tag p_169536_, Tag p_169537_) throws CommandSyntaxException {
if (isTooDeep(p_169537_, this.estimatePathDepth())) {
throw NbtPathArgument.ERROR_DATA_TOO_DEEP.create();
} else {
Tag tag = p_169537_.copy();
List<Tag> list = this.getOrCreateParents(p_169536_);
if (list.isEmpty()) {
return 0;
} else {
NbtPathArgument.Node nbtpathargument$node = this.nodes[this.nodes.length - 1];
MutableBoolean mutableboolean = new MutableBoolean(false);
return apply(list, (p_263259_) -> {
return nbtpathargument$node.setTag(p_263259_, () -> {
if (mutableboolean.isFalse()) {
mutableboolean.setTrue();
return tag;
} else {
return tag.copy();
}
});
});
}
}
}
private int estimatePathDepth() {
return this.nodes.length;
}
public int insert(int p_263397_, CompoundTag p_263348_, List<Tag> p_263419_) throws CommandSyntaxException {
List<Tag> list = new ArrayList<>(p_263419_.size());
for(Tag tag : p_263419_) {
Tag tag1 = tag.copy();
list.add(tag1);
if (isTooDeep(tag1, this.estimatePathDepth())) {
throw NbtPathArgument.ERROR_DATA_TOO_DEEP.create();
}
}
Collection<Tag> collection = this.getOrCreate(p_263348_, ListTag::new);
int j = 0;
boolean flag1 = false;
for(Tag tag2 : collection) {
if (!(tag2 instanceof CollectionTag)) {
throw NbtPathArgument.ERROR_EXPECTED_LIST.create(tag2);
}
CollectionTag<?> collectiontag = (CollectionTag)tag2;
boolean flag = false;
int i = p_263397_ < 0 ? collectiontag.size() + p_263397_ + 1 : p_263397_;
for(Tag tag3 : list) {
try {
if (collectiontag.addTag(i, flag1 ? tag3.copy() : tag3)) {
++i;
flag = true;
}
} catch (IndexOutOfBoundsException indexoutofboundsexception) {
throw NbtPathArgument.ERROR_INVALID_INDEX.create(i);
}
}
flag1 = true;
j += flag ? 1 : 0;
}
return j;
}
public int remove(Tag p_99649_) {
List<Tag> list = Collections.singletonList(p_99649_);
for(int i = 0; i < this.nodes.length - 1; ++i) {
list = this.nodes[i].get(list);
}
NbtPathArgument.Node nbtpathargument$node = this.nodes[this.nodes.length - 1];
return apply(list, nbtpathargument$node::removeTag);
}
private CommandSyntaxException createNotFoundException(NbtPathArgument.Node p_99627_) {
int i = this.nodeToOriginalPosition.getInt(p_99627_);
return NbtPathArgument.ERROR_NOTHING_FOUND.create(this.original.substring(0, i));
}
public String toString() {
return this.original;
}
}
interface Node {
void getTag(Tag p_99666_, List<Tag> p_99667_);
void getOrCreateTag(Tag p_99670_, Supplier<Tag> p_99671_, List<Tag> p_99672_);
Tag createPreferredParentTag();
int setTag(Tag p_99668_, Supplier<Tag> p_99669_);
int removeTag(Tag p_99665_);
default List<Tag> get(List<Tag> p_99654_) {
return this.collect(p_99654_, this::getTag);
}
default List<Tag> getOrCreate(List<Tag> p_99659_, Supplier<Tag> p_99660_) {
return this.collect(p_99659_, (p_99663_, p_99664_) -> {
this.getOrCreateTag(p_99663_, p_99660_, p_99664_);
});
}
default List<Tag> collect(List<Tag> p_99656_, BiConsumer<Tag, List<Tag>> p_99657_) {
List<Tag> list = Lists.newArrayList();
for(Tag tag : p_99656_) {
p_99657_.accept(tag, list);
}
return list;
}
}
}

View File

@@ -0,0 +1,33 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.TagParser;
public class NbtTagArgument implements ArgumentType<Tag> {
private static final Collection<String> EXAMPLES = Arrays.asList("0", "0b", "0l", "0.0", "\"foo\"", "{foo=bar}", "[0]");
private NbtTagArgument() {
}
public static NbtTagArgument nbtTag() {
return new NbtTagArgument();
}
public static <S> Tag getNbtTag(CommandContext<S> p_100663_, String p_100664_) {
return p_100663_.getArgument(p_100664_, Tag.class);
}
public Tag parse(StringReader p_100661_) throws CommandSyntaxException {
return (new TagParser(p_100661_)).readValue();
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,70 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.Scoreboard;
public class ObjectiveArgument implements ArgumentType<String> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "*", "012");
private static final DynamicCommandExceptionType ERROR_OBJECTIVE_NOT_FOUND = new DynamicCommandExceptionType((p_101971_) -> {
return Component.translatable("arguments.objective.notFound", p_101971_);
});
private static final DynamicCommandExceptionType ERROR_OBJECTIVE_READ_ONLY = new DynamicCommandExceptionType((p_101969_) -> {
return Component.translatable("arguments.objective.readonly", p_101969_);
});
public static ObjectiveArgument objective() {
return new ObjectiveArgument();
}
public static Objective getObjective(CommandContext<CommandSourceStack> p_101961_, String p_101962_) throws CommandSyntaxException {
String s = p_101961_.getArgument(p_101962_, String.class);
Scoreboard scoreboard = p_101961_.getSource().getScoreboard();
Objective objective = scoreboard.getObjective(s);
if (objective == null) {
throw ERROR_OBJECTIVE_NOT_FOUND.create(s);
} else {
return objective;
}
}
public static Objective getWritableObjective(CommandContext<CommandSourceStack> p_101966_, String p_101967_) throws CommandSyntaxException {
Objective objective = getObjective(p_101966_, p_101967_);
if (objective.getCriteria().isReadOnly()) {
throw ERROR_OBJECTIVE_READ_ONLY.create(objective.getName());
} else {
return objective;
}
}
public String parse(StringReader p_101959_) throws CommandSyntaxException {
return p_101959_.readUnquotedString();
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_101974_, SuggestionsBuilder p_101975_) {
S s = p_101974_.getSource();
if (s instanceof CommandSourceStack commandsourcestack) {
return SharedSuggestionProvider.suggest(commandsourcestack.getScoreboard().getObjectiveNames(), p_101975_);
} else if (s instanceof SharedSuggestionProvider sharedsuggestionprovider) {
return sharedsuggestionprovider.customSuggestion(p_101974_);
} else {
return Suggestions.empty();
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,74 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Lists;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.stats.Stat;
import net.minecraft.stats.StatType;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
public class ObjectiveCriteriaArgument implements ArgumentType<ObjectiveCriteria> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo.bar.baz", "minecraft:foo");
public static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_102569_) -> {
return Component.translatable("argument.criteria.invalid", p_102569_);
});
private ObjectiveCriteriaArgument() {
}
public static ObjectiveCriteriaArgument criteria() {
return new ObjectiveCriteriaArgument();
}
public static ObjectiveCriteria getCriteria(CommandContext<CommandSourceStack> p_102566_, String p_102567_) {
return p_102566_.getArgument(p_102567_, ObjectiveCriteria.class);
}
public ObjectiveCriteria parse(StringReader p_102560_) throws CommandSyntaxException {
int i = p_102560_.getCursor();
while(p_102560_.canRead() && p_102560_.peek() != ' ') {
p_102560_.skip();
}
String s = p_102560_.getString().substring(i, p_102560_.getCursor());
return ObjectiveCriteria.byName(s).orElseThrow(() -> {
p_102560_.setCursor(i);
return ERROR_INVALID_VALUE.create(s);
});
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_102572_, SuggestionsBuilder p_102573_) {
List<String> list = Lists.newArrayList(ObjectiveCriteria.getCustomCriteriaNames());
for(StatType<?> stattype : BuiltInRegistries.STAT_TYPE) {
for(Object object : stattype.getRegistry()) {
String s = this.getName(stattype, object);
list.add(s);
}
}
return SharedSuggestionProvider.suggest(list, p_102573_);
}
public <T> String getName(StatType<T> p_102557_, Object p_102558_) {
return Stat.buildName(p_102557_, (T)p_102558_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,118 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth;
import net.minecraft.world.scores.Score;
public class OperationArgument implements ArgumentType<OperationArgument.Operation> {
private static final Collection<String> EXAMPLES = Arrays.asList("=", ">", "<");
private static final SimpleCommandExceptionType ERROR_INVALID_OPERATION = new SimpleCommandExceptionType(Component.translatable("arguments.operation.invalid"));
private static final SimpleCommandExceptionType ERROR_DIVIDE_BY_ZERO = new SimpleCommandExceptionType(Component.translatable("arguments.operation.div0"));
public static OperationArgument operation() {
return new OperationArgument();
}
public static OperationArgument.Operation getOperation(CommandContext<CommandSourceStack> p_103276_, String p_103277_) {
return p_103276_.getArgument(p_103277_, OperationArgument.Operation.class);
}
public OperationArgument.Operation parse(StringReader p_103274_) throws CommandSyntaxException {
if (!p_103274_.canRead()) {
throw ERROR_INVALID_OPERATION.create();
} else {
int i = p_103274_.getCursor();
while(p_103274_.canRead() && p_103274_.peek() != ' ') {
p_103274_.skip();
}
return getOperation(p_103274_.getString().substring(i, p_103274_.getCursor()));
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_103302_, SuggestionsBuilder p_103303_) {
return SharedSuggestionProvider.suggest(new String[]{"=", "+=", "-=", "*=", "/=", "%=", "<", ">", "><"}, p_103303_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
private static OperationArgument.Operation getOperation(String p_103282_) throws CommandSyntaxException {
return (p_103282_.equals("><") ? (p_103279_, p_103280_) -> {
int i = p_103279_.getScore();
p_103279_.setScore(p_103280_.getScore());
p_103280_.setScore(i);
} : getSimpleOperation(p_103282_));
}
private static OperationArgument.SimpleOperation getSimpleOperation(String p_103287_) throws CommandSyntaxException {
switch (p_103287_) {
case "=":
return (p_103298_, p_103299_) -> {
return p_103299_;
};
case "+=":
return (p_103295_, p_103296_) -> {
return p_103295_ + p_103296_;
};
case "-=":
return (p_103292_, p_103293_) -> {
return p_103292_ - p_103293_;
};
case "*=":
return (p_103289_, p_103290_) -> {
return p_103289_ * p_103290_;
};
case "/=":
return (p_264713_, p_264714_) -> {
if (p_264714_ == 0) {
throw ERROR_DIVIDE_BY_ZERO.create();
} else {
return Mth.floorDiv(p_264713_, p_264714_);
}
};
case "%=":
return (p_103271_, p_103272_) -> {
if (p_103272_ == 0) {
throw ERROR_DIVIDE_BY_ZERO.create();
} else {
return Mth.positiveModulo(p_103271_, p_103272_);
}
};
case "<":
return Math::min;
case ">":
return Math::max;
default:
throw ERROR_INVALID_OPERATION.create();
}
}
@FunctionalInterface
public interface Operation {
void apply(Score p_103306_, Score p_103307_) throws CommandSyntaxException;
}
@FunctionalInterface
interface SimpleOperation extends OperationArgument.Operation {
int apply(int p_103309_, int p_103310_) throws CommandSyntaxException;
default void apply(Score p_103312_, Score p_103313_) throws CommandSyntaxException {
p_103312_.setScore(this.apply(p_103312_.getScore(), p_103313_.getScore()));
}
}
}

View File

@@ -0,0 +1,71 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleType;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
public class ParticleArgument implements ArgumentType<ParticleOptions> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "particle with options");
public static final DynamicCommandExceptionType ERROR_UNKNOWN_PARTICLE = new DynamicCommandExceptionType((p_103941_) -> {
return Component.translatable("particle.notFound", p_103941_);
});
private final HolderLookup<ParticleType<?>> particles;
public ParticleArgument(CommandBuildContext p_249844_) {
this.particles = p_249844_.holderLookup(Registries.PARTICLE_TYPE);
}
public static ParticleArgument particle(CommandBuildContext p_251304_) {
return new ParticleArgument(p_251304_);
}
public static ParticleOptions getParticle(CommandContext<CommandSourceStack> p_103938_, String p_103939_) {
return p_103938_.getArgument(p_103939_, ParticleOptions.class);
}
public ParticleOptions parse(StringReader p_103933_) throws CommandSyntaxException {
return readParticle(p_103933_, this.particles);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static ParticleOptions readParticle(StringReader p_249275_, HolderLookup<ParticleType<?>> p_251929_) throws CommandSyntaxException {
ParticleType<?> particletype = readParticleType(p_249275_, p_251929_);
return readParticle(p_249275_, particletype);
}
private static ParticleType<?> readParticleType(StringReader p_249621_, HolderLookup<ParticleType<?>> p_248983_) throws CommandSyntaxException {
ResourceLocation resourcelocation = ResourceLocation.read(p_249621_);
ResourceKey<ParticleType<?>> resourcekey = ResourceKey.create(Registries.PARTICLE_TYPE, resourcelocation);
return p_248983_.get(resourcekey).orElseThrow(() -> {
return ERROR_UNKNOWN_PARTICLE.create(resourcelocation);
}).value();
}
private static <T extends ParticleOptions> T readParticle(StringReader p_103935_, ParticleType<T> p_103936_) throws CommandSyntaxException {
return p_103936_.getDeserializer().fromCommand(p_103936_, p_103935_);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_103948_, SuggestionsBuilder p_103949_) {
return SharedSuggestionProvider.suggestResource(this.particles.listElementIds().map(ResourceKey::location), p_103949_);
}
}

View File

@@ -0,0 +1,52 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.commands.CommandSourceStack;
public interface RangeArgument<T extends MinMaxBounds<?>> extends ArgumentType<T> {
static RangeArgument.Ints intRange() {
return new RangeArgument.Ints();
}
static RangeArgument.Floats floatRange() {
return new RangeArgument.Floats();
}
public static class Floats implements RangeArgument<MinMaxBounds.Doubles> {
private static final Collection<String> EXAMPLES = Arrays.asList("0..5.2", "0", "-5.4", "-100.76..", "..100");
public static MinMaxBounds.Doubles getRange(CommandContext<CommandSourceStack> p_170805_, String p_170806_) {
return p_170805_.getArgument(p_170806_, MinMaxBounds.Doubles.class);
}
public MinMaxBounds.Doubles parse(StringReader p_170803_) throws CommandSyntaxException {
return MinMaxBounds.Doubles.fromReader(p_170803_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}
public static class Ints implements RangeArgument<MinMaxBounds.Ints> {
private static final Collection<String> EXAMPLES = Arrays.asList("0..5", "0", "-5", "-100..", "..100");
public static MinMaxBounds.Ints getRange(CommandContext<CommandSourceStack> p_105420_, String p_105421_) {
return p_105420_.getArgument(p_105421_, MinMaxBounds.Ints.class);
}
public MinMaxBounds.Ints parse(StringReader p_105418_) throws CommandSyntaxException {
return MinMaxBounds.Ints.fromReader(p_105418_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}
}

View File

@@ -0,0 +1,151 @@
package net.minecraft.commands.arguments;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.levelgen.structure.Structure;
public class ResourceArgument<T> implements ArgumentType<Holder.Reference<T>> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012");
private static final DynamicCommandExceptionType ERROR_NOT_SUMMONABLE_ENTITY = new DynamicCommandExceptionType((p_248875_) -> {
return Component.translatable("entity.not_summonable", p_248875_);
});
public static final Dynamic2CommandExceptionType ERROR_UNKNOWN_RESOURCE = new Dynamic2CommandExceptionType((p_248525_, p_251552_) -> {
return Component.translatable("argument.resource.not_found", p_248525_, p_251552_);
});
public static final Dynamic3CommandExceptionType ERROR_INVALID_RESOURCE_TYPE = new Dynamic3CommandExceptionType((p_250883_, p_249983_, p_249882_) -> {
return Component.translatable("argument.resource.invalid_type", p_250883_, p_249983_, p_249882_);
});
final ResourceKey<? extends Registry<T>> registryKey;
private final HolderLookup<T> registryLookup;
public ResourceArgument(CommandBuildContext p_248597_, ResourceKey<? extends Registry<T>> p_251778_) {
this.registryKey = p_251778_;
this.registryLookup = p_248597_.holderLookup(p_251778_);
}
public static <T> ResourceArgument<T> resource(CommandBuildContext p_249973_, ResourceKey<? extends Registry<T>> p_251405_) {
return new ResourceArgument<>(p_249973_, p_251405_);
}
public static <T> Holder.Reference<T> getResource(CommandContext<CommandSourceStack> p_251788_, String p_251996_, ResourceKey<Registry<T>> p_250077_) throws CommandSyntaxException {
Holder.Reference<T> reference = p_251788_.getArgument(p_251996_, Holder.Reference.class);
ResourceKey<?> resourcekey = reference.key();
if (resourcekey.isFor(p_250077_)) {
return reference;
} else {
throw ERROR_INVALID_RESOURCE_TYPE.create(resourcekey.location(), resourcekey.registry(), p_250077_.location());
}
}
public static Holder.Reference<Attribute> getAttribute(CommandContext<CommandSourceStack> p_248753_, String p_251157_) throws CommandSyntaxException {
return getResource(p_248753_, p_251157_, Registries.ATTRIBUTE);
}
public static Holder.Reference<ConfiguredFeature<?, ?>> getConfiguredFeature(CommandContext<CommandSourceStack> p_250819_, String p_252256_) throws CommandSyntaxException {
return getResource(p_250819_, p_252256_, Registries.CONFIGURED_FEATURE);
}
public static Holder.Reference<Structure> getStructure(CommandContext<CommandSourceStack> p_250288_, String p_250856_) throws CommandSyntaxException {
return getResource(p_250288_, p_250856_, Registries.STRUCTURE);
}
public static Holder.Reference<EntityType<?>> getEntityType(CommandContext<CommandSourceStack> p_251258_, String p_252322_) throws CommandSyntaxException {
return getResource(p_251258_, p_252322_, Registries.ENTITY_TYPE);
}
public static Holder.Reference<EntityType<?>> getSummonableEntityType(CommandContext<CommandSourceStack> p_251880_, String p_250243_) throws CommandSyntaxException {
Holder.Reference<EntityType<?>> reference = getResource(p_251880_, p_250243_, Registries.ENTITY_TYPE);
if (!reference.value().canSummon()) {
throw ERROR_NOT_SUMMONABLE_ENTITY.create(reference.key().location().toString());
} else {
return reference;
}
}
public static Holder.Reference<MobEffect> getMobEffect(CommandContext<CommandSourceStack> p_250521_, String p_249927_) throws CommandSyntaxException {
return getResource(p_250521_, p_249927_, Registries.MOB_EFFECT);
}
public static Holder.Reference<Enchantment> getEnchantment(CommandContext<CommandSourceStack> p_248656_, String p_248713_) throws CommandSyntaxException {
return getResource(p_248656_, p_248713_, Registries.ENCHANTMENT);
}
public Holder.Reference<T> parse(StringReader p_250909_) throws CommandSyntaxException {
ResourceLocation resourcelocation = ResourceLocation.read(p_250909_);
ResourceKey<T> resourcekey = ResourceKey.create(this.registryKey, resourcelocation);
return this.registryLookup.get(resourcekey).orElseThrow(() -> {
return ERROR_UNKNOWN_RESOURCE.create(resourcelocation, this.registryKey.location());
});
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_249391_, SuggestionsBuilder p_251197_) {
return SharedSuggestionProvider.suggestResource(this.registryLookup.listElementIds().map(ResourceKey::location), p_251197_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Info<T> implements ArgumentTypeInfo<ResourceArgument<T>, ResourceArgument.Info<T>.Template> {
public void serializeToNetwork(ResourceArgument.Info<T>.Template p_250470_, FriendlyByteBuf p_248658_) {
p_248658_.writeResourceLocation(p_250470_.registryKey.location());
}
public ResourceArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf p_248958_) {
ResourceLocation resourcelocation = p_248958_.readResourceLocation();
return new ResourceArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
}
public void serializeToJson(ResourceArgument.Info<T>.Template p_251267_, JsonObject p_250142_) {
p_250142_.addProperty("registry", p_251267_.registryKey.location().toString());
}
public ResourceArgument.Info<T>.Template unpack(ResourceArgument<T> p_250667_) {
return new ResourceArgument.Info.Template(p_250667_.registryKey);
}
public final class Template implements ArgumentTypeInfo.Template<ResourceArgument<T>> {
final ResourceKey<? extends Registry<T>> registryKey;
Template(ResourceKey<? extends Registry<T>> p_250598_) {
this.registryKey = p_250598_;
}
public ResourceArgument<T> instantiate(CommandBuildContext p_251900_) {
return new ResourceArgument<>(p_251900_, this.registryKey);
}
public ArgumentTypeInfo<ResourceArgument<T>, ?> type() {
return Info.this;
}
}
}
}

View File

@@ -0,0 +1,134 @@
package net.minecraft.commands.arguments;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
public class ResourceKeyArgument<T> implements ArgumentType<ResourceKey<T>> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012");
private static final DynamicCommandExceptionType ERROR_INVALID_FEATURE = new DynamicCommandExceptionType((p_212392_) -> {
return Component.translatable("commands.place.feature.invalid", p_212392_);
});
private static final DynamicCommandExceptionType ERROR_INVALID_STRUCTURE = new DynamicCommandExceptionType((p_212385_) -> {
return Component.translatable("commands.place.structure.invalid", p_212385_);
});
private static final DynamicCommandExceptionType ERROR_INVALID_TEMPLATE_POOL = new DynamicCommandExceptionType((p_233264_) -> {
return Component.translatable("commands.place.jigsaw.invalid", p_233264_);
});
final ResourceKey<? extends Registry<T>> registryKey;
public ResourceKeyArgument(ResourceKey<? extends Registry<T>> p_212367_) {
this.registryKey = p_212367_;
}
public static <T> ResourceKeyArgument<T> key(ResourceKey<? extends Registry<T>> p_212387_) {
return new ResourceKeyArgument<>(p_212387_);
}
private static <T> ResourceKey<T> getRegistryKey(CommandContext<CommandSourceStack> p_212374_, String p_212375_, ResourceKey<Registry<T>> p_212376_, DynamicCommandExceptionType p_212377_) throws CommandSyntaxException {
ResourceKey<?> resourcekey = p_212374_.getArgument(p_212375_, ResourceKey.class);
Optional<ResourceKey<T>> optional = resourcekey.cast(p_212376_);
return optional.orElseThrow(() -> {
return p_212377_.create(resourcekey);
});
}
private static <T> Registry<T> getRegistry(CommandContext<CommandSourceStack> p_212379_, ResourceKey<? extends Registry<T>> p_212380_) {
return p_212379_.getSource().getServer().registryAccess().registryOrThrow(p_212380_);
}
private static <T> Holder.Reference<T> resolveKey(CommandContext<CommandSourceStack> p_248662_, String p_252172_, ResourceKey<Registry<T>> p_249701_, DynamicCommandExceptionType p_249790_) throws CommandSyntaxException {
ResourceKey<T> resourcekey = getRegistryKey(p_248662_, p_252172_, p_249701_, p_249790_);
return getRegistry(p_248662_, p_249701_).getHolder(resourcekey).orElseThrow(() -> {
return p_249790_.create(resourcekey.location());
});
}
public static Holder.Reference<ConfiguredFeature<?, ?>> getConfiguredFeature(CommandContext<CommandSourceStack> p_249310_, String p_250729_) throws CommandSyntaxException {
return resolveKey(p_249310_, p_250729_, Registries.CONFIGURED_FEATURE, ERROR_INVALID_FEATURE);
}
public static Holder.Reference<Structure> getStructure(CommandContext<CommandSourceStack> p_248804_, String p_251331_) throws CommandSyntaxException {
return resolveKey(p_248804_, p_251331_, Registries.STRUCTURE, ERROR_INVALID_STRUCTURE);
}
public static Holder.Reference<StructureTemplatePool> getStructureTemplatePool(CommandContext<CommandSourceStack> p_252203_, String p_250407_) throws CommandSyntaxException {
return resolveKey(p_252203_, p_250407_, Registries.TEMPLATE_POOL, ERROR_INVALID_TEMPLATE_POOL);
}
public ResourceKey<T> parse(StringReader p_212369_) throws CommandSyntaxException {
ResourceLocation resourcelocation = ResourceLocation.read(p_212369_);
return ResourceKey.create(this.registryKey, resourcelocation);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_212399_, SuggestionsBuilder p_212400_) {
Object object = p_212399_.getSource();
if (object instanceof SharedSuggestionProvider sharedsuggestionprovider) {
return sharedsuggestionprovider.suggestRegistryElements(this.registryKey, SharedSuggestionProvider.ElementSuggestionType.ELEMENTS, p_212400_, p_212399_);
} else {
return p_212400_.buildFuture();
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Info<T> implements ArgumentTypeInfo<ResourceKeyArgument<T>, ResourceKeyArgument.Info<T>.Template> {
public void serializeToNetwork(ResourceKeyArgument.Info<T>.Template p_233278_, FriendlyByteBuf p_233279_) {
p_233279_.writeResourceLocation(p_233278_.registryKey.location());
}
public ResourceKeyArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf p_233289_) {
ResourceLocation resourcelocation = p_233289_.readResourceLocation();
return new ResourceKeyArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
}
public void serializeToJson(ResourceKeyArgument.Info<T>.Template p_233275_, JsonObject p_233276_) {
p_233276_.addProperty("registry", p_233275_.registryKey.location().toString());
}
public ResourceKeyArgument.Info<T>.Template unpack(ResourceKeyArgument<T> p_233281_) {
return new ResourceKeyArgument.Info.Template(p_233281_.registryKey);
}
public final class Template implements ArgumentTypeInfo.Template<ResourceKeyArgument<T>> {
final ResourceKey<? extends Registry<T>> registryKey;
Template(ResourceKey<? extends Registry<T>> p_233296_) {
this.registryKey = p_233296_;
}
public ResourceKeyArgument<T> instantiate(CommandBuildContext p_233299_) {
return new ResourceKeyArgument<>(this.registryKey);
}
public ArgumentTypeInfo<ResourceKeyArgument<T>, ?> type() {
return Info.this;
}
}
}
}

View File

@@ -0,0 +1,91 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.advancements.Advancement;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.storage.loot.LootDataType;
import net.minecraft.world.level.storage.loot.functions.LootItemFunction;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
public class ResourceLocationArgument implements ArgumentType<ResourceLocation> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012");
private static final DynamicCommandExceptionType ERROR_UNKNOWN_ADVANCEMENT = new DynamicCommandExceptionType((p_107010_) -> {
return Component.translatable("advancement.advancementNotFound", p_107010_);
});
private static final DynamicCommandExceptionType ERROR_UNKNOWN_RECIPE = new DynamicCommandExceptionType((p_107005_) -> {
return Component.translatable("recipe.notFound", p_107005_);
});
private static final DynamicCommandExceptionType ERROR_UNKNOWN_PREDICATE = new DynamicCommandExceptionType((p_106998_) -> {
return Component.translatable("predicate.unknown", p_106998_);
});
private static final DynamicCommandExceptionType ERROR_UNKNOWN_ITEM_MODIFIER = new DynamicCommandExceptionType((p_106991_) -> {
return Component.translatable("item_modifier.unknown", p_106991_);
});
public static ResourceLocationArgument id() {
return new ResourceLocationArgument();
}
public static Advancement getAdvancement(CommandContext<CommandSourceStack> p_106988_, String p_106989_) throws CommandSyntaxException {
ResourceLocation resourcelocation = getId(p_106988_, p_106989_);
Advancement advancement = p_106988_.getSource().getAdvancement(resourcelocation);
if (advancement == null) {
throw ERROR_UNKNOWN_ADVANCEMENT.create(resourcelocation);
} else {
return advancement;
}
}
public static Recipe<?> getRecipe(CommandContext<CommandSourceStack> p_106995_, String p_106996_) throws CommandSyntaxException {
RecipeManager recipemanager = p_106995_.getSource().getRecipeManager();
ResourceLocation resourcelocation = getId(p_106995_, p_106996_);
return recipemanager.byKey(resourcelocation).orElseThrow(() -> {
return ERROR_UNKNOWN_RECIPE.create(resourcelocation);
});
}
public static LootItemCondition getPredicate(CommandContext<CommandSourceStack> p_107002_, String p_107003_) throws CommandSyntaxException {
ResourceLocation resourcelocation = getId(p_107002_, p_107003_);
LootDataManager lootdatamanager = p_107002_.getSource().getServer().getLootData();
LootItemCondition lootitemcondition = lootdatamanager.getElement(LootDataType.PREDICATE, resourcelocation);
if (lootitemcondition == null) {
throw ERROR_UNKNOWN_PREDICATE.create(resourcelocation);
} else {
return lootitemcondition;
}
}
public static LootItemFunction getItemModifier(CommandContext<CommandSourceStack> p_171032_, String p_171033_) throws CommandSyntaxException {
ResourceLocation resourcelocation = getId(p_171032_, p_171033_);
LootDataManager lootdatamanager = p_171032_.getSource().getServer().getLootData();
LootItemFunction lootitemfunction = lootdatamanager.getElement(LootDataType.MODIFIER, resourcelocation);
if (lootitemfunction == null) {
throw ERROR_UNKNOWN_ITEM_MODIFIER.create(resourcelocation);
} else {
return lootitemfunction;
}
}
public static ResourceLocation getId(CommandContext<CommandSourceStack> p_107012_, String p_107013_) {
return p_107012_.getArgument(p_107013_, ResourceLocation.class);
}
public ResourceLocation parse(StringReader p_106986_) throws CommandSyntaxException {
return ResourceLocation.read(p_106986_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,179 @@
package net.minecraft.commands.arguments;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.datafixers.util.Either;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
public class ResourceOrTagArgument<T> implements ArgumentType<ResourceOrTagArgument.Result<T>> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012", "#skeletons", "#minecraft:skeletons");
private static final Dynamic2CommandExceptionType ERROR_UNKNOWN_TAG = new Dynamic2CommandExceptionType((p_250953_, p_249704_) -> {
return Component.translatable("argument.resource_tag.not_found", p_250953_, p_249704_);
});
private static final Dynamic3CommandExceptionType ERROR_INVALID_TAG_TYPE = new Dynamic3CommandExceptionType((p_250188_, p_252173_, p_251453_) -> {
return Component.translatable("argument.resource_tag.invalid_type", p_250188_, p_252173_, p_251453_);
});
private final HolderLookup<T> registryLookup;
final ResourceKey<? extends Registry<T>> registryKey;
public ResourceOrTagArgument(CommandBuildContext p_249382_, ResourceKey<? extends Registry<T>> p_251209_) {
this.registryKey = p_251209_;
this.registryLookup = p_249382_.holderLookup(p_251209_);
}
public static <T> ResourceOrTagArgument<T> resourceOrTag(CommandBuildContext p_251101_, ResourceKey<? extends Registry<T>> p_248888_) {
return new ResourceOrTagArgument<>(p_251101_, p_248888_);
}
public static <T> ResourceOrTagArgument.Result<T> getResourceOrTag(CommandContext<CommandSourceStack> p_249001_, String p_251520_, ResourceKey<Registry<T>> p_250370_) throws CommandSyntaxException {
ResourceOrTagArgument.Result<?> result = p_249001_.getArgument(p_251520_, ResourceOrTagArgument.Result.class);
Optional<ResourceOrTagArgument.Result<T>> optional = result.cast(p_250370_);
return optional.orElseThrow(() -> {
return result.unwrap().map((p_252340_) -> {
ResourceKey<?> resourcekey = p_252340_.key();
return ResourceArgument.ERROR_INVALID_RESOURCE_TYPE.create(resourcekey.location(), resourcekey.registry(), p_250370_.location());
}, (p_250301_) -> {
TagKey<?> tagkey = p_250301_.key();
return ERROR_INVALID_TAG_TYPE.create(tagkey.location(), tagkey.registry(), p_250370_.location());
});
});
}
public ResourceOrTagArgument.Result<T> parse(StringReader p_250860_) throws CommandSyntaxException {
if (p_250860_.canRead() && p_250860_.peek() == '#') {
int i = p_250860_.getCursor();
try {
p_250860_.skip();
ResourceLocation resourcelocation1 = ResourceLocation.read(p_250860_);
TagKey<T> tagkey = TagKey.create(this.registryKey, resourcelocation1);
HolderSet.Named<T> named = this.registryLookup.get(tagkey).orElseThrow(() -> {
return ERROR_UNKNOWN_TAG.create(resourcelocation1, this.registryKey.location());
});
return new ResourceOrTagArgument.TagResult<>(named);
} catch (CommandSyntaxException commandsyntaxexception) {
p_250860_.setCursor(i);
throw commandsyntaxexception;
}
} else {
ResourceLocation resourcelocation = ResourceLocation.read(p_250860_);
ResourceKey<T> resourcekey = ResourceKey.create(this.registryKey, resourcelocation);
Holder.Reference<T> reference = this.registryLookup.get(resourcekey).orElseThrow(() -> {
return ResourceArgument.ERROR_UNKNOWN_RESOURCE.create(resourcelocation, this.registryKey.location());
});
return new ResourceOrTagArgument.ResourceResult<>(reference);
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_250223_, SuggestionsBuilder p_252354_) {
SharedSuggestionProvider.suggestResource(this.registryLookup.listTagIds().map(TagKey::location), p_252354_, "#");
return SharedSuggestionProvider.suggestResource(this.registryLookup.listElementIds().map(ResourceKey::location), p_252354_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Info<T> implements ArgumentTypeInfo<ResourceOrTagArgument<T>, ResourceOrTagArgument.Info<T>.Template> {
public void serializeToNetwork(ResourceOrTagArgument.Info<T>.Template p_250419_, FriendlyByteBuf p_249726_) {
p_249726_.writeResourceLocation(p_250419_.registryKey.location());
}
public ResourceOrTagArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf p_250205_) {
ResourceLocation resourcelocation = p_250205_.readResourceLocation();
return new ResourceOrTagArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
}
public void serializeToJson(ResourceOrTagArgument.Info<T>.Template p_251957_, JsonObject p_249067_) {
p_249067_.addProperty("registry", p_251957_.registryKey.location().toString());
}
public ResourceOrTagArgument.Info<T>.Template unpack(ResourceOrTagArgument<T> p_252206_) {
return new ResourceOrTagArgument.Info.Template(p_252206_.registryKey);
}
public final class Template implements ArgumentTypeInfo.Template<ResourceOrTagArgument<T>> {
final ResourceKey<? extends Registry<T>> registryKey;
Template(ResourceKey<? extends Registry<T>> p_250107_) {
this.registryKey = p_250107_;
}
public ResourceOrTagArgument<T> instantiate(CommandBuildContext p_251386_) {
return new ResourceOrTagArgument<>(p_251386_, this.registryKey);
}
public ArgumentTypeInfo<ResourceOrTagArgument<T>, ?> type() {
return Info.this;
}
}
}
static record ResourceResult<T>(Holder.Reference<T> value) implements ResourceOrTagArgument.Result<T> {
public Either<Holder.Reference<T>, HolderSet.Named<T>> unwrap() {
return Either.left(this.value);
}
public <E> Optional<ResourceOrTagArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_250007_) {
return this.value.key().isFor(p_250007_) ? Optional.of((ResourceOrTagArgument.Result) this) : Optional.empty();
}
public boolean test(Holder<T> p_249230_) {
return p_249230_.equals(this.value);
}
public String asPrintable() {
return this.value.key().location().toString();
}
}
public interface Result<T> extends Predicate<Holder<T>> {
Either<Holder.Reference<T>, HolderSet.Named<T>> unwrap();
<E> Optional<ResourceOrTagArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_249572_);
String asPrintable();
}
static record TagResult<T>(HolderSet.Named<T> tag) implements ResourceOrTagArgument.Result<T> {
public Either<Holder.Reference<T>, HolderSet.Named<T>> unwrap() {
return Either.right(this.tag);
}
public <E> Optional<ResourceOrTagArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_250945_) {
return this.tag.key().isFor(p_250945_) ? Optional.of((ResourceOrTagArgument.Result) this) : Optional.empty();
}
public boolean test(Holder<T> p_252187_) {
return this.tag.contains(p_252187_);
}
public String asPrintable() {
return "#" + this.tag.key().location();
}
}
}

View File

@@ -0,0 +1,157 @@
package net.minecraft.commands.arguments;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.datafixers.util.Either;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
public class ResourceOrTagKeyArgument<T> implements ArgumentType<ResourceOrTagKeyArgument.Result<T>> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012", "#skeletons", "#minecraft:skeletons");
final ResourceKey<? extends Registry<T>> registryKey;
public ResourceOrTagKeyArgument(ResourceKey<? extends Registry<T>> p_248579_) {
this.registryKey = p_248579_;
}
public static <T> ResourceOrTagKeyArgument<T> resourceOrTagKey(ResourceKey<? extends Registry<T>> p_249175_) {
return new ResourceOrTagKeyArgument<>(p_249175_);
}
public static <T> ResourceOrTagKeyArgument.Result<T> getResourceOrTagKey(CommandContext<CommandSourceStack> p_252162_, String p_248628_, ResourceKey<Registry<T>> p_249008_, DynamicCommandExceptionType p_251387_) throws CommandSyntaxException {
ResourceOrTagKeyArgument.Result<?> result = p_252162_.getArgument(p_248628_, ResourceOrTagKeyArgument.Result.class);
Optional<ResourceOrTagKeyArgument.Result<T>> optional = result.cast(p_249008_);
return optional.orElseThrow(() -> {
return p_251387_.create(result);
});
}
public ResourceOrTagKeyArgument.Result<T> parse(StringReader p_250307_) throws CommandSyntaxException {
if (p_250307_.canRead() && p_250307_.peek() == '#') {
int i = p_250307_.getCursor();
try {
p_250307_.skip();
ResourceLocation resourcelocation1 = ResourceLocation.read(p_250307_);
return new ResourceOrTagKeyArgument.TagResult<>(TagKey.create(this.registryKey, resourcelocation1));
} catch (CommandSyntaxException commandsyntaxexception) {
p_250307_.setCursor(i);
throw commandsyntaxexception;
}
} else {
ResourceLocation resourcelocation = ResourceLocation.read(p_250307_);
return new ResourceOrTagKeyArgument.ResourceResult<>(ResourceKey.create(this.registryKey, resourcelocation));
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_251659_, SuggestionsBuilder p_251141_) {
Object object = p_251659_.getSource();
if (object instanceof SharedSuggestionProvider sharedsuggestionprovider) {
return sharedsuggestionprovider.suggestRegistryElements(this.registryKey, SharedSuggestionProvider.ElementSuggestionType.ALL, p_251141_, p_251659_);
} else {
return p_251141_.buildFuture();
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Info<T> implements ArgumentTypeInfo<ResourceOrTagKeyArgument<T>, ResourceOrTagKeyArgument.Info<T>.Template> {
public void serializeToNetwork(ResourceOrTagKeyArgument.Info<T>.Template p_252211_, FriendlyByteBuf p_248784_) {
p_248784_.writeResourceLocation(p_252211_.registryKey.location());
}
public ResourceOrTagKeyArgument.Info<T>.Template deserializeFromNetwork(FriendlyByteBuf p_250656_) {
ResourceLocation resourcelocation = p_250656_.readResourceLocation();
return new ResourceOrTagKeyArgument.Info.Template(ResourceKey.createRegistryKey(resourcelocation));
}
public void serializeToJson(ResourceOrTagKeyArgument.Info<T>.Template p_250715_, JsonObject p_249208_) {
p_249208_.addProperty("registry", p_250715_.registryKey.location().toString());
}
public ResourceOrTagKeyArgument.Info<T>.Template unpack(ResourceOrTagKeyArgument<T> p_250422_) {
return new ResourceOrTagKeyArgument.Info.Template(p_250422_.registryKey);
}
public final class Template implements ArgumentTypeInfo.Template<ResourceOrTagKeyArgument<T>> {
final ResourceKey<? extends Registry<T>> registryKey;
Template(ResourceKey<? extends Registry<T>> p_251992_) {
this.registryKey = p_251992_;
}
public ResourceOrTagKeyArgument<T> instantiate(CommandBuildContext p_251559_) {
return new ResourceOrTagKeyArgument<>(this.registryKey);
}
public ArgumentTypeInfo<ResourceOrTagKeyArgument<T>, ?> type() {
return Info.this;
}
}
}
static record ResourceResult<T>(ResourceKey<T> key) implements ResourceOrTagKeyArgument.Result<T> {
public Either<ResourceKey<T>, TagKey<T>> unwrap() {
return Either.left(this.key);
}
public <E> Optional<ResourceOrTagKeyArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_251369_) {
return this.key.cast(p_251369_).map(ResourceOrTagKeyArgument.ResourceResult::new);
}
public boolean test(Holder<T> p_250257_) {
return p_250257_.is(this.key);
}
public String asPrintable() {
return this.key.location().toString();
}
}
public interface Result<T> extends Predicate<Holder<T>> {
Either<ResourceKey<T>, TagKey<T>> unwrap();
<E> Optional<ResourceOrTagKeyArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_251612_);
String asPrintable();
}
static record TagResult<T>(TagKey<T> key) implements ResourceOrTagKeyArgument.Result<T> {
public Either<ResourceKey<T>, TagKey<T>> unwrap() {
return Either.right(this.key);
}
public <E> Optional<ResourceOrTagKeyArgument.Result<E>> cast(ResourceKey<? extends Registry<E>> p_251833_) {
return this.key.cast(p_251833_).map(ResourceOrTagKeyArgument.TagResult::new);
}
public boolean test(Holder<T> p_252238_) {
return p_252238_.is(this.key);
}
public String asPrintable() {
return "#" + this.key.location();
}
}
}

View File

@@ -0,0 +1,187 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
public class ScoreHolderArgument implements ArgumentType<ScoreHolderArgument.Result> {
public static final SuggestionProvider<CommandSourceStack> SUGGEST_SCORE_HOLDERS = (p_108221_, p_108222_) -> {
StringReader stringreader = new StringReader(p_108222_.getInput());
stringreader.setCursor(p_108222_.getStart());
EntitySelectorParser entityselectorparser = new EntitySelectorParser(stringreader);
try {
entityselectorparser.parse();
} catch (CommandSyntaxException commandsyntaxexception) {
}
return entityselectorparser.fillSuggestions(p_108222_, (p_171606_) -> {
SharedSuggestionProvider.suggest(p_108221_.getSource().getOnlinePlayerNames(), p_171606_);
});
};
private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "*", "@e");
private static final SimpleCommandExceptionType ERROR_NO_RESULTS = new SimpleCommandExceptionType(Component.translatable("argument.scoreHolder.empty"));
final boolean multiple;
public ScoreHolderArgument(boolean p_108216_) {
this.multiple = p_108216_;
}
public static String getName(CommandContext<CommandSourceStack> p_108224_, String p_108225_) throws CommandSyntaxException {
return getNames(p_108224_, p_108225_).iterator().next();
}
public static Collection<String> getNames(CommandContext<CommandSourceStack> p_108244_, String p_108245_) throws CommandSyntaxException {
return getNames(p_108244_, p_108245_, Collections::emptyList);
}
public static Collection<String> getNamesWithDefaultWildcard(CommandContext<CommandSourceStack> p_108247_, String p_108248_) throws CommandSyntaxException {
return getNames(p_108247_, p_108248_, p_108247_.getSource().getServer().getScoreboard()::getTrackedPlayers);
}
public static Collection<String> getNames(CommandContext<CommandSourceStack> p_108227_, String p_108228_, Supplier<Collection<String>> p_108229_) throws CommandSyntaxException {
Collection<String> collection = p_108227_.getArgument(p_108228_, ScoreHolderArgument.Result.class).getNames(p_108227_.getSource(), p_108229_);
if (collection.isEmpty()) {
throw EntityArgument.NO_ENTITIES_FOUND.create();
} else {
return collection;
}
}
public static ScoreHolderArgument scoreHolder() {
return new ScoreHolderArgument(false);
}
public static ScoreHolderArgument scoreHolders() {
return new ScoreHolderArgument(true);
}
public ScoreHolderArgument.Result parse(StringReader p_108219_) throws CommandSyntaxException {
if (p_108219_.canRead() && p_108219_.peek() == '@') {
EntitySelectorParser entityselectorparser = new EntitySelectorParser(p_108219_);
EntitySelector entityselector = entityselectorparser.parse();
if (!this.multiple && entityselector.getMaxResults() > 1) {
throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.create();
} else {
return new ScoreHolderArgument.SelectorResult(entityselector);
}
} else {
int i = p_108219_.getCursor();
while(p_108219_.canRead() && p_108219_.peek() != ' ') {
p_108219_.skip();
}
String s = p_108219_.getString().substring(i, p_108219_.getCursor());
if (s.equals("*")) {
return (p_108231_, p_108232_) -> {
Collection<String> collection1 = p_108232_.get();
if (collection1.isEmpty()) {
throw ERROR_NO_RESULTS.create();
} else {
return collection1;
}
};
} else {
Collection<String> collection = Collections.singleton(s);
return (p_108237_, p_108238_) -> {
return collection;
};
}
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public static class Info implements ArgumentTypeInfo<ScoreHolderArgument, ScoreHolderArgument.Info.Template> {
private static final byte FLAG_MULTIPLE = 1;
public void serializeToNetwork(ScoreHolderArgument.Info.Template p_233469_, FriendlyByteBuf p_233470_) {
int i = 0;
if (p_233469_.multiple) {
i |= 1;
}
p_233470_.writeByte(i);
}
public ScoreHolderArgument.Info.Template deserializeFromNetwork(FriendlyByteBuf p_233480_) {
byte b0 = p_233480_.readByte();
boolean flag = (b0 & 1) != 0;
return new ScoreHolderArgument.Info.Template(flag);
}
public void serializeToJson(ScoreHolderArgument.Info.Template p_233466_, JsonObject p_233467_) {
p_233467_.addProperty("amount", p_233466_.multiple ? "multiple" : "single");
}
public ScoreHolderArgument.Info.Template unpack(ScoreHolderArgument p_233472_) {
return new ScoreHolderArgument.Info.Template(p_233472_.multiple);
}
public final class Template implements ArgumentTypeInfo.Template<ScoreHolderArgument> {
final boolean multiple;
Template(boolean p_233487_) {
this.multiple = p_233487_;
}
public ScoreHolderArgument instantiate(CommandBuildContext p_233490_) {
return new ScoreHolderArgument(this.multiple);
}
public ArgumentTypeInfo<ScoreHolderArgument, ?> type() {
return Info.this;
}
}
}
@FunctionalInterface
public interface Result {
Collection<String> getNames(CommandSourceStack p_108252_, Supplier<Collection<String>> p_108253_) throws CommandSyntaxException;
}
public static class SelectorResult implements ScoreHolderArgument.Result {
private final EntitySelector selector;
public SelectorResult(EntitySelector p_108256_) {
this.selector = p_108256_;
}
public Collection<String> getNames(CommandSourceStack p_108258_, Supplier<Collection<String>> p_108259_) throws CommandSyntaxException {
List<? extends Entity> list = this.selector.findEntities(p_108258_);
if (list.isEmpty()) {
throw EntityArgument.NO_ENTITIES_FOUND.create();
} else {
List<String> list1 = Lists.newArrayList();
for(Entity entity : list) {
list1.add(entity.getScoreboardName());
}
return list1;
}
}
}
}

View File

@@ -0,0 +1,52 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.scores.Scoreboard;
public class ScoreboardSlotArgument implements ArgumentType<Integer> {
private static final Collection<String> EXAMPLES = Arrays.asList("sidebar", "foo.bar");
public static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_109203_) -> {
return Component.translatable("argument.scoreboardDisplaySlot.invalid", p_109203_);
});
private ScoreboardSlotArgument() {
}
public static ScoreboardSlotArgument displaySlot() {
return new ScoreboardSlotArgument();
}
public static int getDisplaySlot(CommandContext<CommandSourceStack> p_109200_, String p_109201_) {
return p_109200_.getArgument(p_109201_, Integer.class);
}
public Integer parse(StringReader p_109198_) throws CommandSyntaxException {
String s = p_109198_.readUnquotedString();
int i = Scoreboard.getDisplaySlotByName(s);
if (i == -1) {
throw ERROR_INVALID_VALUE.create(s);
} else {
return i;
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_109206_, SuggestionsBuilder p_109207_) {
return SharedSuggestionProvider.suggest(Scoreboard.getDisplaySlotNames(), p_109207_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,6 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.arguments.ArgumentType;
public interface SignedArgument<T> extends ArgumentType<T> {
}

View File

@@ -0,0 +1,87 @@
package net.minecraft.commands.arguments;
import com.google.common.collect.Maps;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.EquipmentSlot;
public class SlotArgument implements ArgumentType<Integer> {
private static final Collection<String> EXAMPLES = Arrays.asList("container.5", "12", "weapon");
private static final DynamicCommandExceptionType ERROR_UNKNOWN_SLOT = new DynamicCommandExceptionType((p_111283_) -> {
return Component.translatable("slot.unknown", p_111283_);
});
private static final Map<String, Integer> SLOTS = Util.make(Maps.newHashMap(), (p_111285_) -> {
for(int i = 0; i < 54; ++i) {
p_111285_.put("container." + i, i);
}
for(int j = 0; j < 9; ++j) {
p_111285_.put("hotbar." + j, j);
}
for(int k = 0; k < 27; ++k) {
p_111285_.put("inventory." + k, 9 + k);
}
for(int l = 0; l < 27; ++l) {
p_111285_.put("enderchest." + l, 200 + l);
}
for(int i1 = 0; i1 < 8; ++i1) {
p_111285_.put("villager." + i1, 300 + i1);
}
for(int j1 = 0; j1 < 15; ++j1) {
p_111285_.put("horse." + j1, 500 + j1);
}
p_111285_.put("weapon", EquipmentSlot.MAINHAND.getIndex(98));
p_111285_.put("weapon.mainhand", EquipmentSlot.MAINHAND.getIndex(98));
p_111285_.put("weapon.offhand", EquipmentSlot.OFFHAND.getIndex(98));
p_111285_.put("armor.head", EquipmentSlot.HEAD.getIndex(100));
p_111285_.put("armor.chest", EquipmentSlot.CHEST.getIndex(100));
p_111285_.put("armor.legs", EquipmentSlot.LEGS.getIndex(100));
p_111285_.put("armor.feet", EquipmentSlot.FEET.getIndex(100));
p_111285_.put("horse.saddle", 400);
p_111285_.put("horse.armor", 401);
p_111285_.put("horse.chest", 499);
});
public static SlotArgument slot() {
return new SlotArgument();
}
public static int getSlot(CommandContext<CommandSourceStack> p_111280_, String p_111281_) {
return p_111280_.getArgument(p_111281_, Integer.class);
}
public Integer parse(StringReader p_111278_) throws CommandSyntaxException {
String s = p_111278_.readUnquotedString();
if (!SLOTS.containsKey(s)) {
throw ERROR_UNKNOWN_SLOT.create(s);
} else {
return SLOTS.get(s);
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_111288_, SuggestionsBuilder p_111289_) {
return SharedSuggestionProvider.suggest(SLOTS.keySet(), p_111289_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,56 @@
package net.minecraft.commands.arguments;
import com.google.gson.JsonPrimitive;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.util.StringRepresentable;
public class StringRepresentableArgument<T extends Enum<T> & StringRepresentable> implements ArgumentType<T> {
private static final DynamicCommandExceptionType ERROR_INVALID_VALUE = new DynamicCommandExceptionType((p_234071_) -> {
return Component.translatable("argument.enum.invalid", p_234071_);
});
private final Codec<T> codec;
private final Supplier<T[]> values;
protected StringRepresentableArgument(Codec<T> p_234060_, Supplier<T[]> p_234061_) {
this.codec = p_234060_;
this.values = p_234061_;
}
public T parse(StringReader p_234063_) throws CommandSyntaxException {
String s = p_234063_.readUnquotedString();
return this.codec.parse(JsonOps.INSTANCE, new JsonPrimitive(s)).result().orElseThrow(() -> {
return ERROR_INVALID_VALUE.create(s);
});
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_234074_, SuggestionsBuilder p_234075_) {
return SharedSuggestionProvider.suggest(Arrays.<Enum>stream((Enum[])this.values.get()).map((p_234069_) -> {
return ((StringRepresentable)p_234069_).getSerializedName();
}).map(this::convertId).collect(Collectors.toList()), p_234075_);
}
public Collection<String> getExamples() {
return Arrays.<Enum>stream((Enum[])this.values.get()).map((p_234065_) -> {
return ((StringRepresentable)p_234065_).getSerializedName();
}).map(this::convertId).limit(2L).collect(Collectors.toList());
}
protected String convertId(String p_275436_) {
return p_275436_;
}
}

View File

@@ -0,0 +1,51 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.scores.PlayerTeam;
import net.minecraft.world.scores.Scoreboard;
public class TeamArgument implements ArgumentType<String> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "123");
private static final DynamicCommandExceptionType ERROR_TEAM_NOT_FOUND = new DynamicCommandExceptionType((p_112095_) -> {
return Component.translatable("team.notFound", p_112095_);
});
public static TeamArgument team() {
return new TeamArgument();
}
public static PlayerTeam getTeam(CommandContext<CommandSourceStack> p_112092_, String p_112093_) throws CommandSyntaxException {
String s = p_112092_.getArgument(p_112093_, String.class);
Scoreboard scoreboard = p_112092_.getSource().getScoreboard();
PlayerTeam playerteam = scoreboard.getPlayerTeam(s);
if (playerteam == null) {
throw ERROR_TEAM_NOT_FOUND.create(s);
} else {
return playerteam;
}
}
public String parse(StringReader p_112090_) throws CommandSyntaxException {
return p_112090_.readUnquotedString();
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_112098_, SuggestionsBuilder p_112099_) {
return p_112098_.getSource() instanceof SharedSuggestionProvider ? SharedSuggestionProvider.suggest(((SharedSuggestionProvider)p_112098_.getSource()).getAllTeams(), p_112099_) : Suggestions.empty();
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,19 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.world.level.block.Mirror;
public class TemplateMirrorArgument extends StringRepresentableArgument<Mirror> {
private TemplateMirrorArgument() {
super(Mirror.CODEC, Mirror::values);
}
public static StringRepresentableArgument<Mirror> templateMirror() {
return new TemplateMirrorArgument();
}
public static Mirror getMirror(CommandContext<CommandSourceStack> p_234345_, String p_234346_) {
return p_234345_.getArgument(p_234346_, Mirror.class);
}
}

View File

@@ -0,0 +1,19 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.world.level.block.Rotation;
public class TemplateRotationArgument extends StringRepresentableArgument<Rotation> {
private TemplateRotationArgument() {
super(Rotation.CODEC, Rotation::values);
}
public static TemplateRotationArgument templateRotation() {
return new TemplateRotationArgument();
}
public static Rotation getRotation(CommandContext<CommandSourceStack> p_234416_, String p_234417_) {
return p_234416_.getArgument(p_234417_, Rotation.class);
}
}

View File

@@ -0,0 +1,117 @@
package net.minecraft.commands.arguments;
import com.google.gson.JsonObject;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
public class TimeArgument implements ArgumentType<Integer> {
private static final Collection<String> EXAMPLES = Arrays.asList("0d", "0s", "0t", "0");
private static final SimpleCommandExceptionType ERROR_INVALID_UNIT = new SimpleCommandExceptionType(Component.translatable("argument.time.invalid_unit"));
private static final Dynamic2CommandExceptionType ERROR_TICK_COUNT_TOO_LOW = new Dynamic2CommandExceptionType((p_264715_, p_264716_) -> {
return Component.translatable("argument.time.tick_count_too_low", p_264716_, p_264715_);
});
private static final Object2IntMap<String> UNITS = new Object2IntOpenHashMap<>();
final int minimum;
private TimeArgument(int p_265107_) {
this.minimum = p_265107_;
}
public static TimeArgument time() {
return new TimeArgument(0);
}
public static TimeArgument time(int p_265722_) {
return new TimeArgument(p_265722_);
}
public Integer parse(StringReader p_113039_) throws CommandSyntaxException {
float f = p_113039_.readFloat();
String s = p_113039_.readUnquotedString();
int i = UNITS.getOrDefault(s, 0);
if (i == 0) {
throw ERROR_INVALID_UNIT.create();
} else {
int j = Math.round(f * (float)i);
if (j < this.minimum) {
throw ERROR_TICK_COUNT_TOO_LOW.create(j, this.minimum);
} else {
return j;
}
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_113044_, SuggestionsBuilder p_113045_) {
StringReader stringreader = new StringReader(p_113045_.getRemaining());
try {
stringreader.readFloat();
} catch (CommandSyntaxException commandsyntaxexception) {
return p_113045_.buildFuture();
}
return SharedSuggestionProvider.suggest(UNITS.keySet(), p_113045_.createOffset(p_113045_.getStart() + stringreader.getCursor()));
}
public Collection<String> getExamples() {
return EXAMPLES;
}
static {
UNITS.put("d", 24000);
UNITS.put("s", 20);
UNITS.put("t", 1);
UNITS.put("", 1);
}
public static class Info implements ArgumentTypeInfo<TimeArgument, TimeArgument.Info.Template> {
public void serializeToNetwork(TimeArgument.Info.Template p_265434_, FriendlyByteBuf p_265320_) {
p_265320_.writeInt(p_265434_.min);
}
public TimeArgument.Info.Template deserializeFromNetwork(FriendlyByteBuf p_265324_) {
int i = p_265324_.readInt();
return new TimeArgument.Info.Template(i);
}
public void serializeToJson(TimeArgument.Info.Template p_265110_, JsonObject p_265629_) {
p_265629_.addProperty("min", p_265110_.min);
}
public TimeArgument.Info.Template unpack(TimeArgument p_265544_) {
return new TimeArgument.Info.Template(p_265544_.minimum);
}
public final class Template implements ArgumentTypeInfo.Template<TimeArgument> {
final int min;
Template(int p_265096_) {
this.min = p_265096_;
}
public TimeArgument instantiate(CommandBuildContext p_265466_) {
return TimeArgument.time(this.min);
}
public ArgumentTypeInfo<TimeArgument, ?> type() {
return Info.this;
}
}
}
}

View File

@@ -0,0 +1,49 @@
package net.minecraft.commands.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
public class UuidArgument implements ArgumentType<UUID> {
public static final SimpleCommandExceptionType ERROR_INVALID_UUID = new SimpleCommandExceptionType(Component.translatable("argument.uuid.invalid"));
private static final Collection<String> EXAMPLES = Arrays.asList("dd12be42-52a9-4a91-a8a1-11c01849e498");
private static final Pattern ALLOWED_CHARACTERS = Pattern.compile("^([-A-Fa-f0-9]+)");
public static UUID getUuid(CommandContext<CommandSourceStack> p_113854_, String p_113855_) {
return p_113854_.getArgument(p_113855_, UUID.class);
}
public static UuidArgument uuid() {
return new UuidArgument();
}
public UUID parse(StringReader p_113852_) throws CommandSyntaxException {
String s = p_113852_.getRemaining();
Matcher matcher = ALLOWED_CHARACTERS.matcher(s);
if (matcher.find()) {
String s1 = matcher.group(1);
try {
UUID uuid = UUID.fromString(s1);
p_113852_.setCursor(p_113852_.getCursor() + s1.length());
return uuid;
} catch (IllegalArgumentException illegalargumentexception) {
}
}
throw ERROR_INVALID_UUID.create();
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,79 @@
package net.minecraft.commands.arguments.blocks;
import java.util.Set;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.block.state.properties.Property;
public class BlockInput implements Predicate<BlockInWorld> {
private final BlockState state;
private final Set<Property<?>> properties;
@Nullable
private final CompoundTag tag;
public BlockInput(BlockState p_114666_, Set<Property<?>> p_114667_, @Nullable CompoundTag p_114668_) {
this.state = p_114666_;
this.properties = p_114667_;
this.tag = p_114668_;
}
public BlockState getState() {
return this.state;
}
public Set<Property<?>> getDefinedProperties() {
return this.properties;
}
public boolean test(BlockInWorld p_114675_) {
BlockState blockstate = p_114675_.getState();
if (!blockstate.is(this.state.getBlock())) {
return false;
} else {
for(Property<?> property : this.properties) {
if (blockstate.getValue(property) != this.state.getValue(property)) {
return false;
}
}
if (this.tag == null) {
return true;
} else {
BlockEntity blockentity = p_114675_.getEntity();
return blockentity != null && NbtUtils.compareNbt(this.tag, blockentity.saveWithFullMetadata(), true);
}
}
}
public boolean test(ServerLevel p_173524_, BlockPos p_173525_) {
return this.test(new BlockInWorld(p_173524_, p_173525_, false));
}
public boolean place(ServerLevel p_114671_, BlockPos p_114672_, int p_114673_) {
BlockState blockstate = Block.updateFromNeighbourShapes(this.state, p_114671_, p_114672_);
if (blockstate.isAir()) {
blockstate = this.state;
}
if (!p_114671_.setBlock(p_114672_, blockstate, p_114673_)) {
return false;
} else {
if (this.tag != null) {
BlockEntity blockentity = p_114671_.getBlockEntity(p_114672_);
if (blockentity != null) {
blockentity.load(this.tag);
}
}
return true;
}
}
}

View File

@@ -0,0 +1,152 @@
package net.minecraft.commands.arguments.blocks;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.block.state.properties.Property;
public class BlockPredicateArgument implements ArgumentType<BlockPredicateArgument.Result> {
private static final Collection<String> EXAMPLES = Arrays.asList("stone", "minecraft:stone", "stone[foo=bar]", "#stone", "#stone[foo=bar]{baz=nbt}");
private final HolderLookup<Block> blocks;
public BlockPredicateArgument(CommandBuildContext p_234626_) {
this.blocks = p_234626_.holderLookup(Registries.BLOCK);
}
public static BlockPredicateArgument blockPredicate(CommandBuildContext p_234628_) {
return new BlockPredicateArgument(p_234628_);
}
public BlockPredicateArgument.Result parse(StringReader p_115572_) throws CommandSyntaxException {
return parse(this.blocks, p_115572_);
}
public static BlockPredicateArgument.Result parse(HolderLookup<Block> p_234634_, StringReader p_234635_) throws CommandSyntaxException {
return BlockStateParser.parseForTesting(p_234634_, p_234635_, true).map((p_234630_) -> {
return new BlockPredicateArgument.BlockPredicate(p_234630_.blockState(), p_234630_.properties().keySet(), p_234630_.nbt());
}, (p_234632_) -> {
return new BlockPredicateArgument.TagPredicate(p_234632_.tag(), p_234632_.vagueProperties(), p_234632_.nbt());
});
}
public static Predicate<BlockInWorld> getBlockPredicate(CommandContext<CommandSourceStack> p_115574_, String p_115575_) throws CommandSyntaxException {
return p_115574_.getArgument(p_115575_, BlockPredicateArgument.Result.class);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_115587_, SuggestionsBuilder p_115588_) {
return BlockStateParser.fillSuggestions(this.blocks, p_115588_, true, true);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
static class BlockPredicate implements BlockPredicateArgument.Result {
private final BlockState state;
private final Set<Property<?>> properties;
@Nullable
private final CompoundTag nbt;
public BlockPredicate(BlockState p_115595_, Set<Property<?>> p_115596_, @Nullable CompoundTag p_115597_) {
this.state = p_115595_;
this.properties = p_115596_;
this.nbt = p_115597_;
}
public boolean test(BlockInWorld p_115599_) {
BlockState blockstate = p_115599_.getState();
if (!blockstate.is(this.state.getBlock())) {
return false;
} else {
for(Property<?> property : this.properties) {
if (blockstate.getValue(property) != this.state.getValue(property)) {
return false;
}
}
if (this.nbt == null) {
return true;
} else {
BlockEntity blockentity = p_115599_.getEntity();
return blockentity != null && NbtUtils.compareNbt(this.nbt, blockentity.saveWithFullMetadata(), true);
}
}
}
public boolean requiresNbt() {
return this.nbt != null;
}
}
public interface Result extends Predicate<BlockInWorld> {
boolean requiresNbt();
}
static class TagPredicate implements BlockPredicateArgument.Result {
private final HolderSet<Block> tag;
@Nullable
private final CompoundTag nbt;
private final Map<String, String> vagueProperties;
TagPredicate(HolderSet<Block> p_234637_, Map<String, String> p_234638_, @Nullable CompoundTag p_234639_) {
this.tag = p_234637_;
this.vagueProperties = p_234638_;
this.nbt = p_234639_;
}
public boolean test(BlockInWorld p_115617_) {
BlockState blockstate = p_115617_.getState();
if (!blockstate.is(this.tag)) {
return false;
} else {
for(Map.Entry<String, String> entry : this.vagueProperties.entrySet()) {
Property<?> property = blockstate.getBlock().getStateDefinition().getProperty(entry.getKey());
if (property == null) {
return false;
}
Comparable<?> comparable = (Comparable)property.getValue(entry.getValue()).orElse(null);
if (comparable == null) {
return false;
}
if (blockstate.getValue(property) != comparable) {
return false;
}
}
if (this.nbt == null) {
return true;
} else {
BlockEntity blockentity = p_115617_.getEntity();
return blockentity != null && NbtUtils.compareNbt(this.nbt, blockentity.saveWithFullMetadata(), true);
}
}
}
public boolean requiresNbt() {
return this.nbt != null;
}
}
}

View File

@@ -0,0 +1,46 @@
package net.minecraft.commands.arguments.blocks;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.level.block.Block;
public class BlockStateArgument implements ArgumentType<BlockInput> {
private static final Collection<String> EXAMPLES = Arrays.asList("stone", "minecraft:stone", "stone[foo=bar]", "foo{bar=baz}");
private final HolderLookup<Block> blocks;
public BlockStateArgument(CommandBuildContext p_234649_) {
this.blocks = p_234649_.holderLookup(Registries.BLOCK);
}
public static BlockStateArgument block(CommandBuildContext p_234651_) {
return new BlockStateArgument(p_234651_);
}
public BlockInput parse(StringReader p_116122_) throws CommandSyntaxException {
BlockStateParser.BlockResult blockstateparser$blockresult = BlockStateParser.parseForBlock(this.blocks, p_116122_, true);
return new BlockInput(blockstateparser$blockresult.blockState(), blockstateparser$blockresult.properties().keySet(), blockstateparser$blockresult.nbt());
}
public static BlockInput getBlock(CommandContext<CommandSourceStack> p_116124_, String p_116125_) {
return p_116124_.getArgument(p_116125_, BlockInput.class);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_116128_, SuggestionsBuilder p_116129_) {
return BlockStateParser.fillSuggestions(this.blocks, p_116129_, false, true);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,541 @@
package net.minecraft.commands.arguments.blocks;
import com.google.common.collect.Maps;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.datafixers.util.Either;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import javax.annotation.Nullable;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.Property;
public class BlockStateParser {
public static final SimpleCommandExceptionType ERROR_NO_TAGS_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.block.tag.disallowed"));
public static final DynamicCommandExceptionType ERROR_UNKNOWN_BLOCK = new DynamicCommandExceptionType((p_116790_) -> {
return Component.translatable("argument.block.id.invalid", p_116790_);
});
public static final Dynamic2CommandExceptionType ERROR_UNKNOWN_PROPERTY = new Dynamic2CommandExceptionType((p_116820_, p_116821_) -> {
return Component.translatable("argument.block.property.unknown", p_116820_, p_116821_);
});
public static final Dynamic2CommandExceptionType ERROR_DUPLICATE_PROPERTY = new Dynamic2CommandExceptionType((p_116813_, p_116814_) -> {
return Component.translatable("argument.block.property.duplicate", p_116814_, p_116813_);
});
public static final Dynamic3CommandExceptionType ERROR_INVALID_VALUE = new Dynamic3CommandExceptionType((p_116795_, p_116796_, p_116797_) -> {
return Component.translatable("argument.block.property.invalid", p_116795_, p_116797_, p_116796_);
});
public static final Dynamic2CommandExceptionType ERROR_EXPECTED_VALUE = new Dynamic2CommandExceptionType((p_116792_, p_116793_) -> {
return Component.translatable("argument.block.property.novalue", p_116792_, p_116793_);
});
public static final SimpleCommandExceptionType ERROR_EXPECTED_END_OF_PROPERTIES = new SimpleCommandExceptionType(Component.translatable("argument.block.property.unclosed"));
public static final DynamicCommandExceptionType ERROR_UNKNOWN_TAG = new DynamicCommandExceptionType((p_234709_) -> {
return Component.translatable("arguments.block.tag.unknown", p_234709_);
});
private static final char SYNTAX_START_PROPERTIES = '[';
private static final char SYNTAX_START_NBT = '{';
private static final char SYNTAX_END_PROPERTIES = ']';
private static final char SYNTAX_EQUALS = '=';
private static final char SYNTAX_PROPERTY_SEPARATOR = ',';
private static final char SYNTAX_TAG = '#';
private static final Function<SuggestionsBuilder, CompletableFuture<Suggestions>> SUGGEST_NOTHING = SuggestionsBuilder::buildFuture;
private final HolderLookup<Block> blocks;
private final StringReader reader;
private final boolean forTesting;
private final boolean allowNbt;
private final Map<Property<?>, Comparable<?>> properties = Maps.newHashMap();
private final Map<String, String> vagueProperties = Maps.newHashMap();
private ResourceLocation id = new ResourceLocation("");
@Nullable
private StateDefinition<Block, BlockState> definition;
@Nullable
private BlockState state;
@Nullable
private CompoundTag nbt;
@Nullable
private HolderSet<Block> tag;
private Function<SuggestionsBuilder, CompletableFuture<Suggestions>> suggestions = SUGGEST_NOTHING;
private BlockStateParser(HolderLookup<Block> p_234673_, StringReader p_234674_, boolean p_234675_, boolean p_234676_) {
this.blocks = p_234673_;
this.reader = p_234674_;
this.forTesting = p_234675_;
this.allowNbt = p_234676_;
}
public static BlockStateParser.BlockResult parseForBlock(HolderLookup<Block> p_251394_, String p_248677_, boolean p_250430_) throws CommandSyntaxException {
return parseForBlock(p_251394_, new StringReader(p_248677_), p_250430_);
}
public static BlockStateParser.BlockResult parseForBlock(HolderLookup<Block> p_234692_, StringReader p_234693_, boolean p_234694_) throws CommandSyntaxException {
int i = p_234693_.getCursor();
try {
BlockStateParser blockstateparser = new BlockStateParser(p_234692_, p_234693_, false, p_234694_);
blockstateparser.parse();
return new BlockStateParser.BlockResult(blockstateparser.state, blockstateparser.properties, blockstateparser.nbt);
} catch (CommandSyntaxException commandsyntaxexception) {
p_234693_.setCursor(i);
throw commandsyntaxexception;
}
}
public static Either<BlockStateParser.BlockResult, BlockStateParser.TagResult> parseForTesting(HolderLookup<Block> p_252082_, String p_251830_, boolean p_249125_) throws CommandSyntaxException {
return parseForTesting(p_252082_, new StringReader(p_251830_), p_249125_);
}
public static Either<BlockStateParser.BlockResult, BlockStateParser.TagResult> parseForTesting(HolderLookup<Block> p_234717_, StringReader p_234718_, boolean p_234719_) throws CommandSyntaxException {
int i = p_234718_.getCursor();
try {
BlockStateParser blockstateparser = new BlockStateParser(p_234717_, p_234718_, true, p_234719_);
blockstateparser.parse();
return blockstateparser.tag != null ? Either.right(new BlockStateParser.TagResult(blockstateparser.tag, blockstateparser.vagueProperties, blockstateparser.nbt)) : Either.left(new BlockStateParser.BlockResult(blockstateparser.state, blockstateparser.properties, blockstateparser.nbt));
} catch (CommandSyntaxException commandsyntaxexception) {
p_234718_.setCursor(i);
throw commandsyntaxexception;
}
}
public static CompletableFuture<Suggestions> fillSuggestions(HolderLookup<Block> p_234696_, SuggestionsBuilder p_234697_, boolean p_234698_, boolean p_234699_) {
StringReader stringreader = new StringReader(p_234697_.getInput());
stringreader.setCursor(p_234697_.getStart());
BlockStateParser blockstateparser = new BlockStateParser(p_234696_, stringreader, p_234698_, p_234699_);
try {
blockstateparser.parse();
} catch (CommandSyntaxException commandsyntaxexception) {
}
return blockstateparser.suggestions.apply(p_234697_.createOffset(stringreader.getCursor()));
}
private void parse() throws CommandSyntaxException {
if (this.forTesting) {
this.suggestions = this::suggestBlockIdOrTag;
} else {
this.suggestions = this::suggestItem;
}
if (this.reader.canRead() && this.reader.peek() == '#') {
this.readTag();
this.suggestions = this::suggestOpenVaguePropertiesOrNbt;
if (this.reader.canRead() && this.reader.peek() == '[') {
this.readVagueProperties();
this.suggestions = this::suggestOpenNbt;
}
} else {
this.readBlock();
this.suggestions = this::suggestOpenPropertiesOrNbt;
if (this.reader.canRead() && this.reader.peek() == '[') {
this.readProperties();
this.suggestions = this::suggestOpenNbt;
}
}
if (this.allowNbt && this.reader.canRead() && this.reader.peek() == '{') {
this.suggestions = SUGGEST_NOTHING;
this.readNbt();
}
}
private CompletableFuture<Suggestions> suggestPropertyNameOrEnd(SuggestionsBuilder p_234684_) {
if (p_234684_.getRemaining().isEmpty()) {
p_234684_.suggest(String.valueOf(']'));
}
return this.suggestPropertyName(p_234684_);
}
private CompletableFuture<Suggestions> suggestVaguePropertyNameOrEnd(SuggestionsBuilder p_234715_) {
if (p_234715_.getRemaining().isEmpty()) {
p_234715_.suggest(String.valueOf(']'));
}
return this.suggestVaguePropertyName(p_234715_);
}
private CompletableFuture<Suggestions> suggestPropertyName(SuggestionsBuilder p_234729_) {
String s = p_234729_.getRemaining().toLowerCase(Locale.ROOT);
for(Property<?> property : this.state.getProperties()) {
if (!this.properties.containsKey(property) && property.getName().startsWith(s)) {
p_234729_.suggest(property.getName() + "=");
}
}
return p_234729_.buildFuture();
}
private CompletableFuture<Suggestions> suggestVaguePropertyName(SuggestionsBuilder p_234731_) {
String s = p_234731_.getRemaining().toLowerCase(Locale.ROOT);
if (this.tag != null) {
for(Holder<Block> holder : this.tag) {
for(Property<?> property : holder.value().getStateDefinition().getProperties()) {
if (!this.vagueProperties.containsKey(property.getName()) && property.getName().startsWith(s)) {
p_234731_.suggest(property.getName() + "=");
}
}
}
}
return p_234731_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOpenNbt(SuggestionsBuilder p_234733_) {
if (p_234733_.getRemaining().isEmpty() && this.hasBlockEntity()) {
p_234733_.suggest(String.valueOf('{'));
}
return p_234733_.buildFuture();
}
private boolean hasBlockEntity() {
if (this.state != null) {
return this.state.hasBlockEntity();
} else {
if (this.tag != null) {
for(Holder<Block> holder : this.tag) {
if (holder.value().defaultBlockState().hasBlockEntity()) {
return true;
}
}
}
return false;
}
}
private CompletableFuture<Suggestions> suggestEquals(SuggestionsBuilder p_234735_) {
if (p_234735_.getRemaining().isEmpty()) {
p_234735_.suggest(String.valueOf('='));
}
return p_234735_.buildFuture();
}
private CompletableFuture<Suggestions> suggestNextPropertyOrEnd(SuggestionsBuilder p_234737_) {
if (p_234737_.getRemaining().isEmpty()) {
p_234737_.suggest(String.valueOf(']'));
}
if (p_234737_.getRemaining().isEmpty() && this.properties.size() < this.state.getProperties().size()) {
p_234737_.suggest(String.valueOf(','));
}
return p_234737_.buildFuture();
}
private static <T extends Comparable<T>> SuggestionsBuilder addSuggestions(SuggestionsBuilder p_116787_, Property<T> p_116788_) {
for(T t : p_116788_.getPossibleValues()) {
if (t instanceof Integer integer) {
p_116787_.suggest(integer);
} else {
p_116787_.suggest(p_116788_.getName(t));
}
}
return p_116787_;
}
private CompletableFuture<Suggestions> suggestVaguePropertyValue(SuggestionsBuilder p_234686_, String p_234687_) {
boolean flag = false;
if (this.tag != null) {
for(Holder<Block> holder : this.tag) {
Block block = holder.value();
Property<?> property = block.getStateDefinition().getProperty(p_234687_);
if (property != null) {
addSuggestions(p_234686_, property);
}
if (!flag) {
for(Property<?> property1 : block.getStateDefinition().getProperties()) {
if (!this.vagueProperties.containsKey(property1.getName())) {
flag = true;
break;
}
}
}
}
}
if (flag) {
p_234686_.suggest(String.valueOf(','));
}
p_234686_.suggest(String.valueOf(']'));
return p_234686_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOpenVaguePropertiesOrNbt(SuggestionsBuilder p_234739_) {
if (p_234739_.getRemaining().isEmpty() && this.tag != null) {
boolean flag = false;
boolean flag1 = false;
for(Holder<Block> holder : this.tag) {
Block block = holder.value();
flag |= !block.getStateDefinition().getProperties().isEmpty();
flag1 |= block.defaultBlockState().hasBlockEntity();
if (flag && flag1) {
break;
}
}
if (flag) {
p_234739_.suggest(String.valueOf('['));
}
if (flag1) {
p_234739_.suggest(String.valueOf('{'));
}
}
return p_234739_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOpenPropertiesOrNbt(SuggestionsBuilder p_234741_) {
if (p_234741_.getRemaining().isEmpty()) {
if (!this.definition.getProperties().isEmpty()) {
p_234741_.suggest(String.valueOf('['));
}
if (this.state.hasBlockEntity()) {
p_234741_.suggest(String.valueOf('{'));
}
}
return p_234741_.buildFuture();
}
private CompletableFuture<Suggestions> suggestTag(SuggestionsBuilder p_234743_) {
return SharedSuggestionProvider.suggestResource(this.blocks.listTagIds().map(TagKey::location), p_234743_, String.valueOf('#'));
}
private CompletableFuture<Suggestions> suggestItem(SuggestionsBuilder p_234745_) {
return SharedSuggestionProvider.suggestResource(this.blocks.listElementIds().map(ResourceKey::location), p_234745_);
}
private CompletableFuture<Suggestions> suggestBlockIdOrTag(SuggestionsBuilder p_234747_) {
this.suggestTag(p_234747_);
this.suggestItem(p_234747_);
return p_234747_.buildFuture();
}
private void readBlock() throws CommandSyntaxException {
int i = this.reader.getCursor();
this.id = ResourceLocation.read(this.reader);
Block block = this.blocks.get(ResourceKey.create(Registries.BLOCK, this.id)).orElseThrow(() -> {
this.reader.setCursor(i);
return ERROR_UNKNOWN_BLOCK.createWithContext(this.reader, this.id.toString());
}).value();
this.definition = block.getStateDefinition();
this.state = block.defaultBlockState();
}
private void readTag() throws CommandSyntaxException {
if (!this.forTesting) {
throw ERROR_NO_TAGS_ALLOWED.createWithContext(this.reader);
} else {
int i = this.reader.getCursor();
this.reader.expect('#');
this.suggestions = this::suggestTag;
ResourceLocation resourcelocation = ResourceLocation.read(this.reader);
this.tag = this.blocks.get(TagKey.create(Registries.BLOCK, resourcelocation)).orElseThrow(() -> {
this.reader.setCursor(i);
return ERROR_UNKNOWN_TAG.createWithContext(this.reader, resourcelocation.toString());
});
}
}
private void readProperties() throws CommandSyntaxException {
this.reader.skip();
this.suggestions = this::suggestPropertyNameOrEnd;
this.reader.skipWhitespace();
while(true) {
if (this.reader.canRead() && this.reader.peek() != ']') {
this.reader.skipWhitespace();
int i = this.reader.getCursor();
String s = this.reader.readString();
Property<?> property = this.definition.getProperty(s);
if (property == null) {
this.reader.setCursor(i);
throw ERROR_UNKNOWN_PROPERTY.createWithContext(this.reader, this.id.toString(), s);
}
if (this.properties.containsKey(property)) {
this.reader.setCursor(i);
throw ERROR_DUPLICATE_PROPERTY.createWithContext(this.reader, this.id.toString(), s);
}
this.reader.skipWhitespace();
this.suggestions = this::suggestEquals;
if (!this.reader.canRead() || this.reader.peek() != '=') {
throw ERROR_EXPECTED_VALUE.createWithContext(this.reader, this.id.toString(), s);
}
this.reader.skip();
this.reader.skipWhitespace();
this.suggestions = (p_234690_) -> {
return addSuggestions(p_234690_, property).buildFuture();
};
int j = this.reader.getCursor();
this.setValue(property, this.reader.readString(), j);
this.suggestions = this::suggestNextPropertyOrEnd;
this.reader.skipWhitespace();
if (!this.reader.canRead()) {
continue;
}
if (this.reader.peek() == ',') {
this.reader.skip();
this.suggestions = this::suggestPropertyName;
continue;
}
if (this.reader.peek() != ']') {
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
}
}
if (this.reader.canRead()) {
this.reader.skip();
return;
}
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
}
}
private void readVagueProperties() throws CommandSyntaxException {
this.reader.skip();
this.suggestions = this::suggestVaguePropertyNameOrEnd;
int i = -1;
this.reader.skipWhitespace();
while(true) {
if (this.reader.canRead() && this.reader.peek() != ']') {
this.reader.skipWhitespace();
int j = this.reader.getCursor();
String s = this.reader.readString();
if (this.vagueProperties.containsKey(s)) {
this.reader.setCursor(j);
throw ERROR_DUPLICATE_PROPERTY.createWithContext(this.reader, this.id.toString(), s);
}
this.reader.skipWhitespace();
if (!this.reader.canRead() || this.reader.peek() != '=') {
this.reader.setCursor(j);
throw ERROR_EXPECTED_VALUE.createWithContext(this.reader, this.id.toString(), s);
}
this.reader.skip();
this.reader.skipWhitespace();
this.suggestions = (p_234712_) -> {
return this.suggestVaguePropertyValue(p_234712_, s);
};
i = this.reader.getCursor();
String s1 = this.reader.readString();
this.vagueProperties.put(s, s1);
this.reader.skipWhitespace();
if (!this.reader.canRead()) {
continue;
}
i = -1;
if (this.reader.peek() == ',') {
this.reader.skip();
this.suggestions = this::suggestVaguePropertyName;
continue;
}
if (this.reader.peek() != ']') {
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
}
}
if (this.reader.canRead()) {
this.reader.skip();
return;
}
if (i >= 0) {
this.reader.setCursor(i);
}
throw ERROR_EXPECTED_END_OF_PROPERTIES.createWithContext(this.reader);
}
}
private void readNbt() throws CommandSyntaxException {
this.nbt = (new TagParser(this.reader)).readStruct();
}
private <T extends Comparable<T>> void setValue(Property<T> p_116776_, String p_116777_, int p_116778_) throws CommandSyntaxException {
Optional<T> optional = p_116776_.getValue(p_116777_);
if (optional.isPresent()) {
this.state = this.state.setValue(p_116776_, optional.get());
this.properties.put(p_116776_, optional.get());
} else {
this.reader.setCursor(p_116778_);
throw ERROR_INVALID_VALUE.createWithContext(this.reader, this.id.toString(), p_116776_.getName(), p_116777_);
}
}
public static String serialize(BlockState p_116770_) {
StringBuilder stringbuilder = new StringBuilder(p_116770_.getBlockHolder().unwrapKey().map((p_234682_) -> {
return p_234682_.location().toString();
}).orElse("air"));
if (!p_116770_.getProperties().isEmpty()) {
stringbuilder.append('[');
boolean flag = false;
for(Map.Entry<Property<?>, Comparable<?>> entry : p_116770_.getValues().entrySet()) {
if (flag) {
stringbuilder.append(',');
}
appendProperty(stringbuilder, entry.getKey(), entry.getValue());
flag = true;
}
stringbuilder.append(']');
}
return stringbuilder.toString();
}
private static <T extends Comparable<T>> void appendProperty(StringBuilder p_116803_, Property<T> p_116804_, Comparable<?> p_116805_) {
p_116803_.append(p_116804_.getName());
p_116803_.append('=');
p_116803_.append(p_116804_.getName((T)p_116805_));
}
public static record BlockResult(BlockState blockState, Map<Property<?>, Comparable<?>> properties, @Nullable CompoundTag nbt) {
}
public static record TagResult(HolderSet<Block> tag, Map<String, String> vagueProperties, @Nullable CompoundTag nbt) {
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.arguments.blocks;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,84 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
public class BlockPosArgument implements ArgumentType<Coordinates> {
private static final Collection<String> EXAMPLES = Arrays.asList("0 0 0", "~ ~ ~", "^ ^ ^", "^1 ^ ^-5", "~0.5 ~1 ~-5");
public static final SimpleCommandExceptionType ERROR_NOT_LOADED = new SimpleCommandExceptionType(Component.translatable("argument.pos.unloaded"));
public static final SimpleCommandExceptionType ERROR_OUT_OF_WORLD = new SimpleCommandExceptionType(Component.translatable("argument.pos.outofworld"));
public static final SimpleCommandExceptionType ERROR_OUT_OF_BOUNDS = new SimpleCommandExceptionType(Component.translatable("argument.pos.outofbounds"));
public static BlockPosArgument blockPos() {
return new BlockPosArgument();
}
public static BlockPos getLoadedBlockPos(CommandContext<CommandSourceStack> p_118243_, String p_118244_) throws CommandSyntaxException {
ServerLevel serverlevel = p_118243_.getSource().getLevel();
return getLoadedBlockPos(p_118243_, serverlevel, p_118244_);
}
public static BlockPos getLoadedBlockPos(CommandContext<CommandSourceStack> p_265283_, ServerLevel p_265219_, String p_265677_) throws CommandSyntaxException {
BlockPos blockpos = getBlockPos(p_265283_, p_265677_);
if (!p_265283_.getSource().getUnsidedLevel().hasChunkAt(blockpos)) {
throw ERROR_NOT_LOADED.create();
} else if (!p_265283_.getSource().getUnsidedLevel().isInWorldBounds(blockpos)) {
throw ERROR_OUT_OF_WORLD.create();
} else {
return blockpos;
}
}
public static BlockPos getBlockPos(CommandContext<CommandSourceStack> p_265651_, String p_265039_) {
return p_265651_.getArgument(p_265039_, Coordinates.class).getBlockPos(p_265651_.getSource());
}
public static BlockPos getSpawnablePos(CommandContext<CommandSourceStack> p_174396_, String p_174397_) throws CommandSyntaxException {
BlockPos blockpos = getBlockPos(p_174396_, p_174397_);
if (!Level.isInSpawnableBounds(blockpos)) {
throw ERROR_OUT_OF_BOUNDS.create();
} else {
return blockpos;
}
}
public Coordinates parse(StringReader p_118241_) throws CommandSyntaxException {
return (Coordinates)(p_118241_.canRead() && p_118241_.peek() == '^' ? LocalCoordinates.parse(p_118241_) : WorldCoordinates.parseInt(p_118241_));
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_118250_, SuggestionsBuilder p_118251_) {
if (!(p_118250_.getSource() instanceof SharedSuggestionProvider)) {
return Suggestions.empty();
} else {
String s = p_118251_.getRemaining();
Collection<SharedSuggestionProvider.TextCoordinates> collection;
if (!s.isEmpty() && s.charAt(0) == '^') {
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
} else {
collection = ((SharedSuggestionProvider)p_118250_.getSource()).getRelevantCoordinates();
}
return SharedSuggestionProvider.suggestCoordinates(s, collection, p_118251_, Commands.createValidator(this::parse));
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,70 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ColumnPos;
public class ColumnPosArgument implements ArgumentType<Coordinates> {
private static final Collection<String> EXAMPLES = Arrays.asList("0 0", "~ ~", "~1 ~-2", "^ ^", "^-1 ^0");
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.pos2d.incomplete"));
public static ColumnPosArgument columnPos() {
return new ColumnPosArgument();
}
public static ColumnPos getColumnPos(CommandContext<CommandSourceStack> p_118993_, String p_118994_) {
BlockPos blockpos = p_118993_.getArgument(p_118994_, Coordinates.class).getBlockPos(p_118993_.getSource());
return new ColumnPos(blockpos.getX(), blockpos.getZ());
}
public Coordinates parse(StringReader p_118991_) throws CommandSyntaxException {
int i = p_118991_.getCursor();
if (!p_118991_.canRead()) {
throw ERROR_NOT_COMPLETE.createWithContext(p_118991_);
} else {
WorldCoordinate worldcoordinate = WorldCoordinate.parseInt(p_118991_);
if (p_118991_.canRead() && p_118991_.peek() == ' ') {
p_118991_.skip();
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseInt(p_118991_);
return new WorldCoordinates(worldcoordinate, new WorldCoordinate(true, 0.0D), worldcoordinate1);
} else {
p_118991_.setCursor(i);
throw ERROR_NOT_COMPLETE.createWithContext(p_118991_);
}
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_118997_, SuggestionsBuilder p_118998_) {
if (!(p_118997_.getSource() instanceof SharedSuggestionProvider)) {
return Suggestions.empty();
} else {
String s = p_118998_.getRemaining();
Collection<SharedSuggestionProvider.TextCoordinates> collection;
if (!s.isEmpty() && s.charAt(0) == '^') {
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
} else {
collection = ((SharedSuggestionProvider)p_118997_.getSource()).getRelevantCoordinates();
}
return SharedSuggestionProvider.suggest2DCoordinates(s, collection, p_118998_, Commands.createValidator(this::parse));
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,22 @@
package net.minecraft.commands.arguments.coordinates;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public interface Coordinates {
Vec3 getPosition(CommandSourceStack p_119566_);
Vec2 getRotation(CommandSourceStack p_119567_);
default BlockPos getBlockPos(CommandSourceStack p_119569_) {
return BlockPos.containing(this.getPosition(p_119569_));
}
boolean isXRelative();
boolean isYRelative();
boolean isZRelative();
}

View File

@@ -0,0 +1,103 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Objects;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public class LocalCoordinates implements Coordinates {
public static final char PREFIX_LOCAL_COORDINATE = '^';
private final double left;
private final double up;
private final double forwards;
public LocalCoordinates(double p_119902_, double p_119903_, double p_119904_) {
this.left = p_119902_;
this.up = p_119903_;
this.forwards = p_119904_;
}
public Vec3 getPosition(CommandSourceStack p_119912_) {
Vec2 vec2 = p_119912_.getRotation();
Vec3 vec3 = p_119912_.getAnchor().apply(p_119912_);
float f = Mth.cos((vec2.y + 90.0F) * ((float)Math.PI / 180F));
float f1 = Mth.sin((vec2.y + 90.0F) * ((float)Math.PI / 180F));
float f2 = Mth.cos(-vec2.x * ((float)Math.PI / 180F));
float f3 = Mth.sin(-vec2.x * ((float)Math.PI / 180F));
float f4 = Mth.cos((-vec2.x + 90.0F) * ((float)Math.PI / 180F));
float f5 = Mth.sin((-vec2.x + 90.0F) * ((float)Math.PI / 180F));
Vec3 vec31 = new Vec3((double)(f * f2), (double)f3, (double)(f1 * f2));
Vec3 vec32 = new Vec3((double)(f * f4), (double)f5, (double)(f1 * f4));
Vec3 vec33 = vec31.cross(vec32).scale(-1.0D);
double d0 = vec31.x * this.forwards + vec32.x * this.up + vec33.x * this.left;
double d1 = vec31.y * this.forwards + vec32.y * this.up + vec33.y * this.left;
double d2 = vec31.z * this.forwards + vec32.z * this.up + vec33.z * this.left;
return new Vec3(vec3.x + d0, vec3.y + d1, vec3.z + d2);
}
public Vec2 getRotation(CommandSourceStack p_119915_) {
return Vec2.ZERO;
}
public boolean isXRelative() {
return true;
}
public boolean isYRelative() {
return true;
}
public boolean isZRelative() {
return true;
}
public static LocalCoordinates parse(StringReader p_119907_) throws CommandSyntaxException {
int i = p_119907_.getCursor();
double d0 = readDouble(p_119907_, i);
if (p_119907_.canRead() && p_119907_.peek() == ' ') {
p_119907_.skip();
double d1 = readDouble(p_119907_, i);
if (p_119907_.canRead() && p_119907_.peek() == ' ') {
p_119907_.skip();
double d2 = readDouble(p_119907_, i);
return new LocalCoordinates(d0, d1, d2);
} else {
p_119907_.setCursor(i);
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(p_119907_);
}
} else {
p_119907_.setCursor(i);
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(p_119907_);
}
}
private static double readDouble(StringReader p_119909_, int p_119910_) throws CommandSyntaxException {
if (!p_119909_.canRead()) {
throw WorldCoordinate.ERROR_EXPECTED_DOUBLE.createWithContext(p_119909_);
} else if (p_119909_.peek() != '^') {
p_119909_.setCursor(p_119910_);
throw Vec3Argument.ERROR_MIXED_TYPE.createWithContext(p_119909_);
} else {
p_119909_.skip();
return p_119909_.canRead() && p_119909_.peek() != ' ' ? p_119909_.readDouble() : 0.0D;
}
}
public boolean equals(Object p_119918_) {
if (this == p_119918_) {
return true;
} else if (!(p_119918_ instanceof LocalCoordinates)) {
return false;
} else {
LocalCoordinates localcoordinates = (LocalCoordinates)p_119918_;
return this.left == localcoordinates.left && this.up == localcoordinates.up && this.forwards == localcoordinates.forwards;
}
}
public int hashCode() {
return Objects.hash(this.left, this.up, this.forwards);
}
}

View File

@@ -0,0 +1,45 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Arrays;
import java.util.Collection;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
public class RotationArgument implements ArgumentType<Coordinates> {
private static final Collection<String> EXAMPLES = Arrays.asList("0 0", "~ ~", "~-5 ~5");
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.rotation.incomplete"));
public static RotationArgument rotation() {
return new RotationArgument();
}
public static Coordinates getRotation(CommandContext<CommandSourceStack> p_120483_, String p_120484_) {
return p_120483_.getArgument(p_120484_, Coordinates.class);
}
public Coordinates parse(StringReader p_120481_) throws CommandSyntaxException {
int i = p_120481_.getCursor();
if (!p_120481_.canRead()) {
throw ERROR_NOT_COMPLETE.createWithContext(p_120481_);
} else {
WorldCoordinate worldcoordinate = WorldCoordinate.parseDouble(p_120481_, false);
if (p_120481_.canRead() && p_120481_.peek() == ' ') {
p_120481_.skip();
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseDouble(p_120481_, false);
return new WorldCoordinates(worldcoordinate1, worldcoordinate, new WorldCoordinate(true, 0.0D));
} else {
p_120481_.setCursor(i);
throw ERROR_NOT_COMPLETE.createWithContext(p_120481_);
}
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,60 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
public class SwizzleArgument implements ArgumentType<EnumSet<Direction.Axis>> {
private static final Collection<String> EXAMPLES = Arrays.asList("xyz", "x");
private static final SimpleCommandExceptionType ERROR_INVALID = new SimpleCommandExceptionType(Component.translatable("arguments.swizzle.invalid"));
public static SwizzleArgument swizzle() {
return new SwizzleArgument();
}
public static EnumSet<Direction.Axis> getSwizzle(CommandContext<CommandSourceStack> p_120811_, String p_120812_) {
return p_120811_.getArgument(p_120812_, EnumSet.class);
}
public EnumSet<Direction.Axis> parse(StringReader p_120809_) throws CommandSyntaxException {
EnumSet<Direction.Axis> enumset = EnumSet.noneOf(Direction.Axis.class);
while(p_120809_.canRead() && p_120809_.peek() != ' ') {
char c0 = p_120809_.read();
Direction.Axis direction$axis;
switch (c0) {
case 'x':
direction$axis = Direction.Axis.X;
break;
case 'y':
direction$axis = Direction.Axis.Y;
break;
case 'z':
direction$axis = Direction.Axis.Z;
break;
default:
throw ERROR_INVALID.create();
}
if (enumset.contains(direction$axis)) {
throw ERROR_INVALID.create();
}
enumset.add(direction$axis);
}
return enumset;
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,79 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public class Vec2Argument implements ArgumentType<Coordinates> {
private static final Collection<String> EXAMPLES = Arrays.asList("0 0", "~ ~", "0.1 -0.5", "~1 ~-2");
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.pos2d.incomplete"));
private final boolean centerCorrect;
public Vec2Argument(boolean p_120821_) {
this.centerCorrect = p_120821_;
}
public static Vec2Argument vec2() {
return new Vec2Argument(true);
}
public static Vec2Argument vec2(boolean p_174955_) {
return new Vec2Argument(p_174955_);
}
public static Vec2 getVec2(CommandContext<CommandSourceStack> p_120826_, String p_120827_) {
Vec3 vec3 = p_120826_.getArgument(p_120827_, Coordinates.class).getPosition(p_120826_.getSource());
return new Vec2((float)vec3.x, (float)vec3.z);
}
public Coordinates parse(StringReader p_120824_) throws CommandSyntaxException {
int i = p_120824_.getCursor();
if (!p_120824_.canRead()) {
throw ERROR_NOT_COMPLETE.createWithContext(p_120824_);
} else {
WorldCoordinate worldcoordinate = WorldCoordinate.parseDouble(p_120824_, this.centerCorrect);
if (p_120824_.canRead() && p_120824_.peek() == ' ') {
p_120824_.skip();
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseDouble(p_120824_, this.centerCorrect);
return new WorldCoordinates(worldcoordinate, new WorldCoordinate(true, 0.0D), worldcoordinate1);
} else {
p_120824_.setCursor(i);
throw ERROR_NOT_COMPLETE.createWithContext(p_120824_);
}
}
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_120830_, SuggestionsBuilder p_120831_) {
if (!(p_120830_.getSource() instanceof SharedSuggestionProvider)) {
return Suggestions.empty();
} else {
String s = p_120831_.getRemaining();
Collection<SharedSuggestionProvider.TextCoordinates> collection;
if (!s.isEmpty() && s.charAt(0) == '^') {
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
} else {
collection = ((SharedSuggestionProvider)p_120830_.getSource()).getAbsoluteCoordinates();
}
return SharedSuggestionProvider.suggest2DCoordinates(s, collection, p_120831_, Commands.createValidator(this::parse));
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,69 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.world.phys.Vec3;
public class Vec3Argument implements ArgumentType<Coordinates> {
private static final Collection<String> EXAMPLES = Arrays.asList("0 0 0", "~ ~ ~", "^ ^ ^", "^1 ^ ^-5", "0.1 -0.5 .9", "~0.5 ~1 ~-5");
public static final SimpleCommandExceptionType ERROR_NOT_COMPLETE = new SimpleCommandExceptionType(Component.translatable("argument.pos3d.incomplete"));
public static final SimpleCommandExceptionType ERROR_MIXED_TYPE = new SimpleCommandExceptionType(Component.translatable("argument.pos.mixed"));
private final boolean centerCorrect;
public Vec3Argument(boolean p_120840_) {
this.centerCorrect = p_120840_;
}
public static Vec3Argument vec3() {
return new Vec3Argument(true);
}
public static Vec3Argument vec3(boolean p_120848_) {
return new Vec3Argument(p_120848_);
}
public static Vec3 getVec3(CommandContext<CommandSourceStack> p_120845_, String p_120846_) {
return p_120845_.getArgument(p_120846_, Coordinates.class).getPosition(p_120845_.getSource());
}
public static Coordinates getCoordinates(CommandContext<CommandSourceStack> p_120850_, String p_120851_) {
return p_120850_.getArgument(p_120851_, Coordinates.class);
}
public Coordinates parse(StringReader p_120843_) throws CommandSyntaxException {
return (Coordinates)(p_120843_.canRead() && p_120843_.peek() == '^' ? LocalCoordinates.parse(p_120843_) : WorldCoordinates.parseDouble(p_120843_, this.centerCorrect));
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_120854_, SuggestionsBuilder p_120855_) {
if (!(p_120854_.getSource() instanceof SharedSuggestionProvider)) {
return Suggestions.empty();
} else {
String s = p_120855_.getRemaining();
Collection<SharedSuggestionProvider.TextCoordinates> collection;
if (!s.isEmpty() && s.charAt(0) == '^') {
collection = Collections.singleton(SharedSuggestionProvider.TextCoordinates.DEFAULT_LOCAL);
} else {
collection = ((SharedSuggestionProvider)p_120854_.getSource()).getAbsoluteCoordinates();
}
return SharedSuggestionProvider.suggestCoordinates(s, collection, p_120855_, Commands.createValidator(this::parse));
}
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,100 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.network.chat.Component;
public class WorldCoordinate {
private static final char PREFIX_RELATIVE = '~';
public static final SimpleCommandExceptionType ERROR_EXPECTED_DOUBLE = new SimpleCommandExceptionType(Component.translatable("argument.pos.missing.double"));
public static final SimpleCommandExceptionType ERROR_EXPECTED_INT = new SimpleCommandExceptionType(Component.translatable("argument.pos.missing.int"));
private final boolean relative;
private final double value;
public WorldCoordinate(boolean p_120864_, double p_120865_) {
this.relative = p_120864_;
this.value = p_120865_;
}
public double get(double p_120868_) {
return this.relative ? this.value + p_120868_ : this.value;
}
public static WorldCoordinate parseDouble(StringReader p_120872_, boolean p_120873_) throws CommandSyntaxException {
if (p_120872_.canRead() && p_120872_.peek() == '^') {
throw Vec3Argument.ERROR_MIXED_TYPE.createWithContext(p_120872_);
} else if (!p_120872_.canRead()) {
throw ERROR_EXPECTED_DOUBLE.createWithContext(p_120872_);
} else {
boolean flag = isRelative(p_120872_);
int i = p_120872_.getCursor();
double d0 = p_120872_.canRead() && p_120872_.peek() != ' ' ? p_120872_.readDouble() : 0.0D;
String s = p_120872_.getString().substring(i, p_120872_.getCursor());
if (flag && s.isEmpty()) {
return new WorldCoordinate(true, 0.0D);
} else {
if (!s.contains(".") && !flag && p_120873_) {
d0 += 0.5D;
}
return new WorldCoordinate(flag, d0);
}
}
}
public static WorldCoordinate parseInt(StringReader p_120870_) throws CommandSyntaxException {
if (p_120870_.canRead() && p_120870_.peek() == '^') {
throw Vec3Argument.ERROR_MIXED_TYPE.createWithContext(p_120870_);
} else if (!p_120870_.canRead()) {
throw ERROR_EXPECTED_INT.createWithContext(p_120870_);
} else {
boolean flag = isRelative(p_120870_);
double d0;
if (p_120870_.canRead() && p_120870_.peek() != ' ') {
d0 = flag ? p_120870_.readDouble() : (double)p_120870_.readInt();
} else {
d0 = 0.0D;
}
return new WorldCoordinate(flag, d0);
}
}
public static boolean isRelative(StringReader p_120875_) {
boolean flag;
if (p_120875_.peek() == '~') {
flag = true;
p_120875_.skip();
} else {
flag = false;
}
return flag;
}
public boolean equals(Object p_120877_) {
if (this == p_120877_) {
return true;
} else if (!(p_120877_ instanceof WorldCoordinate)) {
return false;
} else {
WorldCoordinate worldcoordinate = (WorldCoordinate)p_120877_;
if (this.relative != worldcoordinate.relative) {
return false;
} else {
return Double.compare(worldcoordinate.value, this.value) == 0;
}
}
}
public int hashCode() {
int i = this.relative ? 1 : 0;
long j = Double.doubleToLongBits(this.value);
return 31 * i + (int)(j ^ j >>> 32);
}
public boolean isRelative() {
return this.relative;
}
}

View File

@@ -0,0 +1,114 @@
package net.minecraft.commands.arguments.coordinates;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public class WorldCoordinates implements Coordinates {
private final WorldCoordinate x;
private final WorldCoordinate y;
private final WorldCoordinate z;
public WorldCoordinates(WorldCoordinate p_120883_, WorldCoordinate p_120884_, WorldCoordinate p_120885_) {
this.x = p_120883_;
this.y = p_120884_;
this.z = p_120885_;
}
public Vec3 getPosition(CommandSourceStack p_120893_) {
Vec3 vec3 = p_120893_.getPosition();
return new Vec3(this.x.get(vec3.x), this.y.get(vec3.y), this.z.get(vec3.z));
}
public Vec2 getRotation(CommandSourceStack p_120896_) {
Vec2 vec2 = p_120896_.getRotation();
return new Vec2((float)this.x.get((double)vec2.x), (float)this.y.get((double)vec2.y));
}
public boolean isXRelative() {
return this.x.isRelative();
}
public boolean isYRelative() {
return this.y.isRelative();
}
public boolean isZRelative() {
return this.z.isRelative();
}
public boolean equals(Object p_120900_) {
if (this == p_120900_) {
return true;
} else if (!(p_120900_ instanceof WorldCoordinates)) {
return false;
} else {
WorldCoordinates worldcoordinates = (WorldCoordinates)p_120900_;
if (!this.x.equals(worldcoordinates.x)) {
return false;
} else {
return !this.y.equals(worldcoordinates.y) ? false : this.z.equals(worldcoordinates.z);
}
}
}
public static WorldCoordinates parseInt(StringReader p_120888_) throws CommandSyntaxException {
int i = p_120888_.getCursor();
WorldCoordinate worldcoordinate = WorldCoordinate.parseInt(p_120888_);
if (p_120888_.canRead() && p_120888_.peek() == ' ') {
p_120888_.skip();
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseInt(p_120888_);
if (p_120888_.canRead() && p_120888_.peek() == ' ') {
p_120888_.skip();
WorldCoordinate worldcoordinate2 = WorldCoordinate.parseInt(p_120888_);
return new WorldCoordinates(worldcoordinate, worldcoordinate1, worldcoordinate2);
} else {
p_120888_.setCursor(i);
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(p_120888_);
}
} else {
p_120888_.setCursor(i);
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(p_120888_);
}
}
public static WorldCoordinates parseDouble(StringReader p_120890_, boolean p_120891_) throws CommandSyntaxException {
int i = p_120890_.getCursor();
WorldCoordinate worldcoordinate = WorldCoordinate.parseDouble(p_120890_, p_120891_);
if (p_120890_.canRead() && p_120890_.peek() == ' ') {
p_120890_.skip();
WorldCoordinate worldcoordinate1 = WorldCoordinate.parseDouble(p_120890_, false);
if (p_120890_.canRead() && p_120890_.peek() == ' ') {
p_120890_.skip();
WorldCoordinate worldcoordinate2 = WorldCoordinate.parseDouble(p_120890_, p_120891_);
return new WorldCoordinates(worldcoordinate, worldcoordinate1, worldcoordinate2);
} else {
p_120890_.setCursor(i);
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(p_120890_);
}
} else {
p_120890_.setCursor(i);
throw Vec3Argument.ERROR_NOT_COMPLETE.createWithContext(p_120890_);
}
}
public static WorldCoordinates absolute(double p_175086_, double p_175087_, double p_175088_) {
return new WorldCoordinates(new WorldCoordinate(false, p_175086_), new WorldCoordinate(false, p_175087_), new WorldCoordinate(false, p_175088_));
}
public static WorldCoordinates absolute(Vec2 p_175090_) {
return new WorldCoordinates(new WorldCoordinate(false, (double)p_175090_.x), new WorldCoordinate(false, (double)p_175090_.y), new WorldCoordinate(true, 0.0D));
}
public static WorldCoordinates current() {
return new WorldCoordinates(new WorldCoordinate(true, 0.0D), new WorldCoordinate(true, 0.0D), new WorldCoordinate(true, 0.0D));
}
public int hashCode() {
int i = this.x.hashCode();
i = 31 * i + this.y.hashCode();
return 31 * i + this.z.hashCode();
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.arguments.coordinates;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,90 @@
package net.minecraft.commands.arguments.item;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.datafixers.util.Either;
import com.mojang.datafixers.util.Pair;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import net.minecraft.commands.CommandFunction;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
public class FunctionArgument implements ArgumentType<FunctionArgument.Result> {
private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "#foo");
private static final DynamicCommandExceptionType ERROR_UNKNOWN_TAG = new DynamicCommandExceptionType((p_120927_) -> {
return Component.translatable("arguments.function.tag.unknown", p_120927_);
});
private static final DynamicCommandExceptionType ERROR_UNKNOWN_FUNCTION = new DynamicCommandExceptionType((p_120917_) -> {
return Component.translatable("arguments.function.unknown", p_120917_);
});
public static FunctionArgument functions() {
return new FunctionArgument();
}
public FunctionArgument.Result parse(StringReader p_120909_) throws CommandSyntaxException {
if (p_120909_.canRead() && p_120909_.peek() == '#') {
p_120909_.skip();
final ResourceLocation resourcelocation1 = ResourceLocation.read(p_120909_);
return new FunctionArgument.Result() {
public Collection<CommandFunction> create(CommandContext<CommandSourceStack> p_120943_) throws CommandSyntaxException {
return FunctionArgument.getFunctionTag(p_120943_, resourcelocation1);
}
public Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> unwrap(CommandContext<CommandSourceStack> p_120945_) throws CommandSyntaxException {
return Pair.of(resourcelocation1, Either.right(FunctionArgument.getFunctionTag(p_120945_, resourcelocation1)));
}
};
} else {
final ResourceLocation resourcelocation = ResourceLocation.read(p_120909_);
return new FunctionArgument.Result() {
public Collection<CommandFunction> create(CommandContext<CommandSourceStack> p_120952_) throws CommandSyntaxException {
return Collections.singleton(FunctionArgument.getFunction(p_120952_, resourcelocation));
}
public Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> unwrap(CommandContext<CommandSourceStack> p_120954_) throws CommandSyntaxException {
return Pair.of(resourcelocation, Either.left(FunctionArgument.getFunction(p_120954_, resourcelocation)));
}
};
}
}
static CommandFunction getFunction(CommandContext<CommandSourceStack> p_120929_, ResourceLocation p_120930_) throws CommandSyntaxException {
return p_120929_.getSource().getServer().getFunctions().get(p_120930_).orElseThrow(() -> {
return ERROR_UNKNOWN_FUNCTION.create(p_120930_.toString());
});
}
static Collection<CommandFunction> getFunctionTag(CommandContext<CommandSourceStack> p_235274_, ResourceLocation p_235275_) throws CommandSyntaxException {
Collection<CommandFunction> collection = p_235274_.getSource().getServer().getFunctions().getTag(p_235275_);
if (collection == null) {
throw ERROR_UNKNOWN_TAG.create(p_235275_.toString());
} else {
return collection;
}
}
public static Collection<CommandFunction> getFunctions(CommandContext<CommandSourceStack> p_120911_, String p_120912_) throws CommandSyntaxException {
return p_120911_.getArgument(p_120912_, FunctionArgument.Result.class).create(p_120911_);
}
public static Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> getFunctionOrTag(CommandContext<CommandSourceStack> p_120921_, String p_120922_) throws CommandSyntaxException {
return p_120921_.getArgument(p_120922_, FunctionArgument.Result.class).unwrap(p_120921_);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
public interface Result {
Collection<CommandFunction> create(CommandContext<CommandSourceStack> p_120955_) throws CommandSyntaxException;
Pair<ResourceLocation, Either<CommandFunction, Collection<CommandFunction>>> unwrap(CommandContext<CommandSourceStack> p_120956_) throws CommandSyntaxException;
}
}

View File

@@ -0,0 +1,45 @@
package net.minecraft.commands.arguments.item;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.item.Item;
public class ItemArgument implements ArgumentType<ItemInput> {
private static final Collection<String> EXAMPLES = Arrays.asList("stick", "minecraft:stick", "stick{foo=bar}");
private final HolderLookup<Item> items;
public ItemArgument(CommandBuildContext p_235278_) {
this.items = p_235278_.holderLookup(Registries.ITEM);
}
public static ItemArgument item(CommandBuildContext p_235280_) {
return new ItemArgument(p_235280_);
}
public ItemInput parse(StringReader p_120962_) throws CommandSyntaxException {
ItemParser.ItemResult itemparser$itemresult = ItemParser.parseForItem(this.items, p_120962_);
return new ItemInput(itemparser$itemresult.item(), itemparser$itemresult.nbt());
}
public static <S> ItemInput getItem(CommandContext<S> p_120964_, String p_120965_) {
return p_120964_.getArgument(p_120965_, ItemInput.class);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_120968_, SuggestionsBuilder p_120969_) {
return ItemParser.fillSuggestions(this.items, p_120969_, false);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View File

@@ -0,0 +1,63 @@
package net.minecraft.commands.arguments.item;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.core.Holder;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
public class ItemInput implements Predicate<ItemStack> {
private static final Dynamic2CommandExceptionType ERROR_STACK_TOO_BIG = new Dynamic2CommandExceptionType((p_120986_, p_120987_) -> {
return Component.translatable("arguments.item.overstacked", p_120986_, p_120987_);
});
private final Holder<Item> item;
@Nullable
private final CompoundTag tag;
public ItemInput(Holder<Item> p_235282_, @Nullable CompoundTag p_235283_) {
this.item = p_235282_;
this.tag = p_235283_;
}
public Item getItem() {
return this.item.value();
}
public boolean test(ItemStack p_120984_) {
return p_120984_.is(this.item) && NbtUtils.compareNbt(this.tag, p_120984_.getTag(), true);
}
public ItemStack createItemStack(int p_120981_, boolean p_120982_) throws CommandSyntaxException {
ItemStack itemstack = new ItemStack(this.item, p_120981_);
if (this.tag != null) {
itemstack.setTag(this.tag);
}
if (p_120982_ && p_120981_ > itemstack.getMaxStackSize()) {
throw ERROR_STACK_TOO_BIG.create(this.getItemName(), itemstack.getMaxStackSize());
} else {
return itemstack;
}
}
public String serialize() {
StringBuilder stringbuilder = new StringBuilder(this.getItemName());
if (this.tag != null) {
stringbuilder.append((Object)this.tag);
}
return stringbuilder.toString();
}
private String getItemName() {
return this.item.unwrapKey().<Object>map(ResourceKey::location).orElseGet(() -> {
return "unknown[" + this.item + "]";
}).toString();
}
}

View File

@@ -0,0 +1,175 @@
package net.minecraft.commands.arguments.item;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.datafixers.util.Either;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import javax.annotation.Nullable;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
public class ItemParser {
private static final SimpleCommandExceptionType ERROR_NO_TAGS_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.item.tag.disallowed"));
private static final DynamicCommandExceptionType ERROR_UNKNOWN_ITEM = new DynamicCommandExceptionType((p_121013_) -> {
return Component.translatable("argument.item.id.invalid", p_121013_);
});
private static final DynamicCommandExceptionType ERROR_UNKNOWN_TAG = new DynamicCommandExceptionType((p_235313_) -> {
return Component.translatable("arguments.item.tag.unknown", p_235313_);
});
private static final char SYNTAX_START_NBT = '{';
private static final char SYNTAX_TAG = '#';
private static final Function<SuggestionsBuilder, CompletableFuture<Suggestions>> SUGGEST_NOTHING = SuggestionsBuilder::buildFuture;
private final HolderLookup<Item> items;
private final StringReader reader;
private final boolean allowTags;
private Either<Holder<Item>, HolderSet<Item>> result;
@Nullable
private CompoundTag nbt;
private Function<SuggestionsBuilder, CompletableFuture<Suggestions>> suggestions = SUGGEST_NOTHING;
private ItemParser(HolderLookup<Item> p_235291_, StringReader p_235292_, boolean p_235293_) {
this.items = p_235291_;
this.reader = p_235292_;
this.allowTags = p_235293_;
}
public static ItemParser.ItemResult parseForItem(HolderLookup<Item> p_235306_, StringReader p_235307_) throws CommandSyntaxException {
int i = p_235307_.getCursor();
try {
ItemParser itemparser = new ItemParser(p_235306_, p_235307_, false);
itemparser.parse();
Holder<Item> holder = itemparser.result.left().orElseThrow(() -> {
return new IllegalStateException("Parser returned unexpected tag name");
});
return new ItemParser.ItemResult(holder, itemparser.nbt);
} catch (CommandSyntaxException commandsyntaxexception) {
p_235307_.setCursor(i);
throw commandsyntaxexception;
}
}
public static Either<ItemParser.ItemResult, ItemParser.TagResult> parseForTesting(HolderLookup<Item> p_235320_, StringReader p_235321_) throws CommandSyntaxException {
int i = p_235321_.getCursor();
try {
ItemParser itemparser = new ItemParser(p_235320_, p_235321_, true);
itemparser.parse();
return itemparser.result.mapBoth((p_235301_) -> {
return new ItemParser.ItemResult(p_235301_, itemparser.nbt);
}, (p_235304_) -> {
return new ItemParser.TagResult(p_235304_, itemparser.nbt);
});
} catch (CommandSyntaxException commandsyntaxexception) {
p_235321_.setCursor(i);
throw commandsyntaxexception;
}
}
public static CompletableFuture<Suggestions> fillSuggestions(HolderLookup<Item> p_235309_, SuggestionsBuilder p_235310_, boolean p_235311_) {
StringReader stringreader = new StringReader(p_235310_.getInput());
stringreader.setCursor(p_235310_.getStart());
ItemParser itemparser = new ItemParser(p_235309_, stringreader, p_235311_);
try {
itemparser.parse();
} catch (CommandSyntaxException commandsyntaxexception) {
}
return itemparser.suggestions.apply(p_235310_.createOffset(stringreader.getCursor()));
}
private void readItem() throws CommandSyntaxException {
int i = this.reader.getCursor();
ResourceLocation resourcelocation = ResourceLocation.read(this.reader);
Optional<? extends Holder<Item>> optional = this.items.get(ResourceKey.create(Registries.ITEM, resourcelocation));
this.result = Either.left(optional.orElseThrow(() -> {
this.reader.setCursor(i);
return ERROR_UNKNOWN_ITEM.createWithContext(this.reader, resourcelocation);
}));
}
private void readTag() throws CommandSyntaxException {
if (!this.allowTags) {
throw ERROR_NO_TAGS_ALLOWED.createWithContext(this.reader);
} else {
int i = this.reader.getCursor();
this.reader.expect('#');
this.suggestions = this::suggestTag;
ResourceLocation resourcelocation = ResourceLocation.read(this.reader);
Optional<? extends HolderSet<Item>> optional = this.items.get(TagKey.create(Registries.ITEM, resourcelocation));
this.result = Either.right(optional.orElseThrow(() -> {
this.reader.setCursor(i);
return ERROR_UNKNOWN_TAG.createWithContext(this.reader, resourcelocation);
}));
}
}
private void readNbt() throws CommandSyntaxException {
this.nbt = (new TagParser(this.reader)).readStruct();
}
private void parse() throws CommandSyntaxException {
if (this.allowTags) {
this.suggestions = this::suggestItemIdOrTag;
} else {
this.suggestions = this::suggestItem;
}
if (this.reader.canRead() && this.reader.peek() == '#') {
this.readTag();
} else {
this.readItem();
}
this.suggestions = this::suggestOpenNbt;
if (this.reader.canRead() && this.reader.peek() == '{') {
this.suggestions = SUGGEST_NOTHING;
this.readNbt();
}
}
private CompletableFuture<Suggestions> suggestOpenNbt(SuggestionsBuilder p_235298_) {
if (p_235298_.getRemaining().isEmpty()) {
p_235298_.suggest(String.valueOf('{'));
}
return p_235298_.buildFuture();
}
private CompletableFuture<Suggestions> suggestTag(SuggestionsBuilder p_235318_) {
return SharedSuggestionProvider.suggestResource(this.items.listTagIds().map(TagKey::location), p_235318_, String.valueOf('#'));
}
private CompletableFuture<Suggestions> suggestItem(SuggestionsBuilder p_235323_) {
return SharedSuggestionProvider.suggestResource(this.items.listElementIds().map(ResourceKey::location), p_235323_);
}
private CompletableFuture<Suggestions> suggestItemIdOrTag(SuggestionsBuilder p_235326_) {
this.suggestTag(p_235326_);
return this.suggestItem(p_235326_);
}
public static record ItemResult(Holder<Item> item, @Nullable CompoundTag nbt) {
}
public static record TagResult(HolderSet<Item> tag, @Nullable CompoundTag nbt) {
}
}

View File

@@ -0,0 +1,70 @@
package net.minecraft.commands.arguments.item;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mojang.datafixers.util.Either;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
public class ItemPredicateArgument implements ArgumentType<ItemPredicateArgument.Result> {
private static final Collection<String> EXAMPLES = Arrays.asList("stick", "minecraft:stick", "#stick", "#stick{foo=bar}");
private final HolderLookup<Item> items;
public ItemPredicateArgument(CommandBuildContext p_235352_) {
this.items = p_235352_.holderLookup(Registries.ITEM);
}
public static ItemPredicateArgument itemPredicate(CommandBuildContext p_235354_) {
return new ItemPredicateArgument(p_235354_);
}
public ItemPredicateArgument.Result parse(StringReader p_121039_) throws CommandSyntaxException {
Either<ItemParser.ItemResult, ItemParser.TagResult> either = ItemParser.parseForTesting(this.items, p_121039_);
return either.map((p_235356_) -> {
return createResult((p_235359_) -> {
return p_235359_ == p_235356_.item();
}, p_235356_.nbt());
}, (p_235361_) -> {
return createResult(p_235361_.tag()::contains, p_235361_.nbt());
});
}
public static Predicate<ItemStack> getItemPredicate(CommandContext<CommandSourceStack> p_121041_, String p_121042_) {
return p_121041_.getArgument(p_121042_, ItemPredicateArgument.Result.class);
}
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> p_121054_, SuggestionsBuilder p_121055_) {
return ItemParser.fillSuggestions(this.items, p_121055_, true);
}
public Collection<String> getExamples() {
return EXAMPLES;
}
private static ItemPredicateArgument.Result createResult(Predicate<Holder<Item>> p_235366_, @Nullable CompoundTag p_235367_) {
return p_235367_ != null ? (p_235371_) -> {
return p_235371_.is(p_235366_) && NbtUtils.compareNbt(p_235367_, p_235371_.getTag(), true);
} : (p_235364_) -> {
return p_235364_.is(p_235366_);
};
}
public interface Result extends Predicate<ItemStack> {
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.arguments.item;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.arguments;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,249 @@
package net.minecraft.commands.arguments.selector;
import com.google.common.collect.Lists;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
public class EntitySelector {
public static final int INFINITE = Integer.MAX_VALUE;
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_ARBITRARY = (p_261404_, p_261405_) -> {
};
private static final EntityTypeTest<Entity, ?> ANY_TYPE = new EntityTypeTest<Entity, Entity>() {
public Entity tryCast(Entity p_175109_) {
return p_175109_;
}
public Class<? extends Entity> getBaseClass() {
return Entity.class;
}
};
private final int maxResults;
private final boolean includesEntities;
private final boolean worldLimited;
private final Predicate<Entity> predicate;
private final MinMaxBounds.Doubles range;
private final Function<Vec3, Vec3> position;
@Nullable
private final AABB aabb;
private final BiConsumer<Vec3, List<? extends Entity>> order;
private final boolean currentEntity;
@Nullable
private final String playerName;
@Nullable
private final UUID entityUUID;
private final EntityTypeTest<Entity, ?> type;
private final boolean usesSelector;
public EntitySelector(int p_121125_, boolean p_121126_, boolean p_121127_, Predicate<Entity> p_121128_, MinMaxBounds.Doubles p_121129_, Function<Vec3, Vec3> p_121130_, @Nullable AABB p_121131_, BiConsumer<Vec3, List<? extends Entity>> p_121132_, boolean p_121133_, @Nullable String p_121134_, @Nullable UUID p_121135_, @Nullable EntityType<?> p_121136_, boolean p_121137_) {
this.maxResults = p_121125_;
this.includesEntities = p_121126_;
this.worldLimited = p_121127_;
this.predicate = p_121128_;
this.range = p_121129_;
this.position = p_121130_;
this.aabb = p_121131_;
this.order = p_121132_;
this.currentEntity = p_121133_;
this.playerName = p_121134_;
this.entityUUID = p_121135_;
this.type = (EntityTypeTest<Entity, ?>)(p_121136_ == null ? ANY_TYPE : p_121136_);
this.usesSelector = p_121137_;
}
public int getMaxResults() {
return this.maxResults;
}
public boolean includesEntities() {
return this.includesEntities;
}
public boolean isSelfSelector() {
return this.currentEntity;
}
public boolean isWorldLimited() {
return this.worldLimited;
}
public boolean usesSelector() {
return this.usesSelector;
}
private void checkPermissions(CommandSourceStack p_121169_) throws CommandSyntaxException {
if (this.usesSelector && !net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(p_121169_)) {
throw EntityArgument.ERROR_SELECTORS_NOT_ALLOWED.create();
}
}
public Entity findSingleEntity(CommandSourceStack p_121140_) throws CommandSyntaxException {
this.checkPermissions(p_121140_);
List<? extends Entity> list = this.findEntities(p_121140_);
if (list.isEmpty()) {
throw EntityArgument.NO_ENTITIES_FOUND.create();
} else if (list.size() > 1) {
throw EntityArgument.ERROR_NOT_SINGLE_ENTITY.create();
} else {
return list.get(0);
}
}
public List<? extends Entity> findEntities(CommandSourceStack p_121161_) throws CommandSyntaxException {
return this.findEntitiesRaw(p_121161_).stream().filter((p_247981_) -> {
return p_247981_.getType().isEnabled(p_121161_.enabledFeatures());
}).toList();
}
private List<? extends Entity> findEntitiesRaw(CommandSourceStack p_251934_) throws CommandSyntaxException {
this.checkPermissions(p_251934_);
if (!this.includesEntities) {
return this.findPlayers(p_251934_);
} else if (this.playerName != null) {
ServerPlayer serverplayer = p_251934_.getServer().getPlayerList().getPlayerByName(this.playerName);
return (List<? extends Entity>)(serverplayer == null ? Collections.emptyList() : Lists.newArrayList(serverplayer));
} else if (this.entityUUID != null) {
for(ServerLevel serverlevel1 : p_251934_.getServer().getAllLevels()) {
Entity entity = serverlevel1.getEntity(this.entityUUID);
if (entity != null) {
return Lists.newArrayList(entity);
}
}
return Collections.emptyList();
} else {
Vec3 vec3 = this.position.apply(p_251934_.getPosition());
Predicate<Entity> predicate = this.getPredicate(vec3);
if (this.currentEntity) {
return (List<? extends Entity>)(p_251934_.getEntity() != null && predicate.test(p_251934_.getEntity()) ? Lists.newArrayList(p_251934_.getEntity()) : Collections.emptyList());
} else {
List<Entity> list = Lists.newArrayList();
if (this.isWorldLimited()) {
this.addEntities(list, p_251934_.getLevel(), vec3, predicate);
} else {
for(ServerLevel serverlevel : p_251934_.getServer().getAllLevels()) {
this.addEntities(list, serverlevel, vec3, predicate);
}
}
return this.sortAndLimit(vec3, list);
}
}
}
private void addEntities(List<Entity> p_121155_, ServerLevel p_121156_, Vec3 p_121157_, Predicate<Entity> p_121158_) {
int i = this.getResultLimit();
if (p_121155_.size() < i) {
if (this.aabb != null) {
p_121156_.getEntities(this.type, this.aabb.move(p_121157_), p_121158_, p_121155_, i);
} else {
p_121156_.getEntities(this.type, p_121158_, p_121155_, i);
}
}
}
private int getResultLimit() {
return this.order == ORDER_ARBITRARY ? this.maxResults : Integer.MAX_VALUE;
}
public ServerPlayer findSinglePlayer(CommandSourceStack p_121164_) throws CommandSyntaxException {
this.checkPermissions(p_121164_);
List<ServerPlayer> list = this.findPlayers(p_121164_);
if (list.size() != 1) {
throw EntityArgument.NO_PLAYERS_FOUND.create();
} else {
return list.get(0);
}
}
public List<ServerPlayer> findPlayers(CommandSourceStack p_121167_) throws CommandSyntaxException {
this.checkPermissions(p_121167_);
if (this.playerName != null) {
ServerPlayer serverplayer2 = p_121167_.getServer().getPlayerList().getPlayerByName(this.playerName);
return (List<ServerPlayer>)(serverplayer2 == null ? Collections.emptyList() : Lists.newArrayList(serverplayer2));
} else if (this.entityUUID != null) {
ServerPlayer serverplayer1 = p_121167_.getServer().getPlayerList().getPlayer(this.entityUUID);
return (List<ServerPlayer>)(serverplayer1 == null ? Collections.emptyList() : Lists.newArrayList(serverplayer1));
} else {
Vec3 vec3 = this.position.apply(p_121167_.getPosition());
Predicate<Entity> predicate = this.getPredicate(vec3);
if (this.currentEntity) {
if (p_121167_.getEntity() instanceof ServerPlayer) {
ServerPlayer serverplayer3 = (ServerPlayer)p_121167_.getEntity();
if (predicate.test(serverplayer3)) {
return Lists.newArrayList(serverplayer3);
}
}
return Collections.emptyList();
} else {
int i = this.getResultLimit();
List<ServerPlayer> list;
if (this.isWorldLimited()) {
list = p_121167_.getLevel().getPlayers(predicate, i);
} else {
list = Lists.newArrayList();
for(ServerPlayer serverplayer : p_121167_.getServer().getPlayerList().getPlayers()) {
if (predicate.test(serverplayer)) {
list.add(serverplayer);
if (list.size() >= i) {
return list;
}
}
}
}
return this.sortAndLimit(vec3, list);
}
}
}
private Predicate<Entity> getPredicate(Vec3 p_121145_) {
Predicate<Entity> predicate = this.predicate;
if (this.aabb != null) {
AABB aabb = this.aabb.move(p_121145_);
predicate = predicate.and((p_121143_) -> {
return aabb.intersects(p_121143_.getBoundingBox());
});
}
if (!this.range.isAny()) {
predicate = predicate.and((p_121148_) -> {
return this.range.matchesSqr(p_121148_.distanceToSqr(p_121145_));
});
}
return predicate;
}
private <T extends Entity> List<T> sortAndLimit(Vec3 p_121150_, List<T> p_121151_) {
if (p_121151_.size() > 1) {
this.order.accept(p_121150_, p_121151_);
}
return p_121151_.subList(0, Math.min(this.maxResults, p_121151_.size()));
}
public static Component joinNames(List<? extends Entity> p_175104_) {
return ComponentUtils.formatList(p_175104_, Entity::getDisplayName);
}
}

View File

@@ -0,0 +1,639 @@
package net.minecraft.commands.arguments.selector;
import com.google.common.primitives.Doubles;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToDoubleFunction;
import javax.annotation.Nullable;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.advancements.critereon.WrappedMinMaxBounds;
import net.minecraft.commands.arguments.selector.options.EntitySelectorOptions;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
public class EntitySelectorParser {
public static final char SYNTAX_SELECTOR_START = '@';
private static final char SYNTAX_OPTIONS_START = '[';
private static final char SYNTAX_OPTIONS_END = ']';
public static final char SYNTAX_OPTIONS_KEY_VALUE_SEPARATOR = '=';
private static final char SYNTAX_OPTIONS_SEPARATOR = ',';
public static final char SYNTAX_NOT = '!';
public static final char SYNTAX_TAG = '#';
private static final char SELECTOR_NEAREST_PLAYER = 'p';
private static final char SELECTOR_ALL_PLAYERS = 'a';
private static final char SELECTOR_RANDOM_PLAYERS = 'r';
private static final char SELECTOR_CURRENT_ENTITY = 's';
private static final char SELECTOR_ALL_ENTITIES = 'e';
public static final SimpleCommandExceptionType ERROR_INVALID_NAME_OR_UUID = new SimpleCommandExceptionType(Component.translatable("argument.entity.invalid"));
public static final DynamicCommandExceptionType ERROR_UNKNOWN_SELECTOR_TYPE = new DynamicCommandExceptionType((p_121301_) -> {
return Component.translatable("argument.entity.selector.unknown", p_121301_);
});
public static final SimpleCommandExceptionType ERROR_SELECTORS_NOT_ALLOWED = new SimpleCommandExceptionType(Component.translatable("argument.entity.selector.not_allowed"));
public static final SimpleCommandExceptionType ERROR_MISSING_SELECTOR_TYPE = new SimpleCommandExceptionType(Component.translatable("argument.entity.selector.missing"));
public static final SimpleCommandExceptionType ERROR_EXPECTED_END_OF_OPTIONS = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.unterminated"));
public static final DynamicCommandExceptionType ERROR_EXPECTED_OPTION_VALUE = new DynamicCommandExceptionType((p_121267_) -> {
return Component.translatable("argument.entity.options.valueless", p_121267_);
});
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_NEAREST = (p_121313_, p_121314_) -> {
p_121314_.sort((p_175140_, p_175141_) -> {
return Doubles.compare(p_175140_.distanceToSqr(p_121313_), p_175141_.distanceToSqr(p_121313_));
});
};
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_FURTHEST = (p_121298_, p_121299_) -> {
p_121299_.sort((p_175131_, p_175132_) -> {
return Doubles.compare(p_175132_.distanceToSqr(p_121298_), p_175131_.distanceToSqr(p_121298_));
});
};
public static final BiConsumer<Vec3, List<? extends Entity>> ORDER_RANDOM = (p_121264_, p_121265_) -> {
Collections.shuffle(p_121265_);
};
public static final BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> SUGGEST_NOTHING = (p_121363_, p_121364_) -> {
return p_121363_.buildFuture();
};
private final StringReader reader;
private final boolean allowSelectors;
private int maxResults;
private boolean includesEntities;
private boolean worldLimited;
private MinMaxBounds.Doubles distance = MinMaxBounds.Doubles.ANY;
private MinMaxBounds.Ints level = MinMaxBounds.Ints.ANY;
@Nullable
private Double x;
@Nullable
private Double y;
@Nullable
private Double z;
@Nullable
private Double deltaX;
@Nullable
private Double deltaY;
@Nullable
private Double deltaZ;
private WrappedMinMaxBounds rotX = WrappedMinMaxBounds.ANY;
private WrappedMinMaxBounds rotY = WrappedMinMaxBounds.ANY;
private Predicate<Entity> predicate = (p_121321_) -> {
return true;
};
private BiConsumer<Vec3, List<? extends Entity>> order = EntitySelector.ORDER_ARBITRARY;
private boolean currentEntity;
@Nullable
private String playerName;
private int startPosition;
@Nullable
private UUID entityUUID;
private BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> suggestions = SUGGEST_NOTHING;
private boolean hasNameEquals;
private boolean hasNameNotEquals;
private boolean isLimited;
private boolean isSorted;
private boolean hasGamemodeEquals;
private boolean hasGamemodeNotEquals;
private boolean hasTeamEquals;
private boolean hasTeamNotEquals;
@Nullable
private EntityType<?> type;
private boolean typeInverse;
private boolean hasScores;
private boolean hasAdvancements;
private boolean usesSelectors;
public EntitySelectorParser(StringReader p_121218_) {
this(p_121218_, true);
}
public EntitySelectorParser(StringReader p_121220_, boolean p_121221_) {
this.reader = p_121220_;
this.allowSelectors = p_121221_;
}
public EntitySelector getSelector() {
AABB aabb;
if (this.deltaX == null && this.deltaY == null && this.deltaZ == null) {
if (this.distance.getMax() != null) {
double d0 = this.distance.getMax();
aabb = new AABB(-d0, -d0, -d0, d0 + 1.0D, d0 + 1.0D, d0 + 1.0D);
} else {
aabb = null;
}
} else {
aabb = this.createAabb(this.deltaX == null ? 0.0D : this.deltaX, this.deltaY == null ? 0.0D : this.deltaY, this.deltaZ == null ? 0.0D : this.deltaZ);
}
Function<Vec3, Vec3> function;
if (this.x == null && this.y == null && this.z == null) {
function = (p_121292_) -> {
return p_121292_;
};
} else {
function = (p_121258_) -> {
return new Vec3(this.x == null ? p_121258_.x : this.x, this.y == null ? p_121258_.y : this.y, this.z == null ? p_121258_.z : this.z);
};
}
return new EntitySelector(this.maxResults, this.includesEntities, this.worldLimited, this.predicate, this.distance, function, aabb, this.order, this.currentEntity, this.playerName, this.entityUUID, this.type, this.usesSelectors);
}
private AABB createAabb(double p_121234_, double p_121235_, double p_121236_) {
boolean flag = p_121234_ < 0.0D;
boolean flag1 = p_121235_ < 0.0D;
boolean flag2 = p_121236_ < 0.0D;
double d0 = flag ? p_121234_ : 0.0D;
double d1 = flag1 ? p_121235_ : 0.0D;
double d2 = flag2 ? p_121236_ : 0.0D;
double d3 = (flag ? 0.0D : p_121234_) + 1.0D;
double d4 = (flag1 ? 0.0D : p_121235_) + 1.0D;
double d5 = (flag2 ? 0.0D : p_121236_) + 1.0D;
return new AABB(d0, d1, d2, d3, d4, d5);
}
public void finalizePredicates() {
if (this.rotX != WrappedMinMaxBounds.ANY) {
this.predicate = this.predicate.and(this.createRotationPredicate(this.rotX, Entity::getXRot));
}
if (this.rotY != WrappedMinMaxBounds.ANY) {
this.predicate = this.predicate.and(this.createRotationPredicate(this.rotY, Entity::getYRot));
}
if (!this.level.isAny()) {
this.predicate = this.predicate.and((p_287322_) -> {
return !(p_287322_ instanceof ServerPlayer) ? false : this.level.matches(((ServerPlayer)p_287322_).experienceLevel);
});
}
}
private Predicate<Entity> createRotationPredicate(WrappedMinMaxBounds p_121255_, ToDoubleFunction<Entity> p_121256_) {
double d0 = (double)Mth.wrapDegrees(p_121255_.getMin() == null ? 0.0F : p_121255_.getMin());
double d1 = (double)Mth.wrapDegrees(p_121255_.getMax() == null ? 359.0F : p_121255_.getMax());
return (p_175137_) -> {
double d2 = Mth.wrapDegrees(p_121256_.applyAsDouble(p_175137_));
if (d0 > d1) {
return d2 >= d0 || d2 <= d1;
} else {
return d2 >= d0 && d2 <= d1;
}
};
}
protected void parseSelector() throws CommandSyntaxException {
this.usesSelectors = true;
this.suggestions = this::suggestSelector;
if (!this.reader.canRead()) {
throw ERROR_MISSING_SELECTOR_TYPE.createWithContext(this.reader);
} else {
int i = this.reader.getCursor();
char c0 = this.reader.read();
if (c0 == 'p') {
this.maxResults = 1;
this.includesEntities = false;
this.order = ORDER_NEAREST;
this.limitToType(EntityType.PLAYER);
} else if (c0 == 'a') {
this.maxResults = Integer.MAX_VALUE;
this.includesEntities = false;
this.order = EntitySelector.ORDER_ARBITRARY;
this.limitToType(EntityType.PLAYER);
} else if (c0 == 'r') {
this.maxResults = 1;
this.includesEntities = false;
this.order = ORDER_RANDOM;
this.limitToType(EntityType.PLAYER);
} else if (c0 == 's') {
this.maxResults = 1;
this.includesEntities = true;
this.currentEntity = true;
} else {
if (c0 != 'e') {
this.reader.setCursor(i);
throw ERROR_UNKNOWN_SELECTOR_TYPE.createWithContext(this.reader, "@" + String.valueOf(c0));
}
this.maxResults = Integer.MAX_VALUE;
this.includesEntities = true;
this.order = EntitySelector.ORDER_ARBITRARY;
this.predicate = Entity::isAlive;
}
this.suggestions = this::suggestOpenOptions;
if (this.reader.canRead() && this.reader.peek() == '[') {
this.reader.skip();
this.suggestions = this::suggestOptionsKeyOrClose;
this.parseOptions();
}
}
}
protected void parseNameOrUUID() throws CommandSyntaxException {
if (this.reader.canRead()) {
this.suggestions = this::suggestName;
}
int i = this.reader.getCursor();
String s = this.reader.readString();
try {
this.entityUUID = UUID.fromString(s);
this.includesEntities = true;
} catch (IllegalArgumentException illegalargumentexception) {
if (s.isEmpty() || s.length() > 16) {
this.reader.setCursor(i);
throw ERROR_INVALID_NAME_OR_UUID.createWithContext(this.reader);
}
this.includesEntities = false;
this.playerName = s;
}
this.maxResults = 1;
}
public void parseOptions() throws CommandSyntaxException {
this.suggestions = this::suggestOptionsKey;
this.reader.skipWhitespace();
while(true) {
if (this.reader.canRead() && this.reader.peek() != ']') {
this.reader.skipWhitespace();
int i = this.reader.getCursor();
String s = this.reader.readString();
EntitySelectorOptions.Modifier entityselectoroptions$modifier = EntitySelectorOptions.get(this, s, i);
this.reader.skipWhitespace();
if (!this.reader.canRead() || this.reader.peek() != '=') {
this.reader.setCursor(i);
throw ERROR_EXPECTED_OPTION_VALUE.createWithContext(this.reader, s);
}
this.reader.skip();
this.reader.skipWhitespace();
this.suggestions = SUGGEST_NOTHING;
entityselectoroptions$modifier.handle(this);
this.reader.skipWhitespace();
this.suggestions = this::suggestOptionsNextOrClose;
if (!this.reader.canRead()) {
continue;
}
if (this.reader.peek() == ',') {
this.reader.skip();
this.suggestions = this::suggestOptionsKey;
continue;
}
if (this.reader.peek() != ']') {
throw ERROR_EXPECTED_END_OF_OPTIONS.createWithContext(this.reader);
}
}
if (this.reader.canRead()) {
this.reader.skip();
this.suggestions = SUGGEST_NOTHING;
return;
}
throw ERROR_EXPECTED_END_OF_OPTIONS.createWithContext(this.reader);
}
}
public boolean shouldInvertValue() {
this.reader.skipWhitespace();
if (this.reader.canRead() && this.reader.peek() == '!') {
this.reader.skip();
this.reader.skipWhitespace();
return true;
} else {
return false;
}
}
public boolean isTag() {
this.reader.skipWhitespace();
if (this.reader.canRead() && this.reader.peek() == '#') {
this.reader.skip();
this.reader.skipWhitespace();
return true;
} else {
return false;
}
}
public StringReader getReader() {
return this.reader;
}
public void addPredicate(Predicate<Entity> p_121273_) {
this.predicate = this.predicate.and(p_121273_);
}
public void setWorldLimited() {
this.worldLimited = true;
}
public MinMaxBounds.Doubles getDistance() {
return this.distance;
}
public void setDistance(MinMaxBounds.Doubles p_175128_) {
this.distance = p_175128_;
}
public MinMaxBounds.Ints getLevel() {
return this.level;
}
public void setLevel(MinMaxBounds.Ints p_121246_) {
this.level = p_121246_;
}
public WrappedMinMaxBounds getRotX() {
return this.rotX;
}
public void setRotX(WrappedMinMaxBounds p_121253_) {
this.rotX = p_121253_;
}
public WrappedMinMaxBounds getRotY() {
return this.rotY;
}
public void setRotY(WrappedMinMaxBounds p_121290_) {
this.rotY = p_121290_;
}
@Nullable
public Double getX() {
return this.x;
}
@Nullable
public Double getY() {
return this.y;
}
@Nullable
public Double getZ() {
return this.z;
}
public void setX(double p_121232_) {
this.x = p_121232_;
}
public void setY(double p_121283_) {
this.y = p_121283_;
}
public void setZ(double p_121306_) {
this.z = p_121306_;
}
public void setDeltaX(double p_121319_) {
this.deltaX = p_121319_;
}
public void setDeltaY(double p_121332_) {
this.deltaY = p_121332_;
}
public void setDeltaZ(double p_121340_) {
this.deltaZ = p_121340_;
}
@Nullable
public Double getDeltaX() {
return this.deltaX;
}
@Nullable
public Double getDeltaY() {
return this.deltaY;
}
@Nullable
public Double getDeltaZ() {
return this.deltaZ;
}
public void setMaxResults(int p_121238_) {
this.maxResults = p_121238_;
}
public void setIncludesEntities(boolean p_121280_) {
this.includesEntities = p_121280_;
}
public BiConsumer<Vec3, List<? extends Entity>> getOrder() {
return this.order;
}
public void setOrder(BiConsumer<Vec3, List<? extends Entity>> p_121269_) {
this.order = p_121269_;
}
public EntitySelector parse() throws CommandSyntaxException {
this.startPosition = this.reader.getCursor();
this.suggestions = this::suggestNameOrSelector;
if (this.reader.canRead() && this.reader.peek() == '@') {
if (!this.allowSelectors) {
throw ERROR_SELECTORS_NOT_ALLOWED.createWithContext(this.reader);
}
this.reader.skip();
EntitySelector forgeSelector = net.minecraftforge.common.command.EntitySelectorManager.parseSelector(this);
if (forgeSelector != null)
return forgeSelector;
this.parseSelector();
} else {
this.parseNameOrUUID();
}
this.finalizePredicates();
return this.getSelector();
}
private static void fillSelectorSuggestions(SuggestionsBuilder p_121248_) {
p_121248_.suggest("@p", Component.translatable("argument.entity.selector.nearestPlayer"));
p_121248_.suggest("@a", Component.translatable("argument.entity.selector.allPlayers"));
p_121248_.suggest("@r", Component.translatable("argument.entity.selector.randomPlayer"));
p_121248_.suggest("@s", Component.translatable("argument.entity.selector.self"));
p_121248_.suggest("@e", Component.translatable("argument.entity.selector.allEntities"));
net.minecraftforge.common.command.EntitySelectorManager.fillSelectorSuggestions(p_121248_);
}
private CompletableFuture<Suggestions> suggestNameOrSelector(SuggestionsBuilder p_121287_, Consumer<SuggestionsBuilder> p_121288_) {
p_121288_.accept(p_121287_);
if (this.allowSelectors) {
fillSelectorSuggestions(p_121287_);
}
return p_121287_.buildFuture();
}
private CompletableFuture<Suggestions> suggestName(SuggestionsBuilder p_121310_, Consumer<SuggestionsBuilder> p_121311_) {
SuggestionsBuilder suggestionsbuilder = p_121310_.createOffset(this.startPosition);
p_121311_.accept(suggestionsbuilder);
return p_121310_.add(suggestionsbuilder).buildFuture();
}
private CompletableFuture<Suggestions> suggestSelector(SuggestionsBuilder p_121323_, Consumer<SuggestionsBuilder> p_121324_) {
SuggestionsBuilder suggestionsbuilder = p_121323_.createOffset(p_121323_.getStart() - 1);
fillSelectorSuggestions(suggestionsbuilder);
p_121323_.add(suggestionsbuilder);
return p_121323_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOpenOptions(SuggestionsBuilder p_121334_, Consumer<SuggestionsBuilder> p_121335_) {
p_121334_.suggest(String.valueOf('['));
return p_121334_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOptionsKeyOrClose(SuggestionsBuilder p_121342_, Consumer<SuggestionsBuilder> p_121343_) {
p_121342_.suggest(String.valueOf(']'));
EntitySelectorOptions.suggestNames(this, p_121342_);
return p_121342_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOptionsKey(SuggestionsBuilder p_121348_, Consumer<SuggestionsBuilder> p_121349_) {
EntitySelectorOptions.suggestNames(this, p_121348_);
return p_121348_.buildFuture();
}
private CompletableFuture<Suggestions> suggestOptionsNextOrClose(SuggestionsBuilder p_121354_, Consumer<SuggestionsBuilder> p_121355_) {
p_121354_.suggest(String.valueOf(','));
p_121354_.suggest(String.valueOf(']'));
return p_121354_.buildFuture();
}
private CompletableFuture<Suggestions> suggestEquals(SuggestionsBuilder p_175144_, Consumer<SuggestionsBuilder> p_175145_) {
p_175144_.suggest(String.valueOf('='));
return p_175144_.buildFuture();
}
public boolean isCurrentEntity() {
return this.currentEntity;
}
public void setSuggestions(BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> p_121271_) {
this.suggestions = p_121271_;
}
public CompletableFuture<Suggestions> fillSuggestions(SuggestionsBuilder p_121250_, Consumer<SuggestionsBuilder> p_121251_) {
return this.suggestions.apply(p_121250_.createOffset(this.reader.getCursor()), p_121251_);
}
public boolean hasNameEquals() {
return this.hasNameEquals;
}
public void setHasNameEquals(boolean p_121303_) {
this.hasNameEquals = p_121303_;
}
public boolean hasNameNotEquals() {
return this.hasNameNotEquals;
}
public void setHasNameNotEquals(boolean p_121316_) {
this.hasNameNotEquals = p_121316_;
}
public boolean isLimited() {
return this.isLimited;
}
public void setLimited(boolean p_121329_) {
this.isLimited = p_121329_;
}
public boolean isSorted() {
return this.isSorted;
}
public void setSorted(boolean p_121337_) {
this.isSorted = p_121337_;
}
public boolean hasGamemodeEquals() {
return this.hasGamemodeEquals;
}
public void setHasGamemodeEquals(boolean p_121345_) {
this.hasGamemodeEquals = p_121345_;
}
public boolean hasGamemodeNotEquals() {
return this.hasGamemodeNotEquals;
}
public void setHasGamemodeNotEquals(boolean p_121351_) {
this.hasGamemodeNotEquals = p_121351_;
}
public boolean hasTeamEquals() {
return this.hasTeamEquals;
}
public void setHasTeamEquals(boolean p_121357_) {
this.hasTeamEquals = p_121357_;
}
public boolean hasTeamNotEquals() {
return this.hasTeamNotEquals;
}
public void setHasTeamNotEquals(boolean p_121360_) {
this.hasTeamNotEquals = p_121360_;
}
public void limitToType(EntityType<?> p_121242_) {
this.type = p_121242_;
}
public void setTypeLimitedInversely() {
this.typeInverse = true;
}
public boolean isTypeLimited() {
return this.type != null;
}
public boolean isTypeLimitedInversely() {
return this.typeInverse;
}
public boolean hasScores() {
return this.hasScores;
}
public void setHasScores(boolean p_121366_) {
this.hasScores = p_121366_;
}
public boolean hasAdvancements() {
return this.hasAdvancements;
}
public void setHasAdvancements(boolean p_121369_) {
this.hasAdvancements = p_121369_;
}
}

View File

@@ -0,0 +1,566 @@
package net.minecraft.commands.arguments.selector.options;
import com.google.common.collect.Maps;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.advancements.CriterionProgress;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.advancements.critereon.WrappedMinMaxBounds;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.TagParser;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.PlayerAdvancements;
import net.minecraft.server.ServerAdvancementManager;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.TagKey;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataType;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.Score;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.Team;
public class EntitySelectorOptions {
private static final Map<String, EntitySelectorOptions.Option> OPTIONS = Maps.newHashMap();
public static final DynamicCommandExceptionType ERROR_UNKNOWN_OPTION = new DynamicCommandExceptionType((p_121520_) -> {
return Component.translatable("argument.entity.options.unknown", p_121520_);
});
public static final DynamicCommandExceptionType ERROR_INAPPLICABLE_OPTION = new DynamicCommandExceptionType((p_121516_) -> {
return Component.translatable("argument.entity.options.inapplicable", p_121516_);
});
public static final SimpleCommandExceptionType ERROR_RANGE_NEGATIVE = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.distance.negative"));
public static final SimpleCommandExceptionType ERROR_LEVEL_NEGATIVE = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.level.negative"));
public static final SimpleCommandExceptionType ERROR_LIMIT_TOO_SMALL = new SimpleCommandExceptionType(Component.translatable("argument.entity.options.limit.toosmall"));
public static final DynamicCommandExceptionType ERROR_SORT_UNKNOWN = new DynamicCommandExceptionType((p_121508_) -> {
return Component.translatable("argument.entity.options.sort.irreversible", p_121508_);
});
public static final DynamicCommandExceptionType ERROR_GAME_MODE_INVALID = new DynamicCommandExceptionType((p_121493_) -> {
return Component.translatable("argument.entity.options.mode.invalid", p_121493_);
});
public static final DynamicCommandExceptionType ERROR_ENTITY_TYPE_INVALID = new DynamicCommandExceptionType((p_121452_) -> {
return Component.translatable("argument.entity.options.type.invalid", p_121452_);
});
public static void register(String p_121454_, EntitySelectorOptions.Modifier p_121455_, Predicate<EntitySelectorParser> p_121456_, Component p_121457_) {
OPTIONS.put(p_121454_, new EntitySelectorOptions.Option(p_121455_, p_121456_, p_121457_));
}
public static void bootStrap() {
if (OPTIONS.isEmpty()) {
register("name", (p_121425_) -> {
int i = p_121425_.getReader().getCursor();
boolean flag = p_121425_.shouldInvertValue();
String s = p_121425_.getReader().readString();
if (p_121425_.hasNameNotEquals() && !flag) {
p_121425_.getReader().setCursor(i);
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121425_.getReader(), "name");
} else {
if (flag) {
p_121425_.setHasNameNotEquals(true);
} else {
p_121425_.setHasNameEquals(true);
}
p_121425_.addPredicate((p_175209_) -> {
return p_175209_.getName().getString().equals(s) != flag;
});
}
}, (p_121423_) -> {
return !p_121423_.hasNameEquals();
}, Component.translatable("argument.entity.options.name.description"));
register("distance", (p_121421_) -> {
int i = p_121421_.getReader().getCursor();
MinMaxBounds.Doubles minmaxbounds$doubles = MinMaxBounds.Doubles.fromReader(p_121421_.getReader());
if ((minmaxbounds$doubles.getMin() == null || !(minmaxbounds$doubles.getMin() < 0.0D)) && (minmaxbounds$doubles.getMax() == null || !(minmaxbounds$doubles.getMax() < 0.0D))) {
p_121421_.setDistance(minmaxbounds$doubles);
p_121421_.setWorldLimited();
} else {
p_121421_.getReader().setCursor(i);
throw ERROR_RANGE_NEGATIVE.createWithContext(p_121421_.getReader());
}
}, (p_121419_) -> {
return p_121419_.getDistance().isAny();
}, Component.translatable("argument.entity.options.distance.description"));
register("level", (p_121417_) -> {
int i = p_121417_.getReader().getCursor();
MinMaxBounds.Ints minmaxbounds$ints = MinMaxBounds.Ints.fromReader(p_121417_.getReader());
if ((minmaxbounds$ints.getMin() == null || minmaxbounds$ints.getMin() >= 0) && (minmaxbounds$ints.getMax() == null || minmaxbounds$ints.getMax() >= 0)) {
p_121417_.setLevel(minmaxbounds$ints);
p_121417_.setIncludesEntities(false);
} else {
p_121417_.getReader().setCursor(i);
throw ERROR_LEVEL_NEGATIVE.createWithContext(p_121417_.getReader());
}
}, (p_121415_) -> {
return p_121415_.getLevel().isAny();
}, Component.translatable("argument.entity.options.level.description"));
register("x", (p_121413_) -> {
p_121413_.setWorldLimited();
p_121413_.setX(p_121413_.getReader().readDouble());
}, (p_121411_) -> {
return p_121411_.getX() == null;
}, Component.translatable("argument.entity.options.x.description"));
register("y", (p_121409_) -> {
p_121409_.setWorldLimited();
p_121409_.setY(p_121409_.getReader().readDouble());
}, (p_121407_) -> {
return p_121407_.getY() == null;
}, Component.translatable("argument.entity.options.y.description"));
register("z", (p_121405_) -> {
p_121405_.setWorldLimited();
p_121405_.setZ(p_121405_.getReader().readDouble());
}, (p_121403_) -> {
return p_121403_.getZ() == null;
}, Component.translatable("argument.entity.options.z.description"));
register("dx", (p_121401_) -> {
p_121401_.setWorldLimited();
p_121401_.setDeltaX(p_121401_.getReader().readDouble());
}, (p_121399_) -> {
return p_121399_.getDeltaX() == null;
}, Component.translatable("argument.entity.options.dx.description"));
register("dy", (p_121397_) -> {
p_121397_.setWorldLimited();
p_121397_.setDeltaY(p_121397_.getReader().readDouble());
}, (p_121395_) -> {
return p_121395_.getDeltaY() == null;
}, Component.translatable("argument.entity.options.dy.description"));
register("dz", (p_121562_) -> {
p_121562_.setWorldLimited();
p_121562_.setDeltaZ(p_121562_.getReader().readDouble());
}, (p_121560_) -> {
return p_121560_.getDeltaZ() == null;
}, Component.translatable("argument.entity.options.dz.description"));
register("x_rotation", (p_121558_) -> {
p_121558_.setRotX(WrappedMinMaxBounds.fromReader(p_121558_.getReader(), true, Mth::wrapDegrees));
}, (p_121556_) -> {
return p_121556_.getRotX() == WrappedMinMaxBounds.ANY;
}, Component.translatable("argument.entity.options.x_rotation.description"));
register("y_rotation", (p_121554_) -> {
p_121554_.setRotY(WrappedMinMaxBounds.fromReader(p_121554_.getReader(), true, Mth::wrapDegrees));
}, (p_121552_) -> {
return p_121552_.getRotY() == WrappedMinMaxBounds.ANY;
}, Component.translatable("argument.entity.options.y_rotation.description"));
register("limit", (p_121550_) -> {
int i = p_121550_.getReader().getCursor();
int j = p_121550_.getReader().readInt();
if (j < 1) {
p_121550_.getReader().setCursor(i);
throw ERROR_LIMIT_TOO_SMALL.createWithContext(p_121550_.getReader());
} else {
p_121550_.setMaxResults(j);
p_121550_.setLimited(true);
}
}, (p_121548_) -> {
return !p_121548_.isCurrentEntity() && !p_121548_.isLimited();
}, Component.translatable("argument.entity.options.limit.description"));
register("sort", (p_247983_) -> {
int i = p_247983_.getReader().getCursor();
String s = p_247983_.getReader().readUnquotedString();
p_247983_.setSuggestions((p_175153_, p_175154_) -> {
return SharedSuggestionProvider.suggest(Arrays.asList("nearest", "furthest", "random", "arbitrary"), p_175153_);
});
BiConsumer biconsumer;
switch (s) {
case "nearest":
biconsumer = EntitySelectorParser.ORDER_NEAREST;
break;
case "furthest":
biconsumer = EntitySelectorParser.ORDER_FURTHEST;
break;
case "random":
biconsumer = EntitySelectorParser.ORDER_RANDOM;
break;
case "arbitrary":
biconsumer = EntitySelector.ORDER_ARBITRARY;
break;
default:
p_247983_.getReader().setCursor(i);
throw ERROR_SORT_UNKNOWN.createWithContext(p_247983_.getReader(), s);
}
p_247983_.setOrder(biconsumer);
p_247983_.setSorted(true);
}, (p_121544_) -> {
return !p_121544_.isCurrentEntity() && !p_121544_.isSorted();
}, Component.translatable("argument.entity.options.sort.description"));
register("gamemode", (p_121542_) -> {
p_121542_.setSuggestions((p_175193_, p_175194_) -> {
String s1 = p_175193_.getRemaining().toLowerCase(Locale.ROOT);
boolean flag1 = !p_121542_.hasGamemodeNotEquals();
boolean flag2 = true;
if (!s1.isEmpty()) {
if (s1.charAt(0) == '!') {
flag1 = false;
s1 = s1.substring(1);
} else {
flag2 = false;
}
}
for(GameType gametype1 : GameType.values()) {
if (gametype1.getName().toLowerCase(Locale.ROOT).startsWith(s1)) {
if (flag2) {
p_175193_.suggest("!" + gametype1.getName());
}
if (flag1) {
p_175193_.suggest(gametype1.getName());
}
}
}
return p_175193_.buildFuture();
});
int i = p_121542_.getReader().getCursor();
boolean flag = p_121542_.shouldInvertValue();
if (p_121542_.hasGamemodeNotEquals() && !flag) {
p_121542_.getReader().setCursor(i);
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121542_.getReader(), "gamemode");
} else {
String s = p_121542_.getReader().readUnquotedString();
GameType gametype = GameType.byName(s, (GameType)null);
if (gametype == null) {
p_121542_.getReader().setCursor(i);
throw ERROR_GAME_MODE_INVALID.createWithContext(p_121542_.getReader(), s);
} else {
p_121542_.setIncludesEntities(false);
p_121542_.addPredicate((p_175190_) -> {
if (!(p_175190_ instanceof ServerPlayer)) {
return false;
} else {
GameType gametype1 = ((ServerPlayer)p_175190_).gameMode.getGameModeForPlayer();
return flag ? gametype1 != gametype : gametype1 == gametype;
}
});
if (flag) {
p_121542_.setHasGamemodeNotEquals(true);
} else {
p_121542_.setHasGamemodeEquals(true);
}
}
}
}, (p_121540_) -> {
return !p_121540_.hasGamemodeEquals();
}, Component.translatable("argument.entity.options.gamemode.description"));
register("team", (p_121538_) -> {
boolean flag = p_121538_.shouldInvertValue();
String s = p_121538_.getReader().readUnquotedString();
p_121538_.addPredicate((p_175198_) -> {
if (!(p_175198_ instanceof LivingEntity)) {
return false;
} else {
Team team = p_175198_.getTeam();
String s1 = team == null ? "" : team.getName();
return s1.equals(s) != flag;
}
});
if (flag) {
p_121538_.setHasTeamNotEquals(true);
} else {
p_121538_.setHasTeamEquals(true);
}
}, (p_121536_) -> {
return !p_121536_.hasTeamEquals();
}, Component.translatable("argument.entity.options.team.description"));
register("type", (p_121534_) -> {
p_121534_.setSuggestions((p_258162_, p_258163_) -> {
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.keySet(), p_258162_, String.valueOf('!'));
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.getTagNames().map(TagKey::location), p_258162_, "!#");
if (!p_121534_.isTypeLimitedInversely()) {
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.keySet(), p_258162_);
SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.getTagNames().map(TagKey::location), p_258162_, String.valueOf('#'));
}
return p_258162_.buildFuture();
});
int i = p_121534_.getReader().getCursor();
boolean flag = p_121534_.shouldInvertValue();
if (p_121534_.isTypeLimitedInversely() && !flag) {
p_121534_.getReader().setCursor(i);
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121534_.getReader(), "type");
} else {
if (flag) {
p_121534_.setTypeLimitedInversely();
}
if (p_121534_.isTag()) {
TagKey<EntityType<?>> tagkey = TagKey.create(Registries.ENTITY_TYPE, ResourceLocation.read(p_121534_.getReader()));
p_121534_.addPredicate((p_205691_) -> {
return p_205691_.getType().is(tagkey) != flag;
});
} else {
ResourceLocation resourcelocation = ResourceLocation.read(p_121534_.getReader());
EntityType<?> entitytype = BuiltInRegistries.ENTITY_TYPE.getOptional(resourcelocation).orElseThrow(() -> {
p_121534_.getReader().setCursor(i);
return ERROR_ENTITY_TYPE_INVALID.createWithContext(p_121534_.getReader(), resourcelocation.toString());
});
if (Objects.equals(EntityType.PLAYER, entitytype) && !flag) {
p_121534_.setIncludesEntities(false);
}
p_121534_.addPredicate((p_175151_) -> {
return Objects.equals(entitytype, p_175151_.getType()) != flag;
});
if (!flag) {
p_121534_.limitToType(entitytype);
}
}
}
}, (p_121532_) -> {
return !p_121532_.isTypeLimited();
}, Component.translatable("argument.entity.options.type.description"));
register("tag", (p_121530_) -> {
boolean flag = p_121530_.shouldInvertValue();
String s = p_121530_.getReader().readUnquotedString();
p_121530_.addPredicate((p_175166_) -> {
if ("".equals(s)) {
return p_175166_.getTags().isEmpty() != flag;
} else {
return p_175166_.getTags().contains(s) != flag;
}
});
}, (p_121528_) -> {
return true;
}, Component.translatable("argument.entity.options.tag.description"));
register("nbt", (p_121526_) -> {
boolean flag = p_121526_.shouldInvertValue();
CompoundTag compoundtag = (new TagParser(p_121526_.getReader())).readStruct();
p_121526_.addPredicate((p_175176_) -> {
CompoundTag compoundtag1 = p_175176_.saveWithoutId(new CompoundTag());
if (p_175176_ instanceof ServerPlayer) {
ItemStack itemstack = ((ServerPlayer)p_175176_).getInventory().getSelected();
if (!itemstack.isEmpty()) {
compoundtag1.put("SelectedItem", itemstack.save(new CompoundTag()));
}
}
return NbtUtils.compareNbt(compoundtag, compoundtag1, true) != flag;
});
}, (p_121524_) -> {
return true;
}, Component.translatable("argument.entity.options.nbt.description"));
register("scores", (p_121522_) -> {
StringReader stringreader = p_121522_.getReader();
Map<String, MinMaxBounds.Ints> map = Maps.newHashMap();
stringreader.expect('{');
stringreader.skipWhitespace();
while(stringreader.canRead() && stringreader.peek() != '}') {
stringreader.skipWhitespace();
String s = stringreader.readUnquotedString();
stringreader.skipWhitespace();
stringreader.expect('=');
stringreader.skipWhitespace();
MinMaxBounds.Ints minmaxbounds$ints = MinMaxBounds.Ints.fromReader(stringreader);
map.put(s, minmaxbounds$ints);
stringreader.skipWhitespace();
if (stringreader.canRead() && stringreader.peek() == ',') {
stringreader.skip();
}
}
stringreader.expect('}');
if (!map.isEmpty()) {
p_121522_.addPredicate((p_175201_) -> {
Scoreboard scoreboard = p_175201_.getServer().getScoreboard();
String s1 = p_175201_.getScoreboardName();
for(Map.Entry<String, MinMaxBounds.Ints> entry : map.entrySet()) {
Objective objective = scoreboard.getObjective(entry.getKey());
if (objective == null) {
return false;
}
if (!scoreboard.hasPlayerScore(s1, objective)) {
return false;
}
Score score = scoreboard.getOrCreatePlayerScore(s1, objective);
int i = score.getScore();
if (!entry.getValue().matches(i)) {
return false;
}
}
return true;
});
}
p_121522_.setHasScores(true);
}, (p_121518_) -> {
return !p_121518_.hasScores();
}, Component.translatable("argument.entity.options.scores.description"));
register("advancements", (p_121514_) -> {
StringReader stringreader = p_121514_.getReader();
Map<ResourceLocation, Predicate<AdvancementProgress>> map = Maps.newHashMap();
stringreader.expect('{');
stringreader.skipWhitespace();
while(stringreader.canRead() && stringreader.peek() != '}') {
stringreader.skipWhitespace();
ResourceLocation resourcelocation = ResourceLocation.read(stringreader);
stringreader.skipWhitespace();
stringreader.expect('=');
stringreader.skipWhitespace();
if (stringreader.canRead() && stringreader.peek() == '{') {
Map<String, Predicate<CriterionProgress>> map1 = Maps.newHashMap();
stringreader.skipWhitespace();
stringreader.expect('{');
stringreader.skipWhitespace();
while(stringreader.canRead() && stringreader.peek() != '}') {
stringreader.skipWhitespace();
String s = stringreader.readUnquotedString();
stringreader.skipWhitespace();
stringreader.expect('=');
stringreader.skipWhitespace();
boolean flag1 = stringreader.readBoolean();
map1.put(s, (p_175186_) -> {
return p_175186_.isDone() == flag1;
});
stringreader.skipWhitespace();
if (stringreader.canRead() && stringreader.peek() == ',') {
stringreader.skip();
}
}
stringreader.skipWhitespace();
stringreader.expect('}');
stringreader.skipWhitespace();
map.put(resourcelocation, (p_175169_) -> {
for(Map.Entry<String, Predicate<CriterionProgress>> entry : map1.entrySet()) {
CriterionProgress criterionprogress = p_175169_.getCriterion(entry.getKey());
if (criterionprogress == null || !entry.getValue().test(criterionprogress)) {
return false;
}
}
return true;
});
} else {
boolean flag = stringreader.readBoolean();
map.put(resourcelocation, (p_175183_) -> {
return p_175183_.isDone() == flag;
});
}
stringreader.skipWhitespace();
if (stringreader.canRead() && stringreader.peek() == ',') {
stringreader.skip();
}
}
stringreader.expect('}');
if (!map.isEmpty()) {
p_121514_.addPredicate((p_175172_) -> {
if (!(p_175172_ instanceof ServerPlayer serverplayer)) {
return false;
} else {
PlayerAdvancements playeradvancements = serverplayer.getAdvancements();
ServerAdvancementManager serveradvancementmanager = serverplayer.getServer().getAdvancements();
for(Map.Entry<ResourceLocation, Predicate<AdvancementProgress>> entry : map.entrySet()) {
Advancement advancement = serveradvancementmanager.getAdvancement(entry.getKey());
if (advancement == null || !entry.getValue().test(playeradvancements.getOrStartProgress(advancement))) {
return false;
}
}
return true;
}
});
p_121514_.setIncludesEntities(false);
}
p_121514_.setHasAdvancements(true);
}, (p_121506_) -> {
return !p_121506_.hasAdvancements();
}, Component.translatable("argument.entity.options.advancements.description"));
register("predicate", (p_121487_) -> {
boolean flag = p_121487_.shouldInvertValue();
ResourceLocation resourcelocation = ResourceLocation.read(p_121487_.getReader());
p_121487_.addPredicate((p_287325_) -> {
if (!(p_287325_.level() instanceof ServerLevel)) {
return false;
} else {
ServerLevel serverlevel = (ServerLevel)p_287325_.level();
LootItemCondition lootitemcondition = serverlevel.getServer().getLootData().getElement(LootDataType.PREDICATE, resourcelocation);
if (lootitemcondition == null) {
return false;
} else {
LootParams lootparams = (new LootParams.Builder(serverlevel)).withParameter(LootContextParams.THIS_ENTITY, p_287325_).withParameter(LootContextParams.ORIGIN, p_287325_.position()).create(LootContextParamSets.SELECTOR);
LootContext lootcontext = (new LootContext.Builder(lootparams)).create((ResourceLocation)null);
lootcontext.pushVisitedElement(LootContext.createVisitedEntry(lootitemcondition));
return flag ^ lootitemcondition.test(lootcontext);
}
}
});
}, (p_121435_) -> {
return true;
}, Component.translatable("argument.entity.options.predicate.description"));
}
}
public static EntitySelectorOptions.Modifier get(EntitySelectorParser p_121448_, String p_121449_, int p_121450_) throws CommandSyntaxException {
EntitySelectorOptions.Option entityselectoroptions$option = OPTIONS.get(p_121449_);
if (entityselectoroptions$option != null) {
if (entityselectoroptions$option.canUse.test(p_121448_)) {
return entityselectoroptions$option.modifier;
} else {
throw ERROR_INAPPLICABLE_OPTION.createWithContext(p_121448_.getReader(), p_121449_);
}
} else {
p_121448_.getReader().setCursor(p_121450_);
throw ERROR_UNKNOWN_OPTION.createWithContext(p_121448_.getReader(), p_121449_);
}
}
public static void suggestNames(EntitySelectorParser p_121441_, SuggestionsBuilder p_121442_) {
String s = p_121442_.getRemaining().toLowerCase(Locale.ROOT);
for(Map.Entry<String, EntitySelectorOptions.Option> entry : OPTIONS.entrySet()) {
if ((entry.getValue()).canUse.test(p_121441_) && entry.getKey().toLowerCase(Locale.ROOT).startsWith(s)) {
p_121442_.suggest((String)entry.getKey() + "=", (entry.getValue()).description);
}
}
}
public interface Modifier {
void handle(EntitySelectorParser p_121564_) throws CommandSyntaxException;
}
static record Option(EntitySelectorOptions.Modifier modifier, Predicate<EntitySelectorParser> canUse, Component description) {
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.arguments.selector.options;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.arguments.selector;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,22 @@
package net.minecraft.commands.synchronization;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.ArgumentType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.network.FriendlyByteBuf;
public interface ArgumentTypeInfo<A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> {
void serializeToNetwork(T p_235375_, FriendlyByteBuf p_235376_);
T deserializeFromNetwork(FriendlyByteBuf p_235377_);
void serializeToJson(T p_235373_, JsonObject p_235374_);
T unpack(A p_235372_);
public interface Template<A extends ArgumentType<?>> {
A instantiate(CommandBuildContext p_235378_);
ArgumentTypeInfo<A, ?> type();
}
}

View File

@@ -0,0 +1,166 @@
package net.minecraft.commands.synchronization;
import com.google.common.collect.Maps;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.LongArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import java.util.Locale;
import java.util.Map;
import net.minecraft.SharedConstants;
import net.minecraft.commands.arguments.AngleArgument;
import net.minecraft.commands.arguments.ColorArgument;
import net.minecraft.commands.arguments.ComponentArgument;
import net.minecraft.commands.arguments.CompoundTagArgument;
import net.minecraft.commands.arguments.DimensionArgument;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.commands.arguments.GameModeArgument;
import net.minecraft.commands.arguments.GameProfileArgument;
import net.minecraft.commands.arguments.HeightmapTypeArgument;
import net.minecraft.commands.arguments.MessageArgument;
import net.minecraft.commands.arguments.NbtPathArgument;
import net.minecraft.commands.arguments.NbtTagArgument;
import net.minecraft.commands.arguments.ObjectiveArgument;
import net.minecraft.commands.arguments.ObjectiveCriteriaArgument;
import net.minecraft.commands.arguments.OperationArgument;
import net.minecraft.commands.arguments.ParticleArgument;
import net.minecraft.commands.arguments.RangeArgument;
import net.minecraft.commands.arguments.ResourceArgument;
import net.minecraft.commands.arguments.ResourceKeyArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.ResourceOrTagArgument;
import net.minecraft.commands.arguments.ResourceOrTagKeyArgument;
import net.minecraft.commands.arguments.ScoreHolderArgument;
import net.minecraft.commands.arguments.ScoreboardSlotArgument;
import net.minecraft.commands.arguments.SlotArgument;
import net.minecraft.commands.arguments.TeamArgument;
import net.minecraft.commands.arguments.TemplateMirrorArgument;
import net.minecraft.commands.arguments.TemplateRotationArgument;
import net.minecraft.commands.arguments.TimeArgument;
import net.minecraft.commands.arguments.UuidArgument;
import net.minecraft.commands.arguments.blocks.BlockPredicateArgument;
import net.minecraft.commands.arguments.blocks.BlockStateArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.commands.arguments.coordinates.ColumnPosArgument;
import net.minecraft.commands.arguments.coordinates.RotationArgument;
import net.minecraft.commands.arguments.coordinates.SwizzleArgument;
import net.minecraft.commands.arguments.coordinates.Vec2Argument;
import net.minecraft.commands.arguments.coordinates.Vec3Argument;
import net.minecraft.commands.arguments.item.FunctionArgument;
import net.minecraft.commands.arguments.item.ItemArgument;
import net.minecraft.commands.arguments.item.ItemPredicateArgument;
import net.minecraft.commands.synchronization.brigadier.DoubleArgumentInfo;
import net.minecraft.commands.synchronization.brigadier.FloatArgumentInfo;
import net.minecraft.commands.synchronization.brigadier.IntegerArgumentInfo;
import net.minecraft.commands.synchronization.brigadier.LongArgumentInfo;
import net.minecraft.commands.synchronization.brigadier.StringArgumentSerializer;
import net.minecraft.core.Registry;
import net.minecraft.gametest.framework.TestClassNameArgument;
import net.minecraft.gametest.framework.TestFunctionArgument;
public class ArgumentTypeInfos {
private static final Map<Class<?>, ArgumentTypeInfo<?, ?>> BY_CLASS = Maps.newHashMap();
/**
* Forge: Use this in conjunction with a
* {@link net.minecraftforge.registries.DeferredRegister#register(String, java.util.function.Supplier) DeferredRegister#register(String, Supplier)}
* call to both populate the {@code BY_CLASS} map and register the argument type info so it can be used in commands.
*
* @param infoClass the class type of the argument type info
* @param argumentTypeInfo the argument type info instance
* @return the provided argument type info instance for chaining
*/
public static synchronized <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>, I extends ArgumentTypeInfo<A, T>> I registerByClass(Class<A> infoClass, I argumentTypeInfo) {
BY_CLASS.put(infoClass, argumentTypeInfo);
return argumentTypeInfo;
}
private static <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> ArgumentTypeInfo<A, T> register(Registry<ArgumentTypeInfo<?, ?>> p_235387_, String p_235388_, Class<? extends A> p_235389_, ArgumentTypeInfo<A, T> p_235390_) {
BY_CLASS.put(p_235389_, p_235390_);
return Registry.register(p_235387_, p_235388_, p_235390_);
}
public static ArgumentTypeInfo<?, ?> bootstrap(Registry<ArgumentTypeInfo<?, ?>> p_235385_) {
register(p_235385_, "brigadier:bool", BoolArgumentType.class, SingletonArgumentInfo.contextFree(BoolArgumentType::bool));
register(p_235385_, "brigadier:float", FloatArgumentType.class, new FloatArgumentInfo());
register(p_235385_, "brigadier:double", DoubleArgumentType.class, new DoubleArgumentInfo());
register(p_235385_, "brigadier:integer", IntegerArgumentType.class, new IntegerArgumentInfo());
register(p_235385_, "brigadier:long", LongArgumentType.class, new LongArgumentInfo());
register(p_235385_, "brigadier:string", StringArgumentType.class, new StringArgumentSerializer());
register(p_235385_, "entity", EntityArgument.class, new EntityArgument.Info());
register(p_235385_, "game_profile", GameProfileArgument.class, SingletonArgumentInfo.contextFree(GameProfileArgument::gameProfile));
register(p_235385_, "block_pos", BlockPosArgument.class, SingletonArgumentInfo.contextFree(BlockPosArgument::blockPos));
register(p_235385_, "column_pos", ColumnPosArgument.class, SingletonArgumentInfo.contextFree(ColumnPosArgument::columnPos));
register(p_235385_, "vec3", Vec3Argument.class, SingletonArgumentInfo.contextFree(Vec3Argument::vec3));
register(p_235385_, "vec2", Vec2Argument.class, SingletonArgumentInfo.contextFree(Vec2Argument::vec2));
register(p_235385_, "block_state", BlockStateArgument.class, SingletonArgumentInfo.contextAware(BlockStateArgument::block));
register(p_235385_, "block_predicate", BlockPredicateArgument.class, SingletonArgumentInfo.contextAware(BlockPredicateArgument::blockPredicate));
register(p_235385_, "item_stack", ItemArgument.class, SingletonArgumentInfo.contextAware(ItemArgument::item));
register(p_235385_, "item_predicate", ItemPredicateArgument.class, SingletonArgumentInfo.contextAware(ItemPredicateArgument::itemPredicate));
register(p_235385_, "color", ColorArgument.class, SingletonArgumentInfo.contextFree(ColorArgument::color));
register(p_235385_, "component", ComponentArgument.class, SingletonArgumentInfo.contextFree(ComponentArgument::textComponent));
register(p_235385_, "message", MessageArgument.class, SingletonArgumentInfo.contextFree(MessageArgument::message));
register(p_235385_, "nbt_compound_tag", CompoundTagArgument.class, SingletonArgumentInfo.contextFree(CompoundTagArgument::compoundTag));
register(p_235385_, "nbt_tag", NbtTagArgument.class, SingletonArgumentInfo.contextFree(NbtTagArgument::nbtTag));
register(p_235385_, "nbt_path", NbtPathArgument.class, SingletonArgumentInfo.contextFree(NbtPathArgument::nbtPath));
register(p_235385_, "objective", ObjectiveArgument.class, SingletonArgumentInfo.contextFree(ObjectiveArgument::objective));
register(p_235385_, "objective_criteria", ObjectiveCriteriaArgument.class, SingletonArgumentInfo.contextFree(ObjectiveCriteriaArgument::criteria));
register(p_235385_, "operation", OperationArgument.class, SingletonArgumentInfo.contextFree(OperationArgument::operation));
register(p_235385_, "particle", ParticleArgument.class, SingletonArgumentInfo.contextAware(ParticleArgument::particle));
register(p_235385_, "angle", AngleArgument.class, SingletonArgumentInfo.contextFree(AngleArgument::angle));
register(p_235385_, "rotation", RotationArgument.class, SingletonArgumentInfo.contextFree(RotationArgument::rotation));
register(p_235385_, "scoreboard_slot", ScoreboardSlotArgument.class, SingletonArgumentInfo.contextFree(ScoreboardSlotArgument::displaySlot));
register(p_235385_, "score_holder", ScoreHolderArgument.class, new ScoreHolderArgument.Info());
register(p_235385_, "swizzle", SwizzleArgument.class, SingletonArgumentInfo.contextFree(SwizzleArgument::swizzle));
register(p_235385_, "team", TeamArgument.class, SingletonArgumentInfo.contextFree(TeamArgument::team));
register(p_235385_, "item_slot", SlotArgument.class, SingletonArgumentInfo.contextFree(SlotArgument::slot));
register(p_235385_, "resource_location", ResourceLocationArgument.class, SingletonArgumentInfo.contextFree(ResourceLocationArgument::id));
register(p_235385_, "function", FunctionArgument.class, SingletonArgumentInfo.contextFree(FunctionArgument::functions));
register(p_235385_, "entity_anchor", EntityAnchorArgument.class, SingletonArgumentInfo.contextFree(EntityAnchorArgument::anchor));
register(p_235385_, "int_range", RangeArgument.Ints.class, SingletonArgumentInfo.contextFree(RangeArgument::intRange));
register(p_235385_, "float_range", RangeArgument.Floats.class, SingletonArgumentInfo.contextFree(RangeArgument::floatRange));
register(p_235385_, "dimension", DimensionArgument.class, SingletonArgumentInfo.contextFree(DimensionArgument::dimension));
register(p_235385_, "gamemode", GameModeArgument.class, SingletonArgumentInfo.contextFree(GameModeArgument::gameMode));
register(p_235385_, "time", TimeArgument.class, new TimeArgument.Info());
register(p_235385_, "resource_or_tag", fixClassType(ResourceOrTagArgument.class), new ResourceOrTagArgument.Info<Object>());
register(p_235385_, "resource_or_tag_key", fixClassType(ResourceOrTagKeyArgument.class), new ResourceOrTagKeyArgument.Info<Object>());
register(p_235385_, "resource", fixClassType(ResourceArgument.class), new ResourceArgument.Info<Object>());
register(p_235385_, "resource_key", fixClassType(ResourceKeyArgument.class), new ResourceKeyArgument.Info<Object>());
register(p_235385_, "template_mirror", TemplateMirrorArgument.class, SingletonArgumentInfo.contextFree(TemplateMirrorArgument::templateMirror));
register(p_235385_, "template_rotation", TemplateRotationArgument.class, SingletonArgumentInfo.contextFree(TemplateRotationArgument::templateRotation));
register(p_235385_, "heightmap", HeightmapTypeArgument.class, SingletonArgumentInfo.contextFree(HeightmapTypeArgument::heightmap));
// Forge: Register before gametest arguments to provide forge server <-> vanilla client interop and matching int ids
var uuidInfo = register(p_235385_, "uuid", UuidArgument.class, SingletonArgumentInfo.contextFree(UuidArgument::uuid));
if (true) { // Forge: Always register gametest arguments to prevent issues when connecting from gametest-enabled client/server to non-gametest-enabled client/server
register(p_235385_, "test_argument", TestFunctionArgument.class, SingletonArgumentInfo.contextFree(TestFunctionArgument::testFunctionArgument));
register(p_235385_, "test_class", TestClassNameArgument.class, SingletonArgumentInfo.contextFree(TestClassNameArgument::testClassName));
}
return uuidInfo;
}
private static <T extends ArgumentType<?>> Class<T> fixClassType(Class<? super T> p_235396_) {
return (Class<T>)p_235396_;
}
public static boolean isClassRecognized(Class<?> p_235392_) {
return BY_CLASS.containsKey(p_235392_);
}
public static <A extends ArgumentType<?>> ArgumentTypeInfo<A, ?> byClass(A p_235383_) {
ArgumentTypeInfo<?, ?> argumenttypeinfo = BY_CLASS.get(p_235383_.getClass());
if (argumenttypeinfo == null) {
throw new IllegalArgumentException(String.format(Locale.ROOT, "Unrecognized argument type %s (%s)", p_235383_, p_235383_.getClass()));
} else {
return (ArgumentTypeInfo<A, ?>)argumenttypeinfo;
}
}
public static <A extends ArgumentType<?>> ArgumentTypeInfo.Template<A> unpack(A p_235394_) {
return byClass(p_235394_).unpack(p_235394_);
}
}

View File

@@ -0,0 +1,132 @@
package net.minecraft.commands.synchronization;
import com.google.common.collect.Sets;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.tree.ArgumentCommandNode;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
import com.mojang.logging.LogUtils;
import java.util.Collection;
import java.util.Set;
import net.minecraft.core.registries.BuiltInRegistries;
import org.slf4j.Logger;
public class ArgumentUtils {
private static final Logger LOGGER = LogUtils.getLogger();
private static final byte NUMBER_FLAG_MIN = 1;
private static final byte NUMBER_FLAG_MAX = 2;
public static int createNumberFlags(boolean p_235428_, boolean p_235429_) {
int i = 0;
if (p_235428_) {
i |= 1;
}
if (p_235429_) {
i |= 2;
}
return i;
}
public static boolean numberHasMin(byte p_235403_) {
return (p_235403_ & 1) != 0;
}
public static boolean numberHasMax(byte p_235431_) {
return (p_235431_ & 2) != 0;
}
private static <A extends ArgumentType<?>> void serializeCap(JsonObject p_235408_, ArgumentTypeInfo.Template<A> p_235409_) {
serializeCap(p_235408_, p_235409_.type(), p_235409_);
}
private static <A extends ArgumentType<?>, T extends ArgumentTypeInfo.Template<A>> void serializeCap(JsonObject p_235411_, ArgumentTypeInfo<A, T> p_235412_, ArgumentTypeInfo.Template<A> p_235413_) {
p_235412_.serializeToJson((T)p_235413_, p_235411_);
}
private static <T extends ArgumentType<?>> void serializeArgumentToJson(JsonObject p_235405_, T p_235406_) {
ArgumentTypeInfo.Template<T> template = ArgumentTypeInfos.unpack(p_235406_);
p_235405_.addProperty("type", "argument");
p_235405_.addProperty("parser", BuiltInRegistries.COMMAND_ARGUMENT_TYPE.getKey(template.type()).toString());
JsonObject jsonobject = new JsonObject();
serializeCap(jsonobject, template);
if (jsonobject.size() > 0) {
p_235405_.add("properties", jsonobject);
}
}
public static <S> JsonObject serializeNodeToJson(CommandDispatcher<S> p_235415_, CommandNode<S> p_235416_) {
JsonObject jsonobject = new JsonObject();
if (p_235416_ instanceof RootCommandNode) {
jsonobject.addProperty("type", "root");
} else if (p_235416_ instanceof LiteralCommandNode) {
jsonobject.addProperty("type", "literal");
} else if (p_235416_ instanceof ArgumentCommandNode) {
ArgumentCommandNode<?, ?> argumentcommandnode = (ArgumentCommandNode)p_235416_;
serializeArgumentToJson(jsonobject, argumentcommandnode.getType());
} else {
LOGGER.error("Could not serialize node {} ({})!", p_235416_, p_235416_.getClass());
jsonobject.addProperty("type", "unknown");
}
JsonObject jsonobject1 = new JsonObject();
for(CommandNode<S> commandnode : p_235416_.getChildren()) {
jsonobject1.add(commandnode.getName(), serializeNodeToJson(p_235415_, commandnode));
}
if (jsonobject1.size() > 0) {
jsonobject.add("children", jsonobject1);
}
if (p_235416_.getCommand() != null) {
jsonobject.addProperty("executable", true);
}
if (p_235416_.getRedirect() != null) {
Collection<String> collection = p_235415_.getPath(p_235416_.getRedirect());
if (!collection.isEmpty()) {
JsonArray jsonarray = new JsonArray();
for(String s : collection) {
jsonarray.add(s);
}
jsonobject.add("redirect", jsonarray);
}
}
return jsonobject;
}
public static <T> Set<ArgumentType<?>> findUsedArgumentTypes(CommandNode<T> p_235418_) {
Set<CommandNode<T>> set = Sets.newIdentityHashSet();
Set<ArgumentType<?>> set1 = Sets.newHashSet();
findUsedArgumentTypes(p_235418_, set1, set);
return set1;
}
private static <T> void findUsedArgumentTypes(CommandNode<T> p_235420_, Set<ArgumentType<?>> p_235421_, Set<CommandNode<T>> p_235422_) {
if (p_235422_.add(p_235420_)) {
if (p_235420_ instanceof ArgumentCommandNode) {
ArgumentCommandNode<?, ?> argumentcommandnode = (ArgumentCommandNode)p_235420_;
p_235421_.add(argumentcommandnode.getType());
}
p_235420_.getChildren().forEach((p_235426_) -> {
findUsedArgumentTypes(p_235426_, p_235421_, p_235422_);
});
CommandNode<T> commandnode = p_235420_.getRedirect();
if (commandnode != null) {
findUsedArgumentTypes(commandnode, p_235421_, p_235422_);
}
}
}
}

View File

@@ -0,0 +1,56 @@
package net.minecraft.commands.synchronization;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.ArgumentType;
import java.util.function.Function;
import java.util.function.Supplier;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.network.FriendlyByteBuf;
public class SingletonArgumentInfo<A extends ArgumentType<?>> implements ArgumentTypeInfo<A, SingletonArgumentInfo<A>.Template> {
private final SingletonArgumentInfo<A>.Template template;
private SingletonArgumentInfo(Function<CommandBuildContext, A> p_235434_) {
this.template = new SingletonArgumentInfo.Template(p_235434_);
}
public static <T extends ArgumentType<?>> SingletonArgumentInfo<T> contextFree(Supplier<T> p_235452_) {
return new SingletonArgumentInfo<>((p_235455_) -> {
return p_235452_.get();
});
}
public static <T extends ArgumentType<?>> SingletonArgumentInfo<T> contextAware(Function<CommandBuildContext, T> p_235450_) {
return new SingletonArgumentInfo<>(p_235450_);
}
public void serializeToNetwork(SingletonArgumentInfo<A>.Template p_235447_, FriendlyByteBuf p_235448_) {
}
public void serializeToJson(SingletonArgumentInfo<A>.Template p_235444_, JsonObject p_235445_) {
}
public SingletonArgumentInfo<A>.Template deserializeFromNetwork(FriendlyByteBuf p_235457_) {
return this.template;
}
public SingletonArgumentInfo<A>.Template unpack(A p_235459_) {
return this.template;
}
public final class Template implements ArgumentTypeInfo.Template<A> {
private final Function<CommandBuildContext, A> constructor;
public Template(Function<CommandBuildContext, A> p_235466_) {
this.constructor = p_235466_;
}
public A instantiate(CommandBuildContext p_235469_) {
return this.constructor.apply(p_235469_);
}
public ArgumentTypeInfo<A, ?> type() {
return SingletonArgumentInfo.this;
}
}
}

View File

@@ -0,0 +1,73 @@
package net.minecraft.commands.synchronization;
import com.google.common.collect.Maps;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
public class SuggestionProviders {
private static final Map<ResourceLocation, SuggestionProvider<SharedSuggestionProvider>> PROVIDERS_BY_NAME = Maps.newHashMap();
private static final ResourceLocation DEFAULT_NAME = new ResourceLocation("ask_server");
public static final SuggestionProvider<SharedSuggestionProvider> ASK_SERVER = register(DEFAULT_NAME, (p_121673_, p_121674_) -> {
return p_121673_.getSource().customSuggestion(p_121673_);
});
public static final SuggestionProvider<CommandSourceStack> ALL_RECIPES = register(new ResourceLocation("all_recipes"), (p_121670_, p_121671_) -> {
return SharedSuggestionProvider.suggestResource(p_121670_.getSource().getRecipeNames(), p_121671_);
});
public static final SuggestionProvider<CommandSourceStack> AVAILABLE_SOUNDS = register(new ResourceLocation("available_sounds"), (p_121667_, p_121668_) -> {
return SharedSuggestionProvider.suggestResource(p_121667_.getSource().getAvailableSounds(), p_121668_);
});
public static final SuggestionProvider<CommandSourceStack> SUMMONABLE_ENTITIES = register(new ResourceLocation("summonable_entities"), (p_258164_, p_258165_) -> {
return SharedSuggestionProvider.suggestResource(BuiltInRegistries.ENTITY_TYPE.stream().filter((p_247987_) -> {
return p_247987_.isEnabled(p_258164_.getSource().enabledFeatures()) && p_247987_.canSummon();
}), p_258165_, EntityType::getKey, (p_212436_) -> {
return Component.translatable(Util.makeDescriptionId("entity", EntityType.getKey(p_212436_)));
});
});
public static <S extends SharedSuggestionProvider> SuggestionProvider<S> register(ResourceLocation p_121659_, SuggestionProvider<SharedSuggestionProvider> p_121660_) {
if (PROVIDERS_BY_NAME.containsKey(p_121659_)) {
throw new IllegalArgumentException("A command suggestion provider is already registered with the name " + p_121659_);
} else {
PROVIDERS_BY_NAME.put(p_121659_, p_121660_);
return (SuggestionProvider<S>)new SuggestionProviders.Wrapper(p_121659_, p_121660_);
}
}
public static SuggestionProvider<SharedSuggestionProvider> getProvider(ResourceLocation p_121657_) {
return PROVIDERS_BY_NAME.getOrDefault(p_121657_, ASK_SERVER);
}
public static ResourceLocation getName(SuggestionProvider<SharedSuggestionProvider> p_121655_) {
return p_121655_ instanceof SuggestionProviders.Wrapper ? ((SuggestionProviders.Wrapper)p_121655_).name : DEFAULT_NAME;
}
public static SuggestionProvider<SharedSuggestionProvider> safelySwap(SuggestionProvider<SharedSuggestionProvider> p_121665_) {
return p_121665_ instanceof SuggestionProviders.Wrapper ? p_121665_ : ASK_SERVER;
}
protected static class Wrapper implements SuggestionProvider<SharedSuggestionProvider> {
private final SuggestionProvider<SharedSuggestionProvider> delegate;
final ResourceLocation name;
public Wrapper(ResourceLocation p_121678_, SuggestionProvider<SharedSuggestionProvider> p_121679_) {
this.delegate = p_121679_;
this.name = p_121678_;
}
public CompletableFuture<Suggestions> getSuggestions(CommandContext<SharedSuggestionProvider> p_121683_, SuggestionsBuilder p_121684_) throws CommandSyntaxException {
return this.delegate.getSuggestions(p_121683_, p_121684_);
}
}
}

View File

@@ -0,0 +1,64 @@
package net.minecraft.commands.synchronization.brigadier;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.commands.synchronization.ArgumentUtils;
import net.minecraft.network.FriendlyByteBuf;
public class DoubleArgumentInfo implements ArgumentTypeInfo<DoubleArgumentType, DoubleArgumentInfo.Template> {
public void serializeToNetwork(DoubleArgumentInfo.Template p_235485_, FriendlyByteBuf p_235486_) {
boolean flag = p_235485_.min != -Double.MAX_VALUE;
boolean flag1 = p_235485_.max != Double.MAX_VALUE;
p_235486_.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
if (flag) {
p_235486_.writeDouble(p_235485_.min);
}
if (flag1) {
p_235486_.writeDouble(p_235485_.max);
}
}
public DoubleArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf p_235488_) {
byte b0 = p_235488_.readByte();
double d0 = ArgumentUtils.numberHasMin(b0) ? p_235488_.readDouble() : -Double.MAX_VALUE;
double d1 = ArgumentUtils.numberHasMax(b0) ? p_235488_.readDouble() : Double.MAX_VALUE;
return new DoubleArgumentInfo.Template(d0, d1);
}
public void serializeToJson(DoubleArgumentInfo.Template p_235482_, JsonObject p_235483_) {
if (p_235482_.min != -Double.MAX_VALUE) {
p_235483_.addProperty("min", p_235482_.min);
}
if (p_235482_.max != Double.MAX_VALUE) {
p_235483_.addProperty("max", p_235482_.max);
}
}
public DoubleArgumentInfo.Template unpack(DoubleArgumentType p_235474_) {
return new DoubleArgumentInfo.Template(p_235474_.getMinimum(), p_235474_.getMaximum());
}
public final class Template implements ArgumentTypeInfo.Template<DoubleArgumentType> {
final double min;
final double max;
Template(double p_235496_, double p_235497_) {
this.min = p_235496_;
this.max = p_235497_;
}
public DoubleArgumentType instantiate(CommandBuildContext p_235500_) {
return DoubleArgumentType.doubleArg(this.min, this.max);
}
public ArgumentTypeInfo<DoubleArgumentType, ?> type() {
return DoubleArgumentInfo.this;
}
}
}

View File

@@ -0,0 +1,64 @@
package net.minecraft.commands.synchronization.brigadier;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.FloatArgumentType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.commands.synchronization.ArgumentUtils;
import net.minecraft.network.FriendlyByteBuf;
public class FloatArgumentInfo implements ArgumentTypeInfo<FloatArgumentType, FloatArgumentInfo.Template> {
public void serializeToNetwork(FloatArgumentInfo.Template p_235518_, FriendlyByteBuf p_235519_) {
boolean flag = p_235518_.min != -Float.MAX_VALUE;
boolean flag1 = p_235518_.max != Float.MAX_VALUE;
p_235519_.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
if (flag) {
p_235519_.writeFloat(p_235518_.min);
}
if (flag1) {
p_235519_.writeFloat(p_235518_.max);
}
}
public FloatArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf p_235521_) {
byte b0 = p_235521_.readByte();
float f = ArgumentUtils.numberHasMin(b0) ? p_235521_.readFloat() : -Float.MAX_VALUE;
float f1 = ArgumentUtils.numberHasMax(b0) ? p_235521_.readFloat() : Float.MAX_VALUE;
return new FloatArgumentInfo.Template(f, f1);
}
public void serializeToJson(FloatArgumentInfo.Template p_235515_, JsonObject p_235516_) {
if (p_235515_.min != -Float.MAX_VALUE) {
p_235516_.addProperty("min", p_235515_.min);
}
if (p_235515_.max != Float.MAX_VALUE) {
p_235516_.addProperty("max", p_235515_.max);
}
}
public FloatArgumentInfo.Template unpack(FloatArgumentType p_235507_) {
return new FloatArgumentInfo.Template(p_235507_.getMinimum(), p_235507_.getMaximum());
}
public final class Template implements ArgumentTypeInfo.Template<FloatArgumentType> {
final float min;
final float max;
Template(float p_235529_, float p_235530_) {
this.min = p_235529_;
this.max = p_235530_;
}
public FloatArgumentType instantiate(CommandBuildContext p_235533_) {
return FloatArgumentType.floatArg(this.min, this.max);
}
public ArgumentTypeInfo<FloatArgumentType, ?> type() {
return FloatArgumentInfo.this;
}
}
}

View File

@@ -0,0 +1,64 @@
package net.minecraft.commands.synchronization.brigadier;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.commands.synchronization.ArgumentUtils;
import net.minecraft.network.FriendlyByteBuf;
public class IntegerArgumentInfo implements ArgumentTypeInfo<IntegerArgumentType, IntegerArgumentInfo.Template> {
public void serializeToNetwork(IntegerArgumentInfo.Template p_235551_, FriendlyByteBuf p_235552_) {
boolean flag = p_235551_.min != Integer.MIN_VALUE;
boolean flag1 = p_235551_.max != Integer.MAX_VALUE;
p_235552_.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
if (flag) {
p_235552_.writeInt(p_235551_.min);
}
if (flag1) {
p_235552_.writeInt(p_235551_.max);
}
}
public IntegerArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf p_235554_) {
byte b0 = p_235554_.readByte();
int i = ArgumentUtils.numberHasMin(b0) ? p_235554_.readInt() : Integer.MIN_VALUE;
int j = ArgumentUtils.numberHasMax(b0) ? p_235554_.readInt() : Integer.MAX_VALUE;
return new IntegerArgumentInfo.Template(i, j);
}
public void serializeToJson(IntegerArgumentInfo.Template p_235548_, JsonObject p_235549_) {
if (p_235548_.min != Integer.MIN_VALUE) {
p_235549_.addProperty("min", p_235548_.min);
}
if (p_235548_.max != Integer.MAX_VALUE) {
p_235549_.addProperty("max", p_235548_.max);
}
}
public IntegerArgumentInfo.Template unpack(IntegerArgumentType p_235540_) {
return new IntegerArgumentInfo.Template(p_235540_.getMinimum(), p_235540_.getMaximum());
}
public final class Template implements ArgumentTypeInfo.Template<IntegerArgumentType> {
final int min;
final int max;
Template(int p_235562_, int p_235563_) {
this.min = p_235562_;
this.max = p_235563_;
}
public IntegerArgumentType instantiate(CommandBuildContext p_235566_) {
return IntegerArgumentType.integer(this.min, this.max);
}
public ArgumentTypeInfo<IntegerArgumentType, ?> type() {
return IntegerArgumentInfo.this;
}
}
}

View File

@@ -0,0 +1,64 @@
package net.minecraft.commands.synchronization.brigadier;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.LongArgumentType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.commands.synchronization.ArgumentUtils;
import net.minecraft.network.FriendlyByteBuf;
public class LongArgumentInfo implements ArgumentTypeInfo<LongArgumentType, LongArgumentInfo.Template> {
public void serializeToNetwork(LongArgumentInfo.Template p_235584_, FriendlyByteBuf p_235585_) {
boolean flag = p_235584_.min != Long.MIN_VALUE;
boolean flag1 = p_235584_.max != Long.MAX_VALUE;
p_235585_.writeByte(ArgumentUtils.createNumberFlags(flag, flag1));
if (flag) {
p_235585_.writeLong(p_235584_.min);
}
if (flag1) {
p_235585_.writeLong(p_235584_.max);
}
}
public LongArgumentInfo.Template deserializeFromNetwork(FriendlyByteBuf p_235587_) {
byte b0 = p_235587_.readByte();
long i = ArgumentUtils.numberHasMin(b0) ? p_235587_.readLong() : Long.MIN_VALUE;
long j = ArgumentUtils.numberHasMax(b0) ? p_235587_.readLong() : Long.MAX_VALUE;
return new LongArgumentInfo.Template(i, j);
}
public void serializeToJson(LongArgumentInfo.Template p_235581_, JsonObject p_235582_) {
if (p_235581_.min != Long.MIN_VALUE) {
p_235582_.addProperty("min", p_235581_.min);
}
if (p_235581_.max != Long.MAX_VALUE) {
p_235582_.addProperty("max", p_235581_.max);
}
}
public LongArgumentInfo.Template unpack(LongArgumentType p_235573_) {
return new LongArgumentInfo.Template(p_235573_.getMinimum(), p_235573_.getMaximum());
}
public final class Template implements ArgumentTypeInfo.Template<LongArgumentType> {
final long min;
final long max;
Template(long p_235595_, long p_235596_) {
this.min = p_235595_;
this.max = p_235596_;
}
public LongArgumentType instantiate(CommandBuildContext p_235599_) {
return LongArgumentType.longArg(this.min, this.max);
}
public ArgumentTypeInfo<LongArgumentType, ?> type() {
return LongArgumentInfo.this;
}
}
}

View File

@@ -0,0 +1,72 @@
package net.minecraft.commands.synchronization.brigadier;
import com.google.gson.JsonObject;
import com.mojang.brigadier.arguments.StringArgumentType;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
import net.minecraft.network.FriendlyByteBuf;
public class StringArgumentSerializer implements ArgumentTypeInfo<StringArgumentType, StringArgumentSerializer.Template> {
public void serializeToNetwork(StringArgumentSerializer.Template p_235616_, FriendlyByteBuf p_235617_) {
p_235617_.writeEnum(p_235616_.type);
}
public StringArgumentSerializer.Template deserializeFromNetwork(FriendlyByteBuf p_235619_) {
StringArgumentType.StringType stringtype = p_235619_.readEnum(StringArgumentType.StringType.class);
return new StringArgumentSerializer.Template(stringtype);
}
public void serializeToJson(StringArgumentSerializer.Template p_235613_, JsonObject p_235614_) {
String s;
switch (p_235613_.type) {
case SINGLE_WORD:
s = "word";
break;
case QUOTABLE_PHRASE:
s = "phrase";
break;
case GREEDY_PHRASE:
s = "greedy";
break;
default:
throw new IncompatibleClassChangeError();
}
p_235614_.addProperty("type", s);
}
public StringArgumentSerializer.Template unpack(StringArgumentType p_235605_) {
return new StringArgumentSerializer.Template(p_235605_.getType());
}
public final class Template implements ArgumentTypeInfo.Template<StringArgumentType> {
final StringArgumentType.StringType type;
public Template(StringArgumentType.StringType p_235626_) {
this.type = p_235626_;
}
public StringArgumentType instantiate(CommandBuildContext p_235629_) {
StringArgumentType stringargumenttype;
switch (this.type) {
case SINGLE_WORD:
stringargumenttype = StringArgumentType.word();
break;
case QUOTABLE_PHRASE:
stringargumenttype = StringArgumentType.string();
break;
case GREEDY_PHRASE:
stringargumenttype = StringArgumentType.greedyString();
break;
default:
throw new IncompatibleClassChangeError();
}
return stringargumenttype;
}
public ArgumentTypeInfo<StringArgumentType, ?> type() {
return StringArgumentSerializer.this;
}
}
}

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.synchronization.brigadier;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;

View File

@@ -0,0 +1,8 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@FieldsAreNonnullByDefault
package net.minecraft.commands.synchronization;
import javax.annotation.ParametersAreNonnullByDefault;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;