Search in sources :

Example 1 with JsonElement

use of com.viaversion.viaversion.libs.gson.JsonElement in project ViaBackwards by ViaVersion.

the class Protocol1_16_1To1_16_2 method registerPackets.

@Override
protected void registerPackets() {
    executeAsyncAfterLoaded(Protocol1_16_2To1_16_1.class, MAPPINGS::load);
    translatableRewriter.registerBossBar(ClientboundPackets1_16_2.BOSSBAR);
    translatableRewriter.registerCombatEvent(ClientboundPackets1_16_2.COMBAT_EVENT);
    translatableRewriter.registerDisconnect(ClientboundPackets1_16_2.DISCONNECT);
    translatableRewriter.registerTabList(ClientboundPackets1_16_2.TAB_LIST);
    translatableRewriter.registerTitle(ClientboundPackets1_16_2.TITLE);
    translatableRewriter.registerOpenWindow(ClientboundPackets1_16_2.OPEN_WINDOW);
    translatableRewriter.registerPing();
    new CommandRewriter1_16_2(this).registerDeclareCommands(ClientboundPackets1_16_2.DECLARE_COMMANDS);
    (blockItemPackets = new BlockItemPackets1_16_2(this)).register();
    entityRewriter.register();
    SoundRewriter soundRewriter = new SoundRewriter(this);
    soundRewriter.registerSound(ClientboundPackets1_16_2.SOUND);
    soundRewriter.registerSound(ClientboundPackets1_16_2.ENTITY_SOUND);
    soundRewriter.registerNamedSound(ClientboundPackets1_16_2.NAMED_SOUND);
    soundRewriter.registerStopSound(ClientboundPackets1_16_2.STOP_SOUND);
    registerClientbound(ClientboundPackets1_16_2.CHAT_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> {
                JsonElement message = wrapper.passthrough(Type.COMPONENT);
                translatableRewriter.processText(message);
                byte position = wrapper.passthrough(Type.BYTE);
                if (position == 2) {
                    // https://bugs.mojang.com/browse/MC-119145
                    wrapper.clearPacket();
                    wrapper.setId(ClientboundPackets1_16.TITLE.ordinal());
                    wrapper.write(Type.VAR_INT, 2);
                    wrapper.write(Type.COMPONENT, message);
                }
            });
        }
    });
    // Recipe book data has been split into 2 separate packets
    registerServerbound(ServerboundPackets1_16.RECIPE_BOOK_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int type = wrapper.read(Type.VAR_INT);
                    if (type == 0) {
                        // Shown, change to its own packet
                        // Recipe
                        wrapper.passthrough(Type.STRING);
                        wrapper.setId(ServerboundPackets1_16_2.SEEN_RECIPE.ordinal());
                    } else {
                        wrapper.cancel();
                        // Settings
                        for (int i = 0; i < 3; i++) {
                            sendSeenRecipePacket(i, wrapper);
                        }
                    }
                }

                private void sendSeenRecipePacket(int recipeType, PacketWrapper wrapper) throws Exception {
                    boolean open = wrapper.read(Type.BOOLEAN);
                    boolean filter = wrapper.read(Type.BOOLEAN);
                    PacketWrapper newPacket = wrapper.create(ServerboundPackets1_16_2.RECIPE_BOOK_DATA);
                    newPacket.write(Type.VAR_INT, recipeType);
                    newPacket.write(Type.BOOLEAN, open);
                    newPacket.write(Type.BOOLEAN, filter);
                    newPacket.sendToServer(Protocol1_16_1To1_16_2.class);
                }
            });
        }
    });
    new TagRewriter(this).register(ClientboundPackets1_16_2.TAGS, RegistryType.ENTITY);
    new StatisticsRewriter(this).register(ClientboundPackets1_16_2.STATISTICS);
}
Also used : PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) Protocol1_16_2To1_16_1(com.viaversion.viaversion.protocols.protocol1_16_2to1_16_1.Protocol1_16_2To1_16_1) TranslatableRewriter(com.viaversion.viabackwards.api.rewriters.TranslatableRewriter) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) BackwardsProtocol(com.viaversion.viabackwards.api.BackwardsProtocol) Entity1_16_2Types(com.viaversion.viaversion.api.minecraft.entities.Entity1_16_2Types) ClientboundPackets1_16_2(com.viaversion.viaversion.protocols.protocol1_16_2to1_16_1.ClientboundPackets1_16_2) RegistryType(com.viaversion.viaversion.api.minecraft.RegistryType) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) ClientboundPackets1_16(com.viaversion.viaversion.protocols.protocol1_16to1_15_2.ClientboundPackets1_16) Type(com.viaversion.viaversion.api.type.Type) ServerboundPackets1_16(com.viaversion.viaversion.protocols.protocol1_16to1_15_2.ServerboundPackets1_16) ServerboundPackets1_16_2(com.viaversion.viaversion.protocols.protocol1_16_2to1_16_1.ServerboundPackets1_16_2) TagRewriter(com.viaversion.viaversion.rewriter.TagRewriter) BlockItemPackets1_16_2(com.viaversion.viabackwards.protocol.protocol1_16_1to1_16_2.packets.BlockItemPackets1_16_2) StatisticsRewriter(com.viaversion.viaversion.rewriter.StatisticsRewriter) BackwardsMappings(com.viaversion.viabackwards.api.data.BackwardsMappings) EntityTrackerBase(com.viaversion.viaversion.data.entity.EntityTrackerBase) UserConnection(com.viaversion.viaversion.api.connection.UserConnection) CommandRewriter1_16_2(com.viaversion.viabackwards.protocol.protocol1_16_1to1_16_2.data.CommandRewriter1_16_2) EntityRewriter(com.viaversion.viaversion.api.rewriter.EntityRewriter) SoundRewriter(com.viaversion.viabackwards.api.rewriters.SoundRewriter) EntityPackets1_16_2(com.viaversion.viabackwards.protocol.protocol1_16_1to1_16_2.packets.EntityPackets1_16_2) CommandRewriter1_16_2(com.viaversion.viabackwards.protocol.protocol1_16_1to1_16_2.data.CommandRewriter1_16_2) TagRewriter(com.viaversion.viaversion.rewriter.TagRewriter) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) BlockItemPackets1_16_2(com.viaversion.viabackwards.protocol.protocol1_16_1to1_16_2.packets.BlockItemPackets1_16_2) StatisticsRewriter(com.viaversion.viaversion.rewriter.StatisticsRewriter) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) SoundRewriter(com.viaversion.viabackwards.api.rewriters.SoundRewriter)

Example 2 with JsonElement

use of com.viaversion.viaversion.libs.gson.JsonElement in project ViaBackwards by ViaVersion.

the class PlayerPacket1_13 method registerPackets.

@Override
protected void registerPackets() {
    // Login Plugin Request
    protocol.registerClientbound(State.LOGIN, 0x04, -1, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper packetWrapper) throws Exception {
                    packetWrapper.cancel();
                    packetWrapper.create(0x02, new // Plugin response
                    PacketHandler() {

                        @Override
                        public void handle(PacketWrapper newWrapper) throws Exception {
                            // Packet id
                            newWrapper.write(Type.VAR_INT, packetWrapper.read(Type.VAR_INT));
                            // Success
                            newWrapper.write(Type.BOOLEAN, false);
                        }
                    }).sendToServer(Protocol1_12_2To1_13.class);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String channel = wrapper.read(Type.STRING);
                    if (channel.equals("minecraft:trader_list")) {
                        wrapper.write(Type.STRING, "MC|TrList");
                        // 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.FLAT_ITEM);
                            wrapper.write(Type.ITEM, protocol.getItemRewriter().handleItemToClient(input));
                            // Output Item
                            Item output = wrapper.read(Type.FLAT_ITEM);
                            wrapper.write(Type.ITEM, protocol.getItemRewriter().handleItemToClient(output));
                            // Has second item
                            boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                            if (secondItem) {
                                // Second Item
                                Item second = wrapper.read(Type.FLAT_ITEM);
                                wrapper.write(Type.ITEM, protocol.getItemRewriter().handleItemToClient(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 oldChannel = InventoryPackets.getOldPluginChannelId(channel);
                        if (oldChannel == null) {
                            if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                ViaBackwards.getPlatform().getLogger().warning("Ignoring outgoing plugin message with channel: " + channel);
                            }
                            wrapper.cancel();
                            return;
                        }
                        wrapper.write(Type.STRING, oldChannel);
                        if (oldChannel.equals("REGISTER") || oldChannel.equals("UNREGISTER")) {
                            String[] channels = new String(wrapper.read(Type.REMAINING_BYTES), StandardCharsets.UTF_8).split("\0");
                            List<String> rewrittenChannels = new ArrayList<>();
                            for (String s : channels) {
                                String rewritten = InventoryPackets.getOldPluginChannelId(s);
                                if (rewritten != null) {
                                    rewrittenChannels.add(rewritten);
                                } else if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                    ViaBackwards.getPlatform().getLogger().warning("Ignoring plugin channel in outgoing REGISTER: " + s);
                                }
                            }
                            wrapper.write(Type.REMAINING_BYTES, Joiner.on('\0').join(rewrittenChannels).getBytes(StandardCharsets.UTF_8));
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.SPAWN_PARTICLE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Particle ID
            map(Type.INT);
            // 1 - Long Distance
            map(Type.BOOLEAN);
            // 2 - X
            map(Type.FLOAT);
            // 3 - Y
            map(Type.FLOAT);
            // 4 - Z
            map(Type.FLOAT);
            // 5 - Offset X
            map(Type.FLOAT);
            // 6 - Offset Y
            map(Type.FLOAT);
            // 7 - Offset Z
            map(Type.FLOAT);
            // 8 - Particle Data
            map(Type.FLOAT);
            // 9 - Particle Count
            map(Type.INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    ParticleMapping.ParticleData old = ParticleMapping.getMapping(wrapper.get(Type.INT, 0));
                    wrapper.set(Type.INT, 0, old.getHistoryId());
                    int[] data = old.rewriteData(protocol, wrapper);
                    if (data != null) {
                        if (old.getHandler().isBlockHandler() && data[0] == 0) {
                            // Cancel air block particles
                            wrapper.cancel();
                            return;
                        }
                        for (int i : data) {
                            wrapper.write(Type.VAR_INT, i);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.PLAYER_INFO, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper packetWrapper) throws Exception {
                    TabCompleteStorage storage = packetWrapper.user().get(TabCompleteStorage.class);
                    int action = packetWrapper.passthrough(Type.VAR_INT);
                    int nPlayers = packetWrapper.passthrough(Type.VAR_INT);
                    for (int i = 0; i < nPlayers; i++) {
                        UUID uuid = packetWrapper.passthrough(Type.UUID);
                        if (action == 0) {
                            // Add
                            String name = packetWrapper.passthrough(Type.STRING);
                            storage.usernames().put(uuid, name);
                            int nProperties = packetWrapper.passthrough(Type.VAR_INT);
                            for (int j = 0; j < nProperties; j++) {
                                packetWrapper.passthrough(Type.STRING);
                                packetWrapper.passthrough(Type.STRING);
                                if (packetWrapper.passthrough(Type.BOOLEAN)) {
                                    packetWrapper.passthrough(Type.STRING);
                                }
                            }
                            packetWrapper.passthrough(Type.VAR_INT);
                            packetWrapper.passthrough(Type.VAR_INT);
                            if (packetWrapper.passthrough(Type.BOOLEAN)) {
                                packetWrapper.passthrough(Type.COMPONENT);
                            }
                        } else if (action == 1) {
                            // Update Game Mode
                            packetWrapper.passthrough(Type.VAR_INT);
                        } else if (action == 2) {
                            // Update Ping
                            packetWrapper.passthrough(Type.VAR_INT);
                        } else if (action == 3) {
                            // Update Display Name
                            if (packetWrapper.passthrough(Type.BOOLEAN)) {
                                packetWrapper.passthrough(Type.COMPONENT);
                            }
                        } else if (action == 4) {
                            // Remove Player
                            storage.usernames().remove(uuid);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.SCOREBOARD_OBJECTIVE, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    byte mode = wrapper.get(Type.BYTE, 0);
                    if (mode == 0 || mode == 2) {
                        String value = wrapper.read(Type.COMPONENT).toString();
                        value = ChatRewriter.jsonToLegacyText(value);
                        if (value.length() > 32) {
                            value = value.substring(0, 32);
                        }
                        wrapper.write(Type.STRING, value);
                        int type = wrapper.read(Type.VAR_INT);
                        wrapper.write(Type.STRING, type == 1 ? "hearts" : "integer");
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.TEAMS, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    byte action = wrapper.get(Type.BYTE, 0);
                    if (action == 0 || action == 2) {
                        String displayName = wrapper.read(Type.STRING);
                        displayName = ChatRewriter.jsonToLegacyText(displayName);
                        displayName = ChatUtil.removeUnusedColor(displayName, 'f');
                        if (displayName.length() > 32) {
                            displayName = displayName.substring(0, 32);
                        }
                        wrapper.write(Type.STRING, displayName);
                        byte flags = wrapper.read(Type.BYTE);
                        String nameTagVisibility = wrapper.read(Type.STRING);
                        String collisionRule = wrapper.read(Type.STRING);
                        int colour = wrapper.read(Type.VAR_INT);
                        if (colour == 21) {
                            colour = -1;
                        }
                        JsonElement prefixComponent = wrapper.read(Type.COMPONENT);
                        JsonElement suffixComponent = wrapper.read(Type.COMPONENT);
                        String prefix = prefixComponent == null || prefixComponent.isJsonNull() ? "" : ChatRewriter.jsonToLegacyText(prefixComponent.toString());
                        if (ViaBackwards.getConfig().addTeamColorTo1_13Prefix()) {
                            prefix += "§" + (colour > -1 && colour <= 15 ? Integer.toHexString(colour) : "r");
                        }
                        prefix = ChatUtil.removeUnusedColor(prefix, 'f', true);
                        if (prefix.length() > 16)
                            prefix = prefix.substring(0, 16);
                        if (prefix.endsWith("§"))
                            prefix = prefix.substring(0, prefix.length() - 1);
                        String suffix = suffixComponent == null || suffixComponent.isJsonNull() ? "" : ChatRewriter.jsonToLegacyText(suffixComponent.toString());
                        // Don't remove white coloring
                        suffix = ChatUtil.removeUnusedColor(suffix, '\0');
                        if (suffix.length() > 16)
                            suffix = suffix.substring(0, 16);
                        if (suffix.endsWith("§"))
                            suffix = suffix.substring(0, suffix.length() - 1);
                        wrapper.write(Type.STRING, prefix);
                        wrapper.write(Type.STRING, suffix);
                        wrapper.write(Type.BYTE, flags);
                        wrapper.write(Type.STRING, nameTagVisibility);
                        wrapper.write(Type.STRING, collisionRule);
                        wrapper.write(Type.BYTE, (byte) colour);
                    }
                    if (action == 0 || action == 3 || action == 4) {
                        // Entities
                        wrapper.passthrough(Type.STRING_ARRAY);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.DECLARE_COMMANDS, null, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> {
                wrapper.cancel();
                TabCompleteStorage storage = wrapper.user().get(TabCompleteStorage.class);
                if (!storage.commands().isEmpty()) {
                    storage.commands().clear();
                }
                int size = wrapper.read(Type.VAR_INT);
                boolean initialNodes = true;
                for (int i = 0; i < size; i++) {
                    byte flags = wrapper.read(Type.BYTE);
                    // Children indices
                    wrapper.read(Type.VAR_INT_ARRAY_PRIMITIVE);
                    if ((flags & 0x08) != 0) {
                        // Redirect node index
                        wrapper.read(Type.VAR_INT);
                    }
                    byte nodeType = (byte) (flags & 0x03);
                    if (initialNodes && nodeType == 2) {
                        initialNodes = false;
                    }
                    if (nodeType == 1 || nodeType == 2) {
                        // Literal/argument node
                        String name = wrapper.read(Type.STRING);
                        if (nodeType == 1 && initialNodes) {
                            storage.commands().add('/' + name);
                        }
                    }
                    if (nodeType == 2) {
                        // Argument node
                        commandRewriter.handleArgument(wrapper, wrapper.read(Type.STRING));
                    }
                    if ((flags & 0x10) != 0) {
                        // Suggestion type
                        wrapper.read(Type.STRING);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.TAB_COMPLETE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    TabCompleteStorage storage = wrapper.user().get(TabCompleteStorage.class);
                    if (storage.lastRequest() == null) {
                        wrapper.cancel();
                        return;
                    }
                    if (storage.lastId() != wrapper.read(Type.VAR_INT))
                        wrapper.cancel();
                    int start = wrapper.read(Type.VAR_INT);
                    int length = wrapper.read(Type.VAR_INT);
                    int lastRequestPartIndex = storage.lastRequest().lastIndexOf(' ') + 1;
                    // Client only replaces after space
                    if (lastRequestPartIndex != start)
                        wrapper.cancel();
                    if (length != storage.lastRequest().length() - lastRequestPartIndex) {
                        // We can't set the length in previous versions
                        wrapper.cancel();
                    }
                    int count = wrapper.passthrough(Type.VAR_INT);
                    for (int i = 0; i < count; i++) {
                        String match = wrapper.read(Type.STRING);
                        wrapper.write(Type.STRING, (start == 0 && !storage.isLastAssumeCommand() ? "/" : "") + match);
                        // Ignore tooltip
                        if (wrapper.read(Type.BOOLEAN)) {
                            wrapper.read(Type.STRING);
                        }
                    }
                }
            });
        }
    });
    protocol.registerServerbound(ServerboundPackets1_12_1.TAB_COMPLETE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> {
                TabCompleteStorage storage = wrapper.user().get(TabCompleteStorage.class);
                List<String> suggestions = new ArrayList<>();
                String command = wrapper.read(Type.STRING);
                boolean assumeCommand = wrapper.read(Type.BOOLEAN);
                wrapper.read(Type.OPTIONAL_POSITION);
                if (!assumeCommand && !command.startsWith("/")) {
                    // Complete usernames for non-commands
                    String buffer = command.substring(command.lastIndexOf(' ') + 1);
                    for (String value : storage.usernames().values()) {
                        if (startsWithIgnoreCase(value, buffer)) {
                            suggestions.add(value);
                        }
                    }
                } else if (!storage.commands().isEmpty() && !command.contains(" ")) {
                    // Complete commands names with values from 'Declare Commands' packet
                    for (String value : storage.commands()) {
                        if (startsWithIgnoreCase(value, command)) {
                            suggestions.add(value);
                        }
                    }
                }
                if (!suggestions.isEmpty()) {
                    wrapper.cancel();
                    PacketWrapper response = wrapper.create(ClientboundPackets1_12_1.TAB_COMPLETE);
                    response.write(Type.VAR_INT, suggestions.size());
                    for (String value : suggestions) {
                        response.write(Type.STRING, value);
                    }
                    response.scheduleSend(Protocol1_12_2To1_13.class);
                    storage.setLastRequest(null);
                    return;
                }
                if (!assumeCommand && command.startsWith("/")) {
                    command = command.substring(1);
                }
                int id = ThreadLocalRandom.current().nextInt();
                wrapper.write(Type.VAR_INT, id);
                wrapper.write(Type.STRING, command);
                storage.setLastId(id);
                storage.setLastAssumeCommand(assumeCommand);
                storage.setLastRequest(command);
            });
        }
    });
    protocol.registerServerbound(ServerboundPackets1_12_1.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> {
                String channel = wrapper.read(Type.STRING);
                switch(channel) {
                    case "MC|BSign":
                    case "MC|BEdit":
                        wrapper.setId(0x0B);
                        Item book = wrapper.read(Type.ITEM);
                        wrapper.write(Type.FLAT_ITEM, protocol.getItemRewriter().handleItemToServer(book));
                        boolean signing = channel.equals("MC|BSign");
                        wrapper.write(Type.BOOLEAN, signing);
                        break;
                    case "MC|ItemName":
                        wrapper.setId(0x1C);
                        break;
                    case "MC|AdvCmd":
                        byte type = wrapper.read(Type.BYTE);
                        if (type == 0) {
                            // Information from https://wiki.vg/index.php?title=Plugin_channels&oldid=14089
                            // The Notchain client only uses this for command block minecarts and uses MC|AutoCmd for blocks, but the Notchian server still accepts it for either.
                            // Maybe older versions used this and we need to implement this? The issues is that we would have to save the command block types
                            wrapper.setId(0x22);
                            wrapper.cancel();
                            ViaBackwards.getPlatform().getLogger().warning("Client send MC|AdvCmd custom payload to update command block, weird!");
                        } else if (type == 1) {
                            wrapper.setId(0x23);
                            // Entity Id
                            wrapper.write(Type.VAR_INT, wrapper.read(Type.INT));
                            // Command
                            wrapper.passthrough(Type.STRING);
                            // Track Output
                            wrapper.passthrough(Type.BOOLEAN);
                        } else {
                            wrapper.cancel();
                        }
                        break;
                    case "MC|AutoCmd":
                        {
                            wrapper.setId(0x22);
                            int x = wrapper.read(Type.INT);
                            int y = wrapper.read(Type.INT);
                            int z = wrapper.read(Type.INT);
                            wrapper.write(Type.POSITION, new Position(x, (short) y, z));
                            // Command
                            wrapper.passthrough(Type.STRING);
                            byte flags = 0;
                            // Track Output
                            if (wrapper.read(Type.BOOLEAN))
                                flags |= 0x01;
                            String mode = wrapper.read(Type.STRING);
                            int modeId = mode.equals("SEQUENCE") ? 0 : mode.equals("AUTO") ? 1 : 2;
                            wrapper.write(Type.VAR_INT, modeId);
                            // Is conditional
                            if (wrapper.read(Type.BOOLEAN))
                                flags |= 0x02;
                            // Automatic
                            if (wrapper.read(Type.BOOLEAN))
                                flags |= 0x04;
                            wrapper.write(Type.BYTE, flags);
                            break;
                        }
                    case "MC|Struct":
                        {
                            wrapper.setId(0x25);
                            int x = wrapper.read(Type.INT);
                            int y = wrapper.read(Type.INT);
                            int z = wrapper.read(Type.INT);
                            wrapper.write(Type.POSITION, new Position(x, (short) y, z));
                            wrapper.write(Type.VAR_INT, wrapper.read(Type.BYTE) - 1);
                            String mode = wrapper.read(Type.STRING);
                            int modeId = mode.equals("SAVE") ? 0 : mode.equals("LOAD") ? 1 : mode.equals("CORNER") ? 2 : 3;
                            wrapper.write(Type.VAR_INT, modeId);
                            // Name
                            wrapper.passthrough(Type.STRING);
                            // Offset X
                            wrapper.write(Type.BYTE, wrapper.read(Type.INT).byteValue());
                            // Offset Y
                            wrapper.write(Type.BYTE, wrapper.read(Type.INT).byteValue());
                            // Offset Z
                            wrapper.write(Type.BYTE, wrapper.read(Type.INT).byteValue());
                            // Size X
                            wrapper.write(Type.BYTE, wrapper.read(Type.INT).byteValue());
                            // Size Y
                            wrapper.write(Type.BYTE, wrapper.read(Type.INT).byteValue());
                            // Size Z
                            wrapper.write(Type.BYTE, wrapper.read(Type.INT).byteValue());
                            String mirror = wrapper.read(Type.STRING);
                            int mirrorId = mode.equals("NONE") ? 0 : mode.equals("LEFT_RIGHT") ? 1 : 2;
                            String rotation = wrapper.read(Type.STRING);
                            int rotationId = mode.equals("NONE") ? 0 : mode.equals("CLOCKWISE_90") ? 1 : mode.equals("CLOCKWISE_180") ? 2 : 3;
                            // Metadata
                            wrapper.passthrough(Type.STRING);
                            byte flags = 0;
                            // Ignore entities
                            if (wrapper.read(Type.BOOLEAN))
                                flags |= 0x01;
                            // Show air
                            if (wrapper.read(Type.BOOLEAN))
                                flags |= 0x02;
                            // Show bounding box
                            if (wrapper.read(Type.BOOLEAN))
                                flags |= 0x04;
                            // Integrity
                            wrapper.passthrough(Type.FLOAT);
                            // Seed
                            wrapper.passthrough(Type.VAR_LONG);
                            wrapper.write(Type.BYTE, flags);
                            break;
                        }
                    case "MC|Beacon":
                        wrapper.setId(0x20);
                        // Primary Effect
                        wrapper.write(Type.VAR_INT, wrapper.read(Type.INT));
                        // Secondary Effect
                        wrapper.write(Type.VAR_INT, wrapper.read(Type.INT));
                        break;
                    case "MC|TrSel":
                        wrapper.setId(0x1F);
                        // Slot
                        wrapper.write(Type.VAR_INT, wrapper.read(Type.INT));
                        break;
                    case "MC|PickItem":
                        wrapper.setId(0x15);
                        break;
                    default:
                        String newChannel = InventoryPackets.getNewPluginChannelId(channel);
                        if (newChannel == null) {
                            if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                ViaBackwards.getPlatform().getLogger().warning("Ignoring incoming plugin message with channel: " + channel);
                            }
                            wrapper.cancel();
                            return;
                        }
                        wrapper.write(Type.STRING, newChannel);
                        if (newChannel.equals("minecraft:register") || newChannel.equals("minecraft:unregister")) {
                            String[] channels = new String(wrapper.read(Type.REMAINING_BYTES), StandardCharsets.UTF_8).split("\0");
                            List<String> rewrittenChannels = new ArrayList<>();
                            for (String s : channels) {
                                String rewritten = InventoryPackets.getNewPluginChannelId(s);
                                if (rewritten != null) {
                                    rewrittenChannels.add(rewritten);
                                } else if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                    ViaBackwards.getPlatform().getLogger().warning("Ignoring plugin channel in incoming REGISTER: " + s);
                                }
                            }
                            if (!rewrittenChannels.isEmpty()) {
                                wrapper.write(Type.REMAINING_BYTES, Joiner.on('\0').join(rewrittenChannels).getBytes(StandardCharsets.UTF_8));
                            } else {
                                wrapper.cancel();
                                return;
                            }
                        }
                        break;
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.STATISTICS, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.VAR_INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int size = wrapper.get(Type.VAR_INT, 0);
                    int newSize = size;
                    for (int i = 0; i < size; i++) {
                        int categoryId = wrapper.read(Type.VAR_INT);
                        int statisticId = wrapper.read(Type.VAR_INT);
                        String name = "";
                        // categories 0-7 (items, blocks, entities) - probably not feasible
                        switch(categoryId) {
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                            case 7:
                                // remove value
                                wrapper.read(Type.VAR_INT);
                                newSize--;
                                continue;
                            case 8:
                                name = protocol.getMappingData().getStatisticMappings().get(statisticId);
                                if (name == null) {
                                    wrapper.read(Type.VAR_INT);
                                    newSize--;
                                    continue;
                                }
                                break;
                        }
                        // string id
                        wrapper.write(Type.STRING, name);
                        // value
                        wrapper.passthrough(Type.VAR_INT);
                    }
                    if (newSize != size) {
                        wrapper.set(Type.VAR_INT, 0, newSize);
                    }
                }
            });
        }
    });
}
Also used : PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) Item(com.viaversion.viaversion.api.minecraft.item.Item) ClientboundPackets1_12_1(com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ClientboundPackets1_12_1) ArrayList(java.util.ArrayList) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Type(com.viaversion.viaversion.api.type.Type) Protocol1_12_2To1_13(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.Protocol1_12_2To1_13) CommandRewriter(com.viaversion.viaversion.rewriter.CommandRewriter) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) TabCompleteStorage(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.storage.TabCompleteStorage) RewriterBase(com.viaversion.viaversion.api.rewriter.RewriterBase) Position(com.viaversion.viaversion.api.minecraft.Position) ServerboundPackets1_12_1(com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) State(com.viaversion.viaversion.api.protocol.packet.State) UUID(java.util.UUID) ParticleMapping(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.data.ParticleMapping) Via(com.viaversion.viaversion.api.Via) StandardCharsets(java.nio.charset.StandardCharsets) ClientboundPackets1_13(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13) List(java.util.List) ChatUtil(com.viaversion.viabackwards.utils.ChatUtil) ChatRewriter(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ChatRewriter) ViaBackwards(com.viaversion.viabackwards.ViaBackwards) InventoryPackets(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.packets.InventoryPackets) Joiner(com.google.common.base.Joiner) Position(com.viaversion.viaversion.api.minecraft.Position) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) ArrayList(java.util.ArrayList) ParticleMapping(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.data.ParticleMapping) TabCompleteStorage(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.storage.TabCompleteStorage) Item(com.viaversion.viaversion.api.minecraft.item.Item) Protocol1_12_2To1_13(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.Protocol1_12_2To1_13) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID)

Example 3 with JsonElement

use of com.viaversion.viaversion.libs.gson.JsonElement in project ViaBackwards by ViaVersion.

the class BlockItemPackets1_14 method registerPackets.

@Override
protected void registerPackets() {
    protocol.registerServerbound(ServerboundPackets1_13.EDIT_BOOK, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> handleItemToServer(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM)));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.OPEN_WINDOW, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int windowId = wrapper.read(Type.VAR_INT);
                    wrapper.write(Type.UNSIGNED_BYTE, (short) windowId);
                    int type = wrapper.read(Type.VAR_INT);
                    String stringType = null;
                    String containerTitle = null;
                    int slotSize = 0;
                    if (type < 6) {
                        if (type == 2)
                            containerTitle = "Barrel";
                        stringType = "minecraft:container";
                        slotSize = (type + 1) * 9;
                    } else {
                        switch(type) {
                            case 11:
                                stringType = "minecraft:crafting_table";
                                break;
                            // blast furnace
                            case 9:
                            // smoker
                            case 20:
                            // furnace
                            case 13:
                            case // grindstone
                            14:
                                if (type == 9)
                                    containerTitle = "Blast Furnace";
                                else if (type == 20)
                                    containerTitle = "Smoker";
                                else if (type == 14)
                                    containerTitle = "Grindstone";
                                stringType = "minecraft:furnace";
                                slotSize = 3;
                                break;
                            case 6:
                                stringType = "minecraft:dropper";
                                slotSize = 9;
                                break;
                            case 12:
                                stringType = "minecraft:enchanting_table";
                                break;
                            case 10:
                                stringType = "minecraft:brewing_stand";
                                slotSize = 5;
                                break;
                            case 18:
                                stringType = "minecraft:villager";
                                break;
                            case 8:
                                stringType = "minecraft:beacon";
                                slotSize = 1;
                                break;
                            // cartography_table
                            case 21:
                            case 7:
                                if (type == 21)
                                    containerTitle = "Cartography Table";
                                stringType = "minecraft:anvil";
                                break;
                            case 15:
                                stringType = "minecraft:hopper";
                                slotSize = 5;
                                break;
                            case 19:
                                stringType = "minecraft:shulker_box";
                                slotSize = 27;
                                break;
                        }
                    }
                    if (stringType == null) {
                        ViaBackwards.getPlatform().getLogger().warning("Can't open inventory for 1.13 player! Type: " + type);
                        wrapper.cancel();
                        return;
                    }
                    wrapper.write(Type.STRING, stringType);
                    JsonElement title = wrapper.read(Type.COMPONENT);
                    if (containerTitle != null) {
                        // Don't rewrite renamed, only translatable titles
                        JsonObject object;
                        if (title.isJsonObject() && (object = title.getAsJsonObject()).has("translate")) {
                            // Don't rewrite other 9x3 translatable containers
                            if (type != 2 || object.getAsJsonPrimitive("translate").getAsString().equals("container.barrel")) {
                                title = ChatRewriter.legacyTextToJson(containerTitle);
                            }
                        }
                    }
                    wrapper.write(Type.COMPONENT, title);
                    wrapper.write(Type.UNSIGNED_BYTE, (short) slotSize);
                }
            });
        }
    });
    // Horse window -> Open Window
    protocol.registerClientbound(ClientboundPackets1_14.OPEN_HORSE_WINDOW, ClientboundPackets1_13.OPEN_WINDOW, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    // Window id
                    wrapper.passthrough(Type.UNSIGNED_BYTE);
                    // Type
                    wrapper.write(Type.STRING, "EntityHorse");
                    JsonObject object = new JsonObject();
                    object.addProperty("translate", "minecraft.horse");
                    // Title
                    wrapper.write(Type.COMPONENT, object);
                    // Number of slots
                    wrapper.write(Type.UNSIGNED_BYTE, wrapper.read(Type.VAR_INT).shortValue());
                    // Entity id
                    wrapper.passthrough(Type.INT);
                }
            });
        }
    });
    BlockRewriter blockRewriter = new BlockRewriter(protocol, Type.POSITION);
    registerSetCooldown(ClientboundPackets1_14.COOLDOWN);
    registerWindowItems(ClientboundPackets1_14.WINDOW_ITEMS, Type.FLAT_VAR_INT_ITEM_ARRAY);
    registerSetSlot(ClientboundPackets1_14.SET_SLOT, Type.FLAT_VAR_INT_ITEM);
    registerAdvancements(ClientboundPackets1_14.ADVANCEMENTS, Type.FLAT_VAR_INT_ITEM);
    // Trade List -> Plugin Message
    protocol.registerClientbound(ClientboundPackets1_14.TRADE_LIST, ClientboundPackets1_13.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    wrapper.write(Type.STRING, "minecraft:trader_list");
                    int windowId = wrapper.read(Type.VAR_INT);
                    wrapper.write(Type.INT, windowId);
                    int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
                    for (int i = 0; i < size; i++) {
                        // Input Item
                        Item input = wrapper.read(Type.FLAT_VAR_INT_ITEM);
                        input = handleItemToClient(input);
                        wrapper.write(Type.FLAT_VAR_INT_ITEM, input);
                        // Output Item
                        Item output = wrapper.read(Type.FLAT_VAR_INT_ITEM);
                        output = handleItemToClient(output);
                        wrapper.write(Type.FLAT_VAR_INT_ITEM, output);
                        // Has second item
                        boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                        if (secondItem) {
                            // Second Item
                            Item second = wrapper.read(Type.FLAT_VAR_INT_ITEM);
                            second = handleItemToClient(second);
                            wrapper.write(Type.FLAT_VAR_INT_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);
                        wrapper.read(Type.INT);
                        wrapper.read(Type.INT);
                        wrapper.read(Type.FLOAT);
                    }
                    wrapper.read(Type.VAR_INT);
                    wrapper.read(Type.VAR_INT);
                    wrapper.read(Type.BOOLEAN);
                }
            });
        }
    });
    // Open Book -> Plugin Message
    protocol.registerClientbound(ClientboundPackets1_14.OPEN_BOOK, ClientboundPackets1_13.PLUGIN_MESSAGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    wrapper.write(Type.STRING, "minecraft:book_open");
                    wrapper.passthrough(Type.VAR_INT);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.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.FLAT_VAR_INT_ITEM);
            handler(itemToClientHandler(Type.FLAT_VAR_INT_ITEM));
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int entityId = wrapper.get(Type.VAR_INT, 0);
                    EntityType entityType = wrapper.user().getEntityTracker(Protocol1_13_2To1_14.class).entityType(entityId);
                    if (entityType == null)
                        return;
                    if (entityType.isOrHasParent(Entity1_14Types.ABSTRACT_HORSE)) {
                        wrapper.setId(0x3F);
                        wrapper.resetReader();
                        wrapper.passthrough(Type.VAR_INT);
                        wrapper.read(Type.VAR_INT);
                        Item item = wrapper.read(Type.FLAT_VAR_INT_ITEM);
                        int armorType = item == null || item.identifier() == 0 ? 0 : item.identifier() - 726;
                        if (armorType < 0 || armorType > 3) {
                            ViaBackwards.getPlatform().getLogger().warning("Received invalid horse armor: " + item);
                            wrapper.cancel();
                            return;
                        }
                        List<Metadata> metadataList = new ArrayList<>();
                        metadataList.add(new Metadata(16, Types1_13_2.META_TYPES.varIntType, armorType));
                        wrapper.write(Types1_13.METADATA_LIST, metadataList);
                    }
                }
            });
        }
    });
    RecipeRewriter recipeHandler = new RecipeRewriter1_13_2(protocol);
    protocol.registerClientbound(ClientboundPackets1_14.DECLARE_RECIPES, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                private final Set<String> removedTypes = ImmutableSet.of("crafting_special_suspiciousstew", "blasting", "smoking", "campfire_cooking", "stonecutting");

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int size = wrapper.passthrough(Type.VAR_INT);
                    int deleted = 0;
                    for (int i = 0; i < size; i++) {
                        String type = wrapper.read(Type.STRING);
                        // Recipe Identifier
                        String id = wrapper.read(Type.STRING);
                        type = type.replace("minecraft:", "");
                        if (removedTypes.contains(type)) {
                            switch(type) {
                                case "blasting":
                                case "smoking":
                                case "campfire_cooking":
                                    // Group
                                    wrapper.read(Type.STRING);
                                    // Ingredients
                                    wrapper.read(Type.FLAT_VAR_INT_ITEM_ARRAY_VAR_INT);
                                    wrapper.read(Type.FLAT_VAR_INT_ITEM);
                                    // EXP
                                    wrapper.read(Type.FLOAT);
                                    // Cooking time
                                    wrapper.read(Type.VAR_INT);
                                    break;
                                case "stonecutting":
                                    // Group?
                                    wrapper.read(Type.STRING);
                                    // Ingredients
                                    wrapper.read(Type.FLAT_VAR_INT_ITEM_ARRAY_VAR_INT);
                                    // Result
                                    wrapper.read(Type.FLAT_VAR_INT_ITEM);
                                    break;
                            }
                            deleted++;
                            continue;
                        }
                        wrapper.write(Type.STRING, id);
                        wrapper.write(Type.STRING, type);
                        // Handle the rest of the types
                        recipeHandler.handle(wrapper, type);
                    }
                    wrapper.set(Type.VAR_INT, 0, size - deleted);
                }
            });
        }
    });
    registerClickWindow(ServerboundPackets1_13.CLICK_WINDOW, Type.FLAT_VAR_INT_ITEM);
    registerCreativeInvAction(ServerboundPackets1_13.CREATIVE_INVENTORY_ACTION, Type.FLAT_VAR_INT_ITEM);
    protocol.registerClientbound(ClientboundPackets1_14.BLOCK_BREAK_ANIMATION, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.VAR_INT);
            map(Type.POSITION1_14, Type.POSITION);
            map(Type.BYTE);
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.BLOCK_ENTITY_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.POSITION1_14, Type.POSITION);
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.BLOCK_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Location
            map(Type.POSITION1_14, Type.POSITION);
            // Action id
            map(Type.UNSIGNED_BYTE);
            // Action param
            map(Type.UNSIGNED_BYTE);
            // Block id - /!\ NOT BLOCK STATE
            map(Type.VAR_INT);
            handler(wrapper -> {
                int mappedId = protocol.getMappingData().getNewBlockId(wrapper.get(Type.VAR_INT, 0));
                if (mappedId == -1) {
                    wrapper.cancel();
                    return;
                }
                wrapper.set(Type.VAR_INT, 0, mappedId);
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.BLOCK_CHANGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.POSITION1_14, Type.POSITION);
            map(Type.VAR_INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int id = wrapper.get(Type.VAR_INT, 0);
                    wrapper.set(Type.VAR_INT, 0, protocol.getMappingData().getNewBlockStateId(id));
                }
            });
        }
    });
    blockRewriter.registerMultiBlockChange(ClientboundPackets1_14.MULTI_BLOCK_CHANGE);
    protocol.registerClientbound(ClientboundPackets1_14.EXPLOSION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // X
            map(Type.FLOAT);
            // Y
            map(Type.FLOAT);
            // Z
            map(Type.FLOAT);
            // Radius
            map(Type.FLOAT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    for (int i = 0; i < 3; i++) {
                        float coord = wrapper.get(Type.FLOAT, i);
                        if (coord < 0f) {
                            coord = (float) Math.floor(coord);
                            wrapper.set(Type.FLOAT, i, coord);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.CHUNK_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    ClientWorld clientWorld = wrapper.user().get(ClientWorld.class);
                    Chunk chunk = wrapper.read(new Chunk1_14Type());
                    wrapper.write(new Chunk1_13Type(clientWorld), chunk);
                    ChunkLightStorage.ChunkLight chunkLight = wrapper.user().get(ChunkLightStorage.class).getStoredLight(chunk.getX(), chunk.getZ());
                    for (int i = 0; i < chunk.getSections().length; i++) {
                        ChunkSection section = chunk.getSections()[i];
                        if (section == null)
                            continue;
                        ChunkSectionLight sectionLight = new ChunkSectionLightImpl();
                        section.setLight(sectionLight);
                        if (chunkLight == null) {
                            sectionLight.setBlockLight(ChunkLightStorage.FULL_LIGHT);
                            if (clientWorld.getEnvironment() == Environment.NORMAL) {
                                sectionLight.setSkyLight(ChunkLightStorage.FULL_LIGHT);
                            }
                        } else {
                            byte[] blockLight = chunkLight.getBlockLight()[i];
                            sectionLight.setBlockLight(blockLight != null ? blockLight : ChunkLightStorage.FULL_LIGHT);
                            if (clientWorld.getEnvironment() == Environment.NORMAL) {
                                byte[] skyLight = chunkLight.getSkyLight()[i];
                                sectionLight.setSkyLight(skyLight != null ? skyLight : ChunkLightStorage.FULL_LIGHT);
                            }
                        }
                        if (Via.getConfig().isNonFullBlockLightFix() && section.getNonAirBlocksCount() != 0 && sectionLight.hasBlockLight()) {
                            for (int x = 0; x < 16; x++) {
                                for (int y = 0; y < 16; y++) {
                                    for (int z = 0; z < 16; z++) {
                                        int id = section.getFlatBlock(x, y, z);
                                        if (Protocol1_14To1_13_2.MAPPINGS.getNonFullBlocks().contains(id)) {
                                            sectionLight.getBlockLightNibbleArray().set(x, y, z, 0);
                                        }
                                    }
                                }
                            }
                        }
                        for (int j = 0; j < section.getPaletteSize(); j++) {
                            int old = section.getPaletteEntry(j);
                            int newId = protocol.getMappingData().getNewBlockStateId(old);
                            section.setPaletteEntry(j, newId);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.UNLOAD_CHUNK, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int x = wrapper.passthrough(Type.INT);
                    int z = wrapper.passthrough(Type.INT);
                    wrapper.user().get(ChunkLightStorage.class).unloadChunk(x, z);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.EFFECT, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Effect Id
            map(Type.INT);
            // Location
            map(Type.POSITION1_14, Type.POSITION);
            // Data
            map(Type.INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int id = wrapper.get(Type.INT, 0);
                    int data = wrapper.get(Type.INT, 1);
                    if (id == 1010) {
                        // Play record
                        wrapper.set(Type.INT, 1, protocol.getMappingData().getNewItemId(data));
                    } else if (id == 2001) {
                        // Block break + block break sound
                        wrapper.set(Type.INT, 1, protocol.getMappingData().getNewBlockStateId(data));
                    }
                }
            });
        }
    });
    registerSpawnParticle(ClientboundPackets1_14.SPAWN_PARTICLE, Type.FLAT_VAR_INT_ITEM, Type.FLOAT);
    protocol.registerClientbound(ClientboundPackets1_14.MAP_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.VAR_INT);
            map(Type.BYTE);
            map(Type.BOOLEAN);
            // Locked
            map(Type.BOOLEAN, Type.NOTHING);
        }
    });
    protocol.registerClientbound(ClientboundPackets1_14.SPAWN_POSITION, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.POSITION1_14, Type.POSITION);
        }
    });
}
Also used : PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) Environment(com.viaversion.viaversion.api.minecraft.Environment) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) Chunk1_14Type(com.viaversion.viaversion.protocols.protocol1_14to1_13_2.types.Chunk1_14Type) Types1_13(com.viaversion.viaversion.api.type.types.version.Types1_13) Item(com.viaversion.viaversion.api.minecraft.item.Item) ListTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ListTag) Metadata(com.viaversion.viaversion.api.minecraft.metadata.Metadata) ArrayList(java.util.ArrayList) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Type(com.viaversion.viaversion.api.type.Type) ChunkLightStorage(com.viaversion.viabackwards.protocol.protocol1_13_2to1_14.storage.ChunkLightStorage) Chunk(com.viaversion.viaversion.api.minecraft.chunks.Chunk) ServerboundPackets1_13(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ServerboundPackets1_13) Protocol1_14To1_13_2(com.viaversion.viaversion.protocols.protocol1_14to1_13_2.Protocol1_14To1_13_2) Protocol1_13_2To1_14(com.viaversion.viabackwards.protocol.protocol1_13_2to1_14.Protocol1_13_2To1_14) Chunk1_13Type(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.types.Chunk1_13Type) ChunkSectionLightImpl(com.viaversion.viaversion.api.minecraft.chunks.ChunkSectionLightImpl) ImmutableSet(com.google.common.collect.ImmutableSet) Types1_13_2(com.viaversion.viaversion.api.type.types.version.Types1_13_2) EnchantmentRewriter(com.viaversion.viabackwards.api.rewriters.EnchantmentRewriter) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) Tag(com.viaversion.viaversion.libs.opennbt.tag.builtin.Tag) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) Set(java.util.Set) EntityType(com.viaversion.viaversion.api.minecraft.entities.EntityType) StringTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.StringTag) RecipeRewriter1_13_2(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.data.RecipeRewriter1_13_2) Via(com.viaversion.viaversion.api.Via) ChunkSectionLight(com.viaversion.viaversion.api.minecraft.chunks.ChunkSectionLight) RecipeRewriter(com.viaversion.viaversion.rewriter.RecipeRewriter) ClientboundPackets1_13(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13) JsonObject(com.viaversion.viaversion.libs.gson.JsonObject) List(java.util.List) BlockRewriter(com.viaversion.viaversion.rewriter.BlockRewriter) ChatRewriter(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ChatRewriter) ViaBackwards(com.viaversion.viabackwards.ViaBackwards) CompoundTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.CompoundTag) ChunkSection(com.viaversion.viaversion.api.minecraft.chunks.ChunkSection) ClientboundPackets1_14(com.viaversion.viaversion.protocols.protocol1_14to1_13_2.ClientboundPackets1_14) Entity1_14Types(com.viaversion.viaversion.api.minecraft.entities.Entity1_14Types) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Metadata(com.viaversion.viaversion.api.minecraft.metadata.Metadata) ArrayList(java.util.ArrayList) Chunk1_14Type(com.viaversion.viaversion.protocols.protocol1_14to1_13_2.types.Chunk1_14Type) JsonObject(com.viaversion.viaversion.libs.gson.JsonObject) RecipeRewriter1_13_2(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.data.RecipeRewriter1_13_2) BlockRewriter(com.viaversion.viaversion.rewriter.BlockRewriter) Item(com.viaversion.viaversion.api.minecraft.item.Item) ChunkSectionLight(com.viaversion.viaversion.api.minecraft.chunks.ChunkSectionLight) Chunk1_13Type(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.types.Chunk1_13Type) ChunkLightStorage(com.viaversion.viabackwards.protocol.protocol1_13_2to1_14.storage.ChunkLightStorage) RecipeRewriter(com.viaversion.viaversion.rewriter.RecipeRewriter) ChunkSectionLightImpl(com.viaversion.viaversion.api.minecraft.chunks.ChunkSectionLightImpl) Chunk(com.viaversion.viaversion.api.minecraft.chunks.Chunk) EntityType(com.viaversion.viaversion.api.minecraft.entities.EntityType) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) ChunkSection(com.viaversion.viaversion.api.minecraft.chunks.ChunkSection) Protocol1_13_2To1_14(com.viaversion.viabackwards.protocol.protocol1_13_2to1_14.Protocol1_13_2To1_14)

Example 4 with JsonElement

use of com.viaversion.viaversion.libs.gson.JsonElement in project ViaBackwards by ViaVersion.

the class TranslatableRewriter method loadTranslatables.

public static void loadTranslatables() {
    JsonObject jsonObject = VBMappingDataLoader.loadData("translation-mappings.json");
    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        Map<String, String> versionMappings = new HashMap<>();
        TRANSLATABLES.put(entry.getKey(), versionMappings);
        for (Map.Entry<String, JsonElement> translationEntry : entry.getValue().getAsJsonObject().entrySet()) {
            versionMappings.put(translationEntry.getKey(), translationEntry.getValue().getAsString());
        }
    }
}
Also used : HashMap(java.util.HashMap) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) JsonObject(com.viaversion.viaversion.libs.gson.JsonObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with JsonElement

use of com.viaversion.viaversion.libs.gson.JsonElement in project ViaBackwards by ViaVersion.

the class BackwardsMappings method mapIdentifiers.

// Has lots of compat layers, so we can't use the default Via method
private static void mapIdentifiers(int[] output, JsonObject newIdentifiers, JsonObject oldIdentifiers, JsonObject mapping) {
    Object2IntMap<String> newIdentifierMap = MappingDataLoader.indexedObjectToMap(oldIdentifiers);
    for (Map.Entry<String, JsonElement> entry : newIdentifiers.entrySet()) {
        String key = entry.getValue().getAsString();
        int value = newIdentifierMap.getInt(key);
        short hardId = -1;
        if (value == -1) {
            JsonPrimitive replacement = mapping.getAsJsonPrimitive(key);
            int propertyIndex;
            if (replacement == null && (propertyIndex = key.indexOf('[')) != -1) {
                replacement = mapping.getAsJsonPrimitive(key.substring(0, propertyIndex));
            }
            if (replacement != null) {
                if (replacement.getAsString().startsWith("id:")) {
                    String id = replacement.getAsString().replace("id:", "");
                    hardId = Short.parseShort(id);
                    value = newIdentifierMap.getInt(oldIdentifiers.getAsJsonPrimitive(id).getAsString());
                } else {
                    value = newIdentifierMap.getInt(replacement.getAsString());
                }
            }
            if (value == -1) {
                if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                    if (replacement != null) {
                        ViaBackwards.getPlatform().getLogger().warning("No key for " + entry.getValue() + "/" + replacement.getAsString() + " :( ");
                    } else {
                        ViaBackwards.getPlatform().getLogger().warning("No key for " + entry.getValue() + " :( ");
                    }
                }
                continue;
            }
        }
        output[Integer.parseInt(entry.getKey())] = hardId != -1 ? hardId : (short) value;
    }
}
Also used : JsonPrimitive(com.viaversion.viaversion.libs.gson.JsonPrimitive) JsonElement(com.viaversion.viaversion.libs.gson.JsonElement) Object2IntMap(com.viaversion.viaversion.libs.fastutil.objects.Object2IntMap) HashMap(java.util.HashMap) Int2ObjectMap(com.viaversion.viaversion.libs.fastutil.ints.Int2ObjectMap) Map(java.util.Map) Int2ObjectOpenHashMap(com.viaversion.viaversion.libs.fastutil.ints.Int2ObjectOpenHashMap)

Aggregations

JsonElement (com.viaversion.viaversion.libs.gson.JsonElement)13 PacketRemapper (com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)7 Type (com.viaversion.viaversion.api.type.Type)7 JsonObject (com.viaversion.viaversion.libs.gson.JsonObject)7 PacketWrapper (com.viaversion.viaversion.api.protocol.packet.PacketWrapper)5 BackwardsProtocol (com.viaversion.viabackwards.api.BackwardsProtocol)4 UserConnection (com.viaversion.viaversion.api.connection.UserConnection)4 Item (com.viaversion.viaversion.api.minecraft.item.Item)4 EntityTrackerBase (com.viaversion.viaversion.data.entity.EntityTrackerBase)4 ClientWorld (com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 ViaBackwards (com.viaversion.viabackwards.ViaBackwards)3 BackwardsMappings (com.viaversion.viabackwards.api.data.BackwardsMappings)3 TranslatableRewriter (com.viaversion.viabackwards.api.rewriters.TranslatableRewriter)3 PacketHandler (com.viaversion.viaversion.api.protocol.remapper.PacketHandler)3 SoundRewriter (com.viaversion.viabackwards.api.rewriters.SoundRewriter)2 Via (com.viaversion.viaversion.api.Via)2 RegistryType (com.viaversion.viaversion.api.minecraft.RegistryType)2 ValueTransformer (com.viaversion.viaversion.api.protocol.remapper.ValueTransformer)2