Search in sources :

Example 16 with PacketHandler

use of com.viaversion.viaversion.api.protocol.remapper.PacketHandler in project ViaBackwards by ViaVersion.

the class BlockItemPackets1_13 method registerPackets.

@Override
protected void registerPackets() {
    protocol.registerClientbound(ClientboundPackets1_13.COOLDOWN, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int itemId = wrapper.read(Type.VAR_INT);
                    int oldId = protocol.getMappingData().getItemMappings().get(itemId);
                    if (oldId != -1) {
                        Optional<String> eggEntityId = SpawnEggRewriter.getEntityId(oldId);
                        if (eggEntityId.isPresent()) {
                            itemId = 383 << 16;
                        } else {
                            itemId = (oldId >> 4) << 16 | oldId & 0xF;
                        }
                    }
                    wrapper.write(Type.VAR_INT, itemId);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.BLOCK_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Location
            map(Type.POSITION);
            // Action Id
            map(Type.UNSIGNED_BYTE);
            // Action param
            map(Type.UNSIGNED_BYTE);
            // Block Id - /!\ NOT BLOCK STATE ID
            map(Type.VAR_INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int blockId = wrapper.get(Type.VAR_INT, 0);
                    if (blockId == 73)
                        blockId = 25;
                    else if (blockId == 99)
                        blockId = 33;
                    else if (blockId == 92)
                        blockId = 29;
                    else if (blockId == 142)
                        blockId = 54;
                    else if (blockId == 305)
                        blockId = 146;
                    else if (blockId == 249)
                        blockId = 130;
                    else if (blockId == 257)
                        blockId = 138;
                    else if (blockId == 140)
                        blockId = 52;
                    else if (blockId == 472)
                        blockId = 209;
                    else if (blockId >= 483 && blockId <= 498)
                        blockId = blockId - 483 + 219;
                    wrapper.set(Type.VAR_INT, 0, blockId);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.BLOCK_ENTITY_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Position
            map(Type.POSITION);
            // 1 - Action
            map(Type.UNSIGNED_BYTE);
            // 2 - NBT Data
            map(Type.NBT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    BackwardsBlockEntityProvider provider = Via.getManager().getProviders().get(BackwardsBlockEntityProvider.class);
                    // TODO conduit handling
                    if (wrapper.get(Type.UNSIGNED_BYTE, 0) == 5) {
                        wrapper.cancel();
                    }
                    wrapper.set(Type.NBT, 0, provider.transform(wrapper.user(), wrapper.get(Type.POSITION, 0), wrapper.get(Type.NBT, 0)));
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.UNLOAD_CHUNK, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int chunkMinX = wrapper.passthrough(Type.INT) << 4;
                    int chunkMinZ = wrapper.passthrough(Type.INT) << 4;
                    int chunkMaxX = chunkMinX + 15;
                    int chunkMaxZ = chunkMinZ + 15;
                    BackwardsBlockStorage blockStorage = wrapper.user().get(BackwardsBlockStorage.class);
                    blockStorage.getBlocks().entrySet().removeIf(entry -> {
                        Position position = entry.getKey();
                        return position.getX() >= chunkMinX && position.getZ() >= chunkMinZ && position.getX() <= chunkMaxX && position.getZ() <= chunkMaxZ;
                    });
                }
            });
        }
    });
    // Block Change
    protocol.registerClientbound(ClientboundPackets1_13.BLOCK_CHANGE, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int blockState = wrapper.read(Type.VAR_INT);
                    Position position = wrapper.get(Type.POSITION, 0);
                    // Store blocks
                    BackwardsBlockStorage storage = wrapper.user().get(BackwardsBlockStorage.class);
                    storage.checkAndStore(position, blockState);
                    wrapper.write(Type.VAR_INT, protocol.getMappingData().getNewBlockStateId(blockState));
                    // Flower pot special treatment
                    flowerPotSpecialTreatment(wrapper.user(), blockState, position);
                }
            });
        }
    });
    // Multi Block Change
    protocol.registerClientbound(ClientboundPackets1_13.MULTI_BLOCK_CHANGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Chunk X
            map(Type.INT);
            // 1 - Chunk Z
            map(Type.INT);
            map(Type.BLOCK_CHANGE_RECORD_ARRAY);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    BackwardsBlockStorage storage = wrapper.user().get(BackwardsBlockStorage.class);
                    for (BlockChangeRecord record : wrapper.get(Type.BLOCK_CHANGE_RECORD_ARRAY, 0)) {
                        int chunkX = wrapper.get(Type.INT, 0);
                        int chunkZ = wrapper.get(Type.INT, 1);
                        int block = record.getBlockId();
                        Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                        // Store if needed
                        storage.checkAndStore(position, block);
                        // Flower pot special treatment
                        flowerPotSpecialTreatment(wrapper.user(), block, position);
                        // Change to old id
                        record.setBlockId(protocol.getMappingData().getNewBlockStateId(block));
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.WINDOW_ITEMS, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.UNSIGNED_BYTE);
            map(Type.FLAT_ITEM_ARRAY, Type.ITEM_ARRAY);
            handler(itemArrayHandler(Type.ITEM_ARRAY));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.SET_SLOT, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.UNSIGNED_BYTE);
            map(Type.SHORT);
            map(Type.FLAT_ITEM, Type.ITEM);
            handler(itemToClientHandler(Type.ITEM));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.CHUNK_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            handler(wrapper -> {
                ClientWorld clientWorld = wrapper.user().get(ClientWorld.class);
                Chunk1_9_3_4Type type_old = new Chunk1_9_3_4Type(clientWorld);
                Chunk1_13Type type = new Chunk1_13Type(clientWorld);
                Chunk chunk = wrapper.read(type);
                // Handle Block Entities before block rewrite
                BackwardsBlockEntityProvider provider = Via.getManager().getProviders().get(BackwardsBlockEntityProvider.class);
                BackwardsBlockStorage storage = wrapper.user().get(BackwardsBlockStorage.class);
                for (CompoundTag tag : chunk.getBlockEntities()) {
                    Tag idTag = tag.get("id");
                    if (idTag == null)
                        continue;
                    String id = (String) idTag.getValue();
                    // Ignore if we don't handle it
                    if (!provider.isHandled(id))
                        continue;
                    int sectionIndex = ((NumberTag) tag.get("y")).asInt() >> 4;
                    if (sectionIndex < 0 || sectionIndex > 15) {
                        // 1.17 chunks
                        continue;
                    }
                    ChunkSection section = chunk.getSections()[sectionIndex];
                    int x = ((NumberTag) tag.get("x")).asInt();
                    int y = ((NumberTag) tag.get("y")).asInt();
                    int z = ((NumberTag) tag.get("z")).asInt();
                    Position position = new Position(x, (short) y, z);
                    int block = section.getFlatBlock(x & 0xF, y & 0xF, z & 0xF);
                    storage.checkAndStore(position, block);
                    provider.transform(wrapper.user(), position, tag);
                }
                // Rewrite new blocks to old blocks
                for (int i = 0; i < chunk.getSections().length; i++) {
                    ChunkSection section = chunk.getSections()[i];
                    if (section == null) {
                        continue;
                    }
                    // Flower pots require a special treatment, they are no longer block entities :(
                    for (int y = 0; y < 16; y++) {
                        for (int z = 0; z < 16; z++) {
                            for (int x = 0; x < 16; x++) {
                                int block = section.getFlatBlock(x, y, z);
                                // Check if the block is a flower
                                if (FlowerPotHandler.isFlowah(block)) {
                                    Position pos = new Position((x + (chunk.getX() << 4)), (short) (y + (i << 4)), (z + (chunk.getZ() << 4)));
                                    // Store block
                                    storage.checkAndStore(pos, block);
                                    CompoundTag nbt = provider.transform(wrapper.user(), pos, "minecraft:flower_pot");
                                    chunk.getBlockEntities().add(nbt);
                                }
                            }
                        }
                    }
                    for (int p = 0; p < section.getPaletteSize(); p++) {
                        int old = section.getPaletteEntry(p);
                        if (old != 0) {
                            int oldId = protocol.getMappingData().getNewBlockStateId(old);
                            section.setPaletteEntry(p, oldId);
                        }
                    }
                }
                if (chunk.isBiomeData()) {
                    for (int i = 0; i < 256; i++) {
                        int biome = chunk.getBiomeData()[i];
                        int newId = -1;
                        switch(biome) {
                            // end biomes
                            case 40:
                            case 41:
                            case 42:
                            case 43:
                                newId = 9;
                                break;
                            // deep ocean biomes
                            case 47:
                            case 48:
                            case 49:
                                newId = 24;
                                break;
                            case // deep frozen... let's just pick the frozen variant
                            50:
                                newId = 10;
                                break;
                            // the other new ocean biomes
                            case 44:
                            case 45:
                            case 46:
                                newId = 0;
                                break;
                        }
                        if (newId != -1) {
                            chunk.getBiomeData()[i] = newId;
                        }
                    }
                }
                wrapper.write(type_old, chunk);
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.EFFECT, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Effect Id
            map(Type.INT);
            // Location
            map(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().getItemMappings().get(data) >> 4);
                    } else if (id == 2001) {
                        // Block break + block break sound
                        data = protocol.getMappingData().getNewBlockStateId(data);
                        int blockId = data >> 4;
                        int blockData = data & 0xF;
                        wrapper.set(Type.INT, 1, (blockId & 0xFFF) | (blockData << 12));
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.MAP_DATA, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int iconCount = wrapper.passthrough(Type.VAR_INT);
                    for (int i = 0; i < iconCount; i++) {
                        int type = wrapper.read(Type.VAR_INT);
                        byte x = wrapper.read(Type.BYTE);
                        byte z = wrapper.read(Type.BYTE);
                        byte direction = wrapper.read(Type.BYTE);
                        if (wrapper.read(Type.BOOLEAN)) {
                            wrapper.read(Type.COMPONENT);
                        }
                        if (type > 9) {
                            wrapper.set(Type.VAR_INT, 1, wrapper.get(Type.VAR_INT, 1) - 1);
                            continue;
                        }
                        wrapper.write(Type.BYTE, (byte) ((type << 4) | (direction & 0x0F)));
                        wrapper.write(Type.BYTE, x);
                        wrapper.write(Type.BYTE, z);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.ENTITY_EQUIPMENT, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.VAR_INT);
            map(Type.VAR_INT);
            map(Type.FLAT_ITEM, Type.ITEM);
            handler(itemToClientHandler(Type.ITEM));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_13.WINDOW_PROPERTY, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Window Id
            map(Type.UNSIGNED_BYTE);
            // Property
            map(Type.SHORT);
            // Value
            map(Type.SHORT);
            handler(wrapper -> {
                short property = wrapper.get(Type.SHORT, 0);
                // Enchantment table
                if (property >= 4 && property <= 6) {
                    short oldId = wrapper.get(Type.SHORT, 1);
                    wrapper.set(Type.SHORT, 1, (short) protocol.getMappingData().getEnchantmentMappings().getNewId(oldId));
                }
            });
        }
    });
    protocol.registerServerbound(ServerboundPackets1_12_1.CREATIVE_INVENTORY_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.SHORT);
            map(Type.ITEM, Type.FLAT_ITEM);
            handler(itemToServerHandler(Type.FLAT_ITEM));
        }
    });
    protocol.registerServerbound(ServerboundPackets1_12_1.CLICK_WINDOW, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.UNSIGNED_BYTE);
            map(Type.SHORT);
            map(Type.BYTE);
            map(Type.SHORT);
            map(Type.VAR_INT);
            map(Type.ITEM, Type.FLAT_ITEM);
            handler(itemToServerHandler(Type.FLAT_ITEM));
        }
    });
}
Also used : PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) HashMap(java.util.HashMap) Item(com.viaversion.viaversion.api.minecraft.item.Item) ListTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ListTag) FlowerPotHandler(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.block_entity_handlers.FlowerPotHandler) 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) Chunk(com.viaversion.viaversion.api.minecraft.chunks.Chunk) ShortTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ShortTag) Locale(java.util.Locale) Map(java.util.Map) UserConnection(com.viaversion.viaversion.api.connection.UserConnection) IntTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.IntTag) SpawnEggRewriter(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.data.SpawnEggRewriter) Chunk1_13Type(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.types.Chunk1_13Type) ByteTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ByteTag) BlockIdData(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.data.BlockIdData) Position(com.viaversion.viaversion.api.minecraft.Position) ConverterRegistry(com.viaversion.viaversion.libs.opennbt.conversion.ConverterRegistry) ServerboundPackets1_12_1(com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1) EnchantmentRewriter(com.viaversion.viabackwards.api.rewriters.EnchantmentRewriter) BackwardsBlockStorage(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.storage.BackwardsBlockStorage) Tag(com.viaversion.viaversion.libs.opennbt.tag.builtin.Tag) Protocol1_13To1_12_2(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.Protocol1_13To1_12_2) BackwardsBlockEntityProvider(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.providers.BackwardsBlockEntityProvider) Chunk1_9_3_4Type(com.viaversion.viaversion.protocols.protocol1_9_1_2to1_9_3_4.types.Chunk1_9_3_4Type) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) StringTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.StringTag) Via(com.viaversion.viaversion.api.Via) Ints(com.google.common.primitives.Ints) BlockChangeRecord(com.viaversion.viaversion.api.minecraft.BlockChangeRecord) ClientboundPackets1_13(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13) NumberTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.NumberTag) List(java.util.List) ChatRewriter(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ChatRewriter) ViaBackwards(com.viaversion.viabackwards.ViaBackwards) CompoundTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.CompoundTag) Optional(java.util.Optional) ChunkSection(com.viaversion.viaversion.api.minecraft.chunks.ChunkSection) Position(com.viaversion.viaversion.api.minecraft.Position) BackwardsBlockEntityProvider(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.providers.BackwardsBlockEntityProvider) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Chunk(com.viaversion.viaversion.api.minecraft.chunks.Chunk) Chunk1_9_3_4Type(com.viaversion.viaversion.protocols.protocol1_9_1_2to1_9_3_4.types.Chunk1_9_3_4Type) BlockChangeRecord(com.viaversion.viaversion.api.minecraft.BlockChangeRecord) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) BackwardsBlockStorage(com.viaversion.viabackwards.protocol.protocol1_12_2to1_13.storage.BackwardsBlockStorage) Chunk1_13Type(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.types.Chunk1_13Type) NumberTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.NumberTag) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) ListTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ListTag) ShortTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ShortTag) IntTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.IntTag) ByteTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.ByteTag) Tag(com.viaversion.viaversion.libs.opennbt.tag.builtin.Tag) StringTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.StringTag) NumberTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.NumberTag) CompoundTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.CompoundTag) ChunkSection(com.viaversion.viaversion.api.minecraft.chunks.ChunkSection) CompoundTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.CompoundTag)

Example 17 with PacketHandler

use of com.viaversion.viaversion.api.protocol.remapper.PacketHandler in project ViaBackwards by ViaVersion.

the class EntityPackets1_12 method registerPackets.

@Override
protected void registerPackets() {
    protocol.registerClientbound(ClientboundPackets1_12.SPAWN_ENTITY, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity id
            map(Type.VAR_INT);
            // 1 - UUID
            map(Type.UUID);
            // 2 - Type
            map(Type.BYTE);
            // 3 - x
            map(Type.DOUBLE);
            // 4 - y
            map(Type.DOUBLE);
            // 5 - z
            map(Type.DOUBLE);
            // 6 - Pitch
            map(Type.BYTE);
            // 7 - Yaw
            map(Type.BYTE);
            // 8 - data
            map(Type.INT);
            // Track Entity
            handler(getObjectTrackerHandler());
            handler(getObjectRewriter(id -> Entity1_12Types.ObjectType.findById(id).orElse(null)));
            // Handle FallingBlock blocks
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Optional<Entity1_12Types.ObjectType> type = Entity1_12Types.ObjectType.findById(wrapper.get(Type.BYTE, 0));
                    if (type.isPresent() && type.get() == Entity1_12Types.ObjectType.FALLING_BLOCK) {
                        int objectData = wrapper.get(Type.INT, 0);
                        int objType = objectData & 4095;
                        int data = objectData >> 12 & 15;
                        Block block = protocol.getItemRewriter().handleBlock(objType, data);
                        if (block == null) {
                            return;
                        }
                        wrapper.set(Type.INT, 0, block.getId() | block.getData() << 12);
                    }
                }
            });
        }
    });
    registerTracker(ClientboundPackets1_12.SPAWN_EXPERIENCE_ORB, Entity1_12Types.EntityType.EXPERIENCE_ORB);
    registerTracker(ClientboundPackets1_12.SPAWN_GLOBAL_ENTITY, Entity1_12Types.EntityType.WEATHER);
    protocol.registerClientbound(ClientboundPackets1_12.SPAWN_MOB, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity id
            map(Type.VAR_INT);
            // 1 - UUID
            map(Type.UUID);
            // 2 - Entity Type
            map(Type.VAR_INT);
            // 3 - X
            map(Type.DOUBLE);
            // 4 - Y
            map(Type.DOUBLE);
            // 5 - Z
            map(Type.DOUBLE);
            // 6 - Yaw
            map(Type.BYTE);
            // 7 - Pitch
            map(Type.BYTE);
            // 8 - Head Pitch
            map(Type.BYTE);
            // 9 - Velocity X
            map(Type.SHORT);
            // 10 - Velocity Y
            map(Type.SHORT);
            // 11 - Velocity Z
            map(Type.SHORT);
            // 12 - Metadata
            map(Types1_12.METADATA_LIST);
            // Track entity
            handler(getTrackerHandler());
            // Rewrite entity type / metadata
            handler(getMobSpawnRewriter(Types1_12.METADATA_LIST));
        }
    });
    registerTracker(ClientboundPackets1_12.SPAWN_PAINTING, Entity1_12Types.EntityType.PAINTING);
    protocol.registerClientbound(ClientboundPackets1_12.SPAWN_PLAYER, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity ID
            map(Type.VAR_INT);
            // 1 - Player UUID
            map(Type.UUID);
            // 2 - X
            map(Type.DOUBLE);
            // 3 - Y
            map(Type.DOUBLE);
            // 4 - Z
            map(Type.DOUBLE);
            // 5 - Yaw
            map(Type.BYTE);
            // 6 - Pitch
            map(Type.BYTE);
            // 7 - Metadata list
            map(Types1_12.METADATA_LIST);
            handler(getTrackerAndMetaHandler(Types1_12.METADATA_LIST, Entity1_12Types.EntityType.PLAYER));
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12.JOIN_GAME, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity ID
            map(Type.INT);
            // 1 - Gamemode
            map(Type.UNSIGNED_BYTE);
            // 2 - Dimension
            map(Type.INT);
            handler(getTrackerHandler(Entity1_12Types.EntityType.PLAYER, Type.INT));
            handler(getDimensionHandler(1));
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    ShoulderTracker tracker = wrapper.user().get(ShoulderTracker.class);
                    tracker.setEntityId(wrapper.get(Type.INT, 0));
                }
            });
            // Send fake inventory achievement
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper packetWrapper) throws Exception {
                    PacketWrapper wrapper = PacketWrapper.create(0x07, null, packetWrapper.user());
                    wrapper.write(Type.VAR_INT, 1);
                    wrapper.write(Type.STRING, "achievement.openInventory");
                    wrapper.write(Type.VAR_INT, 1);
                    wrapper.scheduleSend(Protocol1_11_1To1_12.class);
                }
            });
        }
    });
    registerRespawn(ClientboundPackets1_12.RESPAWN);
    registerRemoveEntities(ClientboundPackets1_12.DESTROY_ENTITIES);
    registerMetadataRewriter(ClientboundPackets1_12.ENTITY_METADATA, Types1_12.METADATA_LIST);
    protocol.registerClientbound(ClientboundPackets1_12.ENTITY_PROPERTIES, new PacketRemapper() {

        @Override
        public void registerMap() {
            map(Type.VAR_INT);
            map(Type.INT);
            handler(wrapper -> {
                int size = wrapper.get(Type.INT, 0);
                int newSize = size;
                for (int i = 0; i < size; i++) {
                    String key = wrapper.read(Type.STRING);
                    // Remove new attribute
                    if (key.equals("generic.flyingSpeed")) {
                        newSize--;
                        wrapper.read(Type.DOUBLE);
                        int modSize = wrapper.read(Type.VAR_INT);
                        for (int j = 0; j < modSize; j++) {
                            wrapper.read(Type.UUID);
                            wrapper.read(Type.DOUBLE);
                            wrapper.read(Type.BYTE);
                        }
                    } else {
                        wrapper.write(Type.STRING, key);
                        wrapper.passthrough(Type.DOUBLE);
                        int modSize = wrapper.passthrough(Type.VAR_INT);
                        for (int j = 0; j < modSize; j++) {
                            wrapper.passthrough(Type.UUID);
                            wrapper.passthrough(Type.DOUBLE);
                            wrapper.passthrough(Type.BYTE);
                        }
                    }
                }
                if (newSize != size) {
                    wrapper.set(Type.INT, 0, newSize);
                }
            });
        }
    });
}
Also used : ShoulderTracker(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.data.ShoulderTracker) Entity1_12Types(com.viaversion.viaversion.api.minecraft.entities.Entity1_12Types) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) LegacyEntityRewriter(com.viaversion.viabackwards.api.rewriters.LegacyEntityRewriter) ClientboundPackets1_12(com.viaversion.viaversion.protocols.protocol1_12to1_11_1.ClientboundPackets1_12) ParrotStorage(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.data.ParrotStorage) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) EntityType(com.viaversion.viaversion.api.minecraft.entities.EntityType) Block(com.viaversion.viabackwards.utils.Block) Types1_12(com.viaversion.viaversion.api.type.types.version.Types1_12) Metadata(com.viaversion.viaversion.api.minecraft.metadata.Metadata) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Type(com.viaversion.viaversion.api.type.Type) StoredEntityData(com.viaversion.viaversion.api.data.entity.StoredEntityData) MetaType1_12(com.viaversion.viaversion.api.minecraft.metadata.types.MetaType1_12) CompoundTag(com.viaversion.viaversion.libs.opennbt.tag.builtin.CompoundTag) Optional(java.util.Optional) ShoulderTracker(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.data.ShoulderTracker) Protocol1_11_1To1_12(com.viaversion.viabackwards.protocol.protocol1_11_1to1_12.Protocol1_11_1To1_12) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Block(com.viaversion.viabackwards.utils.Block)

Example 18 with PacketHandler

use of com.viaversion.viaversion.api.protocol.remapper.PacketHandler in project ViaBackwards by ViaVersion.

the class ItemPackets1_11_1 method registerPackets.

@Override
protected void registerPackets() {
    registerSetSlot(ClientboundPackets1_9_3.SET_SLOT, Type.ITEM);
    registerWindowItems(ClientboundPackets1_9_3.WINDOW_ITEMS, Type.ITEM_ARRAY);
    registerEntityEquipment(ClientboundPackets1_9_3.ENTITY_EQUIPMENT, Type.ITEM);
    // Plugin message Packet -> Trading
    protocol.registerClientbound(ClientboundPackets1_9_3.PLUGIN_MESSAGE, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    if (wrapper.get(Type.STRING, 0).equalsIgnoreCase("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
                            wrapper.write(Type.ITEM, handleItemToClient(wrapper.read(Type.ITEM)));
                            // Output Item
                            wrapper.write(Type.ITEM, handleItemToClient(wrapper.read(Type.ITEM)));
                            // Has second item
                            boolean secondItem = wrapper.passthrough(Type.BOOLEAN);
                            if (secondItem) {
                                // Second Item
                                wrapper.write(Type.ITEM, handleItemToClient(wrapper.read(Type.ITEM)));
                            }
                            // Trade disabled
                            wrapper.passthrough(Type.BOOLEAN);
                            // Number of tools uses
                            wrapper.passthrough(Type.INT);
                            // Maximum number of trade uses
                            wrapper.passthrough(Type.INT);
                        }
                    }
                }
            });
        }
    });
    registerClickWindow(ServerboundPackets1_9_3.CLICK_WINDOW, Type.ITEM);
    registerCreativeInvAction(ServerboundPackets1_9_3.CREATIVE_INVENTORY_ACTION, Type.ITEM);
    // Handle item metadata
    protocol.getEntityRewriter().filter().handler((event, meta) -> {
        if (meta.metaType().type().equals(Type.ITEM)) {
            // Is Item
            meta.setValue(handleItemToClient((Item) meta.getValue()));
        }
    });
}
Also used : Item(com.viaversion.viaversion.api.minecraft.item.Item) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)

Example 19 with PacketHandler

use of com.viaversion.viaversion.api.protocol.remapper.PacketHandler 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)

Example 20 with PacketHandler

use of com.viaversion.viaversion.api.protocol.remapper.PacketHandler in project ViaVersion by ViaVersion.

the class WorldPackets method register.

public static void register(Protocol protocol) {
    // Outgoing packets
    protocol.registerClientbound(ClientboundPackets1_12_1.SPAWN_PAINTING, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Entity ID
            map(Type.VAR_INT);
            // 1 - Entity UUID
            map(Type.UUID);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    PaintingProvider provider = Via.getManager().getProviders().get(PaintingProvider.class);
                    String motive = wrapper.read(Type.STRING);
                    Optional<Integer> id = provider.getIntByIdentifier(motive);
                    if (!id.isPresent() && (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug())) {
                        Via.getPlatform().getLogger().warning("Could not find painting motive: " + motive + " falling back to default (0)");
                    }
                    wrapper.write(Type.VAR_INT, id.orElse(0));
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.BLOCK_ENTITY_DATA, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Location
            map(Type.POSITION);
            // 1 - Action
            map(Type.UNSIGNED_BYTE);
            // 2 - NBT data
            map(Type.NBT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Position position = wrapper.get(Type.POSITION, 0);
                    short action = wrapper.get(Type.UNSIGNED_BYTE, 0);
                    CompoundTag tag = wrapper.get(Type.NBT, 0);
                    BlockEntityProvider provider = Via.getManager().getProviders().get(BlockEntityProvider.class);
                    int newId = provider.transform(wrapper.user(), position, tag, true);
                    if (newId != -1) {
                        BlockStorage storage = wrapper.user().get(BlockStorage.class);
                        BlockStorage.ReplacementData replacementData = storage.get(position);
                        if (replacementData != null) {
                            replacementData.setReplacement(newId);
                        }
                    }
                    if (action == 5) {
                        // Set type of flower in flower pot
                        // Removed
                        wrapper.cancel();
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.BLOCK_ACTION, new PacketRemapper() {

        @Override
        public void registerMap() {
            // Location
            map(Type.POSITION);
            // Action Id
            map(Type.UNSIGNED_BYTE);
            // Action param
            map(Type.UNSIGNED_BYTE);
            // Block Id - /!\ NOT BLOCK STATE ID
            map(Type.VAR_INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Position pos = wrapper.get(Type.POSITION, 0);
                    short action = wrapper.get(Type.UNSIGNED_BYTE, 0);
                    short param = wrapper.get(Type.UNSIGNED_BYTE, 1);
                    int blockId = wrapper.get(Type.VAR_INT, 0);
                    if (blockId == 25)
                        blockId = 73;
                    else if (blockId == 33)
                        blockId = 99;
                    else if (blockId == 29)
                        blockId = 92;
                    else if (blockId == 54)
                        blockId = 142;
                    else if (blockId == 146)
                        blockId = 305;
                    else if (blockId == 130)
                        blockId = 249;
                    else if (blockId == 138)
                        blockId = 257;
                    else if (blockId == 52)
                        blockId = 140;
                    else if (blockId == 209)
                        blockId = 472;
                    else if (blockId >= 219 && blockId <= 234)
                        blockId = blockId - 219 + 483;
                    if (blockId == 73) {
                        // Note block
                        // block change
                        PacketWrapper blockChange = wrapper.create(0x0B);
                        blockChange.write(Type.POSITION, pos);
                        blockChange.write(Type.VAR_INT, 249 + (action * 24 * 2) + (param * 2));
                        blockChange.send(Protocol1_13To1_12_2.class);
                    }
                    wrapper.set(Type.VAR_INT, 0, blockId);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.BLOCK_CHANGE, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    Position position = wrapper.get(Type.POSITION, 0);
                    int newId = toNewId(wrapper.get(Type.VAR_INT, 0));
                    UserConnection userConnection = wrapper.user();
                    if (Via.getConfig().isServersideBlockConnections()) {
                        ConnectionData.updateBlockStorage(userConnection, position.x(), position.y(), position.z(), newId);
                        newId = ConnectionData.connect(userConnection, position, newId);
                    }
                    wrapper.set(Type.VAR_INT, 0, checkStorage(wrapper.user(), position, newId));
                    if (Via.getConfig().isServersideBlockConnections()) {
                        // Workaround for packet order issue
                        wrapper.send(Protocol1_13To1_12_2.class);
                        wrapper.cancel();
                        ConnectionData.update(userConnection, position);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.MULTI_BLOCK_CHANGE, new PacketRemapper() {

        @Override
        public void registerMap() {
            // 0 - Chunk X
            map(Type.INT);
            // 1 - Chunk Z
            map(Type.INT);
            // 2 - Records
            map(Type.BLOCK_CHANGE_RECORD_ARRAY);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int chunkX = wrapper.get(Type.INT, 0);
                    int chunkZ = wrapper.get(Type.INT, 1);
                    UserConnection userConnection = wrapper.user();
                    BlockChangeRecord[] records = wrapper.get(Type.BLOCK_CHANGE_RECORD_ARRAY, 0);
                    // Convert ids
                    for (BlockChangeRecord record : records) {
                        int newBlock = toNewId(record.getBlockId());
                        Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                        if (Via.getConfig().isServersideBlockConnections()) {
                            ConnectionData.updateBlockStorage(userConnection, position.x(), position.y(), position.z(), newBlock);
                        }
                        record.setBlockId(checkStorage(wrapper.user(), position, newBlock));
                    }
                    if (Via.getConfig().isServersideBlockConnections()) {
                        for (BlockChangeRecord record : records) {
                            int blockState = record.getBlockId();
                            Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                            ConnectionHandler handler = ConnectionData.getConnectionHandler(blockState);
                            if (handler != null) {
                                blockState = handler.connect(userConnection, position, blockState);
                                record.setBlockId(blockState);
                            }
                        }
                        // Workaround for packet order issue
                        wrapper.send(Protocol1_13To1_12_2.class);
                        wrapper.cancel();
                        for (BlockChangeRecord record : records) {
                            Position position = new Position(record.getSectionX() + (chunkX * 16), record.getY(), record.getSectionZ() + (chunkZ * 16));
                            ConnectionData.update(userConnection, position);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.EXPLOSION, new PacketRemapper() {

        @Override
        public void registerMap() {
            if (!Via.getConfig().isServersideBlockConnections())
                return;
            // X
            map(Type.FLOAT);
            // Y
            map(Type.FLOAT);
            // Z
            map(Type.FLOAT);
            // Radius
            map(Type.FLOAT);
            // Record Count
            map(Type.INT);
            handler(new PacketHandler() {

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    UserConnection userConnection = wrapper.user();
                    int x = (int) Math.floor(wrapper.get(Type.FLOAT, 0));
                    int y = (int) Math.floor(wrapper.get(Type.FLOAT, 1));
                    int z = (int) Math.floor(wrapper.get(Type.FLOAT, 2));
                    int recordCount = wrapper.get(Type.INT, 0);
                    Position[] records = new Position[recordCount];
                    for (int i = 0; i < recordCount; i++) {
                        Position position = new Position(x + wrapper.passthrough(Type.BYTE), (short) (y + wrapper.passthrough(Type.BYTE)), z + wrapper.passthrough(Type.BYTE));
                        records[i] = position;
                        // Set to air
                        ConnectionData.updateBlockStorage(userConnection, position.x(), position.y(), position.z(), 0);
                    }
                    // Workaround for packet order issue
                    wrapper.send(Protocol1_13To1_12_2.class);
                    wrapper.cancel();
                    for (int i = 0; i < recordCount; i++) {
                        ConnectionData.update(userConnection, records[i]);
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.UNLOAD_CHUNK, new PacketRemapper() {

        @Override
        public void registerMap() {
            if (Via.getConfig().isServersideBlockConnections()) {
                handler(new PacketHandler() {

                    @Override
                    public void handle(PacketWrapper wrapper) throws Exception {
                        int x = wrapper.passthrough(Type.INT);
                        int z = wrapper.passthrough(Type.INT);
                        ConnectionData.blockConnectionProvider.unloadChunk(wrapper.user(), x, z);
                    }
                });
            }
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.NAMED_SOUND, new PacketRemapper() {

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

                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    String sound = wrapper.get(Type.STRING, 0).replace("minecraft:", "");
                    String newSoundId = NamedSoundRewriter.getNewId(sound);
                    wrapper.set(Type.STRING, 0, newSoundId);
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.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);
                    BlockStorage storage = wrapper.user().get(BlockStorage.class);
                    Chunk1_9_3_4Type type = new Chunk1_9_3_4Type(clientWorld);
                    Chunk1_13Type type1_13 = new Chunk1_13Type(clientWorld);
                    Chunk chunk = wrapper.read(type);
                    wrapper.write(type1_13, chunk);
                    for (int i = 0; i < chunk.getSections().length; i++) {
                        ChunkSection section = chunk.getSections()[i];
                        if (section == null)
                            continue;
                        for (int p = 0; p < section.getPaletteSize(); p++) {
                            int old = section.getPaletteEntry(p);
                            int newId = toNewId(old);
                            section.setPaletteEntry(p, newId);
                        }
                        boolean willSaveToStorage = false;
                        for (int p = 0; p < section.getPaletteSize(); p++) {
                            int newId = section.getPaletteEntry(p);
                            if (storage.isWelcome(newId)) {
                                willSaveToStorage = true;
                                break;
                            }
                        }
                        boolean willSaveConnection = false;
                        if (Via.getConfig().isServersideBlockConnections() && ConnectionData.needStoreBlocks()) {
                            for (int p = 0; p < section.getPaletteSize(); p++) {
                                int newId = section.getPaletteEntry(p);
                                if (ConnectionData.isWelcome(newId)) {
                                    willSaveConnection = true;
                                    break;
                                }
                            }
                        }
                        if (willSaveToStorage) {
                            for (int y = 0; y < 16; y++) {
                                for (int z = 0; z < 16; z++) {
                                    for (int x = 0; x < 16; x++) {
                                        int block = section.getFlatBlock(x, y, z);
                                        if (storage.isWelcome(block)) {
                                            storage.store(new Position((x + (chunk.getX() << 4)), (short) (y + (i << 4)), (z + (chunk.getZ() << 4))), block);
                                        }
                                    }
                                }
                            }
                        }
                        if (willSaveConnection) {
                            for (int y = 0; y < 16; y++) {
                                for (int z = 0; z < 16; z++) {
                                    for (int x = 0; x < 16; x++) {
                                        int block = section.getFlatBlock(x, y, z);
                                        if (ConnectionData.isWelcome(block)) {
                                            ConnectionData.blockConnectionProvider.storeBlock(wrapper.user(), x + (chunk.getX() << 4), y + (i << 4), z + (chunk.getZ() << 4), block);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Rewrite biome id 255 to plains
                    if (chunk.isBiomeData()) {
                        int latestBiomeWarn = Integer.MIN_VALUE;
                        for (int i = 0; i < 256; i++) {
                            int biome = chunk.getBiomeData()[i];
                            if (!VALID_BIOMES.contains(biome)) {
                                if (// is it generated naturally? *shrug*
                                biome != 255 && latestBiomeWarn != biome) {
                                    if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                                        Via.getPlatform().getLogger().warning("Received invalid biome id " + biome);
                                    }
                                    latestBiomeWarn = biome;
                                }
                                // Plains
                                chunk.getBiomeData()[i] = 1;
                            }
                        }
                    }
                    // Rewrite BlockEntities to normal blocks
                    BlockEntityProvider provider = Via.getManager().getProviders().get(BlockEntityProvider.class);
                    final Iterator<CompoundTag> iterator = chunk.getBlockEntities().iterator();
                    while (iterator.hasNext()) {
                        CompoundTag tag = iterator.next();
                        int newId = provider.transform(wrapper.user(), null, tag, false);
                        if (newId != -1) {
                            int x = ((NumberTag) tag.get("x")).asInt();
                            int y = ((NumberTag) tag.get("y")).asInt();
                            int z = ((NumberTag) tag.get("z")).asInt();
                            Position position = new Position(x, (short) y, z);
                            // Store the replacement blocks for blockupdates
                            BlockStorage.ReplacementData replacementData = storage.get(position);
                            if (replacementData != null) {
                                replacementData.setReplacement(newId);
                            }
                            chunk.getSections()[y >> 4].setFlatBlock(x & 0xF, y & 0xF, z & 0xF, newId);
                        }
                        final Tag idTag = tag.get("id");
                        if (idTag instanceof StringTag) {
                            // No longer block entities
                            final String id = ((StringTag) idTag).getValue();
                            if (id.equals("minecraft:noteblock") || id.equals("minecraft:flower_pot")) {
                                iterator.remove();
                            }
                        }
                    }
                    if (Via.getConfig().isServersideBlockConnections()) {
                        ConnectionData.connectBlocks(wrapper.user(), chunk);
                        // Workaround for packet order issue
                        wrapper.send(Protocol1_13To1_12_2.class);
                        wrapper.cancel();
                        for (int i = 0; i < chunk.getSections().length; i++) {
                            ChunkSection section = chunk.getSections()[i];
                            if (section == null)
                                continue;
                            ConnectionData.updateChunkSectionNeighbours(wrapper.user(), chunk.getX(), chunk.getZ(), i);
                        }
                    }
                }
            });
        }
    });
    protocol.registerClientbound(ClientboundPackets1_12_1.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 {
                    int particleId = wrapper.get(Type.INT, 0);
                    // Get the data (Arrays are overrated)
                    int dataCount = 0;
                    // Particles with 1 data [BlockCrack,BlockDust,FallingDust]
                    if (particleId == 37 || particleId == 38 || particleId == 46)
                        dataCount = 1;
                    else // Particles with 2 data [IconCrack]
                    if (particleId == 36)
                        dataCount = 2;
                    Integer[] data = new Integer[dataCount];
                    for (int i = 0; i < data.length; i++) data[i] = wrapper.read(Type.VAR_INT);
                    Particle particle = ParticleRewriter.rewriteParticle(particleId, data);
                    // Cancel if null or completely removed
                    if (particle == null || particle.getId() == -1) {
                        wrapper.cancel();
                        return;
                    }
                    // Handle reddust particle color
                    if (particle.getId() == 11) {
                        int count = wrapper.get(Type.INT, 1);
                        float speed = wrapper.get(Type.FLOAT, 6);
                        // Only handle for count = 0
                        if (count == 0) {
                            wrapper.set(Type.INT, 1, 1);
                            wrapper.set(Type.FLOAT, 6, 0f);
                            List<Particle.ParticleData> arguments = particle.getArguments();
                            for (int i = 0; i < 3; i++) {
                                // RGB values are represented by the X/Y/Z offset
                                float colorValue = wrapper.get(Type.FLOAT, i + 3) * speed;
                                if (colorValue == 0 && i == 0) {
                                    // https://minecraft.gamepedia.com/User:Alphappy/reddust
                                    colorValue = 1;
                                }
                                arguments.get(i).setValue(colorValue);
                                wrapper.set(Type.FLOAT, i + 3, 0f);
                            }
                        }
                    }
                    wrapper.set(Type.INT, 0, particle.getId());
                    for (Particle.ParticleData particleData : particle.getArguments()) wrapper.write(particleData.getType(), particleData.getValue());
                }
            });
        }
    });
}
Also used : StringTag(com.github.steveice10.opennbt.tag.builtin.StringTag) PacketRemapper(com.viaversion.viaversion.api.protocol.remapper.PacketRemapper) Chunk1_9_3_4Type(com.viaversion.viaversion.protocols.protocol1_9_1_2to1_9_3_4.types.Chunk1_9_3_4Type) Particle(com.viaversion.viaversion.api.type.types.Particle) BlockChangeRecord(com.viaversion.viaversion.api.minecraft.BlockChangeRecord) BlockStorage(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.storage.BlockStorage) Chunk1_13Type(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.types.Chunk1_13Type) CompoundTag(com.github.steveice10.opennbt.tag.builtin.CompoundTag) Position(com.viaversion.viaversion.api.minecraft.Position) PaintingProvider(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.providers.PaintingProvider) Chunk(com.viaversion.viaversion.api.minecraft.chunks.Chunk) UserConnection(com.viaversion.viaversion.api.connection.UserConnection) ConnectionHandler(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.blockconnections.ConnectionHandler) PacketHandler(com.viaversion.viaversion.api.protocol.remapper.PacketHandler) PacketWrapper(com.viaversion.viaversion.api.protocol.packet.PacketWrapper) NumberTag(com.github.steveice10.opennbt.tag.builtin.NumberTag) ClientWorld(com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld) CompoundTag(com.github.steveice10.opennbt.tag.builtin.CompoundTag) NumberTag(com.github.steveice10.opennbt.tag.builtin.NumberTag) StringTag(com.github.steveice10.opennbt.tag.builtin.StringTag) Tag(com.github.steveice10.opennbt.tag.builtin.Tag) BlockEntityProvider(com.viaversion.viaversion.protocols.protocol1_13to1_12_2.providers.BlockEntityProvider) ChunkSection(com.viaversion.viaversion.api.minecraft.chunks.ChunkSection)

Aggregations

PacketHandler (com.viaversion.viaversion.api.protocol.remapper.PacketHandler)64 PacketRemapper (com.viaversion.viaversion.api.protocol.remapper.PacketRemapper)64 PacketWrapper (com.viaversion.viaversion.api.protocol.packet.PacketWrapper)62 Type (com.viaversion.viaversion.api.type.Type)26 Item (com.viaversion.viaversion.api.minecraft.item.Item)25 ClientWorld (com.viaversion.viaversion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld)20 Chunk (com.viaversion.viaversion.api.minecraft.chunks.Chunk)17 Metadata (com.viaversion.viaversion.api.minecraft.metadata.Metadata)13 ChunkSection (com.viaversion.viaversion.api.minecraft.chunks.ChunkSection)12 ClientboundPackets1_13 (com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ClientboundPackets1_13)12 Via (com.viaversion.viaversion.api.Via)11 Position (com.viaversion.viaversion.api.minecraft.Position)11 CompoundTag (com.github.steveice10.opennbt.tag.builtin.CompoundTag)10 Chunk1_9_3_4Type (com.viaversion.viaversion.protocols.protocol1_9_1_2to1_9_3_4.types.Chunk1_9_3_4Type)10 UserConnection (com.viaversion.viaversion.api.connection.UserConnection)9 StringTag (com.github.steveice10.opennbt.tag.builtin.StringTag)8 ViaBackwards (com.viaversion.viabackwards.ViaBackwards)7 Entity1_13Types (com.viaversion.viaversion.api.minecraft.entities.Entity1_13Types)7 EntityType (com.viaversion.viaversion.api.minecraft.entities.EntityType)7 List (java.util.List)7