Replace PlayerConnection#sendPacket when possible

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2022-05-10 10:07:55 +02:00
parent abeda20646
commit 7d930ee28d
21 changed files with 101 additions and 168 deletions

View File

@ -1,16 +1,13 @@
package net.minestom.server.advancements;
import net.kyori.adventure.text.Component;
import net.minestom.server.entity.Player;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.minestom.server.network.packet.server.play.AdvancementsPacket;
import net.minestom.server.utils.PacketUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Set;
/**
* Represents an advancement located in an {@link AdvancementTab}.
@ -323,13 +320,8 @@ public class Advancement {
*/
protected void update() {
updateCriteria();
if (tab != null) {
final Set<Player> viewers = tab.getViewers();
AdvancementsPacket createPacket = tab.createPacket();
PacketUtils.sendGroupedPacket(viewers, tab.removePacket);
PacketUtils.sendGroupedPacket(viewers, createPacket);
tab.sendPacketsToViewers(tab.removePacket, tab.createPacket());
}
}

View File

@ -3,7 +3,6 @@ package net.minestom.server.advancements;
import net.minestom.server.Viewable;
import net.minestom.server.entity.Player;
import net.minestom.server.network.packet.server.play.AdvancementsPacket;
import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.validate.Check;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -115,17 +114,10 @@ public class AdvancementTab implements Viewable {
@Override
public synchronized boolean addViewer(@NotNull Player player) {
final boolean result = viewers.add(player);
if (!result) {
return false;
}
final PlayerConnection playerConnection = player.getPlayerConnection();
if (!result) return false;
// Send the tab to the player
playerConnection.sendPacket(createPacket());
player.sendPacket(createPacket());
addPlayer(player);
return true;
}
@ -134,16 +126,9 @@ public class AdvancementTab implements Viewable {
if (!isViewer(player)) {
return false;
}
final PlayerConnection playerConnection = player.getPlayerConnection();
// Remove the tab
if (!player.isRemoved()) {
playerConnection.sendPacket(removePacket);
}
if (!player.isRemoved()) player.sendPacket(removePacket);
removePlayer(player);
return viewers.remove(player);
}

View File

@ -36,7 +36,7 @@ public interface PacketGroupingAudience extends ForwardingAudience {
* @param players the players
* @return the audience
*/
static PacketGroupingAudience of(Collection<Player> players) {
static @NotNull PacketGroupingAudience of(@NotNull Collection<Player> players) {
return () -> players;
}
@ -45,15 +45,15 @@ public interface PacketGroupingAudience extends ForwardingAudience {
*
* @return the connections
*/
@NotNull Collection<Player> getPlayers();
@NotNull Collection<@NotNull Player> getPlayers();
/**
* Broadcast a ServerPacket to all players of this audience
*
* @param packet the packet to broadcast
*/
default void sendGroupedPacket(ServerPacket packet) {
PacketUtils.sendGroupedPacket(this.getPlayers(), packet);
default void sendGroupedPacket(@NotNull ServerPacket packet) {
PacketUtils.sendGroupedPacket(getPlayers(), packet);
}
@Override

View File

@ -45,7 +45,7 @@ public class BossBarManager {
public void addBossBar(@NotNull Player player, @NotNull BossBar bar) {
BossBarHolder holder = this.getOrCreateHandler(bar);
if (holder.addViewer(player)) {
player.getPlayerConnection().sendPacket(holder.createAddPacket());
player.sendPacket(holder.createAddPacket());
this.playerBars.computeIfAbsent(player.getUuid(), uuid -> new HashSet<>()).add(holder);
}
}
@ -59,7 +59,7 @@ public class BossBarManager {
public void removeBossBar(@NotNull Player player, @NotNull BossBar bar) {
BossBarHolder holder = this.bars.get(bar);
if (holder != null && holder.removeViewer(player)) {
player.getPlayerConnection().sendPacket(holder.createRemovePacket());
player.sendPacket(holder.createRemovePacket());
this.removePlayer(player, holder);
}
}

View File

@ -20,7 +20,6 @@ import net.minestom.server.adventure.AdventurePacketConvertor;
import net.minestom.server.adventure.Localizable;
import net.minestom.server.adventure.audience.Audiences;
import net.minestom.server.attribute.Attribute;
import net.minestom.server.command.CommandManager;
import net.minestom.server.command.CommandSender;
import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Pos;
@ -247,14 +246,14 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
List.of("minestom:world"), nbt, dimensionType.toNBT(), dimensionType.getName().asString(),
0, 0, MinecraftServer.getChunkViewDistance(), MinecraftServer.getChunkViewDistance(),
false, true, false, levelFlat);
playerConnection.sendPacket(joinGamePacket);
sendPacket(joinGamePacket);
// Server brand name
playerConnection.sendPacket(PluginMessagePacket.getBrandPacket());
sendPacket(PluginMessagePacket.getBrandPacket());
// Difficulty
playerConnection.sendPacket(new ServerDifficultyPacket(MinecraftServer.getDifficulty(), true));
sendPacket(new ServerDifficultyPacket(MinecraftServer.getDifficulty(), true));
playerConnection.sendPacket(new SpawnPositionPacket(respawnPoint, 0));
sendPacket(new SpawnPositionPacket(respawnPoint, 0));
// Add player to list with spawning skin
PlayerSkinInitEvent skinInitEvent = new PlayerSkinInitEvent(this, skin);
@ -277,13 +276,12 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
// Recipes start
{
RecipeManager recipeManager = MinecraftServer.getRecipeManager();
playerConnection.sendPacket(recipeManager.getDeclareRecipesPacket());
sendPacket(recipeManager.getDeclareRecipesPacket());
List<String> recipesIdentifier = new ArrayList<>();
for (Recipe recipe : recipeManager.getRecipes()) {
if (!recipe.shouldShow(this))
continue;
recipesIdentifier.add(recipe.getRecipeId());
}
if (!recipesIdentifier.isEmpty()) {
@ -293,16 +291,16 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
false, false,
false, false,
recipesIdentifier, recipesIdentifier);
playerConnection.sendPacket(unlockRecipesPacket);
sendPacket(unlockRecipesPacket);
}
}
// Recipes end
// Tags
this.playerConnection.sendPacket(TagsPacket.DEFAULT_TAGS);
sendPacket(TagsPacket.DEFAULT_TAGS);
// Some client updates
this.playerConnection.sendPacket(getPropertiesPacket()); // Send default properties
sendPacket(getPropertiesPacket()); // Send default properties
triggerStatus((byte) (24 + permissionLevel)); // Set permission level
refreshHealth(); // Heal and send health packet
refreshAbilities(); // Send abilities packet
@ -402,14 +400,13 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
// #buildDeathScreenText can return null, check here
if (deathText != null) {
playerConnection.sendPacket(new DeathCombatEventPacket(getEntityId(), -1, deathText));
sendPacket(new DeathCombatEventPacket(getEntityId(), -1, deathText));
}
// #buildDeathMessage can return null, check here
if (chatMessage != null) {
Audiences.players().sendMessage(chatMessage);
}
}
super.kill();
}
@ -425,9 +422,8 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
setFireForDuration(0);
setOnFire(false);
refreshHealth();
RespawnPacket respawnPacket = new RespawnPacket(getDimensionType(), getDimensionType().getName().asString(),
0, gameMode, gameMode, false, levelFlat, true);
getPlayerConnection().sendPacket(respawnPacket);
sendPacket(new RespawnPacket(getDimensionType(), getDimensionType().getName().asString(),
0, gameMode, gameMode, false, levelFlat, true));
PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(this);
EventDispatcher.call(respawnEvent);
@ -443,8 +439,8 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* Sends necessary packets to synchronize player data after a {@link RespawnPacket}
*/
private void refreshClientStateAfterRespawn() {
this.playerConnection.sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation));
this.playerConnection.sendPacket(new SetExperiencePacket(exp, level, 0));
sendPacket(new UpdateHealthPacket(this.getHealth(), food, foodSaturation));
sendPacket(new SetExperiencePacket(exp, level, 0));
triggerStatus((byte) (24 + permissionLevel)); // Set permission level
refreshAbilities();
}
@ -455,9 +451,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* again, and any changes will be visible to the player.
*/
public void refreshCommands() {
CommandManager commandManager = MinecraftServer.getCommandManager();
DeclareCommandsPacket declareCommandsPacket = commandManager.createDeclareCommandsPacket(this);
playerConnection.sendPacket(declareCommandsPacket);
sendPacket(MinecraftServer.getCommandManager().createDeclareCommandsPacket(this));
}
@Override
@ -507,7 +501,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
@Override
public void sendPacketToViewersAndSelf(@NotNull SendablePacket packet) {
this.playerConnection.sendPacket(packet);
sendPacket(packet);
super.sendPacketToViewersAndSelf(packet);
}
@ -639,7 +633,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* @param data the message data
*/
public void sendPluginMessage(@NotNull String channel, byte @NotNull [] data) {
playerConnection.sendPacket(new PluginMessagePacket(channel, data));
sendPacket(new PluginMessagePacket(channel, data));
}
/**
@ -675,7 +669,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
@Override
public void playSound(@NotNull Sound sound, double x, double y, double z) {
playerConnection.sendPacket(AdventurePacketConvertor.createSoundPacket(sound, x, y, z));
sendPacket(AdventurePacketConvertor.createSoundPacket(sound, x, y, z));
}
@Override
@ -686,12 +680,12 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
} else {
packet = AdventurePacketConvertor.createSoundPacket(sound, emitter);
}
playerConnection.sendPacket(packet);
sendPacket(packet);
}
@Override
public void stopSound(@NotNull SoundStop stop) {
playerConnection.sendPacket(AdventurePacketConvertor.createSoundStopPacket(stop));
sendPacket(AdventurePacketConvertor.createSoundStopPacket(stop));
}
/**
@ -705,32 +699,32 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* @param disableRelativeVolume disable volume scaling based on distance
*/
public void playEffect(@NotNull Effects effect, int x, int y, int z, int data, boolean disableRelativeVolume) {
playerConnection.sendPacket(new EffectPacket(effect.getId(), new Vec(x, y, z), data, disableRelativeVolume));
sendPacket(new EffectPacket(effect.getId(), new Vec(x, y, z), data, disableRelativeVolume));
}
@Override
public void sendPlayerListHeaderAndFooter(@NotNull Component header, @NotNull Component footer) {
playerConnection.sendPacket(new PlayerListHeaderAndFooterPacket(header, footer));
sendPacket(new PlayerListHeaderAndFooterPacket(header, footer));
}
@Override
public <T> void sendTitlePart(@NotNull TitlePart<T> part, @NotNull T value) {
playerConnection.sendPacket(AdventurePacketConvertor.createTitlePartPacket(part, value));
sendPacket(AdventurePacketConvertor.createTitlePartPacket(part, value));
}
@Override
public void sendActionBar(@NotNull Component message) {
playerConnection.sendPacket(new ActionBarPacket(message));
sendPacket(new ActionBarPacket(message));
}
@Override
public void resetTitle() {
playerConnection.sendPacket(new ClearTitlesPacket(true));
sendPacket(new ClearTitlesPacket(true));
}
@Override
public void clearTitle() {
playerConnection.sendPacket(new ClearTitlesPacket(false));
sendPacket(new ClearTitlesPacket(false));
}
@Override
@ -753,11 +747,11 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
.pages(book.pages()))
.build();
// Set book in offhand
playerConnection.sendPacket(new SetSlotPacket((byte) 0, 0, (short) PlayerInventoryUtils.OFFHAND_SLOT, writtenBook));
sendPacket(new SetSlotPacket((byte) 0, 0, (short) PlayerInventoryUtils.OFFHAND_SLOT, writtenBook));
// Open the book
playerConnection.sendPacket(new OpenBookPacket(Hand.OFF));
sendPacket(new OpenBookPacket(Hand.OFF));
// Restore the item in offhand
playerConnection.sendPacket(new SetSlotPacket((byte) 0, 0, (short) PlayerInventoryUtils.OFFHAND_SLOT, getItemInOffHand()));
sendPacket(new SetSlotPacket((byte) 0, 0, (short) PlayerInventoryUtils.OFFHAND_SLOT, getItemInOffHand()));
}
@Override
@ -771,7 +765,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
@Override
public void setHealth(float health) {
super.setHealth(health);
this.playerConnection.sendPacket(new UpdateHealthPacket(health, food, foodSaturation));
sendPacket(new UpdateHealthPacket(health, food, foodSaturation));
}
@Override
@ -816,7 +810,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
Check.argCondition(!MathUtils.isBetween(food, 0, 20),
"Food has to be between 0 and 20");
this.food = food;
this.playerConnection.sendPacket(new UpdateHealthPacket(getHealth(), food, foodSaturation));
sendPacket(new UpdateHealthPacket(getHealth(), food, foodSaturation));
}
public float getFoodSaturation() {
@ -833,7 +827,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
Check.argCondition(!MathUtils.isBetween(foodSaturation, 0, 20),
"Food saturation has to be between 0 and 20");
this.foodSaturation = foodSaturation;
this.playerConnection.sendPacket(new UpdateHealthPacket(getHealth(), food, foodSaturation));
sendPacket(new UpdateHealthPacket(getHealth(), food, foodSaturation));
}
/**
@ -935,10 +929,10 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
RespawnPacket respawnPacket = new RespawnPacket(getDimensionType(), getDimensionType().getName().asString(),
0, gameMode, gameMode, false, levelFlat, true);
playerConnection.sendPacket(removePlayerPacket);
playerConnection.sendPacket(destroyEntitiesPacket);
playerConnection.sendPacket(addPlayerPacket);
playerConnection.sendPacket(respawnPacket);
sendPacket(removePlayerPacket);
sendPacket(destroyEntitiesPacket);
sendPacket(addPlayerPacket);
sendPacket(respawnPacket);
refreshClientStateAfterRespawn();
{
@ -1026,7 +1020,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* @param resourcePack the resource pack
*/
public void setResourcePack(@NotNull ResourcePack resourcePack) {
playerConnection.sendPacket(new ResourcePackSendPacket(resourcePack));
sendPacket(new ResourcePackSendPacket(resourcePack));
}
/**
@ -1053,7 +1047,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
private void facePosition(@NotNull FacePoint facePoint, @NotNull Point targetPosition,
@Nullable Entity entity, @Nullable FacePoint targetPoint) {
final int entityId = entity != null ? entity.getEntityId() : 0;
playerConnection.sendPacket(new FacePlayerPacket(
sendPacket(new FacePlayerPacket(
facePoint == FacePoint.EYE ?
FacePlayerPacket.FacePosition.EYES : FacePlayerPacket.FacePosition.FEET, targetPosition,
entityId,
@ -1067,7 +1061,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
* @param entity the entity to spectate
*/
public void spectate(@NotNull Entity entity) {
playerConnection.sendPacket(new CameraPacket(entity));
sendPacket(new CameraPacket(entity));
}
/**
@ -1142,7 +1136,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
public void setExp(float exp) {
Check.argCondition(!MathUtils.isBetween(exp, 0, 1), "Exp should be between 0 and 1");
this.exp = exp;
this.playerConnection.sendPacket(new SetExperiencePacket(exp, level, 0));
sendPacket(new SetExperiencePacket(exp, level, 0));
}
/**
@ -1162,7 +1156,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
*/
public void setLevel(int level) {
this.level = level;
this.playerConnection.sendPacket(new SetExperiencePacket(exp, level, 0));
sendPacket(new SetExperiencePacket(exp, level, 0));
}
/**
@ -1324,7 +1318,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
} else {
disconnectPacket = new DisconnectPacket(component);
}
playerConnection.sendPacket(disconnectPacket);
sendPacket(disconnectPacket);
playerConnection.disconnect();
}
@ -1346,7 +1340,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
public void setHeldItemSlot(byte slot) {
Check.argCondition(!MathUtils.isBetween(slot, 0, 8), "Slot has to be between 0 and 8");
refreshHeldSlot(slot);
this.playerConnection.sendPacket(new HeldItemChangePacket(slot));
sendPacket(new HeldItemChangePacket(slot));
}
/**
@ -1361,8 +1355,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
public void setTeam(Team team) {
super.setTeam(team);
if (team != null) {
var players = MinecraftServer.getConnectionManager().getOnlinePlayers();
PacketUtils.sendGroupedPacket(players, team.createTeamsCreationPacket());
PacketUtils.broadcastPacket(team.createTeamsCreationPacket());
}
}
@ -1411,7 +1404,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
return;
}
playerConnection.sendPacket(new OpenWindowPacket(newInventory.getWindowId(),
sendPacket(new OpenWindowPacket(newInventory.getWindowId(),
newInventory.getInventoryType().getWindowType(), newInventory.getTitle()));
newInventory.addViewer(this);
this.openInventory = newInventory;
@ -1450,7 +1443,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
openInventory.removeViewer(this); // Clear cache
this.openInventory = null;
}
playerConnection.sendPacket(closeWindowPacket);
sendPacket(closeWindowPacket);
inventory.update();
this.didCloseInventory = true;
}
@ -1501,7 +1494,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
@ApiStatus.Internal
protected void synchronizePosition(boolean includeSelf) {
if (includeSelf) {
playerConnection.sendPacket(new PlayerPositionAndLookPacket(position, (byte) 0x00, getNextTeleportId(), false));
sendPacket(new PlayerPositionAndLookPacket(position, (byte) 0x00, getNextTeleportId(), false));
}
super.synchronizePosition(includeSelf);
}
@ -1723,7 +1716,7 @@ public class Player extends LivingEntity implements CommandSender, Localizable,
flags |= PlayerAbilitiesPacket.FLAG_ALLOW_FLYING;
if (instantBreak)
flags |= PlayerAbilitiesPacket.FLAG_INSTANT_BREAK;
playerConnection.sendPacket(new PlayerAbilitiesPacket(flags, flyingSpeed, fieldViewModifier));
sendPacket(new PlayerAbilitiesPacket(flags, flyingSpeed, fieldViewModifier));
}
/**

View File

@ -130,7 +130,7 @@ public class FakePlayer extends Player implements NavigableEntity {
@Override
public void updateNewViewer(@NotNull Player player) {
player.getPlayerConnection().sendPacket(getAddPlayerToList());
player.sendPacket(getAddPlayerToList());
handleTabList(player.getPlayerConnection());
super.updateNewViewer(player);
}

View File

@ -18,6 +18,7 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Represents an inventory which can be viewed by a collection of {@link Player}.
@ -26,9 +27,7 @@ import java.util.concurrent.CopyOnWriteArraySet;
* It can then be opened using {@link Player#openInventory(Inventory)}.
*/
public non-sealed class Inventory extends AbstractInventory implements Viewable {
// incremented each time an inventory is created (used in the window packets)
private static byte LAST_INVENTORY_ID;
private static final AtomicInteger ID_COUNTER = new AtomicInteger();
// the id of this inventory
private final byte id;
@ -58,11 +57,8 @@ public non-sealed class Inventory extends AbstractInventory implements Viewable
this(inventoryType, Component.text(title));
}
private static synchronized byte generateId() {
if (LAST_INVENTORY_ID == Byte.MAX_VALUE) {
LAST_INVENTORY_ID = 0;
}
return ++LAST_INVENTORY_ID;
private static byte generateId() {
return (byte) Math.abs((byte) ID_COUNTER.incrementAndGet());
}
/**
@ -109,7 +105,7 @@ public non-sealed class Inventory extends AbstractInventory implements Viewable
@Override
public synchronized void clear() {
cursorPlayersItem.clear();
this.cursorPlayersItem.clear();
super.clear();
}

View File

@ -140,14 +140,8 @@ public non-sealed class PlayerInventory extends AbstractInventory implements Equ
case CHESTPLATE_SLOT -> EquipmentSlot.CHESTPLATE;
case LEGGINGS_SLOT -> EquipmentSlot.LEGGINGS;
case BOOTS_SLOT -> EquipmentSlot.BOOTS;
default -> {
if (slot == player.getHeldSlot()) {
yield EquipmentSlot.MAIN_HAND;
} else if (slot == OFFHAND_SLOT) {
yield EquipmentSlot.OFF_HAND;
}
yield null;
}
case OFFHAND_SLOT -> EquipmentSlot.OFF_HAND;
default -> slot == player.getHeldSlot() ? EquipmentSlot.MAIN_HAND : null;
};
if (equipmentSlot != null) {
EntityEquipEvent entityEquipEvent = new EntityEquipEvent(player, itemStack, equipmentSlot);

View File

@ -93,7 +93,7 @@ public class BlockPlacementListener {
// using refreshChunk results in the client not being in sync
// after rapid invalid block placements
final Block block = instance.getBlock(placementPosition);
player.getPlayerConnection().sendPacket(new BlockChangePacket(placementPosition, block));
player.sendPacket(new BlockChangePacket(placementPosition, block));
return;
}

View File

@ -45,10 +45,9 @@ public final class PlayerDiggingListener {
} else if (status == ClientPlayerDiggingPacket.Status.SWAP_ITEM_HAND) {
swapItemHand(player);
}
// Acknowledge start/cancel/finish digging status
if (diggingResult != null) {
player.getPlayerConnection().sendPacket(new AcknowledgePlayerDiggingPacket(blockPosition, diggingResult.block,
player.sendPacket(new AcknowledgePlayerDiggingPacket(blockPosition, diggingResult.block,
status, diggingResult.success));
}
}

View File

@ -7,7 +7,6 @@ import net.minestom.server.event.player.PlayerMoveEvent;
import net.minestom.server.instance.Instance;
import net.minestom.server.network.packet.client.play.*;
import net.minestom.server.network.packet.server.play.PlayerPositionAndLookPacket;
import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.chunk.ChunkUtils;
import org.jetbrains.annotations.NotNull;
@ -62,8 +61,7 @@ public class PlayerPositionListener {
}
if (playerMoveEvent.isCancelled()) {
// Teleport to previous position
PlayerConnection connection = player.getPlayerConnection();
connection.sendPacket(new PlayerPositionAndLookPacket(currentPosition, (byte) 0x00, player.getNextTeleportId(), false));
player.sendPacket(new PlayerPositionAndLookPacket(currentPosition, (byte) 0x00, player.getNextTeleportId(), false));
return;
}
final Pos eventPosition = playerMoveEvent.getNewPosition();

View File

@ -7,6 +7,6 @@ import net.minestom.server.network.packet.server.play.CraftRecipeResponse;
public class RecipeListener {
public static void listener(ClientCraftRecipeRequest packet, Player player) {
player.getPlayerConnection().sendPacket(new CraftRecipeResponse(packet.windowId(), packet.recipe()));
player.sendPacket(new CraftRecipeResponse(packet.windowId(), packet.recipe()));
}
}

View File

@ -24,9 +24,8 @@ public class StatusListener {
playerStatistic.getStatisticId(), value));
}
StatisticsPacket statisticsPacket = new StatisticsPacket(statisticList);
player.getPlayerConnection().sendPacket(statisticsPacket);
player.sendPacket(statisticsPacket);
}
}
}
}

View File

@ -57,10 +57,9 @@ public class TabCompleteListener {
Suggestion suggestion = new Suggestion(input, start, inputLength);
suggestionCallback.apply(player, queryResult.context(), suggestion);
player.getPlayerConnection().sendPacket(new TabCompletePacket(packet.transactionId(), suggestion.getStart(), suggestion.getLength(),
player.sendPacket(new TabCompletePacket(packet.transactionId(), suggestion.getStart(), suggestion.getLength(),
suggestion.getEntries().stream()
.map(suggestionEntry -> new TabCompletePacket.Match(suggestionEntry.getEntry(), suggestionEntry.getTooltip())).toList()));
}
}
}

View File

@ -78,7 +78,7 @@ public class WindowListener {
refreshCursorItem(player, inventory);
// (Why is the ping packet necessary?)
player.getPlayerConnection().sendPacket(new PingPacket((1 << 30) | (windowId << 16)));
player.sendPacket(new PingPacket((1 << 30) | (windowId << 16)));
}
public static void pong(ClientPongPacket packet, Player player) {
@ -111,7 +111,7 @@ public class WindowListener {
throw new RuntimeException("Invalid inventory: " + inventory.getClass());
}
final SetSlotPacket setSlotPacket = SetSlotPacket.createCursorPacket(cursorItem);
player.getPlayerConnection().sendPacket(setSlotPacket);
player.sendPacket(setSlotPacket);
}
private static void setCursor(Player player, AbstractInventory inventory, ItemStack itemStack) {

View File

@ -34,10 +34,9 @@ public class Messenger {
*/
public static boolean sendMessage(@NotNull Player player, @NotNull Component message, @NotNull ChatPosition position, @Nullable UUID uuid) {
if (getChatMessageType(player).accepts(position)) {
player.getPlayerConnection().sendPacket(new ChatMessagePacket(message, position, uuid));
player.sendPacket(new ChatMessagePacket(message, position, uuid));
return true;
}
return false;
}
@ -81,7 +80,7 @@ public class Messenger {
* @param player the player
*/
public static void sendRejectionMessage(@NotNull Player player) {
player.getPlayerConnection().sendPacket(CANNOT_SEND_PACKET);
player.sendPacket(CANNOT_SEND_PACKET);
}
/**

View File

@ -278,9 +278,8 @@ public final class ConnectionManager {
for (Player player : getOnlinePlayers()) {
final long lastKeepAlive = tickStart - player.getLastKeepAlive();
if (lastKeepAlive > KEEP_ALIVE_DELAY && player.didAnswerKeepAlive()) {
final PlayerConnection playerConnection = player.getPlayerConnection();
player.refreshKeepAlive(tickStart);
playerConnection.sendPacket(keepAlivePacket);
player.sendPacket(keepAlivePacket);
} else if (lastKeepAlive >= KEEP_ALIVE_KICK) {
player.kick(TIMEOUT_TEXT);
}

View File

@ -3,7 +3,6 @@ package net.minestom.server.scoreboard;
import net.kyori.adventure.text.Component;
import net.minestom.server.entity.Player;
import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket;
import net.minestom.server.network.player.PlayerConnection;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
@ -56,29 +55,22 @@ public class BelowNameTag implements Scoreboard {
@Override
public boolean addViewer(@NotNull Player player) {
boolean result = this.viewers.add(player);
PlayerConnection connection = player.getPlayerConnection();
final boolean result = this.viewers.add(player);
if (result) {
connection.sendPacket(this.scoreboardObjectivePacket);
connection.sendPacket(this.getDisplayScoreboardPacket((byte) 2));
player.sendPacket(this.scoreboardObjectivePacket);
player.sendPacket(this.getDisplayScoreboardPacket((byte) 2));
player.setBelowNameTag(this);
}
return result;
}
@Override
public boolean removeViewer(@NotNull Player player) {
boolean result = this.viewers.remove(player);
PlayerConnection connection = player.getPlayerConnection();
final boolean result = this.viewers.remove(player);
if (result) {
connection.sendPacket(this.getDestructionObjectivePacket());
player.sendPacket(this.getDestructionObjectivePacket());
player.setBelowNameTag(null);
}
return result;
}

View File

@ -8,7 +8,6 @@ import net.minestom.server.network.packet.server.play.DisplayScoreboardPacket;
import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket;
import net.minestom.server.network.packet.server.play.TeamsPacket;
import net.minestom.server.network.packet.server.play.UpdateScorePacket;
import net.minestom.server.network.player.PlayerConnection;
import net.minestom.server.utils.validate.Check;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -208,17 +207,15 @@ public class Sidebar implements Scoreboard {
@Override
public boolean addViewer(@NotNull Player player) {
final boolean result = this.viewers.add(player);
PlayerConnection playerConnection = player.getPlayerConnection();
ScoreboardObjectivePacket scoreboardObjectivePacket = this.getCreationObjectivePacket(this.title, ScoreboardObjectivePacket.Type.INTEGER);
DisplayScoreboardPacket displayScoreboardPacket = this.getDisplayScoreboardPacket((byte) 1);
playerConnection.sendPacket(scoreboardObjectivePacket); // Creative objective
playerConnection.sendPacket(displayScoreboardPacket); // Show sidebar scoreboard (wait for scores packet)
player.sendPacket(scoreboardObjectivePacket); // Creative objective
player.sendPacket(displayScoreboardPacket); // Show sidebar scoreboard (wait for scores packet)
for (ScoreboardLine line : lines) {
playerConnection.sendPacket(line.sidebarTeam.getCreationPacket());
playerConnection.sendPacket(line.getScoreCreationPacket(objectiveName));
player.sendPacket(line.sidebarTeam.getCreationPacket());
player.sendPacket(line.getScoreCreationPacket(objectiveName));
}
return result;
}
@ -226,13 +223,11 @@ public class Sidebar implements Scoreboard {
@Override
public boolean removeViewer(@NotNull Player player) {
final boolean result = this.viewers.remove(player);
PlayerConnection playerConnection = player.getPlayerConnection();
ScoreboardObjectivePacket scoreboardObjectivePacket = this.getDestructionObjectivePacket();
playerConnection.sendPacket(scoreboardObjectivePacket);
player.sendPacket(scoreboardObjectivePacket);
for (ScoreboardLine line : lines) {
playerConnection.sendPacket(line.getScoreDestructionPacket(objectiveName)); // Is it necessary?
playerConnection.sendPacket(line.sidebarTeam.getDestructionPacket());
player.sendPacket(line.getScoreDestructionPacket(objectiveName)); // Is it necessary?
player.sendPacket(line.sidebarTeam.getDestructionPacket());
}
return result;
}

View File

@ -3,7 +3,6 @@ package net.minestom.server.scoreboard;
import net.kyori.adventure.text.Component;
import net.minestom.server.entity.Player;
import net.minestom.server.network.packet.server.play.ScoreboardObjectivePacket;
import net.minestom.server.network.player.PlayerConnection;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
@ -52,26 +51,20 @@ public class TabList implements Scoreboard {
@Override
public boolean addViewer(@NotNull Player player) {
boolean result = this.viewers.add(player);
PlayerConnection connection = player.getPlayerConnection();
final boolean result = this.viewers.add(player);
if (result) {
connection.sendPacket(this.getCreationObjectivePacket(Component.empty(), this.type));
connection.sendPacket(this.getDisplayScoreboardPacket((byte) 0));
player.sendPacket(this.getCreationObjectivePacket(Component.empty(), this.type));
player.sendPacket(this.getDisplayScoreboardPacket((byte) 0));
}
return result;
}
@Override
public boolean removeViewer(@NotNull Player player) {
boolean result = this.viewers.remove(player);
PlayerConnection connection = player.getPlayerConnection();
final boolean result = this.viewers.remove(player);
if (result) {
connection.sendPacket(this.getDestructionObjectivePacket());
player.sendPacket(this.getDestructionObjectivePacket());
}
return result;
}

View File

@ -79,14 +79,14 @@ public final class PacketUtils {
*/
@SuppressWarnings("OverrideOnly") // we need to access the audiences inside ForwardingAudience
public static void sendPacket(@NotNull Audience audience, @NotNull ServerPacket packet) {
if (audience instanceof Player) {
((Player) audience).getPlayerConnection().sendPacket(packet);
} else if (audience instanceof PacketGroupingAudience) {
PacketUtils.sendGroupedPacket(((PacketGroupingAudience) audience).getPlayers(), packet);
} else if (audience instanceof ForwardingAudience.Single) {
PacketUtils.sendPacket(((ForwardingAudience.Single) audience).audience(), packet);
} else if (audience instanceof ForwardingAudience) {
for (Audience member : ((ForwardingAudience) audience).audiences()) {
if (audience instanceof Player player) {
player.sendPacket(packet);
} else if (audience instanceof PacketGroupingAudience groupingAudience) {
PacketUtils.sendGroupedPacket(groupingAudience.getPlayers(), packet);
} else if (audience instanceof ForwardingAudience.Single singleAudience) {
PacketUtils.sendPacket(singleAudience.audience(), packet);
} else if (audience instanceof ForwardingAudience forwardingAudience) {
for (Audience member : forwardingAudience.audiences()) {
PacketUtils.sendPacket(member, packet);
}
}