// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics.Cursor; using osu.Game.Input.Handlers; using osu.Game.Overlays; using osu.Game.Replays; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Screens.Play.HUD.ClicksPerSecond; using osuTK; namespace osu.Game.Rulesets.UI { /// /// Displays an interactive ruleset gameplay instance. /// /// The type of HitObject contained by this DrawableRuleset. public abstract partial class DrawableRuleset : DrawableRuleset, IProvideCursor, ICanAttachHUDPieces where TObject : HitObject { public override event Action NewResult; public override event Action RevertResult; /// /// The selected variant. /// public virtual int Variant => 0; /// /// The key conversion input manager for this DrawableRuleset. /// protected PassThroughInputManager KeyBindingInputManager; public override double GameplayStartTime => Objects.FirstOrDefault()?.StartTime - 2000 ?? 0; private readonly Lazy playfield; /// /// The playfield. /// public override Playfield Playfield => playfield.Value; public override Container Overlays { get; } = new Container { RelativeSizeAxes = Axes.Both }; public override IAdjustableAudioComponent Audio => audioContainer; private readonly AudioContainer audioContainer = new AudioContainer { RelativeSizeAxes = Axes.Both }; /// /// A container which encapsulates the and provides any adjustments to /// ensure correct scale and position. /// public virtual PlayfieldAdjustmentContainer PlayfieldAdjustmentContainer { get; private set; } public override Container FrameStableComponents { get; } = new Container { RelativeSizeAxes = Axes.Both }; public override IFrameStableClock FrameStableClock => frameStabilityContainer; private bool allowBackwardsSeeks; public override bool AllowBackwardsSeeks { get => allowBackwardsSeeks; set { allowBackwardsSeeks = value; if (frameStabilityContainer != null) frameStabilityContainer.AllowBackwardsSeeks = value; } } private bool frameStablePlayback = true; internal override bool FrameStablePlayback { get => frameStablePlayback; set { frameStablePlayback = value; if (frameStabilityContainer != null) frameStabilityContainer.FrameStablePlayback = value; } } /// /// The beatmap. /// [Cached(typeof(IBeatmap))] public readonly Beatmap Beatmap; public override IEnumerable Objects => Beatmap.HitObjects; protected IRulesetConfigManager Config { get; private set; } [Cached(typeof(IReadOnlyList))] public sealed override IReadOnlyList Mods { get; } private FrameStabilityContainer frameStabilityContainer; private OnScreenDisplay onScreenDisplay; private DrawableRulesetDependencies dependencies; /// /// Creates a ruleset visualisation for the provided ruleset and beatmap. /// /// The ruleset being represented. /// The beatmap to create the hit renderer for. /// The s to apply. protected DrawableRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList mods = null) : base(ruleset) { ArgumentNullException.ThrowIfNull(beatmap); if (!(beatmap is Beatmap tBeatmap)) throw new ArgumentException($"{GetType()} expected the beatmap to contain hitobjects of type {typeof(TObject)}.", nameof(beatmap)); Beatmap = tBeatmap; Mods = mods?.ToArray() ?? Array.Empty(); RelativeSizeAxes = Axes.Both; KeyBindingInputManager = CreateInputManager(); playfield = new Lazy(() => CreatePlayfield().With(p => { p.NewResult += (_, r) => NewResult?.Invoke(r); p.RevertResult += r => RevertResult?.Invoke(r); })); } protected override void LoadComplete() { base.LoadComplete(); IsPaused.ValueChanged += paused => { if (HasReplayLoaded.Value) return; KeyBindingInputManager.UseParentInput = !paused.NewValue; }; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new DrawableRulesetDependencies(Ruleset, base.CreateChildDependencies(parent)); Config = dependencies.RulesetConfigManager; onScreenDisplay = dependencies.Get(); if (Config != null) onScreenDisplay?.BeginTracking(this, Config); return dependencies; } public virtual PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new PlayfieldAdjustmentContainer(); [Resolved] private OsuConfigManager config { get; set; } [BackgroundDependencyLoader] private void load(CancellationToken? cancellationToken) { InternalChild = frameStabilityContainer = new FrameStabilityContainer(GameplayStartTime) { FrameStablePlayback = FrameStablePlayback, AllowBackwardsSeeks = AllowBackwardsSeeks, Children = new Drawable[] { FrameStableComponents, audioContainer.WithChild(KeyBindingInputManager .WithChildren(new Drawable[] { PlayfieldAdjustmentContainer = CreatePlayfieldAdjustmentContainer() .WithChild(Playfield), Overlays })), } }; if ((ResumeOverlay = CreateResumeOverlay()) != null) { AddInternal(CreateInputManager() .WithChild(CreatePlayfieldAdjustmentContainer() .WithChild(ResumeOverlay))); } applyRulesetMods(Mods, config); loadObjects(cancellationToken ?? default); } /// /// Creates and adds drawable representations of hit objects to the play field. /// private void loadObjects(CancellationToken cancellationToken) { foreach (TObject h in Beatmap.HitObjects) { cancellationToken.ThrowIfCancellationRequested(); AddHitObject(h); } cancellationToken.ThrowIfCancellationRequested(); Playfield.PostProcess(); foreach (var mod in Mods.OfType()) { foreach (var drawableHitObject in Playfield.AllHitObjects) mod.ApplyToDrawableHitObject(drawableHitObject); } } public override void RequestResume(Action continueResume) { if (ResumeOverlay != null && UseResumeOverlay) { ResumeOverlay.GameplayCursor = Cursor; ResumeOverlay.ResumeAction = continueResume; ResumeOverlay.Show(); } else continueResume(); } public override void CancelResume() { // called if the user pauses while the resume overlay is open ResumeOverlay?.Hide(); } /// /// Adds a to this . /// /// /// This does not add the to the beatmap. /// /// The to add. public void AddHitObject(TObject hitObject) { var drawableRepresentation = CreateDrawableRepresentation(hitObject); // If a drawable representation exists, use it, otherwise assume the hitobject is being pooled. if (drawableRepresentation != null) Playfield.Add(drawableRepresentation); else Playfield.Add(hitObject); } /// /// Removes a from this . /// /// /// This does not remove the from the beatmap. /// /// The to remove. public bool RemoveHitObject(TObject hitObject) { if (Playfield.Remove(hitObject)) return true; // If the entry was not removed from the playfield, assume the hitobject is not being pooled and attempt a direct drawable removal. var drawableObject = Playfield.AllHitObjects.SingleOrDefault(d => d.HitObject == hitObject); if (drawableObject != null) return Playfield.Remove(drawableObject); return false; } public sealed override void SetRecordTarget(Score score) { if (!(KeyBindingInputManager is IHasRecordingHandler recordingInputManager)) throw new InvalidOperationException($"A {nameof(KeyBindingInputManager)} which supports recording is not available"); if (score == null) { recordingInputManager.Recorder = null; return; } var recorder = CreateReplayRecorder(score); if (recorder == null) return; recorder.ScreenSpaceToGamefield = Playfield.ScreenSpaceToGamefield; recordingInputManager.Recorder = recorder; } public override void SetReplayScore(Score replayScore) { if (!(KeyBindingInputManager is IHasReplayHandler replayInputManager)) throw new InvalidOperationException($"A {nameof(KeyBindingInputManager)} which supports replay loading is not available"); var handler = (ReplayScore = replayScore) != null ? CreateReplayInputHandler(replayScore.Replay) : null; replayInputManager.ReplayInputHandler = handler; frameStabilityContainer.ReplayInputHandler = handler; HasReplayLoaded.Value = replayInputManager.ReplayInputHandler != null; if (replayInputManager.ReplayInputHandler != null) replayInputManager.ReplayInputHandler.GamefieldToScreenSpace = Playfield.GamefieldToScreenSpace; if (!ProvidingUserCursor) { // The cursor is hidden by default (see Playfield.load()), but should be shown when there's a replay Playfield.Cursor?.Show(); } } /// /// Creates a to represent a . /// /// /// If this method returns null, then this will assume the requested type is being pooled inside the , /// and will instead attempt to retrieve the s at the point they should become alive via pools registered in the . /// /// The to represent. /// The representing . public abstract DrawableHitObject CreateDrawableRepresentation(TObject h); public void Attach(InputCountController inputCountController) => (KeyBindingInputManager as ICanAttachHUDPieces)?.Attach(inputCountController); public void Attach(ClicksPerSecondController controller) => (KeyBindingInputManager as ICanAttachHUDPieces)?.Attach(controller); /// /// Creates a key conversion input manager. An exception will be thrown if a valid is not returned. /// /// The input manager. protected abstract PassThroughInputManager CreateInputManager(); protected virtual ReplayInputHandler CreateReplayInputHandler(Replay replay) => null; protected virtual ReplayRecorder CreateReplayRecorder(Score score) => null; /// /// Creates a Playfield. /// /// The Playfield. protected abstract Playfield CreatePlayfield(); /// /// Applies the active mods to this DrawableRuleset. /// /// The s to apply. /// The to apply. private void applyRulesetMods(IReadOnlyList mods, OsuConfigManager config) { if (mods == null) return; foreach (var mod in mods.OfType>()) mod.ApplyToDrawableRuleset(this); foreach (var mod in mods.OfType()) mod.ReadFromConfig(config); } #region IProvideCursor protected override bool OnHover(HoverEvent e) => true; // required for IProvideCursor // only show the cursor when within the playfield, by default. public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Playfield.ReceivePositionalInputAt(screenSpacePos); CursorContainer IProvideCursor.Cursor => Playfield.Cursor; public override GameplayCursorContainer Cursor => Playfield.Cursor; public bool ProvidingUserCursor => Playfield.Cursor != null && !HasReplayLoaded.Value; #endregion protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (Config != null) { onScreenDisplay?.StopTracking(this, Config); Config = null; } // Dispose the components created by this dependency container. dependencies?.Dispose(); } } /// /// Displays an interactive ruleset gameplay instance. /// /// This type is required only for adding non-generic type to the draw hierarchy. /// /// [Cached(typeof(DrawableRuleset))] public abstract partial class DrawableRuleset : CompositeDrawable { /// /// Invoked when a has been applied by a . /// public abstract event Action NewResult; /// /// Invoked when a is being reverted by a . /// public abstract event Action RevertResult; /// /// Whether a replay is currently loaded. /// public readonly BindableBool HasReplayLoaded = new BindableBool(); /// /// Whether the game is paused. Used to block user input. /// public readonly BindableBool IsPaused = new BindableBool(); /// /// Audio adjustments which are applied to the playfield. /// public abstract IAdjustableAudioComponent Audio { get; } /// /// The playfield. /// public abstract Playfield Playfield { get; } /// /// Content to be placed above hitobjects. Will be affected by frame stability and adjustments applied to . /// public abstract Container Overlays { get; } /// /// Components to be run potentially multiple times in line with frame-stable gameplay. /// public abstract Container FrameStableComponents { get; } /// /// The frame-stable clock which is being used for playfield display. /// public abstract IFrameStableClock FrameStableClock { get; } /// /// Whether to enable frame-stable playback. /// internal abstract bool FrameStablePlayback { get; set; } /// /// When a replay is not attached, we usually block any backwards seeks. /// This will bypass the check. Should only be used for tests. /// public abstract bool AllowBackwardsSeeks { get; set; } /// /// The mods which are to be applied. /// public abstract IReadOnlyList Mods { get; } /// ~ /// The associated ruleset. /// public readonly Ruleset Ruleset; /// /// Creates a ruleset visualisation for the provided ruleset. /// /// The ruleset. internal DrawableRuleset(Ruleset ruleset) { Ruleset = ruleset; } /// /// All the converted hit objects contained by this hit renderer. /// public abstract IEnumerable Objects { get; } /// /// The point in time at which gameplay starts, including any required lead-in for display purposes. /// Defaults to two seconds before the first . Override as necessary. /// public abstract double GameplayStartTime { get; } /// /// The currently loaded replay. Usually null in the case of a local player. /// public Score ReplayScore { get; protected set; } /// /// The cursor being displayed by the . May be null if no cursor is provided. /// [CanBeNull] public abstract GameplayCursorContainer Cursor { get; } /// /// An optional overlay used when resuming gameplay from a paused state. /// public ResumeOverlay ResumeOverlay { get; protected set; } /// /// Whether a should be displayed on resuming after a pause. /// /// /// Defaults to true. /// Even if true, will not have any effect if the ruleset does not have a resume overlay (see ). /// public bool UseResumeOverlay { get; set; } = true; /// /// Returns first available provided by a . /// [CanBeNull] public HitWindows FirstAvailableHitWindows { get { foreach (var hitObject in Objects) { if (hitObject.HitWindows.WindowFor(HitResult.Miss) > 0) return hitObject.HitWindows; foreach (var nested in hitObject.NestedHitObjects) { if (nested.HitWindows.WindowFor(HitResult.Miss) > 0) return nested.HitWindows; } } return null; } } /// /// Create an optional resume overlay, which is displayed when a player requests to resume gameplay during non-break time. /// This can be used to force the player to return their hands / cursor to the position they left off, to avoid players /// using pauses as a means of adjusting their inputs (aka "pause buffering"). /// protected virtual ResumeOverlay CreateResumeOverlay() => null; /// /// Whether to display gameplay overlays, such as and . /// public virtual bool AllowGameplayOverlays => true; /// /// Sets a replay to be used, overriding local input. /// /// The replay, null for local input. public abstract void SetReplayScore(Score replayScore); /// /// Sets a replay to be used to record gameplay. /// /// The target to be recorded to. public abstract void SetRecordTarget([CanBeNull] Score score); /// /// Invoked when the interactive user requests resuming from a paused state. /// Allows potentially delaying the resume process until an interaction is performed. /// /// The action to run when resuming is to be completed. public abstract void RequestResume(Action continueResume); /// /// Invoked when the user requests to pause while the resume overlay is active. /// public abstract void CancelResume(); } public class BeatmapInvalidForRulesetException : ArgumentException { public BeatmapInvalidForRulesetException(string text) : base(text) { } } }