Search in sources :

Example 26 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaBackwards by ViaVersion.

the class ShoulderTracker method update.

public void update() {
    PacketWrapper wrapper = PacketWrapper.create(ClientboundPackets1_12.CHAT_MESSAGE, null, getUser());
    wrapper.write(Type.COMPONENT, Protocol1_9To1_8.fixJson(generateString()));
    wrapper.write(Type.BYTE, (byte) 2);
    try {
        wrapper.scheduleSend(Protocol1_11_1To1_12.class);
    } catch (Exception e) {
        ViaBackwards.getPlatform().getLogger().severe("Failed to send the shoulder indication");
        e.printStackTrace();
    }
}
Also used : PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper)

Example 27 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project DirtMultiversion by DirtPowered.

the class ViaPlugin method tick.

@Override
public void tick() {
    for (UserData userData : api.getAllConnections()) {
        ProtocolStorage s = userData.getProtocolStorage();
        if (!s.hasObject(PlayerMovementTracker.class))
            return;
        PlayerMovementTracker movementTracker = s.get(PlayerMovementTracker.class);
        if ((System.currentTimeMillis() - movementTracker.getLastLocationUpdate()) >= 50) {
            if (userData.getUniqueId() == null)
                return;
            UserConnection userConnection = connectionManager.getConnectedClient(userData.getUniqueId());
            if (userConnection == null)
                return;
            ProtocolInfo protocolInfo = userConnection.getProtocolInfo();
            if (protocolInfo == null)
                return;
            if (protocolInfo.getPipeline().contains(Protocol1_9To1_8.class) && protocolInfo.getState() == State.PLAY) {
                PacketWrapper wrapper = new PacketWrapperImpl(0x03, null, userConnection);
                wrapper.write(Type.BOOLEAN, true);
                try {
                    wrapper.sendToServer(Protocol1_9To1_8.class, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Also used : ProtocolStorage(com.github.dirtpowered.dirtmv.data.user.ProtocolStorage) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) UserData(com.github.dirtpowered.dirtmv.data.user.UserData) PacketWrapperImpl(com.viaversion.viaversion.protocol.packet.PacketWrapperImpl) ProtocolInfo(com.viaversion.viaversion.api.connection.ProtocolInfo) UserConnection(com.viaversion.viaversion.api.connection.UserConnection) PlayerMovementTracker(com.github.dirtpowered.dirtmv.network.versions.Release47To5.entity.PlayerMovementTracker) Protocol1_9To1_8(com.viaversion.viaversion.protocols.protocol1_9to1_8.Protocol1_9To1_8)

Example 28 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class BungeeServerHandler method checkServerChange.

public void checkServerChange(ServerConnectedEvent e, UserConnection user) throws Exception {
    if (user == null)
        return;
    // Handle server/version change
    if (user.has(BungeeStorage.class)) {
        BungeeStorage storage = user.get(BungeeStorage.class);
        ProxiedPlayer player = storage.getPlayer();
        if (e.getServer() != null) {
            if (!e.getServer().getInfo().getName().equals(storage.getCurrentServer())) {
                // Clear auto-team
                EntityTracker1_9 oldEntityTracker = user.getEntityTracker(Protocol1_9To1_8.class);
                if (oldEntityTracker != null) {
                    if (oldEntityTracker.isAutoTeam() && oldEntityTracker.isTeamExists()) {
                        oldEntityTracker.sendTeamPacket(false, true);
                    }
                }
                String serverName = e.getServer().getInfo().getName();
                storage.setCurrentServer(serverName);
                int protocolId = ProtocolDetectorService.getProtocolId(serverName);
                if (protocolId <= ProtocolVersion.v1_8.getVersion()) {
                    // 1.8 doesn't have BossBar packet
                    if (storage.getBossbar() != null) {
                        // This ensures we can encode it properly as only the 1.9 protocol is currently implemented.
                        if (user.getProtocolInfo().getPipeline().contains(Protocol1_9To1_8.class)) {
                            for (UUID uuid : storage.getBossbar()) {
                                PacketWrapper wrapper = PacketWrapper.create(ClientboundPackets1_9.BOSSBAR, null, user);
                                wrapper.write(Type.UUID, uuid);
                                // remove
                                wrapper.write(Type.VAR_INT, 1);
                                wrapper.send(Protocol1_9To1_8.class);
                            }
                        }
                        storage.getBossbar().clear();
                    }
                }
                ProtocolInfo info = user.getProtocolInfo();
                int previousServerProtocol = info.getServerProtocolVersion();
                // Refresh the pipes
                List<ProtocolPathEntry> protocolPath = Via.getManager().getProtocolManager().getProtocolPath(info.getProtocolVersion(), protocolId);
                ProtocolPipeline pipeline = user.getProtocolInfo().getPipeline();
                user.clearStoredObjects();
                pipeline.cleanPipes();
                if (protocolPath == null) {
                    // TODO Check Bungee Supported Protocols? *shrugs*
                    protocolId = info.getProtocolVersion();
                } else {
                    List<Protocol> protocols = new ArrayList<>(protocolPath.size());
                    for (ProtocolPathEntry entry : protocolPath) {
                        protocols.add(entry.protocol());
                    }
                    pipeline.add(protocols);
                }
                info.setServerProtocolVersion(protocolId);
                // Add version-specific base Protocol
                pipeline.add(Via.getManager().getProtocolManager().getBaseProtocol(protocolId));
                // Workaround 1.13 server change
                int id1_13 = ProtocolVersion.v1_13.getVersion();
                boolean toNewId = previousServerProtocol < id1_13 && protocolId >= id1_13;
                boolean toOldId = previousServerProtocol >= id1_13 && protocolId < id1_13;
                if (previousServerProtocol != -1 && (toNewId || toOldId)) {
                    Collection<String> registeredChannels = (Collection<String>) getRegisteredChannels.invoke(e.getPlayer().getPendingConnection());
                    if (!registeredChannels.isEmpty()) {
                        Collection<String> newChannels = new HashSet<>();
                        for (Iterator<String> iterator = registeredChannels.iterator(); iterator.hasNext(); ) {
                            String channel = iterator.next();
                            String oldChannel = channel;
                            if (toNewId) {
                                channel = InventoryPackets.getNewPluginChannelId(channel);
                            } else {
                                channel = InventoryPackets.getOldPluginChannelId(channel);
                            }
                            if (channel == null) {
                                iterator.remove();
                                continue;
                            }
                            if (!oldChannel.equals(channel)) {
                                iterator.remove();
                                newChannels.add(channel);
                            }
                        }
                        registeredChannels.addAll(newChannels);
                    }
                    PluginMessage brandMessage = (PluginMessage) getBrandMessage.invoke(e.getPlayer().getPendingConnection());
                    if (brandMessage != null) {
                        String channel = brandMessage.getTag();
                        if (toNewId) {
                            channel = InventoryPackets.getNewPluginChannelId(channel);
                        } else {
                            channel = InventoryPackets.getOldPluginChannelId(channel);
                        }
                        if (channel != null) {
                            brandMessage.setTag(channel);
                        }
                    }
                }
                user.put(storage);
                user.setActive(protocolPath != null);
                // Init all protocols TODO check if this can get moved up to the previous for loop, and doesn't require the pipeline to already exist.
                for (Protocol protocol : pipeline.pipes()) {
                    protocol.init(user);
                }
                EntityTracker1_9 newTracker = user.getEntityTracker(Protocol1_9To1_8.class);
                if (newTracker != null) {
                    if (Via.getConfig().isAutoTeam()) {
                        String currentTeam = null;
                        for (Team team : player.getScoreboard().getTeams()) {
                            if (team.getPlayers().contains(info.getUsername())) {
                                currentTeam = team.getName();
                            }
                        }
                        // Reinitialize auto-team
                        newTracker.setAutoTeam(true);
                        if (currentTeam == null) {
                            // Send auto-team as it was cleared above
                            newTracker.sendTeamPacket(true, true);
                            newTracker.setCurrentTeam("viaversion");
                        } else {
                            // Auto-team will be sent when bungee send remove packet
                            newTracker.setAutoTeam(Via.getConfig().isAutoTeam());
                            newTracker.setCurrentTeam(currentTeam);
                        }
                    }
                }
                Object wrapper = channelWrapper.get(player);
                setVersion.invoke(wrapper, protocolId);
                Object entityMap = getEntityMap.invoke(null, protocolId);
                entityRewrite.set(player, entityMap);
            }
        }
    }
}
Also used : ProxiedPlayer(net.md_5.bungee.api.connection.ProxiedPlayer) ProtocolPathEntry(com.viaversion.viaversion.api.protocol.ProtocolPathEntry) EntityTracker1_9(com.viaversion.viaversion.protocols.protocol1_9to1_8.storage.EntityTracker1_9) BungeeStorage(com.viaversion.viaversion.bungee.storage.BungeeStorage) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) ProtocolPipeline(com.viaversion.viaversion.api.protocol.ProtocolPipeline) PluginMessage(net.md_5.bungee.protocol.packet.PluginMessage) ProtocolInfo(com.viaversion.viaversion.api.connection.ProtocolInfo) Team(net.md_5.bungee.api.score.Team) StorableObject(com.viaversion.viaversion.api.connection.StorableObject) Protocol(com.viaversion.viaversion.api.protocol.Protocol)

Example 29 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class ArmorListener method sendArmorUpdate.

public void sendArmorUpdate(Player player) {
    // Ensure that the player is on our pipe
    if (!isOnPipe(player))
        return;
    int armor = 0;
    for (ItemStack stack : player.getInventory().getArmorContents()) {
        armor += ArmorType.findById(stack.getTypeId()).getArmorPoints();
    }
    PacketWrapper wrapper = PacketWrapper.create(ClientboundPackets1_9.ENTITY_PROPERTIES, null, getUserConnection(player));
    try {
        // Player ID
        wrapper.write(Type.VAR_INT, player.getEntityId());
        // only 1 property
        wrapper.write(Type.INT, 1);
        wrapper.write(Type.STRING, "generic.armor");
        // default 0 armor
        wrapper.write(Type.DOUBLE, 0D);
        // 1 modifier
        wrapper.write(Type.VAR_INT, 1);
        // armor modifier uuid
        wrapper.write(Type.UUID, ARMOR_ATTRIBUTE);
        // the modifier value
        wrapper.write(Type.DOUBLE, (double) armor);
        // the modifier operation, 0 is add number
        wrapper.write(Type.BYTE, (byte) 0);
        wrapper.scheduleSend(Protocol1_9To1_8.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) ItemStack(org.bukkit.inventory.ItemStack)

Example 30 with PacketWrapper

use of com.viaversion.viaversion.api.protocol.packet.PacketWrapper in project ViaVersion by ViaVersion.

the class InventoryPackets method registerPackets.

@Override
public void registerPackets() {
    protocol.registerClientbound(ClientboundPackets1_12_1.SET_SLOT, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Window ID
            map(Type.UNSIGNED_BYTE);
            // 1 - Slot ID
            map(Type.SHORT);
            // 2 - Slot Value
            map(Type.ITEM, Type.FLAT_ITEM);
            handler(itemToClientHandler(Type.FLAT_ITEM));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.WINDOW_ITEMS, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Window ID
            map(Type.UNSIGNED_BYTE);
            // 1 - Window Values
            map(Type.ITEM_ARRAY, Type.FLAT_ITEM_ARRAY);
            handler(itemArrayHandler(Type.FLAT_ITEM_ARRAY));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.WINDOW_PROPERTY, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Window id
            map(Type.UNSIGNED_BYTE);
            // Property
            map(Type.SHORT);
            // Value
            map(Type.SHORT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    short property = wrapper.get(Type.SHORT, 0);
                    if (property >= 4 && property <= 6) {
                        // Enchantment id
                        wrapper.set(Type.SHORT, 1, (short) protocol.getMappingData().getEnchantmentMappings().getNewId(wrapper.get(Type.SHORT, 1)));
                    }
                }
            });
        }
    });
    // Plugin message Packet -> Trading
    protocol.registerClientbound(ClientboundPackets1_12_1.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Channel
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String channel = wrapper.get(Type.STRING, 0);
                    // Handle stopsound change
                    if (channel.equalsIgnoreCase("MC|StopSound")) {
                        String originalSource = wrapper.read(Type.STRING);
                        String originalSound = wrapper.read(Type.STRING);
                        // Reset the packet
                        wrapper.clearPacket();
                        wrapper.setId(0x4C);
                        byte flags = 0;
                        // Placeholder
                        wrapper.write(Type.BYTE, flags);
                        if (!originalSource.isEmpty()) {
                            flags |= 1;
                            Optional<SoundSource> finalSource = SoundSource.findBySource(originalSource);
                            if (!finalSource.isPresent()) {
                                if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                    Via.getPlatform().getLogger().info("Could not handle unknown sound source " + originalSource + " falling back to default: master");
                                }
                                finalSource = Optional.of(SoundSource.MASTER);
                            }
                            wrapper.write(Type.VAR_INT, finalSource.get().getId());
                        }
                        if (!originalSound.isEmpty()) {
                            flags |= 2;
                            wrapper.write(Type.STRING, originalSound);
                        }
                        // Update flags
                        wrapper.set(Type.BYTE, 0, flags);
                        return;
                    } else if (channel.equalsIgnoreCase("MC|TrList")) {
                        channel = "minecraft:trader_list";
                        // Passthrough Window ID
                        wrapper.passthrough(Type.INT);
                        int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
                        for (int i = 0; i < size; i++) {
                            // Input Item
                            Item input = wrapper.read(Type.ITEM);
                            handleItemToClient(input);
                            wrapper.write(Type.FLAT_ITEM, input);
                            // Output Item
                            Item output = wrapper.read(Type.ITEM);
                            handleItemToClient(output);
                            wrapper.write(Type.FLAT_ITEM, output);
                            // Has second item
                            boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                            if (secondItem) {
                                // Second Item
                                Item second = wrapper.read(Type.ITEM);
                                handleItemToClient(second);
                                wrapper.write(Type.FLAT_ITEM, second);
                            }
                            // Trade disabled
                            wrapper.passthrough(Type.BOOLEAN);
                            // Number of tools uses
                            wrapper.passthrough(Type.INT);
                            // Maximum number of trade uses
                            wrapper.passthrough(Type.INT);
                        }
                    } else {
                        String old = channel;
                        channel = getNewPluginChannelId(channel);
                        if (channel == null) {
                            if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                Via.getPlatform().getLogger().warning("Ignoring outgoing plugin message with channel: " + old);
                            }
                            wrapper.cancel();
                            return;
                        } else if (channel.equals("minecraft:register") || channel.equals("minecraft:unregister")) {
                            String[] channels = new String(wrapper.read(Type.REMAINING_BYTES), StandardCharsets.UTF_8).split("\0");
                            List<String> rewrittenChannels = new ArrayList<>();
                            for (int i = 0; i < channels.length; i++) {
                                String rewritten = getNewPluginChannelId(channels[i]);
                                if (rewritten != null) {
                                    rewrittenChannels.add(rewritten);
                                } else if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                    Via.getPlatform().getLogger().warning("Ignoring plugin channel in outgoing REGISTER: " + channels[i]);
                                }
                            }
                            if (!rewrittenChannels.isEmpty()) {
                                wrapper.write(Type.REMAINING_BYTES, Joiner.on('\0').join(rewrittenChannels).getBytes(StandardCharsets.UTF_8));
                            } else {
                                wrapper.cancel();
                                return;
                            }
                        }
                    }
                    wrapper.set(Type.STRING, 0, channel);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.ENTITY_EQUIPMENT, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity ID
            map(Type.VAR_INT);
            // 1 - Slot ID
            map(Type.VAR_INT);
            // 2 - Item
            map(Type.ITEM, Type.FLAT_ITEM);
            handler(itemToClientHandler(Type.FLAT_ITEM));
        }
    });
    protocol.registerServerbound(ServerboundPackets1_13.CLICK_WINDOW, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Window ID
            map(Type.UNSIGNED_BYTE);
            // 1 - Slot
            map(Type.SHORT);
            // 2 - Button
            map(Type.BYTE);
            // 3 - Action number
            map(Type.SHORT);
            // 4 - Mode
            map(Type.VAR_INT);
            // 5 - Clicked Item
            map(Type.FLAT_ITEM, Type.ITEM);
            handler(itemToServerHandler(Type.ITEM));
        }
    });
    protocol.registerServerbound(ServerboundPackets1_13.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Channel
            map(Type.STRING);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String channel = wrapper.get(Type.STRING, 0);
                    String old = channel;
                    channel = getOldPluginChannelId(channel);
                    if (channel == null) {
                        if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                            Via.getPlatform().getLogger().warning("Ignoring incoming plugin message with channel: " + old);
                        }
                        wrapper.cancel();
                        return;
                    } else if (channel.equals("REGISTER") || channel.equals("UNREGISTER")) {
                        String[] channels = new String(wrapper.read(Type.REMAINING_BYTES), StandardCharsets.UTF_8).split("\0");
                        List<String> rewrittenChannels = new ArrayList<>();
                        for (int i = 0; i < channels.length; i++) {
                            String rewritten = getOldPluginChannelId(channels[i]);
                            if (rewritten != null) {
                                rewrittenChannels.add(rewritten);
                            } else if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                Via.getPlatform().getLogger().warning("Ignoring plugin channel in incoming REGISTER: " + channels[i]);
                            }
                        }
                        wrapper.write(Type.REMAINING_BYTES, Joiner.on('\0').join(rewrittenChannels).getBytes(StandardCharsets.UTF_8));
                    }
                    wrapper.set(Type.STRING, 0, channel);
                }
            });
        }
    });
    protocol.registerServerbound(ServerboundPackets1_13.CREATIVE_INVENTORY_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Slot
            map(Type.SHORT);
            // 1 - Clicked Item
            map(Type.FLAT_ITEM, Type.ITEM);
            handler(itemToServerHandler(Type.ITEM));
        }
    });
}
Also used : SoundSource(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.data.SoundSource) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) ArrayList(java.util.ArrayList) Item(com.viaversion.viaversion.api.minecraft.item.Item) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

PacketWrapper (com.viaversion.viaversion.api.protocol.packet.PacketWrapper)107 PacketRemapper (com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)76 PacketHandler (com.viaversion.viaversion.api.protocol.remapper.PacketHandler)63 Type (com.viaversion.viaversion.api.type.Type)38 Item (com.viaversion.viaversion.api.minecraft.item.Item)32 Chunk (com.viaversion.viaversion.api.minecraft.chunks.Chunk)22 Metadata (com.viaversion.viaversion.api.minecraft.metadata.Metadata)22 ClientWorld (com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld)22 ChunkSection (com.viaversion.viaversion.api.minecraft.chunks.ChunkSection)18 ArrayList (java.util.ArrayList)17 UserConnection (com.viaversion.viaversion.api.connection.UserConnection)16 Position (com.viaversion.viaversion.api.minecraft.Position)16 List (java.util.List)14 ClientboundPackets1_13 (com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13)13 CompoundTag (com.github.steveice10.opennbt.tag.builtin.CompoundTag)11 EntityType (com.viaversion.viaversion.api.minecraft.entities.EntityType)11 ViaBackwards (com.viaversion.viabackwards.ViaBackwards)10 Via (com.viaversion.viaversion.api.Via)9 BlockChangeRecord (com.viaversion.viaversion.api.minecraft.BlockChangeRecord)9 ClientboundPackets1_14 (com.viaversion.viaversion.protocols.protocol1_14to1_13_2.ClientboundPackets1_14)9