Ejemplo n.º 1
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="hasSkyLight">Contains skylight info</param>
        /// <param name="chunksContinuous">Are the chunk continuous</param>
        /// <param name="cache">Cache for reading chunk data</param>
        private void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, bool hasSkyLight, bool chunksContinuous, List<byte> cache)
        {
            if (protocolversion < MC19Version && 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>(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
                        readData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

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

                //Skip biome metadata
                if (chunksContinuous)
                    readData(Chunk.SizeX * Chunk.SizeZ, cache);
            }
        }
Ejemplo n.º 2
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>
        private bool handlePacket(int packetID, List<byte> packetData)
        {
            if (login_phase)
            {
                switch (packetID) //Packet IDs are different while logging in
                {
                    case 0x03:
                        if (protocolversion >= MC18Version)
                            compression_treshold = readNextVarInt(packetData);
                        break;
                    default:
                        return false; //Ignored packet
                }
            }
            // Regular in-game packets

            switch (getPacketIncomingType(packetID, protocolversion))
            {
                case PacketIncomingType.KeepAlive:
                    SendPacket(protocolversion >= MC19Version ? 0x0B : 0x00, packetData);
                    break;
                case PacketIncomingType.JoinGame:
                    handler.OnGameJoined();
                    break;
                case PacketIncomingType.ChatMessage:
                    string message = readNextString(packetData);
                    try
                    {
                        //Hide system messages or xp bar messages?
                        byte messageType = readNextByte(packetData);
                        if ((messageType == 1 && !Settings.DisplaySystemMessages)
                            || (messageType == 2 && !Settings.DisplayXPBarMessages))
                            break;
                    }
                    catch (ArgumentOutOfRangeException) { /* No message type */ }
                    handler.OnTextReceived(ChatParser.ParseText(message));
                    break;
                case PacketIncomingType.PlayerPositionAndLook:
                    if (Settings.TerrainAndMovements)
                    {
                        double x = readNextDouble(packetData);
                        double y = readNextDouble(packetData);
                        double z = readNextDouble(packetData);
                        readData(8, packetData); //Ignore look
                        byte locMask = readNextByte(packetData);
                        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);

                        if (protocolversion >= MC19Version)
                            readNextVarInt(packetData);
                    }
                    break;
                case PacketIncomingType.ChunkData:
                    if (Settings.TerrainAndMovements)
                    {
                        int chunkX = readNextInt(packetData);
                        int chunkZ = readNextInt(packetData);
                        bool chunksContinuous = readNextBool(packetData);
                        ushort chunkMask = protocolversion >= MC19Version ? (ushort)readNextVarInt(packetData) : readNextUShort(packetData);
                        int dataSize = readNextVarInt(packetData);
                        ProcessChunkColumnData(chunkX, chunkZ, chunkMask, false, chunksContinuous, packetData);
                    }
                    break;
                case PacketIncomingType.MultiBlockChange:
                    if (Settings.TerrainAndMovements)
                    {
                        int chunkX = readNextInt(packetData);
                        int chunkZ = readNextInt(packetData);
                        int recordCount = readNextVarInt(packetData);
                        for (int i = 0; i < recordCount; i++)
                        {
                            byte locationXZ = readNextByte(packetData);
                            int blockX = locationXZ >> 4;
                            int blockZ = locationXZ & 0x0F;
                            int blockY = (ushort)readNextByte(packetData);
                            Block block = new Block((ushort)readNextVarInt(packetData));
                            handler.GetWorld().SetBlock(new Location(chunkX, chunkZ, blockX, blockY, blockZ), block);
                        }
                    }
                    break;
                case PacketIncomingType.BlockChange:
                    if (Settings.TerrainAndMovements)
                        handler.GetWorld().SetBlock(Location.FromLong(readNextULong(packetData)), new Block((ushort)readNextVarInt(packetData)));
                    break;
                case PacketIncomingType.MapChunkBulk:
                    if (protocolversion < MC19Version && Settings.TerrainAndMovements)
                    {
                        bool hasSkyLight = readNextBool(packetData);
                        int chunkCount = readNextVarInt(packetData);

                        //Read chunk records
                        int[] chunkXs = new int[chunkCount];
                        int[] chunkZs = new int[chunkCount];
                        ushort[] chunkMasks = new ushort[chunkCount];
                        for (int chunkColumnNo = 0; chunkColumnNo < chunkCount; chunkColumnNo++)
                        {
                            chunkXs[chunkColumnNo] = readNextInt(packetData);
                            chunkZs[chunkColumnNo] = readNextInt(packetData);
                            chunkMasks[chunkColumnNo] = readNextUShort(packetData);
                        }

                        //Process chunk records
                        for (int chunkColumnNo = 0; chunkColumnNo < chunkCount; chunkColumnNo++)
                            ProcessChunkColumnData(chunkXs[chunkColumnNo], chunkZs[chunkColumnNo], chunkMasks[chunkColumnNo], hasSkyLight, true, packetData);
                    }
                    break;
                case PacketIncomingType.UnloadChunk:
                    if (protocolversion >= MC19Version && Settings.TerrainAndMovements)
                    {
                        int chunkX = readNextInt(packetData);
                        int chunkZ = readNextInt(packetData);
                        handler.GetWorld()[chunkX, chunkZ] = null;
                    }
                    break;
                case PacketIncomingType.PlayerListUpdate:
                    if (protocolversion >= MC18Version)
                    {
                        int action = readNextVarInt(packetData);
                        int numActions = readNextVarInt(packetData);
                        for (int i = 0; i < numActions; i++)
                        {
                            Guid uuid = readNextUUID(packetData);
                            switch (action)
                            {
                                case 0x00: //Player Join
                                    string name = readNextString(packetData);
                                    int propNum = readNextVarInt(packetData);
                                    for (int p = 0; p < propNum; p++)
                                    {
                                        readNextString(packetData);
                                        readNextString(packetData);
                                        if (readNextBool(packetData))
                                            readNextString(packetData);
                                    }
                                    readNextVarInt(packetData);
                                    readNextVarInt(packetData);
                                    if (readNextBool(packetData))
                                        readNextString(packetData);
                                    handler.OnPlayerJoin(uuid, name);
                                    break;
                                case 0x01: //Update gamemode
                                case 0x02: //Update latency
                                    readNextVarInt(packetData);
                                    break;
                                case 0x03: //Update display name
                                    if (readNextBool(packetData))
                                        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 = readNextString(packetData);
                        bool online = readNextBool(packetData);
                        short ping = 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:
                    int autocomplete_count = readNextVarInt(packetData);
                    string tab_list = "";
                    for (int i = 0; i < autocomplete_count; i++)
                    {
                        autocomplete_result = readNextString(packetData);
                        if (autocomplete_result != "")
                            tab_list = tab_list + autocomplete_result + " ";
                    }
                    autocomplete_received = true;
                    tab_list = tab_list.Trim();
                    if (tab_list.Length > 0)
                        ConsoleIO.WriteLineFormatted("§8" + tab_list, false);
                    break;
                case PacketIncomingType.PluginMessage:
                    String channel = readNextString(packetData);
                    if (protocolversion < MC18Version)
                    {
                        if (forgeInfo == null)
                        {
                            // 1.7 and lower prefix plugin channel packets with the length.
                            // We can skip it, though.
                            readNextShort(packetData);
                        }
                        else
                        {
                            // Forge does something even weirder with the length.
                            readNextVarShort(packetData);
                        }
                    }

                    // The remaining data in the array is the entire payload of the packet.
                    handler.OnPluginChannelMessage(channel, packetData.ToArray());

                    #region Forge Login
                    if (forgeInfo != null && fmlHandshakeState != FMLHandshakeClientState.DONE)
                    {
                        if (channel == "FML|HS")
                        {
                            FMLHandshakeDiscriminator discriminator = (FMLHandshakeDiscriminator)readNextByte(packetData);

                            if (discriminator == FMLHandshakeDiscriminator.HandshakeReset)
                            {
                                fmlHandshakeState = FMLHandshakeClientState.START;
                                return true;
                            }

                            switch (fmlHandshakeState)
                            {
                                case FMLHandshakeClientState.START:
                                    if (discriminator != FMLHandshakeDiscriminator.ServerHello)
                                        return false;

                                    // Send the plugin channel registration.
                                    // REGISTER is somewhat special in that it doesn't actually include length information,
                                    // and is also \0-separated.
                                    // Also, yes, "FML" is there twice.  Don't ask me why, but that's the way forge does it.
                                    string[] channels = { "FML|HS", "FML", "FML|MP", "FML", "FORGE" };
                                    SendPluginChannelPacket("REGISTER", Encoding.UTF8.GetBytes(string.Join("\0", channels)));

                                    byte fmlProtocolVersion = readNextByte(packetData);
                                    // There's another value afterwards for the dimension, but we don't need it.

                                    if (Settings.DebugMessages)
                                        ConsoleIO.WriteLineFormatted("§8Forge protocol version : " + fmlProtocolVersion);

                                    // Tell the server we're running the same version.
                                    SendForgeHandshakePacket(FMLHandshakeDiscriminator.ClientHello, new byte[] { fmlProtocolVersion });

                                    // Then tell the server that we're running the same mods.
                                    if (Settings.DebugMessages)
                                        ConsoleIO.WriteLineFormatted("§8Sending falsified mod list to server...");
                                    byte[][] mods = new byte[forgeInfo.Mods.Count][];
                                    for (int i = 0; i < forgeInfo.Mods.Count; i++)
                                    {
                                        ForgeInfo.ForgeMod mod = forgeInfo.Mods[i];
                                        mods[i] = concatBytes(getString(mod.ModID), getString(mod.Version));
                                    }
                                    SendForgeHandshakePacket(FMLHandshakeDiscriminator.ModList,
                                        concatBytes(getVarInt(forgeInfo.Mods.Count), concatBytes(mods)));

                                    fmlHandshakeState = FMLHandshakeClientState.WAITINGSERVERDATA;

                                    return true;
                                case FMLHandshakeClientState.WAITINGSERVERDATA:
                                    if (discriminator != FMLHandshakeDiscriminator.ModList)
                                        return false;

                                    Thread.Sleep(2000);

                                    if (Settings.DebugMessages)
                                        ConsoleIO.WriteLineFormatted("§8Accepting server mod list...");
                                    // Tell the server that yes, we are OK with the mods it has
                                    // even though we don't actually care what mods it has.

                                    SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
                                        new byte[] { (byte)FMLHandshakeClientState.WAITINGSERVERDATA });

                                    fmlHandshakeState = FMLHandshakeClientState.WAITINGSERVERCOMPLETE;
                                    return false;
                                case FMLHandshakeClientState.WAITINGSERVERCOMPLETE:
                                    // The server now will tell us a bunch of registry information.
                                    // We need to read it all, though, until it says that there is no more.
                                    if (discriminator != FMLHandshakeDiscriminator.RegistryData)
                                        return false;

                                    if (protocolversion < MC18Version)
                                    {
                                        // 1.7.10 and below have one registry
                                        // with blocks and items.
                                        int registrySize = readNextVarInt(packetData);

                                        if (Settings.DebugMessages)
                                            ConsoleIO.WriteLineFormatted("§8Received registry with " + registrySize + " entries");

                                        fmlHandshakeState = FMLHandshakeClientState.PENDINGCOMPLETE;
                                    }
                                    else
                                    {
                                        // 1.8+ has more than one registry.

                                        bool hasNextRegistry = readNextBool(packetData);
                                        string registryName = readNextString(packetData);
                                        int registrySize = readNextVarInt(packetData);
                                        if (Settings.DebugMessages)
                                            ConsoleIO.WriteLineFormatted("§8Received registry " + registryName + " with " + registrySize + " entries");
                                        if (!hasNextRegistry)
                                            fmlHandshakeState = FMLHandshakeClientState.PENDINGCOMPLETE;
                                    }

                                    return false;
                                case FMLHandshakeClientState.PENDINGCOMPLETE:
                                    // The server will ask us to accept the registries.
                                    // Just say yes.
                                    if (discriminator != FMLHandshakeDiscriminator.HandshakeAck)
                                        return false;
                                    if (Settings.DebugMessages)
                                        ConsoleIO.WriteLineFormatted("§8Accepting server registries...");
                                    SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
                                        new byte[] { (byte)FMLHandshakeClientState.PENDINGCOMPLETE });
                                    fmlHandshakeState = FMLHandshakeClientState.COMPLETE;

                                    return true;
                                case FMLHandshakeClientState.COMPLETE:
                                    // One final "OK".  On the actual forge source, a packet is sent from
                                    // the client to the client saying that the connection was complete, but
                                    // we don't need to do that.

                                    SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
                                        new byte[] { (byte)FMLHandshakeClientState.COMPLETE });
                                    if (Settings.DebugMessages)
                                        ConsoleIO.WriteLine("Forge server connection complete!");
                                    fmlHandshakeState = FMLHandshakeClientState.DONE;
                                    return true;
                            }
                        }
                    }
                    #endregion

                    return false;
                case PacketIncomingType.KickPacket:
                    handler.OnConnectionLost(ChatBot.DisconnectReason.InGameKick, ChatParser.ParseText(readNextString(packetData)));
                    return false;
                case PacketIncomingType.NetworkCompressionTreshold:
                    if (protocolversion >= MC18Version && protocolversion < MC19Version)
                        compression_treshold = readNextVarInt(packetData);
                    break;
                case PacketIncomingType.ResourcePackSend:
                    string url = readNextString(packetData);
                    string hash = readNextString(packetData);
                    //Send back "accepted" and "successfully loaded" responses for plugins making use of resource pack mandatory
                    SendPacket(protocolversion >= MC19Version ? 0x16 : 0x19, concatBytes(getVarInt(hash.Length), Encoding.UTF8.GetBytes(hash), getVarInt(3)));
                    SendPacket(protocolversion >= MC19Version ? 0x16 : 0x19, concatBytes(getVarInt(hash.Length), Encoding.UTF8.GetBytes(hash), getVarInt(0)));
                    break;
                default:
                    return false; //Ignored packet
            }
            return true; //Packet processed
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Set block at the specified location
 /// </summary>
 /// <param name="location">Location to set block to</param>
 /// <param name="block">Block to set</param>
 public void SetBlock(Location location, Block block)
 {
     ChunkColumn column = this[location.ChunkX, location.ChunkZ];
     if (column != null)
     {
         Chunk chunk = column[location.ChunkY];
         if (chunk == null)
             column[location.ChunkY] = chunk = new Chunk();
         chunk[location.ChunkBlockX, location.ChunkBlockY, location.ChunkBlockZ] = block;
     }
 }