/// <summary>
 /// Read Forge VarShort field
 /// </summary>
 /// <param name="packetData">Packet data to read from</param>
 /// <returns>Length from packet data</returns>
 public int ReadNextVarShort(List <byte> packetData)
 {
     if (ForgeEnabled())
     {
         // Forge special VarShort field.
         return((int)dataTypes.ReadNextVarShort(packetData));
     }
     else
     {
         // Vanilla regular Short field
         return((int)dataTypes.ReadNextShort(packetData));
     }
 }
Exemple #2
0
        /// <summary>
        /// Process chunk column data from the server and (un)load the chunk from the Minecraft world
        /// </summary>
        /// <param name="chunkX">Chunk X location</param>
        /// <param name="chunkZ">Chunk Z location</param>
        /// <param name="chunkMask">Chunk mask for reading data</param>
        /// <param name="chunkMask2">Chunk mask for some additional 1.7 metadata</param>
        /// <param name="hasSkyLight">Contains skylight info</param>
        /// <param name="chunksContinuous">Are the chunk continuous</param>
        /// <param name="currentDimension">Current dimension type (0 = overworld)</param>
        /// <param name="cache">Cache for reading chunk data</param>
        public void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, ushort chunkMask2, bool hasSkyLight, bool chunksContinuous, int currentDimension, Queue <byte> cache)
        {
            if (protocolversion >= Protocol18Handler.MC19Version)
            {
                // 1.9 and above chunk format
                // Unloading chunks is handled by a separate packet
                for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                {
                    if ((chunkMask & (1 << chunkY)) != 0)
                    {
                        // 1.14 and above Non-air block count inside chunk section, for lighting purposes
                        if (protocolversion >= Protocol18Handler.MC114Version)
                        {
                            dataTypes.ReadNextShort(cache);
                        }

                        byte bitsPerBlock = dataTypes.ReadNextByte(cache);
                        bool usePalette   = (bitsPerBlock <= 8);

                        // Vanilla Minecraft will use at least 4 bits per block
                        if (bitsPerBlock < 4)
                        {
                            bitsPerBlock = 4;
                        }

                        // MC 1.9 to 1.12 will set palette length field to 0 when palette
                        // is not used, MC 1.13+ does not send the field at all in this case
                        int paletteLength = 0; // Assume zero when length is absent
                        if (usePalette || protocolversion < Protocol18Handler.MC113Version)
                        {
                            paletteLength = dataTypes.ReadNextVarInt(cache);
                        }

                        int[] palette = new int[paletteLength];
                        for (int i = 0; i < paletteLength; i++)
                        {
                            palette[i] = dataTypes.ReadNextVarInt(cache);
                        }

                        // Bit mask covering bitsPerBlock bits
                        // EG, if bitsPerBlock = 5, valueMask = 00011111 in binary
                        uint valueMask = (uint)((1 << bitsPerBlock) - 1);

                        ulong[] dataArray = dataTypes.ReadNextULongArray(cache);

                        Chunk chunk = new Chunk();

                        if (dataArray.Length > 0)
                        {
                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        int blockNumber = (blockY * Chunk.SizeZ + blockZ) * Chunk.SizeX + blockX;

                                        int startLong   = (blockNumber * bitsPerBlock) / 64;
                                        int startOffset = (blockNumber * bitsPerBlock) % 64;
                                        int endLong     = ((blockNumber + 1) * bitsPerBlock - 1) / 64;

                                        // TODO: In the future a single ushort may not store the entire block id;
                                        // the Block code may need to change if block state IDs go beyond 65535
                                        ushort blockId;
                                        if (startLong == endLong)
                                        {
                                            blockId = (ushort)((dataArray[startLong] >> startOffset) & valueMask);
                                        }
                                        else
                                        {
                                            int endOffset = 64 - startOffset;
                                            blockId = (ushort)((dataArray[startLong] >> startOffset | dataArray[endLong] << endOffset) & valueMask);
                                        }

                                        if (usePalette)
                                        {
                                            // Get the real block ID out of the palette
                                            blockId = (ushort)palette[blockId];
                                        }

                                        chunk[blockX, blockY, blockZ] = new Block(blockId);
                                    }
                                }
                            }
                        }

                        //We have our chunk, save the chunk into the world
                        if (handler.GetWorld()[chunkX, chunkZ] == null)
                        {
                            handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                        }
                        handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;

                        //Pre-1.14 Lighting data
                        if (protocolversion < Protocol18Handler.MC114Version)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (currentDimension == 0)
                            {
                                // Sky light is not sent in the nether or the end
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }
                }

                // Don't worry about skipping remaining data since there is no useful data afterwards in 1.9
                // (plus, it would require parsing the tile entity lists' NBT)
            }
            else if (protocolversion >= Protocol18Handler.MC18Version)
            {
                // 1.8 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Load chunk data from the server
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            //Read chunk data, all at once for performance reasons, and build the chunk object
                            Queue <ushort> queue = new Queue <ushort>(dataTypes.ReadNextUShortsLittleEndian(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ, cache));
                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(queue.Dequeue());
                                    }
                                }
                            }

                            //We have our chunk, save the chunk into the world
                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }

                    //Skip light information
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (hasSkyLight)
                            {
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }

                    //Skip biome metadata
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);
                    }
                }
            }
            else
            {
                // 1.7 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Count chunk sections
                    int sectionCount        = 0;
                    int addDataSectionCount = 0;
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            sectionCount++;
                        }
                        if ((chunkMask2 & (1 << chunkY)) != 0)
                        {
                            addDataSectionCount++;
                        }
                    }

                    //Read chunk data, unpacking 4-bit values into 8-bit values for block metadata
                    Queue <byte> blockTypes = new Queue <byte>(dataTypes.ReadData(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount, cache));
                    Queue <byte> blockMeta  = new Queue <byte>();
                    foreach (byte packed in dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache))
                    {
                        byte hig = (byte)(packed >> 4);
                        byte low = (byte)(packed & (byte)0x0F);
                        blockMeta.Enqueue(hig);
                        blockMeta.Enqueue(low);
                    }

                    //Skip data we don't need
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);          //Block light
                    if (hasSkyLight)
                    {
                        dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);      //Sky light
                    }
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * addDataSectionCount) / 2, cache);   //BlockAdd
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);                                         //Biomes
                    }
                    //Load chunk data
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(blockTypes.Dequeue(), blockMeta.Dequeue());
                                    }
                                }
                            }

                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Handle the given packet
        /// </summary>
        /// <param name="packetID">Packet ID</param>
        /// <param name="packetData">Packet contents</param>
        /// <returns>TRUE if the packet was processed, FALSE if ignored or unknown</returns>
        internal bool HandlePacket(int packetID, List <byte> packetData)
        {
            try
            {
                if (login_phase)
                {
                    switch (packetID) //Packet IDs are different while logging in
                    {
                    case 0x03:
                        if (protocolversion >= MC18Version)
                        {
                            compression_treshold = dataTypes.ReadNextVarInt(packetData);
                        }
                        break;

                    default:
                        return(false);    //Ignored packet
                    }
                }
                // Regular in-game packets
                switch (Protocol18PacketTypes.GetPacketIncomingType(packetID, protocolversion))
                {
                case PacketIncomingType.KeepAlive:
                    SendPacket(PacketOutgoingType.KeepAlive, packetData);
                    break;

                case PacketIncomingType.JoinGame:
                    handler.OnGameJoined();
                    dataTypes.ReadNextInt(packetData);
                    dataTypes.ReadNextByte(packetData);
                    if (protocolversion >= MC191Version)
                    {
                        this.currentDimension = dataTypes.ReadNextInt(packetData);
                    }
                    else
                    {
                        this.currentDimension = (sbyte)dataTypes.ReadNextByte(packetData);
                    }
                    if (protocolversion < MC114Version)
                    {
                        dataTypes.ReadNextByte(packetData);               // Difficulty - 1.13 and below
                    }
                    dataTypes.ReadNextByte(packetData);
                    dataTypes.ReadNextString(packetData);
                    if (protocolversion >= MC114Version)
                    {
                        dataTypes.ReadNextVarInt(packetData);             // View distance - 1.14 and above
                    }
                    if (protocolversion >= MC18Version)
                    {
                        dataTypes.ReadNextBool(packetData);               // Reduced debug info - 1.8 and above
                    }
                    break;

                case PacketIncomingType.ChatMessage:
                    string message = dataTypes.ReadNextString(packetData);
                    try
                    {
                        //Hide system messages or xp bar messages?
                        byte messageType = dataTypes.ReadNextByte(packetData);
                        if ((messageType == 1 && !Settings.DisplaySystemMessages) ||
                            (messageType == 2 && !Settings.DisplayXPBarMessages))
                        {
                            break;
                        }
                    }
                    catch (ArgumentOutOfRangeException) { /* No message type */ }
                    handler.OnTextReceived(message, true);
                    break;

                case PacketIncomingType.Respawn:
                    this.currentDimension = dataTypes.ReadNextInt(packetData);
                    if (protocolversion < MC114Version)
                    {
                        dataTypes.ReadNextByte(packetData);               // Difficulty - 1.13 and below
                    }
                    dataTypes.ReadNextByte(packetData);
                    dataTypes.ReadNextString(packetData);
                    handler.OnRespawn();
                    break;

                case PacketIncomingType.PlayerPositionAndLook:
                    if (handler.GetTerrainEnabled())
                    {
                        double x       = dataTypes.ReadNextDouble(packetData);
                        double y       = dataTypes.ReadNextDouble(packetData);
                        double z       = dataTypes.ReadNextDouble(packetData);
                        float  yaw     = dataTypes.ReadNextFloat(packetData);
                        float  pitch   = dataTypes.ReadNextFloat(packetData);
                        byte   locMask = dataTypes.ReadNextByte(packetData);

                        if (protocolversion >= MC18Version)
                        {
                            Location location = handler.GetCurrentLocation();
                            location.X = (locMask & 1 << 0) != 0 ? location.X + x : x;
                            location.Y = (locMask & 1 << 1) != 0 ? location.Y + y : y;
                            location.Z = (locMask & 1 << 2) != 0 ? location.Z + z : z;
                            handler.UpdateLocation(location, yaw, pitch);
                        }
                        else
                        {
                            handler.UpdateLocation(new Location(x, y, z), yaw, pitch);
                        }
                    }

                    if (protocolversion >= MC19Version)
                    {
                        int teleportID = dataTypes.ReadNextVarInt(packetData);
                        // Teleport confirm packet
                        SendPacket(PacketOutgoingType.TeleportConfirm, dataTypes.GetVarInt(teleportID));
                    }
                    break;

                case PacketIncomingType.ChunkData:
                    if (handler.GetTerrainEnabled())
                    {
                        int    chunkX           = dataTypes.ReadNextInt(packetData);
                        int    chunkZ           = dataTypes.ReadNextInt(packetData);
                        bool   chunksContinuous = dataTypes.ReadNextBool(packetData);
                        ushort chunkMask        = protocolversion >= MC19Version
                                ? (ushort)dataTypes.ReadNextVarInt(packetData)
                                : dataTypes.ReadNextUShort(packetData);
                        if (protocolversion < MC18Version)
                        {
                            ushort addBitmap          = dataTypes.ReadNextUShort(packetData);
                            int    compressedDataSize = dataTypes.ReadNextInt(packetData);
                            byte[] compressed         = dataTypes.ReadData(compressedDataSize, packetData);
                            byte[] decompressed       = ZlibUtils.Decompress(compressed);
                            pTerrain.ProcessChunkColumnData(chunkX, chunkZ, chunkMask, addBitmap, currentDimension == 0, chunksContinuous, currentDimension, new List <byte>(decompressed));
                        }
                        else
                        {
                            if (protocolversion >= MC114Version)
                            {
                                dataTypes.ReadNextNbt(packetData);      // Heightmaps - 1.14 and above
                            }
                            int dataSize = dataTypes.ReadNextVarInt(packetData);
                            pTerrain.ProcessChunkColumnData(chunkX, chunkZ, chunkMask, 0, false, chunksContinuous, currentDimension, packetData);
                        }
                    }
                    break;

                case PacketIncomingType.MultiBlockChange:
                    if (handler.GetTerrainEnabled())
                    {
                        int chunkX      = dataTypes.ReadNextInt(packetData);
                        int chunkZ      = dataTypes.ReadNextInt(packetData);
                        int recordCount = protocolversion < MC18Version
                                ? (int)dataTypes.ReadNextShort(packetData)
                                : dataTypes.ReadNextVarInt(packetData);

                        for (int i = 0; i < recordCount; i++)
                        {
                            byte   locationXZ;
                            ushort blockIdMeta;
                            int    blockY;

                            if (protocolversion < MC18Version)
                            {
                                blockIdMeta = dataTypes.ReadNextUShort(packetData);
                                blockY      = (ushort)dataTypes.ReadNextByte(packetData);
                                locationXZ  = dataTypes.ReadNextByte(packetData);
                            }
                            else
                            {
                                locationXZ  = dataTypes.ReadNextByte(packetData);
                                blockY      = (ushort)dataTypes.ReadNextByte(packetData);
                                blockIdMeta = (ushort)dataTypes.ReadNextVarInt(packetData);
                            }

                            int   blockX = locationXZ >> 4;
                            int   blockZ = locationXZ & 0x0F;
                            Block block  = new Block(blockIdMeta);
                            handler.GetWorld().SetBlock(new Location(chunkX, chunkZ, blockX, blockY, blockZ), block);
                        }
                    }
                    break;

                case PacketIncomingType.BlockChange:
                    if (handler.GetTerrainEnabled())
                    {
                        if (protocolversion < MC18Version)
                        {
                            int   blockX    = dataTypes.ReadNextInt(packetData);
                            int   blockY    = dataTypes.ReadNextByte(packetData);
                            int   blockZ    = dataTypes.ReadNextInt(packetData);
                            short blockId   = (short)dataTypes.ReadNextVarInt(packetData);
                            byte  blockMeta = dataTypes.ReadNextByte(packetData);
                            handler.GetWorld().SetBlock(new Location(blockX, blockY, blockZ), new Block(blockId, blockMeta));
                        }
                        else
                        {
                            handler.GetWorld().SetBlock(dataTypes.ReadNextLocation(packetData), new Block((ushort)dataTypes.ReadNextVarInt(packetData)));
                        }
                    }
                    break;

                case PacketIncomingType.MapChunkBulk:
                    if (protocolversion < MC19Version && handler.GetTerrainEnabled())
                    {
                        int         chunkCount;
                        bool        hasSkyLight;
                        List <byte> chunkData = packetData;

                        //Read global fields
                        if (protocolversion < MC18Version)
                        {
                            chunkCount = dataTypes.ReadNextShort(packetData);
                            int compressedDataSize = dataTypes.ReadNextInt(packetData);
                            hasSkyLight = dataTypes.ReadNextBool(packetData);
                            byte[] compressed   = dataTypes.ReadData(compressedDataSize, packetData);
                            byte[] decompressed = ZlibUtils.Decompress(compressed);
                            chunkData = new List <byte>(decompressed);
                        }
                        else
                        {
                            hasSkyLight = dataTypes.ReadNextBool(packetData);
                            chunkCount  = dataTypes.ReadNextVarInt(packetData);
                        }

                        //Read chunk records
                        int[]    chunkXs    = new int[chunkCount];
                        int[]    chunkZs    = new int[chunkCount];
                        ushort[] chunkMasks = new ushort[chunkCount];
                        ushort[] addBitmaps = new ushort[chunkCount];
                        for (int chunkColumnNo = 0; chunkColumnNo < chunkCount; chunkColumnNo++)
                        {
                            chunkXs[chunkColumnNo]    = dataTypes.ReadNextInt(packetData);
                            chunkZs[chunkColumnNo]    = dataTypes.ReadNextInt(packetData);
                            chunkMasks[chunkColumnNo] = dataTypes.ReadNextUShort(packetData);
                            addBitmaps[chunkColumnNo] = protocolversion < MC18Version
                                    ? dataTypes.ReadNextUShort(packetData)
                                    : (ushort)0;
                        }

                        //Process chunk records
                        for (int chunkColumnNo = 0; chunkColumnNo < chunkCount; chunkColumnNo++)
                        {
                            pTerrain.ProcessChunkColumnData(chunkXs[chunkColumnNo], chunkZs[chunkColumnNo], chunkMasks[chunkColumnNo], addBitmaps[chunkColumnNo], hasSkyLight, true, currentDimension, chunkData);
                        }
                    }
                    break;

                case PacketIncomingType.UnloadChunk:
                    if (protocolversion >= MC19Version && handler.GetTerrainEnabled())
                    {
                        int chunkX = dataTypes.ReadNextInt(packetData);
                        int chunkZ = dataTypes.ReadNextInt(packetData);
                        handler.GetWorld()[chunkX, chunkZ] = null;
                    }
                    break;

                case PacketIncomingType.PlayerListUpdate:
                    if (protocolversion >= MC18Version)
                    {
                        int action     = dataTypes.ReadNextVarInt(packetData);
                        int numActions = dataTypes.ReadNextVarInt(packetData);
                        for (int i = 0; i < numActions; i++)
                        {
                            Guid uuid = dataTypes.ReadNextUUID(packetData);
                            switch (action)
                            {
                            case 0x00:         //Player Join
                                string name    = dataTypes.ReadNextString(packetData);
                                int    propNum = dataTypes.ReadNextVarInt(packetData);
                                for (int p = 0; p < propNum; p++)
                                {
                                    string key = dataTypes.ReadNextString(packetData);
                                    string val = dataTypes.ReadNextString(packetData);
                                    if (dataTypes.ReadNextBool(packetData))
                                    {
                                        dataTypes.ReadNextString(packetData);
                                    }
                                }
                                dataTypes.ReadNextVarInt(packetData);
                                dataTypes.ReadNextVarInt(packetData);
                                if (dataTypes.ReadNextBool(packetData))
                                {
                                    dataTypes.ReadNextString(packetData);
                                }
                                handler.OnPlayerJoin(uuid, name);
                                break;

                            case 0x01:         //Update gamemode
                            case 0x02:         //Update latency
                                dataTypes.ReadNextVarInt(packetData);
                                break;

                            case 0x03:         //Update display name
                                if (dataTypes.ReadNextBool(packetData))
                                {
                                    dataTypes.ReadNextString(packetData);
                                }
                                break;

                            case 0x04:         //Player Leave
                                handler.OnPlayerLeave(uuid);
                                break;

                            default:
                                //Unknown player list item type
                                break;
                            }
                        }
                    }
                    else     //MC 1.7.X does not provide UUID in tab-list updates
                    {
                        string name     = dataTypes.ReadNextString(packetData);
                        bool   online   = dataTypes.ReadNextBool(packetData);
                        short  ping     = dataTypes.ReadNextShort(packetData);
                        Guid   FakeUUID = new Guid(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(name)).Take(16).ToArray());
                        if (online)
                        {
                            handler.OnPlayerJoin(FakeUUID, name);
                        }
                        else
                        {
                            handler.OnPlayerLeave(FakeUUID);
                        }
                    }
                    break;

                case PacketIncomingType.TabCompleteResult:
                    if (protocolversion >= MC113Version)
                    {
                        autocomplete_transaction_id = dataTypes.ReadNextVarInt(packetData);
                        dataTypes.ReadNextVarInt(packetData);     // Start of text to replace
                        dataTypes.ReadNextVarInt(packetData);     // Length of text to replace
                    }

                    int autocomplete_count = dataTypes.ReadNextVarInt(packetData);
                    autocomplete_result.Clear();

                    for (int i = 0; i < autocomplete_count; i++)
                    {
                        autocomplete_result.Add(dataTypes.ReadNextString(packetData));
                        if (protocolversion >= MC113Version)
                        {
                            // Skip optional tooltip for each tab-complete result
                            if (dataTypes.ReadNextBool(packetData))
                            {
                                dataTypes.ReadNextString(packetData);
                            }
                        }
                    }

                    autocomplete_received = true;
                    break;

                case PacketIncomingType.PluginMessage:
                    String channel = dataTypes.ReadNextString(packetData);
                    // Length is unneeded as the whole remaining packetData is the entire payload of the packet.
                    if (protocolversion < MC18Version)
                    {
                        pForge.ReadNextVarShort(packetData);
                    }
                    handler.OnPluginChannelMessage(channel, packetData.ToArray());
                    return(pForge.HandlePluginMessage(channel, packetData, ref currentDimension));

                case PacketIncomingType.KickPacket:
                    handler.OnConnectionLost(ChatBot.DisconnectReason.InGameKick, ChatParser.ParseText(dataTypes.ReadNextString(packetData)));
                    return(false);

                case PacketIncomingType.NetworkCompressionTreshold:
                    if (protocolversion >= MC18Version && protocolversion < MC19Version)
                    {
                        compression_treshold = dataTypes.ReadNextVarInt(packetData);
                    }
                    break;

                case PacketIncomingType.ResourcePackSend:
                    string url  = dataTypes.ReadNextString(packetData);
                    string hash = dataTypes.ReadNextString(packetData);
                    //Send back "accepted" and "successfully loaded" responses for plugins making use of resource pack mandatory
                    byte[] responseHeader = new byte[0];
                    if (protocolversion < MC110Version)     //MC 1.10 does not include resource pack hash in responses
                    {
                        responseHeader = dataTypes.ConcatBytes(dataTypes.GetVarInt(hash.Length), Encoding.UTF8.GetBytes(hash));
                    }
                    SendPacket(PacketOutgoingType.ResourcePackStatus, dataTypes.ConcatBytes(responseHeader, dataTypes.GetVarInt(3)));     //Accepted pack
                    SendPacket(PacketOutgoingType.ResourcePackStatus, dataTypes.ConcatBytes(responseHeader, dataTypes.GetVarInt(0)));     //Successfully loaded
                    break;

                default:
                    return(false); //Ignored packet
                }
                return(true);      //Packet processed
            }
            catch (Exception innerException)
            {
                throw new System.IO.InvalidDataException(
                          String.Format("Failed to process incoming packet of type {0}. (PacketID: {1}, Protocol: {2}, LoginPhase: {3}, InnerException: {4}).",
                                        Protocol18PacketTypes.GetPacketIncomingType(packetID, protocolversion),
                                        packetID,
                                        protocolversion,
                                        login_phase,
                                        innerException.GetType()),
                          innerException);
            }
        }
Exemple #4
0
        /// <summary>
        /// Process chunk column data from the server and (un)load the chunk from the Minecraft world
        /// </summary>
        /// <param name="chunkX">Chunk X location</param>
        /// <param name="chunkZ">Chunk Z location</param>
        /// <param name="chunkMask">Chunk mask for reading data</param>
        /// <param name="chunkMask2">Chunk mask for some additional 1.7 metadata</param>
        /// <param name="hasSkyLight">Contains skylight info</param>
        /// <param name="chunksContinuous">Are the chunk continuous</param>
        /// <param name="currentDimension">Current dimension type (0 = overworld)</param>
        /// <param name="cache">Cache for reading chunk data</param>
        public void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, ushort chunkMask2, bool hasSkyLight, bool chunksContinuous, int currentDimension, Queue <byte> cache)
        {
            if (protocolversion >= Protocol18Handler.MC19Version)
            {
                // 1.9 and above chunk format
                // Unloading chunks is handled by a separate packet
                for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                {
                    if ((chunkMask & (1 << chunkY)) != 0)
                    {
                        // 1.14 and above Non-air block count inside chunk section, for lighting purposes
                        if (protocolversion >= Protocol18Handler.MC114Version)
                        {
                            dataTypes.ReadNextShort(cache);
                        }

                        byte bitsPerBlock = dataTypes.ReadNextByte(cache);
                        bool usePalette   = (bitsPerBlock <= 8);

                        // Vanilla Minecraft will use at least 4 bits per block
                        if (bitsPerBlock < 4)
                        {
                            bitsPerBlock = 4;
                        }

                        // MC 1.9 to 1.12 will set palette length field to 0 when palette
                        // is not used, MC 1.13+ does not send the field at all in this case
                        int paletteLength = 0; // Assume zero when length is absent
                        if (usePalette || protocolversion < Protocol18Handler.MC113Version)
                        {
                            paletteLength = dataTypes.ReadNextVarInt(cache);
                        }

                        int[] palette = new int[paletteLength];
                        for (int i = 0; i < paletteLength; i++)
                        {
                            palette[i] = dataTypes.ReadNextVarInt(cache);
                        }

                        // Bit mask covering bitsPerBlock bits
                        // EG, if bitsPerBlock = 5, valueMask = 00011111 in binary
                        uint valueMask = (uint)((1 << bitsPerBlock) - 1);

                        // Block IDs are packed in the array of 64-bits integers
                        ulong[] dataArray = dataTypes.ReadNextULongArray(cache);

                        Chunk chunk = new Chunk();

                        if (dataArray.Length > 0)
                        {
                            int longIndex   = 0;
                            int startOffset = 0 - bitsPerBlock;

                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        // NOTICE: In the future a single ushort may not store the entire block id;
                                        // the Block class may need to change if block state IDs go beyond 65535
                                        ushort blockId;

                                        // Calculate location of next block ID inside the array of Longs
                                        startOffset += bitsPerBlock;
                                        bool overlap = false;

                                        if ((startOffset + bitsPerBlock) > 64)
                                        {
                                            if (protocolversion >= Protocol18Handler.MC116Version)
                                            {
                                                // In MC 1.16+, padding is applied to prevent overlapping between Longs:
                                                // [      LONG INTEGER      ][      LONG INTEGER      ]
                                                // [Block][Block][Block]XXXXX[Block][Block][Block]XXXXX

                                                // When overlapping, move forward to the beginning of the next Long
                                                startOffset = 0;
                                                longIndex++;
                                            }
                                            else
                                            {
                                                // In MC 1.15 and lower, block IDs can overlap between Longs:
                                                // [      LONG INTEGER      ][      LONG INTEGER      ]
                                                // [Block][Block][Block][Blo  ck][Block][Block][Block][

                                                // Detect when we reached the next Long or switch to overlap mode
                                                if (startOffset >= 64)
                                                {
                                                    startOffset -= 64;
                                                    longIndex++;
                                                }
                                                else
                                                {
                                                    overlap = true;
                                                }
                                            }
                                        }

                                        // Extract Block ID
                                        if (overlap)
                                        {
                                            int endOffset = 64 - startOffset;
                                            blockId = (ushort)((dataArray[longIndex] >> startOffset | dataArray[longIndex + 1] << endOffset) & valueMask);
                                        }
                                        else
                                        {
                                            blockId = (ushort)((dataArray[longIndex] >> startOffset) & valueMask);
                                        }

                                        // Map small IDs to actual larger block IDs
                                        if (usePalette)
                                        {
                                            if (paletteLength <= blockId)
                                            {
                                                int blockNumber = (blockY * Chunk.SizeZ + blockZ) * Chunk.SizeX + blockX;
                                                throw new IndexOutOfRangeException(String.Format("Block ID {0} is outside Palette range 0-{1}! (bitsPerBlock: {2}, blockNumber: {3})",
                                                                                                 blockId,
                                                                                                 paletteLength - 1,
                                                                                                 bitsPerBlock,
                                                                                                 blockNumber));
                                            }

                                            blockId = (ushort)palette[blockId];
                                        }

                                        // We have our block, save the block into the chunk
                                        chunk[blockX, blockY, blockZ] = new Block(blockId);
                                    }
                                }
                            }
                        }

                        //We have our chunk, save the chunk into the world
                        if (handler.GetWorld()[chunkX, chunkZ] == null)
                        {
                            handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                        }
                        handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;

                        //Pre-1.14 Lighting data
                        if (protocolversion < Protocol18Handler.MC114Version)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (currentDimension == 0)
                            {
                                // Sky light is not sent in the nether or the end
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }
                }

                // Don't worry about skipping remaining data since there is no useful data afterwards in 1.9
                // (plus, it would require parsing the tile entity lists' NBT)
            }
            else if (protocolversion >= Protocol18Handler.MC18Version)
            {
                // 1.8 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Load chunk data from the server
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            //Read chunk data, all at once for performance reasons, and build the chunk object
                            Queue <ushort> queue = new Queue <ushort>(dataTypes.ReadNextUShortsLittleEndian(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ, cache));
                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(queue.Dequeue());
                                    }
                                }
                            }

                            //We have our chunk, save the chunk into the world
                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }

                    //Skip light information
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (hasSkyLight)
                            {
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }

                    //Skip biome metadata
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);
                    }
                }
            }
            else
            {
                // 1.7 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Count chunk sections
                    int sectionCount        = 0;
                    int addDataSectionCount = 0;
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            sectionCount++;
                        }
                        if ((chunkMask2 & (1 << chunkY)) != 0)
                        {
                            addDataSectionCount++;
                        }
                    }

                    //Read chunk data, unpacking 4-bit values into 8-bit values for block metadata
                    Queue <byte> blockTypes = new Queue <byte>(dataTypes.ReadData(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount, cache));
                    Queue <byte> blockMeta  = new Queue <byte>();
                    foreach (byte packed in dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache))
                    {
                        byte hig = (byte)(packed >> 4);
                        byte low = (byte)(packed & (byte)0x0F);
                        blockMeta.Enqueue(hig);
                        blockMeta.Enqueue(low);
                    }

                    //Skip data we don't need
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);          //Block light
                    if (hasSkyLight)
                    {
                        dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);      //Sky light
                    }
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * addDataSectionCount) / 2, cache);   //BlockAdd
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);                                         //Biomes
                    }
                    //Load chunk data
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(blockTypes.Dequeue(), blockMeta.Dequeue());
                                    }
                                }
                            }

                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }
                }
            }
        }