Java Code Examples for com.comphenix.protocol.events.PacketContainer

The following examples show how to use com.comphenix.protocol.events.PacketContainer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: SuperVanish   Source File: NightVision.java    License: Mozilla Public License 2.0 7 votes vote down vote up
private void sendAddPotionEffect(Player p, PotionEffect effect) {
    PacketContainer packet = new PacketContainer(ENTITY_EFFECT);
    //noinspection deprecation
    int effectID = effect.getType().getId();
    int amplifier = effect.getAmplifier();
    int duration = effect.getDuration();
    int entityID = p.getEntityId();
    packet.getIntegers().write(0, entityID);
    packet.getBytes().write(0, (byte) effectID);
    packet.getBytes().write(1, (byte) amplifier);
    packet.getIntegers().write(1, duration);
    // hide particles in 1.9
    packet.getBytes().write(2, (byte) 0);
    try {
        ProtocolLibrary.getProtocolManager().sendServerPacket(p, packet);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Cannot send packet", e);
    }
}
 
Example 2
Source Project: FastLogin   Source File: ProtocolLibLoginSource.java    License: MIT License 6 votes vote down vote up
@Override
public void setOnlineMode() throws Exception {
    verifyToken = EncryptionUtil.generateVerifyToken(random);

    /*
     * Packet Information: https://wiki.vg/Protocol#Encryption_Request
     *
     * ServerID="" (String) key=public server key verifyToken=random 4 byte array
     */
    PacketContainer newPacket = new PacketContainer(ENCRYPTION_BEGIN);

    newPacket.getStrings().write(0, serverId);
    newPacket.getSpecificModifier(PublicKey.class).write(0, publicKey);

    newPacket.getByteArrays().write(0, verifyToken);

    //serverId is a empty string
    ProtocolLibrary.getProtocolManager().sendServerPacket(player, newPacket);
}
 
Example 3
Source Project: ChangeSkin   Source File: SkinApplier.java    License: MIT License 6 votes vote down vote up
private PacketContainer createRespawnPacket(NativeGameMode gamemode) throws ReflectiveOperationException {
    PacketContainer respawn = new PacketContainer(RESPAWN);

    Difficulty difficulty = EnumWrappers.getDifficultyConverter().getSpecific(receiver.getWorld().getDifficulty());

    //<= 1.13.1
    int dimensionId = receiver.getWorld().getEnvironment().getId();
    respawn.getIntegers().writeSafely(0, dimensionId);

    //> 1.13.1
    if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.AQUATIC_UPDATE) > 0) {
        try {
            respawn.getDimensions().writeSafely(0, dimensionId);
        } catch (NoSuchMethodError noSuchMethodError) {
            throw new ReflectiveOperationException("Unable to find dimension setter. " +
                    "Your ProtocolLib version is incompatible with this plugin version in combination with " +
                    "Minecraft 1.13.1. " +
                    "Try to download an update of ProtocolLib.", noSuchMethodError);
        }
    }

    respawn.getDifficulties().writeSafely(0, difficulty);
    respawn.getGameModes().write(0, gamemode);
    respawn.getWorldTypeModifier().write(0, receiver.getWorld().getWorldType());
    return respawn;
}
 
Example 4
Source Project: helper   Source File: PacketScoreboardObjective.java    License: MIT License 6 votes vote down vote up
private PacketContainer newScorePacket(String name, int value, ScoreboardAction action) {
    // http://wiki.vg/Protocol#Update_Score
    PacketContainer packet = new PacketContainer(PacketType.Play.Server.SCOREBOARD_SCORE);

    // set "Entity name" - aka the name of the score - limited to 40.
    packet.getStrings().write(0, name);

    // set the action - 0 to create/update an item. 1 to remove an item.
    packet.getScoreboardActions().write(0, action);

    // set objective name - The name of the objective the score belongs to
    packet.getStrings().write(1, getId());

    // set value of the score- The score to be displayed next to the entry. Only sent when Action does not equal 1.
    packet.getIntegers().write(0, value);

    return packet;
}
 
Example 5
Source Project: NameTagChanger   Source File: ProtocolLibPacketHandler.java    License: MIT License 6 votes vote down vote up
@Override
public void sendNamedEntitySpawnPacket(Player playerToSpawn, Player seer) {
    PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.NAMED_ENTITY_SPAWN);
    packet.getIntegers().write(0, playerToSpawn.getEntityId());
    packet.getUUIDs().write(0, playerToSpawn.getUniqueId());
    if (ReflectUtil.isVersionHigherThan(1, 8, 8)) {
        packet.getDoubles().write(0, playerToSpawn.getLocation().getX());
        packet.getDoubles().write(1, playerToSpawn.getLocation().getY());
        packet.getDoubles().write(2, playerToSpawn.getLocation().getZ());
    } else {
        packet.getIntegers().write(0, (int) Math.floor(playerToSpawn.getLocation().getX() * 32D));
        packet.getIntegers().write(1, (int) Math.floor(playerToSpawn.getLocation().getY() * 32D));
        packet.getIntegers().write(2, (int) Math.floor(playerToSpawn.getLocation().getZ() * 32D));
    }
    packet.getBytes().write(0, (byte) (playerToSpawn.getLocation().getYaw() * 256F / 360F));
    packet.getBytes().write(1, (byte) (playerToSpawn.getLocation().getPitch() * 256F / 360F));
    packet.getDataWatcherModifier().write(0, WrappedDataWatcher.getEntityWatcher(playerToSpawn));
    try {
        ProtocolLibrary.getProtocolManager().sendServerPacket(seer, packet);
    } catch (InvocationTargetException e) {
        logMessage(Level.SEVERE, "Failed to send named entity spawn packet!", e);
    }
}
 
Example 6
private void sendNbt(Vector pos, NbtCompound compound) {
    Player player = this.<Player>getPlayer().parent;
    ProtocolManager manager = ProtocolLibrary.getProtocolManager();

    PacketContainer blockNbt = new PacketContainer(PacketType.Play.Server.TILE_ENTITY_DATA);
    blockNbt.getBlockPositionModifier().write(0, new BlockPosition(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()));
    blockNbt.getIntegers().write(0, 7);
    blockNbt.getNbtModifier().write(0, compound);


    try {
        manager.sendServerPacket(player, blockNbt);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: CombatLogX   Source File: ForceFieldAdapter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent e) {
    if(e.isCancelled()) return;

    Player player = e.getPlayer();
    ICombatManager combatManager = this.plugin.getCombatManager();
    if(!combatManager.isInCombat(player)) return;

    UUID uuid = player.getUniqueId();
    PacketContainer packet = e.getPacket();
    World world = player.getWorld();

    WrapperPlayServerBlockChange block = new WrapperPlayServerBlockChange(packet);
    Location location = packet.getBlockPositionModifier().read(0).toLocation(world);
    if(this.forceField.fakeBlocks.containsKey(uuid) && this.forceField.isSafe(location, player) && this.forceField.isSafeSurround(location, player) && ForceField.canPlace(location) && this.forceField.fakeBlocks.get(uuid).contains(location)) {
        block.setBlockData(this.forceField.wrappedData(block.getBlockData()));
    }
}
 
Example 8
private void sendPacket(@NotNull Player player, @NotNull PacketContainer packet) {
    try {
        protocolManager.sendServerPacket(player, packet);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("An error occurred when sending a packet", e);
    }
}
 
Example 9
Source Project: helper   Source File: PacketIndividualHologramFactory.java    License: MIT License 5 votes vote down vote up
@Override
public void removeViewer(@Nonnull Player player) {
    if (!this.viewers.remove(player)) {
        return;
    }

    // handle removing the existing entity?
    PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);

    // set ids
    int[] ids = this.spawnedEntities.stream().mapToInt(HologramEntity::getId).toArray();
    destroyPacket.getIntegerArrays().write(0, ids);

    Protocol.sendPacket(player, destroyPacket);
}
 
Example 10
Source Project: ScoreboardStats   Source File: Objective.java    License: MIT License 5 votes vote down vote up
private void sendScorePacket(String name, int score, ScoreboardAction action) {
    PacketContainer packet = new PacketContainer(SCOREBOARD_SCORE);
    packet.getStrings().write(0, name);
    packet.getStrings().write(1, objectiveId);

    packet.getIntegers().write(0, score);

    packet.getScoreboardActions().write(0, action);

    scoreboard.sendPacket(packet);
}
 
Example 11
Source Project: NameTagChanger   Source File: ProtocolLibPacketHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void sendTabListRemovePacket(Player playerToRemove, Player seer) {
    PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
    packet.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.REMOVE_PLAYER);
    PlayerInfoData playerInfoData = new PlayerInfoData(WrappedGameProfile.fromPlayer(playerToRemove), 0, EnumWrappers.NativeGameMode.NOT_SET, null);
    packet.getPlayerInfoDataLists().write(0, Collections.singletonList(playerInfoData));
    try {
        ProtocolLibrary.getProtocolManager().sendServerPacket(seer, packet);
    } catch (InvocationTargetException e) {
        logMessage(Level.SEVERE, "Failed to send tab list remove packet!", e);
    }
}
 
Example 12
Source Project: NameTagChanger   Source File: ProtocolLibPacketHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void sendEntityDestroyPacket(Player playerToDestroy, Player seer) {
    PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_DESTROY);
    packet.getIntegerArrays().write(0, new int[] {playerToDestroy.getEntityId()});
    try {
        ProtocolLibrary.getProtocolManager().sendServerPacket(seer, packet);
    } catch (InvocationTargetException e) {
        logMessage(Level.SEVERE, "Failed to send entity destroy packet!", e);
    }
}
 
Example 13
/**
 * Constructs a new strongly typed wrapper for the given packet.
 * @param handle - handle to the raw packet data.
 * @param type - the packet type.
 */
protected AbstractPacket(PacketContainer handle, PacketType type) {
	// Make sure we're given a valid packet
	if (handle == null)
		throw new IllegalArgumentException("Packet handle cannot be NULL.");
	if (!Objects.equal(handle.getType(), type))
		throw new IllegalArgumentException(
				handle.getHandle() + " is not a packet of type " + type);

	this.handle = handle;
}
 
Example 14
private void sendOp() {
    Player player = this.<Player>getPlayer().parent;
    ProtocolManager manager = ProtocolLibrary.getProtocolManager();

    PacketConstructor statusCtr = manager.createPacketConstructor(PacketType.Play.Server.ENTITY_STATUS, player, (byte) 28);
    PacketContainer status = statusCtr.createPacket(player, (byte) 28);

    try {
        manager.sendServerPacket(player, status);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
 
Example 15
Source Project: BungeeGuard   Source File: ProtocolHandshakeListener.java    License: MIT License 5 votes vote down vote up
private static void closeConnection(Player player, String kickMessage) throws Exception {
    PacketContainer packet = new PacketContainer(PacketType.Login.Server.DISCONNECT);
    packet.getModifier().writeDefaults();

    WrappedChatComponent component = WrappedChatComponent.fromJson(ComponentSerializer.toString(TextComponent.fromLegacyText(kickMessage)));
    packet.getChatComponents().write(0, component);

    ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
    TemporaryPlayerFactory.getInjectorFromPlayer(player).getSocket().close();
}
 
Example 16
Source Project: BetonQuest   Source File: PacketInterceptor.java    License: GNU General Public License v3.0 5 votes vote down vote up
public PacketInterceptor(Conversation conv, String playerID) {
    this.conv = conv;
    this.player = PlayerConverter.getPlayer(playerID);

    // Intercept Packets
    packetAdapter = new PacketAdapter(BetonQuest.getInstance(), ListenerPriority.HIGHEST,
            PacketType.Play.Server.CHAT

    ) {
        @Override
        public void onPacketSending(PacketEvent event) {
            if (event.getPlayer() != player) {
                return;
            }

            if (event.getPacketType().equals(PacketType.Play.Server.CHAT)) {
                PacketContainer packet = event.getPacket();
                BaseComponent[] bc = (BaseComponent[]) packet.getModifier().read(1);
                if (bc != null && bc.length > 0 && ((TextComponent) bc[0]).getText().contains("_bq_")) {
                    packet.getModifier().write(1, Arrays.copyOfRange(bc, 1, bc.length));
                    event.setPacket(packet);
                    return;
                }

                // Else save message to replay later
                WrapperPlayServerChat chat = new WrapperPlayServerChat(event.getPacket());
                event.setCancelled(true);
                messages.add(chat);
            }
        }
    };

    ProtocolLibrary.getProtocolManager().addPacketListener(packetAdapter);
}
 
Example 17
Source Project: tabbed   Source File: Packets.java    License: MIT License 5 votes vote down vote up
/**
 * Sends a list of ProtocolLib packets to a player.
 * @param player
 * @param packets
 * @return
 */
public static void send(Player player, List<PacketContainer> packets) {
    try {
        for (PacketContainer packet : packets)
            ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
 
Example 18
/**
 * Constructs a new strongly typed wrapper for the given packet.
 * @param handle - handle to the raw packet data.
 * @param type - the packet type.
 */
protected AbstractPacket(PacketContainer handle, PacketType type) {
	// Make sure we're given a valid packet
	if (handle == null)
		throw new IllegalArgumentException("Packet handle cannot be NULL.");
	if (!Objects.equal(handle.getType(), type))
		throw new IllegalArgumentException(
				handle.getHandle() + " is not a packet of type " + type);
	
	this.handle = handle;
}
 
Example 19
Source Project: FastLogin   Source File: VerifyResponseTask.java    License: MIT License 5 votes vote down vote up
private void kickPlayer(String reason) {
    PacketContainer kickPacket = new PacketContainer(DISCONNECT);
    kickPacket.getChatComponents().write(0, WrappedChatComponent.fromText(reason));
    try {
        //send kick packet at login state
        //the normal event.getPlayer.kickPlayer(String) method does only work at play state
        ProtocolLibrary.getProtocolManager().sendServerPacket(player, kickPacket);
        //tell the server that we want to close the connection
        player.kickPlayer("Disconnect");
    } catch (InvocationTargetException ex) {
        plugin.getLog().error("Error sending kick packet for: {}", player, ex);
    }
}
 
Example 20
Source Project: ScoreboardStats   Source File: Objective.java    License: MIT License 5 votes vote down vote up
void sendShowPacket() {
    PacketContainer packet = new PacketContainer(SCOREBOARD_DISPLAY_OBJECTIVE);
    packet.getStrings().write(0, objectiveId);

    packet.getIntegers().write(0, SIDEBAR_SLOT);
    scoreboard.sendPacket(packet);
}
 
Example 21
@Override
public void onPacketSending(PacketEvent packetEvent) {
    Player player = packetEvent.getPlayer();
    PacketContainer packet = packetEvent.getPacket();

    int windowId = packet.getIntegers().read(0);
    if (windowId == PLAYER_INVENTORY && shouldHideInventory(player.getName())) {
        packetEvent.setCancelled(true);
    }
}
 
Example 22
public WrapperLoginServerEncryptionBegin() {
    super(new PacketContainer(TYPE), TYPE);
    handle.getModifier().writeDefaults();
}
 
Example 23
public WrapperPlayServerScoreboardTeam(PacketContainer packet) {
    super(packet, TYPE);
}
 
Example 24
public WrapperPlayClientHeldItemSlot(PacketContainer packet) {
    super(packet, TYPE);
}
 
Example 25
public WrapperPlayClientSetCreativeSlot() {
    super(new PacketContainer(TYPE), TYPE);
    handle.getModifier().writeDefaults();
}
 
Example 26
Source Project: helper   Source File: PacketSignPromptFactory.java    License: MIT License 4 votes vote down vote up
@Override
public void openPrompt(@Nonnull Player player, @Nonnull List<String> lines, @Nonnull ResponseHandler responseHandler) {
    Location location = player.getLocation().clone();
    location.setY(255);
    Players.sendBlockChange(player, location, Material.WALL_SIGN);

    BlockPosition position = new BlockPosition(location.toVector());
    PacketContainer writeToSign = new PacketContainer(PacketType.Play.Server.TILE_ENTITY_DATA);
    writeToSign.getBlockPositionModifier().write(0, position);
    writeToSign.getIntegers().write(0, 9);
    NbtCompound compound = NbtFactory.ofCompound("");

    for (int i = 0; i < 4; i++) {
        compound.put("Text" + (i + 1), "{\"text\":\"" + (lines.size() > i ? lines.get(i) : "") + "\"}");
    }

    compound.put("id", "minecraft:sign");
    compound.put("x", position.getX());
    compound.put("y", position.getY());
    compound.put("z", position.getZ());

    writeToSign.getNbtModifier().write(0, compound);
    Protocol.sendPacket(player, writeToSign);

    PacketContainer openSign = new PacketContainer(PacketType.Play.Server.OPEN_SIGN_EDITOR);
    openSign.getBlockPositionModifier().write(0, position);
    Protocol.sendPacket(player, openSign);

    // we need to ensure that the callback is only called once.
    final AtomicBoolean active = new AtomicBoolean(true);

    Protocol.subscribe(PacketType.Play.Client.UPDATE_SIGN)
            .filter(e -> e.getPlayer().getUniqueId().equals(player.getUniqueId()))
            .biHandler((sub, event) -> {
                if (!active.getAndSet(false)) {
                    return;
                }

                PacketContainer container = event.getPacket();

                List<String> input = new ArrayList<>(Arrays.asList(container.getStringArrays().read(0)));
                Response response = responseHandler.handleResponse(input);

                if (response == Response.TRY_AGAIN) {
                    // didn't pass, re-send the sign and request another input
                    Schedulers.sync().runLater(() -> {
                        if (player.isOnline()) {
                            openPrompt(player, lines, responseHandler);
                        }
                    }, 1L);
                }

                // cleanup this instance
                sub.close();
                Players.sendBlockChange(player, location, Material.AIR);
            });
}
 
Example 27
public WrapperPlayServerNamedEntitySpawn() {
    super(new PacketContainer(TYPE), TYPE);
    handle.getModifier().writeDefaults();
}
 
Example 28
public WrapperPlayServerUpdateHealth(PacketContainer packet) {
    super(packet, TYPE);
}
 
Example 29
Source Project: helper   Source File: PacketScoreboardTeam.java    License: MIT License 4 votes vote down vote up
private PacketContainer newUpdatePacket() {
    // http://wiki.vg/Protocol#Teams
    PacketContainer packet = new PacketContainer(PacketType.Play.Server.SCOREBOARD_TEAM);

    // set team name - 	String (16)
    packet.getStrings().write(0, getId());

    // set mode - byte
    packet.getIntegers().write(GTEQ_1_13 ? 0 : 1, UpdateType.UPDATE.getCode());

    if (GTEQ_1_13) {
        // set display name - Component
        packet.getChatComponents().write(0, PacketScoreboard.toComponent(getDisplayName()));

        // set prefix - Component
        packet.getChatComponents().write(1, PacketScoreboard.toComponent(getPrefix()));

        // set suffix - Component
        packet.getChatComponents().write(2, PacketScoreboard.toComponent(getSuffix()));
    } else {
        // set display name - String(32)
        packet.getStrings().write(1, getDisplayName());

        // set prefix - String(16)
        packet.getStrings().write(2, getPrefix());

        // set suffix - String(16)
        packet.getStrings().write(3, getSuffix());
    }

    // set friendly flags - byte - Bit mask. 0x01: Allow friendly fire, 0x02: can see invisible entities on same team
    int data = 0;
    if (isAllowFriendlyFire()) {
        data |= 1;
    }
    if (isCanSeeFriendlyInvisibles()) {
        data |= 2;
    }

    packet.getIntegers().write(GTEQ_1_13 ? 1 : 2, data);

    // set nametag visibility - String Enum (32)
    packet.getStrings().write(GTEQ_1_13 ? 1 : 4, getNameTagVisibility().getProtocolName());

    if (SUPPORTS_COLLISION_RULE) {
        // set collision rule - String Enum (32)
        packet.getStrings().write(GTEQ_1_13 ? 2 : 5, getCollisionRule().getProtocolName());
    }

    // set color - byte - For colors, the same Chat colors (0-15). -1 indicates RESET/no color.
    if (GTEQ_1_13) {
        packet.getEnumModifier(ChatColor.class, MinecraftReflection.getMinecraftClass("EnumChatFormat")).write(0, getColor());
    } else {
        packet.getIntegers().write(0, COLOR_CODES.getOrDefault(getColor(), -1));
    }

    return packet;
}
 
Example 30
public WrapperPlayClientUpdateSign(PacketContainer packet) {
    super(packet, TYPE);
}