public static Score ReadReplayFromFile(string filename)
        {
            //Make sure the score manager is already initialized.
            if (scoreList == null)
            {
                InitializeScoreManager();
            }

            Stream stream  = File.Open(filename, FileMode.Open);
            Score  inScore = (Score)DynamicDeserializer.Deserialize(stream);

            stream.Close();

            if (BeatmapManager.GetBeatmapByChecksum(inScore.fileChecksum) == null)
            {
                GameBase.ShowMessage("You do not have the beatmap this replay was made for.");
                return(null);
            }

            InsertScore(inScore, false, true);


            return(inScore);

            /*  }
             * catch (Exception e)
             * {
             *  GameBase.ShowMessage("Error reading replay...");
             *  return null;
             * }*/
        }
        private void InitializeSpriteCollection()
        {
            if (SpriteCollection != null)
            {
                return;
            }

            SpriteCollection = new List <pSprite>();

            List <string> list = CollectionManager.FindCollection(Name);

            if (list == null)
            {
                return;
            }

            int total  = list.Count;
            int delete = 0;

            for (int i = total - 1; i >= 0; i--)
            {
                //todo: this shouldn't be done in a sprite/view class.
                Beatmap map = BeatmapManager.GetBeatmapByChecksum(list[i]);
                if (map == null)
                {
                    CollectionManager.RemoveFromCollection(Name, list[i]); //map doesn't exist
                    delete++;
                }
            }
            Count = total - delete;
        }
Exemple #3
0
 private void p_prev(object sender, EventArgs e)
 {
     GameBase.ShowMessageMassive("<< Prev", 1000);
     if (playHistory.Count > 0)
     {
         playFuture.Push(BeatmapManager.Current.BeatmapChecksum);
         BeatmapManager.Current = BeatmapManager.GetBeatmapByChecksum(playHistory.Pop());
     }
     ChooseRandomSong(false, false);
     manualPause = false;
 }
Exemple #4
0
        public static void HandleSongChange(bool resetStart)
        {
            lock (LockReplayScore)
            {
                if (CurrentlySpectating == null)
                {
                    return;
                }

                Beatmap b = BeatmapManager.GetBeatmapByChecksum(CurrentlySpectating.CurrentBeatmapChecksum);
                if (b != null)
                {
                    GameBase.ShowMessage("Host is playing:" + b.DisplayTitle, Color.Green, 1000);

                    BeatmapManager.Current   = b;
                    InputManager.ReplayMode  = true;
                    InputManager.ReplayToEnd = false;

                    InputManager.ReplayStreaming = true;

                    InputManager.ReplayScore = new Score();
                    InputManager.ReplayScore.AllowSubmission = false;
                    InputManager.ReplayScore.enabledMods     = CurrentlySpectating.CurrentMods;

                    if (resetStart)
                    {
                        InputManager.ReplayStreamingStart = 0;
                    }

                    ChatEngine.PendingHide = true;

                    GameBase.ChangeMode(Modes.Play, true);
                }
                else if (!string.IsNullOrEmpty(CurrentlySpectating.BeatmapName))
                {
                    GameBase.ShowMessage("You don't have the beatmap the host is playing (" +
                                         CurrentlySpectating.BeatmapName + ")");
                    BanchoClient.SendRequest(RequestType.Osu_CantSpectate, null);
                    iDontHaveThatBeatmap = true;

                    InputManager.ReplayMode = false;
                    if (GameBase.Mode == Modes.Play)
                    {
                        GameBase.ChangeMode(Modes.Menu, true);
                    }
                }
                else
                {
                    GameBase.ShowMessage("host isn't playing!");
                }
            }
            WaitingLoad = false;
        }
        internal static void InitializeScoreManager()
        {
            if (LocalScores != null)
            {
                return;
            }

            //ensure we have beatmaps available!
            if (BeatmapManager.Beatmaps == null)
            {
                BeatmapManager.ProcessBeatmaps();
            }

            LocalScores = new Dictionary <string, List <Score> >();

            databaseDeserialize();

            if (DatabaseVersion < 1024 && Directory.GetFiles(ReplayCachePath).Length > 0)
            {
                GameBase.MenuActive = true;
                Maintenance m = new Maintenance(MaintenanceType.RestoreLocalScoresFromReplays);
                m.ShowDialog(GameBase.Form);
                GameBase.MenuActive = false;
            }

            //Clean up missing beatmaps.
            foreach (KeyValuePair <string, List <Score> > p in LocalScores)
            {
                if (BeatmapManager.GetBeatmapByChecksum(p.Key) != null)
                {
                    continue;
                }

                foreach (Score s in p.Value)
                {
                    s.PurgeReplay();
                }
            }

            bool databasePresent = File.Exists(DATABASE_FILENAME);

            if (!databasePresent)
            {
                SaveToDisk(true);
            }
        }
Exemple #6
0
        private void p_prev(object sender, EventArgs e)
        {
            if (!ShowControls)
            {
                return;
            }

            AudioEngine.Click(null, @"click-short-confirm");

            NotificationManager.ShowMessageMassive("<< Prev", 1000);
            if (playHistory.Count > 0 && BeatmapManager.Current != null)
            {
                playFuture.Push(BeatmapManager.Current.BeatmapChecksum);
                BeatmapManager.Current = BeatmapManager.GetBeatmapByChecksum(playHistory.Pop());
            }
            ChooseRandomSong(false);
            manualPause = false;
        }
        private static void databaseDeserialize()
        {
            DatabaseHelper.Read(DATABASE_FILENAME, sr =>
            {
                DatabaseVersion = sr.ReadInt32();

                int count = sr.ReadInt32();

                for (int i = 0; i < count; i++)
                {
                    string checksum = sr.ReadString();
                    int scoreCount  = sr.ReadInt32();

                    List <Score> list = new List <Score>(scoreCount);

                    for (int j = 0; j < scoreCount; j++)
                    {
                        Score s = ScoreFactory.Create((PlayModes)sr.ReadByte(), null);
                        s.ReadHeaderFromStream(sr);
                        if (ModManager.CheckActive(s.EnabledMods, Mods.Target))
                        {
                            s = new ScoreTarget(s);
                        }
                        s.ReadFromStream(sr);
                        list.Add(s);
                    }

                    if (BeatmapManager.GetBeatmapByChecksum(checksum) != null)
                    {
                        LocalScores.Add(checksum, list);
                    }
                    else
                    {
                        foreach (Score s in list)
                        {
                            s.PurgeReplay();
                        }
                    }
                }
            });
        }
Exemple #8
0
        public void SetBeatmap(string checksum)
        {
            if (!GameBase.Tournament)
            {
                return;
            }
            if (GameBase.FadeState != FadeStates.Idle)
            {
                return;
            }
            if (GameBase.Mode == OsuModes.Play)
            {
                return;
            }

            GameBase.Scheduler.Add(() =>
            {
                Beatmap b = BeatmapManager.GetBeatmapByChecksum(checksum);

                if (b == null)
                {
                    BeatmapManager.Initialize(true);
                    b = BeatmapManager.GetBeatmapByChecksum(checksum);
                }

                if (BeatmapManager.Current == b)
                {
                    return;
                }

                if (b != null)
                {
                    BeatmapManager.Current = b;
                    AudioEngine.LoadAudioForPreview(BeatmapManager.Current, true, true, false);
                }
            });
        }
        internal static void InitializeScoreManager()
        {
            if (scoreList != null)
            {
                return;
            }

            scoreList = new List <Score>();

            if (File.Exists("scores.db"))
            {
                try
                {
                    Stream stream = File.Open("scores.db", FileMode.Open);
                    scoreList = (List <Score>)DynamicDeserializer.Deserialize(stream);
                    stream.Close();
                    scoreList.RemoveAll(s => BeatmapManager.GetBeatmapByChecksum(s.fileChecksum) == null);
                }
                catch (Exception)
                {
                    Console.WriteLine("corrupt scores database - recreating");
                    try
                    {
                        if (File.Exists("scores.db"))
                        {
                            File.Move("scores.db", "scores.bak");
                        }
                    }
                    catch { }
                }
            }
            else if (File.Exists("scores.dat"))
            {
                StreamReader s = new StreamReader("scores.dat");

                while (!s.EndOfStream)
                {
                    try
                    {
                        string[] line = s.ReadLine().Split(':');

                        Score score = new Score();

                        int i = 0;
                        score.pass         = true;
                        score.fileChecksum = line[i++];
                        score.playerName   = line[i++];
                        string scoreChecksum = line[i++];
                        score.count300     = Convert.ToUInt16(line[i++]);
                        score.count100     = Convert.ToUInt16(line[i++]);
                        score.count50      = Convert.ToUInt16(line[i++]);
                        score.countGeki    = Convert.ToUInt16(line[i++]);
                        score.countKatu    = Convert.ToUInt16(line[i++]);
                        score.countMiss    = Convert.ToUInt16(line[i++]);
                        score.totalScore   = Convert.ToInt32(line[i++]);
                        score.maxCombo     = Convert.ToUInt16(line[i++]);
                        score.perfect      = Convert.ToBoolean(line[i++]);
                        score.enabledMods  = (Mods)Convert.ToInt32(line[i++]);
                        score.rawReplayOld = line[i++];
                        score.ReadGraphData(line[i++]);
                        if (line.Length > i)
                        {
                            score.date = DateTime.FromBinary(long.Parse(line[i]));
                        }

                        if (score.date < DateTime.MinValue || score.date > DateTime.MaxValue)
                        {
                            score.date = DateTime.Now;
                        }

                        scoreList.Add(score);
                    }
                    catch (Exception)
                    {
                    }
                }
                s.Close();

                if (!File.Exists("scores.db"))
                {
                    if (ConfigManager.sFullscreen)
                    {
                        GameBase.ToggleFullscreen();
                    }
                    if (DialogResult.No == MessageBox.Show(
                            "osu! is about to perform some awesome maintenance on your local scores file.  Depending on how many scores and replays you have saved, this could take UP TO 5 MINUTES.  It will only happen ONCE, so please be patient!",
                            "stealin' ur cpu timez", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information))
                    {
                        MessageBox.Show("You think you have a choice?\nThink again... :>",
                                        "it won't take too long, don't worry", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    UpdateScores();
                    if (ConfigManager.sFullscreen)
                    {
                        GameBase.ToggleFullscreen();
                    }
                    if (File.Exists("scores.dat"))
                    {
                        if (!File.Exists("scores.dat.backup"))
                        {
                            File.Move("scores.dat", "scores.dat.backup");
                        }
                    }
                }
            }

            scoreList.Sort(delegate(Score s2, Score s1) { return(s1.totalScore.CompareTo(s2.totalScore)); });
        }
        internal float CalculateScore(bMatch match)
        {
            float matchScore;

            if (matchScoreCache.TryGetValue(match.matchId, out matchScore))
            {
                return(matchScore);
            }

            // Matches having players with ranks close to the user are better
            var matchPlayersScore = 0.0f;

            var playerScores = new List <float>();

            for (int i = 0; i < match.slotId.Length; i++)
            {
                var playerId = match.slotId[i];
                if (playerId <= 0)
                {
                    continue;
                }

                User player = BanchoClient.GetUserById(playerId);
                if (player == null)
                {
                    continue;
                }

                var playerRank = player.Rank != 0 ? player.Rank : 1000000;
                var userRank   = GameBase.User.Rank != 0 ? GameBase.User.Rank : 1000000;

                var rankDifference = userRank - playerRank;
                var rankDistance   = Math.Abs(rankDifference);
                var rankCap        = rankDifference > 0 ? userRank * 0.5f : userRank * 2f;

                var score = (float)((rankCap - rankDistance) / rankCap);
                if (player.IsFriend)
                {
                    score += 0.1f;
                }
                if (player.CountryCode == GameBase.User.CountryCode)
                {
                    score += 0.05f;
                }

                // Negative scores are there only to differentiate matches when all players are outside the user's range,
                // not to penalize matches that have these players.
                if (score < 0)
                {
                    score *= 0.01f;
                }

                playerScores.Add(score);
            }
            if (playerScores.Count > 0)
            {
                var playerIndex = 0;
                foreach (var score in playerScores.OrderByDescending(c => c))
                {
                    matchPlayersScore += score / (playerIndex + 1);
                    playerIndex++;
                }
            }

            // Matches with a selected map close to the user's recommended difficulty are better
            var matchMapScore = 0f;

            var matchBeatmap = BeatmapManager.GetBeatmapByChecksum(match.beatmapChecksum);

            if (matchBeatmap != null)
            {
                var recommendedDifficulty = GameBase.User.RecommendedDifficulty();

                var difficulty   = matchBeatmap.DifficultyTomStars(match.playMode, match.activeMods);
                var useEyupStars = difficulty < 0;
                if (useEyupStars)
                {
                    difficulty = matchBeatmap.DifficultyEyupStars;
                }
                double difference = Math.Abs(difficulty - recommendedDifficulty);

                matchMapScore = (float)Math.Max(0, 1 - difference);
                if (useEyupStars)
                {
                    matchMapScore = (0.3f + matchMapScore) * 0.5f;
                }
            }
            else
            {
                matchMapScore = 0.3f;
            }

            matchScore = matchPlayersScore + matchMapScore;
            matchScoreCache[match.matchId] = matchScore;
            return(matchScore);
        }
Exemple #11
0
        private bool CheckFilter(LobbyMatch match)
        {
            bool hasTextSearch = filterTextBox.Box.Text.Length > 0;

            if (ConfigManager.sLobbyPlayMode.Value >= 0 && match.matchInfo.playMode != (PlayModes)ConfigManager.sLobbyPlayMode.Value)
            {
                if (!hasTextSearch)
                {
                    return(false);
                }
            }

            if (!checkShowFullGames.Checked && match.matchInfo.slotFreeCount == 0)
            {
                if (!hasTextSearch)
                {
                    return(false);
                }
            }

            if (!checkInProgress.Checked && match.matchInfo.inProgress)
            {
                return(false);
            }

            if (checkFriendsOnly.Checked)
            {
                bool found = false;

                for (int i = 0; i < 16; i++)
                {
                    if (match.matchInfo.slotId[i] < 0)
                    {
                        continue;
                    }

                    User u = BanchoClient.GetUserById(match.matchInfo.slotId[i]);

                    if (u != null && u.IsFriend)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            if (!checkShowPasswordedGames.Checked && match.matchInfo.passwordRequired)
            {
                if (!hasTextSearch)
                {
                    return(false);
                }
            }

            if (ConfigManager.sLobbyShowExistingOnly && BeatmapManager.GetBeatmapByChecksum(match.matchInfo.beatmapChecksum) == null)
            {
                if (!hasTextSearch)
                {
                    return(false);
                }
            }

            if (hasTextSearch)
            {
                string filter = filterTextBox.Box.Text.ToLower();

                bool success = false;

                if (match.matchInfo.gameName.ToLower().Contains(filter))
                {
                    success = true;
                }
                else if (match.matchInfo.beatmapName.ToLower().Contains(filter))
                {
                    success = true;
                }
                else
                {
                    for (int i = 0; i < 8; i++)
                    {
                        if (match.matchInfo.slotId[i] < 0)
                        {
                            continue;
                        }

                        User u = BanchoClient.GetUserById(match.matchInfo.slotId[i]);

                        if (u != null && u.Name.ToLower().Contains(filter))
                        {
                            success = true;
                            break;
                        }
                    }
                }

                return(success);
            }

            return(true);
        }
Exemple #12
0
        public override void Update(GameTime gameTime)
        {
            if (!BanchoClient.Connected && GameBase.FadeState == FadeStates.Idle)
            {
                GameBase.ChangeMode(Modes.Menu);
                GameBase.ShowMessage("Multiplayer will not work unless Bancho is connected!");
            }

            if (Match == null)
            {
                if (GameBase.FadeState == FadeStates.Idle)
                {
                    GameBase.ChangeMode(Modes.Menu);
                }
                return;
            }

            if (GameBase.FadeState == FadeStates.FadeOut)
            {
                return;
            }

            if (!paused && AudioEngine.AudioState == AudioEngine.AudioStates.Stopped && GameBase.FadeState == FadeStates.Idle &&
                BeatmapManager.Current != null)
            {
                AudioEngine.LoadAndPreviewMp3(BeatmapManager.Current.AudioFilename, true);
                paused = false;
            }

            if (UpdatePending)
            {
                int uid = Match.findPlayerFromId(GameBase.User.Id);
                if (uid < 0)
                {
                    LeaveGame();
                    return;
                }

                detailsGameName.Box.Text = Match.gameName;

                if (Match.slotReadyCount == Match.slotUsedCount != allReady)
                {
                    allReady = Match.slotReadyCount == Match.slotUsedCount;
                    if (allReady)
                    {
                        AudioEngine.PlaySample("match-confirm");
                    }
                }

                if (allReady && IsHost && Match.slotReadyCount > 1)
                {
                    buttonStart.Text.Text = "Start Game!";
                }
                else if (Match.slotStatus[uid] == SlotStatus.NotReady)
                {
                    if (buttonStart.Text.Text != "Ready!")
                    {
                        buttonStart.Text.Text = "Ready!";
                        AudioEngine.PlaySample("match-notready");
                    }
                }
                else
                {
                    if (buttonStart.Text.Text != "Not Ready")
                    {
                        buttonStart.Text.Text = "Not Ready";
                        AudioEngine.PlaySample("match-ready");
                    }
                }

                for (int i = 0; i < 8; i++)
                {
                    if ((Match.slotStatus[i] & SlotStatus.CompHasPlayer) > 0)
                    {
                        User u = BanchoClient.GetUserById(Match.slotId[i]);
                        if (u == null)
                        {
                            continue;
                        }
                        slotText[i].Text     = u.Name;
                        slotTextInfo[i].Text = string.Format("Acc:{0:0.00}%\nRank:#{1}", u.Accuracy, u.Rank);
                        slotLock[i].ToolTip  = "";
                        slotLock[i].Texture  = content.Load <Texture2D>(IsHost ? "lobby-boot" : "lobby-unlock");
                        slotLock[i].ToolTip  = "Kick this player and lock the slot.";
                    }
                    else
                    {
                        slotTextInfo[i].Text = "";
                    }

                    switch (Match.slotStatus[i])
                    {
                    case SlotStatus.Open:
                        slotText[i].Text = "Open";

                        slotLock[i].Texture = content.Load <Texture2D>("lobby-unlock");
                        slotLock[i].ToolTip = "Lock this slot.";

                        slotStatus[i].StartColour     = Color.White;
                        slotBackground[i].StartColour = Color.White;
                        break;

                    case SlotStatus.Locked:
                        slotText[i].Text = "Locked";

                        slotLock[i].Texture = content.Load <Texture2D>("lobby-lock");
                        slotLock[i].ToolTip = "Unlock this slot.";

                        slotStatus[i].StartColour     = Color.Black;
                        slotBackground[i].StartColour = Color.Black;
                        break;

                    case SlotStatus.NotReady:
                        slotStatus[i].StartColour     = Color.White;
                        slotBackground[i].StartColour = Color.White;
                        break;

                    case SlotStatus.Ready:
                        slotStatus[i].StartColour     = Color.YellowGreen;
                        slotBackground[i].StartColour = Color.YellowGreen;
                        break;

                    case SlotStatus.NoMap:
                        slotStatus[i].StartColour     = Color.OrangeRed;
                        slotBackground[i].StartColour = Color.OrangeRed;
                        slotText[i].Text += " [no map]";
                        break;
                    }
                }

                UpdatePending = false;

                if (SongChangePending)
                {
                    Beatmap map = BeatmapManager.GetBeatmapByChecksum(Match.beatmapChecksum);
                    if (map != null)
                    {
                        BeatmapManager.ProcessHeaders(map);
                    }

                    hasSong = map != null && map.BeatmapChecksum == Match.beatmapChecksum;

                    if (treeItem != null)
                    {
                        treeItem.SpriteCollection.ForEach(s =>
                        {
                            s.FadeOut(400);
                            s.AlwaysDraw = false;
                        });
                    }

                    if (!hasSong)
                    {
                        buttonStart.Hide();
                        BeatmapManager.Current = BeatmapManager.GetBeatmapById(Match.beatmapId);
                        AudioEngine.Stop();
                        Beatmap bm = new Beatmap();
                        bm.SortTitle      = Match.beatmapName;
                        bm.BeatmapPresent = true;
                        bm.Title          = "h";

                        bm.Creator = BeatmapManager.Current != null
                                         ? "Click here to update this map to the latest"
                                         : Match.beatmapId > 0
                                               ? "Click to download this map"
                                               : "You don't have this map";

                        treeItem = new BeatmapTreeItem(bm, 0, null);
                        treeItem.SpriteCollection[0].StartColour = Color.OrangeRed;
                        if (Match.beatmapId > 0)
                        {
                            treeItem.SpriteCollection[0].IsClickable = true;
                            treeItem.SpriteCollection[0].OnClick    += DownloadMap;
                            treeItem.SpriteCollection[0].HoverEffect =
                                new Transformation(treeItem.SpriteCollection[0].StartColour, Color.YellowGreen, 0, 100);
                        }
                        else
                        {
                            treeItem.SpriteCollection[0].IsClickable = false;
                        }

                        BanchoClient.SendRequest(RequestType.Osu_MatchNoBeatmap, null);

                        ((pText)treeItem.SpriteCollection[2]).TextBold = true;
                    }
                    else
                    {
                        if (Match.slotStatus[uid] == SlotStatus.NoMap)
                        {
                            BanchoClient.SendRequest(RequestType.Osu_MatchHasBeatmap, null);
                        }
                        buttonStart.Show();
                        BeatmapManager.Current = map;
                        treeItem = new BeatmapTreeItem(BeatmapManager.Current, 0, null);
                        treeItem.SpriteCollection[1].Text = BeatmapManager.Current.DisplayTitle;
                        if (!IsHost)
                        {
                            treeItem.SpriteCollection[0].IsClickable = false;
                        }
                        treeItem.SpriteCollection[0].OnClick    += OnSelectBeatmap;
                        treeItem.SpriteCollection[0].HoverEffect =
                            new Transformation(treeItem.SpriteCollection[0].StartColour, Color.Orange, 0, 100);
                    }

                    if (map != null)
                    {
                        AudioEngine.LoadAndPreviewMp3(map.AudioFilename, true);
                        paused = false;
                    }

                    treeItem.SpriteCollection.ForEach(
                        delegate(pSprite s)
                    {
                        s.CurrentPosition = new Vector2(600, 165);
                        s.MoveTo(new Vector2(300, 165), 500, EasingTypes.In);
                    });
                    spriteManager.Add(treeItem.SpriteCollection);

                    //detailsBeatmap.Text = "Beatmap: " + Match.beatmapName;
                    SongChangePending = false;
                }

                if (HostChangePending)
                {
                    SetHost();
                }
            }

            if (ModChangePending)
            {
                ModChangePending     = false;
                ModManager.ModStatus = Match.activeMods | (ModManager.ModStatus & Mods.NoVideo);

                modSprites.ForEach(
                    delegate(pSprite s)
                {
                    s.FadeOut(400);
                    s.MoveToRelative(new Vector2(0, 20), 400, EasingTypes.Out);
                    s.AlwaysDraw = false;
                });
                modSprites.Clear();

                int time = 0;

                float dep = 0;
                int   x   = 330;
                foreach (Mods m in Enum.GetValues(typeof(Mods)))
                {
                    if (ModManager.CheckActive(ModManager.ModStatus, m))
                    {
                        Transformation t2 =
                            new Transformation(TransformationType.Scale, 2, 1, GameBase.Time + time,
                                               GameBase.Time + time + 400);
                        Transformation t3 =
                            new Transformation(TransformationType.Fade, 0, 1, GameBase.Time + time,
                                               GameBase.Time + time + 400);
                        t2.Easing = EasingTypes.In;
                        t3.Easing = EasingTypes.In;

                        pSprite p =
                            new pSprite(SkinManager.Load("selection-mod-" + m.ToString().ToLower()),
                                        FieldTypes.Window,
                                        OriginTypes.Centre,
                                        ClockTypes.Game,
                                        new Vector2(x, 250), 0.92F + dep, true,
                                        Color.TransparentWhite);
                        p.Transformations.Add(t2);
                        p.Transformations.Add(t3);
                        spriteManager.Add(p);
                        modSprites.Add(p);

                        time += 200;
                        dep  += 0.00001f;
                        x    += 20;
                    }
                }

                //detailsMods.Text = "Mods: " + ModManager.Format(ModManager.ModStatus, true);
            }

            base.Update(gameTime);
        }
Exemple #13
0
        public static void HandleSongChange(bool resetStart, bool useScoreV2)
        {
            lock (LockReplayScore)
            {
                if (CurrentlySpectating == null)
                {
                    return;
                }

                Beatmap b = BeatmapManager.GetBeatmapByChecksum(CurrentlySpectating.CurrentBeatmapChecksum);

                if (b != null)
                {
                    NotificationManager.ShowMessage("Host is playing:" + b.DisplayTitle, Color.Green, 1000);

                    BeatmapManager.Current   = b;
                    InputManager.ReplayMode  = true;
                    InputManager.ReplayToEnd = false;

                    InputManager.ReplayStreaming = true;

                    InputManager.ReplayScore = ScoreFactory.Create(CurrentlySpectating.PlayMode, null, BeatmapManager.Current, useScoreV2);
                    InputManager.ReplayScore.InvalidateSubmission();
                    InputManager.ReplayScore.EnabledMods = CurrentlySpectating.CurrentMods;

                    if (resetStart)
                    {
                        InputManager.ReplayStartTime = 0;
                    }

                    if (NewUserAndSong)
                    {
                        GameBase.Scheduler.Add(delegate { if (ChatEngine.IsVisible)
                                                          {
                                                              ChatEngine.Visibility = ChatVisibility.ChatOnly;
                                                          }
                                               });
                        NewUserAndSong = false;
                    }

                    GameBase.ChangeMode(OsuModes.Play, true);
                }
                else if (!string.IsNullOrEmpty(CurrentlySpectating.BeatmapName))
                {
                    if (CurrentlySpectating.BeatmapId > 0 && (BanchoClient.Permission & Permissions.Supporter) > 0)
                    {
                        if (OsuDirect.ActiveDownloads.Find(d => d.beatmap != null && d.beatmap.beatmapId == CurrentlySpectating.BeatmapId) == null &&
                            (OsuDirect.RespondingBeatmap == null || OsuDirect.RespondingBeatmap.beatmapId != CurrentlySpectating.BeatmapId))
                        {
                            OsuDirect.HandlePickup(LinkId.Beatmap, CurrentlySpectating.BeatmapId, RestartSpectating);
                        }
                    }
                    else
                    {
                        string message = string.Format("You don't have the beatmap the host is playing ({0}).", CurrentlySpectating.BeatmapName);
                        NotificationManager.ShowMessage(message);
                    }

                    BanchoClient.SendRequest(RequestType.Osu_CantSpectate, null);
                    iDontHaveThatBeatmap = true;

                    InputManager.ReplayMode = false;
                    if (GameBase.Mode == OsuModes.Play)
                    {
                        GameBase.ChangeMode(OsuModes.Menu, true);
                    }
                }
            }
        }
        public static Score ReadReplayFromFile(string filename, bool handlePickup)
        {
            //Make sure the score manager is already initialized.
            InitializeScoreManager();

            Score inScore = null;

            bool success = false;

            try
            {
                using (Stream stream = File.Open(filename, FileMode.Open))
                {
                    SerializationReader sr = new SerializationReader(stream);
                    inScore = ScoreFactory.Create((PlayModes)sr.ReadByte(), null);
                    inScore.ReadHeaderFromStream(sr);
                    if (ModManager.CheckActive(inScore.EnabledMods, Mods.Target))
                    {
                        inScore = new ScoreTarget(inScore);
                    }
                    inScore.ReadFromStream(sr);
                    if (inScore.Date < DateTime.UtcNow + new TimeSpan(365 * 5, 0, 0, 0))
                    {
                        success = true;
                    }
                }
            }
            catch { }


            if (!success)
            {
                try
                {
                    using (Stream stream = File.Open(filename, FileMode.Open))
                        inScore = (Score)DynamicDeserializer.Deserialize(stream);
                }
                catch
                {
                    NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_ReplayCorrupt));
                    return(null);
                }
            }

            if (inScore == null)
            {
                NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_ReplayCorrupt));
                return(null);
            }

            if (inScore.Date.Year > 2050 || inScore.Date == DateTime.MinValue)
            {
                string[] split = filename.Split('-');
                if (split.Length > 1)
                {
                    long outfiletime = 0;
                    if (long.TryParse(split[1].Replace(@".osr", string.Empty), out outfiletime))
                    {
                        inScore.Date = DateTime.FromFileTimeUtc(outfiletime);
                    }
                }
            }

            if (inScore.Date.Year > 2050)
            {
                //this score is TOTALLY f****d.
                File.Delete(filename);
                NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_ReplayCorrupt));
                return(null);
            }

            if (BeatmapManager.GetBeatmapByChecksum(inScore.FileChecksum) == null)
            {
                //attempt pickup.
                if (handlePickup)
                {
                    OsuDirect.HandlePickup(inScore.FileChecksum, null,
                                           delegate
                    {
                        NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_DontHaveBeatmap));
                    });
                }
                return(null);
            }

            InsertScore(inScore, false);

            return(inScore);
        }
Exemple #15
0
        public bool DrawAt(Vector2 pos)
        {
            bool firstPopulation = SpriteCollection == null;

            if (firstPopulation)
            {
                position = pos;

                SpriteCollection = new List <pSprite>();

                bg = new pSprite(GameBase.WhitePixel, Fields.TopLeft,
                                 Origins.TopLeft, Clocks.Game, pos, 0.89F, true,
                                 new Color(255, 255, 255, 25));
                bg.VectorScale = new Vector2(GameBase.WindowManager.WidthScaled - 15, 48);
                bg.Scale       = 1.6f;
                bg.OnHover    += delegate
                {
                    bg.FadeColour(ColourHelper.ChangeAlpha(bg.InitialColour, 50), 100);
                    AudioEngine.Click(null, @"click-short");
                };
                bg.OnHoverLost += delegate { CheckUnhover(); };
                bg.ClickRequiresConfirmation = true;
                bg.OnClick += joinMatch;

                infoLeft1          = new pText(string.Empty, 12, pos + new Vector2(20, 0), 0.9f, true, Color.White);
                infoLeft1.TextBold = true;
                SpriteCollection.Add(infoLeft1);

                infoLeft2 = new pText(string.Empty, 11, pos + new Vector2(56, 13), 0.9f, true, Color.White);
                SpriteCollection.Add(infoLeft2);

                infoRight1          = new pText(string.Empty, 12, pos + new Vector2(240, 0), 0.9f, true, Color.White);
                infoRight1.TextBold = true;
                SpriteCollection.Add(infoRight1);
                infoRight2 = new pText(string.Empty, 11, pos + new Vector2(240, 11), 0.9f, true, Color.White);
                SpriteCollection.Add(infoRight2);

                password = new pSprite(TextureManager.Load(@"lobby-lock", SkinSource.Osu), pos + new Vector2(3, 5), 0.895f, true, Color.TransparentWhite);
                SpriteCollection.Add(password);

                gametype = new pSprite(null, pos + new Vector2(0, 3), 0.894f, true, Color.White);
                SpriteCollection.Add(gametype);

                Vector2 avPos = pos + new Vector2(210, 24);

                hostAvatar                  = new pSpriteDynamic(null, null, 200, avPos, 0.920001f);
                hostBackground              = new pSprite(TextureManager.Load(@"lobby-avatar", SkinSource.Osu), Origins.Centre, avPos, 0.92f, true, playerColour);
                hostBackground.Alpha        = 1;
                hostBackground.Scale        = 1f;
                hostBackground.HandleInput  = true;
                hostBackground.OnHoverLost += delegate { CheckUnhover(); };
                hostBackground.ClickRequiresConfirmation = true;
                hostBackground.OnClick += joinMatch;


                SpriteCollection.Add(hostAvatar);
                SpriteCollection.Add(hostBackground);

                slot_size = !GameBase.WindowManager.IsWidescreen && matchInfo.slotUsedAboveEight ? 0.75f : 1;

                for (int i = 0; i < bMatch.MAX_PLAYERS - 1; i++)
                {
                    avPos = pos + new Vector2(i * 33f * slot_size + 251.4f, 24f + 10.4f);

                    avatars.Add(new pSpriteDynamic(null, null, 200, avPos, 0.920001f));
                    pSprite abg = new pSprite(TextureManager.Load(@"lobby-avatar", SkinSource.Osu), Origins.Centre, avPos, 0.92f, true, Color.TransparentWhite);
                    abg.Alpha        = 0;
                    abg.Scale        = 0.58f * slot_size;
                    abg.HandleInput  = true;
                    abg.OnHoverLost += delegate { CheckUnhover(); };
                    //Because these also get hovered, if the mouse moves from the avatar to another point outside the LobbyMatch the bg will not return states unless this triggers.

                    abg.OnClick += joinMatch;
                    abg.ClickRequiresConfirmation = true;
                    avatarBackgrounds.Add(abg);
                }

                SpriteCollection.AddRange(avatarBackgrounds);
                foreach (pSpriteDynamic p in avatars)
                {
                    SpriteCollection.Add(p);
                }

                SpriteCollection.Add(bg);
            }
            else
            {
                foreach (pSprite p in SpriteCollection)
                {
                    Vector2 destination = pos + (p.InitialPosition - position);
                    p.MoveTo(destination, 500, EasingTypes.Out);
                }
            }

            password.Bypass = !matchInfo.passwordRequired;

            float avgLevel     = 0;
            float avgRank      = 0;
            float minLevel     = 1000;
            float maxLevel     = 0;
            float minRank      = 1000000;
            float maxRank      = 0;
            bool  hasUnranked  = false;
            int   totalPlayers = 0;

            int k = -1;

            for (int j = 0; j < bMatch.MAX_PLAYERS; j++)
            {
                int s = matchInfo.slotId[j];

                pSpriteDynamic thisAvatar;
                pSprite        thisAvatarBackground;

                bool isHost = s == matchInfo.hostId;

                if (!isHost)
                {
                    //Add non-host players to the player list.

                    k++;
                    if (k >= avatars.Count)
                    {
                        break;
                    }
                    thisAvatar           = avatars[k];
                    thisAvatarBackground = avatarBackgrounds[k];

                    if (matchInfo.slotStatus[j] != SlotStatus.Locked)
                    {
                        thisAvatarBackground.Bypass = false;
                        if (matchInfo.slotStatus[j] != SlotStatus.Open)
                        {
                            thisAvatarBackground.HandleInput = true;
                            thisAvatarBackground.FadeColour(playerColour, 200);
                            thisAvatarBackground.FadeTo(1, 200, EasingTypes.None);
                        }
                        else
                        {
                            thisAvatarBackground.HandleInput = false;
                            thisAvatarBackground.FadeColour(openColour, 200);
                            thisAvatarBackground.FadeTo(100 / 255f, 200, EasingTypes.None);
                        }
                    }
                    else
                    {
                        thisAvatarBackground.HandleInput = false;
                        thisAvatarBackground.FadeColour(closedColour, 200);
                        thisAvatarBackground.FadeTo(100 / 255f, 200, EasingTypes.None);
                    }
                }
                else
                {
                    thisAvatar           = hostAvatar;
                    thisAvatarBackground = hostBackground;
                }

                if (s >= 0)
                {
                    User u = BanchoClient.GetUserById(s);

                    if (u == null)
                    {
                        continue;
                    }

                    avgLevel += u.Level;
                    avgRank  += u.Rank;

                    if (u.Level < minLevel)
                    {
                        minLevel = u.Level;
                    }
                    if (u.Level > maxLevel)
                    {
                        maxLevel = u.Level;
                    }

                    if (u.Rank < minRank)
                    {
                        if (u.Rank == 0)
                        {
                            hasUnranked = true;
                        }
                        else
                        {
                            minRank = u.Rank;
                        }
                    }
                    if (u.Rank > maxRank)
                    {
                        maxRank = u.Rank;
                    }

                    totalPlayers++;

                    if (string.IsNullOrEmpty(thisAvatarBackground.ToolTip) || thisAvatarBackground.ToolTip.StartsWith(User.LOADING_STRING))
                    {
                        thisAvatarBackground.ToolTip = string.Format(u.Name + " (#" + u.Rank + ")\n" + u.Location);
                    }

                    if (thisAvatar.Tag != u)
                    {
                        thisAvatar.Tag = u;

                        if (u.LoadAvatarInto(thisAvatar, (thisAvatar == hostAvatar ? 63f : 36f) * slot_size))
                        {
                            thisAvatar.OnTextureLoaded += delegate
                            {
                                thisAvatar.Transformations.Add(new Transformation(TransformationType.Scale, 0, thisAvatar.Scale, GameBase.Time, GameBase.Time + 200, EasingTypes.Out));
                                if (!Filtered)
                                {
                                    thisAvatar.FadeIn(500);
                                }
                            };
                        }
                    }
                }
                else
                {
                    if (thisAvatar.Tag != null)
                    {
                        thisAvatarBackground.ToolTip = null;
                        thisAvatar.Tag     = null;
                        thisAvatar.Texture = null;
                        thisAvatar.FadeOut(500);
                    }
                }
            }

            avgLevel /= totalPlayers;
            avgRank  /= totalPlayers;

            switch (matchInfo.playMode)
            {
            case PlayModes.Osu:
                gametype.Texture = TextureManager.Load(@"mode-osu-small", SkinSource.Osu);
                break;

            case PlayModes.CatchTheBeat:
                gametype.Texture = TextureManager.Load(@"mode-fruits-small", SkinSource.Osu);
                break;

            case PlayModes.Taiko:
                gametype.Texture = TextureManager.Load(@"mode-taiko-small", SkinSource.Osu);
                break;

            case PlayModes.OsuMania:
                gametype.Texture = TextureManager.Load(@"mode-mania-small", SkinSource.Osu);
                break;
            }


            bool foundBeatmapBefore = foundBeatmap;

            if (foundChecksum != matchInfo.beatmapChecksum)
            {
                foundBeatmap  = !string.IsNullOrEmpty(matchInfo.beatmapChecksum) && BeatmapManager.GetBeatmapByChecksum(matchInfo.beatmapChecksum) != null;
                foundChecksum = matchInfo.beatmapChecksum;
            }

            bg.HandleInput = true;
            if (foundBeatmapBefore != foundBeatmap)
            {
                bg.InitialColour = foundBeatmap ? new Color(185, 64, 255, 25) : new Color(202, 202, 202, 25);
            }

            infoLeft1.InitialColour  = matchInfo.inProgress ? Color.Gray : Color.White;
            infoRight1.InitialColour = matchInfo.inProgress ? Color.Gray : Color.White;

            infoLeft1.Text = string.Format(
                @"{0} ({3})
{1} / {2} ",
                GeneralHelper.FormatEnum(matchInfo.playMode.ToString()),
                matchInfo.slotUsedCount,
                matchInfo.slotOpenCount,
                GeneralHelper.FormatEnum(matchInfo.matchTeamType.ToString()));

            /*infoLeft2.Text =
             *  string.Format(minLevel != maxLevel ? @"lv{0:0}-{1:0}" : @"lv{0:0}", minLevel, maxLevel);*/

            if (hasUnranked)
            {
                //maxRank > 0 ensures that at least one non-null rank has been processed.
                infoLeft2.Text = @"rank: " + string.Format(maxRank > 0 ? @"{0:#,#} - ?" : @" ?", minRank, maxRank);
            }
            else
            {
                infoLeft2.Text = @"rank: " + string.Format(minRank != maxRank ? @"{0:#,#} - {1:#,#}" : @"{0:#,#}", minRank, maxRank);
            }

            infoRight1.Text = matchInfo.gameName + @" " + (matchInfo.inProgress ? LocalisationManager.GetString(OsuString.LobbyMatch_InProgress) : string.Empty);
            infoRight2.Text =
                string.IsNullOrEmpty(matchInfo.beatmapChecksum) ? LocalisationManager.GetString(OsuString.LobbyMatch_ChangingBeatmap) :
                string.Format(@"{0}{1}", ModManager.FormatShort(matchInfo.activeMods, true, true), matchInfo.beatmapName);//bofore mapname is better
            infoRight2.InitialColour = new Color(255, 215, 109);

            return(firstPopulation);
        }
Exemple #16
0
        private void updateBeatmap()
        {
            if (BeatmapImport.IsProcessing)
            {
                return;
            }

            if (Lobby.SpectatingMatch == null)
            {
                return;
            }

            if ((Lobby.SpectatingMatch.activeMods & Mods.DoubleTime) > 0)
            {
                AudioEngine.CurrentPlaybackRate = 150;
            }
            else if ((Lobby.SpectatingMatch.activeMods & Mods.HalfTime) > 0)
            {
                AudioEngine.CurrentPlaybackRate = 75;
            }
            else
            {
                AudioEngine.CurrentPlaybackRate = 100;
            }

            if (BeatmapManager.Current?.BeatmapChecksum == Lobby.SpectatingMatch.beatmapChecksum)
            {
                currentSong.Text = BeatmapManager.Current?.DisplayTitleFullAuto ?? string.Empty;
            }
            else
            {
                currentSong.Text = Lobby.SpectatingMatch?.beatmapName ?? string.Empty;
            }
            playingIcon.Alpha = string.IsNullOrEmpty(currentSong.Text) ? 0 : 1;

            if (Lobby.SpectatingMatch.beatmapChecksum == BeatmapManager.Current?.BeatmapChecksum)
            {
                return;
            }

            if (string.IsNullOrEmpty(Lobby.SpectatingMatch.beatmapChecksum))
            {
                pickingUp = false;
            }
            else
            {
                var b = BeatmapManager.GetBeatmapByChecksum(Lobby.SpectatingMatch.beatmapChecksum);

                if (b == null)
                {
                    if (pickingUp)
                    {
                        return;
                    }
                    pickingUp = true;

                    OsuDirect.HandlePickup(Lobby.SpectatingMatch.beatmapChecksum, (o, e) =>
                    {
                        BeatmapImport.Start();
                        pickingUp = false;
                    }, null);
                }
                else
                {
                    BeatmapManager.Load(b);
                    clients.Reset();
                }
            }
        }
Exemple #17
0
        public override void Initialize()
        {
            if (Player.currentScore == null && InputManager.ReplayScore == null)
            {
                GameBase.ChangeModeInstant(OsuModes.Menu, true);
                return;
            }

            spriteManagerWideBelow = new SpriteManager(true);
            InitializeLocalScore();

            if (score == null)
            {
                GameBase.ChangeModeInstant(OsuModes.Menu, true);
                return;
            }

            if (BeatmapManager.Current == null || (!string.IsNullOrEmpty(score.FileChecksum) && BeatmapManager.Current.BeatmapChecksum != score.FileChecksum))
            {
                Beatmap lookup = BeatmapManager.GetBeatmapByChecksum(score.FileChecksum);
                if (lookup != null)
                {
                    BeatmapManager.Current = lookup;
                }
            }

            if (BeatmapManager.Current == null)
            {
                GameBase.ChangeModeInstant(OsuModes.Menu, true);
                return;
            }

            scrollableArea             = new pScrollableArea(new Rectangle(0, 0, GameBase.WindowManager.WidthScaled, GameBase.WindowManager.HeightScaled), new Vector2(GameBase.WindowManager.WidthScaled, GameBase.WindowManager.HeightScaled * (rankingDialog != null ? 1.875f : 1) - 60), true, 60);
            spriteManagerWideScrolling = scrollableArea.ContentSpriteManager;
            //if (rankingDialog != null) rankingDialog.spriteManager = spriteManagerWide;

            spriteManagerWideAbove = new SpriteManager(true);

            BackButton back = new BackButton(delegate { Exit(); });

            spriteManagerWideAbove.Add(back.SpriteCollection);

            bool Spectating = InputManager.ReplayStreaming;

            lock (StreamingManager.LockReplayScore)
            {
                InputManager.ReplayMode      = false;
                InputManager.ReplayStreaming = false;
                InputManager.ReplayStartTime = 0;
            }

            startTime = GameBase.Time + 300;

            KeyboardHandler.OnKeyPressed += GameBase_OnKeyPressed;
            InputManager.Bind(InputEventType.OnClick, onClick);

            backgroundOverlay =
                new pSprite(TextureManager.Load(@"ranking-background-overlay", SkinSource.Osu), Fields.TopRight,
                            Origins.Centre,
                            Clocks.Game, new Vector2(180, SkinManager.UseNewLayout ? 200 : 170), 0.05f, true, Color.White);
            backgroundOverlay.Additive = true;
            backgroundOverlay.Transformations.Add(new Transformation(TransformationType.Rotation, 0, (float)(2 * Math.PI), GameBase.Time, GameBase.Time + 20000));
            backgroundOverlay.Transformations[0].Loop = true;
            spriteManagerWideBelow.Add(backgroundOverlay);

            pSprite p =
                new pSprite(TextureManager.Load(@"ranking-title"), Fields.TopRight, Origins.TopRight,
                            Clocks.Game, new Vector2(20, 0), 0.991F, true, Color.White);

            p.ViewOffsetImmune = SkinManager.UseNewLayout;
            spriteManagerWideScrolling.Add(p);

            InitializeRankingPanel();

            stringTotalScore = String.Format(@"{0:00000000}", score.TotalScore);

            pSprite detailsBack =
                new pSprite(GameBase.WhitePixel, Fields.TopLeft,
                            Origins.TopLeft,
                            Clocks.Game,
                            new Vector2(0, 0), 0.99F, true, Color.Black);

            detailsBack.Alpha            = 0.8f;
            detailsBack.VectorScale      = new Vector2(GameBase.WindowManager.WidthScaled * 1.6f, 60 * 1.6f);
            detailsBack.ViewOffsetImmune = true;
            spriteManagerWideScrolling.Add(detailsBack);

            InitializeSpecifics();

            LoadScore(score);

            base.Initialize();

            if (!ReplayMode)
            {
                PopupRecord();
            }

            if (ReplayMode && !Spectating)
            {
                Progress(false);
            }
            else if (score.SectionResults.FindAll(t => t).Count > score.SectionResults.FindAll(t => !t).Count)
            {
                ApplauseChannel = AudioEngine.PlaySample(@"applause", 100, SkinSource.All);
            }
        }