Command work, and Added TileEntityType as a Forge Registry.

This commit is contained in:
LexManos committed 2018-09-15 00:59:19 -07:00
1 parent 3f743887e7
commit b4c23aba8e
22 files changed
+396 -2758

No files matched your search

@@ -23,21 +23,21 @@ import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Queue;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.CommandSource;
import net.minecraft.server.management.PlayerChunkMapEntry;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentBase;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
import net.minecraft.world.storage.SessionLockException;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.WorldWorkerManager.IWorker;
public class ChunkGenWorker implements IWorker
{
private final ICommandSender listener;
private final CommandSource listener;
protected final BlockPos start;
protected final int total;
private final int dim;
@@ -48,7 +48,7 @@ public class ChunkGenWorker implements IWorker
private int genned = 0;
private Boolean keepingLoaded;
public ChunkGenWorker(ICommandSender listener, BlockPos start, int total, int dim, int interval)
public ChunkGenWorker(CommandSource listener, BlockPos start, int total, int dim, int interval)
{
this.listener = listener;
this.start = start;
@@ -85,17 +85,11 @@ public class ChunkGenWorker implements IWorker
return ret;
}
@Deprecated // TODO remove in 1.13
public TextComponentTranslation getStartMessage()
public TextComponentBase getStartMessage(CommandSource sender)
{
return new TextComponentTranslation("commands.forge.gen.start", total, start.getX(), start.getZ(), dim);
}
public TextComponentBase getStartMessage(ICommandSender sender)
{
return TextComponentHelper.createComponentTranslation(sender, "commands.forge.gen.start", total, start.getX(), start.getZ(), dim);
}
@Override
public boolean hasWork()
{
@@ -112,7 +106,7 @@ public class ChunkGenWorker implements IWorker
world = DimensionManager.getWorld(dim);
if (world == null)
{
listener.sendMessage(TextComponentHelper.createComponentTranslation(listener, "commands.forge.gen.dim_fail", dim));
listener.func_197030_a(new TextComponentTranslation("commands.forge.gen.dim_fail", dim), true);
queue.clear();
return false;
}
@@ -124,7 +118,7 @@ public class ChunkGenWorker implements IWorker
if (lastNotifcationTime < System.currentTimeMillis() - 10*1000)
{
listener.sendMessage(TextComponentHelper.createComponentTranslation(listener, "commands.forge.gen.progress", total - queue.size(), total));
listener.func_197030_a(new TextComponentTranslation("commands.forge.gen.progress", total - queue.size(), total), true);
lastNotifcationTime = System.currentTimeMillis();
}
return false;
@@ -142,7 +136,7 @@ public class ChunkGenWorker implements IWorker
if (++lastNotification >= notificationFrequency || lastNotifcationTime < System.currentTimeMillis() - 60*1000)
{
listener.sendMessage(TextComponentHelper.createComponentTranslation(listener, "commands.forge.gen.progress", total - queue.size(), total));
listener.func_197030_a(new TextComponentTranslation("commands.forge.gen.progress", total - queue.size(), total), true);
lastNotification = 0;
lastNotifcationTime = System.currentTimeMillis();
}
@@ -150,27 +144,27 @@ public class ChunkGenWorker implements IWorker
int x = next.getX();
int z = next.getZ();
Chunk target = world.getChunkFromChunkCoords(x, z);
Chunk target = world.getChunk(x, z);
Chunk[] chunks = { target };
if (!target.isTerrainPopulated())
if (!target.isPopulated())
{
// In order for a chunk to populate, The chunks around its bottom right corner need to be loaded.
// So lets load those chunks, but this needs to be done in a certain order to make this trigger.
// So this does load more chunks then it should, and is a hack, but lets go!.
chunks = new Chunk[] {
target,
world.getChunkFromChunkCoords(x + 1, z),
world.getChunkFromChunkCoords(x + 1, z + 1),
world.getChunkFromChunkCoords(x, z + 1),
world.getChunk(x + 1, z),
world.getChunk(x + 1, z + 1),
world.getChunk(x, z + 1),
};
try
{
world.getChunkProvider().chunkLoader.saveChunk(world, target);
}
catch (IOException | MinecraftException e)
catch (IOException | SessionLockException e)
{
listener.sendMessage(TextComponentHelper.createComponentTranslation(listener, "commands.forge.gen.saveerror", e.getMessage()));
listener.func_197030_a(new TextComponentTranslation("commands.forge.gen.saveerror", e.getMessage()), true);
}
genned++;
}
@@ -185,7 +179,7 @@ public class ChunkGenWorker implements IWorker
if (queue.size() == 0)
{
listener.sendMessage(TextComponentHelper.createComponentTranslation(listener, "commands.forge.gen.complete", genned, total, dim));
listener.func_197030_a(new TextComponentTranslation("commands.forge.gen.complete", genned, total, dim), true);
if (keepingLoaded != null && keepingLoaded)
{
DimensionManager.keepDimensionLoaded(dim, false);
@@ -20,49 +20,30 @@
package net.minecraftforge.server.command;
import it.unimi.dsi.fastutil.ints.IntSortedSet;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.DimensionType;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager;
import java.util.Map;
public class CommandDimensions extends CommandBase
import com.mojang.brigadier.builder.ArgumentBuilder;
public class CommandDimensions
{
@Override
public String getName()
static ArgumentBuilder<CommandSource, ?> register()
{
return "dimensions";
}
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.dimensions.usage";
}
@Override
public int getRequiredPermissionLevel()
{
return 0;
}
@Override
public boolean checkPermission(MinecraftServer server, ICommandSender sender)
{
return true;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.dimensions.list"));
for (Map.Entry<DimensionType, IntSortedSet> entry : DimensionManager.getRegisteredDimensions().entrySet())
{
sender.sendMessage(new TextComponentString(entry.getKey().getName() + ": " + entry.getValue()));
}
return Commands.func_197057_a("dimensions")
.requires(cs->cs.func_197034_c(0)) //permission
.executes(ctx -> {
ctx.getSource().func_197030_a(new TextComponentTranslation("commands.forge.dimensions.list"), true);
for (Map.Entry<DimensionType, IntSortedSet> entry : DimensionManager.getRegisteredDimensions().entrySet())
{
ctx.getSource().func_197030_a(new TextComponentString(entry.getKey().getName() + ": " + entry.getValue()), true);
}
return 0;
});
}
}
@@ -29,94 +29,77 @@ import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Maps;
import net.minecraft.command.CommandBase;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.command.arguments.BlockPosArgument;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityType;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
class CommandEntity extends CommandTreeBase
class CommandEntity
{
public CommandEntity()
static ArgumentBuilder<CommandSource, ?> register()
{
addSubcommand(new EntityListCommand());
addSubcommand(new CommandTreeHelp(this));
return Commands.func_197057_a("entity")
.then(EntityListCommand.register()); //TODO: //Kill, spawn, etc..
}
@Override
public String getUsage(ICommandSender sender)
private static class EntityListCommand
{
return "commands.forge.entity.usage";
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public String getName()
{
return "entity";
}
private static class EntityListCommand extends CommandBase
{
@Override
public String getName()
private static final SimpleCommandExceptionType INVALID_FILTER = new SimpleCommandExceptionType(new TextComponentTranslation("commands.forge.entity.list.invalid"));
private static final DynamicCommandExceptionType INVALID_DIMENSION = new DynamicCommandExceptionType(dim -> new TextComponentTranslation("commands.forge.entity.list.invalidworld", dim));
private static final SimpleCommandExceptionType NO_ENTITIES = new SimpleCommandExceptionType(new TextComponentTranslation("commands.forge.entity.list.none"));
static ArgumentBuilder<CommandSource, ?> register()
{
return "list";
return Commands.func_197057_a("list")
.requires(cs->cs.func_197034_c(2)) //permission
.then(Commands.func_197056_a("filter", StringArgumentType.string())
.suggests((ctx, builder) -> ISuggestionProvider.func_197013_a(ForgeRegistries.ENTITIES.getKeys().stream().map(id -> id.toString()), builder))
.then(Commands.func_197056_a("dim", IntegerArgumentType.integer())
.suggests((ctx, builder) -> ISuggestionProvider.func_197013_a(DimensionManager.getIDStream().sorted().map(id -> id.toString()), builder))
.executes(ctx -> execute(ctx.getSource(), StringArgumentType.getString(ctx, "filter"), IntegerArgumentType.getInteger(ctx, "dim")))
)
.executes(ctx -> execute(ctx.getSource(), StringArgumentType.getString(ctx, "filter"), ctx.getSource().func_197023_e().provider.getDimension()))
)
.executes(ctx -> execute(ctx.getSource(), "*", ctx.getSource().func_197023_e().provider.getDimension()));
}
@Override
public int getRequiredPermissionLevel()
private static int execute(CommandSource sender, String filter, int dim) throws CommandException
{
return 2;
}
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.entity.list.usage";
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
String filter = "*";
if (args.length > 0)
{
filter = args[0];
}
final String cleanFilter = filter.replace("?", ".?").replace("*", ".*?");
Set<ResourceLocation> names = EntityList.getEntityNameList().stream().filter(n -> n.toString().matches(cleanFilter)).collect(Collectors.toSet());
Set<ResourceLocation> names = ForgeRegistries.ENTITIES.getKeys().stream().filter(n -> n.toString().matches(cleanFilter)).collect(Collectors.toSet());
if (names.isEmpty())
throw new WrongUsageException("commands.forge.entity.list.invalid");
int dim = args.length > 1 ? parseInt(args[1]) : sender.getEntityWorld().provider.getDimension();
throw INVALID_FILTER.create();
WorldServer world = DimensionManager.getWorld(dim);
if (world == null)
throw new WrongUsageException("commands.forge.entity.list.invalidworld", dim);
throw INVALID_DIMENSION.create(dim);
Map<ResourceLocation, MutablePair<Integer, Map<ChunkPos, Integer>>> list = Maps.newHashMap();
List<Entity> entities = world.loadedEntityList;
entities.forEach(e -> {
ResourceLocation key = EntityList.getKey(e);
MutablePair<Integer, Map<ChunkPos, Integer>> info = list.computeIfAbsent(key, k -> MutablePair.of(0, Maps.newHashMap()));
MutablePair<Integer, Map<ChunkPos, Integer>> info = list.computeIfAbsent(e.func_200600_R().getRegistryName(), k -> MutablePair.of(0, Maps.newHashMap()));
ChunkPos chunk = new ChunkPos(e.getPosition());
info.left++;
info.right.put(chunk, info.right.getOrDefault(chunk, 0) + 1);
@@ -127,25 +110,23 @@ class CommandEntity extends CommandTreeBase
ResourceLocation name = names.iterator().next();
Pair<Integer, Map<ChunkPos, Integer>> info = list.get(name);
if (info == null)
throw new WrongUsageException("commands.forge.entity.list.none");
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.entity.list.single.header", name, info.getLeft()));
throw NO_ENTITIES.create();
sender.func_197030_a(new TextComponentTranslation("commands.forge.entity.list.single.header", name, info.getLeft()), true);
List<Map.Entry<ChunkPos, Integer>> toSort = new ArrayList<>();
toSort.addAll(info.getRight().entrySet());
toSort.sort((a, b) -> {
if (Objects.equals(a.getValue(), b.getValue()))
{
return a.getKey().toString().compareTo(b.getKey().toString());
}
else
{
return b.getValue() - a.getValue();
}
});
long limit = 10;
for (Map.Entry<ChunkPos, Integer> e : toSort)
{
if (limit-- == 0) break;
sender.sendMessage(new TextComponentString(" " + e.getValue() + ": " + e.getKey().x + ", " + e.getKey().z));
sender.func_197030_a(new TextComponentString(" " + e.getValue() + ": " + e.getKey().x + ", " + e.getKey().z), true);
}
}
else
@@ -161,33 +142,19 @@ class CommandEntity extends CommandTreeBase
});
info.sort((a, b) -> {
if (Objects.equals(a.getRight(), b.getRight()))
{
return a.getKey().toString().compareTo(b.getKey().toString());
}
else
{
return b.getRight() - a.getRight();
}
});
if (info.size() == 0)
throw new WrongUsageException("commands.forge.entity.list.none");
throw NO_ENTITIES.create();
int count = info.stream().mapToInt(Pair::getRight).sum();
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.entity.list.multiple.header", count));
info.forEach(e -> sender.sendMessage(new TextComponentString(" " + e.getValue() + ": " + e.getKey())));
sender.func_197030_a(new TextComponentTranslation("commands.forge.entity.list.multiple.header", count), true);
info.forEach(e -> sender.func_197030_a(new TextComponentString(" " + e.getValue() + ": " + e.getKey()), true));
}
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length == 1)
{
String[] entityNames = EntityList.getEntityNameList().stream().map(ResourceLocation::toString).sorted().toArray(String[]::new);
return getListOfStringsMatchingLastWord(args, entityNames);
}
return Collections.emptyList();
}
}
}
@@ -20,72 +20,61 @@
package net.minecraftforge.server.command;
import javax.annotation.Nullable;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import it.unimi.dsi.fastutil.ints.IntSortedSet;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.command.arguments.BlockPosArgument;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.WorldWorkerManager;
class CommandGenerate extends CommandBase
class CommandGenerate
{
@Override
public String getName()
static ArgumentBuilder<CommandSource, ?> register()
{
return "generate";
return Commands.func_197057_a("generate")
.requires(cs->cs.func_197034_c(4)) //permission
.then(Commands.func_197056_a("pos", BlockPosArgument.func_197276_a())
.then(Commands.func_197056_a("count", IntegerArgumentType.integer(1))
.then(Commands.func_197056_a("dim", IntegerArgumentType.integer())
.suggests((ctx, builder) -> ISuggestionProvider.func_197013_a(DimensionManager.getIDStream().sorted().map(id -> id.toString()), builder))
.then(Commands.func_197056_a("interval", IntegerArgumentType.integer())
.executes(ctx -> execute(ctx.getSource(), BlockPosArgument.func_197274_b(ctx, "pos"), getInt(ctx, "count"), getInt(ctx, "dim"), getInt(ctx, "interval")))
)
.executes(ctx -> execute(ctx.getSource(), BlockPosArgument.func_197274_b(ctx, "pos"), getInt(ctx, "count"), getInt(ctx, "dim"), -1))
)
.executes(ctx -> execute(ctx.getSource(), BlockPosArgument.func_197274_b(ctx, "pos"), getInt(ctx, "count"), ctx.getSource().func_197023_e().provider.getDimension(), -1))
)
);
}
@Override
public List<String> getAliases()
private static int getInt(CommandContext<CommandSource> ctx, String name)
{
return Collections.singletonList("gen");
return IntegerArgumentType.getInteger(ctx, name);
}
@Override
public String getUsage(ICommandSender sender)
private static int execute(CommandSource source, BlockPos pos, int count, int dim, int interval) throws CommandException
{
return "commands.forge.gen.usage";
}
BlockPos chunkpos = new BlockPos(pos.getX() >> 4, 0, pos.getZ() >> 4);
@Override
public int getRequiredPermissionLevel()
{
return 4;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
// x y z chunkCount [dim] [interval]
if (args.length < 4)
{
throw new WrongUsageException("commands.forge.gen.usage");
}
BlockPos blockpos = parseBlockPos(sender, args, 0, false);
int count = parseInt(args[3], 10);
int dim = args.length >= 5 ? parseInt(args[4]) : sender.getEntityWorld().provider.getDimension();
int interval = args.length >= 6 ? parseInt(args[5]) : -1;
BlockPos chunkpos = new BlockPos(blockpos.getX() >> 4, 0, blockpos.getZ() >> 4);
ChunkGenWorker worker = new ChunkGenWorker(sender, chunkpos, count, dim, interval);
sender.sendMessage(worker.getStartMessage(sender));
ChunkGenWorker worker = new ChunkGenWorker(source, chunkpos, count, dim, interval);
source.func_197030_a(worker.getStartMessage(source), true);
WorldWorkerManager.addWorker(worker);
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length < 4)
{
return getTabCompletionCoordinate(args, 0, targetPos);
}
// Chunk Count? No completion
// Dimension, Add support for names? Get list of ids? Meh
return Collections.emptyList();
}
}
@@ -21,85 +21,76 @@ package net.minecraftforge.server.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.command.WrongUsageException;
import net.minecraft.command.arguments.BlockPosArgument;
import net.minecraft.command.arguments.EntityArgument;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.util.ITeleporter;
import javax.annotation.Nullable;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import it.unimi.dsi.fastutil.ints.IntSortedSet;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class CommandSetDimension extends CommandBase
public class CommandSetDimension
{
@Override
public String getName()
private static final SimpleCommandExceptionType NO_ENTITIES = new SimpleCommandExceptionType(new TextComponentTranslation("commands.forge.setdim.invalid.entity"));
private static final DynamicCommandExceptionType INVALID_DIMENSION = new DynamicCommandExceptionType(dim -> new TextComponentTranslation("commands.forge.setdim.invalid.dim", dim));
static ArgumentBuilder<CommandSource, ?> register()
{
return "setdimension";
return Commands.func_197057_a("setdimension")
.requires(cs->cs.func_197034_c(2)) //permission
.then(Commands.func_197056_a("targets", EntityArgument.func_197093_b())
.then(Commands.func_197056_a("dim", IntegerArgumentType.integer())
.suggests((ctx, builder) -> ISuggestionProvider.func_197013_a(DimensionManager.getIDStream().sorted().map(id -> id.toString()), builder))
.then(Commands.func_197056_a("pos", BlockPosArgument.func_197276_a())
.executes(ctx -> execute(ctx.getSource(), EntityArgument.func_197087_c(ctx, "targets"), IntegerArgumentType.getInteger(ctx, "dim"), BlockPosArgument.func_197274_b(ctx, "pos")))
)
.executes(ctx -> execute(ctx.getSource(), EntityArgument.func_197087_c(ctx, "targets"), IntegerArgumentType.getInteger(ctx, "dim"), new BlockPos(ctx.getSource().func_197036_d())))
)
);
}
@Override
public List<String> getAliases()
private static int execute(CommandSource sender, Collection<? extends Entity> entities, int dim, BlockPos pos) throws CommandException
{
return Collections.singletonList("setdim");
}
entities.removeIf(CommandSetDimension::checkEntity);
if (entities.isEmpty())
throw NO_ENTITIES.create();
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.setdim.usage";
}
if (!DimensionManager.isDimensionRegistered(dim))
throw INVALID_DIMENSION.create(dim);
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length > 2 && args.length <= 5)
{
return getTabCompletionCoordinate(args, 2, targetPos);
}
return Collections.emptyList();
}
final ITeleporter teleporter = new CommandTeleporter(pos);
entities.stream().filter(e -> e.dimension == dim).forEach(e -> sender.func_197030_a(new TextComponentTranslation("commands.forge.setdim.invalid.nochange", e.getDisplayName(), dim), true));
entities.stream().filter(e -> e.dimension != dim).forEach(e -> e.changeDimension(dim, teleporter));
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
// args: <entity> <dim> [<x> <y> <z>]
if (args.length != 2 && args.length != 5)
{
throw new WrongUsageException("commands.forge.setdim.usage");
}
Entity entity = getEntity(server, sender, args[0]);
if (!checkEntity(entity))
{
throw new CommandException("commands.forge.setdim.invalid.entity", entity.getName());
}
int dimension = parseInt(args[1]);
if (!DimensionManager.isDimensionRegistered(dimension))
{
throw new CommandException("commands.forge.setdim.invalid.dim", dimension);
}
if (dimension == entity.dimension)
{
throw new CommandException("commands.forge.setdim.invalid.nochange", entity.getName(), dimension);
}
BlockPos pos = args.length == 5 ? parseBlockPos(sender, args, 2, false) : sender.getPosition();
entity.changeDimension(dimension, new CommandTeleporter(pos));
return 0;
}
private static boolean checkEntity(Entity entity)
{
// use vanilla portal logic, try to avoid doing anything too silly
return !entity.isRiding() && !entity.isBeingRidden() && entity.isNonBoss();
return entity.isRiding() || entity.isBeingRidden() || entity.isNonBoss();
}
private static class CommandTeleporter implements ITeleporter
@@ -20,93 +20,74 @@
package net.minecraftforge.server.command;
import java.text.DecimalFormat;
import java.util.stream.Collectors;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.DimensionType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager;
class CommandTps extends CommandBase
class CommandTps
{
private static final DynamicCommandExceptionType INVALID_DIMENSION = new DynamicCommandExceptionType(dim -> new TextComponentTranslation("commands.forge.tps.invalid", dim, DimensionManager.getIDStream().sorted().map(id -> id.toString()).collect(Collectors.joining(", "))));
private static final DecimalFormat TIME_FORMATTER = new DecimalFormat("########0.000");
@Override
public String getName()
static ArgumentBuilder<CommandSource, ?> register()
{
return "tps";
}
return Commands.func_197057_a("tps")
.requires(cs->cs.func_197034_c(0)) //permission
.then(Commands.func_197056_a("dim", IntegerArgumentType.integer())
.suggests((ctx, builder) -> ISuggestionProvider.func_197013_a(DimensionManager.getIDStream().sorted().map(id -> id.toString()), builder))
.executes(ctx -> sendTime(ctx.getSource(), IntegerArgumentType.getInteger(ctx, "dim")))
)
.executes(ctx -> {
for (Integer dim : (Iterable<Integer>)DimensionManager.getIDStream().sorted()::iterator)
sendTime(ctx.getSource(), dim);
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.tps.usage";
}
double meanTickTime = mean(ctx.getSource().func_197028_i().tickTimeArray) * 1.0E-6D;
double meanTPS = Math.min(1000.0/meanTickTime, 20);
ctx.getSource().func_197030_a(new TextComponentTranslation("commands.forge.tps.summary.all", TIME_FORMATTER.format(meanTickTime), TIME_FORMATTER.format(meanTPS)), true);
@Override
public int getRequiredPermissionLevel()
{
return 0;
}
@Override
public boolean checkPermission(MinecraftServer server, ICommandSender sender)
{
return true;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
int dim = 0;
boolean summary = true;
if (args.length > 0)
{
dim = parseInt(args[0]);
summary = false;
}
if (summary)
{
for (Integer dimId : DimensionManager.getIDs())
{
double worldTickTime = mean(server.worldTickTimes.get(dimId)) * 1.0E-6D;
double worldTPS = Math.min(1000.0/worldTickTime, 20);
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tps.summary", getDimensionPrefix(dimId), TIME_FORMATTER.format(worldTickTime), TIME_FORMATTER.format(worldTPS)));
return 0;
}
double meanTickTime = mean(server.tickTimeArray) * 1.0E-6D;
double meanTPS = Math.min(1000.0/meanTickTime, 20);
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tps.summary","Overall", TIME_FORMATTER.format(meanTickTime), TIME_FORMATTER.format(meanTPS)));
}
else
{
double worldTickTime = mean(server.worldTickTimes.get(dim)) * 1.0E-6D;
double worldTPS = Math.min(1000.0/worldTickTime, 20);
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tps.summary", getDimensionPrefix(dim), TIME_FORMATTER.format(worldTickTime), TIME_FORMATTER.format(worldTPS)));
}
);
}
private static String getDimensionPrefix(int dimId)
private static long[] getTimes(int dim)
{
DimensionType providerType = DimensionManager.getProviderType(dimId);
if (providerType == null)
{
return String.format("Dim %2d", dimId);
}
//TODO: Implement, needs patch.
return null;
}
private static int sendTime(CommandSource cs, int dim) throws CommandSyntaxException
{
long[] times = getTimes(dim);
if (times == null)
throw INVALID_DIMENSION.create(dim);
double worldTickTime = mean(times) * 1.0E-6D;
double worldTPS = Math.min(1000.0 / worldTickTime, 20);
DimensionType type = DimensionManager.getProviderType(dim);
if (type == null)
cs.func_197030_a(new TextComponentTranslation("commands.forge.tps.summary.basic", dim, TIME_FORMATTER.format(worldTickTime), TIME_FORMATTER.format(worldTPS)), true);
else
{
return String.format("Dim %2d (%s)", dimId, providerType.getName());
}
cs.func_197030_a(new TextComponentTranslation("commands.forge.tps.summary.named", dim, type.getName(), TIME_FORMATTER.format(worldTickTime), TIME_FORMATTER.format(worldTPS)), true);
return 1;
}
private static long mean(long[] values)
{
long sum = 0L;
for (long v : values)
{
sum += v;
}
return sum / values.length;
}
}
@@ -20,187 +20,114 @@
package net.minecraftforge.server.command;
import javax.annotation.Nullable;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.ISuggestionProvider;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.DimensionType;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.server.timings.ForgeTimings;
import net.minecraftforge.server.timings.TimeTracker;
class CommandTrack extends CommandTreeBase
class CommandTrack
{
private static final DecimalFormat TIME_FORMAT = new DecimalFormat("#####0.00");
public CommandTrack()
static ArgumentBuilder<CommandSource, ?> register()
{
addSubcommand(new StartTrackingCommand());
addSubcommand(new ResetTrackingCommand());
addSubcommand(new TrackResultsTileEntity());
addSubcommand(new TrackResultsEntity());
addSubcommand(new CommandTreeHelp(this));
return Commands.func_197057_a("track")
.then(StartTrackingCommand.register())
.then(ResetTrackingCommand.register())
.then(TrackResultsEntity.register())
.then(TrackResultsTileEntity.register())
.then(StartTrackingCommand.register());
}
@Override
public String getName()
private static class StartTrackingCommand
{
return "track";
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.tracking.usage";
}
private static class StartTrackingCommand extends CommandBase
{
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
static ArgumentBuilder<CommandSource, ?> register()
{
if (args.length != 2)
{
throw new WrongUsageException(getUsage(sender));
}
String type = args[0];
int duration = parseInt(args[1], 1, 60);
if ("te".equals(type))
{
TimeTracker.TILE_ENTITY_UPDATE.reset();
TimeTracker.TILE_ENTITY_UPDATE.enable(duration);
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.te.enabled", duration));
}
else if ("entity".equals(type))
{
TimeTracker.ENTITY_UPDATE.reset();
TimeTracker.ENTITY_UPDATE.enable(duration);
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.entity.enabled", duration));
}
else
{
throw new WrongUsageException(getUsage(sender));
}
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
return Arrays.asList("te", "entity");
}
@Override
public String getName()
{
return "start";
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.tracking.start.usage";
return Commands.func_197057_a("start")
.requires(cs->cs.func_197034_c(2)) //permission
.then(Commands.func_197057_a("te")
.then(Commands.func_197056_a("duration", IntegerArgumentType.integer(1))
.executes(ctx -> {
int duration = IntegerArgumentType.getInteger(ctx, "duration");
TimeTracker.TILE_ENTITY_UPDATE.reset();
TimeTracker.TILE_ENTITY_UPDATE.enable(duration);
ctx.getSource().func_197030_a(new TextComponentTranslation("commands.forge.tracking.te.enabled", duration), true);
return 0;
})
)
)
.then(Commands.func_197057_a("entity")
.then(Commands.func_197056_a("duration", IntegerArgumentType.integer(1))
.executes(ctx -> {
int duration = IntegerArgumentType.getInteger(ctx, "duration");
TimeTracker.ENTITY_UPDATE.reset();
TimeTracker.ENTITY_UPDATE.enable(duration);
ctx.getSource().func_197030_a(new TextComponentTranslation("commands.forge.tracking.entity.enabled", duration), true);
return 0;
})
)
);
}
}
private static class ResetTrackingCommand extends CommandBase
private static class ResetTrackingCommand
{
@Override
public String getName()
static ArgumentBuilder<CommandSource, ?> register()
{
return "reset";
}
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.tracking.reset.usage";
}
@Override
public int getRequiredPermissionLevel()
{
return 2;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
if (args.length != 1)
{
throw new WrongUsageException(getUsage(sender));
}
String type = args[0];
if ("te".equals(type))
{
TimeTracker.TILE_ENTITY_UPDATE.reset();
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.reset"));
}
else if ("entity".equals(type))
{
TimeTracker.ENTITY_UPDATE.reset();
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.reset"));
}
else
{
throw new WrongUsageException(getUsage(sender));
}
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
return Arrays.asList("te", "entity");
return Commands.func_197057_a("reset")
.requires(cs->cs.func_197034_c(2)) //permission
.then(Commands.func_197057_a("te")
.executes(ctx -> {
TimeTracker.TILE_ENTITY_UPDATE.reset();
ctx.getSource().func_197030_a(new TextComponentTranslation("commands.forge.tracking.te.reset"), true);
return 0;
})
)
.then(Commands.func_197057_a("entity")
.executes(ctx -> {
TimeTracker.ENTITY_UPDATE.reset();
ctx.getSource().func_197030_a(new TextComponentTranslation("commands.forge.tracking.entity.reset"), true);
return 0;
})
);
}
}
/**
* A base command for all the tracking results commands
*
* @param <T>
*/
private static abstract class TrackResultsBaseCommand<T> extends CommandBase
private static class TrackResults
{
private TimeTracker<T> tracker;
protected TrackResultsBaseCommand(TimeTracker<T> tracker)
{
this.tracker = tracker;
}
/**
* Returns the time objects recorded by the time tracker sorted by average time
*
* @return A list of time objects
*/
protected List<ForgeTimings<T>> getSortedTimings()
private static <T> List<ForgeTimings<T>> getSortedTimings(TimeTracker<T> tracker)
{
ArrayList<ForgeTimings<T>> list = new ArrayList<>();
@@ -211,42 +138,21 @@ class CommandTrack extends CommandTreeBase
return list;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
private static <T> int execute(CommandSource source, TimeTracker<T> tracker, Function<ForgeTimings<T>, ITextComponent> toString) throws CommandException
{
List<ForgeTimings<T>> timingsList = getSortedTimings();
List<ForgeTimings<T>> timingsList = getSortedTimings(tracker);
if (timingsList.isEmpty())
{
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.noData"));
source.func_197030_a(new TextComponentTranslation("commands.forge.tracking.no_data"), true);
}
else
{
timingsList.stream()
.filter(timings -> timings.getObject().get() != null)
.limit(10)
.forEach(timings -> sender.sendMessage(buildTrackString(sender, timings))
);
}
}
protected abstract ITextComponent buildTrackString(ICommandSender sender, ForgeTimings<T> data);
/**
* Gets the time suffix for the provided time in nanoseconds
*
* @param time The time in nanoseconds
* @return The time suffix
*/
protected String getTimeSuffix(double time)
{
if (time < 1000)
{
return "µs";
}
else
{
return "ms";
.forEach(timings -> source.func_197030_a(toString.apply(timings), true));
}
return 0;
}
/**
@@ -255,105 +161,53 @@ class CommandTrack extends CommandTreeBase
* @param dimId The dimension ID
* @return The name of the dimension
*/
protected String getWorldName(int dimId)
protected static String getWorldName(int dimId)
{
DimensionType type = DimensionManager.getProviderType(dimId);
if (type == null)
{
return "Dim " + dimId;
}
else
{
return type.getName();
}
}
}
private static class TrackResultsEntity extends TrackResultsBaseCommand<Entity>
private static class TrackResultsEntity
{
public TrackResultsEntity()
static ArgumentBuilder<CommandSource, ?> register()
{
super(TimeTracker.ENTITY_UPDATE);
}
return Commands.func_197057_a("entity").executes(ctx -> TrackResults.execute(ctx.getSource(), TimeTracker.ENTITY_UPDATE, data ->
{
Entity entity = data.getObject().get();
if (entity == null)
return new TextComponentTranslation("commands.forge.tracking.invalid");
@Override
public String getName()
{
return "entity";
}
BlockPos pos = entity.getPosition();
double averageTimings = data.getAverageTimings();
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + (averageTimings < 1000 ? "µs" : "ms");
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.tracking.entity.usage";
}
@Override
protected ITextComponent buildTrackString(ICommandSender sender, ForgeTimings<Entity> data)
{
Entity entity = data.getObject().get();
if (entity == null)
return TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.invalid");
BlockPos currentPos = entity.getPosition();
String world = getWorldName(entity.world.provider.getDimension());
double averageTimings = data.getAverageTimings();
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + getTimeSuffix(
averageTimings);
return TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.timingEntry", entity.getName(),
world, currentPos.getX(), currentPos.getY(), currentPos.getZ(), tickTime);
return new TextComponentTranslation("commands.forge.tracking.timing_entry", entity.func_200600_R().getRegistryName(), TrackResults.getWorldName(entity.world.provider.getDimension()), pos.getX(), pos.getY(), pos.getZ(), tickTime);
})
);
}
}
private static class TrackResultsTileEntity extends TrackResultsBaseCommand<TileEntity>
private static class TrackResultsTileEntity
{
public TrackResultsTileEntity()
static ArgumentBuilder<CommandSource, ?> register()
{
super(TimeTracker.TILE_ENTITY_UPDATE);
}
return Commands.func_197057_a("te").executes(ctx -> TrackResults.execute(ctx.getSource(), TimeTracker.TILE_ENTITY_UPDATE, data ->
{
TileEntity te = data.getObject().get();
if (te == null)
return new TextComponentTranslation("commands.forge.tracking.invalid");
@Override
public String getName()
{
return "te";
}
BlockPos pos = te.getPos();
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.tracking.te.usage";
}
@Override
protected ITextComponent buildTrackString(ICommandSender sender, ForgeTimings<TileEntity> data)
{
TileEntity te = data.getObject().get();
if (te == null)
return TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.invalid");
String name = getTileEntityName(te);
BlockPos pos = te.getPos();
double averageTimings = data.getAverageTimings();
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + getTimeSuffix(
averageTimings);
return TextComponentHelper
.createComponentTranslation(sender, "commands.forge.tracking.timingEntry", name,
getWorldName(te.getWorld().provider.getDimension()),
pos.getX(), pos.getY(), pos.getZ(), tickTime);
}
private String getTileEntityName(TileEntity tileEntity)
{
ResourceLocation registryId = TileEntity.getKey(tileEntity.getClass());
if (registryId == null)
return tileEntity.getClass().getSimpleName();
else
{
return registryId.toString();
}
double averageTimings = data.getAverageTimings();
String tickTime = (averageTimings > 1000 ? TIME_FORMAT.format(averageTimings / 1000) : TIME_FORMAT.format(averageTimings)) + (averageTimings < 1000 ? "µs" : "ms");
return new TextComponentTranslation("commands.forge.tracking.timing_entry", te.func_200662_C().getRegistryName(), TrackResults.getWorldName(te.getWorld().provider.getDimension()), pos.getX(), pos.getY(), pos.getZ(), tickTime);
})
);
}
}
}
@@ -1,181 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.server.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Base class for commands that has subcommands.
* <p>
* E.g. /team settings set [value]
* settings is subcommand of team and set is subcommand of settings
*/
public abstract class CommandTreeBase extends CommandBase
{
private final Map<String, ICommand> commandMap = new HashMap<>();
private final Map<String, ICommand> commandAliasMap = new HashMap<>();
public void addSubcommand(ICommand command)
{
commandMap.put(command.getName(), command);
for (String alias : command.getAliases())
{
commandAliasMap.put(alias, command);
}
}
public Collection<ICommand> getSubCommands()
{
return commandMap.values();
}
@Nullable
public ICommand getSubCommand(String command)
{
ICommand cmd = commandMap.get(command);
if (cmd != null)
{
return cmd;
}
return commandAliasMap.get(command);
}
public Map<String, ICommand> getCommandMap()
{
return Collections.unmodifiableMap(commandMap);
}
public List<ICommand> getSortedCommandList()
{
List<ICommand> list = new ArrayList<>(getSubCommands());
Collections.sort(list);
return list;
}
private static String[] shiftArgs(@Nullable String[] s)
{
if(s == null || s.length == 0)
{
return new String[0];
}
String[] s1 = new String[s.length - 1];
System.arraycopy(s, 1, s1, 0, s1.length);
return s1;
}
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos pos)
{
if(args.length == 1)
{
List<String> keys = new ArrayList<>();
for (ICommand c : getSubCommands())
{
if(c.checkPermission(server, sender))
{
keys.add(c.getName());
}
}
keys.sort(null);
return getListOfStringsMatchingLastWord(args, keys);
}
ICommand cmd = getSubCommand(args[0]);
if(cmd != null)
{
return cmd.getTabCompletions(server, sender, shiftArgs(args), pos);
}
return super.getTabCompletions(server, sender, args, pos);
}
@Override
public boolean isUsernameIndex(String[] args, int index)
{
if (index > 0 && args.length > 1)
{
ICommand cmd = getSubCommand(args[0]);
if (cmd != null)
{
return cmd.isUsernameIndex(shiftArgs(args), index - 1);
}
}
return false;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
if (args.length < 1)
{
String subCommandsString = getAvailableSubCommandsString(server, sender);
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.tree_base.available_subcommands", subCommandsString));
}
else
{
ICommand cmd = getSubCommand(args[0]);
if(cmd == null)
{
String subCommandsString = getAvailableSubCommandsString(server, sender);
throw new CommandException("commands.tree_base.invalid_cmd.list_subcommands", args[0], subCommandsString);
}
else if(!cmd.checkPermission(server, sender))
{
throw new CommandException("commands.generic.permission");
}
else
{
cmd.execute(server, sender, shiftArgs(args));
}
}
}
private String getAvailableSubCommandsString(MinecraftServer server, ICommandSender sender)
{
Collection<String> availableCommands = new ArrayList<>();
for (ICommand command : getSubCommands())
{
if (command.checkPermission(server, sender))
{
availableCommands.add(command.getName());
}
}
return CommandBase.joinNiceStringFromCollection(availableCommands);
}
}
@@ -1,122 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.server.command;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
/**
* Add help for parent and all its children.
* Must be added to parent after all other commands.
*/
public class CommandTreeHelp extends CommandTreeBase
{
private final ICommand parent;
public CommandTreeHelp(CommandTreeBase parent)
{
this.parent = parent;
for (ICommand command : parent.getSubCommands())
{
addSubcommand(new HelpSubCommand(this, command));
}
}
@Override
public int getRequiredPermissionLevel()
{
return 0;
}
@Override
public String getName()
{
return "help";
}
@Override
public String getUsage(ICommandSender sender)
{
return "commands.forge.usage.help";
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
if (args.length == 0)
{
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, parent.getUsage(sender)));
for (ICommand subCommand : getSubCommands())
{
if (subCommand instanceof HelpSubCommand && subCommand.checkPermission(server, sender))
{
subCommand.execute(server, sender, args);
}
}
return;
}
super.execute(server, sender, args);
}
public static class HelpSubCommand extends CommandBase
{
private final CommandTreeHelp parent;
private final ICommand command;
public HelpSubCommand(CommandTreeHelp parent, ICommand command)
{
this.parent = parent;
this.command = command;
}
@Override
public int getRequiredPermissionLevel()
{
return 0;
}
@Override
public String getName()
{
return command.getName();
}
@Override
public String getUsage(ICommandSender sender)
{
return command.getUsage(sender);
}
@Override
public boolean checkPermission(MinecraftServer server, ICommandSender sender)
{
return command.checkPermission(server, sender);
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, command.getUsage(sender)));
}
}
}
@@ -22,24 +22,19 @@ package net.minecraftforge.server.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.command.CommandSource;
import net.minecraft.util.text.TextComponentString;
public class ForgeCommand
{
public ForgeCommand(CommandDispatcher<CommandSource> dispatcher)
{
dispatcher.register(LiteralArgumentBuilder.<CommandSource>literal("forge").
requires(cs->cs.func_197034_c(2)).
then(LiteralArgumentBuilder.literal("tps")).
executes(c->{c.getSource().func_197021_a(new TextComponentString("command.forge.tps.summary")); return 1;}));
/*
super.addSubcommand(new CommandTps());
super.addSubcommand(new CommandTrack());
super.addSubcommand(new CommandGenerate());
super.addSubcommand(new CommandEntity());
super.addSubcommand(new CommandSetDimension());
super.addSubcommand(new CommandDimensions());
super.addSubcommand(new CommandTreeHelp(this));
*/
dispatcher.register(
LiteralArgumentBuilder.<CommandSource>literal("forge")
.then(CommandTps.register())
.then(CommandTrack.register())
.then(CommandEntity.register())
.then(CommandGenerate.register())
.then(CommandDimensions.register())
.then(CommandSetDimension.register())
);
}
}