Small cleanup

This commit is contained in:
themode 2020-10-29 22:52:07 +01:00
parent c887392a91
commit 872dccd7ce
26 changed files with 111 additions and 93 deletions

View File

@ -60,20 +60,20 @@ public abstract class BasicEnumGenerator extends MinestomEnumGenerator<BasicEnum
ParameterSpec[] signature = new ParameterSpec[]{idParam};
if (linear) {
generator.addStaticMethod("fromId", signature, className, code -> {
code.beginControlFlow("if($N >= 0 && $N < values().length)", idParam, idParam)
.addStatement("return values()[$N]", idParam)
.endControlFlow()
.addStatement("return " + (defaultEntry == null ? "null" : identifier(defaultEntry)));
code.beginControlFlow("if($N >= 0 && $N < values().length)", idParam, idParam)
.addStatement("return values()[$N]", idParam)
.endControlFlow()
.addStatement("return " + (defaultEntry == null ? "null" : identifier(defaultEntry)));
}
);
} else {
generator.addStaticMethod("fromId", signature, className, code -> {
code.beginControlFlow("for($T o : values())")
.beginControlFlow("if(o.getId() == id)")
.addStatement("return o")
.endControlFlow()
.endControlFlow()
.addStatement("return " + (defaultEntry == null ? "null" : identifier(defaultEntry)));
code.beginControlFlow("for($T o : values())")
.beginControlFlow("if(o.getId() == id)")
.addStatement("return o")
.endControlFlow()
.endControlFlow()
.addStatement("return " + (defaultEntry == null ? "null" : identifier(defaultEntry)));
}
);
}

View File

@ -108,10 +108,12 @@ public class Command {
*
* @param executor the executor to call when the syntax is successfully received
* @param args all the arguments of the syntax
* @return the created {@link CommandSyntax}
*/
public void addSyntax(@NotNull CommandExecutor executor, @NotNull Argument<?>... args) {
public CommandSyntax addSyntax(@NotNull CommandExecutor executor, @NotNull Argument<?>... args) {
final CommandSyntax syntax = new CommandSyntax(executor, args);
this.syntaxes.add(syntax);
return syntax;
}
/**
@ -126,10 +128,8 @@ public class Command {
/**
* Gets the command's aliases.
* <p>
* Can be null or empty.
*
* @return the command aliases
* @return the command aliases, can be null or empty
*/
@Nullable
public String[] getAliases() {
@ -137,10 +137,10 @@ public class Command {
}
/**
* Gets the default {@link CommandExecutor} (which is called when there is no argument)
* Gets the default {@link CommandExecutor} which is called when there is no argument
* or if no corresponding syntax has been found.
*
* @return the default executor
* @return the default executor, null if not any
*/
@Nullable
public CommandExecutor getDefaultExecutor() {
@ -150,7 +150,7 @@ public class Command {
/**
* Sets the default {@link CommandExecutor} (which is called when there is no argument).
*
* @param executor the new default executor
* @param executor the new default executor, null to remove it
*/
public void setDefaultExecutor(@Nullable CommandExecutor executor) {
this.defaultExecutor = executor;

View File

@ -106,7 +106,7 @@ public class CommandDispatcher {
TreeMap<Integer, CommandSuggestionHolder> syntaxesSuggestions = new TreeMap<>(Collections.reverseOrder());
for (CommandSyntax syntax : syntaxes) {
final Argument<Object>[] arguments = syntax.getArguments();
final Argument<?>[] arguments = syntax.getArguments();
final String[] argsValues = new String[arguments.length];
boolean syntaxCorrect = true;
@ -115,7 +115,7 @@ public class CommandDispatcher {
boolean useRemaining = false;
// Check the validity of the arguments...
for (int argCount = 0; argCount < syntax.getArguments().length; argCount++) {
final Argument<Object> argument = syntax.getArguments()[argCount];
final Argument<?> argument = syntax.getArguments()[argCount];
useRemaining = argument.useRemaining();
// the correction result of the argument
@ -200,10 +200,10 @@ public class CommandDispatcher {
// Otherwise, search for the first syntax with an incorrect argument
for (CommandSyntax syntax : validSyntaxes) {
final Argument<Object>[] arguments = syntax.getArguments();
final Argument[] arguments = syntax.getArguments();
final String[] argsValues = syntaxesValues.get(syntax);
for (int i = 0; i < arguments.length; i++) {
final Argument<Object> argument = arguments[i];
final Argument argument = arguments[i];
final String argValue = argsValues[i];
// Finally parse it
final Object parsedValue = argument.parse(argValue);
@ -239,7 +239,7 @@ public class CommandDispatcher {
final int argIndex = suggestionHolder.argIndex;
// Found the closest syntax with at least 1 correct argument
final Argument<Object> argument = syntax.getArguments()[argIndex];
final Argument<?> argument = syntax.getArguments()[argIndex];
if (argument.hasErrorCallback()) {
result.callback = argument.getCallback();
result.value = argValue;
@ -279,10 +279,10 @@ public class CommandDispatcher {
Arguments syntaxValues = new Arguments();
boolean fullyCorrect = true;
final Argument<Object>[] arguments = syntax.getArguments();
final Argument<?>[] arguments = syntax.getArguments();
final String[] argsValues = syntaxesValues.get(syntax);
for (int i = 0; i < arguments.length; i++) {
final Argument<Object> argument = arguments[i];
final Argument argument = arguments[i];
final String argValue = argsValues[i];
// Finally parse it
final Object parsedValue = argument.parse(argValue);

View File

@ -4,14 +4,15 @@ import net.minestom.server.command.builder.arguments.Argument;
import org.jetbrains.annotations.NotNull;
/**
* Represents a syntax in {@link Command}.
* Represents a syntax in {@link Command}
* which is initialized with {@link Command#addSyntax(CommandExecutor, Argument[])}.
*/
public class CommandSyntax {
private final Argument[] args;
private final Argument<?>[] args;
private CommandExecutor executor;
protected CommandSyntax(@NotNull CommandExecutor commandExecutor, @NotNull Argument... args) {
protected CommandSyntax(@NotNull CommandExecutor commandExecutor, @NotNull Argument<?>... args) {
this.executor = commandExecutor;
this.args = args;
}
@ -22,7 +23,7 @@ public class CommandSyntax {
* @return the required arguments
*/
@NotNull
public Argument<Object>[] getArguments() {
public Argument<?>[] getArguments() {
return args;
}

View File

@ -112,7 +112,7 @@ public abstract class Argument<T> {
/**
* Gets the {@link ArgumentCallback} to check if the argument-specific conditions are validated or not.
*
* @return the argument callback
* @return the argument callback, null if not any
*/
@Nullable
public ArgumentCallback getCallback() {
@ -122,7 +122,7 @@ public abstract class Argument<T> {
/**
* Sets the {@link ArgumentCallback}.
*
* @param callback the argument callback
* @param callback the argument callback, null to do not have one
*/
public void setCallback(@Nullable ArgumentCallback callback) {
this.callback = callback;

View File

@ -37,8 +37,7 @@ public class ArgumentNbtTag extends Argument<NBT> {
@Override
public NBT parse(@NotNull String value) {
try {
NBT nbt = new SNBTParser(new StringReader(value)).parse();
return nbt;
return new SNBTParser(new StringReader(value)).parse();
} catch (NBTException e) {
return null;
}

View File

@ -648,9 +648,9 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer {
/**
* Convenient method to get the entity current chunk.
*
* @return the entity chunk
* @return the entity chunk, can be null even if unlikely
*/
@NotNull
@Nullable
public Chunk getChunk() {
return instance.getChunkAt(lastX, lastZ);
}

View File

@ -144,7 +144,7 @@ public abstract class EntityCreature extends LivingEntity {
}
@Override
public void setInstance(Instance instance) {
public void setInstance(@NotNull Instance instance) {
super.setInstance(instance);
this.pathFinder = new HydrazinePathFinder(pathingEntity, instance.getInstanceSpace());
}
@ -224,7 +224,7 @@ public abstract class EntityCreature extends LivingEntity {
}
/**
* Changes the entity target
* Changes the entity target.
*
* @param target the new entity target
*/

View File

@ -7,6 +7,7 @@ import net.minestom.server.entity.ai.TargetSelector;
import net.minestom.server.instance.Chunk;
import net.minestom.server.instance.Instance;
import net.minestom.server.utils.chunk.ChunkUtils;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@ -17,11 +18,11 @@ import java.util.Set;
*/
public class ClosestEntityTarget extends TargetSelector {
private float range;
private Class<? extends LivingEntity>[] entitiesTarget;
private final float range;
private final Class<? extends LivingEntity>[] entitiesTarget;
public ClosestEntityTarget(EntityCreature entityCreature, float range,
Class<? extends LivingEntity>... entitiesTarget) {
public ClosestEntityTarget(@NotNull EntityCreature entityCreature, float range,
@NotNull Class<? extends LivingEntity>... entitiesTarget) {
super(entityCreature);
this.range = range;
this.entitiesTarget = entitiesTarget;
@ -31,6 +32,10 @@ public class ClosestEntityTarget extends TargetSelector {
public Entity findTarget() {
final Instance instance = getEntityCreature().getInstance();
final Chunk currentChunk = instance.getChunkAt(entityCreature.getPosition());
if (currentChunk == null) {
return null;
}
final List<Chunk> chunks = getNeighbours(instance, currentChunk.getChunkX(), currentChunk.getChunkZ());
Entity entity = null;

View File

@ -56,7 +56,7 @@ public class EntityGuardian extends EntityCreature implements Monster {
return target;
}
public void setTarget(Entity target) {
public void setTarget(@NotNull Entity target) {
this.target = target;
}
}

View File

@ -4,6 +4,7 @@ import net.minestom.server.chat.RichMessage;
import net.minestom.server.entity.Player;
import net.minestom.server.event.CancellableEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
@ -29,9 +30,9 @@ public class PlayerChatEvent extends CancellableEvent {
/**
* Changes the chat format.
*
* @param chatFormat the custom chat format
* @param chatFormat the custom chat format, null to use the default one
*/
public void setChatFormat(@NotNull Function<PlayerChatEvent, RichMessage> chatFormat) {
public void setChatFormat(@Nullable Function<PlayerChatEvent, RichMessage> chatFormat) {
this.chatFormat = chatFormat;
}
@ -81,9 +82,9 @@ public class PlayerChatEvent extends CancellableEvent {
* <p>
* If null, the default format will be used.
*
* @return the chat format which will be used
* @return the chat format which will be used, null if this is the default one
*/
@NotNull
@Nullable
public Function<PlayerChatEvent, RichMessage> getChatFormatFunction() {
return chatFormat;
}

View File

@ -28,7 +28,7 @@ class LootTableContainer {
return new LootTable(type, pools);
}
private class Pool {
private static class Pool {
private ConditionContainer[] conditions;
private FunctionContainer[] functions;
private RangeContainer rolls;

View File

@ -31,6 +31,7 @@ public final class LootTableManager {
/**
* Registers a condition factory to the given namespaceID
*
* @param namespaceID
* @param factory
*/
@ -40,6 +41,7 @@ public final class LootTableManager {
/**
* Registers a loot table type to the given namespaceID
*
* @param namespaceID
* @param type
*/
@ -49,6 +51,7 @@ public final class LootTableManager {
/**
* Registers a loot table entry type to the given namespaceID
*
* @param namespaceID
* @param type
*/
@ -58,6 +61,7 @@ public final class LootTableManager {
/**
* Registers a loot table function to the given namespaceID
*
* @param namespaceID
* @param function
*/
@ -66,22 +70,22 @@ public final class LootTableManager {
}
public LootTable load(NamespaceID name) throws FileNotFoundException {
return load(name, new FileReader(new File(ResourceGatherer.DATA_FOLDER, "data/"+name.getDomain()+"/loot_tables/"+name.getPath()+".json")));
return load(name, new FileReader(new File(ResourceGatherer.DATA_FOLDER, "data/" + name.getDomain() + "/loot_tables/" + name.getPath() + ".json")));
}
/**
* Loads a loot table with the given name. Loot tables can be cached, so 'reader' is used only on cache misses
* @param name the name to cache the loot table with
*
* @param name the name to cache the loot table with
* @param reader the reader to read the loot table from, if none cached. **Will** be closed no matter the results of this call
* @return
*/
public LootTable load(NamespaceID name, Reader reader) {
try {
try (reader) {
return cache.computeIfAbsent(name, _name -> create(reader));
} finally {
try {
reader.close();
} catch (IOException e) {}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@ -92,28 +96,31 @@ public final class LootTableManager {
/**
* Returns the registered table type corresponding to the given namespace ID. If none is registered, throws {@link IllegalArgumentException}
*
* @param id
* @return
*/
public LootTableType getTableType(NamespaceID id) {
if(!tableTypes.containsKey(id))
throw new IllegalArgumentException("Unknown table type: "+id);
if (!tableTypes.containsKey(id))
throw new IllegalArgumentException("Unknown table type: " + id);
return tableTypes.get(id);
}
/**
* Returns the registered entry type corresponding to the given namespace ID. If none is registered, throws {@link IllegalArgumentException}
*
* @param id
* @return
*/
public LootTableEntryType getEntryType(NamespaceID id) {
if(!entryTypes.containsKey(id))
throw new IllegalArgumentException("Unknown entry type: "+id);
if (!entryTypes.containsKey(id))
throw new IllegalArgumentException("Unknown entry type: " + id);
return entryTypes.get(id);
}
/**
* Returns the registered table type corresponding to the given namespace ID. If none is registered, returns {@link LootTableFunction#IDENTITY}
*
* @param id
* @return
*/

View File

@ -31,6 +31,6 @@ public class DynamicEntry extends LootTable.Entry {
public enum Type {
SELF,
CONTENTS;
CONTENTS
}
}

View File

@ -59,7 +59,9 @@ public abstract class Chunk implements Viewable, DataContainer {
public static final int BIOME_COUNT = 1024; // 4x4x4 blocks group
@NotNull
protected final Instance instance;
@NotNull
protected final Biome[] biomes;
protected final int chunkX, chunkZ;

View File

@ -24,6 +24,7 @@ import net.minestom.server.utils.time.UpdateOption;
import net.minestom.server.utils.validate.Check;
import net.minestom.server.world.biomes.Biome;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
@ -58,7 +59,7 @@ public class DynamicChunk extends Chunk {
// Block entities
protected final Set<Integer> blockEntities = new CopyOnWriteArraySet<>();
public DynamicChunk(Instance instance, Biome[] biomes, int chunkX, int chunkZ) {
public DynamicChunk(@NotNull Instance instance, @Nullable Biome[] biomes, int chunkX, int chunkZ) {
super(instance, biomes, chunkX, chunkZ, true);
}
@ -136,16 +137,18 @@ public class DynamicChunk extends Chunk {
// Update cooldown
final UpdateOption updateOption = customBlock.getUpdateOption();
final long lastUpdate = updatableBlocksLastUpdate.get(index);
final boolean hasCooldown = CooldownUtils.hasCooldown(time, lastUpdate, updateOption);
if (hasCooldown)
continue;
if (updateOption != null) {
final long lastUpdate = updatableBlocksLastUpdate.get(index);
final boolean hasCooldown = CooldownUtils.hasCooldown(time, lastUpdate, updateOption);
if (hasCooldown)
continue;
this.updatableBlocksLastUpdate.put(index, time); // Refresh last update time
this.updatableBlocksLastUpdate.put(index, time); // Refresh last update time
final BlockPosition blockPosition = ChunkUtils.getBlockPosition(index, chunkX, chunkZ);
final Data data = getBlockData(index);
customBlock.update(instance, blockPosition, data);
final BlockPosition blockPosition = ChunkUtils.getBlockPosition(index, chunkX, chunkZ);
final Data data = getBlockData(index);
customBlock.update(instance, blockPosition, data);
}
}
}
@ -343,7 +346,7 @@ public class DynamicChunk extends Chunk {
// CHUNK DATA
// Chunk data
final boolean hasChunkData = reader.readBoolean();
if (hasChunkData) {
if (hasDataIndex && hasChunkData) {
SerializableData serializableData = new SerializableDataImpl();
serializableData.readSerializedData(reader, typeToIndexMap);
}
@ -371,7 +374,7 @@ public class DynamicChunk extends Chunk {
{
final boolean hasBlockData = reader.readBoolean();
// Data deserializer
if (hasBlockData) {
if (hasDataIndex && hasBlockData) {
// Read the data with the deserialized index map
data = new SerializableDataImpl();
data.readSerializedData(reader, typeToIndexMap);

View File

@ -86,7 +86,7 @@ public abstract class CustomBlock {
* If this is not null, {@link #update(Instance, BlockPosition, Data)}
* should be overridden or errors with occurs.
*
* @return the update option of the block
* @return the update option of the block, null if not any
*/
@Nullable
public UpdateOption getUpdateOption() {

View File

@ -74,12 +74,10 @@ public class ChatMessageListener {
final ColoredText usernameText = ColoredText.of(String.format("<%s>", username));
final RichMessage richMessage = RichMessage.of(usernameText)
return RichMessage.of(usernameText)
.setHoverEvent(ChatHoverEvent.showText("Click to send a message to " + username))
.setClickEvent(ChatClickEvent.suggestCommand("/msg " + username + " "))
.append(ColoredText.of(" " + chatEvent.getMessage()));
return richMessage;
}
}

View File

@ -347,6 +347,6 @@ public enum MapColors {
/**
* RGB components are divided by 10 before issuing a lookup (as with the PRECISE strategy), but saves on memory usage
*/
APPROXIMATE;
APPROXIMATE
}
}

View File

@ -46,7 +46,7 @@ public class AdvancementsPacket implements ServerPacket {
public Advancement value;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeSizedString(key);
value.write(writer);
}
@ -60,7 +60,7 @@ public class AdvancementsPacket implements ServerPacket {
public Requirement[] requirements;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
// hasParent
writer.writeBoolean(parentIdentifier != null);
if (parentIdentifier != null) {
@ -94,7 +94,7 @@ public class AdvancementsPacket implements ServerPacket {
public float y;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeSizedString(title.toString());
writer.writeSizedString(description.toString());
writer.writeItemStack(icon);
@ -114,7 +114,7 @@ public class AdvancementsPacket implements ServerPacket {
public String[] requirements;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeVarInt(requirements.length);
for (String requirement : requirements) {
writer.writeSizedString(requirement);
@ -127,7 +127,7 @@ public class AdvancementsPacket implements ServerPacket {
public AdvancementProgress value;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeSizedString(key);
value.write(writer);
}
@ -137,7 +137,7 @@ public class AdvancementsPacket implements ServerPacket {
public Criteria[] criteria;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeVarInt(criteria.length);
for (Criteria criterion : criteria) {
criterion.write(writer);
@ -150,7 +150,7 @@ public class AdvancementsPacket implements ServerPacket {
public CriterionProgress criterionProgress;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeSizedString(criterionIdentifier);
criterionProgress.write(writer);
}
@ -162,7 +162,7 @@ public class AdvancementsPacket implements ServerPacket {
public long dateOfAchieving;
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeBoolean(achieved);
if (dateOfAchieving != 0)
writer.writeLong(dateOfAchieving);

View File

@ -38,7 +38,7 @@ public class DeclareCommandsPacket implements ServerPacket {
public String suggestionsType; // Only if flags 0x10
@Override
public void write(BinaryWriter writer) {
public void write(@NotNull BinaryWriter writer) {
writer.writeByte(flags);
writer.writeVarIntArray(children);

View File

@ -23,8 +23,7 @@ public class MultiBlockChangePacket implements ServerPacket {
if (blockChanges != null) {
final int length = blockChanges.length;
writer.writeVarInt(length);
for (int i = 0; i < length; i++) {
final BlockChange blockChange = blockChanges[i];
for (final BlockChange blockChange : blockChanges) {
writer.writeVarLong(blockChange.newBlockId << 12 | getLocalBlockPosAsShort(blockChange.positionX, blockChange.positionY, blockChange.positionZ));
}
} else {

View File

@ -23,9 +23,9 @@ import java.util.concurrent.atomic.AtomicInteger;
* <p>
* Shutdown {@link Task} are built with {@link #buildShutdownTask(Runnable)}.
*/
public class SchedulerManager {
public final class SchedulerManager {
private boolean instanced;
private static boolean instanced;
// A counter for all normal tasks
private final AtomicInteger counter;
// A counter for all shutdown tasks
@ -47,7 +47,8 @@ public class SchedulerManager {
throw new IllegalStateException("You cannot instantiate a SchedulerManager," +
" use MinecraftServer.getSchedulerManager()");
}
this.instanced = true;
SchedulerManager.instanced = true;
this.counter = new AtomicInteger();
this.shutdownCounter = new AtomicInteger();
@ -111,6 +112,7 @@ public class SchedulerManager {
try {
batchesPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

View File

@ -105,7 +105,6 @@ public final class ArrayUtils {
* @param supplier the supplier to fill the array
* @param <T> the array type
*/
@NotNull
public static <T> void fill(@NotNull T[] array, @NotNull Supplier<T> supplier) {
for (int i = 0; i < array.length; i++) {
array[i] = supplier.get();

View File

@ -1,5 +1,7 @@
package net.minestom.server.utils.time;
import org.jetbrains.annotations.NotNull;
public final class CooldownUtils {
private CooldownUtils() {
@ -15,7 +17,7 @@ public final class CooldownUtils {
* @param cooldown the value of the cooldown
* @return true if the cooldown is in progress, false otherwise
*/
public static boolean hasCooldown(long currentTime, long lastUpdate, TimeUnit timeUnit, int cooldown) {
public static boolean hasCooldown(long currentTime, long lastUpdate, @NotNull TimeUnit timeUnit, int cooldown) {
final long cooldownMs = timeUnit.toMilliseconds(cooldown);
return currentTime - lastUpdate < cooldownMs;
}
@ -28,7 +30,7 @@ public final class CooldownUtils {
* @param updateOption the cooldown
* @return true if the cooldown is in progress, false otherwise
*/
public static boolean hasCooldown(long currentTime, long lastUpdate, UpdateOption updateOption) {
public static boolean hasCooldown(long currentTime, long lastUpdate, @NotNull UpdateOption updateOption) {
return hasCooldown(currentTime, lastUpdate, updateOption.getTimeUnit(), updateOption.getValue());
}
@ -40,7 +42,7 @@ public final class CooldownUtils {
* @param cooldown the value of the cooldown
* @return true if the cooldown is in progress, false otherwise
*/
public static boolean hasCooldown(long lastUpdate, TimeUnit timeUnit, int cooldown) {
public static boolean hasCooldown(long lastUpdate, @NotNull TimeUnit timeUnit, int cooldown) {
return hasCooldown(System.currentTimeMillis(), lastUpdate, timeUnit, cooldown);
}
}

View File

@ -50,7 +50,7 @@ public class Biome {
@Builder.Default
private final Precipitation precipitation = Precipitation.RAIN;
@Builder.Default
private TemperatureModifier temperature_modifier = TemperatureModifier.NONE;
private final TemperatureModifier temperature_modifier = TemperatureModifier.NONE;
public NBTCompound toNbt() {
NBTCompound nbt = new NBTCompound();