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

Merge branch 'master' into morth-taiko-changes

This commit is contained in:
smoogipoo 2020-08-13 00:31:10 +09:00
commit 90189fc40c
143 changed files with 3460 additions and 1164 deletions

View File

@ -51,7 +51,7 @@
<Reference Include="Java.Interop" /> <Reference Include="Java.Interop" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="ppy.osu.Game.Resources" Version="2020.727.1" /> <PackageReference Include="ppy.osu.Game.Resources" Version="2020.731.0" />
<PackageReference Include="ppy.osu.Framework.Android" Version="2020.723.0" /> <PackageReference Include="ppy.osu.Framework.Android" Version="2020.810.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -2,7 +2,7 @@
<Import Project="..\osu.TestProject.props" /> <Import Project="..\osu.TestProject.props" />
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" /> <PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="NUnit" Version="3.12.0" /> <PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />

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 System.Collections.Generic;
using osu.Game.Audio;
using osu.Game.Rulesets.Catch.Judgements; using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Judgements;
@ -8,8 +10,27 @@ namespace osu.Game.Rulesets.Catch.Objects
{ {
public class Banana : Fruit public class Banana : Fruit
{ {
/// <summary>
/// Index of banana in current shower.
/// </summary>
public int BananaIndex;
public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana; public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana;
public override Judgement CreateJudgement() => new CatchBananaJudgement(); public override Judgement CreateJudgement() => new CatchBananaJudgement();
private static readonly List<HitSampleInfo> samples = new List<HitSampleInfo> { new BananaHitSampleInfo() };
public Banana()
{
Samples = samples;
}
private class BananaHitSampleInfo : HitSampleInfo
{
private static string[] lookupNames { get; } = { "metronomelow", "catch-banana" };
public override IEnumerable<string> LookupNames => lookupNames;
}
} }
} }

View File

@ -30,15 +30,21 @@ namespace osu.Game.Rulesets.Catch.Objects
if (spacing <= 0) if (spacing <= 0)
return; return;
for (double i = StartTime; i <= EndTime; i += spacing) double time = StartTime;
int i = 0;
while (time <= EndTime)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
AddNested(new Banana AddNested(new Banana
{ {
Samples = Samples, StartTime = time,
StartTime = i BananaIndex = i,
}); });
time += spacing;
i++;
} }
} }

View File

@ -40,6 +40,13 @@ namespace osu.Game.Rulesets.Catch.Objects.Drawables
float getRandomAngle() => 180 * (RNG.NextSingle() * 2 - 1); float getRandomAngle() => 180 * (RNG.NextSingle() * 2 - 1);
} }
public override void PlaySamples()
{
base.PlaySamples();
if (Samples != null)
Samples.Frequency.Value = 0.77f + ((Banana)HitObject).BananaIndex * 0.006f;
}
private Color4 getBananaColour() private Color4 getBananaColour()
{ {
switch (RNG.Next(0, 3)) switch (RNG.Next(0, 3))

View File

@ -1,23 +1,27 @@
// 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.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Pooling;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Judgements;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Mania.UI;
using osu.Game.Skinning; using osu.Game.Rulesets.Objects;
using osuTK; using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Mania.Tests.Skinning namespace osu.Game.Rulesets.Mania.Tests.Skinning
{ {
[TestFixture] [TestFixture]
public class TestSceneHitExplosion : ManiaSkinnableTestScene public class TestSceneHitExplosion : ManiaSkinnableTestScene
{ {
private readonly List<DrawablePool<PoolableHitExplosion>> hitExplosionPools = new List<DrawablePool<PoolableHitExplosion>>();
public TestSceneHitExplosion() public TestSceneHitExplosion()
{ {
int runcount = 0; int runcount = 0;
@ -29,28 +33,40 @@ namespace osu.Game.Rulesets.Mania.Tests.Skinning
if (runcount % 15 > 12) if (runcount % 15 > 12)
return; return;
CreatedDrawables.OfType<Container>().ForEach(c => int poolIndex = 0;
foreach (var c in CreatedDrawables.OfType<Container>())
{ {
c.Add(new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion, 0), c.Add(hitExplosionPools[poolIndex].Get(e =>
_ => new DefaultHitExplosion((runcount / 15) % 2 == 0 ? new Color4(94, 0, 57, 255) : new Color4(6, 84, 0, 255), runcount % 6 != 0)
{ {
Anchor = Anchor.Centre, e.Apply(new JudgementResult(new HitObject(), runcount % 6 == 0 ? new HoldNoteTickJudgement() : new ManiaJudgement()));
Origin = Anchor.Centre,
e.Anchor = Anchor.Centre;
e.Origin = Anchor.Centre;
})); }));
});
poolIndex++;
}
}, 100); }, 100);
} }
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {
SetContents(() => new ColumnTestContainer(0, ManiaAction.Key1) SetContents(() =>
{
var pool = new DrawablePool<PoolableHitExplosion>(5);
hitExplosionPools.Add(pool);
return new ColumnTestContainer(0, ManiaAction.Key1)
{ {
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
RelativePositionAxes = Axes.Y, RelativePositionAxes = Axes.Y,
Y = -0.25f, Y = -0.25f,
Size = new Vector2(Column.COLUMN_WIDTH, DefaultNotePiece.NOTE_HEIGHT), Size = new Vector2(Column.COLUMN_WIDTH, DefaultNotePiece.NOTE_HEIGHT),
Child = pool
};
}); });
} }
} }

View File

@ -2,7 +2,7 @@
<Import Project="..\osu.TestProject.props" /> <Import Project="..\osu.TestProject.props" />
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" /> <PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="NUnit" Version="3.12.0" /> <PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />

View File

@ -6,13 +6,15 @@ using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Animations; using osu.Framework.Graphics.Animations;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Skinning; using osu.Game.Skinning;
using osuTK; using osuTK;
namespace osu.Game.Rulesets.Mania.Skinning namespace osu.Game.Rulesets.Mania.Skinning
{ {
public class LegacyHitExplosion : LegacyManiaColumnElement public class LegacyHitExplosion : LegacyManiaColumnElement, IHitExplosion
{ {
private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>(); private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();
@ -62,9 +64,9 @@ namespace osu.Game.Rulesets.Mania.Skinning
explosion.Anchor = direction.NewValue == ScrollingDirection.Up ? Anchor.TopCentre : Anchor.BottomCentre; explosion.Anchor = direction.NewValue == ScrollingDirection.Up ? Anchor.TopCentre : Anchor.BottomCentre;
} }
protected override void LoadComplete() public void Animate(JudgementResult result)
{ {
base.LoadComplete(); (explosion as IFramedAnimation)?.GotoFrame(0);
explosion?.FadeInFromZero(80) explosion?.FadeInFromZero(80)
.Then().FadeOut(120); .Then().FadeOut(120);

View File

@ -9,9 +9,9 @@ using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Input.Bindings; using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.UI.Components; using osu.Game.Rulesets.Mania.UI.Components;
using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Skinning; using osu.Game.Skinning;
@ -34,8 +34,8 @@ namespace osu.Game.Rulesets.Mania.UI
public readonly Bindable<ManiaAction> Action = new Bindable<ManiaAction>(); public readonly Bindable<ManiaAction> Action = new Bindable<ManiaAction>();
public readonly ColumnHitObjectArea HitObjectArea; public readonly ColumnHitObjectArea HitObjectArea;
internal readonly Container TopLevelContainer; internal readonly Container TopLevelContainer;
private readonly DrawablePool<PoolableHitExplosion> hitExplosionPool;
public Container UnderlayElements => HitObjectArea.UnderlayElements; public Container UnderlayElements => HitObjectArea.UnderlayElements;
@ -53,6 +53,7 @@ namespace osu.Game.Rulesets.Mania.UI
InternalChildren = new[] InternalChildren = new[]
{ {
hitExplosionPool = new DrawablePool<PoolableHitExplosion>(5),
// For input purposes, the background is added at the highest depth, but is then proxied back below all other elements // For input purposes, the background is added at the highest depth, but is then proxied back below all other elements
background.CreateProxy(), background.CreateProxy(),
HitObjectArea = new ColumnHitObjectArea(Index, HitObjectContainer) { RelativeSizeAxes = Axes.Both }, HitObjectArea = new ColumnHitObjectArea(Index, HitObjectContainer) { RelativeSizeAxes = Axes.Both },
@ -108,15 +109,7 @@ namespace osu.Game.Rulesets.Mania.UI
if (!result.IsHit || !judgedObject.DisplayResult || !DisplayJudgements.Value) if (!result.IsHit || !judgedObject.DisplayResult || !DisplayJudgements.Value)
return; return;
var explosion = new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion, Index), _ => HitObjectArea.Explosions.Add(hitExplosionPool.Get(e => e.Apply(result)));
new DefaultHitExplosion(judgedObject.AccentColour.Value, judgedObject is DrawableHoldNoteTick))
{
RelativeSizeAxes = Axes.Both
};
HitObjectArea.Explosions.Add(explosion);
explosion.Delay(200).Expire(true);
} }
public bool OnPressed(ManiaAction action) public bool OnPressed(ManiaAction action)

View File

@ -8,6 +8,8 @@ using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Effects;
using osu.Framework.Utils; using osu.Framework.Utils;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Judgements;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Rulesets.UI.Scrolling;
using osuTK; using osuTK;
@ -15,35 +17,36 @@ using osuTK.Graphics;
namespace osu.Game.Rulesets.Mania.UI namespace osu.Game.Rulesets.Mania.UI
{ {
public class DefaultHitExplosion : CompositeDrawable public class DefaultHitExplosion : CompositeDrawable, IHitExplosion
{ {
private const float default_large_faint_size = 0.8f;
public override bool RemoveWhenNotAlive => true; public override bool RemoveWhenNotAlive => true;
[Resolved]
private Column column { get; set; }
private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>(); private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();
private readonly CircularContainer largeFaint; private CircularContainer largeFaint;
private readonly CircularContainer mainGlow1; private CircularContainer mainGlow1;
public DefaultHitExplosion(Color4 objectColour, bool isSmall = false) public DefaultHitExplosion()
{ {
Origin = Anchor.Centre; Origin = Anchor.Centre;
RelativeSizeAxes = Axes.X; RelativeSizeAxes = Axes.X;
Height = DefaultNotePiece.NOTE_HEIGHT; Height = DefaultNotePiece.NOTE_HEIGHT;
}
// scale roughly in-line with visual appearance of notes [BackgroundDependencyLoader]
Scale = new Vector2(1f, 0.6f); private void load(IScrollingInfo scrollingInfo)
{
if (isSmall)
Scale *= 0.5f;
const float angle_variangle = 15; // should be less than 45 const float angle_variangle = 15; // should be less than 45
const float roundness = 80; const float roundness = 80;
const float initial_height = 10; const float initial_height = 10;
var colour = Interpolation.ValueAt(0.4f, objectColour, Color4.White, 0, 1); var colour = Interpolation.ValueAt(0.4f, column.AccentColour, Color4.White, 0, 1);
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{ {
@ -54,12 +57,12 @@ namespace osu.Game.Rulesets.Mania.UI
RelativeSizeAxes = Axes.Both, RelativeSizeAxes = Axes.Both,
Masking = true, Masking = true,
// we want our size to be very small so the glow dominates it. // we want our size to be very small so the glow dominates it.
Size = new Vector2(0.8f), Size = new Vector2(default_large_faint_size),
Blending = BlendingParameters.Additive, Blending = BlendingParameters.Additive,
EdgeEffect = new EdgeEffectParameters EdgeEffect = new EdgeEffectParameters
{ {
Type = EdgeEffectType.Glow, Type = EdgeEffectType.Glow,
Colour = Interpolation.ValueAt(0.1f, objectColour, Color4.White, 0, 1).Opacity(0.3f), Colour = Interpolation.ValueAt(0.1f, column.AccentColour, Color4.White, 0, 1).Opacity(0.3f),
Roundness = 160, Roundness = 160,
Radius = 200, Radius = 200,
}, },
@ -74,7 +77,7 @@ namespace osu.Game.Rulesets.Mania.UI
EdgeEffect = new EdgeEffectParameters EdgeEffect = new EdgeEffectParameters
{ {
Type = EdgeEffectType.Glow, Type = EdgeEffectType.Glow,
Colour = Interpolation.ValueAt(0.6f, objectColour, Color4.White, 0, 1), Colour = Interpolation.ValueAt(0.6f, column.AccentColour, Color4.White, 0, 1),
Roundness = 20, Roundness = 20,
Radius = 50, Radius = 50,
}, },
@ -114,30 +117,11 @@ namespace osu.Game.Rulesets.Mania.UI
}, },
} }
}; };
}
[BackgroundDependencyLoader]
private void load(IScrollingInfo scrollingInfo)
{
direction.BindTo(scrollingInfo.Direction); direction.BindTo(scrollingInfo.Direction);
direction.BindValueChanged(onDirectionChanged, true); direction.BindValueChanged(onDirectionChanged, true);
} }
protected override void LoadComplete()
{
const double duration = 200;
base.LoadComplete();
largeFaint
.ResizeTo(largeFaint.Size * new Vector2(5, 1), duration, Easing.OutQuint)
.FadeOut(duration * 2);
mainGlow1.ScaleTo(1.4f, duration, Easing.OutQuint);
this.FadeOut(duration, Easing.Out);
}
private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction) private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction)
{ {
if (direction.NewValue == ScrollingDirection.Up) if (direction.NewValue == ScrollingDirection.Up)
@ -151,5 +135,29 @@ namespace osu.Game.Rulesets.Mania.UI
Y = -DefaultNotePiece.NOTE_HEIGHT / 2; Y = -DefaultNotePiece.NOTE_HEIGHT / 2;
} }
} }
public void Animate(JudgementResult result)
{
// scale roughly in-line with visual appearance of notes
Vector2 scale = new Vector2(1, 0.6f);
if (result.Judgement is HoldNoteTickJudgement)
scale *= 0.5f;
this.ScaleTo(scale);
largeFaint
.ResizeTo(default_large_faint_size)
.Then()
.ResizeTo(default_large_faint_size * new Vector2(5, 1), PoolableHitExplosion.DURATION, Easing.OutQuint)
.FadeOut(PoolableHitExplosion.DURATION * 2);
mainGlow1
.ScaleTo(1)
.Then()
.ScaleTo(1.4f, PoolableHitExplosion.DURATION, Easing.OutQuint);
this.FadeOutFromOne(PoolableHitExplosion.DURATION, Easing.Out);
}
} }
} }

View File

@ -15,6 +15,10 @@ namespace osu.Game.Rulesets.Mania.UI
{ {
} }
public DrawableManiaJudgement()
{
}
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {

View File

@ -0,0 +1,19 @@
// 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.Rulesets.Judgements;
namespace osu.Game.Rulesets.Mania.UI
{
/// <summary>
/// Common interface for all hit explosion bodies.
/// </summary>
public interface IHitExplosion
{
/// <summary>
/// Begins animating this <see cref="IHitExplosion"/>.
/// </summary>
/// <param name="result">The type of <see cref="JudgementResult"/> that caused this explosion.</param>
void Animate(JudgementResult result);
}
}

View File

@ -0,0 +1,51 @@
// 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Game.Rulesets.Judgements;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania.UI
{
public class PoolableHitExplosion : PoolableDrawable
{
public const double DURATION = 200;
public JudgementResult Result { get; private set; }
[Resolved]
private Column column { get; set; }
private SkinnableDrawable skinnableExplosion;
public PoolableHitExplosion()
{
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = skinnableExplosion = new SkinnableDrawable(new ManiaSkinComponent(ManiaSkinComponents.HitExplosion, column.Index), _ => new DefaultHitExplosion())
{
RelativeSizeAxes = Axes.Both
};
}
public void Apply(JudgementResult result)
{
Result = result;
}
protected override void PrepareForUse()
{
base.PrepareForUse();
(skinnableExplosion?.Drawable as IHitExplosion)?.Animate(Result);
this.Delay(DURATION).Then().Expire();
}
}
}

View File

@ -6,6 +6,7 @@ using System.Linq;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Pooling;
using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Objects;
@ -33,8 +34,8 @@ namespace osu.Game.Rulesets.Mania.UI
public IReadOnlyList<Column> Columns => columnFlow.Children; public IReadOnlyList<Column> Columns => columnFlow.Children;
private readonly FillFlowContainer<Column> columnFlow; private readonly FillFlowContainer<Column> columnFlow;
public Container<DrawableManiaJudgement> Judgements => judgements;
private readonly JudgementContainer<DrawableManiaJudgement> judgements; private readonly JudgementContainer<DrawableManiaJudgement> judgements;
private readonly DrawablePool<DrawableManiaJudgement> judgementPool;
private readonly Drawable barLineContainer; private readonly Drawable barLineContainer;
private readonly Container topLevelContainer; private readonly Container topLevelContainer;
@ -63,6 +64,7 @@ namespace osu.Game.Rulesets.Mania.UI
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{ {
judgementPool = new DrawablePool<DrawableManiaJudgement>(2),
new Container new Container
{ {
Anchor = Anchor.TopCentre, Anchor = Anchor.TopCentre,
@ -208,12 +210,14 @@ namespace osu.Game.Rulesets.Mania.UI
if (!judgedObject.DisplayResult || !DisplayJudgements.Value) if (!judgedObject.DisplayResult || !DisplayJudgements.Value)
return; return;
judgements.Clear(); judgements.Clear(false);
judgements.Add(new DrawableManiaJudgement(result, judgedObject) judgements.Add(judgementPool.Get(j =>
{ {
Anchor = Anchor.Centre, j.Apply(result, judgedObject);
Origin = Anchor.Centre,
}); j.Anchor = Anchor.Centre;
j.Origin = Anchor.Centre;
}));
} }
protected override void Update() protected override void Update()

View File

@ -1,12 +1,27 @@
// 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.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Tests.Visual; using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Osu.Tests namespace osu.Game.Rulesets.Osu.Tests
{ {
public abstract class OsuSkinnableTestScene : SkinnableTestScene public abstract class OsuSkinnableTestScene : SkinnableTestScene
{ {
private Container content;
protected override Container<Drawable> Content
{
get
{
if (content == null)
base.Content.Add(content = new OsuInputManager(new RulesetInfo { ID = 0 }));
return content;
}
}
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -3,7 +3,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio; using osu.Game.Audio;
using osu.Game.Beatmaps; using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.ControlPoints;
@ -26,19 +25,6 @@ namespace osu.Game.Rulesets.Osu.Tests
[TestFixture] [TestFixture]
public class TestSceneSlider : OsuSkinnableTestScene public class TestSceneSlider : OsuSkinnableTestScene
{ {
private Container content;
protected override Container<Drawable> Content
{
get
{
if (content == null)
base.Content.Add(content = new OsuInputManager(new RulesetInfo { ID = 0 }));
return content;
}
}
private int depthIndex; private int depthIndex;
public TestSceneSlider() public TestSceneSlider()

View File

@ -4,57 +4,76 @@
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps; using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Osu.Tests namespace osu.Game.Rulesets.Osu.Tests
{ {
[TestFixture] [TestFixture]
public class TestSceneSpinner : OsuTestScene public class TestSceneSpinner : OsuSkinnableTestScene
{ {
private readonly Container content;
protected override Container<Drawable> Content => content;
private int depthIndex; private int depthIndex;
public TestSceneSpinner() private TestDrawableSpinner drawableSpinner;
{
base.Content.Add(content = new OsuInputManager(new RulesetInfo { ID = 0 }));
AddStep("Miss Big", () => testSingle(2)); [TestCase(false)]
AddStep("Miss Medium", () => testSingle(5)); [TestCase(true)]
AddStep("Miss Small", () => testSingle(7)); public void TestVariousSpinners(bool autoplay)
AddStep("Hit Big", () => testSingle(2, true)); {
AddStep("Hit Medium", () => testSingle(5, true)); string term = autoplay ? "Hit" : "Miss";
AddStep("Hit Small", () => testSingle(7, true)); AddStep($"{term} Big", () => SetContents(() => testSingle(2, autoplay)));
AddStep($"{term} Medium", () => SetContents(() => testSingle(5, autoplay)));
AddStep($"{term} Small", () => SetContents(() => testSingle(7, autoplay)));
} }
private void testSingle(float circleSize, bool auto = false) [TestCase(false)]
[TestCase(true)]
public void TestLongSpinner(bool autoplay)
{ {
var spinner = new Spinner { StartTime = Time.Current + 2000, EndTime = Time.Current + 5000 }; AddStep("Very short spinner", () => SetContents(() => testSingle(5, autoplay, 2000)));
AddUntilStep("Wait for completion", () => drawableSpinner.Result.HasResult);
AddUntilStep("Check correct progress", () => drawableSpinner.Progress == (autoplay ? 1 : 0));
}
[TestCase(false)]
[TestCase(true)]
public void TestSuperShortSpinner(bool autoplay)
{
AddStep("Very short spinner", () => SetContents(() => testSingle(5, autoplay, 200)));
AddUntilStep("Wait for completion", () => drawableSpinner.Result.HasResult);
AddUntilStep("Short spinner implicitly completes", () => drawableSpinner.Progress == 1);
}
private Drawable testSingle(float circleSize, bool auto = false, double length = 3000)
{
const double delay = 2000;
var spinner = new Spinner
{
StartTime = Time.Current + delay,
EndTime = Time.Current + delay + length
};
spinner.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty { CircleSize = circleSize }); spinner.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty { CircleSize = circleSize });
var drawable = new TestDrawableSpinner(spinner, auto) drawableSpinner = new TestDrawableSpinner(spinner, auto)
{ {
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Depth = depthIndex++ Depth = depthIndex++
}; };
foreach (var mod in SelectedMods.Value.OfType<IApplicableToDrawableHitObjects>()) foreach (var mod in SelectedMods.Value.OfType<IApplicableToDrawableHitObjects>())
mod.ApplyToDrawableHitObjects(new[] { drawable }); mod.ApplyToDrawableHitObjects(new[] { drawableSpinner });
Add(drawable); return drawableSpinner;
} }
private class TestDrawableSpinner : DrawableSpinner private class TestDrawableSpinner : DrawableSpinner
{ {
private bool auto; private readonly bool auto;
public TestDrawableSpinner(Spinner s, bool auto) public TestDrawableSpinner(Spinner s, bool auto)
: base(s) : base(s)
@ -62,16 +81,11 @@ namespace osu.Game.Rulesets.Osu.Tests
this.auto = auto; this.auto = auto;
} }
protected override void CheckForResult(bool userTriggered, double timeOffset) protected override void Update()
{ {
if (auto && !userTriggered && Time.Current > Spinner.StartTime + Spinner.Duration / 2 && Progress < 1) base.Update();
{ if (auto)
// force completion only once to not break human interaction RotationTracker.AddRotation((float)(Clock.ElapsedFrameTime * 3));
Disc.CumulativeRotation = Spinner.SpinsRequired * 360;
auto = false;
}
base.CheckForResult(userTriggered, timeOffset);
} }
} }
} }

View File

@ -1,11 +1,13 @@
// 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;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Audio; using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Sprites;
using osu.Framework.Testing; using osu.Framework.Testing;
using osu.Framework.Timing; using osu.Framework.Timing;
@ -60,66 +62,75 @@ namespace osu.Game.Rulesets.Osu.Tests
[Test] [Test]
public void TestSpinnerRewindingRotation() public void TestSpinnerRewindingRotation()
{ {
double trackerRotationTolerance = 0;
addSeekStep(5000); addSeekStep(5000);
AddAssert("is disc rotation not almost 0", () => !Precision.AlmostEquals(drawableSpinner.Disc.Rotation, 0, 100)); AddStep("calculate rotation tolerance", () =>
AddAssert("is disc rotation absolute not almost 0", () => !Precision.AlmostEquals(drawableSpinner.Disc.CumulativeRotation, 0, 100)); {
trackerRotationTolerance = Math.Abs(drawableSpinner.RotationTracker.Rotation * 0.1f);
});
AddAssert("is disc rotation not almost 0", () => !Precision.AlmostEquals(drawableSpinner.RotationTracker.Rotation, 0, 100));
AddAssert("is disc rotation absolute not almost 0", () => !Precision.AlmostEquals(drawableSpinner.RotationTracker.RateAdjustedRotation, 0, 100));
addSeekStep(0); addSeekStep(0);
AddAssert("is disc rotation almost 0", () => Precision.AlmostEquals(drawableSpinner.Disc.Rotation, 0, 100)); AddAssert("is disc rotation almost 0", () => Precision.AlmostEquals(drawableSpinner.RotationTracker.Rotation, 0, trackerRotationTolerance));
AddAssert("is disc rotation absolute almost 0", () => Precision.AlmostEquals(drawableSpinner.Disc.CumulativeRotation, 0, 100)); AddAssert("is disc rotation absolute almost 0", () => Precision.AlmostEquals(drawableSpinner.RotationTracker.RateAdjustedRotation, 0, 100));
} }
[Test] [Test]
public void TestSpinnerMiddleRewindingRotation() public void TestSpinnerMiddleRewindingRotation()
{ {
double finalAbsoluteDiscRotation = 0, finalRelativeDiscRotation = 0, finalSpinnerSymbolRotation = 0; double finalCumulativeTrackerRotation = 0;
double finalTrackerRotation = 0, trackerRotationTolerance = 0;
double finalSpinnerSymbolRotation = 0, spinnerSymbolRotationTolerance = 0;
addSeekStep(5000); addSeekStep(5000);
AddStep("retrieve disc relative rotation", () => finalRelativeDiscRotation = drawableSpinner.Disc.Rotation); AddStep("retrieve disc rotation", () =>
AddStep("retrieve disc absolute rotation", () => finalAbsoluteDiscRotation = drawableSpinner.Disc.CumulativeRotation); {
AddStep("retrieve spinner symbol rotation", () => finalSpinnerSymbolRotation = spinnerSymbol.Rotation); finalTrackerRotation = drawableSpinner.RotationTracker.Rotation;
trackerRotationTolerance = Math.Abs(finalTrackerRotation * 0.05f);
});
AddStep("retrieve spinner symbol rotation", () =>
{
finalSpinnerSymbolRotation = spinnerSymbol.Rotation;
spinnerSymbolRotationTolerance = Math.Abs(finalSpinnerSymbolRotation * 0.05f);
});
AddStep("retrieve cumulative disc rotation", () => finalCumulativeTrackerRotation = drawableSpinner.RotationTracker.RateAdjustedRotation);
addSeekStep(2500); addSeekStep(2500);
AddUntilStep("disc rotation rewound", AddAssert("disc rotation rewound",
// we want to make sure that the rotation at time 2500 is in the same direction as at time 5000, but about half-way in. // we want to make sure that the rotation at time 2500 is in the same direction as at time 5000, but about half-way in.
() => Precision.AlmostEquals(drawableSpinner.Disc.Rotation, finalRelativeDiscRotation / 2, 100)); // due to the exponential damping applied we're allowing a larger margin of error of about 10%
AddUntilStep("symbol rotation rewound", // (5% relative to the final rotation value, but we're half-way through the spin).
() => Precision.AlmostEquals(spinnerSymbol.Rotation, finalSpinnerSymbolRotation / 2, 100)); () => Precision.AlmostEquals(drawableSpinner.RotationTracker.Rotation, finalTrackerRotation / 2, trackerRotationTolerance));
AddAssert("symbol rotation rewound",
() => Precision.AlmostEquals(spinnerSymbol.Rotation, finalSpinnerSymbolRotation / 2, spinnerSymbolRotationTolerance));
AddAssert("is cumulative rotation rewound",
// cumulative rotation is not damped, so we're treating it as the "ground truth" and allowing a comparatively smaller margin of error.
() => Precision.AlmostEquals(drawableSpinner.RotationTracker.RateAdjustedRotation, finalCumulativeTrackerRotation / 2, 100));
addSeekStep(5000); addSeekStep(5000);
AddAssert("is disc rotation almost same", AddAssert("is disc rotation almost same",
() => Precision.AlmostEquals(drawableSpinner.Disc.Rotation, finalRelativeDiscRotation, 100)); () => Precision.AlmostEquals(drawableSpinner.RotationTracker.Rotation, finalTrackerRotation, trackerRotationTolerance));
AddAssert("is symbol rotation almost same", AddAssert("is symbol rotation almost same",
() => Precision.AlmostEquals(spinnerSymbol.Rotation, finalSpinnerSymbolRotation, 100)); () => Precision.AlmostEquals(spinnerSymbol.Rotation, finalSpinnerSymbolRotation, spinnerSymbolRotationTolerance));
AddAssert("is disc rotation absolute almost same", AddAssert("is cumulative rotation almost same",
() => Precision.AlmostEquals(drawableSpinner.Disc.CumulativeRotation, finalAbsoluteDiscRotation, 100)); () => Precision.AlmostEquals(drawableSpinner.RotationTracker.RateAdjustedRotation, finalCumulativeTrackerRotation, 100));
} }
[Test] [Test]
public void TestRotationDirection([Values(true, false)] bool clockwise) public void TestRotationDirection([Values(true, false)] bool clockwise)
{ {
if (clockwise) if (clockwise)
{ transformReplay(flip);
AddStep("flip replay", () =>
{
var drawableRuleset = this.ChildrenOfType<DrawableOsuRuleset>().Single();
var score = drawableRuleset.ReplayScore;
var scoreWithFlippedReplay = new Score
{
ScoreInfo = score.ScoreInfo,
Replay = flipReplay(score.Replay)
};
drawableRuleset.SetReplayScore(scoreWithFlippedReplay);
});
}
addSeekStep(5000); addSeekStep(5000);
AddAssert("disc spin direction correct", () => clockwise ? drawableSpinner.Disc.Rotation > 0 : drawableSpinner.Disc.Rotation < 0); AddAssert("disc spin direction correct", () => clockwise ? drawableSpinner.RotationTracker.Rotation > 0 : drawableSpinner.RotationTracker.Rotation < 0);
AddAssert("spinner symbol direction correct", () => clockwise ? spinnerSymbol.Rotation > 0 : spinnerSymbol.Rotation < 0); AddAssert("spinner symbol direction correct", () => clockwise ? spinnerSymbol.Rotation > 0 : spinnerSymbol.Rotation < 0);
} }
private Replay flipReplay(Replay scoreReplay) => new Replay private Replay flip(Replay scoreReplay) => new Replay
{ {
Frames = scoreReplay Frames = scoreReplay
.Frames .Frames
@ -142,7 +153,7 @@ namespace osu.Game.Rulesets.Osu.Tests
{ {
// multipled by 2 to nullify the score multiplier. (autoplay mod selected) // multipled by 2 to nullify the score multiplier. (autoplay mod selected)
var totalScore = ((ScoreExposedPlayer)Player).ScoreProcessor.TotalScore.Value * 2; var totalScore = ((ScoreExposedPlayer)Player).ScoreProcessor.TotalScore.Value * 2;
return totalScore == (int)(drawableSpinner.Disc.CumulativeRotation / 360) * SpinnerTick.SCORE_PER_TICK; return totalScore == (int)(drawableSpinner.RotationTracker.RateAdjustedRotation / 360) * SpinnerTick.SCORE_PER_TICK;
}); });
addSeekStep(0); addSeekStep(0);
@ -174,6 +185,49 @@ namespace osu.Game.Rulesets.Osu.Tests
AddAssert("spm still valid", () => Precision.AlmostEquals(drawableSpinner.SpmCounter.SpinsPerMinute, estimatedSpm, 1.0)); AddAssert("spm still valid", () => Precision.AlmostEquals(drawableSpinner.SpmCounter.SpinsPerMinute, estimatedSpm, 1.0));
} }
[TestCase(0.5)]
[TestCase(2.0)]
public void TestSpinUnaffectedByClockRate(double rate)
{
double expectedProgress = 0;
double expectedSpm = 0;
addSeekStep(1000);
AddStep("retrieve spinner state", () =>
{
expectedProgress = drawableSpinner.Progress;
expectedSpm = drawableSpinner.SpmCounter.SpinsPerMinute;
});
addSeekStep(0);
AddStep("adjust track rate", () => track.AddAdjustment(AdjustableProperty.Tempo, new BindableDouble(rate)));
// autoplay replay frames use track time;
// if a spin takes 1000ms in track time and we're playing with a 2x rate adjustment, the spin will take 500ms of *real* time.
// therefore we need to apply the rate adjustment to the replay itself to change from track time to real time,
// as real time is what we care about for spinners
// (so we're making the spin take 1000ms in real time *always*, regardless of the track clock's rate).
transformReplay(replay => applyRateAdjustment(replay, rate));
addSeekStep(1000);
AddAssert("progress almost same", () => Precision.AlmostEquals(expectedProgress, drawableSpinner.Progress, 0.05));
AddAssert("spm almost same", () => Precision.AlmostEquals(expectedSpm, drawableSpinner.SpmCounter.SpinsPerMinute, 2.0));
}
private Replay applyRateAdjustment(Replay scoreReplay, double rate) => new Replay
{
Frames = scoreReplay
.Frames
.Cast<OsuReplayFrame>()
.Select(replayFrame =>
{
var adjustedTime = replayFrame.Time * rate;
return new OsuReplayFrame(adjustedTime, replayFrame.Position, replayFrame.Actions.ToArray());
})
.Cast<ReplayFrame>()
.ToList()
};
private void addSeekStep(double time) private void addSeekStep(double time)
{ {
AddStep($"seek to {time}", () => track.Seek(time)); AddStep($"seek to {time}", () => track.Seek(time));
@ -181,6 +235,18 @@ namespace osu.Game.Rulesets.Osu.Tests
AddUntilStep("wait for seek to finish", () => Precision.AlmostEquals(time, Player.DrawableRuleset.FrameStableClock.CurrentTime, 100)); AddUntilStep("wait for seek to finish", () => Precision.AlmostEquals(time, Player.DrawableRuleset.FrameStableClock.CurrentTime, 100));
} }
private void transformReplay(Func<Replay, Replay> replayTransformation) => AddStep("set replay", () =>
{
var drawableRuleset = this.ChildrenOfType<DrawableOsuRuleset>().Single();
var score = drawableRuleset.ReplayScore;
var transformedScore = new Score
{
ScoreInfo = score.ScoreInfo,
Replay = replayTransformation.Invoke(score.Replay)
};
drawableRuleset.SetReplayScore(transformedScore);
});
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new Beatmap protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new Beatmap
{ {
HitObjects = new List<HitObject> HitObjects = new List<HitObject>

View File

@ -2,7 +2,7 @@
<Import Project="..\osu.TestProject.props" /> <Import Project="..\osu.TestProject.props" />
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" /> <PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="NUnit" Version="3.12.0" /> <PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />

View File

@ -82,9 +82,7 @@ namespace osu.Game.Rulesets.Osu.Mods
case DrawableSpinner spinner: case DrawableSpinner spinner:
// hide elements we don't care about. // hide elements we don't care about.
spinner.Disc.Hide(); // todo: hide background
spinner.Ticks.Hide();
spinner.Background.Hide();
using (spinner.BeginAbsoluteSequence(fadeOutStartTime + longFadeDuration, true)) using (spinner.BeginAbsoluteSequence(fadeOutStartTime + longFadeDuration, true))
spinner.FadeOut(fadeOutDuration); spinner.FadeOut(fadeOutDuration);

View File

@ -40,8 +40,8 @@ namespace osu.Game.Rulesets.Osu.Mods
{ {
var spinner = (DrawableSpinner)drawable; var spinner = (DrawableSpinner)drawable;
spinner.Disc.Tracking = true; spinner.RotationTracker.Tracking = true;
spinner.Disc.Rotate(MathUtils.RadiansToDegrees((float)spinner.Clock.ElapsedFrameTime * 0.03f)); spinner.RotationTracker.AddRotation(MathUtils.RadiansToDegrees((float)spinner.Clock.ElapsedFrameTime * 0.03f));
} }
} }
} }

View File

@ -43,6 +43,8 @@ namespace osu.Game.Rulesets.Osu.Mods
var h = drawableOsu.HitObject; var h = drawableOsu.HitObject;
//todo: expose and hide spinner background somehow
switch (drawable) switch (drawable)
{ {
case DrawableHitCircle circle: case DrawableHitCircle circle:
@ -56,11 +58,6 @@ namespace osu.Game.Rulesets.Osu.Mods
slider.Body.OnSkinChanged += () => applySliderState(slider); slider.Body.OnSkinChanged += () => applySliderState(slider);
applySliderState(slider); applySliderState(slider);
break; break;
case DrawableSpinner spinner:
spinner.Disc.Hide();
spinner.Background.Hide();
break;
} }
} }

View File

@ -14,8 +14,8 @@ using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Scoring;
using osuTK;
using osu.Game.Skinning; using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.Objects.Drawables namespace osu.Game.Rulesets.Osu.Objects.Drawables
{ {

View File

@ -3,21 +3,19 @@
using System; using System;
using System.Linq; using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;
using osu.Game.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Objects;
using osu.Framework.Utils;
using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Ranking; using osu.Game.Screens.Ranking;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.Objects.Drawables namespace osu.Game.Rulesets.Osu.Objects.Drawables
{ {
@ -27,28 +25,12 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
private readonly Container<DrawableSpinnerTick> ticks; private readonly Container<DrawableSpinnerTick> ticks;
public readonly SpinnerDisc Disc; public readonly SpinnerRotationTracker RotationTracker;
public readonly SpinnerTicks Ticks;
public readonly SpinnerSpmCounter SpmCounter; public readonly SpinnerSpmCounter SpmCounter;
private readonly SpinnerBonusDisplay bonusDisplay; private readonly SpinnerBonusDisplay bonusDisplay;
private readonly Container mainContainer;
public readonly SpinnerBackground Background;
private readonly Container circleContainer;
private readonly CirclePiece circle;
private readonly GlowPiece glow;
private readonly SpriteIcon symbol;
private readonly Color4 baseColour = Color4Extensions.FromHex(@"002c3c");
private readonly Color4 fillColour = Color4Extensions.FromHex(@"005b7c");
private readonly IBindable<Vector2> positionBindable = new Bindable<Vector2>(); private readonly IBindable<Vector2> positionBindable = new Bindable<Vector2>();
private Color4 normalColour;
private Color4 completeColour;
public DrawableSpinner(Spinner s) public DrawableSpinner(Spinner s)
: base(s) : base(s)
{ {
@ -57,66 +39,20 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
RelativeSizeAxes = Axes.Both; RelativeSizeAxes = Axes.Both;
// we are slightly bigger than our parent, to clip the top and bottom of the circle
Height = 1.3f;
Spinner = s; Spinner = s;
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{ {
ticks = new Container<DrawableSpinnerTick>(), ticks = new Container<DrawableSpinnerTick>(),
circleContainer = new Container new AspectContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
glow = new GlowPiece(),
circle = new CirclePiece
{
Position = Vector2.Zero,
Anchor = Anchor.Centre,
},
new RingPiece(),
symbol = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(48),
Icon = FontAwesome.Solid.Asterisk,
Shadow = false,
},
}
},
mainContainer = new AspectContainer
{ {
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y, RelativeSizeAxes = Axes.Y,
Children = new[] Children = new Drawable[]
{ {
Background = new SpinnerBackground new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SpinnerBody), _ => new DefaultSpinnerDisc()),
{ RotationTracker = new SpinnerRotationTracker(Spinner)
Disc =
{
Alpha = 0f,
},
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
Disc = new SpinnerDisc(Spinner)
{
Scale = Vector2.Zero,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
circleContainer.CreateProxy(),
Ticks = new SpinnerTicks
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
} }
}, },
SpmCounter = new SpinnerSpmCounter SpmCounter = new SpinnerSpmCounter
@ -135,6 +71,58 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
}; };
} }
private Bindable<bool> isSpinning;
protected override void LoadComplete()
{
base.LoadComplete();
isSpinning = RotationTracker.IsSpinning.GetBoundCopy();
isSpinning.BindValueChanged(updateSpinningSample);
}
private SkinnableSound spinningSample;
private const float minimum_volume = 0.0001f;
protected override void LoadSamples()
{
base.LoadSamples();
spinningSample?.Expire();
spinningSample = null;
var firstSample = HitObject.Samples.FirstOrDefault();
if (firstSample != null)
{
var clone = HitObject.SampleControlPoint.ApplyTo(firstSample);
clone.Name = "spinnerspin";
AddInternal(spinningSample = new SkinnableSound(clone)
{
Volume = { Value = minimum_volume },
Looping = true,
});
}
}
private void updateSpinningSample(ValueChangedEvent<bool> tracking)
{
// note that samples will not start playing if exiting a seek operation in the middle of a spinner.
// may be something we want to address at a later point, but not so easy to make happen right now
// (SkinnableSound would need to expose whether the sample is already playing and this logic would need to run in Update).
if (tracking.NewValue && ShouldPlaySamples)
{
spinningSample?.Play();
spinningSample?.VolumeTo(1, 200);
}
else
{
spinningSample?.VolumeTo(minimum_volume, 200).Finally(_ => spinningSample.Stop());
}
}
protected override void AddNestedHitObject(DrawableHitObject hitObject) protected override void AddNestedHitObject(DrawableHitObject hitObject)
{ {
base.AddNestedHitObject(hitObject); base.AddNestedHitObject(hitObject);
@ -147,6 +135,17 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
} }
} }
protected override void UpdateStateTransforms(ArmedState state)
{
base.UpdateStateTransforms(state);
using (BeginDelayedSequence(Spinner.Duration, true))
this.FadeOut(160);
// skin change does a rewind of transforms, which will stop the spinning sound from playing if it's currently in playback.
isSpinning?.TriggerChange();
}
protected override void ClearNestedHitObjects() protected override void ClearNestedHitObjects()
{ {
base.ClearNestedHitObjects(); base.ClearNestedHitObjects();
@ -170,31 +169,31 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load(OsuColour colours) private void load(OsuColour colours)
{ {
normalColour = baseColour;
completeColour = colours.YellowLight;
Background.AccentColour = normalColour;
Ticks.AccentColour = normalColour;
Disc.AccentColour = fillColour;
circle.Colour = colours.BlueDark;
glow.Colour = colours.BlueDark;
positionBindable.BindValueChanged(pos => Position = pos.NewValue); positionBindable.BindValueChanged(pos => Position = pos.NewValue);
positionBindable.BindTo(HitObject.PositionBindable); positionBindable.BindTo(HitObject.PositionBindable);
} }
public float Progress => Math.Clamp(Disc.CumulativeRotation / 360 / Spinner.SpinsRequired, 0, 1); /// <summary>
/// The completion progress of this spinner from 0..1 (clamped).
/// </summary>
public float Progress
{
get
{
if (Spinner.SpinsRequired == 0)
// some spinners are so short they can't require an integer spin count.
// these become implicitly hit.
return 1;
return Math.Clamp(RotationTracker.RateAdjustedRotation / 360 / Spinner.SpinsRequired, 0, 1);
}
}
protected override void CheckForResult(bool userTriggered, double timeOffset) protected override void CheckForResult(bool userTriggered, double timeOffset)
{ {
if (Time.Current < HitObject.StartTime) return; if (Time.Current < HitObject.StartTime) return;
if (Progress >= 1 && !Disc.Complete) RotationTracker.Complete.Value = Progress >= 1;
{
Disc.Complete = true;
transformFillColour(completeColour, 200);
}
if (userTriggered || Time.Current < Spinner.EndTime) if (userTriggered || Time.Current < Spinner.EndTime)
return; return;
@ -219,29 +218,24 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
protected override void Update() protected override void Update()
{ {
base.Update(); base.Update();
if (HandleUserInput) if (HandleUserInput)
Disc.Tracking = OsuActionInputManager?.PressedActions.Any(x => x == OsuAction.LeftButton || x == OsuAction.RightButton) ?? false; RotationTracker.Tracking = !Result.HasResult && (OsuActionInputManager?.PressedActions.Any(x => x == OsuAction.LeftButton || x == OsuAction.RightButton) ?? false);
if (spinningSample != null)
// todo: implement SpinnerFrequencyModulate
spinningSample.Frequency.Value = 0.5f + Progress;
} }
protected override void UpdateAfterChildren() protected override void UpdateAfterChildren()
{ {
base.UpdateAfterChildren(); base.UpdateAfterChildren();
if (!SpmCounter.IsPresent && Disc.Tracking) if (!SpmCounter.IsPresent && RotationTracker.Tracking)
SpmCounter.FadeIn(HitObject.TimeFadeIn); SpmCounter.FadeIn(HitObject.TimeFadeIn);
SpmCounter.SetRotation(RotationTracker.RateAdjustedRotation);
circle.Rotation = Disc.Rotation;
Ticks.Rotation = Disc.Rotation;
SpmCounter.SetRotation(Disc.CumulativeRotation);
updateBonusScore(); updateBonusScore();
float relativeCircleScale = Spinner.Scale * circle.DrawHeight / mainContainer.DrawHeight;
float targetScale = relativeCircleScale + (1 - relativeCircleScale) * Progress;
Disc.Scale = new Vector2((float)Interpolation.Lerp(Disc.Scale.X, targetScale, Math.Clamp(Math.Abs(Time.Elapsed) / 100, 0, 1)));
symbol.Rotation = (float)Interpolation.Lerp(symbol.Rotation, Disc.Rotation / 2, Math.Clamp(Math.Abs(Time.Elapsed) / 40, 0, 1));
} }
private int wholeSpins; private int wholeSpins;
@ -251,7 +245,7 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
if (ticks.Count == 0) if (ticks.Count == 0)
return; return;
int spins = (int)(Disc.CumulativeRotation / 360); int spins = (int)(RotationTracker.RateAdjustedRotation / 360);
if (spins < wholeSpins) if (spins < wholeSpins)
{ {
@ -275,64 +269,5 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables
wholeSpins++; wholeSpins++;
} }
} }
protected override void UpdateInitialTransforms()
{
base.UpdateInitialTransforms();
circleContainer.ScaleTo(0);
mainContainer.ScaleTo(0);
using (BeginDelayedSequence(HitObject.TimePreempt / 2, true))
{
float phaseOneScale = Spinner.Scale * 0.7f;
circleContainer.ScaleTo(phaseOneScale, HitObject.TimePreempt / 4, Easing.OutQuint);
mainContainer
.ScaleTo(phaseOneScale * circle.DrawHeight / DrawHeight * 1.6f, HitObject.TimePreempt / 4, Easing.OutQuint)
.RotateTo((float)(25 * Spinner.Duration / 2000), HitObject.TimePreempt + Spinner.Duration);
using (BeginDelayedSequence(HitObject.TimePreempt / 2, true))
{
circleContainer.ScaleTo(Spinner.Scale, 400, Easing.OutQuint);
mainContainer.ScaleTo(1, 400, Easing.OutQuint);
}
}
}
protected override void UpdateStateTransforms(ArmedState state)
{
base.UpdateStateTransforms(state);
using (BeginDelayedSequence(Spinner.Duration, true))
{
this.FadeOut(160);
switch (state)
{
case ArmedState.Hit:
transformFillColour(completeColour, 0);
this.ScaleTo(Scale * 1.2f, 320, Easing.Out);
mainContainer.RotateTo(mainContainer.Rotation + 180, 320);
break;
case ArmedState.Miss:
this.ScaleTo(Scale * 0.8f, 320, Easing.In);
break;
}
}
}
private void transformFillColour(Colour4 colour, double duration)
{
Disc.FadeAccent(colour, duration);
Background.FadeAccent(colour.Darken(1), duration);
Ticks.FadeAccent(colour, duration);
circle.FadeColour(colour, duration);
glow.FadeColour(colour, duration);
}
} }
} }

View File

@ -0,0 +1,189 @@
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
public class DefaultSpinnerDisc : CompositeDrawable
{
private DrawableSpinner drawableSpinner;
private Spinner spinner;
private const float idle_alpha = 0.2f;
private const float tracking_alpha = 0.4f;
private Color4 normalColour;
private Color4 completeColour;
private SpinnerTicks ticks;
private int wholeRotationCount;
private SpinnerFill fill;
private Container mainContainer;
private SpinnerCentreLayer centre;
private SpinnerBackgroundLayer background;
public DefaultSpinnerDisc()
{
RelativeSizeAxes = Axes.Both;
// 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.
Scale = new Vector2(1.3f);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, DrawableHitObject drawableHitObject)
{
drawableSpinner = (DrawableSpinner)drawableHitObject;
spinner = (Spinner)drawableSpinner.HitObject;
normalColour = colours.BlueDark;
completeColour = colours.YellowLight;
InternalChildren = new Drawable[]
{
mainContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
background = new SpinnerBackgroundLayer(),
fill = new SpinnerFill
{
Alpha = idle_alpha,
AccentColour = normalColour
},
ticks = new SpinnerTicks
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AccentColour = normalColour
},
}
},
centre = new SpinnerCentreLayer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
};
}
protected override void LoadComplete()
{
base.LoadComplete();
drawableSpinner.RotationTracker.Complete.BindValueChanged(complete => updateComplete(complete.NewValue, 200));
drawableSpinner.State.BindValueChanged(updateStateTransforms, true);
}
protected override void Update()
{
base.Update();
if (drawableSpinner.RotationTracker.Complete.Value)
{
if (checkNewRotationCount)
{
fill.FinishTransforms(false, nameof(Alpha));
fill
.FadeTo(tracking_alpha + 0.2f, 60, Easing.OutExpo)
.Then()
.FadeTo(tracking_alpha, 250, Easing.OutQuint);
}
}
else
{
fill.Alpha = (float)Interpolation.Damp(fill.Alpha, drawableSpinner.RotationTracker.Tracking ? tracking_alpha : idle_alpha, 0.98f, (float)Math.Abs(Clock.ElapsedFrameTime));
}
const float initial_scale = 0.2f;
float targetScale = initial_scale + (1 - initial_scale) * drawableSpinner.Progress;
fill.Scale = new Vector2((float)Interpolation.Lerp(fill.Scale.X, targetScale, Math.Clamp(Math.Abs(Time.Elapsed) / 100, 0, 1)));
mainContainer.Rotation = drawableSpinner.RotationTracker.Rotation;
}
private void updateStateTransforms(ValueChangedEvent<ArmedState> state)
{
centre.ScaleTo(0);
mainContainer.ScaleTo(0);
using (BeginAbsoluteSequence(spinner.StartTime - spinner.TimePreempt / 2, true))
{
// constant ambient rotation to give the spinner "spinning" character.
this.RotateTo((float)(25 * spinner.Duration / 2000), spinner.TimePreempt + spinner.Duration);
centre.ScaleTo(0.3f, spinner.TimePreempt / 4, Easing.OutQuint);
mainContainer.ScaleTo(0.2f, spinner.TimePreempt / 4, Easing.OutQuint);
using (BeginDelayedSequence(spinner.TimePreempt / 2, true))
{
centre.ScaleTo(0.5f, spinner.TimePreempt / 2, Easing.OutQuint);
mainContainer.ScaleTo(1, spinner.TimePreempt / 2, Easing.OutQuint);
}
}
// transforms we have from completing the spinner will be rolled back, so reapply immediately.
updateComplete(state.NewValue == ArmedState.Hit, 0);
using (BeginDelayedSequence(spinner.Duration, true))
{
switch (state.NewValue)
{
case ArmedState.Hit:
this.ScaleTo(Scale * 1.2f, 320, Easing.Out);
this.RotateTo(mainContainer.Rotation + 180, 320);
break;
case ArmedState.Miss:
this.ScaleTo(Scale * 0.8f, 320, Easing.In);
break;
}
}
}
private void updateComplete(bool complete, double duration)
{
var colour = complete ? completeColour : normalColour;
ticks.FadeAccent(colour.Darken(1), duration);
fill.FadeAccent(colour.Darken(1), duration);
background.FadeAccent(colour, duration);
centre.FadeAccent(colour, duration);
}
private bool checkNewRotationCount
{
get
{
int rotations = (int)(drawableSpinner.RotationTracker.RateAdjustedRotation / 360);
if (wholeRotationCount == rotations) return false;
wholeRotationCount = rotations;
return true;
}
}
}
}

View File

@ -10,7 +10,7 @@ using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{ {
public class SpinnerBackground : CircularContainer, IHasAccentColour public class SpinnerFill : CircularContainer, IHasAccentColour
{ {
public readonly Box Disc; public readonly Box Disc;
@ -31,11 +31,14 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
} }
} }
public SpinnerBackground() public SpinnerFill()
{ {
RelativeSizeAxes = Axes.Both; RelativeSizeAxes = Axes.Both;
Masking = true; Masking = true;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Children = new Drawable[] Children = new Drawable[]
{ {
Disc = new Box Disc = new Box

View File

@ -2,89 +2,62 @@
// 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 osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events; using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Utils; using osu.Framework.Utils;
using osuTK;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{ {
public class SpinnerDisc : CircularContainer, IHasAccentColour public class SpinnerRotationTracker : CircularContainer
{ {
private readonly Spinner spinner; private readonly Spinner spinner;
public Color4 AccentColour
{
get => background.AccentColour;
set => background.AccentColour = value;
}
private readonly SpinnerBackground background;
private const float idle_alpha = 0.2f;
private const float tracking_alpha = 0.4f;
public override bool IsPresent => true; // handle input when hidden public override bool IsPresent => true; // handle input when hidden
public SpinnerDisc(Spinner s) public SpinnerRotationTracker(Spinner s)
{ {
spinner = s; spinner = s;
RelativeSizeAxes = Axes.Both; RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
background = new SpinnerBackground { Alpha = idle_alpha },
};
} }
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
private bool tracking; public bool Tracking { get; set; }
public bool Tracking public readonly BindableBool Complete = new BindableBool();
{
get => tracking;
set
{
if (value == tracking) return;
tracking = value;
background.FadeTo(tracking ? tracking_alpha : idle_alpha, 100);
}
}
private bool complete;
public bool Complete
{
get => complete;
set
{
if (value == complete) return;
complete = value;
updateCompleteTick();
}
}
/// <summary> /// <summary>
/// The total rotation performed on the spinner disc, disregarding the spin direction. /// The total rotation performed on the spinner disc, disregarding the spin direction,
/// adjusted for the track's playback rate.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para>
/// This value is always non-negative and is monotonically increasing with time /// This value is always non-negative and is monotonically increasing with time
/// (i.e. will only increase if time is passing forward, but can decrease during rewind). /// (i.e. will only increase if time is passing forward, but can decrease during rewind).
/// </para>
/// <para>
/// The rotation from each frame is multiplied by the clock's current playback rate.
/// The reason this is done is to ensure that spinners give the same score and require the same number of spins
/// regardless of whether speed-modifying mods are applied.
/// </para>
/// </remarks> /// </remarks>
/// <example> /// <example>
/// If the spinner is spun 360 degrees clockwise and then 360 degrees counter-clockwise, /// Assuming no speed-modifying mods are active,
/// if the spinner is spun 360 degrees clockwise and then 360 degrees counter-clockwise,
/// this property will return the value of 720 (as opposed to 0 for <see cref="Drawable.Rotation"/>). /// this property will return the value of 720 (as opposed to 0 for <see cref="Drawable.Rotation"/>).
/// If Double Time is active instead (with a speed multiplier of 1.5x),
/// in the same scenario the property will return 720 * 1.5 = 1080.
/// </example> /// </example>
public float CumulativeRotation; public float RateAdjustedRotation { get; private set; }
/// <summary>
/// Whether the spinning is spinning at a reasonable speed to be considered visually spinning.
/// </summary>
public readonly BindableBool IsSpinning = new BindableBool();
/// <summary> /// <summary>
/// Whether currently in the correct time range to allow spinning. /// Whether currently in the correct time range to allow spinning.
@ -101,9 +74,6 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
private float lastAngle; private float lastAngle;
private float currentRotation; private float currentRotation;
private int completeTick;
private bool updateCompleteTick() => completeTick != (completeTick = (int)(CumulativeRotation / 360));
private bool rotationTransferred; private bool rotationTransferred;
@ -114,21 +84,14 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
var delta = thisAngle - lastAngle; var delta = thisAngle - lastAngle;
if (tracking) if (Tracking)
Rotate(delta); AddRotation(delta);
lastAngle = thisAngle; lastAngle = thisAngle;
if (Complete && updateCompleteTick()) IsSpinning.Value = isSpinnableTime && Math.Abs(currentRotation / 2 - Rotation) > 5f;
{
background.FinishTransforms(false, nameof(Alpha));
background
.FadeTo(tracking_alpha + 0.2f, 60, Easing.OutExpo)
.Then()
.FadeTo(tracking_alpha, 250, Easing.OutQuint);
}
Rotation = (float)Interpolation.Lerp(Rotation, currentRotation / 2, Math.Clamp(Math.Abs(Time.Elapsed) / 40, 0, 1)); Rotation = (float)Interpolation.Damp(Rotation, currentRotation / 2, 0.99, Math.Abs(Time.Elapsed));
} }
/// <summary> /// <summary>
@ -138,7 +101,7 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
/// Will be a no-op if not a valid time to spin. /// Will be a no-op if not a valid time to spin.
/// </remarks> /// </remarks>
/// <param name="angle">The delta angle.</param> /// <param name="angle">The delta angle.</param>
public void Rotate(float angle) public void AddRotation(float angle)
{ {
if (!isSpinnableTime) if (!isSpinnableTime)
return; return;
@ -161,7 +124,9 @@ namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
} }
currentRotation += angle; currentRotation += angle;
CumulativeRotation += Math.Abs(angle) * Math.Sign(Clock.ElapsedFrameTime); // rate has to be applied each frame, because it's not guaranteed to be constant throughout playback
// (see: ModTimeRamp)
RateAdjustedRotation += (float)(Math.Abs(angle) * Clock.Rate);
} }
} }
} }

View File

@ -0,0 +1,22 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class SpinnerBackgroundLayer : SpinnerFill
{
[BackgroundDependencyLoader]
private void load(OsuColour colours, DrawableHitObject drawableHitObject)
{
Disc.Alpha = 0;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
}
}

View File

@ -0,0 +1,71 @@
// 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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class SpinnerCentreLayer : CompositeDrawable, IHasAccentColour
{
private DrawableSpinner spinner;
private CirclePiece circle;
private GlowPiece glow;
private SpriteIcon symbol;
[BackgroundDependencyLoader]
private void load(DrawableHitObject drawableHitObject)
{
spinner = (DrawableSpinner)drawableHitObject;
InternalChildren = new Drawable[]
{
glow = new GlowPiece(),
circle = new CirclePiece
{
Position = Vector2.Zero,
Anchor = Anchor.Centre,
},
new RingPiece(),
symbol = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(48),
Icon = FontAwesome.Solid.Asterisk,
Shadow = false,
},
};
}
protected override void Update()
{
base.Update();
symbol.Rotation = (float)Interpolation.Lerp(symbol.Rotation, spinner.RotationTracker.Rotation / 2, Math.Clamp(Math.Abs(Time.Elapsed) / 40, 0, 1));
}
private Color4 accentColour;
public Color4 AccentColour
{
get => accentColour;
set
{
accentColour = value;
circle.Colour = accentColour;
glow.Colour = accentColour;
}
}
}
}

View File

@ -1,7 +1,6 @@
// 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;
using osu.Game.Beatmaps; using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Judgements;
@ -45,7 +44,7 @@ namespace osu.Game.Rulesets.Osu.Objects
double minimumRotationsPerSecond = stable_matching_fudge * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5); double minimumRotationsPerSecond = stable_matching_fudge * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5);
SpinsRequired = (int)Math.Max(1, (secondsDuration * minimumRotationsPerSecond)); SpinsRequired = (int)(secondsDuration * minimumRotationsPerSecond);
MaximumBonusSpins = (int)((maximum_rotations_per_second - minimumRotationsPerSecond) * secondsDuration); MaximumBonusSpins = (int)((maximum_rotations_per_second - minimumRotationsPerSecond) * secondsDuration);
} }

View File

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

View File

@ -14,6 +14,7 @@ using osu.Game.Rulesets.Osu.Objects;
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.Osu.Skinning namespace osu.Game.Rulesets.Osu.Skinning
{ {
@ -28,19 +29,32 @@ namespace osu.Game.Rulesets.Osu.Skinning
Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);
} }
private Container<Sprite> circleSprites;
private Sprite hitCircleSprite;
private Sprite hitCircleOverlay;
private SkinnableSpriteText hitCircleText;
private readonly IBindable<ArmedState> state = new Bindable<ArmedState>(); private readonly IBindable<ArmedState> state = new Bindable<ArmedState>();
private readonly Bindable<Color4> accentColour = new Bindable<Color4>(); private readonly Bindable<Color4> accentColour = new Bindable<Color4>();
private readonly IBindable<int> indexInCurrentCombo = new Bindable<int>(); private readonly IBindable<int> indexInCurrentCombo = new Bindable<int>();
[Resolved]
private ISkinSource skin { get; set; }
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load(DrawableHitObject drawableObject, ISkinSource skin) private void load(DrawableHitObject drawableObject)
{ {
OsuHitObject osuObject = (OsuHitObject)drawableObject.HitObject; OsuHitObject osuObject = (OsuHitObject)drawableObject.HitObject;
Sprite hitCircleSprite;
SkinnableSpriteText hitCircleText;
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{
circleSprites = new Container<Sprite>
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Children = new[]
{ {
hitCircleSprite = new Sprite hitCircleSprite = new Sprite
{ {
@ -49,32 +63,33 @@ namespace osu.Game.Rulesets.Osu.Skinning
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
}, },
hitCircleText = new SkinnableSpriteText(new OsuSkinComponent(OsuSkinComponents.HitCircleText), _ => new OsuSpriteText hitCircleOverlay = new Sprite
{
Font = OsuFont.Numeric.With(size: 40),
UseFullGlyphHeight = false,
}, confineMode: ConfineMode.NoScaling),
new Sprite
{ {
Texture = getTextureWithFallback("overlay"), Texture = getTextureWithFallback("overlay"),
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
} }
}
},
hitCircleText = new SkinnableSpriteText(new OsuSkinComponent(OsuSkinComponents.HitCircleText), _ => new OsuSpriteText
{
Font = OsuFont.Numeric.With(size: 40),
UseFullGlyphHeight = false,
}, confineMode: ConfineMode.NoScaling)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
}; };
bool overlayAboveNumber = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.HitCircleOverlayAboveNumber)?.Value ?? true; bool overlayAboveNumber = skin.GetConfig<OsuSkinConfiguration, bool>(OsuSkinConfiguration.HitCircleOverlayAboveNumber)?.Value ?? true;
if (!overlayAboveNumber) if (overlayAboveNumber)
ChangeInternalChildDepth(hitCircleText, -float.MaxValue); AddInternal(hitCircleOverlay.CreateProxy());
state.BindTo(drawableObject.State); state.BindTo(drawableObject.State);
state.BindValueChanged(updateState, true);
accentColour.BindTo(drawableObject.AccentColour); accentColour.BindTo(drawableObject.AccentColour);
accentColour.BindValueChanged(colour => hitCircleSprite.Colour = colour.NewValue, true);
indexInCurrentCombo.BindTo(osuObject.IndexInCurrentComboBindable); indexInCurrentCombo.BindTo(osuObject.IndexInCurrentComboBindable);
indexInCurrentCombo.BindValueChanged(index => hitCircleText.Text = (index.NewValue + 1).ToString(), true);
Texture getTextureWithFallback(string name) Texture getTextureWithFallback(string name)
{ {
@ -87,6 +102,15 @@ namespace osu.Game.Rulesets.Osu.Skinning
} }
} }
protected override void LoadComplete()
{
base.LoadComplete();
state.BindValueChanged(updateState, true);
accentColour.BindValueChanged(colour => hitCircleSprite.Colour = colour.NewValue, true);
indexInCurrentCombo.BindValueChanged(index => hitCircleText.Text = (index.NewValue + 1).ToString(), true);
}
private void updateState(ValueChangedEvent<ArmedState> state) private void updateState(ValueChangedEvent<ArmedState> state)
{ {
const double legacy_fade_duration = 240; const double legacy_fade_duration = 240;
@ -94,8 +118,21 @@ namespace osu.Game.Rulesets.Osu.Skinning
switch (state.NewValue) switch (state.NewValue)
{ {
case ArmedState.Hit: case ArmedState.Hit:
this.FadeOut(legacy_fade_duration, Easing.Out); circleSprites.FadeOut(legacy_fade_duration, Easing.Out);
this.ScaleTo(1.4f, legacy_fade_duration, Easing.Out); circleSprites.ScaleTo(1.4f, legacy_fade_duration, Easing.Out);
var legacyVersion = skin.GetConfig<LegacySetting, decimal>(LegacySetting.Version)?.Value;
if (legacyVersion >= 2.0m)
// legacy skins of version 2.0 and newer only apply very short fade out to the number piece.
hitCircleText.FadeOut(legacy_fade_duration / 4, Easing.Out);
else
{
// old skins scale and fade it normally along other pieces.
hitCircleText.FadeOut(legacy_fade_duration, Easing.Out);
hitCircleText.ScaleTo(1.4f, legacy_fade_duration, Easing.Out);
}
break; break;
} }
} }

View File

@ -0,0 +1,99 @@
// 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.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Utils;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning
{
/// <summary>
/// Legacy skinned spinner with two main spinning layers, one fixed overlay and one final spinning overlay.
/// No background layer.
/// </summary>
public class LegacyNewStyleSpinner : CompositeDrawable
{
private Sprite discBottom;
private Sprite discTop;
private Sprite spinningMiddle;
private Sprite fixedMiddle;
private DrawableSpinner drawableSpinner;
private const float final_scale = 0.625f;
[BackgroundDependencyLoader]
private void load(ISkinSource source, DrawableHitObject drawableObject)
{
drawableSpinner = (DrawableSpinner)drawableObject;
Scale = new Vector2(final_scale);
InternalChildren = new Drawable[]
{
discBottom = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = source.GetTexture("spinner-bottom")
},
discTop = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = source.GetTexture("spinner-top")
},
fixedMiddle = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = source.GetTexture("spinner-middle")
},
spinningMiddle = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = source.GetTexture("spinner-middle2")
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeOut();
drawableSpinner.State.BindValueChanged(updateStateTransforms, true);
}
private void updateStateTransforms(ValueChangedEvent<ArmedState> state)
{
var spinner = (Spinner)drawableSpinner.HitObject;
using (BeginAbsoluteSequence(spinner.StartTime - spinner.TimePreempt / 2, true))
this.FadeInFromZero(spinner.TimePreempt / 2);
fixedMiddle.FadeColour(Color4.White);
using (BeginAbsoluteSequence(spinner.StartTime, true))
fixedMiddle.FadeColour(Color4.Red, spinner.Duration);
}
protected override void Update()
{
base.Update();
spinningMiddle.Rotation = discTop.Rotation = drawableSpinner.RotationTracker.Rotation;
discBottom.Rotation = discTop.Rotation / 3;
Scale = new Vector2(final_scale * (0.8f + (float)Interpolation.ApplyEasing(Easing.Out, drawableSpinner.Progress) * 0.2f));
}
}
}

View File

@ -0,0 +1,114 @@
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Utils;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.Skinning
{
/// <summary>
/// Legacy skinned spinner with one main spinning layer and a background layer.
/// </summary>
public class LegacyOldStyleSpinner : CompositeDrawable
{
private DrawableSpinner drawableSpinner;
private Sprite disc;
private Container metre;
private const float background_y_offset = 20;
private const float sprite_scale = 1 / 1.6f;
[BackgroundDependencyLoader]
private void load(ISkinSource source, DrawableHitObject drawableObject)
{
drawableSpinner = (DrawableSpinner)drawableObject;
RelativeSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
new Sprite
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Texture = source.GetTexture("spinner-background"),
Y = background_y_offset,
Scale = new Vector2(sprite_scale)
},
disc = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = source.GetTexture("spinner-circle"),
Scale = new Vector2(sprite_scale)
},
metre = new Container
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Y = background_y_offset,
Masking = true,
Child = new Sprite
{
Texture = source.GetTexture("spinner-metre"),
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
},
Scale = new Vector2(0.625f)
}
};
}
private Vector2 metreFinalSize;
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeOut();
drawableSpinner.State.BindValueChanged(updateStateTransforms, true);
metreFinalSize = metre.Size = metre.Child.Size;
}
private void updateStateTransforms(ValueChangedEvent<ArmedState> state)
{
var spinner = drawableSpinner.HitObject;
using (BeginAbsoluteSequence(spinner.StartTime - spinner.TimePreempt / 2, true))
this.FadeInFromZero(spinner.TimePreempt / 2);
}
protected override void Update()
{
base.Update();
disc.Rotation = drawableSpinner.RotationTracker.Rotation;
metre.Height = getMetreHeight(drawableSpinner.Progress);
}
private const int total_bars = 10;
private float getMetreHeight(float progress)
{
progress = Math.Min(99, progress * 100);
int barCount = (int)progress / 10;
// todo: add SpinnerNoBlink support
if (RNG.NextBool(((int)progress % 10) / 10f))
barCount++;
return (float)barCount / total_bars * metreFinalSize.Y;
}
}
}

View File

@ -102,6 +102,16 @@ namespace osu.Game.Rulesets.Osu.Skinning
Scale = new Vector2(0.8f), Scale = new Vector2(0.8f),
Spacing = new Vector2(-overlap, 0) Spacing = new Vector2(-overlap, 0)
}; };
case OsuSkinComponents.SpinnerBody:
bool hasBackground = Source.GetTexture("spinner-background") != null;
if (Source.GetTexture("spinner-top") != null && !hasBackground)
return new LegacyNewStyleSpinner();
else if (hasBackground)
return new LegacyOldStyleSpinner();
return null;
} }
return null; return null;

View File

@ -35,7 +35,7 @@ namespace osu.Game.Rulesets.Osu.UI
protected override PassThroughInputManager CreateInputManager() => new OsuInputManager(Ruleset.RulesetInfo); protected override PassThroughInputManager CreateInputManager() => new OsuInputManager(Ruleset.RulesetInfo);
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer(); public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { AlignWithStoryboard = true };
protected override ResumeOverlay CreateResumeOverlay() => new OsuResumeOverlay(); protected override ResumeOverlay CreateResumeOverlay() => new OsuResumeOverlay();

View File

@ -23,7 +23,8 @@ namespace osu.Game.Rulesets.Osu.UI
{ {
public class OsuPlayfield : Playfield public class OsuPlayfield : Playfield
{ {
private readonly ApproachCircleProxyContainer approachCircles; private readonly ProxyContainer approachCircles;
private readonly ProxyContainer spinnerProxies;
private readonly JudgementContainer<DrawableOsuJudgement> judgementLayer; private readonly JudgementContainer<DrawableOsuJudgement> judgementLayer;
private readonly FollowPointRenderer followPoints; private readonly FollowPointRenderer followPoints;
private readonly OrderedHitPolicy hitPolicy; private readonly OrderedHitPolicy hitPolicy;
@ -38,6 +39,10 @@ namespace osu.Game.Rulesets.Osu.UI
{ {
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{ {
spinnerProxies = new ProxyContainer
{
RelativeSizeAxes = Axes.Both
},
followPoints = new FollowPointRenderer followPoints = new FollowPointRenderer
{ {
RelativeSizeAxes = Axes.Both, RelativeSizeAxes = Axes.Both,
@ -54,7 +59,7 @@ namespace osu.Game.Rulesets.Osu.UI
{ {
Child = HitObjectContainer, Child = HitObjectContainer,
}, },
approachCircles = new ApproachCircleProxyContainer approachCircles = new ProxyContainer
{ {
RelativeSizeAxes = Axes.Both, RelativeSizeAxes = Axes.Both,
Depth = -1, Depth = -1,
@ -76,6 +81,9 @@ namespace osu.Game.Rulesets.Osu.UI
h.OnNewResult += onNewResult; h.OnNewResult += onNewResult;
h.OnLoadComplete += d => h.OnLoadComplete += d =>
{ {
if (d is DrawableSpinner)
spinnerProxies.Add(d.CreateProxy());
if (d is IDrawableHitObjectWithProxiedApproach c) if (d is IDrawableHitObjectWithProxiedApproach c)
approachCircles.Add(c.ProxiedLayer.CreateProxy()); approachCircles.Add(c.ProxiedLayer.CreateProxy());
}; };
@ -113,9 +121,9 @@ namespace osu.Game.Rulesets.Osu.UI
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => HitObjectContainer.ReceivePositionalInputAt(screenSpacePos); public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => HitObjectContainer.ReceivePositionalInputAt(screenSpacePos);
private class ApproachCircleProxyContainer : LifetimeManagementContainer private class ProxyContainer : LifetimeManagementContainer
{ {
public void Add(Drawable approachCircleProxy) => AddInternal(approachCircleProxy); public void Add(Drawable proxy) => AddInternal(proxy);
} }
private class DrawableJudgementPool : DrawablePool<DrawableOsuJudgement> private class DrawableJudgementPool : DrawablePool<DrawableOsuJudgement>

View File

@ -11,10 +11,19 @@ namespace osu.Game.Rulesets.Osu.UI
public class OsuPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer public class OsuPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{ {
protected override Container<Drawable> Content => content; protected override Container<Drawable> Content => content;
private readonly Container content; private readonly ScalingContainer content;
private const float playfield_size_adjust = 0.8f; private const float playfield_size_adjust = 0.8f;
/// <summary>
/// When true, an offset is applied to allow alignment with historical storyboards displayed in the same parent space.
/// This will shift the playfield downwards slightly.
/// </summary>
public bool AlignWithStoryboard
{
set => content.PlayfieldShift = value;
}
public OsuPlayfieldAdjustmentContainer() public OsuPlayfieldAdjustmentContainer()
{ {
Anchor = Anchor.Centre; Anchor = Anchor.Centre;
@ -39,6 +48,8 @@ namespace osu.Game.Rulesets.Osu.UI
/// </summary> /// </summary>
private class ScalingContainer : Container private class ScalingContainer : Container
{ {
internal bool PlayfieldShift { get; set; }
protected override void Update() protected override void Update()
{ {
base.Update(); base.Update();
@ -55,6 +66,7 @@ namespace osu.Game.Rulesets.Osu.UI
// Scale = 819.2 / 512 // Scale = 819.2 / 512
// Scale = 1.6 // Scale = 1.6
Scale = new Vector2(Parent.ChildSize.X / OsuPlayfield.BASE_SIZE.X); Scale = new Vector2(Parent.ChildSize.X / OsuPlayfield.BASE_SIZE.X);
Position = new Vector2(0, (PlayfieldShift ? 8f : 0f) * Scale.X);
// Size = 0.625 // Size = 0.625
Size = Vector2.Divide(Vector2.One, Scale); Size = Vector2.Divide(Vector2.One, Scale);
} }

View File

@ -0,0 +1,10 @@
osu file format v14
[General]
Mode: 1
[TimingPoints]
0,300,4,1,2,100,1,0
[HitObjects]
444,320,1000,5,0,0:0:0:0:

View File

@ -0,0 +1,52 @@
// 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.Reflection;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TestSceneTaikoHitObjectSamples : HitObjectSampleTest
{
protected override Ruleset CreatePlayerRuleset() => new TaikoRuleset();
protected override IResourceStore<byte[]> Resources => new DllResourceStore(Assembly.GetAssembly(typeof(TestSceneTaikoHitObjectSamples)));
[TestCase("taiko-normal-hitnormal")]
[TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestDefaultCustomSampleFromBeatmap(string expectedSample)
{
SetupSkins(expectedSample, expectedSample);
CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu");
AssertBeatmapLookup(expectedSample);
}
[TestCase("taiko-normal-hitnormal")]
[TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample)
{
SetupSkins(string.Empty, expectedSample);
CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu");
AssertUserLookup(expectedSample);
}
[TestCase("taiko-normal-hitnormal2")]
[TestCase("normal-hitnormal2")]
public void TestUserSkinLookupIgnoresSampleBank(string unwantedSample)
{
SetupSkins(string.Empty, unwantedSample);
CreateTestWithBeatmap("taiko-hitobject-beatmap-custom-sample-bank.osu");
AssertNoLookup(unwantedSample);
}
}
}

View File

@ -2,7 +2,7 @@
<Import Project="..\osu.TestProject.props" /> <Import Project="..\osu.TestProject.props" />
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" /> <PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="NUnit" Version="3.12.0" /> <PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />

View File

@ -6,9 +6,9 @@ using osu.Framework.IO.Stores;
using osu.Framework.Testing; using osu.Framework.Testing;
using osu.Game.Rulesets; using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Tests.Beatmaps; using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Resources; using osu.Game.Tests.Resources;
using static osu.Game.Skinning.LegacySkinConfiguration;
namespace osu.Game.Tests.Gameplay namespace osu.Game.Tests.Gameplay
{ {
@ -67,9 +67,11 @@ namespace osu.Game.Tests.Gameplay
/// Tests that a hitobject which provides a custom sample set of 2 retrieves the following samples from the beatmap skin: /// Tests that a hitobject which provides a custom sample set of 2 retrieves the following samples from the beatmap skin:
/// normal-hitnormal2 /// normal-hitnormal2
/// normal-hitnormal /// normal-hitnormal
/// hitnormal
/// </summary> /// </summary>
[TestCase("normal-hitnormal2")] [TestCase("normal-hitnormal2")]
[TestCase("normal-hitnormal")] [TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestDefaultCustomSampleFromBeatmap(string expectedSample) public void TestDefaultCustomSampleFromBeatmap(string expectedSample)
{ {
SetupSkins(expectedSample, expectedSample); SetupSkins(expectedSample, expectedSample);
@ -80,12 +82,13 @@ namespace osu.Game.Tests.Gameplay
} }
/// <summary> /// <summary>
/// Tests that a hitobject which provides a custom sample set of 2 retrieves the following samples from the user skin when the beatmap does not contain the sample: /// Tests that a hitobject which provides a custom sample set of 2 retrieves the following samples from the user skin
/// normal-hitnormal2 /// (ignoring the custom sample set index) when the beatmap skin does not contain the sample:
/// normal-hitnormal /// normal-hitnormal
/// hitnormal
/// </summary> /// </summary>
[TestCase("normal-hitnormal2")]
[TestCase("normal-hitnormal")] [TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample) public void TestDefaultCustomSampleFromUserSkinFallback(string expectedSample)
{ {
SetupSkins(string.Empty, expectedSample); SetupSkins(string.Empty, expectedSample);
@ -95,6 +98,23 @@ namespace osu.Game.Tests.Gameplay
AssertUserLookup(expectedSample); AssertUserLookup(expectedSample);
} }
/// <summary>
/// Tests that a hitobject which provides a custom sample set of 2 does not retrieve a normal-hitnormal2 sample from the user skin
/// if the beatmap skin does not contain the sample.
/// User skins in stable ignore the custom sample set index when performing lookups.
/// </summary>
[Test]
public void TestUserSkinLookupIgnoresSampleBank()
{
const string unwanted_sample = "normal-hitnormal2";
SetupSkins(string.Empty, unwanted_sample);
CreateTestWithBeatmap("hitobject-beatmap-custom-sample.osu");
AssertNoLookup(unwanted_sample);
}
/// <summary> /// <summary>
/// Tests that a hitobject which provides a sample file retrieves the sample file from the beatmap skin. /// Tests that a hitobject which provides a sample file retrieves the sample file from the beatmap skin.
/// </summary> /// </summary>
@ -145,6 +165,7 @@ namespace osu.Game.Tests.Gameplay
/// </summary> /// </summary>
[TestCase("normal-hitnormal2")] [TestCase("normal-hitnormal2")]
[TestCase("normal-hitnormal")] [TestCase("normal-hitnormal")]
[TestCase("hitnormal")]
public void TestControlPointCustomSampleFromBeatmap(string sampleName) public void TestControlPointCustomSampleFromBeatmap(string sampleName)
{ {
SetupSkins(sampleName, sampleName); SetupSkins(sampleName, sampleName);
@ -178,7 +199,7 @@ namespace osu.Game.Tests.Gameplay
string[] expectedSamples = string[] expectedSamples =
{ {
"normal-hitnormal2", "normal-hitnormal2",
"normal-hitwhistle2" "normal-hitwhistle" // user skin lookups ignore custom sample set index
}; };
SetupSkins(expectedSamples[0], expectedSamples[1]); SetupSkins(expectedSamples[0], expectedSamples[1]);
@ -190,7 +211,7 @@ namespace osu.Game.Tests.Gameplay
} }
/// <summary> /// <summary>
/// Tests that when a custom sample bank is used, but <see cref="GlobalSkinConfiguration.LayeredHitSounds"/> is disabled, /// Tests that when a custom sample bank is used, but <see cref="LegacySetting.LayeredHitSounds"/> is disabled,
/// only the additional sound will be looked up. /// only the additional sound will be looked up.
/// </summary> /// </summary>
[Test] [Test]
@ -209,7 +230,7 @@ namespace osu.Game.Tests.Gameplay
} }
/// <summary> /// <summary>
/// Tests that when a normal sample bank is used and <see cref="GlobalSkinConfiguration.LayeredHitSounds"/> is disabled, /// Tests that when a normal sample bank is used and <see cref="LegacySetting.LayeredHitSounds"/> is disabled,
/// the normal sound will be looked up anyway. /// the normal sound will be looked up anyway.
/// </summary> /// </summary>
[Test] [Test]
@ -226,6 +247,6 @@ namespace osu.Game.Tests.Gameplay
} }
private void disableLayeredHitSounds() private void disableLayeredHitSounds()
=> AddStep("set LayeredHitSounds to false", () => Skin.Configuration.ConfigDictionary[GlobalSkinConfiguration.LayeredHitSounds.ToString()] = "0"); => AddStep("set LayeredHitSounds to false", () => Skin.Configuration.ConfigDictionary[LegacySetting.LayeredHitSounds.ToString()] = "0");
} }
} }

View File

@ -3,14 +3,24 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API; using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Multiplayer; using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring; using osu.Game.Scoring;
using osu.Game.Screens.Multi.Ranking; using osu.Game.Screens.Multi.Ranking;
using osu.Game.Screens.Ranking;
using osu.Game.Tests.Beatmaps; using osu.Game.Tests.Beatmaps;
using osu.Game.Users; using osu.Game.Users;
@ -18,43 +28,134 @@ namespace osu.Game.Tests.Visual.Multiplayer
{ {
public class TestSceneTimeshiftResultsScreen : ScreenTestScene public class TestSceneTimeshiftResultsScreen : ScreenTestScene
{ {
private bool roomsReceived; private const int scores_per_result = 10;
private TestResultsScreen resultsScreen;
private int currentScoreId;
private bool requestComplete;
[SetUp] [SetUp]
public void Setup() => Schedule(() => public void Setup() => Schedule(() =>
{ {
roomsReceived = false; currentScoreId = 0;
requestComplete = false;
bindHandler(); bindHandler();
}); });
[Test] [Test]
public void TestShowResultsWithScore() public void TestShowWithUserScore()
{ {
createResults(new TestScoreInfo(new OsuRuleset().RulesetInfo)); ScoreInfo userScore = null;
AddWaitStep("wait for display", 5);
AddStep("bind user score info handler", () =>
{
userScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { OnlineScoreID = currentScoreId++ };
bindHandler(userScore: userScore);
});
createResults(() => userScore);
waitForDisplay();
AddAssert("user score selected", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineScoreID == userScore.OnlineScoreID).State == PanelState.Expanded);
} }
[Test] [Test]
public void TestShowResultsNullScore() public void TestShowNullUserScore()
{ {
createResults(null); createResults();
AddWaitStep("wait for display", 5); waitForDisplay();
AddAssert("top score selected", () => this.ChildrenOfType<ScorePanel>().OrderByDescending(p => p.Score.TotalScore).First().State == PanelState.Expanded);
} }
[Test] [Test]
public void TestShowResultsNullScoreWithDelay() public void TestShowUserScoreWithDelay()
{
ScoreInfo userScore = null;
AddStep("bind user score info handler", () =>
{
userScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { OnlineScoreID = currentScoreId++ };
bindHandler(3000, userScore);
});
createResults(() => userScore);
waitForDisplay();
AddAssert("more than 1 panel displayed", () => this.ChildrenOfType<ScorePanel>().Count() > 1);
AddAssert("user score selected", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineScoreID == userScore.OnlineScoreID).State == PanelState.Expanded);
}
[Test]
public void TestShowNullUserScoreWithDelay()
{ {
AddStep("bind delayed handler", () => bindHandler(3000)); AddStep("bind delayed handler", () => bindHandler(3000));
createResults(null);
AddUntilStep("wait for rooms to be received", () => roomsReceived); createResults();
AddWaitStep("wait for display", 5); waitForDisplay();
AddAssert("top score selected", () => this.ChildrenOfType<ScorePanel>().OrderByDescending(p => p.Score.TotalScore).First().State == PanelState.Expanded);
} }
private void createResults(ScoreInfo score) [Test]
public void TestFetchWhenScrolledToTheRight()
{
createResults();
waitForDisplay();
AddStep("bind delayed handler", () => bindHandler(3000));
for (int i = 0; i < 2; i++)
{
int beforePanelCount = 0;
AddStep("get panel count", () => beforePanelCount = this.ChildrenOfType<ScorePanel>().Count());
AddStep("scroll to right", () => resultsScreen.ScorePanelList.ChildrenOfType<OsuScrollContainer>().Single().ScrollToEnd(false));
AddAssert("right loading spinner shown", () => resultsScreen.RightSpinner.State.Value == Visibility.Visible);
waitForDisplay();
AddAssert($"count increased by {scores_per_result}", () => this.ChildrenOfType<ScorePanel>().Count() == beforePanelCount + scores_per_result);
AddAssert("right loading spinner hidden", () => resultsScreen.RightSpinner.State.Value == Visibility.Hidden);
}
}
[Test]
public void TestFetchWhenScrolledToTheLeft()
{
ScoreInfo userScore = null;
AddStep("bind user score info handler", () =>
{
userScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { OnlineScoreID = currentScoreId++ };
bindHandler(userScore: userScore);
});
createResults(() => userScore);
waitForDisplay();
AddStep("bind delayed handler", () => bindHandler(3000));
for (int i = 0; i < 2; i++)
{
int beforePanelCount = 0;
AddStep("get panel count", () => beforePanelCount = this.ChildrenOfType<ScorePanel>().Count());
AddStep("scroll to left", () => resultsScreen.ScorePanelList.ChildrenOfType<OsuScrollContainer>().Single().ScrollToStart(false));
AddAssert("left loading spinner shown", () => resultsScreen.LeftSpinner.State.Value == Visibility.Visible);
waitForDisplay();
AddAssert($"count increased by {scores_per_result}", () => this.ChildrenOfType<ScorePanel>().Count() == beforePanelCount + scores_per_result);
AddAssert("left loading spinner hidden", () => resultsScreen.LeftSpinner.State.Value == Visibility.Hidden);
}
}
private void createResults(Func<ScoreInfo> getScore = null)
{ {
AddStep("load results", () => AddStep("load results", () =>
{ {
LoadScreen(new TimeshiftResultsScreen(score, 1, new PlaylistItem LoadScreen(resultsScreen = new TestResultsScreen(getScore?.Invoke(), 1, new PlaylistItem
{ {
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo }, Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo } Ruleset = { Value = new OsuRuleset().RulesetInfo }
@ -62,42 +163,40 @@ namespace osu.Game.Tests.Visual.Multiplayer
}); });
} }
private void bindHandler(double delay = 0) private void waitForDisplay()
{ {
var roomScores = new List<MultiplayerScore>(); AddUntilStep("wait for request to complete", () => requestComplete);
AddWaitStep("wait for display", 5);
for (int i = 0; i < 10; i++)
{
roomScores.Add(new MultiplayerScore
{
ID = i,
Accuracy = 0.9 - 0.01 * i,
EndedAt = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(i)),
Passed = true,
Rank = ScoreRank.B,
MaxCombo = 999,
TotalScore = 999999 - i * 1000,
User = new User
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics =
{
{ HitResult.Miss, 1 },
{ HitResult.Meh, 50 },
{ HitResult.Good, 100 },
{ HitResult.Great, 300 },
}
});
} }
((DummyAPIAccess)API).HandleRequest = request => private void bindHandler(double delay = 0, ScoreInfo userScore = null, bool failRequests = false) => ((DummyAPIAccess)API).HandleRequest = request =>
{ {
requestComplete = false;
if (failRequests)
{
triggerFail(request, delay);
return;
}
switch (request) switch (request)
{ {
case GetRoomPlaylistScoresRequest r: case ShowPlaylistUserScoreRequest s:
if (userScore == null)
triggerFail(s, delay);
else
triggerSuccess(s, createUserResponse(userScore), delay);
break;
case IndexPlaylistScoresRequest i:
triggerSuccess(i, createIndexResponse(i), delay);
break;
}
};
private void triggerSuccess<T>(APIRequest<T> req, T result, double delay)
where T : class
{
if (delay == 0) if (delay == 0)
success(); success();
else else
@ -111,13 +210,167 @@ namespace osu.Game.Tests.Visual.Multiplayer
void success() void success()
{ {
r.TriggerSuccess(new RoomPlaylistScores { Scores = roomScores }); requestComplete = true;
roomsReceived = true; req.TriggerSuccess(result);
}
} }
break; private void triggerFail(APIRequest req, double delay)
{
if (delay == 0)
fail();
else
{
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromMilliseconds(delay));
Schedule(fail);
});
}
void fail()
{
requestComplete = true;
req.TriggerFailure(new WebException("Failed."));
}
}
private MultiplayerScore createUserResponse([NotNull] ScoreInfo userScore)
{
var multiplayerUserScore = new MultiplayerScore
{
ID = (int)(userScore.OnlineScoreID ?? currentScoreId++),
Accuracy = userScore.Accuracy,
EndedAt = userScore.Date,
Passed = userScore.Passed,
Rank = userScore.Rank,
Position = 200,
MaxCombo = userScore.MaxCombo,
TotalScore = userScore.TotalScore,
User = userScore.User,
Statistics = userScore.Statistics,
ScoresAround = new MultiplayerScoresAround
{
Higher = new MultiplayerScores(),
Lower = new MultiplayerScores()
}
};
for (int i = 1; i <= scores_per_result; i++)
{
multiplayerUserScore.ScoresAround.Lower.Scores.Add(new MultiplayerScore
{
ID = currentScoreId++,
Accuracy = userScore.Accuracy,
EndedAt = userScore.Date,
Passed = true,
Rank = userScore.Rank,
MaxCombo = userScore.MaxCombo,
TotalScore = userScore.TotalScore - i,
User = new User
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics = userScore.Statistics
});
multiplayerUserScore.ScoresAround.Higher.Scores.Add(new MultiplayerScore
{
ID = currentScoreId++,
Accuracy = userScore.Accuracy,
EndedAt = userScore.Date,
Passed = true,
Rank = userScore.Rank,
MaxCombo = userScore.MaxCombo,
TotalScore = userScore.TotalScore + i,
User = new User
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics = userScore.Statistics
});
}
addCursor(multiplayerUserScore.ScoresAround.Lower);
addCursor(multiplayerUserScore.ScoresAround.Higher);
return multiplayerUserScore;
}
private IndexedMultiplayerScores createIndexResponse(IndexPlaylistScoresRequest req)
{
var result = new IndexedMultiplayerScores();
long startTotalScore = req.Cursor?.Properties["total_score"].ToObject<long>() ?? 1000000;
string sort = req.IndexParams?.Properties["sort"].ToObject<string>() ?? "score_desc";
for (int i = 1; i <= scores_per_result; i++)
{
result.Scores.Add(new MultiplayerScore
{
ID = currentScoreId++,
Accuracy = 1,
EndedAt = DateTimeOffset.Now,
Passed = true,
Rank = ScoreRank.X,
MaxCombo = 1000,
TotalScore = startTotalScore + (sort == "score_asc" ? i : -i),
User = new User
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Miss, 1 },
{ HitResult.Meh, 50 },
{ HitResult.Good, 100 },
{ HitResult.Great, 300 }
}
});
}
addCursor(result);
return result;
}
private void addCursor(MultiplayerScores scores)
{
scores.Cursor = new Cursor
{
Properties = new Dictionary<string, JToken>
{
{ "total_score", JToken.FromObject(scores.Scores[^1].TotalScore) },
{ "score_id", JToken.FromObject(scores.Scores[^1].ID) },
}
};
scores.Params = new IndexScoresParams
{
Properties = new Dictionary<string, JToken>
{
{ "sort", JToken.FromObject(scores.Scores[^1].TotalScore > scores.Scores[^2].TotalScore ? "score_asc" : "score_desc") }
} }
}; };
} }
private class TestResultsScreen : TimeshiftResultsScreen
{
public new LoadingSpinner LeftSpinner => base.LeftSpinner;
public new LoadingSpinner CentreSpinner => base.CentreSpinner;
public new LoadingSpinner RightSpinner => base.RightSpinner;
public new ScorePanelList ScorePanelList => base.ScorePanelList;
public TestResultsScreen(ScoreInfo score, int roomId, PlaylistItem playlistItem, bool allowRetry = true)
: base(score, roomId, playlistItem, allowRetry)
{
}
}
} }
} }

View File

@ -31,15 +31,16 @@ namespace osu.Game.Tests.Visual.Online
{ {
new NewsCard(new APINewsPost new NewsCard(new APINewsPost
{ {
Title = "This post has an image which starts with \"/\" and has many authors!", Title = "This post has an image which starts with \"/\" and has many authors! (clickable)",
Preview = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", Preview = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
Author = "someone, someone1, someone2, someone3, someone4", Author = "someone, someone1, someone2, someone3, someone4",
FirstImage = "/help/wiki/shared/news/banners/monthly-beatmapping-contest.png", FirstImage = "/help/wiki/shared/news/banners/monthly-beatmapping-contest.png",
PublishedAt = DateTimeOffset.Now PublishedAt = DateTimeOffset.Now,
Slug = "2020-07-16-summer-theme-park-2020-voting-open"
}), }),
new NewsCard(new APINewsPost new NewsCard(new APINewsPost
{ {
Title = "This post has a full-url image! (HTML entity: &amp;)", Title = "This post has a full-url image! (HTML entity: &amp;) (non-clickable)",
Preview = "boom (HTML entity: &amp;)", Preview = "boom (HTML entity: &amp;)",
Author = "user (HTML entity: &amp;)", Author = "user (HTML entity: &amp;)",
FirstImage = "https://assets.ppy.sh/artists/88/header.jpg", FirstImage = "https://assets.ppy.sh/artists/88/header.jpg",

View File

@ -0,0 +1,53 @@
// 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 NUnit.Framework;
using osu.Game.Overlays.News;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Framework.Allocation;
namespace osu.Game.Tests.Visual.Online
{
public class TestSceneNewsHeader : OsuTestScene
{
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
private TestHeader header;
[SetUp]
public void Setup() => Schedule(() =>
{
Child = header = new TestHeader
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
};
});
[Test]
public void TestControl()
{
AddAssert("Front page selected", () => header.Current.Value == "frontpage");
AddAssert("1 tab total", () => header.TabCount == 1);
AddStep("Set article 1", () => header.SetArticle("1"));
AddAssert("Article 1 selected", () => header.Current.Value == "1");
AddAssert("2 tabs total", () => header.TabCount == 2);
AddStep("Set article 2", () => header.SetArticle("2"));
AddAssert("Article 2 selected", () => header.Current.Value == "2");
AddAssert("2 tabs total", () => header.TabCount == 2);
AddStep("Set front page", () => header.SetFrontPage());
AddAssert("Front page selected", () => header.Current.Value == "frontpage");
AddAssert("1 tab total", () => header.TabCount == 1);
}
private class TestHeader : NewsHeader
{
public int TabCount => TabControl.Items.Count;
}
}
}

View File

@ -2,65 +2,64 @@
// 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 osu.Framework.Graphics; using NUnit.Framework;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays; using osu.Game.Overlays;
using osu.Game.Overlays.News;
namespace osu.Game.Tests.Visual.Online namespace osu.Game.Tests.Visual.Online
{ {
public class TestSceneNewsOverlay : OsuTestScene public class TestSceneNewsOverlay : OsuTestScene
{ {
private TestNewsOverlay news; private DummyAPIAccess dummyAPI => (DummyAPIAccess)API;
protected override void LoadComplete() private NewsOverlay news;
[SetUp]
public void SetUp() => Schedule(() => Child = news = new NewsOverlay());
[Test]
public void TestRequest()
{ {
base.LoadComplete(); setUpNewsResponse(responseExample);
Add(news = new TestNewsOverlay()); AddStep("Show", () => news.Show());
AddStep(@"Show", news.Show); AddStep("Show article", () => news.ShowArticle("article"));
AddStep(@"Hide", news.Hide);
AddStep(@"Show front page", () => news.ShowFrontPage());
AddStep(@"Custom article", () => news.Current.Value = "Test Article 101");
AddStep(@"Article covers", () => news.LoadAndShowContent(new NewsCoverTest()));
} }
private class TestNewsOverlay : NewsOverlay private void setUpNewsResponse(GetNewsResponse r)
=> AddStep("set up response", () =>
{ {
public new void LoadAndShowContent(NewsContent content) => base.LoadAndShowContent(content); dummyAPI.HandleRequest = request =>
} {
if (!(request is GetNewsRequest getNewsRequest))
return;
private class NewsCoverTest : NewsContent getNewsRequest.TriggerSuccess(r);
{
public NewsCoverTest()
{
Spacing = new osuTK.Vector2(0, 10);
var article = new NewsArticleCover.ArticleInfo
{
Author = "Ephemeral",
CoverUrl = "https://assets.ppy.sh/artists/58/header.jpg",
Time = new DateTime(2019, 12, 4),
Title = "New Featured Artist: Kurokotei"
}; };
});
Children = new Drawable[] private GetNewsResponse responseExample => new GetNewsResponse
{ {
new NewsArticleCover(article) NewsPosts = new[]
{ {
Height = 200 new APINewsPost
{
Title = "This post has an image which starts with \"/\" and has many authors!",
Preview = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
Author = "someone, someone1, someone2, someone3, someone4",
FirstImage = "/help/wiki/shared/news/banners/monthly-beatmapping-contest.png",
PublishedAt = DateTimeOffset.Now
}, },
new NewsArticleCover(article) new APINewsPost
{ {
Height = 120 Title = "This post has a full-url image! (HTML entity: &amp;)",
}, Preview = "boom (HTML entity: &amp;)",
new NewsArticleCover(article) Author = "user (HTML entity: &amp;)",
{ FirstImage = "https://assets.ppy.sh/artists/88/header.jpg",
RelativeSizeAxes = Axes.None, PublishedAt = DateTimeOffset.Now
Size = new osuTK.Vector2(400, 200), }
} }
}; };
} }
} }
}
}

View File

@ -4,19 +4,22 @@
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Game.Graphics; using osu.Game.Overlays;
namespace osu.Game.Tests.Visual.Online namespace osu.Game.Tests.Visual.Online
{ {
public class TestSceneShowMoreButton : OsuTestScene public class TestSceneShowMoreButton : OsuTestScene
{ {
[Cached]
private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Green);
public TestSceneShowMoreButton() public TestSceneShowMoreButton()
{ {
TestButton button = null; ShowMoreButton button = null;
int fireCount = 0; int fireCount = 0;
Add(button = new TestButton Add(button = new ShowMoreButton
{ {
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
@ -46,16 +49,5 @@ namespace osu.Game.Tests.Visual.Online
AddAssert("action fired twice", () => fireCount == 2); AddAssert("action fired twice", () => fireCount == 2);
AddAssert("is in loading state", () => button.IsLoading); AddAssert("is in loading state", () => button.IsLoading);
} }
private class TestButton : ShowMoreButton
{
[BackgroundDependencyLoader]
private void load(OsuColour colors)
{
IdleColour = colors.YellowDark;
HoverColour = colors.Yellow;
ChevronIconColour = colors.Red;
}
}
} }
} }

View File

@ -64,5 +64,77 @@ namespace osu.Game.Tests.Visual.Settings
}, 0, true); }, 0, true);
}); });
} }
[Test]
public void TestClearButtonOnBindings()
{
KeyBindingRow backBindingRow = null;
AddStep("click back binding row", () =>
{
backBindingRow = panel.ChildrenOfType<KeyBindingRow>().ElementAt(10);
InputManager.MoveMouseTo(backBindingRow);
InputManager.Click(MouseButton.Left);
});
clickClearButton();
AddAssert("first binding cleared", () => string.IsNullOrEmpty(backBindingRow.ChildrenOfType<KeyBindingRow.KeyButton>().First().Text.Text));
AddStep("click second binding", () =>
{
var target = backBindingRow.ChildrenOfType<KeyBindingRow.KeyButton>().ElementAt(1);
InputManager.MoveMouseTo(target);
InputManager.Click(MouseButton.Left);
});
clickClearButton();
AddAssert("second binding cleared", () => string.IsNullOrEmpty(backBindingRow.ChildrenOfType<KeyBindingRow.KeyButton>().ElementAt(1).Text.Text));
void clickClearButton()
{
AddStep("click clear button", () =>
{
var clearButton = backBindingRow.ChildrenOfType<KeyBindingRow.ClearButton>().Single();
InputManager.MoveMouseTo(clearButton);
InputManager.Click(MouseButton.Left);
});
}
}
[Test]
public void TestClickRowSelectsFirstBinding()
{
KeyBindingRow backBindingRow = null;
AddStep("click back binding row", () =>
{
backBindingRow = panel.ChildrenOfType<KeyBindingRow>().ElementAt(10);
InputManager.MoveMouseTo(backBindingRow);
InputManager.Click(MouseButton.Left);
});
AddAssert("first binding selected", () => backBindingRow.ChildrenOfType<KeyBindingRow.KeyButton>().First().IsBinding);
AddStep("click second binding", () =>
{
var target = backBindingRow.ChildrenOfType<KeyBindingRow.KeyButton>().ElementAt(1);
InputManager.MoveMouseTo(target);
InputManager.Click(MouseButton.Left);
});
AddStep("click back binding row", () =>
{
backBindingRow = panel.ChildrenOfType<KeyBindingRow>().ElementAt(10);
InputManager.MoveMouseTo(backBindingRow);
InputManager.Click(MouseButton.Left);
});
AddAssert("first binding selected", () => backBindingRow.ChildrenOfType<KeyBindingRow.KeyButton>().First().IsBinding);
}
} }
} }

View File

@ -44,6 +44,7 @@ namespace osu.Game.Tests.Visual
typeof(NotificationOverlay), typeof(NotificationOverlay),
typeof(BeatmapListingOverlay), typeof(BeatmapListingOverlay),
typeof(DashboardOverlay), typeof(DashboardOverlay),
typeof(NewsOverlay),
typeof(ChannelManager), typeof(ChannelManager),
typeof(ChatOverlay), typeof(ChatOverlay),
typeof(SettingsOverlay), typeof(SettingsOverlay),

View File

@ -0,0 +1,150 @@
// 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.Containers;
using osu.Framework.Graphics;
using osu.Game.Overlays.Dashboard.Home;
using osu.Game.Beatmaps;
using osu.Game.Overlays;
using osu.Framework.Allocation;
using osu.Game.Users;
using System;
using osu.Framework.Graphics.Shapes;
using System.Collections.Generic;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneDashboardBeatmapListing : OsuTestScene
{
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
private readonly Container content;
public TestSceneDashboardBeatmapListing()
{
Add(content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Y,
Width = 300,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background4
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Horizontal = 10 },
Child = new DashboardBeatmapListing(new_beatmaps, popular_beatmaps)
}
}
});
}
protected override void LoadComplete()
{
base.LoadComplete();
AddStep("Set width to 500", () => content.ResizeWidthTo(500, 500));
AddStep("Set width to 300", () => content.ResizeWidthTo(300, 500));
}
private static readonly List<BeatmapSetInfo> new_beatmaps = new List<BeatmapSetInfo>
{
new BeatmapSetInfo
{
Metadata = new BeatmapMetadata
{
Title = "Very Long Title (TV size) [TATOE]",
Artist = "This artist has a really long name how is this possible",
Author = new User
{
Username = "author",
Id = 100
}
},
OnlineInfo = new BeatmapSetOnlineInfo
{
Covers = new BeatmapSetOnlineCovers
{
Cover = "https://assets.ppy.sh/beatmaps/1189904/covers/cover.jpg?1595456608",
},
Ranked = DateTimeOffset.Now
}
},
new BeatmapSetInfo
{
Metadata = new BeatmapMetadata
{
Title = "Very Long Title (TV size) [TATOE]",
Artist = "This artist has a really long name how is this possible",
Author = new User
{
Username = "author",
Id = 100
}
},
OnlineInfo = new BeatmapSetOnlineInfo
{
Covers = new BeatmapSetOnlineCovers
{
Cover = "https://assets.ppy.sh/beatmaps/1189904/covers/cover.jpg?1595456608",
},
Ranked = DateTimeOffset.MinValue
}
}
};
private static readonly List<BeatmapSetInfo> popular_beatmaps = new List<BeatmapSetInfo>
{
new BeatmapSetInfo
{
Metadata = new BeatmapMetadata
{
Title = "Title",
Artist = "Artist",
Author = new User
{
Username = "author",
Id = 100
}
},
OnlineInfo = new BeatmapSetOnlineInfo
{
Covers = new BeatmapSetOnlineCovers
{
Cover = "https://assets.ppy.sh/beatmaps/1079428/covers/cover.jpg?1595295586",
},
FavouriteCount = 100
}
},
new BeatmapSetInfo
{
Metadata = new BeatmapMetadata
{
Title = "Title 2",
Artist = "Artist 2",
Author = new User
{
Username = "someone",
Id = 100
}
},
OnlineInfo = new BeatmapSetOnlineInfo
{
Covers = new BeatmapSetOnlineCovers
{
Cover = "https://assets.ppy.sh/beatmaps/1079428/covers/cover.jpg?1595295586",
},
FavouriteCount = 10
}
}
};
}
}

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.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
@ -263,7 +264,7 @@ namespace osu.Game.Tests.Visual.UserInterface
private void moveLogoFacade() private void moveLogoFacade()
{ {
if (logoFacade?.Transforms.Count == 0 && transferContainer?.Transforms.Count == 0) if (!(logoFacade?.Transforms).Any() && !(transferContainer?.Transforms).Any())
{ {
Random random = new Random(); Random random = new Random();
trackingContainer.Delay(500).MoveTo(new Vector2(random.Next(0, (int)logo.Parent.DrawWidth), random.Next(0, (int)logo.Parent.DrawHeight)), 300); trackingContainer.Delay(500).MoveTo(new Vector2(random.Next(0, (int)logo.Parent.DrawWidth), random.Next(0, (int)logo.Parent.DrawHeight)), 300);

View File

@ -3,7 +3,7 @@
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" /> <PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="DeepEqual" Version="2.0.0" /> <PackageReference Include="DeepEqual" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="NUnit" Version="3.12.0" /> <PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" /> <PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />

View File

@ -5,7 +5,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup Label="Package References"> <ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" /> <PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="NUnit" Version="3.12.0" /> <PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
</ItemGroup> </ItemGroup>

View File

@ -81,7 +81,7 @@ namespace osu.Game.Tournament.Screens.Ladder.Components
{ {
} }
private class SettingsRoundDropdown : LadderSettingsDropdown<TournamentRound> private class SettingsRoundDropdown : SettingsDropdown<TournamentRound>
{ {
public SettingsRoundDropdown(BindableList<TournamentRound> rounds) public SettingsRoundDropdown(BindableList<TournamentRound> rounds)
{ {

View File

@ -1,26 +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.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
namespace osu.Game.Tournament.Screens.Ladder.Components
{
public class LadderSettingsDropdown<T> : SettingsDropdown<T>
{
protected override OsuDropdown<T> CreateDropdown() => new DropdownControl();
private new class DropdownControl : SettingsDropdown<T>.DropdownControl
{
protected override DropdownMenu CreateMenu() => new Menu();
private new class Menu : OsuDropdownMenu
{
public Menu()
{
MaxHeight = 200;
}
}
}
}
}

View File

@ -6,11 +6,12 @@ using System.Collections.Specialized;
using System.Linq; using System.Linq;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Overlays.Settings;
using osu.Game.Tournament.Models; using osu.Game.Tournament.Models;
namespace osu.Game.Tournament.Screens.Ladder.Components namespace osu.Game.Tournament.Screens.Ladder.Components
{ {
public class SettingsTeamDropdown : LadderSettingsDropdown<TournamentTeam> public class SettingsTeamDropdown : SettingsDropdown<TournamentTeam>
{ {
public SettingsTeamDropdown(BindableList<TournamentTeam> teams) public SettingsTeamDropdown(BindableList<TournamentTeam> teams)
{ {

View File

@ -109,25 +109,58 @@ namespace osu.Game.Beatmaps
} }
private CancellationTokenSource trackedUpdateCancellationSource; private CancellationTokenSource trackedUpdateCancellationSource;
private readonly List<CancellationTokenSource> linkedCancellationSources = new List<CancellationTokenSource>();
/// <summary> /// <summary>
/// Updates all tracked <see cref="BindableStarDifficulty"/> using the current ruleset and mods. /// Updates all tracked <see cref="BindableStarDifficulty"/> using the current ruleset and mods.
/// </summary> /// </summary>
private void updateTrackedBindables() private void updateTrackedBindables()
{ {
trackedUpdateCancellationSource?.Cancel(); cancelTrackedBindableUpdate();
trackedUpdateCancellationSource = new CancellationTokenSource(); trackedUpdateCancellationSource = new CancellationTokenSource();
foreach (var b in trackedBindables) foreach (var b in trackedBindables)
{ {
if (trackedUpdateCancellationSource.IsCancellationRequested) var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(trackedUpdateCancellationSource.Token, b.CancellationToken);
break; linkedCancellationSources.Add(linkedSource);
using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(trackedUpdateCancellationSource.Token, b.CancellationToken))
updateBindable(b, currentRuleset.Value, currentMods.Value, linkedSource.Token); updateBindable(b, currentRuleset.Value, currentMods.Value, linkedSource.Token);
} }
} }
/// <summary>
/// Cancels the existing update of all tracked <see cref="BindableStarDifficulty"/> via <see cref="updateTrackedBindables"/>.
/// </summary>
private void cancelTrackedBindableUpdate()
{
trackedUpdateCancellationSource?.Cancel();
trackedUpdateCancellationSource = null;
if (linkedCancellationSources != null)
{
foreach (var c in linkedCancellationSources)
c.Dispose();
linkedCancellationSources.Clear();
}
}
/// <summary>
/// Creates a new <see cref="BindableStarDifficulty"/> and triggers an initial value update.
/// </summary>
/// <param name="beatmapInfo">The <see cref="BeatmapInfo"/> that star difficulty should correspond to.</param>
/// <param name="initialRulesetInfo">The initial <see cref="RulesetInfo"/> to get the difficulty with.</param>
/// <param name="initialMods">The initial <see cref="Mod"/>s to get the difficulty with.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> which stops updating the star difficulty for the given <see cref="BeatmapInfo"/>.</param>
/// <returns>The <see cref="BindableStarDifficulty"/>.</returns>
private BindableStarDifficulty createBindable([NotNull] BeatmapInfo beatmapInfo, [CanBeNull] RulesetInfo initialRulesetInfo, [CanBeNull] IEnumerable<Mod> initialMods,
CancellationToken cancellationToken)
{
var bindable = new BindableStarDifficulty(beatmapInfo, cancellationToken);
updateBindable(bindable, initialRulesetInfo, initialMods, cancellationToken);
return bindable;
}
/// <summary> /// <summary>
/// Updates the value of a <see cref="BindableStarDifficulty"/> with a given ruleset + mods. /// Updates the value of a <see cref="BindableStarDifficulty"/> with a given ruleset + mods.
/// </summary> /// </summary>
@ -148,22 +181,6 @@ namespace osu.Game.Beatmaps
}, cancellationToken); }, cancellationToken);
} }
/// <summary>
/// Creates a new <see cref="BindableStarDifficulty"/> and triggers an initial value update.
/// </summary>
/// <param name="beatmapInfo">The <see cref="BeatmapInfo"/> that star difficulty should correspond to.</param>
/// <param name="initialRulesetInfo">The initial <see cref="RulesetInfo"/> to get the difficulty with.</param>
/// <param name="initialMods">The initial <see cref="Mod"/>s to get the difficulty with.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> which stops updating the star difficulty for the given <see cref="BeatmapInfo"/>.</param>
/// <returns>The <see cref="BindableStarDifficulty"/>.</returns>
private BindableStarDifficulty createBindable([NotNull] BeatmapInfo beatmapInfo, [CanBeNull] RulesetInfo initialRulesetInfo, [CanBeNull] IEnumerable<Mod> initialMods,
CancellationToken cancellationToken)
{
var bindable = new BindableStarDifficulty(beatmapInfo, cancellationToken);
updateBindable(bindable, initialRulesetInfo, initialMods, cancellationToken);
return bindable;
}
/// <summary> /// <summary>
/// Computes the difficulty defined by a <see cref="DifficultyCacheLookup"/> key, and stores it to the timed cache. /// Computes the difficulty defined by a <see cref="DifficultyCacheLookup"/> key, and stores it to the timed cache.
/// </summary> /// </summary>
@ -220,6 +237,14 @@ namespace osu.Game.Beatmaps
return difficultyCache.TryGetValue(key, out existingDifficulty); return difficultyCache.TryGetValue(key, out existingDifficulty);
} }
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
cancelTrackedBindableUpdate();
updateScheduler?.Dispose();
}
private readonly struct DifficultyCacheLookup : IEquatable<DifficultyCacheLookup> private readonly struct DifficultyCacheLookup : IEquatable<DifficultyCacheLookup>
{ {
public readonly int BeatmapId; public readonly int BeatmapId;

View File

@ -1,13 +1,15 @@
// 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.Framework.Allocation;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Sprites; using osu.Game.Graphics.Sprites;
using osu.Game.Overlays;
using osuTK; using osuTK;
using osuTK.Graphics;
using System.Collections.Generic; using System.Collections.Generic;
namespace osu.Game.Graphics.UserInterface namespace osu.Game.Graphics.UserInterface
@ -16,14 +18,6 @@ namespace osu.Game.Graphics.UserInterface
{ {
private const int duration = 200; private const int duration = 200;
private Color4 chevronIconColour;
protected Color4 ChevronIconColour
{
get => chevronIconColour;
set => chevronIconColour = leftChevron.Colour = rightChevron.Colour = value;
}
public string Text public string Text
{ {
get => text.Text; get => text.Text;
@ -32,22 +26,28 @@ namespace osu.Game.Graphics.UserInterface
protected override IEnumerable<Drawable> EffectTargets => new[] { background }; protected override IEnumerable<Drawable> EffectTargets => new[] { background };
private ChevronIcon leftChevron; private ChevronIcon leftIcon;
private ChevronIcon rightChevron; private ChevronIcon rightIcon;
private SpriteText text; private SpriteText text;
private Box background; private Box background;
private FillFlowContainer textContainer; private FillFlowContainer textContainer;
public ShowMoreButton() public ShowMoreButton()
{ {
Height = 30; AutoSizeAxes = Axes.Both;
Width = 140; }
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
IdleColour = colourProvider.Background2;
HoverColour = colourProvider.Background1;
} }
protected override Drawable CreateContent() => new CircularContainer protected override Drawable CreateContent() => new CircularContainer
{ {
Masking = true, Masking = true,
RelativeSizeAxes = Axes.Both, AutoSizeAxes = Axes.Both,
Children = new Drawable[] Children = new Drawable[]
{ {
background = new Box background = new Box
@ -56,22 +56,36 @@ namespace osu.Game.Graphics.UserInterface
}, },
textContainer = new FillFlowContainer textContainer = new FillFlowContainer
{ {
AlwaysPresent = true,
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both, AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal, Direction = FillDirection.Horizontal,
Spacing = new Vector2(7), Spacing = new Vector2(10),
Margin = new MarginPadding
{
Horizontal = 20,
Vertical = 5
},
Children = new Drawable[] Children = new Drawable[]
{ {
leftChevron = new ChevronIcon(), leftIcon = new ChevronIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
text = new OsuSpriteText text = new OsuSpriteText
{ {
Anchor = Anchor.Centre, Anchor = Anchor.Centre,
Origin = Anchor.Centre, Origin = Anchor.Centre,
Font = OsuFont.GetFont(size: 12, weight: FontWeight.Bold), Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold),
Text = "show more".ToUpper(), Text = "show more".ToUpper(),
}, },
rightChevron = new ChevronIcon(), rightIcon = new ChevronIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
} }
} }
} }
@ -81,17 +95,40 @@ namespace osu.Game.Graphics.UserInterface
protected override void OnLoadFinished() => textContainer.FadeIn(duration, Easing.OutQuint); protected override void OnLoadFinished() => textContainer.FadeIn(duration, Easing.OutQuint);
private class ChevronIcon : SpriteIcon protected override bool OnHover(HoverEvent e)
{ {
private const int icon_size = 8; base.OnHover(e);
leftIcon.SetHoveredState(true);
rightIcon.SetHoveredState(true);
return true;
}
protected override void OnHoverLost(HoverLostEvent e)
{
base.OnHoverLost(e);
leftIcon.SetHoveredState(false);
rightIcon.SetHoveredState(false);
}
public class ChevronIcon : SpriteIcon
{
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
public ChevronIcon() public ChevronIcon()
{ {
Anchor = Anchor.Centre; Size = new Vector2(7.5f);
Origin = Anchor.Centre;
Size = new Vector2(icon_size);
Icon = FontAwesome.Solid.ChevronDown; Icon = FontAwesome.Solid.ChevronDown;
} }
[BackgroundDependencyLoader]
private void load()
{
Colour = colourProvider.Foreground1;
}
public void SetHoveredState(bool hovered) =>
this.FadeColour(hovered ? colourProvider.Light1 : colourProvider.Foreground1, 200, Easing.OutQuint);
} }
} }
} }

View File

@ -136,6 +136,11 @@ namespace osu.Game.Online.API
Success?.Invoke(); Success?.Invoke();
} }
internal void TriggerFailure(Exception e)
{
Failure?.Invoke(e);
}
public void Cancel() => Fail(new OperationCanceledException(@"Request cancelled")); public void Cancel() => Fail(new OperationCanceledException(@"Request cancelled"));
public void Fail(Exception e) public void Fail(Exception e)
@ -166,7 +171,7 @@ namespace osu.Game.Online.API
} }
Logger.Log($@"Failing request {this} ({e})", LoggingTarget.Network); Logger.Log($@"Failing request {this} ({e})", LoggingTarget.Network);
pendingFailure = () => Failure?.Invoke(e); pendingFailure = () => TriggerFailure(e);
checkAndScheduleFailure(); checkAndScheduleFailure();
} }

View File

@ -15,6 +15,6 @@ namespace osu.Game.Online.API.Requests
{ {
[UsedImplicitly] [UsedImplicitly]
[JsonExtensionData] [JsonExtensionData]
public IDictionary<string, JToken> Properties; public IDictionary<string, JToken> Properties { get; set; } = new Dictionary<string, JToken>();
} }
} }

View File

@ -0,0 +1,27 @@
// 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.IO.Network;
using osu.Game.Extensions;
namespace osu.Game.Online.API.Requests
{
public class GetNewsRequest : APIRequest<GetNewsResponse>
{
private readonly Cursor cursor;
public GetNewsRequest(Cursor cursor = null)
{
this.cursor = cursor;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.AddCursor(cursor);
return req;
}
protected override string Target => "news";
}
}

View File

@ -0,0 +1,15 @@
// 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.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.API.Requests
{
public class GetNewsResponse : ResponseWithCursor
{
[JsonProperty("news_posts")]
public IEnumerable<APINewsPost> NewsPosts;
}
}

View File

@ -11,17 +11,20 @@ namespace osu.Game.Online.Multiplayer
{ {
private readonly int roomId; private readonly int roomId;
private readonly int playlistItemId; private readonly int playlistItemId;
private readonly string versionHash;
public CreateRoomScoreRequest(int roomId, int playlistItemId) public CreateRoomScoreRequest(int roomId, int playlistItemId, string versionHash)
{ {
this.roomId = roomId; this.roomId = roomId;
this.playlistItemId = playlistItemId; this.playlistItemId = playlistItemId;
this.versionHash = versionHash;
} }
protected override WebRequest CreateWebRequest() protected override WebRequest CreateWebRequest()
{ {
var req = base.CreateWebRequest(); var req = base.CreateWebRequest();
req.Method = HttpMethod.Post; req.Method = HttpMethod.Post;
req.AddParameter("version_hash", versionHash);
return req; return req;
} }

View File

@ -1,29 +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.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API;
namespace osu.Game.Online.Multiplayer
{
public class GetRoomPlaylistScoresRequest : APIRequest<RoomPlaylistScores>
{
private readonly int roomId;
private readonly int playlistItemId;
public GetRoomPlaylistScoresRequest(int roomId, int playlistItemId)
{
this.roomId = roomId;
this.playlistItemId = playlistItemId;
}
protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores";
}
public class RoomPlaylistScores
{
[JsonProperty("scores")]
public List<MultiplayerScore> Scores { get; set; }
}
}

View File

@ -0,0 +1,59 @@
// 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.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.IO.Network;
using osu.Game.Extensions;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// Returns a list of scores for the specified playlist item.
/// </summary>
public class IndexPlaylistScoresRequest : APIRequest<IndexedMultiplayerScores>
{
public readonly int RoomId;
public readonly int PlaylistItemId;
[CanBeNull]
public readonly Cursor Cursor;
[CanBeNull]
public readonly IndexScoresParams IndexParams;
public IndexPlaylistScoresRequest(int roomId, int playlistItemId)
{
RoomId = roomId;
PlaylistItemId = playlistItemId;
}
public IndexPlaylistScoresRequest(int roomId, int playlistItemId, [NotNull] Cursor cursor, [NotNull] IndexScoresParams indexParams)
: this(roomId, playlistItemId)
{
Cursor = cursor;
IndexParams = indexParams;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
if (Cursor != null)
{
Debug.Assert(IndexParams != null);
req.AddCursor(Cursor);
foreach (var (key, value) in IndexParams.Properties)
req.AddParameter(key, value.ToString());
}
return req;
}
protected override string Target => $@"rooms/{RoomId}/playlist/{PlaylistItemId}/scores";
}
}

View File

@ -0,0 +1,20 @@
// 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.Collections.Generic;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// A collection of parameters which should be passed to the index endpoint to fetch the next page.
/// </summary>
public class IndexScoresParams
{
[UsedImplicitly]
[JsonExtensionData]
public IDictionary<string, JToken> Properties { get; set; } = new Dictionary<string, JToken>();
}
}

View File

@ -0,0 +1,27 @@
// 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 JetBrains.Annotations;
using Newtonsoft.Json;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// A <see cref="MultiplayerScores"/> object returned via a <see cref="IndexPlaylistScoresRequest"/>.
/// </summary>
public class IndexedMultiplayerScores : MultiplayerScores
{
/// <summary>
/// The total scores in the playlist item.
/// </summary>
[JsonProperty("total")]
public int? TotalScores { get; set; }
/// <summary>
/// The user's score, if any.
/// </summary>
[JsonProperty("user_score")]
[CanBeNull]
public MultiplayerScore UserScore { get; set; }
}
}

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using osu.Game.Online.API; using osu.Game.Online.API;
@ -47,6 +48,19 @@ namespace osu.Game.Online.Multiplayer
[JsonProperty("ended_at")] [JsonProperty("ended_at")]
public DateTimeOffset EndedAt { get; set; } public DateTimeOffset EndedAt { get; set; }
/// <summary>
/// The position of this score, starting at 1.
/// </summary>
[JsonProperty("position")]
public int? Position { get; set; }
/// <summary>
/// Any scores in the room around this score.
/// </summary>
[JsonProperty("scores_around")]
[CanBeNull]
public MultiplayerScoresAround ScoresAround { get; set; }
public ScoreInfo CreateScoreInfo(PlaylistItem playlistItem) public ScoreInfo CreateScoreInfo(PlaylistItem playlistItem)
{ {
var rulesetInstance = playlistItem.Ruleset.Value.CreateInstance(); var rulesetInstance = playlistItem.Ruleset.Value.CreateInstance();
@ -66,7 +80,8 @@ namespace osu.Game.Online.Multiplayer
Date = EndedAt, Date = EndedAt,
Hash = string.Empty, // todo: temporary? Hash = string.Empty, // todo: temporary?
Rank = Rank, Rank = Rank,
Mods = Mods?.Select(m => m.ToMod(rulesetInstance)).ToArray() ?? Array.Empty<Mod>() Mods = Mods?.Select(m => m.ToMod(rulesetInstance)).ToArray() ?? Array.Empty<Mod>(),
Position = Position,
}; };
return scoreInfo; return scoreInfo;

View File

@ -0,0 +1,27 @@
// 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.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API.Requests;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// An object which contains scores and related data for fetching next pages.
/// </summary>
public class MultiplayerScores : ResponseWithCursor
{
/// <summary>
/// The scores.
/// </summary>
[JsonProperty("scores")]
public List<MultiplayerScore> Scores { get; set; } = new List<MultiplayerScore>();
/// <summary>
/// The parameters to be used to fetch the next page.
/// </summary>
[JsonProperty("params")]
public IndexScoresParams Params { get; set; } = new IndexScoresParams();
}
}

View File

@ -0,0 +1,28 @@
// 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 JetBrains.Annotations;
using Newtonsoft.Json;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// An object which stores scores higher and lower than the user's score.
/// </summary>
public class MultiplayerScoresAround
{
/// <summary>
/// Scores sorted "higher" than the user's score, depending on the sorting order.
/// </summary>
[JsonProperty("higher")]
[CanBeNull]
public MultiplayerScores Higher { get; set; }
/// <summary>
/// Scores sorted "lower" than the user's score, depending on the sorting order.
/// </summary>
[JsonProperty("lower")]
[CanBeNull]
public MultiplayerScores Lower { get; set; }
}
}

View File

@ -0,0 +1,23 @@
// 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.Online.API;
namespace osu.Game.Online.Multiplayer
{
public class ShowPlaylistUserScoreRequest : APIRequest<MultiplayerScore>
{
private readonly int roomId;
private readonly int playlistItemId;
private readonly long userId;
public ShowPlaylistUserScoreRequest(int roomId, int playlistItemId, long userId)
{
this.roomId = roomId;
this.playlistItemId = playlistItemId;
this.userId = userId;
}
protected override string Target => $"rooms/{roomId}/playlist/{playlistItemId}/scores/users/{userId}";
}
}

View File

@ -67,12 +67,12 @@ namespace osu.Game
[NotNull] [NotNull]
private readonly NotificationOverlay notifications = new NotificationOverlay(); private readonly NotificationOverlay notifications = new NotificationOverlay();
private NowPlayingOverlay nowPlaying;
private BeatmapListingOverlay beatmapListing; private BeatmapListingOverlay beatmapListing;
private DashboardOverlay dashboard; private DashboardOverlay dashboard;
private NewsOverlay news;
private UserProfileOverlay userProfile; private UserProfileOverlay userProfile;
private BeatmapSetOverlay beatmapSetOverlay; private BeatmapSetOverlay beatmapSetOverlay;
@ -632,6 +632,7 @@ namespace osu.Game
// overlay elements // overlay elements
loadComponentSingleFile(beatmapListing = new BeatmapListingOverlay(), overlayContent.Add, true); loadComponentSingleFile(beatmapListing = new BeatmapListingOverlay(), overlayContent.Add, true);
loadComponentSingleFile(dashboard = new DashboardOverlay(), overlayContent.Add, true); loadComponentSingleFile(dashboard = new DashboardOverlay(), overlayContent.Add, true);
loadComponentSingleFile(news = new NewsOverlay(), overlayContent.Add, true);
var rankingsOverlay = loadComponentSingleFile(new RankingsOverlay(), overlayContent.Add, true); var rankingsOverlay = loadComponentSingleFile(new RankingsOverlay(), overlayContent.Add, true);
loadComponentSingleFile(channelManager = new ChannelManager(), AddInternal, true); loadComponentSingleFile(channelManager = new ChannelManager(), AddInternal, true);
loadComponentSingleFile(chatOverlay = new ChatOverlay(), overlayContent.Add, true); loadComponentSingleFile(chatOverlay = new ChatOverlay(), overlayContent.Add, true);
@ -647,7 +648,7 @@ namespace osu.Game
Origin = Anchor.TopRight, Origin = Anchor.TopRight,
}, rightFloatingOverlayContent.Add, true); }, rightFloatingOverlayContent.Add, true);
loadComponentSingleFile(nowPlaying = new NowPlayingOverlay loadComponentSingleFile(new NowPlayingOverlay
{ {
GetToolbarHeight = () => ToolbarOffset, GetToolbarHeight = () => ToolbarOffset,
Anchor = Anchor.TopRight, Anchor = Anchor.TopRight,
@ -682,14 +683,13 @@ namespace osu.Game
{ {
overlay.State.ValueChanged += state => overlay.State.ValueChanged += state =>
{ {
if (state.NewValue == Visibility.Hidden) return; if (state.NewValue != Visibility.Hidden)
showOverlayAboveOthers(overlay, informationalOverlays);
informationalOverlays.Where(o => o != overlay).ForEach(o => o.Hide());
}; };
} }
// ensure only one of these overlays are open at once. // ensure only one of these overlays are open at once.
var singleDisplayOverlays = new OverlayContainer[] { chatOverlay, dashboard, beatmapListing, changelogOverlay, rankingsOverlay }; var singleDisplayOverlays = new OverlayContainer[] { chatOverlay, news, dashboard, beatmapListing, changelogOverlay, rankingsOverlay };
foreach (var overlay in singleDisplayOverlays) foreach (var overlay in singleDisplayOverlays)
{ {
@ -698,9 +698,8 @@ namespace osu.Game
// informational overlays should be dismissed on a show or hide of a full overlay. // informational overlays should be dismissed on a show or hide of a full overlay.
informationalOverlays.ForEach(o => o.Hide()); informationalOverlays.ForEach(o => o.Hide());
if (state.NewValue == Visibility.Hidden) return; if (state.NewValue != Visibility.Hidden)
showOverlayAboveOthers(overlay, singleDisplayOverlays);
singleDisplayOverlays.Where(o => o != overlay).ForEach(o => o.Hide());
}; };
} }
@ -725,6 +724,15 @@ namespace osu.Game
notifications.State.ValueChanged += _ => updateScreenOffset(); notifications.State.ValueChanged += _ => updateScreenOffset();
} }
private void showOverlayAboveOthers(OverlayContainer overlay, OverlayContainer[] otherOverlays)
{
otherOverlays.Where(o => o != overlay).ForEach(o => o.Hide());
// show above others if not visible at all, else leave at current depth.
if (!overlay.IsPresent)
overlayContent.ChangeChildDepth(overlay, (float)-Clock.CurrentTime);
}
public class GameIdleTracker : IdleTracker public class GameIdleTracker : IdleTracker
{ {
private InputManager inputManager; private InputManager inputManager;
@ -859,18 +867,6 @@ namespace osu.Game
switch (action) switch (action)
{ {
case GlobalAction.ToggleNowPlaying:
nowPlaying.ToggleVisibility();
return true;
case GlobalAction.ToggleChat:
chatOverlay.ToggleVisibility();
return true;
case GlobalAction.ToggleSocial:
dashboard.ToggleVisibility();
return true;
case GlobalAction.ResetInputSettings: case GlobalAction.ResetInputSettings:
var sensitivity = frameworkConfig.GetBindable<double>(FrameworkSetting.CursorSensitivity); var sensitivity = frameworkConfig.GetBindable<double>(FrameworkSetting.CursorSensitivity);
@ -886,18 +882,6 @@ namespace osu.Game
Toolbar.ToggleVisibility(); Toolbar.ToggleVisibility();
return true; return true;
case GlobalAction.ToggleSettings:
Settings.ToggleVisibility();
return true;
case GlobalAction.ToggleDirect:
beatmapListing.ToggleVisibility();
return true;
case GlobalAction.ToggleNotifications:
notifications.ToggleVisibility();
return true;
case GlobalAction.ToggleGameplayMouseButtons: case GlobalAction.ToggleGameplayMouseButtons:
LocalConfig.Set(OsuSetting.MouseDisableButtons, !LocalConfig.Get<bool>(OsuSetting.MouseDisableButtons)); LocalConfig.Set(OsuSetting.MouseDisableButtons, !LocalConfig.Get<bool>(OsuSetting.MouseDisableButtons));
return true; return true;

View File

@ -11,6 +11,7 @@ using osu.Framework.Allocation;
using osu.Framework.Audio; using osu.Framework.Audio;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Development; using osu.Framework.Development;
using osu.Framework.Extensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.IO.Stores; using osu.Framework.IO.Stores;
@ -35,6 +36,7 @@ using osu.Game.Rulesets.Mods;
using osu.Game.Scoring; using osu.Game.Scoring;
using osu.Game.Skinning; using osu.Game.Skinning;
using osuTK.Input; using osuTK.Input;
using RuntimeInfo = osu.Framework.RuntimeInfo;
namespace osu.Game namespace osu.Game
{ {
@ -97,6 +99,11 @@ namespace osu.Game
public virtual Version AssemblyVersion => Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(); public virtual Version AssemblyVersion => Assembly.GetEntryAssembly()?.GetName().Version ?? new Version();
/// <summary>
/// MD5 representation of the game executable.
/// </summary>
public string VersionHash { get; private set; }
public bool IsDeployedBuild => AssemblyVersion.Major > 0; public bool IsDeployedBuild => AssemblyVersion.Major > 0;
public virtual string Version public virtual string Version
@ -128,6 +135,18 @@ namespace osu.Game
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {
try
{
using (var str = File.OpenRead(typeof(OsuGameBase).Assembly.Location))
VersionHash = str.ComputeMD5Hash();
}
catch
{
// special case for android builds, which can't read DLLs from a packed apk.
// should eventually be handled in a better way.
VersionHash = $"{Version}-{RuntimeInfo.OS}".ComputeMD5Hash();
}
Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly)); Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly));
dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage)); dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage));

View File

@ -5,12 +5,12 @@ using osu.Framework.Allocation;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events; using osu.Framework.Input.Events;
using osu.Game.Graphics; using osu.Game.Graphics;
using osu.Game.Graphics.Sprites; using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
using osuTK; using osuTK;
using static osu.Game.Graphics.UserInterface.ShowMoreButton;
namespace osu.Game.Overlays.Comments.Buttons namespace osu.Game.Overlays.Comments.Buttons
{ {
@ -25,7 +25,7 @@ namespace osu.Game.Overlays.Comments.Buttons
[Resolved] [Resolved]
private OverlayColourProvider colourProvider { get; set; } private OverlayColourProvider colourProvider { get; set; }
private readonly SpriteIcon icon; private readonly ChevronIcon icon;
private readonly Box background; private readonly Box background;
private readonly OsuSpriteText text; private readonly OsuSpriteText text;
@ -68,12 +68,10 @@ namespace osu.Game.Overlays.Comments.Buttons
AlwaysPresent = true, AlwaysPresent = true,
Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold) Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold)
}, },
icon = new SpriteIcon icon = new ChevronIcon
{ {
Anchor = Anchor.CentreLeft, Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft, Origin = Anchor.CentreLeft
Size = new Vector2(7.5f),
Icon = FontAwesome.Solid.ChevronDown
} }
} }
} }
@ -88,7 +86,6 @@ namespace osu.Game.Overlays.Comments.Buttons
private void load() private void load()
{ {
background.Colour = colourProvider.Background2; background.Colour = colourProvider.Background2;
icon.Colour = colourProvider.Foreground1;
} }
protected void SetIconDirection(bool upwards) => icon.ScaleTo(new Vector2(1, upwards ? -1 : 1)); protected void SetIconDirection(bool upwards) => icon.ScaleTo(new Vector2(1, upwards ? -1 : 1));
@ -99,7 +96,7 @@ namespace osu.Game.Overlays.Comments.Buttons
{ {
base.OnHover(e); base.OnHover(e);
background.FadeColour(colourProvider.Background1, 200, Easing.OutQuint); background.FadeColour(colourProvider.Background1, 200, Easing.OutQuint);
icon.FadeColour(colourProvider.Light1, 200, Easing.OutQuint); icon.SetHoveredState(true);
return true; return true;
} }
@ -107,7 +104,7 @@ namespace osu.Game.Overlays.Comments.Buttons
{ {
base.OnHoverLost(e); base.OnHoverLost(e);
background.FadeColour(colourProvider.Background2, 200, Easing.OutQuint); background.FadeColour(colourProvider.Background2, 200, Easing.OutQuint);
icon.FadeColour(colourProvider.Foreground1, 200, Easing.OutQuint); icon.SetHoveredState(false);
} }
} }
} }

View File

@ -12,13 +12,13 @@ using osu.Framework.Allocation;
namespace osu.Game.Overlays.Comments.Buttons namespace osu.Game.Overlays.Comments.Buttons
{ {
public class ShowMoreButton : LoadingButton public class ShowMoreRepliesButton : LoadingButton
{ {
protected override IEnumerable<Drawable> EffectTargets => new[] { text }; protected override IEnumerable<Drawable> EffectTargets => new[] { text };
private OsuSpriteText text; private OsuSpriteText text;
public ShowMoreButton() public ShowMoreRepliesButton()
{ {
AutoSizeAxes = Axes.Both; AutoSizeAxes = Axes.Both;
LoadingAnimationSize = new Vector2(8); LoadingAnimationSize = new Vector2(8);

View File

@ -1,7 +1,6 @@
// 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.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
@ -11,16 +10,6 @@ namespace osu.Game.Overlays.Comments
{ {
public readonly BindableInt Current = new BindableInt(); public readonly BindableInt Current = new BindableInt();
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
Height = 20;
IdleColour = colourProvider.Background2;
HoverColour = colourProvider.Background1;
ChevronIconColour = colourProvider.Foreground1;
}
protected override void LoadComplete() protected override void LoadComplete()
{ {
Current.BindValueChanged(onCurrentChanged, true); Current.BindValueChanged(onCurrentChanged, true);

View File

@ -46,7 +46,7 @@ namespace osu.Game.Overlays.Comments
private FillFlowContainer childCommentsVisibilityContainer; private FillFlowContainer childCommentsVisibilityContainer;
private FillFlowContainer childCommentsContainer; private FillFlowContainer childCommentsContainer;
private LoadRepliesButton loadRepliesButton; private LoadRepliesButton loadRepliesButton;
private ShowMoreButton showMoreButton; private ShowMoreRepliesButton showMoreButton;
private ShowRepliesButton showRepliesButton; private ShowRepliesButton showRepliesButton;
private ChevronButton chevronButton; private ChevronButton chevronButton;
private DeletedCommentsCounter deletedCommentsCounter; private DeletedCommentsCounter deletedCommentsCounter;
@ -213,7 +213,7 @@ namespace osu.Game.Overlays.Comments
Top = 10 Top = 10
} }
}, },
showMoreButton = new ShowMoreButton showMoreButton = new ShowMoreRepliesButton
{ {
Action = () => RepliesRequested(this, ++currentPage) Action = () => RepliesRequested(this, ++currentPage)
} }

View File

@ -0,0 +1,43 @@
// 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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osuTK;
namespace osu.Game.Overlays.Dashboard.Home
{
public class DashboardBeatmapListing : CompositeDrawable
{
private readonly List<BeatmapSetInfo> newBeatmaps;
private readonly List<BeatmapSetInfo> popularBeatmaps;
public DashboardBeatmapListing(List<BeatmapSetInfo> newBeatmaps, List<BeatmapSetInfo> popularBeatmaps)
{
this.newBeatmaps = newBeatmaps;
this.popularBeatmaps = popularBeatmaps;
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = new FillFlowContainer<DrawableBeatmapList>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = new DrawableBeatmapList[]
{
new DrawableNewBeatmapList(newBeatmaps),
new DrawablePopularBeatmapList(popularBeatmaps)
}
};
}
}
}

View File

@ -0,0 +1,168 @@
// 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osuTK;
namespace osu.Game.Overlays.Dashboard.Home
{
public abstract class DashboardBeatmapPanel : OsuClickableContainer
{
[Resolved]
protected OverlayColourProvider ColourProvider { get; private set; }
[Resolved(canBeNull: true)]
private BeatmapSetOverlay beatmapOverlay { get; set; }
protected readonly BeatmapSetInfo SetInfo;
private Box hoverBackground;
private SpriteIcon chevron;
protected DashboardBeatmapPanel(BeatmapSetInfo setInfo)
{
SetInfo = setInfo;
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
Height = 60;
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Horizontal = -10 },
Child = hoverBackground = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourProvider.Background3,
Alpha = 0
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Absolute, 70),
new Dimension(),
new Dimension(GridSizeMode.AutoSize)
},
RowDimensions = new[]
{
new Dimension()
},
Content = new[]
{
new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
CornerRadius = 6,
Child = new UpdateableBeatmapSetCover
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
BeatmapSet = SetInfo
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Horizontal = 10 },
Child = new FillFlowContainer
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new OsuSpriteText
{
RelativeSizeAxes = Axes.X,
Truncate = true,
Font = OsuFont.GetFont(weight: FontWeight.Regular),
Text = SetInfo.Metadata.Title
},
new OsuSpriteText
{
RelativeSizeAxes = Axes.X,
Truncate = true,
Font = OsuFont.GetFont(size: 12, weight: FontWeight.Regular),
Text = SetInfo.Metadata.Artist
},
new LinkFlowContainer(f => f.Font = OsuFont.GetFont(size: 10, weight: FontWeight.Regular))
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Spacing = new Vector2(3),
Margin = new MarginPadding { Top = 2 }
}.With(c =>
{
c.AddText("by");
c.AddUserLink(SetInfo.Metadata.Author);
c.AddArbitraryDrawable(CreateInfo());
})
}
}
},
chevron = new SpriteIcon
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
Size = new Vector2(16),
Icon = FontAwesome.Solid.ChevronRight,
Colour = ColourProvider.Foreground1
}
}
}
}
}
};
Action = () =>
{
if (SetInfo.OnlineBeatmapSetID.HasValue)
beatmapOverlay?.FetchAndShowBeatmapSet(SetInfo.OnlineBeatmapSetID.Value);
};
}
protected abstract Drawable CreateInfo();
protected override bool OnHover(HoverEvent e)
{
base.OnHover(e);
hoverBackground.FadeIn(200, Easing.OutQuint);
chevron.FadeColour(ColourProvider.Light1, 200, Easing.OutQuint);
return true;
}
protected override void OnHoverLost(HoverLostEvent e)
{
base.OnHoverLost(e);
hoverBackground.FadeOut(200, Easing.OutQuint);
chevron.FadeColour(ColourProvider.Foreground1, 200, Easing.OutQuint);
}
}
}

View File

@ -0,0 +1,23 @@
// 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 osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
namespace osu.Game.Overlays.Dashboard.Home
{
public class DashboardNewBeatmapPanel : DashboardBeatmapPanel
{
public DashboardNewBeatmapPanel(BeatmapSetInfo setInfo)
: base(setInfo)
{
}
protected override Drawable CreateInfo() => new DrawableDate(SetInfo.OnlineInfo.Ranked ?? DateTimeOffset.Now, 10, false)
{
Colour = ColourProvider.Foreground1
};
}
}

View File

@ -0,0 +1,42 @@
// 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.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK;
namespace osu.Game.Overlays.Dashboard.Home
{
public class DashboardPopularBeatmapPanel : DashboardBeatmapPanel
{
public DashboardPopularBeatmapPanel(BeatmapSetInfo setInfo)
: base(setInfo)
{
}
protected override Drawable CreateInfo() => new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(3, 0),
Colour = ColourProvider.Foreground1,
Children = new Drawable[]
{
new SpriteIcon
{
Size = new Vector2(10),
Icon = FontAwesome.Solid.Heart
},
new OsuSpriteText
{
Font = OsuFont.GetFont(size: 10, weight: FontWeight.Regular),
Text = SetInfo.OnlineInfo.FavouriteCount.ToString()
}
}
};
}
}

View File

@ -0,0 +1,56 @@
// 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.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK;
namespace osu.Game.Overlays.Dashboard.Home
{
public abstract class DrawableBeatmapList : CompositeDrawable
{
private readonly List<BeatmapSetInfo> beatmaps;
protected DrawableBeatmapList(List<BeatmapSetInfo> beatmaps)
{
this.beatmaps = beatmaps;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
FillFlowContainer flow;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = flow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = new Drawable[]
{
new OsuSpriteText
{
Font = OsuFont.GetFont(size: 16, weight: FontWeight.Bold),
Colour = colourProvider.Light1,
Text = Title
}
}
};
flow.AddRange(beatmaps.Select(CreateBeatmapPanel));
}
protected abstract string Title { get; }
protected abstract DashboardBeatmapPanel CreateBeatmapPanel(BeatmapSetInfo setInfo);
}
}

View File

@ -0,0 +1,20 @@
// 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.Collections.Generic;
using osu.Game.Beatmaps;
namespace osu.Game.Overlays.Dashboard.Home
{
public class DrawableNewBeatmapList : DrawableBeatmapList
{
public DrawableNewBeatmapList(List<BeatmapSetInfo> beatmaps)
: base(beatmaps)
{
}
protected override DashboardBeatmapPanel CreateBeatmapPanel(BeatmapSetInfo setInfo) => new DashboardNewBeatmapPanel(setInfo);
protected override string Title => "New Ranked Beatmaps";
}
}

View File

@ -0,0 +1,20 @@
// 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.Collections.Generic;
using osu.Game.Beatmaps;
namespace osu.Game.Overlays.Dashboard.Home
{
public class DrawablePopularBeatmapList : DrawableBeatmapList
{
public DrawablePopularBeatmapList(List<BeatmapSetInfo> beatmaps)
: base(beatmaps)
{
}
protected override DashboardBeatmapPanel CreateBeatmapPanel(BeatmapSetInfo setInfo) => new DashboardPopularBeatmapPanel(setInfo);
protected override string Title => "Popular Beatmaps";
}
}

View File

@ -19,7 +19,6 @@ namespace osu.Game.Overlays
{ {
private CancellationTokenSource cancellationToken; private CancellationTokenSource cancellationToken;
private Box background;
private Container content; private Container content;
private DashboardOverlayHeader header; private DashboardOverlayHeader header;
private LoadingLayer loading; private LoadingLayer loading;
@ -35,9 +34,10 @@ namespace osu.Game.Overlays
{ {
Children = new Drawable[] Children = new Drawable[]
{ {
background = new Box new Box
{ {
RelativeSizeAxes = Axes.Both RelativeSizeAxes = Axes.Both,
Colour = ColourProvider.Background5
}, },
scrollFlow = new OverlayScrollContainer scrollFlow = new OverlayScrollContainer
{ {
@ -66,8 +66,6 @@ namespace osu.Game.Overlays
}, },
loading = new LoadingLayer(content), loading = new LoadingLayer(content),
}; };
background.Colour = ColourProvider.Background5;
} }
protected override void LoadComplete() protected override void LoadComplete()

View File

@ -48,8 +48,7 @@ namespace osu.Game.Overlays.KeyBinding
public bool FilteringActive { get; set; } public bool FilteringActive { get; set; }
private OsuSpriteText text; private OsuSpriteText text;
private Drawable pressAKey; private FillFlowContainer cancelAndClearButtons;
private FillFlowContainer<KeyButton> buttons; private FillFlowContainer<KeyButton> buttons;
public IEnumerable<string> FilterTerms => bindings.Select(b => b.KeyCombination.ReadableString()).Prepend((string)text.Text); public IEnumerable<string> FilterTerms => bindings.Select(b => b.KeyCombination.ReadableString()).Prepend((string)text.Text);
@ -80,7 +79,7 @@ namespace osu.Game.Overlays.KeyBinding
Hollow = true, Hollow = true,
}; };
Children = new[] Children = new Drawable[]
{ {
new Box new Box
{ {
@ -99,7 +98,7 @@ namespace osu.Game.Overlays.KeyBinding
Anchor = Anchor.TopRight, Anchor = Anchor.TopRight,
Origin = Anchor.TopRight Origin = Anchor.TopRight
}, },
pressAKey = new FillFlowContainer cancelAndClearButtons = new FillFlowContainer
{ {
AutoSizeAxes = Axes.Both, AutoSizeAxes = Axes.Both,
Padding = new MarginPadding(padding) { Top = height + padding * 2 }, Padding = new MarginPadding(padding) { Top = height + padding * 2 },
@ -187,7 +186,8 @@ namespace osu.Game.Overlays.KeyBinding
if (bindTarget.IsHovered) if (bindTarget.IsHovered)
finalise(); finalise();
else // prevent updating bind target before clear button's action
else if (!cancelAndClearButtons.Any(b => b.IsHovered))
updateBindTarget(); updateBindTarget();
} }
@ -298,8 +298,8 @@ namespace osu.Game.Overlays.KeyBinding
if (HasFocus) if (HasFocus)
GetContainingInputManager().ChangeFocus(null); GetContainingInputManager().ChangeFocus(null);
pressAKey.FadeOut(300, Easing.OutQuint); cancelAndClearButtons.FadeOut(300, Easing.OutQuint);
pressAKey.BypassAutoSizeAxes |= Axes.Y; cancelAndClearButtons.BypassAutoSizeAxes |= Axes.Y;
} }
protected override void OnFocus(FocusEvent e) protected override void OnFocus(FocusEvent e)
@ -307,8 +307,8 @@ namespace osu.Game.Overlays.KeyBinding
AutoSizeDuration = 500; AutoSizeDuration = 500;
AutoSizeEasing = Easing.OutQuint; AutoSizeEasing = Easing.OutQuint;
pressAKey.FadeIn(300, Easing.OutQuint); cancelAndClearButtons.FadeIn(300, Easing.OutQuint);
pressAKey.BypassAutoSizeAxes &= ~Axes.Y; cancelAndClearButtons.BypassAutoSizeAxes &= ~Axes.Y;
updateBindTarget(); updateBindTarget();
base.OnFocus(e); base.OnFocus(e);
@ -320,6 +320,9 @@ namespace osu.Game.Overlays.KeyBinding
base.OnFocusLost(e); base.OnFocusLost(e);
} }
/// <summary>
/// Updates the bind target to the currently hovered key button or the first if clicked anywhere else.
/// </summary>
private void updateBindTarget() private void updateBindTarget()
{ {
if (bindTarget != null) bindTarget.IsBinding = false; if (bindTarget != null) bindTarget.IsBinding = false;
@ -354,7 +357,7 @@ namespace osu.Game.Overlays.KeyBinding
} }
} }
private class KeyButton : Container public class KeyButton : Container
{ {
public readonly Framework.Input.Bindings.KeyBinding KeyBinding; public readonly Framework.Input.Bindings.KeyBinding KeyBinding;

View File

@ -236,8 +236,8 @@ namespace osu.Game.Overlays
{ {
if (beatmap is Bindable<WorkingBeatmap> working) if (beatmap is Bindable<WorkingBeatmap> working)
working.Value = beatmaps.GetWorkingBeatmap(playable.Beatmaps.First(), beatmap.Value); working.Value = beatmaps.GetWorkingBeatmap(playable.Beatmaps.First(), beatmap.Value);
beatmap.Value.Track.Restart();
restartTrack();
return PreviousTrackResult.Previous; return PreviousTrackResult.Previous;
} }
@ -262,13 +262,21 @@ namespace osu.Game.Overlays
{ {
if (beatmap is Bindable<WorkingBeatmap> working) if (beatmap is Bindable<WorkingBeatmap> working)
working.Value = beatmaps.GetWorkingBeatmap(playable.Beatmaps.First(), beatmap.Value); working.Value = beatmaps.GetWorkingBeatmap(playable.Beatmaps.First(), beatmap.Value);
beatmap.Value.Track.Restart();
restartTrack();
return true; return true;
} }
return false; return false;
} }
private void restartTrack()
{
// if not scheduled, the previously track will be stopped one frame later (see ScheduleAfterChildren logic in GameBase).
// we probably want to move this to a central method for switching to a new working beatmap in the future.
Schedule(() => beatmap.Value.Track.Restart());
}
private WorkingBeatmap current; private WorkingBeatmap current;
private TrackChangeDirection? queuedDirection; private TrackChangeDirection? queuedDirection;

View File

@ -0,0 +1,114 @@
// 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.Linq;
using System.Threading;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osuTK;
namespace osu.Game.Overlays.News.Displays
{
public class FrontPageDisplay : CompositeDrawable
{
[Resolved]
private IAPIProvider api { get; set; }
private FillFlowContainer content;
private ShowMoreButton showMore;
private GetNewsRequest request;
private Cursor lastCursor;
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Padding = new MarginPadding
{
Vertical = 20,
Left = 30,
Right = 50
};
InternalChild = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = new Drawable[]
{
content = new FillFlowContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10)
},
showMore = new ShowMoreButton
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Margin = new MarginPadding
{
Top = 15
},
Action = performFetch,
Alpha = 0
}
}
};
performFetch();
}
private void performFetch()
{
request?.Cancel();
request = new GetNewsRequest(lastCursor);
request.Success += response => Schedule(() => onSuccess(response));
api.PerformAsync(request);
}
private CancellationTokenSource cancellationToken;
private void onSuccess(GetNewsResponse response)
{
cancellationToken?.Cancel();
lastCursor = response.Cursor;
var flow = new FillFlowContainer<NewsCard>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = response.NewsPosts.Select(p => new NewsCard(p)).ToList()
};
LoadComponentAsync(flow, loaded =>
{
content.Add(loaded);
showMore.IsLoading = false;
showMore.Show();
}, (cancellationToken = new CancellationTokenSource()).Token);
}
protected override void Dispose(bool isDisposing)
{
request?.Cancel();
cancellationToken?.Cancel();
base.Dispose(isDisposing);
}
}
}

View File

@ -1,174 +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 osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
namespace osu.Game.Overlays.News
{
public class NewsArticleCover : Container
{
private const int hover_duration = 300;
private readonly Box gradient;
public NewsArticleCover(ArticleInfo info)
{
RelativeSizeAxes = Axes.X;
Masking = true;
CornerRadius = 4;
NewsBackground bg;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.2f), OsuColour.Gray(0.1f))
},
new DelayedLoadWrapper(bg = new NewsBackground(info.CoverUrl)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fill,
Alpha = 0
})
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
},
gradient = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(Color4.Black.Opacity(0.1f), Color4.Black.Opacity(0.7f)),
Alpha = 0
},
new DateContainer(info.Time)
{
Margin = new MarginPadding
{
Right = 20,
Top = 20,
}
},
new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Margin = new MarginPadding
{
Left = 25,
Bottom = 50,
},
Font = OsuFont.GetFont(Typeface.Torus, 24, FontWeight.Bold),
Text = info.Title,
},
new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Margin = new MarginPadding
{
Left = 25,
Bottom = 30,
},
Font = OsuFont.GetFont(Typeface.Torus, 16, FontWeight.Bold),
Text = "by " + info.Author
}
};
bg.OnLoadComplete += d => d.FadeIn(250, Easing.In);
}
protected override bool OnHover(HoverEvent e)
{
gradient.FadeIn(hover_duration, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
base.OnHoverLost(e);
gradient.FadeOut(hover_duration, Easing.OutQuint);
}
[LongRunningLoad]
private class NewsBackground : Sprite
{
private readonly string url;
public NewsBackground(string coverUrl)
{
url = coverUrl ?? "Headers/news";
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore store)
{
Texture = store.Get(url);
}
}
private class DateContainer : Container, IHasTooltip
{
private readonly DateTime date;
public DateContainer(DateTime date)
{
this.date = date;
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Masking = true;
CornerRadius = 4;
AutoSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(0.5f),
},
new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.GetFont(Typeface.Torus, 12, FontWeight.Bold, false, false),
Text = date.ToString("d MMM yyy").ToUpper(),
Margin = new MarginPadding
{
Vertical = 4,
Horizontal = 8,
}
}
};
}
public string TooltipText => date.ToString("dddd dd MMMM yyyy hh:mm:ss UTCz").ToUpper();
}
// fake API data struct to use for now as a skeleton for data, as there is no API struct for news article info for now
public class ArticleInfo
{
public string Title { get; set; }
public string CoverUrl { get; set; }
public DateTime Time { get; set; }
public string Author { get; set; }
}
}
}

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 osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
@ -11,17 +12,17 @@ using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Textures;
using osu.Framework.Input.Events; using osu.Framework.Input.Events;
using osu.Framework.Platform;
using osu.Game.Graphics; using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites; using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Overlays.News namespace osu.Game.Overlays.News
{ {
public class NewsCard : CompositeDrawable public class NewsCard : OsuHoverContainer
{ {
[Resolved] protected override IEnumerable<Drawable> EffectTargets => new[] { background };
private OverlayColourProvider colourProvider { get; set; }
private readonly APINewsPost post; private readonly APINewsPost post;
@ -31,24 +32,28 @@ namespace osu.Game.Overlays.News
public NewsCard(APINewsPost post) public NewsCard(APINewsPost post)
{ {
this.post = post; this.post = post;
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.X; RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y; AutoSizeAxes = Axes.Y;
Masking = true; Masking = true;
CornerRadius = 6; CornerRadius = 6;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider, GameHost host)
{
if (post.Slug != null)
{
TooltipText = "view in browser";
Action = () => host.OpenUrlExternally("https://osu.ppy.sh/home/news/" + post.Slug);
}
NewsBackground bg; NewsBackground bg;
AddRange(new Drawable[]
InternalChildren = new Drawable[]
{ {
background = new Box background = new Box
{ {
RelativeSizeAxes = Axes.Both, RelativeSizeAxes = Axes.Both
Colour = colourProvider.Background4
}, },
new FillFlowContainer new FillFlowContainer
{ {
@ -104,9 +109,11 @@ namespace osu.Game.Overlays.News
} }
} }
} }
}, }
new HoverClickSounds() });
};
IdleColour = colourProvider.Background4;
HoverColour = colourProvider.Background3;
bg.OnLoadComplete += d => d.FadeIn(250, Easing.In); bg.OnLoadComplete += d => d.FadeIn(250, Easing.In);
@ -116,18 +123,6 @@ namespace osu.Game.Overlays.News
main.AddText(post.Author, t => t.Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold)); main.AddText(post.Author, t => t.Font = OsuFont.GetFont(size: 12, weight: FontWeight.SemiBold));
} }
protected override bool OnHover(HoverEvent e)
{
background.FadeColour(colourProvider.Background3, 200, Easing.OutQuint);
return true;
}
protected override void OnHoverLost(HoverLostEvent e)
{
background.FadeColour(colourProvider.Background4, 200, Easing.OutQuint);
base.OnHoverLost(e);
}
[LongRunningLoad] [LongRunningLoad]
private class NewsBackground : Sprite private class NewsBackground : Sprite
{ {
@ -193,6 +188,8 @@ namespace osu.Game.Overlays.News
} }
}; };
} }
protected override bool OnClick(ClickEvent e) => true; // Protects the NewsCard from clicks while hovering DateContainer
} }
} }
} }

View File

@ -1,19 +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;
namespace osu.Game.Overlays.News
{
public abstract class NewsContent : FillFlowContainer
{
protected NewsContent()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Direction = FillDirection.Vertical;
Padding = new MarginPadding { Bottom = 100, Top = 20, Horizontal = 50 };
}
}
}

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