Cleanup + javadoc comments

This commit is contained in:
Felix Cravic 2020-07-21 18:48:15 +02:00
parent 287f7e64a3
commit 189376f951
31 changed files with 362 additions and 105 deletions

View File

@ -7,6 +7,9 @@ import net.minestom.server.network.packet.server.ServerPacket;
import java.util.HashSet;
import java.util.Set;
/**
* Represent something in the instance which can be showed or hidden to players
*/
public interface Viewable {
/**
@ -21,22 +24,56 @@ public interface Viewable {
*/
boolean removeViewer(Player player);
/**
* Get all the viewers of this viewable element
*
* @return A Set containing all the element's viewers
*/
Set<Player> getViewers();
/**
* Get if a player is seeing this viewable object
*
* @param player the player to check
* @return true if {@code player} is a viewer, false otherwise
*/
default boolean isViewer(Player player) {
return getViewers().contains(player);
}
/**
* Send a packet to all viewers
* <p>
* It is better than looping through the viewers
* to send a packet since it is here only serialized once
*
* @param packet the packet to send to all viewers
*/
default void sendPacketToViewers(ServerPacket packet) {
PacketWriterUtils.writeAndSend(getViewers(), packet);
}
/**
* Send multiple packets to all viewers
* <p>
* It is better than looping through the viewers
* to send a packet since it is here only serialized once
*
* @param packets the packets to send
*/
default void sendPacketsToViewers(ServerPacket... packets) {
for (ServerPacket packet : packets) {
PacketWriterUtils.writeAndSend(getViewers(), packet);
}
}
/**
* Send a packet to all viewers and the viewable element if it is a player
* <p>
* If 'this' isn't a player, then {@link #sendPacketToViewers(ServerPacket)} is called instead
*
* @param packet the packet to send
*/
default void sendPacketToViewersAndSelf(ServerPacket packet) {
if (this instanceof Player) {
if (getViewers().isEmpty()) {

View File

@ -1,5 +1,8 @@
package net.minestom.server.chat;
/**
* Represent a click event for a specific portion of the message
*/
public class ChatClickEvent {
private String action;
@ -10,14 +13,32 @@ public class ChatClickEvent {
this.value = value;
}
/**
* Open an URL when clicked
*
* @param url the URL to open
* @return the chat click event
*/
public static ChatClickEvent openUrl(String url) {
return new ChatClickEvent("open_url", url);
}
/**
* Run a command when clicked
*
* @param command the command to run
* @return the chat click event
*/
public static ChatClickEvent runCommand(String command) {
return new ChatClickEvent("run_command", command);
}
/**
* Write a string in the player's chat when clicked
*
* @param command the command to suggest
* @return the chat click event
*/
public static ChatClickEvent suggestCommand(String command) {
return new ChatClickEvent("suggest_command", command);
}

View File

@ -5,6 +5,9 @@ import net.minestom.server.utils.validate.Check;
import java.util.HashMap;
import java.util.Map;
/**
* Represent a color in a text
*/
public class ChatColor {
// Special
@ -114,6 +117,14 @@ public class ChatColor {
this.special = true;
}
/**
* Create an RGB color
*
* @param r the red component
* @param g the green component
* @param b the blue component
* @return a chat color with the specified RGB color
*/
public static ChatColor fromRGB(int r, int g, int b) {
return fromRGB(r, g, b, -1);
}
@ -122,10 +133,22 @@ public class ChatColor {
return new ChatColor(r, g, b, id);
}
/**
* Get a color based on its name (eg: white, black, aqua, etc...)
*
* @param name the color name
* @return the color associated with the name, {@link #NO_COLOR} if not found
*/
public static ChatColor fromName(String name) {
return colorCode.getOrDefault(name.toLowerCase(), NO_COLOR);
}
/**
* Get a color based on its legacy color code (eg: 1, 2, 3,... f)
*
* @param colorCode the color legacy code
* @return the color associated with the code
*/
public static ChatColor fromLegacyColorCodes(char colorCode) {
return legacyColorCodesMap.getOrDefault(colorCode, NO_COLOR);
}
@ -134,18 +157,38 @@ public class ChatColor {
return empty;
}
/**
* Get the red component of the color
*
* @return the red component of the color
*/
public int getRed() {
return red;
}
/**
* Get the green component of the color
*
* @return the green component of the color
*/
public int getGreen() {
return green;
}
/**
* Get the blue component of the color
*
* @return the blue component of the color
*/
public int getBlue() {
return blue;
}
/**
* Get if the color is special (eg: no color, bold, reset, etc...)
*
* @return true if the color is special, false otherwise
*/
public boolean isSpecial() {
return special;
}

View File

@ -5,6 +5,9 @@ import net.minestom.server.entity.Entity;
import net.minestom.server.entity.EntityType;
import net.minestom.server.item.ItemStack;
/**
* Represent a hover event for a specific portion of the message
*/
public class ChatHoverEvent {
private String action;
@ -23,18 +26,42 @@ public class ChatHoverEvent {
this.isJson = true;
}
/**
* Show a {@link ColoredText} when hovered
*
* @param text the text to show
* @return the chat hover event
*/
public static ChatHoverEvent showText(ColoredText text) {
return new ChatHoverEvent("show_text", text.getJsonObject());
}
/**
* Show a raw text when hovered
*
* @param text the text to show
* @return the chat hover event
*/
public static ChatHoverEvent showText(String text) {
return new ChatHoverEvent("show_text", text);
}
/**
* Show an item when hovered
*
* @param itemStack the item to show
* @return the chat hover event
*/
public static ChatHoverEvent showItem(ItemStack itemStack) {
return new ChatHoverEvent("show_item", "{id:35,Damage:5,Count:2,tag:{display:{Name:Testing}}}");
}
/**
* Show an entity when hovered
*
* @param entity the entity to show
* @return the chat hover event
*/
public static ChatHoverEvent showEntity(Entity entity) {
final String id = entity.getUuid().toString();
final String type = EntityType.fromId(entity.getEntityType())

View File

@ -8,6 +8,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* Represent a text with one or multiple colors
*/
public class ColoredText {
private String message;

View File

@ -7,6 +7,10 @@ import net.minestom.server.utils.validate.Check;
import java.util.ArrayList;
import java.util.List;
/**
* Represent multiple {@link ColoredText} batched together with the possibility to add
* click & hover events
*/
public class RichMessage {
private List<RichComponent> components = new ArrayList<>();

View File

@ -1,5 +1,8 @@
package net.minestom.server.chat;
/**
* Represent a translatable component which can be used in {@link ColoredText}
*/
public class TranslatableText {
private String code;
@ -10,10 +13,23 @@ public class TranslatableText {
this.arguments = arguments;
}
/**
* Get the translatable component of the specific code
*
* @param code the translatable code
* @return the translatable component linked to the code
*/
public static TranslatableText of(String code) {
return new TranslatableText(code, null);
}
/**
* Get the translatable component and the specific code with arguments
*
* @param code the translatable code
* @param arguments the translatable component arguments in order
* @return the translatable component linked to the code and arguments
*/
public static TranslatableText of(String code, String... arguments) {
return new TranslatableText(code, arguments);
}

View File

@ -37,7 +37,7 @@ public class CommandManager {
running = true;
// Setup console thread
Thread consoleThread = new Thread(() -> {
Scanner scanner = new Scanner(System.in);
final Scanner scanner = new Scanner(System.in);
while (running) {
if (scanner.hasNext()) {
String command = scanner.nextLine();
@ -103,14 +103,14 @@ public class CommandManager {
return true;
} catch (NullPointerException e) {
// Check for legacy-command
String[] splitted = command.split(" ");
String commandName = splitted[0];
CommandProcessor commandProcessor = commandProcessorMap.get(commandName.toLowerCase());
final String[] splitted = command.split(" ");
final String commandName = splitted[0];
final CommandProcessor commandProcessor = commandProcessorMap.get(commandName.toLowerCase());
if (commandProcessor == null)
return false;
// Execute the legacy-command
String[] args = command.substring(command.indexOf(" ") + 1).split(" ");
final String[] args = command.substring(command.indexOf(" ") + 1).split(" ");
return commandProcessor.process(sender, commandName, args);

View File

@ -2,20 +2,45 @@ package net.minestom.server.command;
import net.minestom.server.entity.Player;
/**
* Represent something which can send commands to the server
* <p>
* Main implementations are {@link Player} and {@link ConsoleSender}
*/
public interface CommandSender {
/**
* Send a raw string message
*
* @param message the message to send
*/
void sendMessage(String message);
/**
* Send multiple raw string messages
*
* @param messages the messages to send
*/
default void sendMessage(String[] messages) {
for (String message : messages) {
sendMessage(message);
}
}
/**
* Get if the sender is a player
*
* @return true if 'this' is a player, false otherwise
*/
default boolean isPlayer() {
return this instanceof Player;
}
/**
* Get if the sender is the console
*
* @return true if 'this' is the console, false otherwise
*/
default boolean isConsole() {
return this instanceof ConsoleSender;
}

View File

@ -1,6 +1,10 @@
package net.minestom.server.command;
/**
* Represent the console when sending a command to the server
*/
public class ConsoleSender implements CommandSender {
@Override
public void sendMessage(String message) {
System.out.println(message);

View File

@ -2,12 +2,34 @@ package net.minestom.server.instance;
import java.util.function.Consumer;
/**
* Interface implemented to change the way chunks are loaded/saved
* see {@link MinestomBasicChunkLoader} for the default implementation used in {@link InstanceContainer}
*/
public interface IChunkLoader {
/**
* Load a specific chunk
*
* @param instance the instance where the chunk belong
* @param chunkX the chunk X
* @param chunkZ the chunk Z
* @param callback the callback executed when the chunk is done loading
* @return true if the chunk loaded successfully, false otherwise
*/
boolean loadChunk(Instance instance, int chunkX, int chunkZ, Consumer<Chunk> callback);
/**
* Save a specific chunk with a callback for when it is done
*
* @param chunk the chunk to save
* @param callback the callback executed when the chunk is done saving
*/
void saveChunk(Chunk chunk, Runnable callback);
/**
* Does this ChunkLoader allow for multithreaded saving of chunks?
* Does this ChunkLoader allow for multi-threaded saving of chunks?
*
* @return
*/
default boolean supportsParallelSaving() {
@ -15,7 +37,8 @@ public interface IChunkLoader {
}
/**
* Does this ChunkLoader allow for multithreaded loading of chunks?
* Does this ChunkLoader allow for multi-threaded loading of chunks?
*
* @return
*/
default boolean supportsParallelLoading() {

View File

@ -33,6 +33,12 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
/**
* Instances are what are called "worlds" in Minecraft
* <p>
* An instance has entities and chunks, each instance contains its own entity list but the
* chunk implementation has to be defined, see {@link InstanceContainer}
*/
public abstract class Instance implements BlockModifier, EventHandler, DataContainer {
protected static final BlockManager BLOCK_MANAGER = MinecraftServer.getBlockManager();
@ -119,6 +125,8 @@ public abstract class Instance implements BlockModifier, EventHandler, DataConta
public abstract void unloadChunk(Chunk chunk);
/**
* Get the specified chunk
*
* @param chunkX the chunk X
* @param chunkZ the chunk Z
* @return the chunk at the specified position, null if not loaded
@ -126,6 +134,8 @@ public abstract class Instance implements BlockModifier, EventHandler, DataConta
public abstract Chunk getChunk(int chunkX, int chunkZ);
/**
* Save a chunk into the defined storage folder
*
* @param chunk the chunk to save
* @param callback called when the chunk is done saving
* @throws NullPointerException if {@link #getStorageFolder()} returns null
@ -133,17 +143,23 @@ public abstract class Instance implements BlockModifier, EventHandler, DataConta
public abstract void saveChunkToStorageFolder(Chunk chunk, Runnable callback);
/**
* Save multiple chunks into the defined storage folder
*
* @param callback called when the chunks are done saving
* @throws NullPointerException if {@link #getStorageFolder()} returns null
*/
public abstract void saveChunksToStorageFolder(Runnable callback);
/**
* Create a new block batch linked to this instance
*
* @return a BlockBatch linked to the instance
*/
public abstract BlockBatch createBlockBatch();
/**
* Create a new chunk batch linked to this instance and the specified chunk
*
* @param chunk the chunk to modify
* @return a ChunkBatch linked to {@code chunk}
* @throws NullPointerException if {@code chunk} is null
@ -151,26 +167,36 @@ public abstract class Instance implements BlockModifier, EventHandler, DataConta
public abstract ChunkBatch createChunkBatch(Chunk chunk);
/**
* Get the instance chunk generator
*
* @return the chunk generator of the instance
*/
public abstract ChunkGenerator getChunkGenerator();
/**
* Change the instance chunk generator
*
* @param chunkGenerator the new chunk generator of the instance
*/
public abstract void setChunkGenerator(ChunkGenerator chunkGenerator);
/**
* Get all the instance's chunks
*
* @return an unmodifiable containing all the loaded chunks of the instance
*/
public abstract Collection<Chunk> getChunks();
/**
* Get the instance storage folder
*
* @return the storage folder of the instance
*/
public abstract StorageFolder getStorageFolder();
/**
* Change the instance storage folder
*
* @param storageFolder the new storage folder of the instance
*/
public abstract void setStorageFolder(StorageFolder storageFolder);

View File

@ -19,16 +19,16 @@ public class MinestomBasicChunkLoader implements IChunkLoader {
@Override
public void saveChunk(Chunk chunk, Runnable callback) {
if(storageFolder == null) {
if (storageFolder == null) {
callback.run();
LOGGER.warn("No folder to save chunk!");
return;
}
int chunkX = chunk.getChunkX();
int chunkZ = chunk.getChunkZ();
final int chunkX = chunk.getChunkX();
final int chunkZ = chunk.getChunkZ();
try {
byte[] data = chunk.getSerializedData();
final byte[] data = chunk.getSerializedData();
storageFolder.set(getChunkKey(chunkX, chunkZ), data);
if (callback != null)
@ -40,7 +40,7 @@ public class MinestomBasicChunkLoader implements IChunkLoader {
@Override
public boolean loadChunk(Instance instance, int chunkX, int chunkZ, Consumer<Chunk> callback) {
byte[] bytes = storageFolder == null ? null : storageFolder.get(getChunkKey(chunkX, chunkZ));
final byte[] bytes = storageFolder == null ? null : storageFolder.get(getChunkKey(chunkX, chunkZ));
if (bytes == null) {
return false;

View File

@ -14,7 +14,8 @@ import java.util.UUID;
import java.util.function.Consumer;
/**
* Shared instance is an instance that share the same chunks as instanceContainer, entities are separated.
* Shared instance is an instance that share the same chunks as instanceContainer,
* entities are separated.
*/
public class SharedInstance extends Instance {

View File

@ -5,6 +5,9 @@ import net.minestom.server.entity.Player;
import net.minestom.server.network.packet.server.play.WorldBorderPacket;
import net.minestom.server.utils.Position;
/**
* Represent the world border of an instance
*/
public class WorldBorder {
private Instance instance;
@ -35,12 +38,23 @@ public class WorldBorder {
}
/**
* Change the X and Z position of the center
*
* @param centerX the X center
* @param centerZ the Z center
*/
public void setCenter(float centerX, float centerZ) {
this.centerX = centerX;
this.centerZ = centerZ;
refreshCenter();
}
/**
* Get the center X of the world border
*
* @return the X center
*/
public float getCenterX() {
return centerX;
}
@ -50,6 +64,11 @@ public class WorldBorder {
refreshCenter();
}
/**
* Get the center Z of the world border
*
* @return the Z center
*/
public float getCenterZ() {
return centerZ;
}
@ -112,8 +131,10 @@ public class WorldBorder {
}
/**
* @return the current world border diameter
* Get the diameter of the world border
* It takes lerp in consideration
*
* @return the current world border diameter
*/
public double getDiameter() {
return currentDiameter;
@ -178,6 +199,7 @@ public class WorldBorder {
/**
* Used to update in real-time the current diameter time
* Called in the instance tick update
*/
protected void update() {
if (lerpStartTime == 0) {
@ -207,6 +229,8 @@ public class WorldBorder {
}
/**
* Get the instance linked to this world border
*
* @return the instance of this world border
*/
public Instance getInstance() {

View File

@ -11,7 +11,7 @@ public class AbilitiesListener {
final boolean canFly = player.isAllowFlying() || player.isCreative();
if (canFly) {
boolean isFlying = (packet.flags & 0x2) > 0;
final boolean isFlying = (packet.flags & 0x2) > 0;
player.refreshFlying(isFlying);

View File

@ -9,7 +9,7 @@ public class AnimationListener {
public static void animationListener(ClientAnimationPacket packet, Player player) {
AnimationEvent animationEvent = new AnimationEvent(player, packet.hand);
player.callCancellableEvent(AnimationEvent.class, animationEvent, () -> {
Player.Hand hand = animationEvent.getHand();
final Player.Hand hand = animationEvent.getHand();
switch (hand) {
case MAIN:
player.swingMainHand();

View File

@ -50,31 +50,31 @@ public class BlockPlacementListener {
}
});
if(playerBlockInteractEvent.isBlockingItemUse()) {
if (playerBlockInteractEvent.isBlockingItemUse()) {
return;
}
// Check if item at hand is a block
ItemStack usedItem = hand == Player.Hand.MAIN ? playerInventory.getItemInMainHand() : playerInventory.getItemInOffHand();
Material material = Material.fromId(usedItem.getMaterialId());
if(material == Material.AIR) {
final ItemStack usedItem = hand == Player.Hand.MAIN ? playerInventory.getItemInMainHand() : playerInventory.getItemInOffHand();
final Material material = Material.fromId(usedItem.getMaterialId());
if (material == Material.AIR) {
return;
}
// Get the newly placed block position
int offsetX = blockFace == BlockFace.WEST ? -1 : blockFace == BlockFace.EAST ? 1 : 0;
int offsetY = blockFace == BlockFace.BOTTOM ? -1 : blockFace == BlockFace.TOP ? 1 : 0;
int offsetZ = blockFace == BlockFace.NORTH ? -1 : blockFace == BlockFace.SOUTH ? 1 : 0;
final int offsetX = blockFace == BlockFace.WEST ? -1 : blockFace == BlockFace.EAST ? 1 : 0;
final int offsetY = blockFace == BlockFace.BOTTOM ? -1 : blockFace == BlockFace.TOP ? 1 : 0;
final int offsetZ = blockFace == BlockFace.NORTH ? -1 : blockFace == BlockFace.SOUTH ? 1 : 0;
blockPosition.add(offsetX, offsetY, offsetZ);
Chunk chunk = instance.getChunkAt(blockPosition);
final Chunk chunk = instance.getChunkAt(blockPosition);
boolean refreshChunk = false;
if (material.isBlock()) {
Block block = material.getBlock();
Set<Entity> entities = instance.getChunkEntities(chunk);
final Block block = material.getBlock();
final Set<Entity> entities = instance.getChunkEntities(chunk);
boolean intersect = false;
if (block.isSolid()) {
for (Entity entity : entities) {
@ -86,8 +86,8 @@ public class BlockPlacementListener {
if (!intersect) {
// BlockPlacementRule check
BlockManager blockManager = MinecraftServer.getBlockManager();
BlockPlacementRule blockPlacementRule = blockManager.getBlockPlacementRule(block);
final BlockManager blockManager = MinecraftServer.getBlockManager();
final BlockPlacementRule blockPlacementRule = blockManager.getBlockPlacementRule(block);
short blockid = block.getBlockId();
if (blockPlacementRule != null) {
blockid = blockPlacementRule.blockPlace(instance, block, blockFace, player);

View File

@ -6,6 +6,7 @@ import net.minestom.server.command.CommandManager;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.PlayerChatEvent;
import net.minestom.server.event.player.PlayerCommandEvent;
import net.minestom.server.network.ConnectionManager;
import net.minestom.server.network.PacketWriterUtils;
import net.minestom.server.network.packet.client.play.ClientChatMessagePacket;
import net.minestom.server.network.packet.server.play.ChatMessagePacket;
@ -15,18 +16,20 @@ import java.util.function.Function;
public class ChatMessageListener {
private static final CommandManager COMMAND_MANAGER = MinecraftServer.getCommandManager();
private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager();
public static void listener(ClientChatMessagePacket packet, Player player) {
String message = packet.message;
CommandManager commandManager = MinecraftServer.getCommandManager();
String cmdPrefix = commandManager.getCommandPrefix();
String cmdPrefix = COMMAND_MANAGER.getCommandPrefix();
if (message.startsWith(cmdPrefix)) {
// The message is a command
message = message.replaceFirst(cmdPrefix, "");
PlayerCommandEvent playerCommandEvent = new PlayerCommandEvent(player, message);
player.callCancellableEvent(PlayerCommandEvent.class, playerCommandEvent, () -> {
commandManager.execute(player, playerCommandEvent.getCommand());
COMMAND_MANAGER.execute(player, playerCommandEvent.getCommand());
});
// Do not call chat event
@ -34,13 +37,13 @@ public class ChatMessageListener {
}
Collection<Player> players = MinecraftServer.getConnectionManager().getOnlinePlayers();
final Collection<Player> players = CONNECTION_MANAGER.getOnlinePlayers();
PlayerChatEvent playerChatEvent = new PlayerChatEvent(player, players, message);
// Call the event
player.callCancellableEvent(PlayerChatEvent.class, playerChatEvent, () -> {
Function<PlayerChatEvent, RichMessage> formatFunction = playerChatEvent.getChatFormatFunction();
final Function<PlayerChatEvent, RichMessage> formatFunction = playerChatEvent.getChatFormatFunction();
RichMessage textObject;
@ -52,9 +55,9 @@ public class ChatMessageListener {
textObject = buildDefaultChatMessage(playerChatEvent);
}
Collection<Player> recipients = playerChatEvent.getRecipients();
final Collection<Player> recipients = playerChatEvent.getRecipients();
if (!recipients.isEmpty()) {
String jsonMessage = textObject.toString();
final String jsonMessage = textObject.toString();
// Send the message with the correct player UUID
ChatMessagePacket chatMessagePacket =
@ -68,11 +71,11 @@ public class ChatMessageListener {
}
private static RichMessage buildDefaultChatMessage(PlayerChatEvent chatEvent) {
String username = chatEvent.getSender().getUsername();
final String username = chatEvent.getSender().getUsername();
ColoredText usernameText = ColoredText.of(String.format("<%s>", username));
final ColoredText usernameText = ColoredText.of(String.format("<%s>", username));
RichMessage richMessage = RichMessage.of(usernameText)
final RichMessage richMessage = RichMessage.of(usernameText)
.setHoverEvent(ChatHoverEvent.showText(ColoredText.of(ChatColor.GRAY + "Its " + username)))
.setClickEvent(ChatClickEvent.suggestCommand("/msg " + username + " "))
.append(ColoredText.of(" " + chatEvent.getMessage()));

View File

@ -12,7 +12,8 @@ public class CreativeInventoryActionListener {
public static void listener(ClientCreativeInventoryActionPacket packet, Player player) {
if (player.getGameMode() != GameMode.CREATIVE)
return;
ItemStack item = packet.item;
final ItemStack item = packet.item;
short slot = packet.slot;
if (slot != -1) {
// Set item

View File

@ -19,7 +19,7 @@ public class KeepAliveListener {
player.refreshAnswerKeepAlive(true);
// Update latency
int latency = (int) (System.currentTimeMillis() - packet.id);
final int latency = (int) (System.currentTimeMillis() - packet.id);
player.refreshLatency(latency);
}
}

View File

@ -18,14 +18,14 @@ import net.minestom.server.utils.BlockPosition;
public class PlayerDiggingListener {
public static void playerDiggingListener(ClientPlayerDiggingPacket packet, Player player) {
ClientPlayerDiggingPacket.Status status = packet.status;
BlockPosition blockPosition = packet.blockPosition;
final ClientPlayerDiggingPacket.Status status = packet.status;
final BlockPosition blockPosition = packet.blockPosition;
PlayerInventory playerInventory = player.getInventory();
ItemStack mainHand = playerInventory.getItemInMainHand();
ItemStack offHand = playerInventory.getItemInOffHand();
final PlayerInventory playerInventory = player.getInventory();
final ItemStack mainHand = playerInventory.getItemInMainHand();
final ItemStack offHand = playerInventory.getItemInOffHand();
Instance instance = player.getInstance();
final Instance instance = player.getInstance();
if (instance == null)
return;

View File

@ -9,8 +9,6 @@ import net.minestom.server.network.packet.client.play.ClientPlayerRotationPacket
import net.minestom.server.utils.Position;
import net.minestom.server.utils.chunk.ChunkUtils;
import java.util.function.Consumer;
public class PlayerPositionListener {
public static void playerPacketListener(ClientPlayerPacket packet, Player player) {
@ -18,48 +16,39 @@ public class PlayerPositionListener {
}
public static void playerLookListener(ClientPlayerRotationPacket packet, Player player) {
Position playerPosition = player.getPosition();
float x = playerPosition.getX();
float y = playerPosition.getY();
float z = playerPosition.getZ();
float yaw = packet.yaw;
float pitch = packet.pitch;
processMovement(player, x, y, z, yaw, pitch, (position) -> {
player.refreshPosition(position.getX(), position.getY(), position.getZ());
player.refreshView(position.getYaw(), position.getPitch());
player.refreshOnGround(packet.onGround);
});
final Position playerPosition = player.getPosition();
final float x = playerPosition.getX();
final float y = playerPosition.getY();
final float z = playerPosition.getZ();
final float yaw = packet.yaw;
final float pitch = packet.pitch;
final boolean onGround = packet.onGround;
processMovement(player, x, y, z, yaw, pitch, onGround);
}
public static void playerPositionListener(ClientPlayerPositionPacket packet, Player player) {
Position playerPosition = player.getPosition();
float x = (float) packet.x;
float y = (float) packet.y;
float z = (float) packet.z;
float yaw = playerPosition.getYaw();
float pitch = playerPosition.getPitch();
processMovement(player, x, y, z, yaw, pitch, (position) -> {
player.refreshPosition(position.getX(), position.getY(), position.getZ());
player.refreshView(position.getYaw(), position.getPitch());
player.refreshOnGround(packet.onGround);
});
final Position playerPosition = player.getPosition();
final float x = (float) packet.x;
final float y = (float) packet.y;
final float z = (float) packet.z;
final float yaw = playerPosition.getYaw();
final float pitch = playerPosition.getPitch();
final boolean onGround = packet.onGround;
processMovement(player, x, y, z, yaw, pitch, onGround);
}
public static void playerPositionAndLookListener(ClientPlayerPositionAndRotationPacket packet, Player player) {
float x = (float) packet.x;
float y = (float) packet.y;
float z = (float) packet.z;
float yaw = packet.yaw;
float pitch = packet.pitch;
processMovement(player, x, y, z, yaw, pitch, (position) -> {
player.refreshPosition(position.getX(), position.getY(), position.getZ());
player.refreshView(position.getYaw(), position.getPitch());
player.refreshOnGround(packet.onGround);
});
final float x = (float) packet.x;
final float y = (float) packet.y;
final float z = (float) packet.z;
final float yaw = packet.yaw;
final float pitch = packet.pitch;
final boolean onGround = packet.onGround;
processMovement(player, x, y, z, yaw, pitch, onGround);
}
private static void processMovement(Player player, float x, float y, float z,
float yaw, float pitch, Consumer<Position> consumer) {
float yaw, float pitch, boolean onGround) {
// Try to move in an unloaded chunk, prevent it
if (ChunkUtils.isChunkUnloaded(player.getInstance(), x, z)) {
@ -71,7 +60,11 @@ public class PlayerPositionListener {
PlayerMoveEvent playerMoveEvent = new PlayerMoveEvent(player, newPosition);
player.callEvent(PlayerMoveEvent.class, playerMoveEvent);
if (!playerMoveEvent.isCancelled()) {
consumer.accept(playerMoveEvent.getNewPosition());
// Move the player
newPosition = playerMoveEvent.getNewPosition();
player.refreshPosition(newPosition.getX(), newPosition.getY(), newPosition.getZ());
player.refreshView(newPosition.getYaw(), newPosition.getPitch());
player.refreshOnGround(onGround);
} else {
player.teleport(player.getPosition());
}

View File

@ -11,19 +11,19 @@ import net.minestom.server.utils.Position;
public class PlayerVehicleListener {
public static void steerVehicleListener(ClientSteerVehiclePacket packet, Player player) {
byte flags = packet.flags;
boolean jump = (flags & 0x1) != 0;
boolean unmount = (flags & 0x2) != 0;
final byte flags = packet.flags;
final boolean jump = (flags & 0x1) != 0;
final boolean unmount = (flags & 0x2) != 0;
player.refreshVehicleSteer(packet.sideways, packet.forward, jump, unmount);
}
public static void vehicleMoveListener(ClientVehicleMovePacket packet, Player player) {
Entity vehicle = player.getVehicle();
final Entity vehicle = player.getVehicle();
if (vehicle == null)
return;
Position newPosition = new Position((float) packet.x, (float) packet.y, (float) packet.z);
final Position newPosition = new Position((float) packet.x, (float) packet.y, (float) packet.z);
vehicle.refreshPosition(newPosition);
vehicle.refreshView(packet.yaw, packet.pitch);
vehicle.askSynchronization();
@ -40,7 +40,7 @@ public class PlayerVehicleListener {
}
public static void boatSteerListener(ClientSteerBoatPacket packet, Player player) {
Entity vehicle = player.getVehicle();
final Entity vehicle = player.getVehicle();
if (vehicle == null || !(vehicle instanceof EntityBoat))
return;

View File

@ -8,7 +8,7 @@ import net.minestom.server.resourcepack.ResourcePackStatus;
public class ResourcePackListener {
public static void listener(ClientResourcePackStatusPacket packet, Player player) {
ResourcePackStatus result = packet.result;
final ResourcePackStatus result = packet.result;
PlayerResourcePackStatusEvent resourcePackStatusEvent = new PlayerResourcePackStatusEvent(player, result);
player.callEvent(PlayerResourcePackStatusEvent.class, resourcePackStatusEvent);
}

View File

@ -20,7 +20,7 @@ public class StatusListener {
List<StatisticsPacket.Statistic> statisticList = new ArrayList<>();
StatisticsPacket statisticsPacket = new StatisticsPacket();
Map<PlayerStatistic, Integer> playerStatisticValueMap = player.getStatisticValueMap();
final Map<PlayerStatistic, Integer> playerStatisticValueMap = player.getStatisticValueMap();
for (Map.Entry<PlayerStatistic, Integer> entry : playerStatisticValueMap.entrySet()) {
PlayerStatistic playerStatistic = entry.getKey();
int value = entry.getValue();

View File

@ -10,7 +10,7 @@ import net.minestom.server.network.packet.client.play.ClientInteractEntityPacket
public class UseEntityListener {
public static void useEntityListener(ClientInteractEntityPacket packet, Player player) {
Entity entity = Entity.getEntity(packet.targetId);
final Entity entity = Entity.getEntity(packet.targetId);
if (entity == null)
return;
ClientInteractEntityPacket.Type type = packet.type;

View File

@ -13,23 +13,23 @@ import net.minestom.server.network.packet.client.play.ClientUseItemPacket;
public class UseItemListener {
public static void useItemListener(ClientUseItemPacket packet, Player player) {
PlayerInventory inventory = player.getInventory();
Player.Hand hand = packet.hand;
ItemStack itemStack = hand == Player.Hand.MAIN ? inventory.getItemInMainHand() : inventory.getItemInOffHand();
final PlayerInventory inventory = player.getInventory();
final Player.Hand hand = packet.hand;
final ItemStack itemStack = hand == Player.Hand.MAIN ? inventory.getItemInMainHand() : inventory.getItemInOffHand();
PlayerUseItemEvent useItemEvent = new PlayerUseItemEvent(player, hand, itemStack);
player.callEvent(PlayerUseItemEvent.class, useItemEvent);
Material material = Material.fromId(itemStack.getMaterialId());
final Material material = Material.fromId(itemStack.getMaterialId());
// Equip armor with right click
if (material.isArmor()) {
PlayerInventory playerInventory = player.getInventory();
final PlayerInventory playerInventory = player.getInventory();
if (useItemEvent.isCancelled()) {
playerInventory.update();
return;
}
ArmorEquipEvent.ArmorSlot armorSlot;
final ArmorEquipEvent.ArmorSlot armorSlot;
if (material.isHelmet()) {
armorSlot = ArmorEquipEvent.ArmorSlot.HELMET;
} else if (material.isChestplate()) {
@ -41,7 +41,7 @@ public class UseItemListener {
}
ArmorEquipEvent armorEquipEvent = new ArmorEquipEvent(player, itemStack, armorSlot);
player.callEvent(ArmorEquipEvent.class, armorEquipEvent);
ItemStack armorItem = armorEquipEvent.getArmorItem();
final ItemStack armorItem = armorEquipEvent.getArmorItem();
if (hand == Player.Hand.MAIN) {
playerInventory.setItemInMainHand(ItemStack.getAirItem());
@ -66,7 +66,7 @@ public class UseItemListener {
}
ArmAnimationEvent armAnimationEvent = null;
boolean offhand = hand == Player.Hand.OFF;
final boolean offhand = hand == Player.Hand.OFF;
boolean riptideSpinAttack = false;
if (material == Material.BOW) {

View File

@ -15,8 +15,8 @@ import net.minestom.server.network.packet.server.play.WindowConfirmationPacket;
public class WindowListener {
public static void clickWindowListener(ClientClickWindowPacket packet, Player player) {
Inventory inventory;
byte windowId = packet.windowId;
final Inventory inventory;
final byte windowId = packet.windowId;
if (windowId == 0) {
inventory = null;
} else {
@ -26,10 +26,10 @@ public class WindowListener {
InventoryClickHandler clickHandler = inventory == null ?
player.getInventory() : player.getOpenInventory();
short slot = packet.slot;
byte button = packet.button;
short actionNumber = packet.actionNumber;
int mode = packet.mode;
final short slot = packet.slot;
final byte button = packet.button;
final short actionNumber = packet.actionNumber;
final int mode = packet.mode;
// System.out.println("Window id: " + windowId + " | slot: " + slot + " | button: " + button + " | mode: " + mode);

View File

@ -5,6 +5,9 @@ import net.minestom.server.network.packet.server.play.ParticlePacket;
import java.util.function.Consumer;
/**
* Small utils class to create particle packet
*/
public class ParticleCreator {
public static ParticlePacket createParticlePacket(Particle particle, boolean distance,

View File

@ -7,6 +7,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Represent the data sent to the player when refreshing his server list
*/
public class ResponseData {
private JsonObject jsonObject = new JsonObject();