1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-14 11:42:56 +08:00

Merge branch 'master' into circular-arc-freeze

This commit is contained in:
Naxess 2021-04-01 17:09:45 +02:00 committed by GitHub
commit 7e47922fb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
149 changed files with 1688 additions and 691 deletions

View File

@ -1,7 +1,18 @@
--- ---
name: Bug Report name: Bug Report
about: Issues regarding encountered bugs. about: Report a bug or crash to desktop
--- ---
<!--
IMPORTANT: Your issue may already be reported.
Please check:
- Pinned issues, at the top of https://github.com/ppy/osu/issues
- Current priority 0 issues at https://github.com/ppy/osu/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Apriority%3A0
- Search for your issue. If you find that it already exists, please respond with a reaction or add any further information that may be helpful.
-->
**Describe the bug:** **Describe the bug:**
**Screenshots or videos showing encountered issue:** **Screenshots or videos showing encountered issue:**
@ -9,6 +20,7 @@ about: Issues regarding encountered bugs.
**osu!lazer version:** **osu!lazer version:**
**Logs:** **Logs:**
<!-- <!--
*please attach logs here, which are located at:* *please attach logs here, which are located at:*
- `%AppData%/osu/logs` *(on Windows),* - `%AppData%/osu/logs` *(on Windows),*

View File

@ -1,20 +0,0 @@
---
name: Crash Report
about: Issues regarding crashes or permanent freezes.
---
**Describe the crash:**
**Screenshots or videos showing encountered issue:**
**osu!lazer version:**
**Logs:**
<!--
*please attach logs here, which are located at:*
- `%AppData%/osu/logs` *(on Windows),*
- `~/.local/share/osu/logs` *(on Linux & macOS).*
- `Android/Data/sh.ppy.osulazer/logs` *(on Android)*,
- on iOS they can be obtained by connecting your device to your desktop and copying the `logs` directory from the app's own document storage using iTunes. (https://support.apple.com/en-us/HT201301#copy-to-computer)
-->
**Computer Specifications:**

View File

@ -1,6 +1,6 @@
--- ---
name: Feature Request name: Feature Request
about: Features you would like to see in the game! about: Propose a feature you would like to see in the game!
--- ---
**Describe the new feature:** **Describe the new feature:**

View File

@ -1,20 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="osu! (legacy osuTK)" type="DotNetProject" factoryName=".NET Project" folderName="osu!" activateToolWindowBeforeRun="false">
<option name="EXE_PATH" value="$PROJECT_DIR$/osu.Desktop/bin/Debug/net5.0/osu!.dll" />
<option name="PROGRAM_PARAMETERS" value="--tk" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/osu.Desktop/bin/Debug/net5.0" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/osu.Desktop/osu.Desktop.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net5.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>

View File

@ -52,6 +52,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="ppy.osu.Game.Resources" Version="2021.211.1" /> <PackageReference Include="ppy.osu.Game.Resources" Version="2021.211.1" />
<PackageReference Include="ppy.osu.Framework.Android" Version="2021.317.0" /> <PackageReference Include="ppy.osu.Framework.Android" Version="2021.330.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -53,5 +53,10 @@
<ItemGroup> <ItemGroup>
<AndroidResource Include="Resources\drawable\lazer.png" /> <AndroidResource Include="Resources\drawable\lazer.png" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="System.Formats.Asn1">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project> </Project>

View File

@ -2,6 +2,7 @@
// 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 System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@ -18,6 +19,7 @@ using osu.Framework.Screens;
using osu.Game.Screens.Menu; using osu.Game.Screens.Menu;
using osu.Game.Updater; using osu.Game.Updater;
using osu.Desktop.Windows; using osu.Desktop.Windows;
using osu.Framework.Threading;
using osu.Game.IO; using osu.Game.IO;
namespace osu.Desktop namespace osu.Desktop
@ -144,13 +146,39 @@ namespace osu.Desktop
desktopWindow.DragDrop += f => fileDrop(new[] { f }); desktopWindow.DragDrop += f => fileDrop(new[] { f });
} }
private readonly List<string> importableFiles = new List<string>();
private ScheduledDelegate importSchedule;
private void fileDrop(string[] filePaths) private void fileDrop(string[] filePaths)
{
lock (importableFiles)
{ {
var firstExtension = Path.GetExtension(filePaths.First()); var firstExtension = Path.GetExtension(filePaths.First());
if (filePaths.Any(f => Path.GetExtension(f) != firstExtension)) return; if (filePaths.Any(f => Path.GetExtension(f) != firstExtension)) return;
Task.Factory.StartNew(() => Import(filePaths), TaskCreationOptions.LongRunning); importableFiles.AddRange(filePaths);
Logger.Log($"Adding {filePaths.Length} files for import");
// File drag drop operations can potentially trigger hundreds or thousands of these calls on some platforms.
// In order to avoid spawning multiple import tasks for a single drop operation, debounce a touch.
importSchedule?.Cancel();
importSchedule = Scheduler.AddDelayed(handlePendingImports, 100);
}
}
private void handlePendingImports()
{
lock (importableFiles)
{
Logger.Log($"Handling batch import of {importableFiles.Count} files");
var paths = importableFiles.ToArray();
importableFiles.Clear();
Task.Factory.StartNew(() => Import(paths), TaskCreationOptions.LongRunning);
}
} }
} }
} }

View File

@ -27,8 +27,8 @@
<PackageReference Include="Microsoft.NETCore.Targets" Version="5.0.0" /> <PackageReference Include="Microsoft.NETCore.Targets" Version="5.0.0" />
<PackageReference Include="System.IO.Packaging" Version="5.0.0" /> <PackageReference Include="System.IO.Packaging" Version="5.0.0" />
<PackageReference Include="ppy.squirrel.windows" Version="1.9.0.5" /> <PackageReference Include="ppy.squirrel.windows" Version="1.9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.6" />
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" /> <PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageReference Include="DiscordRichPresence" Version="1.0.175" /> <PackageReference Include="DiscordRichPresence" Version="1.0.175" />
</ItemGroup> </ItemGroup>

View File

@ -35,5 +35,10 @@
<Name>osu.Game</Name> <Name>osu.Game</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="System.Formats.Asn1">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project> </Project>

View File

@ -5,7 +5,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
<PackageReference Include="NUnit" Version="3.13.1" /> <PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Project"> <PropertyGroup Label="Project">
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>

View File

@ -3,13 +3,16 @@
using System.Linq; using System.Linq;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Objects.Drawables; using osu.Game.Rulesets.Catch.Objects.Drawables;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Mods namespace osu.Game.Rulesets.Catch.Mods
{ {
public class CatchModHidden : ModHidden public class CatchModHidden : ModHidden, IApplicableToDrawableRuleset<CatchHitObject>
{ {
public override string Description => @"Play with fading fruits."; public override string Description => @"Play with fading fruits.";
public override double ScoreMultiplier => 1.06; public override double ScoreMultiplier => 1.06;
@ -17,6 +20,14 @@ namespace osu.Game.Rulesets.Catch.Mods
private const double fade_out_offset_multiplier = 0.6; private const double fade_out_offset_multiplier = 0.6;
private const double fade_out_duration_multiplier = 0.44; private const double fade_out_duration_multiplier = 0.44;
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset)
{
var drawableCatchRuleset = (DrawableCatchRuleset)drawableRuleset;
var catchPlayfield = (CatchPlayfield)drawableCatchRuleset.Playfield;
catchPlayfield.CatcherArea.MovableCatcher.CatchFruitOnPlate = false;
}
protected override void ApplyNormalVisibilityState(DrawableHitObject hitObject, ArmedState state) protected override void ApplyNormalVisibilityState(DrawableHitObject hitObject, ArmedState state)
{ {
base.ApplyNormalVisibilityState(hitObject, state); base.ApplyNormalVisibilityState(hitObject, state);

View File

@ -5,7 +5,6 @@ using osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Game.Skinning; using osu.Game.Skinning;
using osuTK.Graphics; using osuTK.Graphics;
using static osu.Game.Skinning.LegacySkinConfiguration;
namespace osu.Game.Rulesets.Catch.Skinning.Legacy namespace osu.Game.Rulesets.Catch.Skinning.Legacy
{ {
@ -14,7 +13,7 @@ namespace osu.Game.Rulesets.Catch.Skinning.Legacy
/// <summary> /// <summary>
/// For simplicity, let's use legacy combo font texture existence as a way to identify legacy skins from default. /// For simplicity, let's use legacy combo font texture existence as a way to identify legacy skins from default.
/// </summary> /// </summary>
private bool providesComboCounter => this.HasFont(GetConfig<LegacySetting, string>(LegacySetting.ComboPrefix)?.Value ?? "score"); private bool providesComboCounter => this.HasFont(LegacyFont.Combo);
public CatchLegacySkinTransformer(ISkinSource source) public CatchLegacySkinTransformer(ISkinSource source)
: base(source) : base(source)
@ -69,7 +68,6 @@ namespace osu.Game.Rulesets.Catch.Skinning.Legacy
this.GetAnimation("fruit-ryuuta", true, true, true); this.GetAnimation("fruit-ryuuta", true, true, true);
case CatchSkinComponents.CatchComboCounter: case CatchSkinComponents.CatchComboCounter:
if (providesComboCounter) if (providesComboCounter)
return new LegacyCatchComboCounter(Source); return new LegacyCatchComboCounter(Source);

View File

@ -7,7 +7,6 @@ using osu.Game.Rulesets.Catch.UI;
using osu.Game.Skinning; using osu.Game.Skinning;
using osuTK; using osuTK;
using osuTK.Graphics; using osuTK.Graphics;
using static osu.Game.Skinning.LegacySkinConfiguration;
namespace osu.Game.Rulesets.Catch.Skinning.Legacy namespace osu.Game.Rulesets.Catch.Skinning.Legacy
{ {
@ -22,9 +21,6 @@ namespace osu.Game.Rulesets.Catch.Skinning.Legacy
public LegacyCatchComboCounter(ISkin skin) public LegacyCatchComboCounter(ISkin skin)
{ {
var fontName = skin.GetConfig<LegacySetting, string>(LegacySetting.ComboPrefix)?.Value ?? "score";
var fontOverlap = skin.GetConfig<LegacySetting, float>(LegacySetting.ComboOverlap)?.Value ?? -2f;
AutoSizeAxes = Axes.Both; AutoSizeAxes = Axes.Both;
Alpha = 0f; Alpha = 0f;
@ -34,7 +30,7 @@ namespace osu.Game.Rulesets.Catch.Skinning.Legacy
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{ {
explosion = new LegacyRollingCounter(skin, fontName, fontOverlap) explosion = new LegacyRollingCounter(skin, LegacyFont.Combo)
{ {
Alpha = 0.65f, Alpha = 0.65f,
Blending = BlendingParameters.Additive, Blending = BlendingParameters.Additive,
@ -42,7 +38,7 @@ namespace osu.Game.Rulesets.Catch.Skinning.Legacy
Origin = Anchor.Centre, Origin = Anchor.Centre,
Scale = new Vector2(1.5f), Scale = new Vector2(1.5f),
}, },
counter = new LegacyRollingCounter(skin, fontName, fontOverlap) counter = new LegacyRollingCounter(skin, LegacyFont.Combo)
{ {
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,

View File

@ -43,6 +43,11 @@ namespace osu.Game.Rulesets.Catch.UI
/// </summary> /// </summary>
public bool HyperDashing => hyperDashModifier != 1; public bool HyperDashing => hyperDashModifier != 1;
/// <summary>
/// Whether <see cref="DrawablePalpableCatchHitObject"/> fruit should appear on the plate.
/// </summary>
public bool CatchFruitOnPlate { get; set; } = true;
/// <summary> /// <summary>
/// The relative space to cover in 1 millisecond. based on 1 game pixel per millisecond as in osu-stable. /// The relative space to cover in 1 millisecond. based on 1 game pixel per millisecond as in osu-stable.
/// </summary> /// </summary>
@ -237,6 +242,7 @@ namespace osu.Game.Rulesets.Catch.UI
{ {
var positionInStack = computePositionInStack(new Vector2(palpableObject.X - X, 0), palpableObject.DisplaySize.X / 2); var positionInStack = computePositionInStack(new Vector2(palpableObject.X - X, 0), palpableObject.DisplaySize.X / 2);
if (CatchFruitOnPlate)
placeCaughtObject(palpableObject, positionInStack); placeCaughtObject(palpableObject, positionInStack);
if (hitLighting.Value) if (hitLighting.Value)

View File

@ -35,5 +35,10 @@
<Name>osu.Game</Name> <Name>osu.Game</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="System.Formats.Asn1">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project> </Project>

View File

@ -56,7 +56,7 @@ namespace osu.Game.Rulesets.Mania.Tests
Assert.IsTrue(generated.Frames.Count == frame_offset + 2, "Replay must have 3 frames"); Assert.IsTrue(generated.Frames.Count == frame_offset + 2, "Replay must have 3 frames");
Assert.AreEqual(1000, generated.Frames[frame_offset].Time, "Incorrect hit time"); Assert.AreEqual(1000, generated.Frames[frame_offset].Time, "Incorrect hit time");
Assert.AreEqual(3000 + ManiaAutoGenerator.RELEASE_DELAY, generated.Frames[frame_offset + 1].Time, "Incorrect release time"); Assert.AreEqual(3000, generated.Frames[frame_offset + 1].Time, "Incorrect release time");
Assert.IsTrue(checkContains(generated.Frames[frame_offset], ManiaAction.Special1), "Special1 has not been pressed"); Assert.IsTrue(checkContains(generated.Frames[frame_offset], ManiaAction.Special1), "Special1 has not been pressed");
Assert.IsFalse(checkContains(generated.Frames[frame_offset + 1], ManiaAction.Special1), "Special1 has not been released"); Assert.IsFalse(checkContains(generated.Frames[frame_offset + 1], ManiaAction.Special1), "Special1 has not been released");
} }
@ -99,7 +99,7 @@ namespace osu.Game.Rulesets.Mania.Tests
Assert.IsTrue(generated.Frames.Count == frame_offset + 2, "Replay must have 3 frames"); Assert.IsTrue(generated.Frames.Count == frame_offset + 2, "Replay must have 3 frames");
Assert.AreEqual(1000, generated.Frames[frame_offset].Time, "Incorrect hit time"); Assert.AreEqual(1000, generated.Frames[frame_offset].Time, "Incorrect hit time");
Assert.AreEqual(3000 + ManiaAutoGenerator.RELEASE_DELAY, generated.Frames[frame_offset + 1].Time, "Incorrect release time"); Assert.AreEqual(3000, generated.Frames[frame_offset + 1].Time, "Incorrect release time");
Assert.IsTrue(checkContains(generated.Frames[frame_offset], ManiaAction.Key1, ManiaAction.Key2), "Key1 & Key2 have not been pressed"); Assert.IsTrue(checkContains(generated.Frames[frame_offset], ManiaAction.Key1, ManiaAction.Key2), "Key1 & Key2 have not been pressed");
Assert.IsFalse(checkContains(generated.Frames[frame_offset + 1], ManiaAction.Key1, ManiaAction.Key2), "Key1 & Key2 have not been released"); Assert.IsFalse(checkContains(generated.Frames[frame_offset + 1], ManiaAction.Key1, ManiaAction.Key2), "Key1 & Key2 have not been released");
@ -148,9 +148,9 @@ namespace osu.Game.Rulesets.Mania.Tests
Assert.IsTrue(generated.Frames.Count == frame_offset + 4, "Replay must have 4 generated frames"); Assert.IsTrue(generated.Frames.Count == frame_offset + 4, "Replay must have 4 generated frames");
Assert.AreEqual(1000, generated.Frames[frame_offset].Time, "Incorrect first note hit time"); Assert.AreEqual(1000, generated.Frames[frame_offset].Time, "Incorrect first note hit time");
Assert.AreEqual(3000 + ManiaAutoGenerator.RELEASE_DELAY, generated.Frames[frame_offset + 2].Time, "Incorrect first note release time"); Assert.AreEqual(3000, generated.Frames[frame_offset + 2].Time, "Incorrect first note release time");
Assert.AreEqual(2000, generated.Frames[frame_offset + 1].Time, "Incorrect second note hit time"); Assert.AreEqual(2000, generated.Frames[frame_offset + 1].Time, "Incorrect second note hit time");
Assert.AreEqual(4000 + ManiaAutoGenerator.RELEASE_DELAY, generated.Frames[frame_offset + 3].Time, "Incorrect second note release time"); Assert.AreEqual(4000, generated.Frames[frame_offset + 3].Time, "Incorrect second note release time");
Assert.IsTrue(checkContains(generated.Frames[frame_offset], ManiaAction.Key1), "Key1 has not been pressed"); Assert.IsTrue(checkContains(generated.Frames[frame_offset], ManiaAction.Key1), "Key1 has not been pressed");
Assert.IsTrue(checkContains(generated.Frames[frame_offset + 1], ManiaAction.Key1, ManiaAction.Key2), "Key1 & Key2 have not been pressed"); Assert.IsTrue(checkContains(generated.Frames[frame_offset + 1], ManiaAction.Key1, ManiaAction.Key2), "Key1 & Key2 have not been pressed");
Assert.IsFalse(checkContains(generated.Frames[frame_offset + 2], ManiaAction.Key1), "Key1 has not been released"); Assert.IsFalse(checkContains(generated.Frames[frame_offset + 2], ManiaAction.Key1), "Key1 has not been released");
@ -168,7 +168,7 @@ namespace osu.Game.Rulesets.Mania.Tests
// | | | // | | |
var beatmap = new ManiaBeatmap(new StageDefinition { Columns = 2 }); var beatmap = new ManiaBeatmap(new StageDefinition { Columns = 2 });
beatmap.HitObjects.Add(new HoldNote { StartTime = 1000, Duration = 2000 - ManiaAutoGenerator.RELEASE_DELAY }); beatmap.HitObjects.Add(new HoldNote { StartTime = 1000, Duration = 2000 });
beatmap.HitObjects.Add(new Note { StartTime = 3000, Column = 1 }); beatmap.HitObjects.Add(new Note { StartTime = 3000, Column = 1 });
var generated = new ManiaAutoGenerator(beatmap).Generate(); var generated = new ManiaAutoGenerator(beatmap).Generate();

View File

@ -5,11 +5,13 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Screens; using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Beatmaps; using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Replays; using osu.Game.Replays;
using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Replays; using osu.Game.Rulesets.Mania.Replays;
using osu.Game.Rulesets.Mania.Scoring; using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects;
@ -286,17 +288,56 @@ namespace osu.Game.Rulesets.Mania.Tests
.All(j => j.Type.IsHit())); .All(j => j.Type.IsHit()));
} }
[Test]
public void TestHitTailBeforeLastTick()
{
const int tick_rate = 8;
const double tick_spacing = TimingControlPoint.DEFAULT_BEAT_LENGTH / tick_rate;
const double time_last_tick = time_head + tick_spacing * (int)((time_tail - time_head) / tick_spacing - 1);
var beatmap = new Beatmap<ManiaHitObject>
{
HitObjects =
{
new HoldNote
{
StartTime = time_head,
Duration = time_tail - time_head,
Column = 0,
}
},
BeatmapInfo =
{
BaseDifficulty = new BeatmapDifficulty { SliderTickRate = tick_rate },
Ruleset = new ManiaRuleset().RulesetInfo
},
};
performTest(new List<ReplayFrame>
{
new ManiaReplayFrame(time_head, ManiaAction.Key1),
new ManiaReplayFrame(time_last_tick - 5)
}, beatmap);
assertHeadJudgement(HitResult.Perfect);
assertLastTickJudgement(HitResult.LargeTickMiss);
assertTailJudgement(HitResult.Ok);
}
private void assertHeadJudgement(HitResult result) private void assertHeadJudgement(HitResult result)
=> AddAssert($"head judged as {result}", () => judgementResults[0].Type == result); => AddAssert($"head judged as {result}", () => judgementResults.First(j => j.HitObject is Note).Type == result);
private void assertTailJudgement(HitResult result) private void assertTailJudgement(HitResult result)
=> AddAssert($"tail judged as {result}", () => judgementResults[^2].Type == result); => AddAssert($"tail judged as {result}", () => judgementResults.Single(j => j.HitObject is TailNote).Type == result);
private void assertNoteJudgement(HitResult result) private void assertNoteJudgement(HitResult result)
=> AddAssert($"hold note judged as {result}", () => judgementResults[^1].Type == result); => AddAssert($"hold note judged as {result}", () => judgementResults.Single(j => j.HitObject is HoldNote).Type == result);
private void assertTickJudgement(HitResult result) private void assertTickJudgement(HitResult result)
=> AddAssert($"tick judged as {result}", () => judgementResults[6].Type == result); // arbitrary tick => AddAssert($"any tick judged as {result}", () => judgementResults.Where(j => j.HitObject is HoldNoteTick).Any(j => j.Type == result));
private void assertLastTickJudgement(HitResult result)
=> AddAssert($"last tick judged as {result}", () => judgementResults.Last(j => j.HitObject is HoldNoteTick).Type == result);
private ScoreAccessibleReplayPlayer currentPlayer; private ScoreAccessibleReplayPlayer currentPlayer;
@ -345,6 +386,14 @@ namespace osu.Game.Rulesets.Mania.Tests
AddUntilStep("Beatmap at 0", () => Beatmap.Value.Track.CurrentTime == 0); AddUntilStep("Beatmap at 0", () => Beatmap.Value.Track.CurrentTime == 0);
AddUntilStep("Wait until player is loaded", () => currentPlayer.IsCurrentScreen()); AddUntilStep("Wait until player is loaded", () => currentPlayer.IsCurrentScreen());
AddUntilStep("wait for head", () => currentPlayer.GameplayClockContainer.GameplayClock.CurrentTime >= time_head);
AddAssert("head is visible",
() => currentPlayer.ChildrenOfType<DrawableHoldNote>()
.Single(note => note.HitObject == beatmap.HitObjects[0])
.Head
.Alpha == 1);
AddUntilStep("Wait for completion", () => currentPlayer.ScoreProcessor.HasCompleted.Value); AddUntilStep("Wait for completion", () => currentPlayer.ScoreProcessor.HasCompleted.Value);
} }
@ -352,6 +401,8 @@ namespace osu.Game.Rulesets.Mania.Tests
{ {
public new ScoreProcessor ScoreProcessor => base.ScoreProcessor; public new ScoreProcessor ScoreProcessor => base.ScoreProcessor;
public new GameplayClockContainer GameplayClockContainer => base.GameplayClockContainer;
protected override bool PauseOnFocusLost => false; protected override bool PauseOnFocusLost => false;
public ScoreAccessibleReplayPlayer(Score score) public ScoreAccessibleReplayPlayer(Score score)

View File

@ -5,7 +5,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
<PackageReference Include="NUnit" Version="3.13.1" /> <PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Project"> <PropertyGroup Label="Project">
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>

View File

@ -47,7 +47,7 @@ namespace osu.Game.Rulesets.Mania.Beatmaps
if (IsForCurrentRuleset) if (IsForCurrentRuleset)
{ {
TargetColumns = (int)Math.Max(1, roundedCircleSize); TargetColumns = GetColumnCountForNonConvert(beatmap.BeatmapInfo);
if (TargetColumns > ManiaRuleset.MAX_STAGE_KEYS) if (TargetColumns > ManiaRuleset.MAX_STAGE_KEYS)
{ {
@ -71,6 +71,12 @@ namespace osu.Game.Rulesets.Mania.Beatmaps
originalTargetColumns = TargetColumns; originalTargetColumns = TargetColumns;
} }
public static int GetColumnCountForNonConvert(BeatmapInfo beatmap)
{
var roundedCircleSize = Math.Round(beatmap.BaseDifficulty.CircleSize);
return (int)Math.Max(1, roundedCircleSize);
}
public override bool CanConvert() => Beatmap.HitObjects.All(h => h is IHasXPosition); public override bool CanConvert() => Beatmap.HitObjects.All(h => h is IHasXPosition);
protected override Beatmap<ManiaHitObject> ConvertBeatmap(IBeatmap original, CancellationToken cancellationToken) protected override Beatmap<ManiaHitObject> ConvertBeatmap(IBeatmap original, CancellationToken cancellationToken)

View File

@ -119,5 +119,8 @@ namespace osu.Game.Rulesets.Mania.Edit
beatSnapGrid.SelectionTimeRange = null; beatSnapGrid.SelectionTimeRange = null;
} }
} }
public override string ConvertSelectionToString()
=> string.Join(',', EditorBeatmap.SelectedHitObjects.Cast<ManiaHitObject>().OrderBy(h => h.StartTime).Select(h => $"{h.StartTime}|{h.Column}"));
} }
} }

View File

@ -0,0 +1,33 @@
// 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 osu.Game.Beatmaps;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Rulesets.Mania
{
public class ManiaFilterCriteria : IRulesetFilterCriteria
{
private FilterCriteria.OptionalRange<float> keys;
public bool Matches(BeatmapInfo beatmap)
{
return !keys.HasFilter || (beatmap.RulesetID == new ManiaRuleset().LegacyID && keys.IsInRange(ManiaBeatmapConverter.GetColumnCountForNonConvert(beatmap)));
}
public bool TryParseCustomKeywordCriteria(string key, Operator op, string value)
{
switch (key)
{
case "key":
case "keys":
return FilterQueryParser.TryUpdateCriteriaRange(ref keys, op, value);
}
return false;
}
}
}

View File

@ -22,6 +22,7 @@ using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.Mania.Configuration;
using osu.Game.Rulesets.Mania.Difficulty; using osu.Game.Rulesets.Mania.Difficulty;
@ -382,6 +383,11 @@ namespace osu.Game.Rulesets.Mania
} }
} }
}; };
public override IRulesetFilterCriteria CreateRulesetFilterCriteria()
{
return new ManiaFilterCriteria();
}
} }
public enum PlayfieldType public enum PlayfieldType

View File

@ -233,6 +233,12 @@ namespace osu.Game.Rulesets.Mania.Objects.Drawables
{ {
if (Tail.AllJudged) if (Tail.AllJudged)
{ {
foreach (var tick in tickContainer)
{
if (!tick.Judged)
tick.MissForcefully();
}
ApplyResult(r => r.Type = r.Judgement.MaxResult); ApplyResult(r => r.Type = r.Judgement.MaxResult);
endHold(); endHold();
} }

View File

@ -1,6 +1,8 @@
// 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 osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Objects.Drawables namespace osu.Game.Rulesets.Mania.Objects.Drawables
{ {
/// <summary> /// <summary>
@ -25,6 +27,14 @@ namespace osu.Game.Rulesets.Mania.Objects.Drawables
LifetimeEnd = LifetimeStart + 30000; LifetimeEnd = LifetimeStart + 30000;
} }
protected override void UpdateHitStateTransforms(ArmedState state)
{
// suppress the base call explicitly.
// the hold note head should never change its visual state on its own due to the "freezing" mechanic
// (when hit, it remains visible in place at the judgement line; when dropped, it will scroll past the line).
// it will be hidden along with its parenting hold note when required.
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override void OnReleased(ManiaAction action) public override void OnReleased(ManiaAction action)

View File

@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using osu.Game.Replays; using osu.Game.Replays;
using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Replays;
@ -85,20 +86,28 @@ namespace osu.Game.Rulesets.Mania.Replays
{ {
var currentObject = Beatmap.HitObjects[i]; var currentObject = Beatmap.HitObjects[i];
var nextObjectInColumn = GetNextObject(i); // Get the next object that requires pressing the same button var nextObjectInColumn = GetNextObject(i); // Get the next object that requires pressing the same button
var releaseTime = calculateReleaseTime(currentObject, nextObjectInColumn);
double endTime = currentObject.GetEndTime();
bool canDelayKeyUp = nextObjectInColumn == null ||
nextObjectInColumn.StartTime > endTime + RELEASE_DELAY;
double calculatedDelay = canDelayKeyUp ? RELEASE_DELAY : (nextObjectInColumn.StartTime - endTime) * 0.9;
yield return new HitPoint { Time = currentObject.StartTime, Column = currentObject.Column }; yield return new HitPoint { Time = currentObject.StartTime, Column = currentObject.Column };
yield return new ReleasePoint { Time = endTime + calculatedDelay, Column = currentObject.Column }; yield return new ReleasePoint { Time = releaseTime, Column = currentObject.Column };
} }
} }
private double calculateReleaseTime(HitObject currentObject, HitObject nextObject)
{
double endTime = currentObject.GetEndTime();
if (currentObject is HoldNote)
// hold note releases must be timed exactly.
return endTime;
bool canDelayKeyUpFully = nextObject == null ||
nextObject.StartTime > endTime + RELEASE_DELAY;
return endTime + (canDelayKeyUpFully ? RELEASE_DELAY : (nextObject.StartTime - endTime) * 0.9);
}
protected override HitObject GetNextObject(int currentIndex) protected override HitObject GetNextObject(int currentIndex)
{ {
int desiredColumn = Beatmap.HitObjects[currentIndex].Column; int desiredColumn = Beatmap.HitObjects[currentIndex].Column;

View File

@ -17,6 +17,8 @@ namespace osu.Game.Rulesets.Mania.Skinning.Legacy
{ {
public class LegacyHitExplosion : LegacyManiaColumnElement, IHitExplosion public class LegacyHitExplosion : LegacyManiaColumnElement, IHitExplosion
{ {
public const double FADE_IN_DURATION = 80;
private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>(); private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();
private Drawable explosion; private Drawable explosion;
@ -72,7 +74,7 @@ namespace osu.Game.Rulesets.Mania.Skinning.Legacy
(explosion as IFramedAnimation)?.GotoFrame(0); (explosion as IFramedAnimation)?.GotoFrame(0);
explosion?.FadeInFromZero(80) explosion?.FadeInFromZero(FADE_IN_DURATION)
.Then().FadeOut(120); .Then().FadeOut(120);
} }
} }

View File

@ -101,8 +101,8 @@ namespace osu.Game.Rulesets.Mania.Skinning.Legacy
{ {
if (action == column.Action.Value) if (action == column.Action.Value)
{ {
upSprite.FadeTo(1); upSprite.Delay(LegacyHitExplosion.FADE_IN_DURATION).FadeTo(1);
downSprite.FadeTo(0); downSprite.Delay(LegacyHitExplosion.FADE_IN_DURATION).FadeTo(0);
} }
} }
} }

View File

@ -35,5 +35,10 @@
<Name>osu.Game</Name> <Name>osu.Game</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="System.Formats.Asn1">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project> </Project>

View File

@ -15,13 +15,13 @@ namespace osu.Game.Rulesets.Osu.Tests
{ {
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.9311451172608853d, "diffcalc-test")] [TestCase(6.9311451172574934d, "diffcalc-test")]
[TestCase(1.0736587013228804d, "zero-length-sliders")] [TestCase(1.0736586907780401d, "zero-length-sliders")]
public void Test(double expected, string name) public void Test(double expected, string name)
=> base.Test(expected, name); => base.Test(expected, name);
[TestCase(8.6228371119393064d, "diffcalc-test")] [TestCase(8.6228371119271454d, "diffcalc-test")]
[TestCase(1.2864585434597433d, "zero-length-sliders")] [TestCase(1.2864585280364178d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name) public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime()); => Test(expected, name, new OsuModDoubleTime());

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 865 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,2 +1,6 @@
[General] [General]
Version: 1.0 Version: 1.0
[Fonts]
HitCircleOverlap: 3
ScoreOverlap: 3

View File

@ -5,7 +5,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
<PackageReference Include="NUnit" Version="3.13.1" /> <PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Project"> <PropertyGroup Label="Project">
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>

View File

@ -82,6 +82,9 @@ namespace osu.Game.Rulesets.Osu.Edit
protected override ComposeBlueprintContainer CreateBlueprintContainer() protected override ComposeBlueprintContainer CreateBlueprintContainer()
=> new OsuBlueprintContainer(this); => new OsuBlueprintContainer(this);
public override string ConvertSelectionToString()
=> string.Join(',', selectedHitObjects.Cast<OsuHitObject>().OrderBy(h => h.StartTime).Select(h => (h.IndexInCurrentCombo + 1).ToString()));
private DistanceSnapGrid distanceSnapGrid; private DistanceSnapGrid distanceSnapGrid;
private Container distanceSnapGridContainer; private Container distanceSnapGridContainer;

View File

@ -36,8 +36,18 @@ namespace osu.Game.Rulesets.Osu.Edit
referencePathTypes = null; referencePathTypes = null;
} }
public override bool HandleMovement(MoveSelectionEvent moveEvent) => public override bool HandleMovement(MoveSelectionEvent moveEvent)
moveSelection(moveEvent.InstantDelta); {
var hitObjects = selectedMovableObjects;
// this will potentially move the selection out of bounds...
foreach (var h in hitObjects)
h.Position += moveEvent.InstantDelta;
// but this will be corrected.
moveSelectionInBounds();
return true;
}
/// <summary> /// <summary>
/// During a transform, the initial origin is stored so it can be used throughout the operation. /// During a transform, the initial origin is stored so it can be used throughout the operation.
@ -147,42 +157,11 @@ namespace osu.Game.Rulesets.Osu.Edit
// the only hit object selected. with a group selection, it's likely the user // the only hit object selected. with a group selection, it's likely the user
// is not looking to change the duration of the slider but expand the whole pattern. // is not looking to change the duration of the slider but expand the whole pattern.
if (hitObjects.Length == 1 && hitObjects.First() is Slider slider) if (hitObjects.Length == 1 && hitObjects.First() is Slider slider)
{ scaleSlider(slider, scale);
referencePathTypes ??= slider.Path.ControlPoints.Select(p => p.Type.Value).ToList();
Quad quad = getSurroundingQuad(slider.Path.ControlPoints.Select(p => p.Position.Value));
Vector2 pathRelativeDeltaScale = new Vector2(1 + scale.X / quad.Width, 1 + scale.Y / quad.Height);
foreach (var point in slider.Path.ControlPoints)
point.Position.Value *= pathRelativeDeltaScale;
// Maintain the path types in case they were defaulted to bezier at some point during scaling
for (int i = 0; i < slider.Path.ControlPoints.Count; ++i)
slider.Path.ControlPoints[i].Type.Value = referencePathTypes[i];
}
else else
{ scaleHitObjects(hitObjects, reference, scale);
// move the selection before scaling if dragging from top or left anchors.
if ((reference & Anchor.x0) > 0 && !moveSelection(new Vector2(-scale.X, 0))) return false;
if ((reference & Anchor.y0) > 0 && !moveSelection(new Vector2(0, -scale.Y))) return false;
Quad quad = getSurroundingQuad(hitObjects);
foreach (var h in hitObjects)
{
var newPosition = h.Position;
// guard against no-ops and NaN.
if (scale.X != 0 && quad.Width > 0)
newPosition.X = quad.TopLeft.X + (h.X - quad.TopLeft.X) / quad.Width * (quad.Width + scale.X);
if (scale.Y != 0 && quad.Height > 0)
newPosition.Y = quad.TopLeft.Y + (h.Y - quad.TopLeft.Y) / quad.Height * (quad.Height + scale.Y);
h.Position = newPosition;
}
}
moveSelectionInBounds();
return true; return true;
} }
@ -220,28 +199,130 @@ namespace osu.Game.Rulesets.Osu.Edit
return true; return true;
} }
private bool moveSelection(Vector2 delta) private void scaleSlider(Slider slider, Vector2 scale)
{
referencePathTypes ??= slider.Path.ControlPoints.Select(p => p.Type.Value).ToList();
Quad sliderQuad = getSurroundingQuad(slider.Path.ControlPoints.Select(p => p.Position.Value));
// Limit minimum distance between control points after scaling to almost 0. Less than 0 causes the slider to flip, exactly 0 causes a crash through division by 0.
scale = Vector2.ComponentMax(new Vector2(Precision.FLOAT_EPSILON), sliderQuad.Size + scale) - sliderQuad.Size;
Vector2 pathRelativeDeltaScale = new Vector2(1 + scale.X / sliderQuad.Width, 1 + scale.Y / sliderQuad.Height);
Queue<Vector2> oldControlPoints = new Queue<Vector2>();
foreach (var point in slider.Path.ControlPoints)
{
oldControlPoints.Enqueue(point.Position.Value);
point.Position.Value *= pathRelativeDeltaScale;
}
// Maintain the path types in case they were defaulted to bezier at some point during scaling
for (int i = 0; i < slider.Path.ControlPoints.Count; ++i)
slider.Path.ControlPoints[i].Type.Value = referencePathTypes[i];
//if sliderhead or sliderend end up outside playfield, revert scaling.
Quad scaledQuad = getSurroundingQuad(new OsuHitObject[] { slider });
(bool xInBounds, bool yInBounds) = isQuadInBounds(scaledQuad);
if (xInBounds && yInBounds)
return;
foreach (var point in slider.Path.ControlPoints)
point.Position.Value = oldControlPoints.Dequeue();
}
private void scaleHitObjects(OsuHitObject[] hitObjects, Anchor reference, Vector2 scale)
{
scale = getClampedScale(hitObjects, reference, scale);
// move the selection before scaling if dragging from top or left anchors.
float xOffset = ((reference & Anchor.x0) > 0) ? -scale.X : 0;
float yOffset = ((reference & Anchor.y0) > 0) ? -scale.Y : 0;
Quad selectionQuad = getSurroundingQuad(hitObjects);
foreach (var h in hitObjects)
{
var newPosition = h.Position;
// guard against no-ops and NaN.
if (scale.X != 0 && selectionQuad.Width > 0)
newPosition.X = selectionQuad.TopLeft.X + xOffset + (h.X - selectionQuad.TopLeft.X) / selectionQuad.Width * (selectionQuad.Width + scale.X);
if (scale.Y != 0 && selectionQuad.Height > 0)
newPosition.Y = selectionQuad.TopLeft.Y + yOffset + (h.Y - selectionQuad.TopLeft.Y) / selectionQuad.Height * (selectionQuad.Height + scale.Y);
h.Position = newPosition;
}
}
private (bool X, bool Y) isQuadInBounds(Quad quad)
{
bool xInBounds = (quad.TopLeft.X >= 0) && (quad.BottomRight.X <= DrawWidth);
bool yInBounds = (quad.TopLeft.Y >= 0) && (quad.BottomRight.Y <= DrawHeight);
return (xInBounds, yInBounds);
}
private void moveSelectionInBounds()
{ {
var hitObjects = selectedMovableObjects; var hitObjects = selectedMovableObjects;
Quad quad = getSurroundingQuad(hitObjects); Quad quad = getSurroundingQuad(hitObjects);
Vector2 newTopLeft = quad.TopLeft + delta; Vector2 delta = Vector2.Zero;
if (newTopLeft.X < 0)
delta.X -= newTopLeft.X;
if (newTopLeft.Y < 0)
delta.Y -= newTopLeft.Y;
Vector2 newBottomRight = quad.BottomRight + delta; if (quad.TopLeft.X < 0)
if (newBottomRight.X > DrawWidth) delta.X -= quad.TopLeft.X;
delta.X -= newBottomRight.X - DrawWidth; if (quad.TopLeft.Y < 0)
if (newBottomRight.Y > DrawHeight) delta.Y -= quad.TopLeft.Y;
delta.Y -= newBottomRight.Y - DrawHeight;
if (quad.BottomRight.X > DrawWidth)
delta.X -= quad.BottomRight.X - DrawWidth;
if (quad.BottomRight.Y > DrawHeight)
delta.Y -= quad.BottomRight.Y - DrawHeight;
foreach (var h in hitObjects) foreach (var h in hitObjects)
h.Position += delta; h.Position += delta;
}
return true; /// <summary>
/// Clamp scale for multi-object-scaling where selection does not exceed playfield bounds or flip.
/// </summary>
/// <param name="hitObjects">The hitobjects to be scaled</param>
/// <param name="reference">The anchor from which the scale operation is performed</param>
/// <param name="scale">The scale to be clamped</param>
/// <returns>The clamped scale vector</returns>
private Vector2 getClampedScale(OsuHitObject[] hitObjects, Anchor reference, Vector2 scale)
{
float xOffset = ((reference & Anchor.x0) > 0) ? -scale.X : 0;
float yOffset = ((reference & Anchor.y0) > 0) ? -scale.Y : 0;
Quad selectionQuad = getSurroundingQuad(hitObjects);
//todo: this is not always correct for selections involving sliders. This approximation assumes each point is scaled independently, but sliderends move with the sliderhead.
Quad scaledQuad = new Quad(selectionQuad.TopLeft.X + xOffset, selectionQuad.TopLeft.Y + yOffset, selectionQuad.Width + scale.X, selectionQuad.Height + scale.Y);
//max Size -> playfield bounds
if (scaledQuad.TopLeft.X < 0)
scale.X += scaledQuad.TopLeft.X;
if (scaledQuad.TopLeft.Y < 0)
scale.Y += scaledQuad.TopLeft.Y;
if (scaledQuad.BottomRight.X > DrawWidth)
scale.X -= scaledQuad.BottomRight.X - DrawWidth;
if (scaledQuad.BottomRight.Y > DrawHeight)
scale.Y -= scaledQuad.BottomRight.Y - DrawHeight;
//min Size -> almost 0. Less than 0 causes the quad to flip, exactly 0 causes scaling to get stuck at minimum scale.
Vector2 scaledSize = selectionQuad.Size + scale;
Vector2 minSize = new Vector2(Precision.FLOAT_EPSILON);
scale = Vector2.ComponentMax(minSize, scaledSize) - selectionQuad.Size;
return scale;
} }
/// <summary> /// <summary>

View File

@ -164,28 +164,29 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
ApproachCircle.Expire(true); ApproachCircle.Expire(true);
} }
protected override void UpdateStartTimeStateTransforms()
{
base.UpdateStartTimeStateTransforms();
ApproachCircle.FadeOut(50);
}
protected override void UpdateHitStateTransforms(ArmedState state) protected override void UpdateHitStateTransforms(ArmedState state)
{ {
Debug.Assert(HitObject.HitWindows != null); Debug.Assert(HitObject.HitWindows != null);
// todo: temporary / arbitrary, used for lifetime optimisation.
this.Delay(800).FadeOut();
switch (state) switch (state)
{ {
case ArmedState.Idle: case ArmedState.Idle:
this.Delay(HitObject.TimePreempt).FadeOut(500);
HitArea.HitAction = null; HitArea.HitAction = null;
break; break;
case ArmedState.Miss: case ArmedState.Miss:
ApproachCircle.FadeOut(50);
this.FadeOut(100); this.FadeOut(100);
break; break;
case ArmedState.Hit:
ApproachCircle.FadeOut(50);
// todo: temporary / arbitrary
this.Delay(800).FadeOut();
break;
} }
Expire(); Expire();

View File

@ -33,12 +33,20 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
public SpinnerSpmCounter SpmCounter { get; private set; } public SpinnerSpmCounter SpmCounter { get; private set; }
private Container<DrawableSpinnerTick> ticks; private Container<DrawableSpinnerTick> ticks;
private SpinnerBonusDisplay bonusDisplay;
private PausableSkinnableSound spinningSample; private PausableSkinnableSound spinningSample;
private Bindable<bool> isSpinning; private Bindable<bool> isSpinning;
private bool spinnerFrequencyModulate; private bool spinnerFrequencyModulate;
/// <summary>
/// The amount of bonus score gained from spinning after the required number of spins, for display purposes.
/// </summary>
public IBindable<double> GainedBonus => gainedBonus;
private readonly Bindable<double> gainedBonus = new Bindable<double>();
private const double fade_out_duration = 160;
public DrawableSpinner() public DrawableSpinner()
: this(null) : this(null)
{ {
@ -65,7 +73,7 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
RelativeSizeAxes = Axes.Y, RelativeSizeAxes = Axes.Y,
Children = new Drawable[] Children = new Drawable[]
{ {
new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SpinnerBody), _ => new DefaultSpinnerDisc()), new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SpinnerBody), _ => new DefaultSpinner()),
RotationTracker = new SpinnerRotationTracker(this) RotationTracker = new SpinnerRotationTracker(this)
} }
}, },
@ -76,12 +84,6 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
Y = 120, Y = 120,
Alpha = 0 Alpha = 0
}, },
bonusDisplay = new SpinnerBonusDisplay
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Y = -120,
},
spinningSample = new PausableSkinnableSound spinningSample = new PausableSkinnableSound
{ {
Volume = { Value = 0 }, Volume = { Value = 0 },
@ -131,12 +133,13 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
if (tracking.NewValue) if (tracking.NewValue)
{ {
if (!spinningSample.IsPlaying) if (!spinningSample.IsPlaying)
spinningSample?.Play(); spinningSample.Play();
spinningSample?.VolumeTo(1, 300);
spinningSample.VolumeTo(1, 300);
} }
else else
{ {
spinningSample?.VolumeTo(0, 300).OnComplete(_ => spinningSample.Stop()); spinningSample.VolumeTo(0, fade_out_duration);
} }
} }
@ -173,7 +176,14 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
{ {
base.UpdateHitStateTransforms(state); base.UpdateHitStateTransforms(state);
this.FadeOut(160).Expire(); this.FadeOut(fade_out_duration).OnComplete(_ =>
{
// looping sample should be stopped here as it is safer than running in the OnComplete
// of the volume transition above.
spinningSample.Stop();
});
Expire();
// skin change does a rewind of transforms, which will stop the spinning sound from playing if it's currently in playback. // skin change does a rewind of transforms, which will stop the spinning sound from playing if it's currently in playback.
isSpinning?.TriggerChange(); isSpinning?.TriggerChange();
@ -288,6 +298,8 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
private void fadeInCounter() => SpmCounter.FadeIn(HitObject.TimeFadeIn); private void fadeInCounter() => SpmCounter.FadeIn(HitObject.TimeFadeIn);
private static readonly int score_per_tick = new SpinnerBonusTick.OsuSpinnerBonusTickJudgement().MaxNumericResult;
private int wholeSpins; private int wholeSpins;
private void updateBonusScore() private void updateBonusScore()
@ -312,8 +324,9 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
if (tick != null) if (tick != null)
{ {
tick.TriggerResult(true); tick.TriggerResult(true);
if (tick is DrawableSpinnerBonusTick) if (tick is DrawableSpinnerBonusTick)
bonusDisplay.SetBonusCount(spins - HitObject.SpinsRequired); gainedBonus.Value = score_per_tick * (spins - HitObject.SpinsRequired);
} }
wholeSpins++; wholeSpins++;

View File

@ -18,6 +18,6 @@ namespace osu.Game.Rulesets.Osu
SliderFollowCircle, SliderFollowCircle,
SliderBall, SliderBall,
SliderBody, SliderBody,
SpinnerBody SpinnerBody,
} }
} }

View File

@ -1,5 +1,18 @@
{ {
"Mappings": [{ "Mappings": [{
"StartTime": 114993,
"Objects": [{
"StartTime": 114993,
"EndTime": 114993,
"X": 493,
"Y": 92
}, {
"StartTime": 115290,
"EndTime": 115290,
"X": 451.659241,
"Y": 267.188
}]
}, {
"StartTime": 118858.0, "StartTime": 118858.0,
"Objects": [{ "Objects": [{
"StartTime": 118858.0, "StartTime": 118858.0,

View File

@ -9,7 +9,9 @@ SliderMultiplier:1.87
SliderTickRate:1 SliderTickRate:1
[TimingPoints] [TimingPoints]
49051,230.769230769231,4,2,1,15,1,0 114000,346.820809248555,4,2,1,71,1,0
118000,230.769230769231,4,2,1,15,1,0
[HitObjects] [HitObjects]
493,92,114993,2,0,P|472:181|442:308,1,180,12|0,0:0|0:0,0:0:0:0:
219,215,118858,2,0,P|224:170|244:-10,1,187,8|2,0:0|0:0,0:0:0:0: 219,215,118858,2,0,P|224:170|244:-10,1,187,8|2,0:0|0:0,0:0:0:0:

View File

@ -0,0 +1,68 @@
// 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.Globalization;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
public class DefaultSpinner : CompositeDrawable
{
private DrawableSpinner drawableSpinner;
private OsuSpriteText bonusCounter;
public DefaultSpinner()
{
RelativeSizeAxes = Axes.Both;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(DrawableHitObject drawableHitObject)
{
drawableSpinner = (DrawableSpinner)drawableHitObject;
AddRangeInternal(new Drawable[]
{
new DefaultSpinnerDisc
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
bonusCounter = new OsuSpriteText
{
Alpha = 0,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.Numeric.With(size: 24),
Y = -120,
}
});
}
private IBindable<double> gainedBonus;
protected override void LoadComplete()
{
base.LoadComplete();
gainedBonus = drawableSpinner.GainedBonus.GetBoundCopy();
gainedBonus.BindValueChanged(bonus =>
{
bonusCounter.Text = bonus.NewValue.ToString(NumberFormatInfo.InvariantInfo);
bonusCounter.FadeOutFromOne(1500);
bonusCounter.ScaleTo(1.5f).Then().ScaleTo(1f, 1000, Easing.OutQuint);
});
}
}
}

View File

@ -40,14 +40,9 @@ namespace osu.Game.Rulesets.Osu.Skinning.Default
public DefaultSpinnerDisc() public DefaultSpinnerDisc()
{ {
RelativeSizeAxes = Axes.Both;
// we are slightly bigger than our parent, to clip the top and bottom of the circle // we are slightly bigger than our parent, to clip the top and bottom of the circle
// this should probably be revisited when scaled spinners are a thing. // this should probably be revisited when scaled spinners are a thing.
Scale = new Vector2(initial_scale); Scale = new Vector2(initial_scale);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
} }
[BackgroundDependencyLoader] [BackgroundDependencyLoader]

View File

@ -74,10 +74,11 @@ namespace osu.Game.Rulesets.Osu.Skinning.Default
private void updateState(DrawableHitObject drawableObject, ArmedState state) private void updateState(DrawableHitObject drawableObject, ArmedState state)
{ {
using (BeginAbsoluteSequence(drawableObject.HitStateUpdateTime, true)) using (BeginAbsoluteSequence(drawableObject.StateUpdateTime))
{
glow.FadeOut(400); glow.FadeOut(400);
using (BeginAbsoluteSequence(drawableObject.HitStateUpdateTime))
{
switch (state) switch (state)
{ {
case ArmedState.Hit: case ArmedState.Hit:

View File

@ -1,47 +0,0 @@
// 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 osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Osu.Objects;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
/// <summary>
/// Shows incremental bonus score achieved for a spinner.
/// </summary>
public class SpinnerBonusDisplay : CompositeDrawable
{
private static readonly int score_per_tick = new SpinnerBonusTick().CreateJudgement().MaxNumericResult;
private readonly OsuSpriteText bonusCounter;
public SpinnerBonusDisplay()
{
AutoSizeAxes = Axes.Both;
InternalChild = bonusCounter = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.Numeric.With(size: 24),
Alpha = 0,
};
}
private int displayedCount;
public void SetBonusCount(int count)
{
if (displayedCount == count)
return;
displayedCount = count;
bonusCounter.Text = $"{score_per_tick * count}";
bonusCounter.FadeOutFromOne(1500);
bonusCounter.ScaleTo(1.5f).Then().ScaleTo(1f, 1000, Easing.OutQuint);
}
}
}

View File

@ -2,6 +2,7 @@
// 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 System; using System;
using System.Globalization;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
@ -32,6 +33,8 @@ namespace osu.Game.Rulesets.Osu.Skinning.Legacy
private Sprite spin; private Sprite spin;
private Sprite clear; private Sprite clear;
private LegacySpriteText bonusCounter;
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load(DrawableHitObject drawableHitObject, ISkinSource source) private void load(DrawableHitObject drawableHitObject, ISkinSource source)
{ {
@ -45,13 +48,16 @@ namespace osu.Game.Rulesets.Osu.Skinning.Legacy
DrawableSpinner = (DrawableSpinner)drawableHitObject; DrawableSpinner = (DrawableSpinner)drawableHitObject;
AddRangeInternal(new[] AddInternal(new Container
{
Depth = float.MinValue,
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{ {
spin = new Sprite spin = new Sprite
{ {
Anchor = Anchor.TopCentre, Anchor = Anchor.TopCentre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
Depth = float.MinValue,
Texture = source.GetTexture("spinner-spin"), Texture = source.GetTexture("spinner-spin"),
Scale = new Vector2(SPRITE_SCALE), Scale = new Vector2(SPRITE_SCALE),
Y = SPINNER_TOP_OFFSET + 335, Y = SPINNER_TOP_OFFSET + 335,
@ -61,20 +67,38 @@ namespace osu.Game.Rulesets.Osu.Skinning.Legacy
Alpha = 0, Alpha = 0,
Anchor = Anchor.TopCentre, Anchor = Anchor.TopCentre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
Depth = float.MinValue,
Texture = source.GetTexture("spinner-clear"), Texture = source.GetTexture("spinner-clear"),
Scale = new Vector2(SPRITE_SCALE), Scale = new Vector2(SPRITE_SCALE),
Y = SPINNER_TOP_OFFSET + 115, Y = SPINNER_TOP_OFFSET + 115,
}, },
bonusCounter = new LegacySpriteText(source, LegacyFont.Score)
{
Alpha = 0f,
Anchor = Anchor.TopCentre,
Origin = Anchor.Centre,
Scale = new Vector2(SPRITE_SCALE),
Y = SPINNER_TOP_OFFSET + 299,
}.With(s => s.Font = s.Font.With(fixedWidth: false)),
}
}); });
} }
private IBindable<double> gainedBonus;
private readonly Bindable<bool> completed = new Bindable<bool>(); private readonly Bindable<bool> completed = new Bindable<bool>();
protected override void LoadComplete() protected override void LoadComplete()
{ {
base.LoadComplete(); base.LoadComplete();
gainedBonus = DrawableSpinner.GainedBonus.GetBoundCopy();
gainedBonus.BindValueChanged(bonus =>
{
bonusCounter.Text = bonus.NewValue.ToString(NumberFormatInfo.InvariantInfo);
bonusCounter.FadeOutFromOne(800, Easing.Out);
bonusCounter.ScaleTo(SPRITE_SCALE * 2f).Then().ScaleTo(SPRITE_SCALE * 1.28f, 800, Easing.Out);
});
completed.BindValueChanged(onCompletedChanged, true); completed.BindValueChanged(onCompletedChanged, true);
DrawableSpinner.ApplyCustomUpdateState += UpdateStateTransforms; DrawableSpinner.ApplyCustomUpdateState += UpdateStateTransforms;

View File

@ -97,16 +97,13 @@ namespace osu.Game.Rulesets.Osu.Skinning.Legacy
return null; return null;
case OsuSkinComponents.HitCircleText: case OsuSkinComponents.HitCircleText:
var font = GetConfig<OsuSkinConfiguration, string>(OsuSkinConfiguration.HitCirclePrefix)?.Value ?? "default"; if (!this.HasFont(LegacyFont.HitCircle))
var overlap = GetConfig<OsuSkinConfiguration, float>(OsuSkinConfiguration.HitCircleOverlap)?.Value ?? -2; return null;
return !this.HasFont(font) return new LegacySpriteText(Source, LegacyFont.HitCircle)
? null
: new LegacySpriteText(Source, font)
{ {
// stable applies a blanket 0.8x scale to hitcircle fonts // stable applies a blanket 0.8x scale to hitcircle fonts
Scale = new Vector2(0.8f), Scale = new Vector2(0.8f),
Spacing = new Vector2(-overlap, 0)
}; };
case OsuSkinComponents.SpinnerBody: case OsuSkinComponents.SpinnerBody:

View File

@ -5,8 +5,6 @@ namespace osu.Game.Rulesets.Osu.Skinning
{ {
public enum OsuSkinConfiguration public enum OsuSkinConfiguration
{ {
HitCirclePrefix,
HitCircleOverlap,
SliderBorderSize, SliderBorderSize,
SliderPathRadius, SliderPathRadius,
AllowSliderBallTint, AllowSliderBallTint,

View File

@ -35,5 +35,10 @@
<Name>osu.Game</Name> <Name>osu.Game</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="System.Formats.Asn1">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project> </Project>

View File

@ -5,7 +5,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
<PackageReference Include="NUnit" Version="3.13.1" /> <PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Project"> <PropertyGroup Label="Project">
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>

View File

@ -75,6 +75,9 @@
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="DeepEqual" Version="2.0.0" /> <PackageReference Include="DeepEqual" Version="2.0.0" />
<PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="System.Formats.Asn1">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project> </Project>

View File

@ -0,0 +1,26 @@
// 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.Globalization;
using NUnit.Framework;
using osu.Game.Utils;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class FormatUtilsTest
{
[TestCase(0, "0.00%")]
[TestCase(0.01, "1.00%")]
[TestCase(0.9899, "98.99%")]
[TestCase(0.989999, "98.99%")]
[TestCase(0.99, "99.00%")]
[TestCase(0.9999, "99.99%")]
[TestCase(0.999999, "99.99%")]
[TestCase(1, "100.00%")]
public void TestAccuracyFormatting(double input, string expectedOutput)
{
Assert.AreEqual(expectedOutput, input.FormatAccuracy(CultureInfo.InvariantCulture));
}
}
}

View File

@ -25,7 +25,7 @@ namespace osu.Game.Tests.Online
var deserialized = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod)); var deserialized = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod));
Assert.That(deserialized.Acronym, Is.EqualTo(apiMod.Acronym)); Assert.That(deserialized?.Acronym, Is.EqualTo(apiMod.Acronym));
} }
[Test] [Test]
@ -35,7 +35,7 @@ namespace osu.Game.Tests.Online
var deserialized = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod)); var deserialized = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod));
Assert.That(deserialized.Settings, Contains.Key("test_setting").With.ContainValue(2.0)); Assert.That(deserialized?.Settings, Contains.Key("test_setting").With.ContainValue(2.0));
} }
[Test] [Test]
@ -44,9 +44,9 @@ namespace osu.Game.Tests.Online
var apiMod = new APIMod(new TestMod { TestSetting = { Value = 2 } }); var apiMod = new APIMod(new TestMod { TestSetting = { Value = 2 } });
var deserialized = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod)); var deserialized = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod));
var converted = (TestMod)deserialized.ToMod(new TestRuleset()); var converted = (TestMod)deserialized?.ToMod(new TestRuleset());
Assert.That(converted.TestSetting.Value, Is.EqualTo(2)); Assert.That(converted?.TestSetting.Value, Is.EqualTo(2));
} }
[Test] [Test]
@ -61,11 +61,11 @@ namespace osu.Game.Tests.Online
}); });
var deserialised = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod)); var deserialised = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod));
var converted = (TestModTimeRamp)deserialised.ToMod(new TestRuleset()); var converted = (TestModTimeRamp)deserialised?.ToMod(new TestRuleset());
Assert.That(converted.AdjustPitch.Value, Is.EqualTo(false)); Assert.That(converted?.AdjustPitch.Value, Is.EqualTo(false));
Assert.That(converted.InitialRate.Value, Is.EqualTo(1.25)); Assert.That(converted?.InitialRate.Value, Is.EqualTo(1.25));
Assert.That(converted.FinalRate.Value, Is.EqualTo(0.25)); Assert.That(converted?.FinalRate.Value, Is.EqualTo(0.25));
} }
[Test] [Test]
@ -78,10 +78,10 @@ namespace osu.Game.Tests.Online
}); });
var deserialised = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod)); var deserialised = JsonConvert.DeserializeObject<APIMod>(JsonConvert.SerializeObject(apiMod));
var converted = (TestModDifficultyAdjust)deserialised.ToMod(new TestRuleset()); var converted = (TestModDifficultyAdjust)deserialised?.ToMod(new TestRuleset());
Assert.That(converted.ExtendedLimits.Value, Is.True); Assert.That(converted?.ExtendedLimits.Value, Is.True);
Assert.That(converted.OverallDifficulty.Value, Is.EqualTo(11)); Assert.That(converted?.OverallDifficulty.Value, Is.EqualTo(11));
} }
private class TestRuleset : Ruleset private class TestRuleset : Ruleset

View File

@ -23,8 +23,10 @@ namespace osu.Game.Tests.Online
{ {
case CommentVoteRequest cRequest: case CommentVoteRequest cRequest:
cRequest.TriggerSuccess(new CommentBundle()); cRequest.TriggerSuccess(new CommentBundle());
break; return true;
} }
return false;
}); });
CommentVoteRequest request = null; CommentVoteRequest request = null;
@ -108,8 +110,10 @@ namespace osu.Game.Tests.Online
{ {
case LeaveChannelRequest cRequest: case LeaveChannelRequest cRequest:
cRequest.TriggerSuccess(); cRequest.TriggerSuccess();
break; return true;
} }
return false;
}); });
} }
} }

View File

@ -113,6 +113,31 @@ namespace osu.Game.Tests.Skins.IO
} }
} }
[Test]
public async Task TestImportUpperCasedOskArchive()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportSkinTest)))
{
try
{
var osu = LoadOsuIntoHost(host);
var imported = await loadSkinIntoOsu(osu, new ZipArchiveReader(createOsk("name 1", "author 1"), "skin1.OsK"));
Assert.That(imported.Name, Is.EqualTo("name 1"));
Assert.That(imported.Creator, Is.EqualTo("author 1"));
var imported2 = await loadSkinIntoOsu(osu, new ZipArchiveReader(createOsk("name 1", "author 1"), "skin1.oSK"));
Assert.That(imported2.Hash, Is.EqualTo(imported.Hash));
}
finally
{
host.Exit();
}
}
}
private MemoryStream createOsk(string name, string author) private MemoryStream createOsk(string name, string author)
{ {
var zipStream = new MemoryStream(); var zipStream = new MemoryStream();

View File

@ -135,13 +135,15 @@ namespace osu.Game.Tests.Visual.Background
dummyAPI.HandleRequest = request => dummyAPI.HandleRequest = request =>
{ {
if (dummyAPI.State.Value != APIState.Online || !(request is GetSeasonalBackgroundsRequest backgroundsRequest)) if (dummyAPI.State.Value != APIState.Online || !(request is GetSeasonalBackgroundsRequest backgroundsRequest))
return; return false;
backgroundsRequest.TriggerSuccess(new APISeasonalBackgrounds backgroundsRequest.TriggerSuccess(new APISeasonalBackgrounds
{ {
Backgrounds = seasonal_background_urls.Select(url => new APISeasonalBackground { Url = url }).ToList(), Backgrounds = seasonal_background_urls.Select(url => new APISeasonalBackground { Url = url }).ToList(),
EndDate = endDate EndDate = endDate
}); });
return true;
}; };
}); });

View File

@ -56,7 +56,6 @@ namespace osu.Game.Tests.Visual.Multiplayer
beatmaps.Add(new BeatmapInfo beatmaps.Add(new BeatmapInfo
{ {
Ruleset = rulesets.GetRuleset(i % 4), Ruleset = rulesets.GetRuleset(i % 4),
RulesetID = i % 4, // workaround for efcore 5 compatibility.
OnlineBeatmapID = beatmapId, OnlineBeatmapID = beatmapId,
Length = length, Length = length,
BPM = bpm, BPM = bpm,

View File

@ -58,7 +58,7 @@ namespace osu.Game.Tests.Visual.Navigation
public void TestPerformAtSongSelectFromPlayerLoader() public void TestPerformAtSongSelectFromPlayerLoader()
{ {
PushAndConfirm(() => new PlaySongSelect()); PushAndConfirm(() => new PlaySongSelect());
PushAndConfirm(() => new PlayerLoader(() => new Player())); PushAndConfirm(() => new PlayerLoader(() => new SoloPlayer()));
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true, new[] { typeof(PlaySongSelect) })); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true, new[] { typeof(PlaySongSelect) }));
AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is PlaySongSelect); AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is PlaySongSelect);
@ -69,7 +69,7 @@ namespace osu.Game.Tests.Visual.Navigation
public void TestPerformAtMenuFromPlayerLoader() public void TestPerformAtMenuFromPlayerLoader()
{ {
PushAndConfirm(() => new PlaySongSelect()); PushAndConfirm(() => new PlaySongSelect());
PushAndConfirm(() => new PlayerLoader(() => new Player())); PushAndConfirm(() => new PlayerLoader(() => new SoloPlayer()));
AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true));
AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is MainMenu); AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is MainMenu);

View File

@ -43,6 +43,29 @@ namespace osu.Game.Tests.Visual.Navigation
exitViaEscapeAndConfirm(); exitViaEscapeAndConfirm();
} }
[Test]
public void TestRetryCountIncrements()
{
Player player = null;
PushAndConfirm(() => new TestSongSelect());
AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait());
AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault);
AddStep("press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("wait for player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null);
AddAssert("retry count is 0", () => player.RestartCount == 0);
AddStep("attempt to retry", () => player.ChildrenOfType<HotkeyRetryOverlay>().First().Action());
AddUntilStep("wait for old player gone", () => Game.ScreenStack.CurrentScreen != player);
AddUntilStep("get new player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null);
AddAssert("retry count is 1", () => player.RestartCount == 1);
}
[Test] [Test]
public void TestRetryFromResults() public void TestRetryFromResults()
{ {

View File

@ -30,13 +30,14 @@ namespace osu.Game.Tests.Visual.Online
((DummyAPIAccess)API).HandleRequest = req => ((DummyAPIAccess)API).HandleRequest = req =>
{ {
if (req is SearchBeatmapSetsRequest searchBeatmapSetsRequest) if (!(req is SearchBeatmapSetsRequest searchBeatmapSetsRequest)) return false;
{
searchBeatmapSetsRequest.TriggerSuccess(new SearchBeatmapSetsResponse searchBeatmapSetsRequest.TriggerSuccess(new SearchBeatmapSetsResponse
{ {
BeatmapSets = setsForResponse, BeatmapSets = setsForResponse,
}); });
}
return true;
}; };
} }

View File

@ -63,13 +63,15 @@ namespace osu.Game.Tests.Visual.Online
Builds = builds.Values.ToList() Builds = builds.Values.ToList()
}; };
changelogRequest.TriggerSuccess(changelogResponse); changelogRequest.TriggerSuccess(changelogResponse);
break; return true;
case GetChangelogBuildRequest buildRequest: case GetChangelogBuildRequest buildRequest:
if (requestedBuild != null) if (requestedBuild != null)
buildRequest.TriggerSuccess(requestedBuild); buildRequest.TriggerSuccess(requestedBuild);
break; return true;
} }
return false;
}; };
Child = changelog = new TestChangelogOverlay(); Child = changelog = new TestChangelogOverlay();

View File

@ -11,6 +11,8 @@ using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.UserInterface; using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing; using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Chat; using osu.Game.Online.Chat;
using osu.Game.Overlays; using osu.Game.Overlays;
using osu.Game.Overlays.Chat.Selection; using osu.Game.Overlays.Chat.Selection;
@ -64,6 +66,24 @@ namespace osu.Game.Tests.Visual.Online
}); });
} }
[SetUpSteps]
public void SetUpSteps()
{
AddStep("register request handling", () =>
{
((DummyAPIAccess)API).HandleRequest = req =>
{
switch (req)
{
case JoinChannelRequest _:
return true;
}
return false;
};
});
}
[Test] [Test]
public void TestHideOverlay() public void TestHideOverlay()
{ {

View File

@ -85,9 +85,10 @@ namespace osu.Game.Tests.Visual.Online
dummyAPI.HandleRequest = request => dummyAPI.HandleRequest = request =>
{ {
if (!(request is GetCommentsRequest getCommentsRequest)) if (!(request is GetCommentsRequest getCommentsRequest))
return; return false;
getCommentsRequest.TriggerSuccess(commentBundle); getCommentsRequest.TriggerSuccess(commentBundle);
return true;
}; };
}); });

View File

@ -33,9 +33,10 @@ namespace osu.Game.Tests.Visual.Online
dummyAPI.HandleRequest = request => dummyAPI.HandleRequest = request =>
{ {
if (!(request is GetNewsRequest getNewsRequest)) if (!(request is GetNewsRequest getNewsRequest))
return; return false;
getNewsRequest.TriggerSuccess(r); getNewsRequest.TriggerSuccess(r);
return true;
}; };
}); });

View File

@ -170,6 +170,17 @@ namespace osu.Game.Tests.Visual.Playlists
private void bindHandler(bool delayed = false, ScoreInfo userScore = null, bool failRequests = false) => ((DummyAPIAccess)API).HandleRequest = request => private void bindHandler(bool delayed = false, ScoreInfo userScore = null, bool failRequests = false) => ((DummyAPIAccess)API).HandleRequest = request =>
{ {
// pre-check for requests we should be handling (as they are scheduled below).
switch (request)
{
case ShowPlaylistUserScoreRequest _:
case IndexPlaylistScoresRequest _:
break;
default:
return false;
}
requestComplete = false; requestComplete = false;
double delay = delayed ? 3000 : 0; double delay = delayed ? 3000 : 0;
@ -196,6 +207,8 @@ namespace osu.Game.Tests.Visual.Playlists
break; break;
} }
}, delay); }, delay);
return true;
}; };
private void triggerSuccess<T>(APIRequest<T> req, T result) private void triggerSuccess<T>(APIRequest<T> req, T result)

View File

@ -45,6 +45,8 @@ namespace osu.Game.Tests.Visual.Settings
public Bindable<Vector2> AreaOffset { get; } = new Bindable<Vector2>(); public Bindable<Vector2> AreaOffset { get; } = new Bindable<Vector2>();
public Bindable<Vector2> AreaSize { get; } = new Bindable<Vector2>(); public Bindable<Vector2> AreaSize { get; } = new Bindable<Vector2>();
public Bindable<float> Rotation { get; } = new Bindable<float>();
public IBindable<TabletInfo> Tablet => tablet; public IBindable<TabletInfo> Tablet => tablet;
private readonly Bindable<TabletInfo> tablet = new Bindable<TabletInfo>(); private readonly Bindable<TabletInfo> tablet = new Bindable<TabletInfo>();

View File

@ -32,8 +32,10 @@ namespace osu.Game.Tests.Visual.SongSelect
{ {
case GetUserRequest userRequest: case GetUserRequest userRequest:
userRequest.TriggerSuccess(getUser(userRequest.Ruleset.ID)); userRequest.TriggerSuccess(getUser(userRequest.Ruleset.ID));
break; return true;
} }
return false;
}; };
}); });
@ -186,7 +188,6 @@ namespace osu.Game.Tests.Visual.SongSelect
Metadata = metadata, Metadata = metadata,
BaseDifficulty = new BeatmapDifficulty(), BaseDifficulty = new BeatmapDifficulty(),
Ruleset = ruleset, Ruleset = ruleset,
RulesetID = ruleset.ID.GetValueOrDefault(), // workaround for efcore 5 compatibility.
StarDifficulty = difficultyIndex + 1, StarDifficulty = difficultyIndex + 1,
Version = $"SR{difficultyIndex + 1}" Version = $"SR{difficultyIndex + 1}"
}).ToList() }).ToList()

View File

@ -911,11 +911,9 @@ namespace osu.Game.Tests.Visual.SongSelect
int length = RNG.Next(30000, 200000); int length = RNG.Next(30000, 200000);
double bpm = RNG.NextSingle(80, 200); double bpm = RNG.NextSingle(80, 200);
var ruleset = getRuleset();
beatmaps.Add(new BeatmapInfo beatmaps.Add(new BeatmapInfo
{ {
Ruleset = ruleset, Ruleset = getRuleset(),
RulesetID = ruleset.ID.GetValueOrDefault(), // workaround for efcore 5 compatibility.
OnlineBeatmapID = beatmapId, OnlineBeatmapID = beatmapId,
Version = $"{beatmapId} (length {TimeSpan.FromMilliseconds(length):m\\:ss}, bpm {bpm:0.#})", Version = $"{beatmapId} (length {TimeSpan.FromMilliseconds(length):m\\:ss}, bpm {bpm:0.#})",
Length = length, Length = length,

View File

@ -34,6 +34,7 @@ namespace osu.Game.Tests.Visual.UserInterface
public void SetUp() => Schedule(() => public void SetUp() => Schedule(() =>
{ {
OsuSpriteText query; OsuSpriteText query;
OsuSpriteText general;
OsuSpriteText ruleset; OsuSpriteText ruleset;
OsuSpriteText category; OsuSpriteText category;
OsuSpriteText genre; OsuSpriteText genre;
@ -58,6 +59,7 @@ namespace osu.Game.Tests.Visual.UserInterface
Children = new Drawable[] Children = new Drawable[]
{ {
query = new OsuSpriteText(), query = new OsuSpriteText(),
general = new OsuSpriteText(),
ruleset = new OsuSpriteText(), ruleset = new OsuSpriteText(),
category = new OsuSpriteText(), category = new OsuSpriteText(),
genre = new OsuSpriteText(), genre = new OsuSpriteText(),
@ -71,6 +73,7 @@ namespace osu.Game.Tests.Visual.UserInterface
}; };
control.Query.BindValueChanged(q => query.Text = $"Query: {q.NewValue}", true); control.Query.BindValueChanged(q => query.Text = $"Query: {q.NewValue}", true);
control.General.BindCollectionChanged((u, v) => general.Text = $"General: {(control.General.Any() ? string.Join('.', control.General.Select(i => i.ToString().ToLowerInvariant())) : "")}", true);
control.Ruleset.BindValueChanged(r => ruleset.Text = $"Ruleset: {r.NewValue}", true); control.Ruleset.BindValueChanged(r => ruleset.Text = $"Ruleset: {r.NewValue}", true);
control.Category.BindValueChanged(c => category.Text = $"Category: {c.NewValue}", true); control.Category.BindValueChanged(c => category.Text = $"Category: {c.NewValue}", true);
control.Genre.BindValueChanged(g => genre.Text = $"Genre: {g.NewValue}", true); control.Genre.BindValueChanged(g => genre.Text = $"Genre: {g.NewValue}", true);

View File

@ -6,7 +6,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
<PackageReference Include="NUnit" Version="3.13.1" /> <PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
<PackageReference Include="Moq" Version="4.16.1" /> <PackageReference Include="Moq" Version="4.16.1" />
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Project"> <PropertyGroup Label="Project">

View File

@ -0,0 +1,73 @@
// 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;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Tournament.IO;
using osu.Game.Tournament.IPC;
namespace osu.Game.Tournament.Tests.NonVisual
{
[TestFixture]
public class IPCLocationTest
{
[Test]
public void CheckIPCLocation()
{
// don't use clean run because files are being written before osu! launches.
using (HeadlessGameHost host = new HeadlessGameHost(nameof(CheckIPCLocation)))
{
string basePath = Path.Combine(RuntimeInfo.StartupDirectory, "headless", nameof(CheckIPCLocation));
// Set up a fake IPC client for the IPC Storage to switch to.
string testStableInstallDirectory = Path.Combine(basePath, "stable-ce");
Directory.CreateDirectory(testStableInstallDirectory);
string ipcFile = Path.Combine(testStableInstallDirectory, "ipc.txt");
File.WriteAllText(ipcFile, string.Empty);
try
{
var osu = loadOsu(host);
TournamentStorage storage = (TournamentStorage)osu.Dependencies.Get<Storage>();
FileBasedIPC ipc = null;
waitForOrAssert(() => (ipc = osu.Dependencies.Get<MatchIPCInfo>() as FileBasedIPC) != null, @"ipc could not be populated in a reasonable amount of time");
Assert.True(ipc.SetIPCLocation(testStableInstallDirectory));
Assert.True(storage.AllTournaments.Exists("stable.json"));
}
finally
{
host.Storage.DeleteDirectory(testStableInstallDirectory);
host.Storage.DeleteDirectory("tournaments");
host.Exit();
}
}
}
private TournamentGameBase loadOsu(GameHost host)
{
var osu = new TournamentGameBase();
Task.Run(() => host.Run(osu));
waitForOrAssert(() => osu.IsLoaded, @"osu! failed to start in a reasonable amount of time");
return osu;
}
private static void waitForOrAssert(Func<bool> result, string failureMessage, int timeout = 90000)
{
Task task = Task.Run(() =>
{
while (!result()) Thread.Sleep(200);
});
Assert.IsTrue(task.Wait(timeout), failureMessage);
}
}
}

View File

@ -1,12 +1,12 @@
// 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 System.Collections.Generic;
using System.IO;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Logging; using osu.Framework.Logging;
using osu.Framework.Platform; using osu.Framework.Platform;
using osu.Game.IO; using osu.Game.IO;
using System.IO;
using System.Collections.Generic;
using osu.Game.Tournament.Configuration; using osu.Game.Tournament.Configuration;
namespace osu.Game.Tournament.IO namespace osu.Game.Tournament.IO
@ -15,7 +15,12 @@ namespace osu.Game.Tournament.IO
{ {
private const string default_tournament = "default"; private const string default_tournament = "default";
private readonly Storage storage; private readonly Storage storage;
private readonly Storage allTournaments;
/// <summary>
/// The storage where all tournaments are located.
/// </summary>
public readonly Storage AllTournaments;
private readonly TournamentStorageManager storageConfig; private readonly TournamentStorageManager storageConfig;
public readonly Bindable<string> CurrentTournament; public readonly Bindable<string> CurrentTournament;
@ -23,16 +28,16 @@ namespace osu.Game.Tournament.IO
: base(storage.GetStorageForDirectory("tournaments"), string.Empty) : base(storage.GetStorageForDirectory("tournaments"), string.Empty)
{ {
this.storage = storage; this.storage = storage;
allTournaments = UnderlyingStorage; AllTournaments = UnderlyingStorage;
storageConfig = new TournamentStorageManager(storage); storageConfig = new TournamentStorageManager(storage);
if (storage.Exists("tournament.ini")) if (storage.Exists("tournament.ini"))
{ {
ChangeTargetStorage(allTournaments.GetStorageForDirectory(storageConfig.Get<string>(StorageConfig.CurrentTournament))); ChangeTargetStorage(AllTournaments.GetStorageForDirectory(storageConfig.Get<string>(StorageConfig.CurrentTournament)));
} }
else else
Migrate(allTournaments.GetStorageForDirectory(default_tournament)); Migrate(AllTournaments.GetStorageForDirectory(default_tournament));
CurrentTournament = storageConfig.GetBindable<string>(StorageConfig.CurrentTournament); CurrentTournament = storageConfig.GetBindable<string>(StorageConfig.CurrentTournament);
Logger.Log("Using tournament storage: " + GetFullPath(string.Empty)); Logger.Log("Using tournament storage: " + GetFullPath(string.Empty));
@ -42,11 +47,11 @@ namespace osu.Game.Tournament.IO
private void updateTournament(ValueChangedEvent<string> newTournament) private void updateTournament(ValueChangedEvent<string> newTournament)
{ {
ChangeTargetStorage(allTournaments.GetStorageForDirectory(newTournament.NewValue)); ChangeTargetStorage(AllTournaments.GetStorageForDirectory(newTournament.NewValue));
Logger.Log("Changing tournament storage: " + GetFullPath(string.Empty)); Logger.Log("Changing tournament storage: " + GetFullPath(string.Empty));
} }
public IEnumerable<string> ListTournaments() => allTournaments.GetDirectories(string.Empty); public IEnumerable<string> ListTournaments() => AllTournaments.GetDirectories(string.Empty);
public override void Migrate(Storage newStorage) public override void Migrate(Storage newStorage)
{ {

View File

@ -5,6 +5,7 @@ using System;
using System.IO; using System.IO;
using Newtonsoft.Json; using Newtonsoft.Json;
using osu.Framework.Platform; using osu.Framework.Platform;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Models namespace osu.Game.Tournament.Models
{ {
@ -24,13 +25,14 @@ namespace osu.Game.Tournament.Models
/// </summary> /// </summary>
public event Action OnStableInfoSaved; public event Action OnStableInfoSaved;
private const string config_path = "tournament/stable.json"; private const string config_path = "stable.json";
private readonly Storage storage; private readonly Storage storage;
public StableInfo(Storage storage) public StableInfo(Storage storage)
{ {
this.storage = storage; TournamentStorage tStorage = (TournamentStorage)storage;
this.storage = tStorage.AllTournaments;
if (!storage.Exists(config_path)) if (!storage.Exists(config_path))
return; return;

View File

@ -2,6 +2,7 @@
// 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 System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -43,10 +44,13 @@ namespace osu.Game.Tournament.Screens.Editors
private void addAllCountries() private void addAllCountries()
{ {
List<TournamentTeam> countries; List<TournamentTeam> countries;
using (Stream stream = game.Resources.GetStream("Resources/countries.json")) using (Stream stream = game.Resources.GetStream("Resources/countries.json"))
using (var sr = new StreamReader(stream)) using (var sr = new StreamReader(stream))
countries = JsonConvert.DeserializeObject<List<TournamentTeam>>(sr.ReadToEnd()); countries = JsonConvert.DeserializeObject<List<TournamentTeam>>(sr.ReadToEnd());
Debug.Assert(countries != null);
foreach (var c in countries) foreach (var c in countries)
Storage.Add(c); Storage.Add(c);
} }

View File

@ -2,18 +2,21 @@
// 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 System.Drawing; using System.Drawing;
using osu.Framework.Extensions.Color4Extensions; using System.Linq;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Configuration; using osu.Framework.Configuration;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Colour; using osu.Framework.Input.Handlers.Mouse;
using osu.Game.Graphics.Cursor; using osu.Framework.Platform;
using osu.Game.Tournament.Models;
using osu.Game.Graphics; using osu.Game.Graphics;
using osu.Game.Graphics.Cursor;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.Models;
using osuTK; using osuTK;
using osuTK.Graphics; using osuTK.Graphics;
@ -36,7 +39,7 @@ namespace osu.Game.Tournament
private LoadingSpinner loadingSpinner; private LoadingSpinner loadingSpinner;
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load(FrameworkConfigManager frameworkConfig) private void load(FrameworkConfigManager frameworkConfig, GameHost host)
{ {
windowSize = frameworkConfig.GetBindable<Size>(FrameworkSetting.WindowedSize); windowSize = frameworkConfig.GetBindable<Size>(FrameworkSetting.WindowedSize);
windowMode = frameworkConfig.GetBindable<WindowMode>(FrameworkSetting.WindowMode); windowMode = frameworkConfig.GetBindable<WindowMode>(FrameworkSetting.WindowMode);
@ -48,6 +51,13 @@ namespace osu.Game.Tournament
Margin = new MarginPadding(40), Margin = new MarginPadding(40),
}); });
// in order to have the OS mouse cursor visible, relative mode needs to be disabled.
// can potentially be removed when https://github.com/ppy/osu-framework/issues/4309 is resolved.
var mouseHandler = host.AvailableInputHandlers.OfType<MouseHandler>().FirstOrDefault();
if (mouseHandler != null)
mouseHandler.UseRelativeMode.Value = false;
loadingSpinner.Show(); loadingSpinner.Show();
BracketLoadTask.ContinueWith(_ => LoadComponentsAsync(new[] BracketLoadTask.ContinueWith(_ => LoadComponentsAsync(new[]

View File

@ -171,8 +171,6 @@ namespace osu.Game.Beatmaps
if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null)) if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null))
throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}."); throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}.");
beatmapSet.Requery(ContextFactory);
// check if a set already exists with the same online id, delete if it does. // check if a set already exists with the same online id, delete if it does.
if (beatmapSet.OnlineBeatmapSetID != null) if (beatmapSet.OnlineBeatmapSetID != null)
{ {

View File

@ -36,7 +36,13 @@ namespace osu.Game.Beatmaps.Formats
if (ShouldSkipLine(line)) if (ShouldSkipLine(line))
continue; continue;
line = StripComments(line).TrimEnd(); if (section != Section.Metadata)
{
// comments should not be stripped from metadata lines, as the song metadata may contain "//" as valid data.
line = StripComments(line);
}
line = line.TrimEnd();
if (line.StartsWith('[') && line.EndsWith(']')) if (line.StartsWith('[') && line.EndsWith(']'))
{ {

View File

@ -462,8 +462,6 @@ namespace osu.Game.Database
// Dereference the existing file info, since the file model will be removed. // Dereference the existing file info, since the file model will be removed.
if (file.FileInfo != null) if (file.FileInfo != null)
{ {
file.Requery(usage.Context);
Files.Dereference(file.FileInfo); Files.Dereference(file.FileInfo);
// This shouldn't be required, but here for safety in case the provided TModel is not being change tracked // This shouldn't be required, but here for safety in case the provided TModel is not being change tracked
@ -637,12 +635,10 @@ namespace osu.Game.Database
{ {
using (Stream s = reader.GetStream(file)) using (Stream s = reader.GetStream(file))
{ {
var fileInfo = files.Add(s);
fileInfos.Add(new TFileModel fileInfos.Add(new TFileModel
{ {
Filename = file.Substring(prefix.Length).ToStandardisedPath(), Filename = file.Substring(prefix.Length).ToStandardisedPath(),
FileInfo = fileInfo, FileInfo = files.Add(s)
FileInfoID = fileInfo.ID // workaround for efcore 5 compatibility.
}); });
} }
} }

View File

@ -1,71 +0,0 @@
// 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;
using System.Collections.Generic;
using osu.Game.Beatmaps;
using osu.Game.Scoring;
using osu.Game.Skinning;
namespace osu.Game.Database
{
/// <summary>
/// Extension methods which contain workarounds to make EFcore 5.x work with our existing (incorrect) thread safety.
/// The intention is to avoid blocking package updates while we consider the future of the database backend, with a potential backend switch imminent.
/// </summary>
public static class DatabaseWorkaroundExtensions
{
/// <summary>
/// Re-query the provided model to ensure it is in a sane state. This method requires explicit implementation per model type.
/// </summary>
/// <param name="model"></param>
/// <param name="contextFactory"></param>
public static void Requery(this IHasPrimaryKey model, IDatabaseContextFactory contextFactory)
{
switch (model)
{
case SkinInfo skinInfo:
requeryFiles(skinInfo.Files, contextFactory);
break;
case ScoreInfo scoreInfo:
requeryFiles(scoreInfo.Beatmap.BeatmapSet.Files, contextFactory);
requeryFiles(scoreInfo.Files, contextFactory);
break;
case BeatmapSetInfo beatmapSetInfo:
var context = contextFactory.Get();
foreach (var beatmap in beatmapSetInfo.Beatmaps)
{
// Workaround System.InvalidOperationException
// The instance of entity type 'RulesetInfo' cannot be tracked because another instance with the same key value for {'ID'} is already being tracked.
beatmap.Ruleset = context.RulesetInfo.Find(beatmap.RulesetID);
}
requeryFiles(beatmapSetInfo.Files, contextFactory);
break;
default:
throw new ArgumentException($"{nameof(Requery)} does not have support for the provided model type", nameof(model));
}
void requeryFiles<T>(List<T> files, IDatabaseContextFactory databaseContextFactory) where T : class, INamedFileInfo
{
var dbContext = databaseContextFactory.Get();
foreach (var file in files)
{
Requery(file, dbContext);
}
}
}
public static void Requery(this INamedFileInfo file, OsuDbContext dbContext)
{
// Workaround System.InvalidOperationException
// The instance of entity type 'FileInfo' cannot be tracked because another instance with the same key value for {'ID'} is already being tracked.
file.FileInfo = dbContext.FileInfo.Find(file.FileInfoID);
}
}
}

View File

@ -3,6 +3,7 @@
using System; using System;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using osu.Framework.Logging; using osu.Framework.Logging;
using osu.Framework.Statistics; using osu.Framework.Statistics;
@ -110,10 +111,10 @@ namespace osu.Game.Database
{ {
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
optionsBuilder optionsBuilder
.UseSqlite(connectionString, // this is required for the time being due to the way we are querying in places like BeatmapStore.
sqliteOptions => sqliteOptions // if we ever move to having consumers file their own .Includes, or get eager loading support, this could be re-enabled.
.CommandTimeout(10) .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning))
.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery)) .UseSqlite(connectionString, sqliteOptions => sqliteOptions.CommandTimeout(10))
.UseLoggerFactory(logger.Value); .UseLoggerFactory(logger.Value);
} }

View File

@ -34,8 +34,6 @@ namespace osu.Game.Input.Handlers
public override bool IsActive => true; public override bool IsActive => true;
public override int Priority => 0;
public class ReplayState<T> : IInput public class ReplayState<T> : IInput
where T : struct where T : struct
{ {

View File

@ -131,8 +131,11 @@ namespace osu.Game.Online.API
{ {
} }
private bool succeeded;
internal virtual void TriggerSuccess() internal virtual void TriggerSuccess()
{ {
succeeded = true;
Success?.Invoke(); Success?.Invoke();
} }
@ -145,10 +148,7 @@ namespace osu.Game.Online.API
public void Fail(Exception e) public void Fail(Exception e)
{ {
if (WebRequest?.Completed == true) if (succeeded || cancelled)
return;
if (cancelled)
return; return;
cancelled = true; cancelled = true;
@ -181,9 +181,13 @@ namespace osu.Game.Online.API
/// <returns>Whether we are in a failed or cancelled state.</returns> /// <returns>Whether we are in a failed or cancelled state.</returns>
private bool checkAndScheduleFailure() private bool checkAndScheduleFailure()
{ {
if (API == null || pendingFailure == null) return cancelled; if (pendingFailure == null) return cancelled;
if (API == null)
pendingFailure();
else
API.Schedule(pendingFailure); API.Schedule(pendingFailure);
pendingFailure = null; pendingFailure = null;
return true; return true;
} }

View File

@ -34,8 +34,9 @@ namespace osu.Game.Online.API
/// <summary> /// <summary>
/// Provide handling logic for an arbitrary API request. /// Provide handling logic for an arbitrary API request.
/// Should return true is a request was handled. If null or false return, the request will be failed with a <see cref="NotSupportedException"/>.
/// </summary> /// </summary>
public Action<APIRequest> HandleRequest; public Func<APIRequest, bool> HandleRequest;
private readonly Bindable<APIState> state = new Bindable<APIState>(APIState.Online); private readonly Bindable<APIState> state = new Bindable<APIState>(APIState.Online);
@ -55,7 +56,12 @@ namespace osu.Game.Online.API
public virtual void Queue(APIRequest request) public virtual void Queue(APIRequest request)
{ {
HandleRequest?.Invoke(request); if (HandleRequest?.Invoke(request) != true)
{
// this will fail due to not receiving an APIAccess, and trigger a failure on the request.
// this is intended - any request in testing that needs non-failures should use HandleRequest.
request.Perform(this);
}
} }
public void Perform(APIRequest request) => HandleRequest?.Invoke(request); public void Perform(APIRequest request) => HandleRequest?.Invoke(request);

View File

@ -15,6 +15,9 @@ namespace osu.Game.Online.API.Requests
{ {
public class SearchBeatmapSetsRequest : APIRequest<SearchBeatmapSetsResponse> public class SearchBeatmapSetsRequest : APIRequest<SearchBeatmapSetsResponse>
{ {
[CanBeNull]
public IReadOnlyCollection<SearchGeneral> General { get; }
public SearchCategory SearchCategory { get; } public SearchCategory SearchCategory { get; }
public SortCriteria SortCriteria { get; } public SortCriteria SortCriteria { get; }
@ -45,6 +48,7 @@ namespace osu.Game.Online.API.Requests
string query, string query,
RulesetInfo ruleset, RulesetInfo ruleset,
Cursor cursor = null, Cursor cursor = null,
IReadOnlyCollection<SearchGeneral> general = null,
SearchCategory searchCategory = SearchCategory.Any, SearchCategory searchCategory = SearchCategory.Any,
SortCriteria sortCriteria = SortCriteria.Ranked, SortCriteria sortCriteria = SortCriteria.Ranked,
SortDirection sortDirection = SortDirection.Descending, SortDirection sortDirection = SortDirection.Descending,
@ -59,6 +63,7 @@ namespace osu.Game.Online.API.Requests
this.ruleset = ruleset; this.ruleset = ruleset;
this.cursor = cursor; this.cursor = cursor;
General = general;
SearchCategory = searchCategory; SearchCategory = searchCategory;
SortCriteria = sortCriteria; SortCriteria = sortCriteria;
SortDirection = sortDirection; SortDirection = sortDirection;
@ -75,6 +80,9 @@ namespace osu.Game.Online.API.Requests
var req = base.CreateWebRequest(); var req = base.CreateWebRequest();
req.AddParameter("q", query); req.AddParameter("q", query);
if (General != null && General.Any())
req.AddParameter("c", string.Join('.', General.Select(e => e.ToString().ToLowerInvariant())));
if (ruleset.ID.HasValue) if (ruleset.ID.HasValue)
req.AddParameter("m", ruleset.ID.Value.ToString()); req.AddParameter("m", ruleset.ID.Value.ToString());

View File

@ -123,13 +123,13 @@ namespace osu.Game.Online
{ {
if (attachedRequest.Progress == 1) if (attachedRequest.Progress == 1)
{ {
State.Value = DownloadState.Importing;
Progress.Value = 1; Progress.Value = 1;
State.Value = DownloadState.Importing;
} }
else else
{ {
State.Value = DownloadState.Downloading;
Progress.Value = attachedRequest.Progress; Progress.Value = attachedRequest.Progress;
State.Value = DownloadState.Downloading;
attachedRequest.Failure += onRequestFailure; attachedRequest.Failure += onRequestFailure;
attachedRequest.DownloadProgressed += onRequestProgress; attachedRequest.DownloadProgressed += onRequestProgress;

View File

@ -8,6 +8,6 @@ namespace osu.Game.Online.Rooms
public class APIScoreToken public class APIScoreToken
{ {
[JsonProperty("id")] [JsonProperty("id")]
public int ID { get; set; } public long ID { get; set; }
} }
} }

View File

@ -45,6 +45,9 @@ namespace osu.Game.Online.Rooms
Progress.BindValueChanged(_ => Progress.BindValueChanged(_ =>
{ {
if (State.Value != DownloadState.Downloading)
return;
// incoming progress changes are going to be at a very high rate. // incoming progress changes are going to be at a very high rate.
// we don't want to flood the network with this, so rate limit how often we send progress updates. // we don't want to flood the network with this, so rate limit how often we send progress updates.
if (progressUpdate?.Completed != false) if (progressUpdate?.Completed != false)

View File

@ -0,0 +1,32 @@
// 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 osu.Framework.IO.Network;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
namespace osu.Game.Online.Solo
{
public class CreateSoloScoreRequest : APIRequest<APIScoreToken>
{
private readonly int beatmapId;
private readonly string versionHash;
public CreateSoloScoreRequest(int beatmapId, string versionHash)
{
this.beatmapId = beatmapId;
this.versionHash = versionHash;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Post;
req.AddParameter("version_hash", versionHash);
return req;
}
protected override string Target => $@"solo/{beatmapId}/scores";
}
}

View File

@ -0,0 +1,45 @@
// 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>
{
private readonly long scoreId;
private readonly int beatmapId;
private readonly ScoreInfo scoreInfo;
public SubmitSoloScoreRequest(int beatmapId, long scoreId, ScoreInfo scoreInfo)
{
this.beatmapId = beatmapId;
this.scoreId = scoreId;
this.scoreInfo = scoreInfo;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.ContentType = "application/json";
req.Method = HttpMethod.Put;
req.AddRaw(JsonConvert.SerializeObject(scoreInfo, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
return req;
}
protected override string Target => $@"solo/{beatmapId}/scores/{scoreId}";
}
}

Some files were not shown because too many files have changed in this diff Show More