Merge branch 'master' into disallow-skipping

This commit is contained in:
Bartłomiej Dach 2020-12-24 12:35:22 +01:00 committed by GitHub
commit d5fc517fab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 85 additions and 34 deletions

View File

@ -1,7 +1,9 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Screens.Multi.Components; using osu.Game.Screens.Multi.Components;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.RealtimeMultiplayer namespace osu.Game.Tests.Visual.RealtimeMultiplayer
{ {
@ -15,6 +17,28 @@ namespace osu.Game.Tests.Visual.RealtimeMultiplayer
AddUntilStep("wait for loaded", () => multi.IsLoaded); AddUntilStep("wait for loaded", () => multi.IsLoaded);
} }
[Test]
public void TestOneUserJoinedMultipleTimes()
{
var user = new User { Id = 33 };
AddRepeatStep("add user multiple times", () => Client.AddUser(user), 3);
AddAssert("room has 2 users", () => Client.Room?.Users.Count == 2);
}
[Test]
public void TestOneUserLeftMultipleTimes()
{
var user = new User { Id = 44 };
AddStep("add user", () => Client.AddUser(user));
AddAssert("room has 2 users", () => Client.Room?.Users.Count == 2);
AddRepeatStep("remove user multiple times", () => Client.RemoveUser(user), 3);
AddAssert("room has 1 user", () => Client.Room?.Users.Count == 1);
}
private class TestRealtimeMultiplayer : Screens.Multi.RealtimeMultiplayer.RealtimeMultiplayer private class TestRealtimeMultiplayer : Screens.Multi.RealtimeMultiplayer.RealtimeMultiplayer
{ {
protected override RoomManager CreateRoomManager() => new TestRealtimeRoomManager(); protected override RoomManager CreateRoomManager() => new TestRealtimeRoomManager();

View File

@ -55,8 +55,6 @@ namespace osu.Game.Tests.Visual.RealtimeMultiplayer
} }
} }
}; };
Client.AddUser(API.LocalUser.Value);
}); });
[Test] [Test]

View File

@ -226,6 +226,10 @@ namespace osu.Game.Online.RealtimeMultiplayer
if (Room == null) if (Room == null)
return; return;
// for sanity, ensure that there can be no duplicate users in the room user list.
if (Room.Users.Any(existing => existing.UserID == user.UserID))
return;
Room.Users.Add(user); Room.Users.Add(user);
RoomChanged?.Invoke(); RoomChanged?.Invoke();

View File

@ -14,6 +14,11 @@ namespace osu.Game.Online.Spectator
[Serializable] [Serializable]
public class FrameHeader public class FrameHeader
{ {
/// <summary>
/// The current accuracy of the score.
/// </summary>
public double Accuracy { get; set; }
/// <summary> /// <summary>
/// The current combo of the score. /// The current combo of the score.
/// </summary> /// </summary>
@ -42,16 +47,18 @@ namespace osu.Game.Online.Spectator
{ {
Combo = score.Combo; Combo = score.Combo;
MaxCombo = score.MaxCombo; MaxCombo = score.MaxCombo;
Accuracy = score.Accuracy;
// copy for safety // copy for safety
Statistics = new Dictionary<HitResult, int>(score.Statistics); Statistics = new Dictionary<HitResult, int>(score.Statistics);
} }
[JsonConstructor] [JsonConstructor]
public FrameHeader(int combo, int maxCombo, Dictionary<HitResult, int> statistics, DateTimeOffset receivedTime) public FrameHeader(int combo, int maxCombo, double accuracy, Dictionary<HitResult, int> statistics, DateTimeOffset receivedTime)
{ {
Combo = combo; Combo = combo;
MaxCombo = maxCombo; MaxCombo = maxCombo;
Accuracy = accuracy;
Statistics = statistics; Statistics = statistics;
ReceivedTime = receivedTime; ReceivedTime = receivedTime;
} }

View File

@ -193,7 +193,7 @@ namespace osu.Game.Rulesets.Scoring
private void updateScore() private void updateScore()
{ {
if (rollingMaxBaseScore != 0) if (rollingMaxBaseScore != 0)
Accuracy.Value = baseScore / rollingMaxBaseScore; Accuracy.Value = calculateAccuracyRatio(baseScore, true);
TotalScore.Value = getScore(Mode.Value); TotalScore.Value = getScore(Mode.Value);
} }
@ -233,13 +233,13 @@ namespace osu.Game.Rulesets.Scoring
} }
/// <summary> /// <summary>
/// Given a minimal set of inputs, return the computed score and accuracy for the tracked beatmap / mods combination, at the current point in time. /// Given a minimal set of inputs, return the computed score for the tracked beatmap / mods combination, at the current point in time.
/// </summary> /// </summary>
/// <param name="mode">The <see cref="ScoringMode"/> to compute the total score in.</param> /// <param name="mode">The <see cref="ScoringMode"/> to compute the total score in.</param>
/// <param name="maxCombo">The maximum combo achievable in the beatmap.</param> /// <param name="maxCombo">The maximum combo achievable in the beatmap.</param>
/// <param name="statistics">Statistics to be used for calculating accuracy, bonus score, etc.</param> /// <param name="statistics">Statistics to be used for calculating accuracy, bonus score, etc.</param>
/// <returns>The computed score and accuracy for provided inputs.</returns> /// <returns>The computed score for provided inputs.</returns>
public (double score, double accuracy) GetScoreAndAccuracy(ScoringMode mode, int maxCombo, Dictionary<HitResult, int> statistics) public double GetImmediateScore(ScoringMode mode, int maxCombo, Dictionary<HitResult, int> statistics)
{ {
// calculate base score from statistics pairs // calculate base score from statistics pairs
int computedBaseScore = 0; int computedBaseScore = 0;
@ -252,12 +252,7 @@ namespace osu.Game.Rulesets.Scoring
computedBaseScore += Judgement.ToNumericResult(pair.Key) * pair.Value; computedBaseScore += Judgement.ToNumericResult(pair.Key) * pair.Value;
} }
double pointInTimeAccuracy = calculateAccuracyRatio(computedBaseScore, true); return GetScore(mode, maxAchievableCombo, calculateAccuracyRatio(computedBaseScore), calculateComboRatio(maxCombo), scoreResultCounts);
double comboRatio = calculateComboRatio(maxCombo);
double score = GetScore(mode, maxAchievableCombo, calculateAccuracyRatio(computedBaseScore), comboRatio, scoreResultCounts);
return (score, pointInTimeAccuracy);
} }
/// <summary> /// <summary>

View File

@ -3,12 +3,12 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Logging; using osu.Framework.Logging;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Multiplayer; using osu.Game.Online.Multiplayer;
using osu.Game.Online.RealtimeMultiplayer; using osu.Game.Online.RealtimeMultiplayer;
using osu.Game.Scoring; using osu.Game.Scoring;
@ -34,13 +34,14 @@ namespace osu.Game.Screens.Multi.RealtimeMultiplayer
private IBindable<bool> isConnected; private IBindable<bool> isConnected;
private readonly TaskCompletionSource<bool> resultsReady = new TaskCompletionSource<bool>(); private readonly TaskCompletionSource<bool> resultsReady = new TaskCompletionSource<bool>();
private readonly ManualResetEventSlim startedEvent = new ManualResetEventSlim();
[CanBeNull] [CanBeNull]
private MultiplayerGameplayLeaderboard leaderboard; private MultiplayerGameplayLeaderboard leaderboard;
private readonly int[] userIds; private readonly int[] userIds;
private LoadingLayer loadingDisplay;
/// <summary> /// <summary>
/// Construct a multiplayer player. /// Construct a multiplayer player.
/// </summary> /// </summary>
@ -66,6 +67,12 @@ namespace osu.Game.Screens.Multi.RealtimeMultiplayer
client.MatchStarted += onMatchStarted; client.MatchStarted += onMatchStarted;
client.ResultsReady += onResultsReady; client.ResultsReady += onResultsReady;
ScoreProcessor.HasCompleted.BindValueChanged(completed =>
{
// wait for server to tell us that results are ready (see SubmitScore implementation)
loadingDisplay.Show();
});
isConnected = client.IsConnected.GetBoundCopy(); isConnected = client.IsConnected.GetBoundCopy();
isConnected.BindValueChanged(connected => isConnected.BindValueChanged(connected =>
{ {
@ -76,19 +83,20 @@ namespace osu.Game.Screens.Multi.RealtimeMultiplayer
} }
}, true); }, true);
client.ChangeState(MultiplayerUserState.Loaded)
.ContinueWith(task => failAndBail(task.Exception?.Message ?? "Server error"), TaskContinuationOptions.NotOnRanToCompletion);
if (!startedEvent.Wait(TimeSpan.FromSeconds(30)))
{
failAndBail("Failed to start the multiplayer match in time.");
return;
}
Debug.Assert(client.Room != null); Debug.Assert(client.Room != null);
// todo: this should be implemented via a custom HUD implementation, and correctly masked to the main content area. // todo: this should be implemented via a custom HUD implementation, and correctly masked to the main content area.
LoadComponentAsync(leaderboard = new MultiplayerGameplayLeaderboard(ScoreProcessor, userIds), HUDOverlay.Add); LoadComponentAsync(leaderboard = new MultiplayerGameplayLeaderboard(ScoreProcessor, userIds), HUDOverlay.Add);
HUDOverlay.Add(loadingDisplay = new LoadingLayer(DrawableRuleset) { Depth = float.MaxValue });
}
protected override void StartGameplay()
{
// block base call, but let the server know we are ready to start.
loadingDisplay.Show();
client.ChangeState(MultiplayerUserState.Loaded).ContinueWith(task => failAndBail(task.Exception?.Message ?? "Server error"), TaskContinuationOptions.NotOnRanToCompletion);
} }
private void failAndBail(string message = null) private void failAndBail(string message = null)
@ -96,7 +104,6 @@ namespace osu.Game.Screens.Multi.RealtimeMultiplayer
if (!string.IsNullOrEmpty(message)) if (!string.IsNullOrEmpty(message))
Logger.Log(message, LoggingTarget.Runtime, LogLevel.Important); Logger.Log(message, LoggingTarget.Runtime, LogLevel.Important);
startedEvent.Set();
Schedule(() => PerformExit(false)); Schedule(() => PerformExit(false));
} }
@ -118,7 +125,11 @@ namespace osu.Game.Screens.Multi.RealtimeMultiplayer
padding + HUDOverlay.TopScoringElementsHeight); padding + HUDOverlay.TopScoringElementsHeight);
} }
private void onMatchStarted() => startedEvent.Set(); private void onMatchStarted() => Scheduler.Add(() =>
{
loadingDisplay.Hide();
base.StartGameplay();
});
private void onResultsReady() => resultsReady.SetResult(true); private void onResultsReady() => resultsReady.SetResult(true);
@ -128,9 +139,9 @@ namespace osu.Game.Screens.Multi.RealtimeMultiplayer
await client.ChangeState(MultiplayerUserState.FinishedPlay); await client.ChangeState(MultiplayerUserState.FinishedPlay);
// Await up to 30 seconds for results to become available (3 api request timeouts). // Await up to 60 seconds for results to become available (6 api request timeouts).
// This is arbitrary just to not leave the player in an essentially deadlocked state if any connection issues occur. // This is arbitrary just to not leave the player in an essentially deadlocked state if any connection issues occur.
await Task.WhenAny(resultsReady.Task, Task.Delay(TimeSpan.FromSeconds(30))); await Task.WhenAny(resultsReady.Task, Task.Delay(TimeSpan.FromSeconds(60)));
} }
protected override ResultsScreen CreateResults(ScoreInfo score) protected override ResultsScreen CreateResults(ScoreInfo score)

View File

@ -122,8 +122,8 @@ namespace osu.Game.Screens.Play.HUD
if (LastHeader == null) if (LastHeader == null)
return; return;
(score.Value, accuracy.Value) = processor.GetScoreAndAccuracy(mode, LastHeader.MaxCombo, LastHeader.Statistics); score.Value = processor.GetImmediateScore(mode, LastHeader.MaxCombo, LastHeader.Statistics);
accuracy.Value = LastHeader.Accuracy;
currentCombo.Value = LastHeader.Combo; currentCombo.Value = LastHeader.Combo;
} }
} }

View File

@ -734,9 +734,6 @@ namespace osu.Game.Screens.Play
storyboardReplacesBackground.Value = Beatmap.Value.Storyboard.ReplacesBackground && Beatmap.Value.Storyboard.HasDrawable; storyboardReplacesBackground.Value = Beatmap.Value.Storyboard.ReplacesBackground && Beatmap.Value.Storyboard.HasDrawable;
GameplayClockContainer.Restart();
GameplayClockContainer.FadeInFromZero(750, Easing.OutQuint);
foreach (var mod in Mods.Value.OfType<IApplicableToPlayer>()) foreach (var mod in Mods.Value.OfType<IApplicableToPlayer>())
mod.ApplyToPlayer(this); mod.ApplyToPlayer(this);
@ -751,6 +748,21 @@ namespace osu.Game.Screens.Play
mod.ApplyToTrack(musicController.CurrentTrack); mod.ApplyToTrack(musicController.CurrentTrack);
updateGameplayState(); updateGameplayState();
GameplayClockContainer.FadeInFromZero(750, Easing.OutQuint);
StartGameplay();
}
/// <summary>
/// Called to trigger the starting of the gameplay clock and underlying gameplay.
/// This will be called on entering the player screen once. A derived class may block the first call to this to delay the start of gameplay.
/// </summary>
protected virtual void StartGameplay()
{
if (GameplayClockContainer.GameplayClock.IsRunning)
throw new InvalidOperationException($"{nameof(StartGameplay)} should not be called when the gameplay clock is already running");
GameplayClockContainer.Restart();
} }
public override void OnSuspending(IScreen next) public override void OnSuspending(IScreen next)

View File

@ -31,7 +31,7 @@ namespace osu.Game.Tests.Visual.RealtimeMultiplayer
public void RemoveUser(User user) public void RemoveUser(User user)
{ {
Debug.Assert(Room != null); Debug.Assert(Room != null);
((IMultiplayerClient)this).UserLeft(Room.Users.Single(u => u.User == user)); ((IMultiplayerClient)this).UserLeft(new MultiplayerRoomUser(user.Id));
Schedule(() => Schedule(() =>
{ {