1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-21 15:27:24 +08:00

Merge branch 'master' into net6

This commit is contained in:
Dean Herbert 2022-02-14 22:06:35 +09:00
commit 5b30921cbf
50 changed files with 546 additions and 211 deletions

View File

@ -51,7 +51,7 @@
<Reference Include="Java.Interop" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.204.0" />
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.211.0" />
<PackageReference Include="ppy.osu.Framework.Android" Version="2022.204.0" />
</ItemGroup>
<ItemGroup Label="Transitive Dependencies">

View File

@ -87,8 +87,8 @@ namespace osu.Game.Rulesets.Osu.Mods
requiresHold |= slider.Ball.IsHovered || h.IsHovered;
break;
case DrawableSpinner _:
requiresHold = true;
case DrawableSpinner spinner:
requiresHold |= spinner.HitObject.SpinsRequired > 0;
break;
}
}

View File

@ -45,7 +45,7 @@ namespace osu.Game.Rulesets.Taiko.Tests
Player.ScoreProcessor.NewJudgement += b => judged = true;
});
AddUntilStep("swell judged", () => judged);
AddAssert("failed", () => Player.HasFailed);
AddAssert("failed", () => Player.GameplayState.HasFailed);
}
}
}

View File

@ -29,7 +29,7 @@ namespace osu.Game.Tests.Visual.Gameplay
protected override void AddCheckSteps()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddUntilStep("wait for fail overlay", () => ((FailPlayer)Player).FailOverlay.State.Value == Visibility.Visible);
// The pause screen and fail animation both ramp frequency.

View File

@ -21,7 +21,7 @@ namespace osu.Game.Tests.Visual.Gameplay
protected override void AddCheckSteps()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddUntilStep("wait for multiple judgements", () => ((FailPlayer)Player).ScoreProcessor.JudgedHits > 1);
AddAssert("total number of results == 1", () =>
{

View File

@ -185,7 +185,7 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestPauseAfterFail()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddUntilStep("fail overlay shown", () => Player.FailOverlayVisible);
confirmClockRunning(false);
@ -201,7 +201,7 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestExitFromFailedGameplayAfterFailAnimation()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddUntilStep("wait for fail overlay shown", () => Player.FailOverlayVisible);
confirmClockRunning(false);
@ -213,7 +213,7 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestExitFromFailedGameplayDuringFailAnimation()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
// will finish the fail animation and show the fail/pause screen.
AddStep("attempt exit via pause key", () => Player.ExitViaPause());
@ -227,7 +227,7 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestQuickRetryFromFailedGameplay()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddStep("quick retry", () => Player.GameplayClockContainer.ChildrenOfType<HotkeyRetryOverlay>().First().Action?.Invoke());
confirmExited();
@ -236,7 +236,7 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestQuickExitFromFailedGameplay()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddStep("quick exit", () => Player.GameplayClockContainer.ChildrenOfType<HotkeyExitOverlay>().First().Action?.Invoke());
confirmExited();
@ -341,7 +341,7 @@ namespace osu.Game.Tests.Visual.Gameplay
{
confirmClockRunning(false);
confirmNotExited();
AddAssert("player not failed", () => !Player.HasFailed);
AddAssert("player not failed", () => !Player.GameplayState.HasFailed);
AddAssert("pause overlay shown", () => Player.PauseOverlayVisible);
}

View File

@ -159,7 +159,7 @@ namespace osu.Game.Tests.Visual.Gameplay
AddUntilStep("wait for token request", () => Player.TokenCreationRequested);
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddStep("exit", () => Player.Exit());
AddAssert("ensure no submission", () => Player.SubmittedScore == null);
@ -176,7 +176,7 @@ namespace osu.Game.Tests.Visual.Gameplay
addFakeHit();
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddStep("exit", () => Player.Exit());
AddAssert("ensure failing submission", () => Player.SubmittedScore?.ScoreInfo.Passed == false);

View File

@ -155,11 +155,13 @@ namespace osu.Game.Tests.Visual.Gameplay
waitForPlayer();
checkPaused(true);
sendFrames();
finish();
finish(SpectatedUserState.Failed);
checkPaused(false);
// TODO: should replay until running out of frames then fail
checkPaused(false); // Should continue playing until out of frames
checkPaused(true); // And eventually stop after running out of frames and fail.
// Todo: Should check for + display a failed message.
}
[Test]
@ -211,7 +213,7 @@ namespace osu.Game.Tests.Visual.Gameplay
AddStep("send frames and finish play", () =>
{
spectatorClient.HandleFrame(new OsuReplayFrame(1000, Vector2.Zero));
spectatorClient.EndPlaying();
spectatorClient.EndPlaying(new GameplayState(new TestBeatmap(new OsuRuleset().RulesetInfo), new OsuRuleset()) { HasPassed = true });
});
// We can't access API because we're an "online" test.
@ -234,6 +236,71 @@ namespace osu.Game.Tests.Visual.Gameplay
AddAssert("last frame has header", () => lastBundle.Frames[^1].Header != null);
}
[Test]
public void TestPlayingState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
[Test]
public void TestPassedState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("send passed", () => spectatorClient.EndPlay(streamingUser.Id, SpectatedUserState.Passed));
AddUntilStep("state is passed", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Passed);
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
[Test]
public void TestQuitState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("send quit", () => spectatorClient.EndPlay(streamingUser.Id));
AddUntilStep("state is quit", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Quit);
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
[Test]
public void TestFailedState()
{
loadSpectatingScreen();
start();
sendFrames();
waitForPlayer();
AddStep("send failed", () => spectatorClient.EndPlay(streamingUser.Id, SpectatedUserState.Failed));
AddUntilStep("state is failed", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Failed);
start();
sendFrames();
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
}
private OsuFramedReplayInputHandler replayHandler =>
(OsuFramedReplayInputHandler)Stack.ChildrenOfType<OsuInputManager>().First().ReplayInputHandler;
@ -246,7 +313,7 @@ namespace osu.Game.Tests.Visual.Gameplay
private void start(int? beatmapId = null) => AddStep("start play", () => spectatorClient.StartPlay(streamingUser.Id, beatmapId ?? importedBeatmapId));
private void finish() => AddStep("end play", () => spectatorClient.EndPlay(streamingUser.Id));
private void finish(SpectatedUserState state = SpectatedUserState.Quit) => AddStep("end play", () => spectatorClient.EndPlay(streamingUser.Id, state));
private void checkPaused(bool state) =>
AddUntilStep($"game is {(state ? "paused" : "playing")}", () => player.ChildrenOfType<DrawableRuleset>().First().IsPaused.Value == state);

View File

@ -37,8 +37,8 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestClientSendsCorrectRuleset()
{
AddUntilStep("spectator client sending frames", () => spectatorClient.PlayingUserStates.ContainsKey(dummy_user_id));
AddAssert("spectator client sent correct ruleset", () => spectatorClient.PlayingUserStates[dummy_user_id].RulesetID == Ruleset.Value.OnlineID);
AddUntilStep("spectator client sending frames", () => spectatorClient.WatchedUserStates.ContainsKey(dummy_user_id));
AddAssert("spectator client sent correct ruleset", () => spectatorClient.WatchedUserStates[dummy_user_id].RulesetID == Ruleset.Value.OnlineID);
}
public override void TearDownSteps()

View File

@ -96,7 +96,7 @@ namespace osu.Game.Tests.Visual.Gameplay
AddStep("set storyboard duration to 0.6s", () => currentStoryboardDuration = 600);
});
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail", () => Player.GameplayState.HasFailed);
AddUntilStep("storyboard ends", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= currentStoryboardDuration);
AddUntilStep("wait for fail overlay", () => Player.FailOverlay.State.Value == Visibility.Visible);
}

View File

@ -115,7 +115,7 @@ namespace osu.Game.Tests.Visual.Multiplayer
public void RandomlyUpdateState()
{
foreach (int userId in PlayingUsers)
foreach ((int userId, _) in WatchedUserStates)
{
if (RNG.NextBool())
continue;

View File

@ -211,7 +211,7 @@ namespace osu.Game.Tests.Visual.Navigation
return (player = Game.ScreenStack.CurrentScreen as Player) != null;
});
AddUntilStep("wait for fail", () => player.HasFailed);
AddUntilStep("wait for fail", () => player.GameplayState.HasFailed);
AddUntilStep("wait for track stop", () => !Game.MusicController.IsPlaying);
AddAssert("Ensure time before preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().BeatmapInfo.Metadata.PreviewTime);

View File

@ -3,32 +3,69 @@
using System.IO;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings.Sections.Maintenance;
namespace osu.Game.Tests.Visual.Settings
{
public class TestSceneMigrationScreens : ScreenTestScene
{
[Cached]
private readonly NotificationOverlay notifications;
public TestSceneMigrationScreens()
{
AddStep("Push screen", () => Stack.Push(new TestMigrationSelectScreen()));
Children = new Drawable[]
{
notifications = new NotificationOverlay
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
}
};
}
[Test]
public void TestDeleteSuccess()
{
AddStep("Push screen", () => Stack.Push(new TestMigrationSelectScreen(true)));
}
[Test]
public void TestDeleteFails()
{
AddStep("Push screen", () => Stack.Push(new TestMigrationSelectScreen(false)));
}
private class TestMigrationSelectScreen : MigrationSelectScreen
{
protected override void BeginMigration(DirectoryInfo target) => this.Push(new TestMigrationRunScreen());
private readonly bool deleteSuccess;
public TestMigrationSelectScreen(bool deleteSuccess)
{
this.deleteSuccess = deleteSuccess;
}
protected override void BeginMigration(DirectoryInfo target) => this.Push(new TestMigrationRunScreen(deleteSuccess));
private class TestMigrationRunScreen : MigrationRunScreen
{
protected override void PerformMigration()
{
Thread.Sleep(3000);
}
private readonly bool success;
public TestMigrationRunScreen()
public TestMigrationRunScreen(bool success)
: base(null)
{
this.success = success;
}
protected override bool PerformMigration()
{
Thread.Sleep(3000);
return success;
}
}
}

View File

@ -41,6 +41,68 @@ namespace osu.Game.Tests.Visual.SongSelect
this.rulesets = rulesets;
}
[Test]
public void TestExternalRulesetChange()
{
createCarousel(new List<BeatmapSetInfo>());
AddStep("filter to ruleset 0", () => carousel.Filter(new FilterCriteria
{
Ruleset = rulesets.AvailableRulesets.ElementAt(0),
AllowConvertedBeatmaps = true,
}, false));
AddStep("add mixed ruleset beatmapset", () =>
{
var testMixed = TestResources.CreateTestBeatmapSetInfo(3);
for (int i = 0; i <= 2; i++)
{
testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i);
}
carousel.UpdateBeatmapSet(testMixed);
});
AddUntilStep("wait for filtered difficulties", () =>
{
var visibleBeatmapPanels = carousel.Items.OfType<DrawableCarouselBeatmap>().Where(p => p.IsPresent).ToArray();
return visibleBeatmapPanels.Length == 1
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 0) == 1;
});
AddStep("filter to ruleset 1", () => carousel.Filter(new FilterCriteria
{
Ruleset = rulesets.AvailableRulesets.ElementAt(1),
AllowConvertedBeatmaps = true,
}, false));
AddUntilStep("wait for filtered difficulties", () =>
{
var visibleBeatmapPanels = carousel.Items.OfType<DrawableCarouselBeatmap>().Where(p => p.IsPresent).ToArray();
return visibleBeatmapPanels.Length == 2
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 0) == 1
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 1) == 1;
});
AddStep("filter to ruleset 2", () => carousel.Filter(new FilterCriteria
{
Ruleset = rulesets.AvailableRulesets.ElementAt(2),
AllowConvertedBeatmaps = true,
}, false));
AddUntilStep("wait for filtered difficulties", () =>
{
var visibleBeatmapPanels = carousel.Items.OfType<DrawableCarouselBeatmap>().Where(p => p.IsPresent).ToArray();
return visibleBeatmapPanels.Length == 2
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 0) == 1
&& visibleBeatmapPanels.Count(p => ((CarouselBeatmap)p.Item).BeatmapInfo.Ruleset.OnlineID == 2) == 1;
});
}
[Test]
public void TestScrollPositionMaintainedOnAdd()
{

View File

@ -70,7 +70,7 @@ namespace osu.Game.Tournament.IO
public IEnumerable<string> ListTournaments() => AllTournaments.GetDirectories(string.Empty);
public override void Migrate(Storage newStorage)
public override bool Migrate(Storage newStorage)
{
// this migration only happens once on moving to the per-tournament storage system.
// listed files are those known at that point in time.
@ -94,6 +94,8 @@ namespace osu.Game.Tournament.IO
ChangeTargetStorage(newStorage);
storageConfig.SetValue(StorageConfig.CurrentTournament, default_tournament);
storageConfig.Save();
return true;
}
private void moveFileIfExists(string file, DirectoryInfo destination)

View File

@ -33,7 +33,7 @@ namespace osu.Game.Beatmaps.Drawables.Cards
bool firstGroup = true;
foreach (var group in beatmapSetInfo.Beatmaps.GroupBy(beatmap => beatmap.Ruleset.OnlineID).OrderBy(group => group.Key))
foreach (var group in beatmapSetInfo.Beatmaps.GroupBy(beatmap => beatmap.Ruleset).OrderBy(group => group.Key))
{
if (!firstGroup)
{

View File

@ -62,10 +62,8 @@ namespace osu.Game.Beatmaps.Drawables
// matching web: https://github.com/ppy/osu-web/blob/d06d8c5e735eb1f48799b1654b528e9a7afb0a35/resources/assets/lib/beatmapset-panel.tsx#L127
bool collapsed = beatmapSet.Beatmaps.Count() > 12;
foreach (var rulesetGrouping in beatmapSet.Beatmaps.GroupBy(beatmap => beatmap.Ruleset.OnlineID).OrderBy(group => group.Key))
{
flow.Add(new RulesetDifficultyGroup(rulesetGrouping.Key, rulesetGrouping, collapsed));
}
foreach (var rulesetGrouping in beatmapSet.Beatmaps.GroupBy(beatmap => beatmap.Ruleset).OrderBy(group => group.Key))
flow.Add(new RulesetDifficultyGroup(rulesetGrouping.Key.OnlineID, rulesetGrouping, collapsed));
}
protected override void LoadComplete()

View File

@ -33,7 +33,8 @@ namespace osu.Game.IO
/// A general purpose migration method to move the storage to a different location.
/// <param name="newStorage">The target storage of the migration.</param>
/// </summary>
public virtual void Migrate(Storage newStorage)
/// <returns>Whether cleanup could complete.</returns>
public virtual bool Migrate(Storage newStorage)
{
var source = new DirectoryInfo(GetFullPath("."));
var destination = new DirectoryInfo(newStorage.GetFullPath("."));
@ -57,17 +58,20 @@ namespace osu.Game.IO
CopyRecursive(source, destination);
ChangeTargetStorage(newStorage);
DeleteRecursive(source);
return DeleteRecursive(source);
}
protected void DeleteRecursive(DirectoryInfo target, bool topLevelExcludes = true)
protected bool DeleteRecursive(DirectoryInfo target, bool topLevelExcludes = true)
{
bool allFilesDeleted = true;
foreach (System.IO.FileInfo fi in target.GetFiles())
{
if (topLevelExcludes && IgnoreFiles.Contains(fi.Name))
continue;
AttemptOperation(() => fi.Delete());
allFilesDeleted &= AttemptOperation(() => fi.Delete(), throwOnFailure: false);
}
foreach (DirectoryInfo dir in target.GetDirectories())
@ -75,11 +79,13 @@ namespace osu.Game.IO
if (topLevelExcludes && IgnoreDirectories.Contains(dir.Name))
continue;
AttemptOperation(() => dir.Delete(true));
allFilesDeleted &= AttemptOperation(() => dir.Delete(true), throwOnFailure: false);
}
if (target.GetFiles().Length == 0 && target.GetDirectories().Length == 0)
AttemptOperation(target.Delete);
allFilesDeleted &= AttemptOperation(target.Delete, throwOnFailure: false);
return allFilesDeleted;
}
protected void CopyRecursive(DirectoryInfo source, DirectoryInfo destination, bool topLevelExcludes = true)
@ -110,19 +116,25 @@ namespace osu.Game.IO
/// </summary>
/// <param name="action">The action to perform.</param>
/// <param name="attempts">The number of attempts (250ms wait between each).</param>
protected static void AttemptOperation(Action action, int attempts = 10)
/// <param name="throwOnFailure">Whether to throw an exception on failure. If <c>false</c>, will silently fail.</param>
protected static bool AttemptOperation(Action action, int attempts = 10, bool throwOnFailure = true)
{
while (true)
{
try
{
action();
return;
return true;
}
catch (Exception)
{
if (attempts-- == 0)
throw;
{
if (throwOnFailure)
throw;
return false;
}
}
Thread.Sleep(250);

View File

@ -113,11 +113,14 @@ namespace osu.Game.IO
}
}
public override void Migrate(Storage newStorage)
public override bool Migrate(Storage newStorage)
{
base.Migrate(newStorage);
bool cleanupSucceeded = base.Migrate(newStorage);
storageConfig.SetValue(StorageConfig.FullPath, newStorage.GetFullPath("."));
storageConfig.Save();
return cleanupSucceeded;
}
}

View File

@ -39,6 +39,7 @@ namespace osu.Game.Online.API.Requests
{
Best,
Firsts,
Recent
Recent,
Pinned
}
}

View File

@ -98,7 +98,7 @@ namespace osu.Game.Online.API.Requests.Responses
public string MD5Hash => Checksum;
public IRulesetInfo Ruleset => new RulesetInfo { OnlineID = RulesetID };
public IRulesetInfo Ruleset => new APIRuleset { OnlineID = RulesetID };
[JsonIgnore]
public string Hash => throw new NotImplementedException();
@ -106,5 +106,29 @@ namespace osu.Game.Online.API.Requests.Responses
#endregion
public bool Equals(IBeatmapInfo? other) => other is APIBeatmap b && this.MatchesOnlineID(b);
private class APIRuleset : IRulesetInfo
{
public int OnlineID { get; set; } = -1;
public string Name => $@"{nameof(APIRuleset)} (ID: {OnlineID})";
public string ShortName => nameof(APIRuleset);
public string InstantiationInfo => string.Empty;
public Ruleset CreateInstance() => throw new NotImplementedException();
public bool Equals(IRulesetInfo? other) => other is APIRuleset r && this.MatchesOnlineID(r);
public int CompareTo(IRulesetInfo other)
{
if (!(other is APIRuleset ruleset))
throw new ArgumentException($@"Object is not of type {nameof(APIRuleset)}.", nameof(other));
return OnlineID.CompareTo(ruleset.OnlineID);
}
// ReSharper disable once NonReadonlyMemberInGetHashCode
public override int GetHashCode() => OnlineID;
}
}
}

View File

@ -151,6 +151,9 @@ namespace osu.Game.Online.API.Requests.Responses
[JsonProperty(@"scores_recent_count")]
public int ScoresRecentCount;
[JsonProperty(@"scores_pinned_count")]
public int ScoresPinnedCount;
[JsonProperty(@"beatmap_playcounts_count")]
public int BeatmapPlayCountsCount;

View File

@ -1,46 +1,22 @@
// 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.
using System.Net.Http;
using Newtonsoft.Json;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
using osu.Game.Online.Solo;
using osu.Game.Scoring;
namespace osu.Game.Online.Rooms
{
public class SubmitRoomScoreRequest : APIRequest<MultiplayerScore>
public class SubmitRoomScoreRequest : SubmitScoreRequest
{
private readonly long scoreId;
private readonly long roomId;
private readonly long playlistItemId;
private readonly SubmittableScore score;
public SubmitRoomScoreRequest(long scoreId, long roomId, long playlistItemId, ScoreInfo scoreInfo)
public SubmitRoomScoreRequest(ScoreInfo scoreInfo, long scoreId, long roomId, long playlistItemId)
: base(scoreInfo, scoreId)
{
this.scoreId = scoreId;
this.roomId = roomId;
this.playlistItemId = playlistItemId;
score = new SubmittableScore(scoreInfo);
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.ContentType = "application/json";
req.Method = HttpMethod.Put;
req.Timeout = 30000;
req.AddRaw(JsonConvert.SerializeObject(score, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
return req;
}
protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores/{scoreId}";
protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores/{ScoreId}";
}
}

View File

@ -0,0 +1,41 @@
// 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.
using System.Net.Http;
using Newtonsoft.Json;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
using osu.Game.Online.Solo;
using osu.Game.Scoring;
namespace osu.Game.Online.Rooms
{
public abstract class SubmitScoreRequest : APIRequest<MultiplayerScore>
{
public readonly SubmittableScore Score;
protected readonly long ScoreId;
protected SubmitScoreRequest(ScoreInfo scoreInfo, long scoreId)
{
Score = new SubmittableScore(scoreInfo);
ScoreId = scoreId;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.ContentType = "application/json";
req.Method = HttpMethod.Put;
req.Timeout = 30000;
req.AddRaw(JsonConvert.SerializeObject(Score, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
return req;
}
}
}

View File

@ -1,46 +1,21 @@
// 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.
using System.Net.Http;
using Newtonsoft.Json;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Scoring;
namespace osu.Game.Online.Solo
{
public class SubmitSoloScoreRequest : APIRequest<MultiplayerScore>
public class SubmitSoloScoreRequest : SubmitScoreRequest
{
public readonly SubmittableScore Score;
private readonly long scoreId;
private readonly int beatmapId;
public SubmitSoloScoreRequest(int beatmapId, long scoreId, ScoreInfo scoreInfo)
public SubmitSoloScoreRequest(ScoreInfo scoreInfo, long scoreId, int beatmapId)
: base(scoreInfo, scoreId)
{
this.beatmapId = beatmapId;
this.scoreId = scoreId;
Score = new SubmittableScore(scoreInfo);
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.ContentType = "application/json";
req.Method = HttpMethod.Put;
req.Timeout = 30000;
req.AddRaw(JsonConvert.SerializeObject(Score, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
return req;
}
protected override string Target => $@"beatmaps/{beatmapId}/solo/scores/{scoreId}";
protected override string Target => $@"beatmaps/{beatmapId}/solo/scores/{ScoreId}";
}
}

View File

@ -0,0 +1,38 @@
// 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.
namespace osu.Game.Online.Spectator
{
public enum SpectatedUserState
{
/// <summary>
/// The spectated user is not yet playing.
/// </summary>
Idle,
/// <summary>
/// The spectated user is currently playing.
/// </summary>
Playing,
/// <summary>
/// The spectated user is currently paused. Unused for the time being.
/// </summary>
Paused,
/// <summary>
/// The spectated user has passed gameplay.
/// </summary>
Passed,
/// <summary>
/// The spectated user has failed gameplay.
/// </summary>
Failed,
/// <summary>
/// The spectated user has quit gameplay.
/// </summary>
Quit
}
}

View File

@ -35,19 +35,28 @@ namespace osu.Game.Online.Spectator
/// </summary>
public abstract IBindable<bool> IsConnected { get; }
private readonly List<int> watchingUsers = new List<int>();
/// <summary>
/// The states of all users currently being watched.
/// </summary>
public IBindableDictionary<int, SpectatorState> WatchedUserStates => watchedUserStates;
/// <summary>
/// A global list of all players currently playing.
/// </summary>
public IBindableList<int> PlayingUsers => playingUsers;
private readonly BindableList<int> playingUsers = new BindableList<int>();
public IBindableDictionary<int, SpectatorState> PlayingUserStates => playingUserStates;
private readonly BindableDictionary<int, SpectatorState> playingUserStates = new BindableDictionary<int, SpectatorState>();
/// <summary>
/// All users currently being watched.
/// </summary>
private readonly List<int> watchedUsers = new List<int>();
private readonly BindableDictionary<int, SpectatorState> watchedUserStates = new BindableDictionary<int, SpectatorState>();
private readonly BindableList<int> playingUsers = new BindableList<int>();
private readonly SpectatorState currentState = new SpectatorState();
private IBeatmap? currentBeatmap;
private Score? currentScore;
private readonly SpectatorState currentState = new SpectatorState();
/// <summary>
/// Whether the local user is playing.
/// </summary>
@ -76,8 +85,8 @@ namespace osu.Game.Online.Spectator
if (connected.NewValue)
{
// get all the users that were previously being watched
int[] users = watchingUsers.ToArray();
watchingUsers.Clear();
int[] users = watchedUsers.ToArray();
watchedUsers.Clear();
// resubscribe to watched users.
foreach (int userId in users)
@ -90,7 +99,7 @@ namespace osu.Game.Online.Spectator
else
{
playingUsers.Clear();
playingUserStates.Clear();
watchedUserStates.Clear();
}
}), true);
}
@ -102,11 +111,8 @@ namespace osu.Game.Online.Spectator
if (!playingUsers.Contains(userId))
playingUsers.Add(userId);
// UserBeganPlaying() is called by the server regardless of whether the local user is watching the remote user, and is called a further time when the remote user is watched.
// This may be a temporary thing (see: https://github.com/ppy/osu-server-spectator/blob/2273778e02cfdb4a9c6a934f2a46a8459cb5d29c/osu.Server.Spectator/Hubs/SpectatorHub.cs#L28-L29).
// We don't want the user states to update unless the player is being watched, otherwise calling BindUserBeganPlaying() can lead to double invocations.
if (watchingUsers.Contains(userId))
playingUserStates[userId] = state;
if (watchedUsers.Contains(userId))
watchedUserStates[userId] = state;
OnUserBeganPlaying?.Invoke(userId, state);
});
@ -119,7 +125,9 @@ namespace osu.Game.Online.Spectator
Schedule(() =>
{
playingUsers.Remove(userId);
playingUserStates.Remove(userId);
if (watchedUsers.Contains(userId))
watchedUserStates[userId] = state;
OnUserFinishedPlaying?.Invoke(userId, state);
});
@ -151,6 +159,7 @@ namespace osu.Game.Online.Spectator
currentState.BeatmapID = score.ScoreInfo.BeatmapInfo.OnlineID;
currentState.RulesetID = score.ScoreInfo.RulesetID;
currentState.Mods = score.ScoreInfo.Mods.Select(m => new APIMod(m)).ToArray();
currentState.State = SpectatedUserState.Playing;
currentBeatmap = state.Beatmap;
currentScore = score;
@ -161,7 +170,7 @@ namespace osu.Game.Online.Spectator
public void SendFrames(FrameDataBundle data) => lastSend = SendFramesInternal(data);
public void EndPlaying()
public void EndPlaying(GameplayState state)
{
// This method is most commonly called via Dispose(), which is can be asynchronous (via the AsyncDisposalQueue).
// We probably need to find a better way to handle this...
@ -176,6 +185,13 @@ namespace osu.Game.Online.Spectator
IsPlaying = false;
currentBeatmap = null;
if (state.HasPassed)
currentState.State = SpectatedUserState.Passed;
else if (state.HasFailed)
currentState.State = SpectatedUserState.Failed;
else
currentState.State = SpectatedUserState.Quit;
EndPlayingInternal(currentState);
});
}
@ -184,10 +200,10 @@ namespace osu.Game.Online.Spectator
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (watchingUsers.Contains(userId))
if (watchedUsers.Contains(userId))
return;
watchingUsers.Add(userId);
watchedUsers.Add(userId);
WatchUserInternal(userId);
}
@ -198,8 +214,8 @@ namespace osu.Game.Online.Spectator
// Todo: This should not be a thing, but requires framework changes.
Schedule(() =>
{
watchingUsers.Remove(userId);
playingUserStates.Remove(userId);
watchedUsers.Remove(userId);
watchedUserStates.Remove(userId);
StopWatchingUserInternal(userId);
});
}

View File

@ -24,14 +24,17 @@ namespace osu.Game.Online.Spectator
[Key(2)]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
[Key(3)]
public SpectatedUserState State { get; set; }
public bool Equals(SpectatorState other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID;
return BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && State == other.State;
}
public override string ToString() => $"Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
public override string ToString() => $"Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID} State:{State}";
}
}

View File

@ -413,7 +413,7 @@ namespace osu.Game
Scheduler.AddDelayed(GracefullyExit, 2000);
}
public void Migrate(string path)
public bool Migrate(string path)
{
Logger.Log($@"Migrating osu! data from ""{Storage.GetFullPath(string.Empty)}"" to ""{path}""...");
@ -432,14 +432,15 @@ namespace osu.Game
readyToRun.Wait();
(Storage as OsuStorage)?.Migrate(Host.GetStorage(path));
bool? cleanupSucceded = (Storage as OsuStorage)?.Migrate(Host.GetStorage(path));
Logger.Log(@"Migration complete!");
return cleanupSucceded != false;
}
finally
{
realmBlocker?.Dispose();
}
Logger.Log(@"Migration complete!");
}
protected override UserInputManager CreateUserInputManager() => new OsuUserInputManager();

View File

@ -2,6 +2,7 @@
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
@ -52,21 +53,24 @@ namespace osu.Game.Overlays.Dashboard
base.LoadComplete();
playingUsers.BindTo(spectatorClient.PlayingUsers);
playingUsers.BindCollectionChanged(onUsersChanged, true);
playingUsers.BindCollectionChanged(onPlayingUsersChanged, true);
}
private void onUsersChanged(object sender, NotifyCollectionChangedEventArgs e) => Schedule(() =>
private void onPlayingUsersChanged(object sender, NotifyCollectionChangedEventArgs e) => Schedule(() =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (int id in e.NewItems.OfType<int>().ToArray())
Debug.Assert(e.NewItems != null);
foreach (int userId in e.NewItems)
{
users.GetUserAsync(id).ContinueWith(task =>
users.GetUserAsync(userId).ContinueWith(task =>
{
var user = task.GetResultSafely();
if (user == null) return;
if (user == null)
return;
Schedule(() =>
{
@ -82,12 +86,10 @@ namespace osu.Game.Overlays.Dashboard
break;
case NotifyCollectionChangedAction.Remove:
foreach (int u in e.OldItems.OfType<int>())
userFlow.FirstOrDefault(card => card.User.Id == u)?.Expire();
break;
Debug.Assert(e.OldItems != null);
case NotifyCollectionChangedAction.Reset:
userFlow.Clear();
foreach (int userId in e.OldItems)
userFlow.FirstOrDefault(card => card.User.Id == userId)?.Expire();
break;
}
});

View File

@ -46,6 +46,9 @@ namespace osu.Game.Overlays.Profile.Sections.Ranks
case ScoreType.Recent:
return user.ScoresRecentCount;
case ScoreType.Pinned:
return user.ScoresPinnedCount;
default:
return 0;
}

View File

@ -18,6 +18,7 @@ namespace osu.Game.Overlays.Profile.Sections
{
Children = new[]
{
new PaginatedScoreContainer(ScoreType.Pinned, User, UsersStrings.ShowExtraTopRanksPinnedTitle),
new PaginatedScoreContainer(ScoreType.Best, User, UsersStrings.ShowExtraTopRanksBestTitle),
new PaginatedScoreContainer(ScoreType.Firsts, User, UsersStrings.ShowExtraTopRanksFirstTitle)
};

View File

@ -4,13 +4,16 @@
using System.IO;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Notifications;
using osu.Game.Screens;
using osuTK;
@ -23,6 +26,15 @@ namespace osu.Game.Overlays.Settings.Sections.Maintenance
[Resolved(canBeNull: true)]
private OsuGame game { get; set; }
[Resolved]
private NotificationOverlay notifications { get; set; }
[Resolved]
private Storage storage { get; set; }
[Resolved]
private GameHost host { get; set; }
public override bool AllowBackButton => false;
public override bool AllowExternalScreenChange => false;
@ -84,17 +96,33 @@ namespace osu.Game.Overlays.Settings.Sections.Maintenance
Beatmap.Value = Beatmap.Default;
var originalStorage = new NativeStorage(storage.GetFullPath(string.Empty), host);
migrationTask = Task.Run(PerformMigration)
.ContinueWith(t =>
.ContinueWith(task =>
{
if (t.IsFaulted)
Logger.Log($"Error during migration: {t.Exception?.Message}", level: LogLevel.Error);
if (task.IsFaulted)
{
Logger.Error(task.Exception, $"Error during migration: {task.Exception?.Message}");
}
else if (!task.GetResultSafely())
{
notifications.Post(new SimpleNotification
{
Text = "Some files couldn't be cleaned up during migration. Clicking this notification will open the folder so you can manually clean things up.",
Activated = () =>
{
originalStorage.PresentExternally();
return true;
}
});
}
Schedule(this.Exit);
});
}
protected virtual void PerformMigration() => game?.Migrate(destination.FullName);
protected virtual bool PerformMigration() => game?.Migrate(destination.FullName) != false;
public override void OnEntering(IScreen last)
{

View File

@ -11,7 +11,7 @@ namespace osu.Game.Rulesets
{
[ExcludeFromDynamicCompile]
[Table(@"RulesetInfo")]
public sealed class EFRulesetInfo : IEquatable<EFRulesetInfo>, IRulesetInfo
public sealed class EFRulesetInfo : IEquatable<EFRulesetInfo>, IComparable<EFRulesetInfo>, IRulesetInfo
{
public int? ID { get; set; }
@ -42,7 +42,15 @@ namespace osu.Game.Rulesets
public bool Equals(EFRulesetInfo other) => other != null && ID == other.ID && Available == other.Available && Name == other.Name && InstantiationInfo == other.InstantiationInfo;
public int CompareTo(RulesetInfo other) => OnlineID.CompareTo(other.OnlineID);
public int CompareTo(EFRulesetInfo other) => OnlineID.CompareTo(other.OnlineID);
public int CompareTo(IRulesetInfo other)
{
if (!(other is EFRulesetInfo ruleset))
throw new ArgumentException($@"Object is not of type {nameof(EFRulesetInfo)}.", nameof(other));
return CompareTo(ruleset);
}
public override bool Equals(object obj) => obj is EFRulesetInfo rulesetInfo && Equals(rulesetInfo);

View File

@ -11,7 +11,7 @@ namespace osu.Game.Rulesets
/// <summary>
/// A representation of a ruleset's metadata.
/// </summary>
public interface IRulesetInfo : IHasOnlineID<int>, IEquatable<IRulesetInfo>, IComparable<RulesetInfo>
public interface IRulesetInfo : IHasOnlineID<int>, IEquatable<IRulesetInfo>, IComparable<IRulesetInfo>
{
/// <summary>
/// The user-exposed name of this ruleset.

View File

@ -12,7 +12,7 @@ namespace osu.Game.Rulesets
{
[ExcludeFromDynamicCompile]
[MapTo("Ruleset")]
public class RulesetInfo : RealmObject, IEquatable<RulesetInfo>, IRulesetInfo
public class RulesetInfo : RealmObject, IEquatable<RulesetInfo>, IComparable<RulesetInfo>, IRulesetInfo
{
[PrimaryKey]
public string ShortName { get; set; } = string.Empty;
@ -47,7 +47,7 @@ namespace osu.Game.Rulesets
return ShortName == other.ShortName;
}
public bool Equals(IRulesetInfo? other) => other is RulesetInfo b && Equals(b);
public bool Equals(IRulesetInfo? other) => other is RulesetInfo r && Equals(r);
public int CompareTo(RulesetInfo other)
{
@ -63,6 +63,14 @@ namespace osu.Game.Rulesets
return string.Compare(ShortName, other.ShortName, StringComparison.Ordinal);
}
public int CompareTo(IRulesetInfo other)
{
if (!(other is RulesetInfo ruleset))
throw new ArgumentException($@"Object is not of type {nameof(RulesetInfo)}.", nameof(other));
return CompareTo(ruleset);
}
public override int GetHashCode()
{
// Importantly, ignore the underlying realm hash code, as it will usually not match.

View File

@ -28,7 +28,7 @@ namespace osu.Game.Rulesets.UI
public int RecordFrameRate = 60;
[Resolved(canBeNull: true)]
[Resolved]
private SpectatorClient spectatorClient { get; set; }
[Resolved]
@ -48,14 +48,13 @@ namespace osu.Game.Rulesets.UI
base.LoadComplete();
inputManager = GetContainingInputManager();
spectatorClient?.BeginPlaying(gameplayState, target);
spectatorClient.BeginPlaying(gameplayState, target);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
spectatorClient?.EndPlaying();
spectatorClient?.EndPlaying(gameplayState);
}
protected override void Update()

View File

@ -851,7 +851,7 @@ namespace osu.Game.Screens.Edit
var difficultyItems = new List<MenuItem>();
foreach (var rulesetBeatmaps in beatmapSet.Beatmaps.GroupBy(b => b.Ruleset.ShortName).OrderBy(group => group.Key))
foreach (var rulesetBeatmaps in beatmapSet.Beatmaps.GroupBy(b => b.Ruleset).OrderBy(group => group.Key))
{
if (difficultyItems.Count > 0)
difficultyItems.Add(new EditorMenuItemSpacer());

View File

@ -9,7 +9,7 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
public class MultiplayerPlayerLoader : PlayerLoader
{
public bool GameplayPassed => player?.GameplayPassed == true;
public bool GameplayPassed => player?.GameplayState.HasPassed == true;
private Player player;

View File

@ -207,15 +207,20 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
}
}
protected override void OnUserStateChanged(int userId, SpectatorState spectatorState)
protected override void OnNewPlayingUserState(int userId, SpectatorState spectatorState)
{
}
protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState)
=> instances.Single(i => i.UserId == userId).LoadScore(spectatorGameplayState.Score);
protected override void EndGameplay(int userId)
protected override void EndGameplay(int userId, SpectatorState state)
{
// Allowed passed/failed users to complete their remaining replay frames.
// The failed state isn't really possible in multiplayer (yet?) but is added here just for safety in case it starts being used.
if (state.State == SpectatedUserState.Passed || state.State == SpectatedUserState.Failed)
return;
RemoveUser(userId);
var instance = instances.Single(i => i.UserId == userId);

View File

@ -39,6 +39,21 @@ namespace osu.Game.Screens.Play
/// </summary>
public readonly Score Score;
/// <summary>
/// Whether gameplay completed without the user failing.
/// </summary>
public bool HasPassed { get; set; }
/// <summary>
/// Whether the user failed during gameplay.
/// </summary>
public bool HasFailed { get; set; }
/// <summary>
/// Whether the user quit gameplay without having either passed or failed.
/// </summary>
public bool HasQuit { get; set; }
/// <summary>
/// A bindable tracking the last judgement result applied to any hit object.
/// </summary>

View File

@ -72,15 +72,8 @@ namespace osu.Game.Screens.Play
/// </summary>
protected virtual bool PauseOnFocusLost => true;
/// <summary>
/// Whether gameplay has completed without the user having failed.
/// </summary>
public bool GameplayPassed { get; private set; }
public Action RestartRequested;
public bool HasFailed { get; private set; }
private Bindable<bool> mouseWheelDisabled;
private readonly Bindable<bool> storyboardReplacesBackground = new Bindable<bool>();
@ -560,7 +553,7 @@ namespace osu.Game.Screens.Play
if (showDialogFirst && !pauseOrFailDialogVisible)
{
// if the fail animation is currently in progress, accelerate it (it will show the pause dialog on completion).
if (ValidForResume && HasFailed)
if (ValidForResume && GameplayState.HasFailed)
{
failAnimationLayer.FinishTransforms(true);
return;
@ -679,7 +672,7 @@ namespace osu.Game.Screens.Play
resultsDisplayDelegate?.Cancel();
resultsDisplayDelegate = null;
GameplayPassed = false;
GameplayState.HasPassed = false;
ValidForResume = true;
skipOutroOverlay.Hide();
return;
@ -689,7 +682,7 @@ namespace osu.Game.Screens.Play
if (HealthProcessor.HasFailed)
return;
GameplayPassed = true;
GameplayState.HasPassed = true;
// Setting this early in the process means that even if something were to go wrong in the order of events following, there
// is no chance that a user could return to the (already completed) Player instance from a child screen.
@ -805,7 +798,7 @@ namespace osu.Game.Screens.Play
if (!CheckModsAllowFailure())
return false;
HasFailed = true;
GameplayState.HasFailed = true;
Score.ScoreInfo.Passed = false;
// There is a chance that we could be in a paused state as the ruleset's internal clock (see FrameStabilityContainer)
@ -860,13 +853,13 @@ namespace osu.Game.Screens.Play
// replays cannot be paused and exit immediately
&& !DrawableRuleset.HasReplayLoaded.Value
// cannot pause if we are already in a fail state
&& !HasFailed;
&& !GameplayState.HasFailed;
private bool canResume =>
// cannot resume from a non-paused state
GameplayClockContainer.IsPaused.Value
// cannot resume if we are already in a fail state
&& !HasFailed
&& !GameplayState.HasFailed
// already resuming
&& !IsResuming;
@ -991,6 +984,9 @@ namespace osu.Game.Screens.Play
public override bool OnExiting(IScreen next)
{
if (!GameplayState.HasPassed && !GameplayState.HasFailed)
GameplayState.HasQuit = true;
screenSuspension?.RemoveAndDisposeImmediately();
failAnimationLayer?.RemoveFilters();
@ -1005,7 +1001,7 @@ namespace osu.Game.Screens.Play
// EndPlaying() is typically called from ReplayRecorder.Dispose(). Disposal is currently asynchronous.
// To resolve test failures, forcefully end playing synchronously when this screen exits.
// Todo: Replace this with a more permanent solution once osu-framework has a synchronous cleanup method.
spectatorClient.EndPlaying();
spectatorClient.EndPlaying(GameplayState);
// GameplayClockContainer performs seeks / start / stop operations on the beatmap's track.
// as we are no longer the current screen, we cannot guarantee the track is still usable.

View File

@ -34,7 +34,7 @@ namespace osu.Game.Screens.Play
protected override APIRequest<MultiplayerScore> CreateSubmissionRequest(Score score, long token)
{
Debug.Assert(Room.RoomID.Value != null);
return new SubmitRoomScoreRequest(token, Room.RoomID.Value.Value, PlaylistItem.ID, score.ScoreInfo);
return new SubmitRoomScoreRequest(score.ScoreInfo, token, Room.RoomID.Value.Value, PlaylistItem.ID);
}
}
}

View File

@ -46,7 +46,7 @@ namespace osu.Game.Screens.Play
Debug.Assert(beatmap.OnlineID > 0);
return new SubmitSoloScoreRequest(beatmap.OnlineID, token, score.ScoreInfo);
return new SubmitSoloScoreRequest(score.ScoreInfo, token, beatmap.OnlineID);
}
}
}

View File

@ -166,7 +166,7 @@ namespace osu.Game.Screens.Play
automaticDownload.Current.BindValueChanged(_ => checkForAutomaticDownload());
}
protected override void OnUserStateChanged(int userId, SpectatorState spectatorState)
protected override void OnNewPlayingUserState(int userId, SpectatorState spectatorState)
{
clearDisplay();
showBeatmapPanel(spectatorState);
@ -180,7 +180,7 @@ namespace osu.Game.Screens.Play
scheduleStart(spectatorGameplayState);
}
protected override void EndGameplay(int userId)
protected override void EndGameplay(int userId, SpectatorState state)
{
scheduledStart?.Cancel();
immediateSpectatorGameplayState = null;

View File

@ -87,7 +87,7 @@ namespace osu.Game.Screens.Select.Carousel
var beatmaps = carouselSet.Beatmaps.ToList();
return beatmaps.Count > maximum_difficulty_icons
? (IEnumerable<DifficultyIcon>)beatmaps.GroupBy(b => b.BeatmapInfo.Ruleset.ShortName)
? (IEnumerable<DifficultyIcon>)beatmaps.GroupBy(b => b.BeatmapInfo.Ruleset)
.Select(group => new FilterableGroupedDifficultyIcon(group.ToList(), group.Last().BeatmapInfo.Ruleset))
: beatmaps.Select(b => new FilterableDifficultyIcon(b));
}

View File

@ -42,7 +42,7 @@ namespace osu.Game.Screens.Spectate
[Resolved]
private UserLookupCache userLookupCache { get; set; }
private readonly IBindableDictionary<int, SpectatorState> playingUserStates = new BindableDictionary<int, SpectatorState>();
private readonly IBindableDictionary<int, SpectatorState> userStates = new BindableDictionary<int, SpectatorState>();
private readonly Dictionary<int, APIUser> userMap = new Dictionary<int, APIUser>();
private readonly Dictionary<int, SpectatorGameplayState> gameplayStates = new Dictionary<int, SpectatorGameplayState>();
@ -77,8 +77,8 @@ namespace osu.Game.Screens.Spectate
userMap[u.Id] = u;
}
playingUserStates.BindTo(spectatorClient.PlayingUserStates);
playingUserStates.BindCollectionChanged(onPlayingUserStatesChanged, true);
userStates.BindTo(spectatorClient.WatchedUserStates);
userStates.BindCollectionChanged(onUserStatesChanged, true);
realmSubscription = realm.RegisterForNotifications(
realm => realm.All<BeatmapSetInfo>().Where(s => !s.DeletePending), beatmapsChanged);
@ -99,51 +99,55 @@ namespace osu.Game.Screens.Spectate
{
foreach ((int userId, _) in userMap)
{
if (!playingUserStates.TryGetValue(userId, out var userState))
if (!userStates.TryGetValue(userId, out var userState))
continue;
if (beatmapSet.Beatmaps.Any(b => b.OnlineID == userState.BeatmapID))
updateGameplayState(userId);
startGameplay(userId);
}
}
private void onPlayingUserStatesChanged(object sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e)
private void onUserStatesChanged(object sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e)
{
switch (e.Action)
{
case NotifyDictionaryChangedAction.Add:
case NotifyDictionaryChangedAction.Replace:
foreach ((int userId, var state) in e.NewItems.AsNonNull())
onUserStateAdded(userId, state);
onUserStateChanged(userId, state);
break;
case NotifyDictionaryChangedAction.Remove:
foreach ((int userId, var _) in e.OldItems.AsNonNull())
onUserStateRemoved(userId);
break;
case NotifyDictionaryChangedAction.Replace:
foreach ((int userId, var _) in e.OldItems.AsNonNull())
onUserStateRemoved(userId);
foreach ((int userId, var state) in e.NewItems.AsNonNull())
onUserStateAdded(userId, state);
foreach ((int userId, SpectatorState state) in e.OldItems.AsNonNull())
onUserStateRemoved(userId, state);
break;
}
}
private void onUserStateAdded(int userId, SpectatorState state)
private void onUserStateChanged(int userId, SpectatorState newState)
{
if (state.RulesetID == null || state.BeatmapID == null)
if (newState.RulesetID == null || newState.BeatmapID == null)
return;
if (!userMap.ContainsKey(userId))
return;
Schedule(() => OnUserStateChanged(userId, state));
updateGameplayState(userId);
switch (newState.State)
{
case SpectatedUserState.Passed:
// Make sure that gameplay completes to the end.
if (gameplayStates.TryGetValue(userId, out var gameplayState))
gameplayState.Score.Replay.HasReceivedAllFrames = true;
break;
case SpectatedUserState.Playing:
Schedule(() => OnNewPlayingUserState(userId, newState));
startGameplay(userId);
break;
}
}
private void onUserStateRemoved(int userId)
private void onUserStateRemoved(int userId, SpectatorState state)
{
if (!userMap.ContainsKey(userId))
return;
@ -154,15 +158,15 @@ namespace osu.Game.Screens.Spectate
gameplayState.Score.Replay.HasReceivedAllFrames = true;
gameplayStates.Remove(userId);
Schedule(() => EndGameplay(userId));
Schedule(() => EndGameplay(userId, state));
}
private void updateGameplayState(int userId)
private void startGameplay(int userId)
{
Debug.Assert(userMap.ContainsKey(userId));
var user = userMap[userId];
var spectatorState = playingUserStates[userId];
var spectatorState = userStates[userId];
var resolvedRuleset = rulesets.AvailableRulesets.FirstOrDefault(r => r.OnlineID == spectatorState.RulesetID)?.CreateInstance();
if (resolvedRuleset == null)
@ -191,11 +195,11 @@ namespace osu.Game.Screens.Spectate
}
/// <summary>
/// Invoked when a spectated user's state has changed.
/// Invoked when a spectated user's state has changed to a new state indicating the player is currently playing.
/// </summary>
/// <param name="userId">The user whose state has changed.</param>
/// <param name="spectatorState">The new state.</param>
protected abstract void OnUserStateChanged(int userId, [NotNull] SpectatorState spectatorState);
protected abstract void OnNewPlayingUserState(int userId, [NotNull] SpectatorState spectatorState);
/// <summary>
/// Starts gameplay for a user.
@ -208,7 +212,8 @@ namespace osu.Game.Screens.Spectate
/// Ends gameplay for a user.
/// </summary>
/// <param name="userId">The user to end gameplay for.</param>
protected abstract void EndGameplay(int userId);
/// <param name="state">The final user state.</param>
protected abstract void EndGameplay(int userId, SpectatorState state);
/// <summary>
/// Stops spectating a user.
@ -216,7 +221,10 @@ namespace osu.Game.Screens.Spectate
/// <param name="userId">The user to stop spectating.</param>
protected void RemoveUser(int userId)
{
onUserStateRemoved(userId);
if (!userStates.TryGetValue(userId, out var state))
return;
onUserStateRemoved(userId, state);
users.Remove(userId);
userMap.Remove(userId);

View File

@ -58,7 +58,8 @@ namespace osu.Game.Tests.Visual.Spectator
/// Ends play for an arbitrary user.
/// </summary>
/// <param name="userId">The user to end play for.</param>
public void EndPlay(int userId)
/// <param name="state">The spectator state to end play with.</param>
public void EndPlay(int userId, SpectatedUserState state = SpectatedUserState.Quit)
{
if (!userBeatmapDictionary.ContainsKey(userId))
return;
@ -67,6 +68,7 @@ namespace osu.Game.Tests.Visual.Spectator
{
BeatmapID = userBeatmapDictionary[userId],
RulesetID = 0,
State = state
});
userBeatmapDictionary.Remove(userId);
@ -142,6 +144,7 @@ namespace osu.Game.Tests.Visual.Spectator
{
BeatmapID = userBeatmapDictionary[userId],
RulesetID = 0,
State = SpectatedUserState.Playing
});
}
}

View File

@ -37,7 +37,7 @@
</PackageReference>
<PackageReference Include="Realm" Version="10.8.0" />
<PackageReference Include="ppy.osu.Framework" Version="2022.204.0" />
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.204.0" />
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.211.0" />
<PackageReference Include="Sentry" Version="3.13.0" />
<PackageReference Include="SharpCompress" Version="0.30.1" />
<PackageReference Include="NUnit" Version="3.13.2" />

View File

@ -61,7 +61,7 @@
</ItemGroup>
<ItemGroup Label="Package References">
<PackageReference Include="ppy.osu.Framework.iOS" Version="2022.204.0" />
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.204.0" />
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.211.0" />
</ItemGroup>
<!-- See https://github.com/dotnet/runtime/issues/35988 (can be removed after Xamarin uses net6.0) -->
<PropertyGroup>