示例#1
0
        public virtual void StartLevel(PlayerInfo sender, StartLevelInfo options, SongInfo song)
        {
            if (sender.Equals(roomHost))
            {
                selectedSong   = song;
                startLevelInfo = options;

                SongWithOptions songWithDifficulty = new SongWithOptions(selectedSong, startLevelInfo);

                NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

                outMsg.Write((byte)CommandType.StartLevel);
                startLevelInfo.AddToMessage(outMsg);
                selectedSong.AddToMessage(outMsg);

                BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                BroadcastWebSocket(CommandType.StartLevel, songWithDifficulty);

                roomState      = RoomState.InGame;
                _songStartTime = DateTime.Now;
                _readyPlayers.Clear();
            }
            else
            {
                Logger.Instance.Warning($"{sender.playerName}({sender.playerId}) tried to start the level, but he is not the host");
            }
        }
示例#2
0
        public virtual void SetLevelOptions(PlayerInfo sender, StartLevelInfo info)
        {
            if (sender.Equals(roomHost))
            {
                startLevelInfo = info;

                NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

                outMsg.Write((byte)CommandType.SetLevelOptions);
                startLevelInfo.AddToMessage(outMsg);

                BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered, 0, new List <Client>()
                {
                    roomClients.First(x => x.playerInfo.Equals(sender))
                });
                BroadcastWebSocket(CommandType.SetLevelOptions, startLevelInfo);
            }
            else
            {
                Logger.Instance.Warning($"{sender.playerName}({sender.playerId}) tried to change level options, but he is not the host");
            }
        }
示例#3
0
    public override void OpenPopup()
    {
        var popup = Instantiate(popupPrefab) as GameObject;

        popup.SetActive(true);
        popup.transform.localScale = Vector3.zero;
        popup.transform.SetParent(m_canvas.transform, false);

        var playPopup = popup.GetComponent <PlayPopup>();

        playPopup.Open();
        playPopup.SetAchievedStars(starsObtained);


        StartLevelInfo _StartLevelInfo = popup.GetComponent <StartLevelInfo>();

        if (_StartLevelInfo != null)
        {
            _StartLevelInfo.star        = starsObtained;
            _StartLevelInfo.level       = level;
            _StartLevelInfo.title.text += _StartLevelInfo.level.ToString();
        }
    }
        private void PacketReceived(NetIncomingMessage msg)
        {
            if (msg == null)
            {
                DisconnectCommandReceived(null);
                return;
            }

            CommandType commandType = (CommandType)msg.ReadByte();

            if (!joined)
            {
                if (commandType == CommandType.JoinRoom)
                {
                    switch (msg.ReadByte())
                    {
                    case 0:
                    {
                        Client.Instance.playerInfo.playerState = PlayerState.DownloadingSongs;
                        Client.Instance.RequestRoomInfo();
                        Client.Instance.SendPlayerInfo();
                        Client.Instance.InRoom = true;
                        joined = true;
                        InGameOnlineController.Instance.needToSendUpdates = true;
                        if (Config.Instance.EnableVoiceChat)
                        {
                            InGameOnlineController.Instance.VoiceChatStartRecording();
                        }
                    }
                    break;

                    case 1:
                    {
                        _roomNavigationController.DisplayError("Unable to join room!\nRoom not found");
                    }
                    break;

                    case 2:
                    {
                        _roomNavigationController.DisplayError("Unable to join room!\nIncorrect password");
                    }
                    break;

                    case 3:
                    {
                        _roomNavigationController.DisplayError("Unable to join room!\nToo much players");
                    }
                    break;

                    default:
                    {
                        _roomNavigationController.DisplayError("Unable to join room!\nUnknown error");
                    }
                    break;
                    }
                }
            }
            else
            {
                try
                {
                    switch (commandType)
                    {
                    case CommandType.GetRoomInfo:
                    {
                        Client.Instance.playerInfo.playerState = PlayerState.Room;

                        roomInfo = new RoomInfo(msg);

                        Client.Instance.isHost = Client.Instance.playerInfo.Equals(roomInfo.roomHost);

                        UpdateUI(roomInfo.roomState);
                    }
                    break;

                    case CommandType.SetSelectedSong:
                    {
                        if (msg.LengthBytes < 16)
                        {
                            roomInfo.roomState    = RoomState.SelectingSong;
                            roomInfo.selectedSong = null;

                            PreviewPlayer.CrossfadeToDefault();

                            UpdateUI(roomInfo.roomState);

                            if (songToDownload != null)
                            {
                                songToDownload.songQueueState          = SongQueueState.Error;
                                Client.Instance.playerInfo.playerState = PlayerState.Room;
                            }
                        }
                        else
                        {
                            roomInfo.roomState = RoomState.Preparing;
                            SongInfo selectedSong = new SongInfo(msg);
                            roomInfo.selectedSong = selectedSong;

                            if (roomInfo.startLevelInfo == null)
                            {
                                roomInfo.startLevelInfo = new StartLevelInfo(BeatmapDifficulty.Hard, GameplayModifiers.defaultModifiers, "Standard");
                            }

                            if (songToDownload != null)
                            {
                                songToDownload.songQueueState = SongQueueState.Error;
                            }

                            UpdateUI(roomInfo.roomState);
                        }
                    }
                    break;

                    case CommandType.SetLevelOptions:
                    {
                        if (roomInfo.roomState == RoomState.SelectingSong)
                        {
                            roomInfo.startLevelInfo = new StartLevelInfo(msg);

                            _playerManagementViewController.SetGameplayModifiers(roomInfo.startLevelInfo.modifiers);
                            _difficultySelectionViewController.SetBeatmapCharacteristic(_beatmapCharacteristics.First(x => x.serializedName == roomInfo.startLevelInfo.characteristicName));

                            if (!roomInfo.perPlayerDifficulty)
                            {
                                _difficultySelectionViewController.SetBeatmapDifficulty(roomInfo.startLevelInfo.difficulty);
                            }
                        }
                    }
                    break;

                    case CommandType.GetRandomSongInfo:
                    {
                        SongInfo random = new SongInfo(SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).ToArray().Random() as BeatmapLevelSO);

                        Client.Instance.SetSelectedSong(random);
                    }
                    break;

                    case CommandType.TransferHost:
                    {
                        roomInfo.roomHost      = new PlayerInfo(msg);
                        Client.Instance.isHost = Client.Instance.playerInfo.Equals(roomInfo.roomHost);

                        if (Client.Instance.playerInfo.playerState == PlayerState.DownloadingSongs)
                        {
                            return;
                        }

                        UpdateUI(roomInfo.roomState);
                    }
                    break;

                    case CommandType.StartLevel:
                    {
                        if (Client.Instance.playerInfo.playerState == PlayerState.DownloadingSongs)
                        {
                            return;
                        }

                        StartLevelInfo levelInfo = new StartLevelInfo(msg);

                        BeatmapCharacteristicSO characteristic = _beatmapCharacteristics.First(x => x.serializedName == levelInfo.characteristicName);

                        SongInfo       songInfo = new SongInfo(msg);
                        BeatmapLevelSO level    = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(songInfo.levelId)) as BeatmapLevelSO;

                        if (level == null)
                        {
                            Logger.Error("Unable to start level! Level is null! LevelID=" + songInfo.levelId);
                        }

                        if (roomInfo.perPlayerDifficulty && _difficultySelectionViewController != null)
                        {
                            StartLevel(level, characteristic, _difficultySelectionViewController.selectedDifficulty, levelInfo.modifiers);
                        }
                        else
                        {
                            StartLevel(level, characteristic, levelInfo.difficulty, levelInfo.modifiers);
                        }
                    }
                    break;

                    case CommandType.LeaveRoom:
                    {
                        LeaveRoom();
                    }
                    break;

                    case CommandType.UpdatePlayerInfo:
                    {
                        if (roomInfo != null)
                        {
                            currentTime = msg.ReadFloat();
                            totalTime   = msg.ReadFloat();

                            int playersCount = msg.ReadInt32();

                            List <PlayerInfo> playerInfos = new List <PlayerInfo>();
                            for (int j = 0; j < playersCount; j++)
                            {
                                try
                                {
                                    playerInfos.Add(new PlayerInfo(msg));
                                }
                                catch (Exception e)
                                {
#if DEBUG
                                    Misc.Logger.Exception($"Unable to parse PlayerInfo! Excpetion: {e}");
#endif
                                }
                            }

                            switch (roomInfo.roomState)
                            {
                            case RoomState.InGame:
                                playerInfos = playerInfos.Where(x => x.playerScore > 0 && x.playerState == PlayerState.Game).ToList();
                                UpdateLeaderboard(playerInfos, currentTime, totalTime, false);
                                break;

                            case RoomState.Results:
                                playerInfos = playerInfos.Where(x => x.playerScore > 0 && (x.playerState == PlayerState.Game || x.playerState == PlayerState.Room)).ToList();
                                UpdateLeaderboard(playerInfos, currentTime, totalTime, true);
                                break;
                            }

                            _playerManagementViewController.UpdatePlayerList(playerInfos, roomInfo.roomState);
                        }
                    }
                    break;

                    case CommandType.PlayerReady:
                    {
                        int playersReady = msg.ReadInt32();
                        int playersTotal = msg.ReadInt32();

                        if (roomInfo.roomState == RoomState.Preparing && _difficultySelectionViewController != null)
                        {
                            _difficultySelectionViewController.SetPlayersReady(playersReady, playersTotal);
                        }
                    }
                    break;

                    case CommandType.Disconnect:
                    {
                        DisconnectCommandReceived(msg);
                    }
                    break;
                    }
                }catch (Exception e)
                {
                    Logger.Exception($"Unable to parse packet! Packet={commandType}, DataLength={msg.LengthBytes}\nException: {e}");
                }
            }
        }
示例#5
0
        private static void HubLoop(object sender, HighResolutionTimerElapsedEventArgs e)
        {
            if (_ticksLength.Count > 30)
            {
                _ticksLength.RemoveAt(0);
            }
            _ticksLength.Add(DateTime.UtcNow.Subtract(_lastTick).Ticks / (float)TimeSpan.TicksPerMillisecond);
            _lastTick = DateTime.UtcNow;
            List <RoomInfo> roomsList = RoomsController.GetRoomInfosList();

            string titleBuffer = $"ServerHub v{Assembly.GetEntryAssembly().GetName().Version}: {roomsList.Count} rooms, {hubClients.Count} clients in lobby, {roomsList.Select(x => x.players).Sum() + hubClients.Count} clients total {(Settings.Instance.Server.ShowTickrateInTitle ? $", {Tickrate.ToString("0.0")} tickrate" : "")}";

            if (_currentTitle != titleBuffer)
            {
                _currentTitle = titleBuffer;
                Console.Title = _currentTitle;
            }

            List <Client> allClients = hubClients.Concat(RoomsController.GetRoomsList().SelectMany(x => x.roomClients)).Concat(RadioController.radioChannels.SelectMany(x => x.radioClients)).ToList();

            NetIncomingMessage msg;

            while ((msg = ListenerServer.ReadMessage()) != null)
            {
                try
                {
                    Program.networkBytesInNow += msg.LengthBytes;

                    switch (msg.MessageType)
                    {
                    case NetIncomingMessageType.ConnectionApproval:
                    {
                        byte[] versionBytes = msg.PeekBytes(4);
                        byte[] version      = msg.ReadBytes(4);

                        if (version[0] == 0 && version[1] == 0)
                        {
                            uint versionUint       = BitConverter.ToUInt32(version, 0);
                            uint serverVersionUint = ((uint)Assembly.GetEntryAssembly().GetName().Version.Major).ConcatUInts((uint)Assembly.GetEntryAssembly().GetName().Version.Minor).ConcatUInts((uint)Assembly.GetEntryAssembly().GetName().Version.Build).ConcatUInts((uint)Assembly.GetEntryAssembly().GetName().Version.Revision);
                            msg.SenderConnection.Deny($"Version mismatch!\nServer:{serverVersionUint}\nClient:{versionUint}");
                            Logger.Instance.Log($"Client version v{versionUint} tried to connect");
                            break;
                        }

                        byte[] serverVersion = new byte[4] {
                            (byte)Assembly.GetEntryAssembly().GetName().Version.Major, (byte)Assembly.GetEntryAssembly().GetName().Version.Minor, (byte)Assembly.GetEntryAssembly().GetName().Version.Build, (byte)Assembly.GetEntryAssembly().GetName().Version.Revision
                        };

                        if (version[0] != serverVersion[0] || version[1] != serverVersion[1] || version[2] != serverVersion[2])
                        {
                            msg.SenderConnection.Deny($"Version mismatch|{string.Join('.', serverVersion)}|{string.Join('.', version)}");
                            Logger.Instance.Log($"Client version v{string.Join('.', version)} tried to connect");
                            break;
                        }

                        PlayerInfo playerInfo = new PlayerInfo(msg);

                        if (Settings.Instance.Access.WhitelistEnabled)
                        {
                            if (!IsWhitelisted(msg.SenderConnection.RemoteEndPoint, playerInfo))
                            {
                                msg.SenderConnection.Deny("You are not whitelisted on this ServerHub!");
                                Logger.Instance.Warning($"Client {playerInfo.playerName}({playerInfo.playerId})@{msg.SenderConnection.RemoteEndPoint.Address} is not whitelisted!");
                                break;
                            }
                        }

                        if (IsBlacklisted(msg.SenderConnection.RemoteEndPoint, playerInfo))
                        {
                            msg.SenderConnection.Deny("You are banned on this ServerHub!");
                            Logger.Instance.Warning($"Client {playerInfo.playerName}({playerInfo.playerId})@{msg.SenderConnection.RemoteEndPoint.Address} is banned!");
                            break;
                        }

                        msg.SenderConnection.Approve();

                        Client client = new Client(msg.SenderConnection, playerInfo);
                        client.playerInfo.playerState = PlayerState.Lobby;

                        client.ClientDisconnected += ClientDisconnected;

                        hubClients.Add(client);
                        allClients.Add(client);
                        Logger.Instance.Log($"{playerInfo.playerName} connected!");
                    };
                        break;

                    case NetIncomingMessageType.Data:
                    {
                        Client client = allClients.FirstOrDefault(x => x.playerConnection.RemoteEndPoint.Equals(msg.SenderEndPoint));

                        switch ((CommandType)msg.ReadByte())
                        {
                        case CommandType.Disconnect:
                        {
                            if (client != null)
                            {
                                allClients.Remove(client);
                                ClientDisconnected(client);
                            }
                        }
                        break;

                        case CommandType.UpdatePlayerInfo:
                        {
                            if (client != null)
                            {
                                client.playerInfo = new PlayerInfo(msg);
                                if (Settings.Instance.Misc.PlayerColors.ContainsKey(client.playerInfo.playerId))
                                {
                                    client.playerInfo.playerNameColor = Settings.Instance.Misc.PlayerColors[client.playerInfo.playerId];
                                }
                            }
                        }
                        break;

                        case CommandType.UpdateVoIPData:
                        {
                            if (!Settings.Instance.Server.AllowVoiceChat)
                            {
                                return;
                            }

                            if (client != null)
                            {
                                UnityVOIP.VoipFragment data = new UnityVOIP.VoipFragment(msg);
                                if (data.playerId == client.playerInfo.playerId)
                                {
                                    client.playerVoIPQueue.Enqueue(data);
                                }
                            }
                        }
                        break;

                        case CommandType.JoinRoom:
                        {
                            if (client != null)
                            {
                                uint roomId = msg.ReadUInt32();

                                BaseRoom room = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == roomId);

                                if (room != null)
                                {
                                    if (room.roomSettings.UsePassword)
                                    {
                                        if (RoomsController.ClientJoined(client, roomId, msg.ReadString()))
                                        {
                                            if (hubClients.Contains(client))
                                            {
                                                hubClients.Remove(client);
                                            }
                                            client.joinedRoomID = roomId;
                                        }
                                    }
                                    else
                                    {
                                        if (RoomsController.ClientJoined(client, roomId, ""))
                                        {
                                            if (hubClients.Contains(client))
                                            {
                                                hubClients.Remove(client);
                                            }
                                            client.joinedRoomID = roomId;
                                        }
                                    }
                                }
                                else
                                {
                                    RoomsController.ClientJoined(client, roomId, "");
                                }
                            }
                        }
                        break;

                        case CommandType.LeaveRoom:
                        {
                            if (client != null)
                            {
                                RoomsController.ClientLeftRoom(client);
                                client.joinedRoomID           = 0;
                                client.playerInfo.playerState = PlayerState.Lobby;
                                if (!hubClients.Contains(client))
                                {
                                    hubClients.Add(client);
                                }
                            }
                        }
                        break;

                        case CommandType.GetRooms:
                        {
                            NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                            outMsg.Write((byte)CommandType.GetRooms);
                            RoomsController.AddRoomListToMessage(outMsg);

                            msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                            Program.networkBytesOutNow += outMsg.LengthBytes;
                        }
                        break;

                        case CommandType.CreateRoom:
                        {
                            if (client != null)
                            {
                                uint roomId = RoomsController.CreateRoom(new RoomSettings(msg), client.playerInfo);

                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage(5);
                                outMsg.Write((byte)CommandType.CreateRoom);
                                outMsg.Write(roomId);

                                msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                Program.networkBytesOutNow += outMsg.LengthBytes;
                            }
                        }
                        break;

                        case CommandType.GetRoomInfo:
                        {
                            if (client != null)
                            {
#if DEBUG
                                Logger.Instance.Log("GetRoomInfo: Client room=" + client.joinedRoomID);
#endif
                                if (client.joinedRoomID != 0)
                                {
                                    BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                    if (joinedRoom != null)
                                    {
                                        NetOutgoingMessage outMsg = ListenerServer.CreateMessage();

                                        outMsg.Write((byte)CommandType.GetRoomInfo);

                                        joinedRoom.GetRoomInfo().AddToMessage(outMsg);

                                        msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                        Program.networkBytesOutNow += outMsg.LengthBytes;
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.SetSelectedSong:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    if (msg.LengthBytes < 16)
                                    {
                                        joinedRoom.SetSelectedSong(client.playerInfo, null);
                                    }
                                    else
                                    {
                                        joinedRoom.SetSelectedSong(client.playerInfo, new SongInfo(msg));
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.SetLevelOptions:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.SetLevelOptions(client.playerInfo, new StartLevelInfo(msg));
                                }
                            }
                        }
                        break;

                        case CommandType.StartLevel:
                        {
#if DEBUG
                            Logger.Instance.Log("Received command StartLevel");
#endif

                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    StartLevelInfo options = new StartLevelInfo(msg);
                                    SongInfo       song    = new SongInfo(msg);
                                    song.songDuration += 2.5f;
                                    joinedRoom.StartLevel(client.playerInfo, options, song);
                                }
                            }
                        }
                        break;

                        case CommandType.DestroyRoom:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.DestroyRoom(client.playerInfo);
                                }
                            }
                        }
                        break;

                        case CommandType.TransferHost:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.TransferHost(client.playerInfo, new PlayerInfo(msg));
                                }
                            }
                        }
                        break;

                        case CommandType.PlayerReady:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.ReadyStateChanged(client.playerInfo, msg.ReadBoolean());
                                }
                            }
                        }
                        break;

                        case CommandType.SendEventMessage:
                        {
                            if (client != null && client.joinedRoomID != 0 && Settings.Instance.Server.AllowEventMessages)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    string header = msg.ReadString();
                                    string data   = msg.ReadString();

                                    joinedRoom.BroadcastEventMessage(header, data, new List <Client>()
                                            {
                                                client
                                            });
                                    joinedRoom.BroadcastWebSocket(CommandType.SendEventMessage, new EventMessage(header, data));

                                    EventMessageReceived?.Invoke(client, header, data);
#if DEBUG
                                    Logger.Instance.Log($"Received event message! Header=\"{header}\", Data=\"{data}\"");
#endif
                                }
                            }
                        }
                        break;

                        case CommandType.GetChannelInfo:
                        {
                            if (Settings.Instance.Radio.EnableRadio && RadioController.radioStarted)
                            {
                                int channelId = msg.ReadInt32();

                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                                outMsg.Write((byte)CommandType.GetChannelInfo);

                                if (RadioController.radioChannels.Count > channelId)
                                {
                                    RadioController.radioChannels[channelId].channelInfo.AddToMessage(outMsg);
                                }
                                else
                                {
                                    new ChannelInfo()
                                    {
                                        channelId = -1, currentSong = new SongInfo()
                                        {
                                            levelId = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
                                        }
                                    }.AddToMessage(outMsg);
                                }

                                msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                Program.networkBytesOutNow += outMsg.LengthBytes;
                            }
                        }
                        break;

                        case CommandType.JoinChannel:
                        {
                            int channelId = msg.ReadInt32();

                            NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                            outMsg.Write((byte)CommandType.JoinChannel);

                            if (RadioController.ClientJoinedChannel(client, channelId))
                            {
                                outMsg.Write((byte)0);
                                hubClients.Remove(client);
                            }
                            else
                            {
                                outMsg.Write((byte)1);
                            }

                            msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                            Program.networkBytesOutNow += outMsg.LengthBytes;
                        }
                        break;

                        case CommandType.GetSongDuration:
                        {
                            foreach (RadioChannel channel in RadioController.radioChannels)
                            {
                                if (channel.radioClients.Contains(client) && channel.requestingSongDuration)
                                {
                                    SongInfo info = new SongInfo(msg);
                                    if (info.levelId == channel.channelInfo.currentSong.levelId)
                                    {
                                        channel.songDurationResponses.TryAdd(client, info.songDuration);
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.LeaveChannel:
                        {
                            if (RadioController.radioStarted && client != null)
                            {
                                RadioController.ClientLeftChannel(client);
                            }
                        }; break;
                        }
                    };
                        break;



                    case NetIncomingMessageType.WarningMessage:
                        Logger.Instance.Warning(msg.ReadString());
                        break;

                    case NetIncomingMessageType.ErrorMessage:
                        Logger.Instance.Error(msg.ReadString());
                        break;

                    case NetIncomingMessageType.StatusChanged:
                    {
                        NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                        Client client = allClients.FirstOrDefault(x => x.playerConnection.RemoteEndPoint.Equals(msg.SenderEndPoint));

                        if (client != null)
                        {
                            if (status == NetConnectionStatus.Disconnected)
                            {
                                allClients.Remove(client);
                                ClientDisconnected(client);
                            }
                        }
                    }
                    break;

#if DEBUG
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.DebugMessage:
                        Logger.Instance.Log(msg.ReadString());
                        break;

                    default:
                        Logger.Instance.Log("Unhandled message type: " + msg.MessageType);
                        break;
#endif
                    }
                }catch (Exception ex)
                {
                    Logger.Instance.Log($"Exception on message received: {ex}");
                }
                ListenerServer.Recycle(msg);
            }
        }
示例#6
0
        private void MessageReceived(NetIncomingMessage msg)
        {
            if (msg == null)
            {
                InGameOnlineController.Instance.needToSendUpdates = false;

                PopAllViewControllers();
                InGameOnlineController.Instance.DestroyPlayerControllers();
                PreviewPlayer.CrossfadeToDefault();
                joined = false;

                _radioNavController.DisplayError("Lost connection to the ServerHub!");
                return;
            }

            CommandType commandType = (CommandType)msg.ReadByte();

            if (!joined)
            {
                if (commandType == CommandType.JoinChannel)
                {
                    switch (msg.ReadByte())
                    {
                    case 0:
                    {
                        Client.Instance.playerInfo.playerState = PlayerState.Room;
                        Client.Instance.RequestChannelInfo(channelId);
                        Client.Instance.SendPlayerInfo();
                        joined = true;
                        InGameOnlineController.Instance.needToSendUpdates = true;
                    }
                    break;

                    case 1:
                    {
                        _radioNavController.DisplayError("Unable to join channel!\nChannel not found");
                    }
                    break;

                    default:
                    {
                        _radioNavController.DisplayError("Unable to join channel!\nUnknown error");
                    }
                    break;
                    }
                }
            }
            else
            {
                try
                {
                    switch (commandType)
                    {
                    case CommandType.GetChannelInfo:
                    {
                        channelInfo      = new ChannelInfo(msg);
                        channelInfo.ip   = ip;
                        channelInfo.port = port;

                        UpdateUI(channelInfo.state);
                    }
                    break;

                    case CommandType.SetSelectedSong:
                    {
                        if (msg.LengthBytes > 16)
                        {
                            SongInfo song = new SongInfo(msg);
                            channelInfo.currentSong = song;
                            channelInfo.state       = ChannelState.NextSong;

                            UpdateUI(channelInfo.state);
                        }
                    }
                    break;

                    case CommandType.GetSongDuration:
                    {
                        SongInfo       requestedSong = new SongInfo(msg);
                        BeatmapLevelSO level         = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(channelInfo.currentSong.levelId)) as BeatmapLevelSO;

                        if (level != null)
                        {
                            SongLoader.Instance.LoadAudioClipForLevel((CustomLevel)level,
                                                                      (loadedLevel) =>
                                {
                                    Client.Instance.SendSongDuration(new SongInfo(loadedLevel));
                                });
                        }
                    }
                    break;

                    case CommandType.StartLevel:
                    {
                        if (Client.Instance.playerInfo.playerState == PlayerState.DownloadingSongs)
                        {
                            return;
                        }

                        if (nextSongSkipped)
                        {
                            nextSongSkipped   = false;
                            channelInfo.state = ChannelState.InGame;
                            UpdateUI(channelInfo.state);
                            return;
                        }

                        StartLevelInfo levelInfo = new StartLevelInfo(msg);

                        BeatmapCharacteristicSO characteristic = _beatmapCharacteristics.First(x => x.serializedName == levelInfo.characteristicName);

                        SongInfo       songInfo = new SongInfo(msg);
                        BeatmapLevelSO level    = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(songInfo.levelId)) as BeatmapLevelSO;

                        if (level == null)
                        {
                            Misc.Logger.Error("Unable to start level! Level is null! LevelID=" + songInfo.levelId);
                            return;
                        }

                        SongLoader.Instance.LoadAudioClipForLevel((CustomLevel)level,
                                                                  (levelLoaded) =>
                            {
                                try
                                {
                                    BS_Utils.Gameplay.Gamemode.NextLevelIsIsolated("Beat Saber Multiplayer");
                                }
                                catch
                                {
                                }

                                StartLevel(levelLoaded, characteristic, levelInfo.difficulty, levelInfo.modifiers);
                            });
                    }
                    break;

                    case CommandType.LeaveRoom:
                    {
                        LeaveChannel();
                    }
                    break;

                    case CommandType.UpdatePlayerInfo:
                    {
                        if (channelInfo != null)
                        {
                            currentTime = msg.ReadFloat();
                            totalTime   = msg.ReadFloat();

                            switch (channelInfo.state)
                            {
                            case ChannelState.InGame:
                                UpdateInGameScreen();
                                break;

                            case ChannelState.NextSong:
                                UpdateNextSongScreen();
                                break;

                            case ChannelState.Results:
                            {
                                UpdateResultsScreen();

                                int playersCount = msg.ReadInt32();

                                List <PlayerInfo> playerInfos = new List <PlayerInfo>();

                                try
                                {
                                    for (int j = 0; j < playersCount; j++)
                                    {
                                        playerInfos.Add(new PlayerInfo(msg));
                                    }
                                }
                                catch (Exception e)
                                {
#if DEBUG
                                    Misc.Logger.Exception($"Unable to parse PlayerInfo! Excpetion: {e}");
#endif
                                    return;
                                }

                                playerInfos = playerInfos.Where(x => x.playerScore > 0 && (x.playerState == PlayerState.Game || x.playerState == PlayerState.Room)).ToList();
                            }
                            break;
                            }
                        }
                    }
                    break;

                    case CommandType.Disconnect:
                    {
                        InGameOnlineController.Instance.needToSendUpdates = false;

                        if (msg.LengthBytes > 3)
                        {
                            string reason = msg.ReadString();

                            PopAllViewControllers();
                            InGameOnlineController.Instance.DestroyPlayerControllers();
                            PreviewPlayer.CrossfadeToDefault();
                            joined = false;

                            _radioNavController.DisplayError(reason);
                        }
                        else
                        {
                            _radioNavController.DisplayError("ServerHub refused connection!");
                        }
                    }
                    break;
                    }
                }
                catch (Exception e)
                {
                    Misc.Logger.Exception($"Unable to parse packet! Packet={commandType}, DataLength={msg.LengthBytes}\nException: {e}");
                }
            }
        }
 public SongWithOptions(SongInfo songInfo, StartLevelInfo optionsInfo)
 {
     song    = songInfo;
     options = optionsInfo;
 }