Rampage/Game/RampageGame.cs

The main game-flow component for the Rampage scene. Runs the intro sequence (black, misfit recall lines, title card, input lock), tracks combo, score pops, milestones, ticker headlines, camera shake and slow motion, and drives the results screen with hold-to-restart or hold-to-leave scene changes. It reads state from a shared Rampage bus and SumpState save notes, and spawns the RampageHud and RampageAudio components.

using System;
using System.Collections.Generic;
using System.Linq;

public enum RampagePhase { Intro, Rampage }

/// <summary>
/// The rules and the flow of THE RAMPAGE, and everything the HUD and the sound need worked out
/// for them. <see cref="RampageBootstrap"/> adds it to the Rampage object; it then adds a
/// <see cref="ScreenPanel"/> with the <see cref="RampageUi.RampageHud"/> and a
/// <see cref="RampageAudio"/> next to itself.
///
///   - Intro: black, a few lines recalling the misfits by name, the title card, then control.
///     Any of Jump, Use or Attack skips it. Replays get the short version.
///   - While it runs: combos (hits close together chain, display only, but long chains pay a
///     bonus), milestones for people flung, things smashed and town flattened, an announcement
///     of what the town tries next at every tier, camera shake from <see cref="Rampage.Impact"/>
///     and a short slow-motion beat on huge hits.
///   - Results: hold Score (Tab) at any time; they also come up by themselves once the last tier
///     is reached. From there hold F to start again or G to go back down to the Sump.
///
/// There is no losing. It reads the other modules through the <see cref="Rampage"/> bus and
/// <see cref="RampageLinks"/>, and writes only <see cref="Rampage.Score"/> (bonuses),
/// <see cref="Rampage.Announce"/> and <see cref="Rampage.Prompt"/> (taken down every frame, as
/// the Sump does, so set a prompt every frame you want it shown).
///
/// What it changes outside itself is always put back: the lizard's input lock (the intro), and
/// the scene's time scale (a slow-motion beat), on the way out of either, when it is switched
/// off or destroyed, and before any change of scene.
/// </summary>
[Title( "Rampage Game" ), Category( "Rampage" ), Icon( "emoji_events" )]
public sealed class RampageGame : Component
{
	public static RampageGame Current { get; private set; }

	[Property] public bool UseHud { get; set; } = true;
	[Property] public bool UseAudio { get; set; } = true;
	[Property] public int HudZIndex { get; set; } = 100;

	// ---- Intro ----------------------------------------------------------------------------------
	[Property, Group( "Intro" )] public bool PlayIntro { get; set; } = true;
	[Property, Group( "Intro" )] public float IntroBlackSeconds { get; set; } = 0.8f;
	/// <summary>Seconds the lines recalling the misfits stay up (first visit only).</summary>
	[Property, Group( "Intro" )] public float IntroRecallSeconds { get; set; } = 5.5f;
	/// <summary>Seconds of title card, during which the black lifts.</summary>
	[Property, Group( "Intro" )] public float IntroTitleSeconds { get; set; } = 3.2f;
	/// <summary>Hold the lizard still until the title card has gone.</summary>
	[Property, Group( "Intro" )] public bool LockInputInIntro { get; set; } = true;
	[Property, Group( "Intro" )] public float ControlsSeconds { get; set; } = 14f;

	// ---- Combo ----------------------------------------------------------------------------------
	/// <summary>Seconds after a hit in which the next one still chains.</summary>
	[Property, Group( "Combo" )] public float ComboWindow { get; set; } = 2.5f;
	/// <summary>Bonus points for a combo milestone, per hit in the chain (more at higher tiers).</summary>
	[Property, Group( "Combo" )] public float ComboBonusPerHit { get; set; } = 10f;
	/// <summary>Bonus points for a milestone of people flung or things smashed, per one counted.</summary>
	[Property, Group( "Combo" )] public float MilestoneBonusPerCount { get; set; } = 8f;

	// ---- Feel -----------------------------------------------------------------------------------
	/// <summary>Camera kick, in inches, at full shake.</summary>
	[Property, Group( "Feel" )] public float ShakeInches { get; set; } = 12f;
	/// <summary>The most shake that can build up, however much is going on (1 is one full-strength impact).</summary>
	[Property, Group( "Feel" )] public float ShakeCap { get; set; } = 2f;
	/// <summary>How fast shake dies away, per second.</summary>
	[Property, Group( "Feel" )] public float ShakeDecay { get; set; } = 3.8f;
	[Property, Group( "Feel" )] public bool SlowMotion { get; set; } = true;
	/// <summary>A single hit worth this many points earns a slow-motion beat (the bar rises with the tier).</summary>
	[Property, Group( "Feel" )] public float SlowMoPoints { get; set; } = 300f;
	[Property, Group( "Feel" ), Range( 0.05f, 1f )] public float SlowMoScale { get; set; } = 0.3f;
	/// <summary>Real seconds a slow-motion beat lasts.</summary>
	[Property, Group( "Feel" )] public float SlowMoSeconds { get; set; } = 0.32f;
	/// <summary>Real seconds before another beat is allowed.</summary>
	[Property, Group( "Feel" )] public float SlowMoCooldown { get; set; } = 3f;

	// ---- HUD timings ----------------------------------------------------------------------------
	[Property, Group( "Hud" )] public float PopSeconds { get; set; } = 2.6f;
	[Property, Group( "Hud" )] public int PopLines { get; set; } = 7;
	[Property, Group( "Hud" )] public float SplashSeconds { get; set; } = 3.4f;
	/// <summary>Seconds a headline stays on the ticker before the next.</summary>
	[Property, Group( "Hud" )] public float TickerSeconds { get; set; } = 6.5f;
	/// <summary>Take <see cref="Rampage.Prompt"/> down at the end of every frame, so stale prompts vanish.</summary>
	[Property, Group( "Hud" )] public bool PromptsExpire { get; set; } = true;

	// ---- Results --------------------------------------------------------------------------------
	[Property, Group( "Results" )] public string ResultsAction { get; set; } = "Score";
	[Property, Group( "Results" )] public string RestartAction { get; set; } = "Flashlight";
	[Property, Group( "Results" )] public string LeaveAction { get; set; } = "Drop";
	/// <summary>Seconds the restart or leave key must be held.</summary>
	[Property, Group( "Results" )] public float HoldSeconds { get; set; } = 1.1f;
	/// <summary>Seconds after the last tier is reached before the results come up by themselves.</summary>
	[Property, Group( "Results" )] public float FinalResultsDelay { get; set; } = 6f;
	[Property, Group( "Results" )] public string SumpScene { get; set; } = "scenes/sump.scene";

	const string BestNote = "rampage_best";
	const string RunsNote = "rampage_runs";

	/// <summary>One line of the score feed. Hits on the same thing in quick succession share a line.</summary>
	public sealed class ScorePop
	{
		public string Label;
		public float Points;
		public int Count = 1;
		public bool Bonus;
		public float Born, Until;
	}

	// ---- What the HUD and the sound read --------------------------------------------------------
	public RampagePhase Phase { get; private set; } = RampagePhase.Rampage;
	/// <summary>Black over everything, 0 to 1.</summary>
	public float Fade { get; private set; }
	public string CardTitle { get; private set; } = "";
	public string CardSub { get; private set; } = "";
	public List<string> CardLines { get; } = new();

	public List<ScorePop> Pops { get; } = new();
	public int Combo { get; private set; }
	public int BestCombo { get; private set; }
	/// <summary>How much of the combo window is left, 1 just hit to 0 gone.</summary>
	public float ComboLeft => Combo > 0 ? Math.Clamp( 1f - (RealTime.Now - _lastHitAt) / MathF.Max( ComboWindow, 0.1f ), 0f, 1f ) : 0f;
	public float LastHitAt => _lastHitAt;

	/// <summary>The destruction counter as shown: it runs after the real one.</summary>
	public float ShownDestruction { get; private set; }
	/// <summary>Things smashed, without the bonuses this component paid through <see cref="Rampage.Score"/>.</summary>
	public int ThingsSmashed => Math.Max( Rampage.ThingsSmashed - _bonusesPaid, 0 );

	public string Headline { get; private set; } = "";
	public float HeadlineAt { get; private set; }

	public int SplashTier { get; private set; }
	public string SplashName { get; private set; } = "";
	public string SplashHeadline { get; private set; } = "";
	public float SplashAt { get; private set; } = -100f;
	public bool SplashShowing => RealTime.Now < SplashAt + SplashSeconds;

	public string ShownPrompt { get; private set; }
	public bool ShowControls { get; private set; }

	public bool ShowResults { get; private set; }
	/// <summary>The results came up by themselves, after the last tier.</summary>
	public bool ResultsFinal { get; private set; }
	public float RestartHold { get; private set; }
	public float LeaveHold { get; private set; }
	public string SilliestThing { get; private set; } = "";
	public string BiggestThing { get; private set; } = "";
	public float BiggestPoints { get; private set; }
	public string FavouriteThing { get; private set; } = "";
	public int FavouriteCount { get; private set; }
	public float BestDestruction { get; private set; }
	public int BestTier { get; private set; }
	public int BestComboEver { get; private set; }
	/// <summary>This run has beaten the saved best destruction.</summary>
	public bool NewRecord { get; private set; }

	/// <summary>How hard the camera is shaking, 0 to <see cref="ShakeCap"/>.</summary>
	public float ShakeNow => _shake;
	/// <summary>How frightened the crowd sounds, 0 to 1: rises with every person flung, dies away.</summary>
	public float Panic { get; private set; }

	/// <summary>
	/// Something the sound should mark, by name: "intro", "title", "go", "combo" (with the combo
	/// length), "combo_break", "bonus", "milestone", "results", "record", "tick".
	/// </summary>
	public event Action<string, int> Cue;

	// ---- Private state --------------------------------------------------------------------------
	float _introAt, _introBegan;
	bool _introQuick;
	List<string> _recall;
	/// <summary>The longest the title will wait for the town to be built behind the black.</summary>
	const float IntroWaitsForTown = 30f;
	bool _lockedPlayer;
	string _introStep = "";

	float _lastHitAt = -100f;
	int _humansSeen;
	int _bonusesPaid;
	bool _payingBonus;
	readonly List<(Vector3 At, float Points, string Label)> _owed = new();
	int _humanMilestone, _thingMilestone, _townMilestone;

	readonly Dictionary<string, int> _counts = new();
	int _silliness;

	string _newsLabel;
	bool _newsHuman;
	float _newsPoints;
	int _idleHeadlines;

	readonly Dictionary<string, string> _labels = new();
	readonly Dictionary<string, string> _plain = new();

	float _shake;
	float _slowUntil, _slowReadyAt, _slowScale;
	float _finalAt = -1f;
	bool _finalDone, _finalOpen;
	float _controlsUntil = -1f;
	bool _listening;

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		SumpState.EnsureStarted();
		LoadBest();

		if ( UseHud ) StartHud();
		if ( UseAudio ) StartAudio();

		int runs = ParseInt( SumpState.GetNote( RunsNote ), 0 );
		_introQuick = runs > 0;
		SumpState.SetNote( RunsNote, (runs + 1).ToString() );

		if ( PlayIntro ) BeginIntro();
		else EndIntro();
	}

	public RampageUi.RampageHud Hud { get; private set; }
	public RampageAudio Audio { get; private set; }

	void StartHud()
	{
		try
		{
			var screen = Components.GetOrCreate<ScreenPanel>();
			screen.ZIndex = HudZIndex;
			Hud = Components.GetOrCreate<RampageUi.RampageHud>();
		}
		catch ( Exception e ) { Log.Warning( $"Rampage HUD not started: {e.Message}" ); }
	}

	void StartAudio()
	{
		try { Audio = Components.GetOrCreate<RampageAudio>(); }
		catch ( Exception e ) { Log.Warning( $"Rampage audio not started: {e.Message}" ); }
	}

	protected override void OnEnabled()
	{
		if ( Scene.IsEditor || _listening ) return;
		Rampage.Scored += OnScored;
		Rampage.TierUp += OnTierUp;
		Rampage.Impact += OnImpact;
		_listening = true;
		_humansSeen = Rampage.HumansSent;
	}

	protected override void OnDisabled()
	{
		if ( _listening )
		{
			Rampage.Scored -= OnScored;
			Rampage.TierUp -= OnTierUp;
			Rampage.Impact -= OnImpact;
			_listening = false;
		}
		EndSlowMo();
		UnlockPlayer();
	}

	protected override void OnDestroy()
	{
		if ( Current != this ) return;
		Current = null;
		if ( Rampage.Destruction > 0f ) SaveBest();
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		float now = RealTime.Now;
		float dt = Math.Clamp( RealTime.Delta, 0f, 0.1f );

		if ( Phase == RampagePhase.Intro ) UpdateIntro( now );
		UpdateCombo( now );
		PayBonuses();
		UpdateMilestones();
		UpdateTicker( now );
		UpdateShake( dt );
		UpdateSlowMo( now );
		UpdateResults( now, dt );

		// The counter runs after the truth: fast when far behind, never slower than a crawl.
		float behind = Rampage.Destruction - ShownDestruction;
		if ( behind > 0f ) ShownDestruction = MathF.Min( ShownDestruction + MathF.Max( behind * 5f, 40f ) * dt, Rampage.Destruction );
		else ShownDestruction = Rampage.Destruction;

		for ( int i = Pops.Count - 1; i >= 0; i-- )
			if ( now > Pops[i].Until ) Pops.RemoveAt( i );
		Panic = MathF.Max( Panic - dt * 0.22f, 0f );
		ShowControls = Phase == RampagePhase.Rampage && (now < _controlsUntil || ShowResults);
	}

	protected override void OnPreRender()
	{
		if ( Scene.IsEditor ) return;
		ShownPrompt = Rampage.Prompt;
		if ( PromptsExpire ) Rampage.Prompt = null;
	}

	// ---- Intro ----------------------------------------------------------------------------------

	void BeginIntro()
	{
		Phase = RampagePhase.Intro;
		Rampage.Started = false;
		_introAt = _introBegan = RealTime.Now;
		Fade = 1f;
		SetIntroStep( "intro" );
	}

	void UpdateIntro( float now )
	{
		float recall = _introQuick ? 0f : MathF.Max( IntroRecallSeconds, 0f );
		float titleFrom = IntroBlackSeconds + recall;
		float end = titleFrom + MathF.Max( IntroTitleSeconds, 0.5f );
		float t = now - _introAt;

		if ( LockInputInIntro && Rampage.Player.IsValid() && !Rampage.Player.InputLocked )
		{
			Rampage.Player.InputLocked = true;
			_lockedPlayer = true;
		}

		// Somebody is holding the scene's clock (the loading screen does, until the town stands):
		// the intro waits with it, so its cards are not played out behind another screen. Not for
		// ever: nothing may keep the lizard locked.
		if ( Scene.TimeScale < 0.01f && now - _introBegan < IntroWaitsForTown )
		{
			_introAt += Math.Clamp( RealTime.Delta, 0f, 0.1f );
			Fade = 1f;
			return;
		}

		// The town is put up over a few frames behind the black. The black does not lift, and
		// nothing can be skipped, until it stands (or, if it never does, until patience runs out).
		bool building = !(RampageWorld.Ready && RampagePopulace.Built) && now - _introBegan < IntroWaitsForTown;
		float hold = titleFrom - 0.05f;
		if ( building && t > hold )
		{
			_introAt = now - hold;
			t = hold;
		}

		// Any key that means "get on with it" jumps to the last second of the title.
		if ( !building && t > 0.6f && t < end - 1f && (Input.Pressed( "Jump" ) || Input.Pressed( "Use" ) || Input.Pressed( "Attack1" )) )
		{
			_introAt = now - (end - 1f);
			t = end - 1f;
		}

		CardTitle = CardSub = "";
		CardLines.Clear();
		if ( t < IntroBlackSeconds )
		{
			Fade = 1f;
		}
		else if ( t < titleFrom )
		{
			Fade = 1f;
			SetIntroStep( "recall" );
			CardLines.Add( "They shot us. They cut us open. They sold us, laughed at us, and forgot us." );
			CardLines.AddRange( _recall ??= RecallLines() );
			CardLines.Add( "Up we come. Through the square. Trousers optional." );
		}
		else if ( t < end )
		{
			SetIntroStep( "title" );
			float into = (t - titleFrom) / (end - titleFrom);
			Fade = Math.Clamp( 1f - (into - 0.15f) / 0.6f, 0f, 1f );
			CardTitle = "THE COMEUPPANCE";
			CardSub = "a victory lap, with a club";
		}
		else EndIntro();
	}

	void SetIntroStep( string step )
	{
		if ( _introStep == step ) return;
		_introStep = step;
		if ( step != "recall" ) Cue?.Invoke( step, 0 );
	}

	void EndIntro()
	{
		Phase = RampagePhase.Rampage;
		Rampage.Started = true;
		Fade = 0f;
		CardTitle = CardSub = "";
		CardLines.Clear();
		UnlockPlayer();
		_controlsUntil = RealTime.Now + ControlsSeconds;
		Headline = "TOWN SQUARE ERUPTS. LIZARD THE SIZE OF THE TOWN HALL STANDS UP IN IT, DRAGGING SOMETHING. 'PROBABLY NOTHING', SAYS MAYOR.";
		HeadlineAt = RealTime.Now;
		Say( "GIVE THEM WHAT THEY GAVE US. WITH THE BIG END.", 3.5f );
		Cue?.Invoke( "go", 0 );
	}

	void UnlockPlayer()
	{
		if ( !_lockedPlayer ) return;
		_lockedPlayer = false;
		if ( Rampage.Player.IsValid() ) Rampage.Player.InputLocked = false;
	}

	/// <summary>"For Biscuit. For Exhibit C." The healed ones by name, three to a line (everybody, if nobody is healed yet).</summary>
	static List<string> RecallLines()
	{
		var lines = new List<string>();
		try
		{
			var who = SumpState.Misfits.Where( m => m is not null && m.Healed ).ToList();
			if ( who.Count == 0 ) who = SumpState.Misfits.Where( m => m is not null ).ToList();
			var names = who.Select( m => MisfitVoice.ShortName( m ) ).Where( n => !string.IsNullOrWhiteSpace( n ) ).Distinct().Take( 9 ).ToList();
			for ( int i = 0; i < names.Count; i += 3 )
				lines.Add( string.Join( "  ", names.Skip( i ).Take( 3 ).Select( n => $"For {n}." ) ) );
		}
		catch ( Exception ) { }
		if ( lines.Count == 0 ) lines.Add( "For everybody down there." );
		return lines;
	}

	// ---- Scoring: pops, combo, bonuses ------------------------------------------------------------

	void OnScored( Vector3 at, float points, string label )
	{
		float now = RealTime.Now;
		bool human = Rampage.HumansSent != _humansSeen;
		_humansSeen = Rampage.HumansSent;
		label = string.IsNullOrWhiteSpace( label ) ? (human ? "SOMEBODY" : "SOMETHING") : Tidy( label );

		// Our own bonus coming back round: show it, and let it count for nothing else.
		if ( _payingBonus )
		{
			_bonusesPaid++;
			Pops.Add( new ScorePop { Label = label, Points = points, Bonus = true, Born = now, Until = now + PopSeconds * 1.4f } );
			TrimPops();
			return;
		}

		// The feed: the same thing hit again straight away adds to its line.
		ScorePop same = null;
		for ( int i = Pops.Count - 1; i >= 0 && same is null; i-- )
		{
			var pop = Pops[i];
			if ( !pop.Bonus && now - pop.Born < 0.7f && pop.Label == label ) same = pop;
		}
		if ( same is not null ) { same.Count++; same.Points += points; same.Until = now + PopSeconds; }
		else Pops.Add( new ScorePop { Label = label, Points = points, Born = now, Until = now + PopSeconds } );
		TrimPops();

		// The combo.
		Combo = now - _lastHitAt <= ComboWindow ? Combo + 1 : 1;
		_lastHitAt = now;
		if ( Combo > BestCombo ) BestCombo = Combo;
		if ( Array.IndexOf( RampageNews.ComboMilestones, Combo ) >= 0 )
		{
			float bonus = Combo * ComboBonusPerHit * (1f + Rampage.Tier * 0.5f);
			_owed.Add( (at, bonus, $"x{Combo} {RampageNews.ComboWord( Combo )} BONUS") );
			Cue?.Invoke( "combo", Combo );
		}

		// What the results will remember.
		if ( human ) Panic = MathF.Min( Panic + 0.12f, 1f );
		else
		{
			// "TAX OFFICE (ONE FLOOR OF)" counts toward the TAX OFFICE.
			if ( !_plain.TryGetValue( label, out string thing ) )
			{
				if ( _plain.Count > 400 ) _plain.Clear();
				_plain[label] = thing = RampageNews.Plain( label );
			}
			int times = _counts.TryGetValue( thing, out int count ) ? count + 1 : 1;
			_counts[thing] = times;
			if ( times > FavouriteCount ) { FavouriteCount = times; FavouriteThing = thing; }
			if ( points > BiggestPoints ) { BiggestPoints = points; BiggestThing = label; }
			int silliness = RampageNews.Silliness( thing );
			if ( silliness > _silliness ) { _silliness = silliness; SilliestThing = thing; }
		}

		// The ticker reports the biggest thing since its last headline.
		if ( _newsLabel is null || points >= _newsPoints ) { _newsLabel = label; _newsHuman = human; _newsPoints = points; }

		if ( points >= SlowMoPoints * (1f + Rampage.Tier * 0.6f) ) TrySlowMo( SlowMoSeconds );
	}

	/// <summary>A label as the feed shows it (trimmed, in capitals). The same few hundred come round again and again, so each is made once.</summary>
	string Tidy( string label )
	{
		if ( _labels.TryGetValue( label, out string tidy ) ) return tidy;
		if ( _labels.Count > 400 ) _labels.Clear();
		return _labels[label] = label.Trim().ToUpperInvariant();
	}

	void TrimPops()
	{
		while ( Pops.Count > Math.Max( PopLines, 1 ) ) Pops.RemoveAt( 0 );
	}

	void UpdateCombo( float now )
	{
		if ( Combo <= 0 || now - _lastHitAt <= ComboWindow ) return;
		if ( Combo >= 5 ) Cue?.Invoke( "combo_break", Combo );
		Combo = 0;
	}

	/// <summary>Pays what is owed through the bus, outside its own event (a bonus must not start another).</summary>
	void PayBonuses()
	{
		if ( _owed.Count == 0 || !Rampage.Running ) return;
		// Nothing is added to the list while it is being paid: a bonus coming back round is only shown.
		int paid = _owed.Count;
		_payingBonus = true;
		for ( int i = 0; i < paid; i++ ) Rampage.Score( _owed[i].At, _owed[i].Points, _owed[i].Label );
		_payingBonus = false;
		_owed.RemoveRange( 0, paid );
		Cue?.Invoke( "bonus", paid );
	}

	void UpdateMilestones()
	{
		var at = Rampage.Player.IsValid() ? Rampage.Player.WorldPosition : WorldPosition;

		while ( _humanMilestone < RampageNews.HumanMilestones.Length && Rampage.HumansSent >= RampageNews.HumanMilestones[_humanMilestone].Count )
		{
			var (count, title) = RampageNews.HumanMilestones[_humanMilestone++];
			Say( $"{count} PILLOCKS AIRBORNE: {title}", 3.5f );
			_owed.Add( (at, count * MilestoneBonusPerCount, title) );
			Cue?.Invoke( "milestone", count );
		}

		while ( _thingMilestone < RampageNews.ThingMilestones.Length && ThingsSmashed >= RampageNews.ThingMilestones[_thingMilestone].Count )
		{
			var (count, title) = RampageNews.ThingMilestones[_thingMilestone++];
			Say( $"{count} THINGS KNACKERED: {title}", 3.5f );
			_owed.Add( (at, count * MilestoneBonusPerCount, title) );
			Cue?.Invoke( "milestone", count );
		}

		int standing = RampageLinks.StandingPercent;
		if ( standing < 0 || Rampage.Destruction <= 0f ) return;
		while ( _townMilestone < RampageNews.TownMilestones.Length && standing <= RampageNews.TownMilestones[_townMilestone].Percent )
		{
			var (percent, text) = RampageNews.TownMilestones[_townMilestone++];
			Say( text, 4f );
			_owed.Add( (at, (100 - percent) * 10f * (1f + Rampage.Tier * 0.5f), percent <= 0 ? "TOWN FLATTENED" : $"TOWN {percent}% STANDING") );
			Cue?.Invoke( "milestone", percent );
			if ( percent <= 0 ) ScheduleFinalResults();
		}
	}

	// ---- Tiers, announcements, the ticker ---------------------------------------------------------

	void OnTierUp( int tier )
	{
		float now = RealTime.Now;
		SplashTier = tier;
		SplashName = Rampage.TierName;
		SplashHeadline = RampageNews.TierHeadline( tier );
		SplashAt = now;
		Headline = SplashHeadline;
		HeadlineAt = now;

		// The stamp has the screen first; whatever anybody announces meanwhile waits behind it.
		Rampage.HoldBanners( SplashSeconds );
		string happens = RampageNews.TierEvent( tier );
		if ( !string.IsNullOrEmpty( happens ) ) Say( happens, 4f );

		TrySlowMo( SlowMoSeconds * 1.8f );
		SaveBest();
		if ( tier >= Rampage.TierNames.Length - 1 ) ScheduleFinalResults();
	}

	/// <summary>An announcement for the banner. Every module's go through <see cref="Rampage.Announce"/>, which shows them one after another, after any tier-up stamp.</summary>
	public void Say( string text, float seconds = 3f ) => Rampage.Announce( text, seconds );

	void UpdateTicker( float now )
	{
		if ( Phase != RampagePhase.Rampage || now - HeadlineAt < TickerSeconds ) return;

		if ( _newsLabel is not null )
		{
			Headline = RampageNews.Headline( _newsLabel, _newsHuman );
			_newsLabel = null;
			_newsPoints = 0f;
			_idleHeadlines = 0;
		}
		else
		{
			// Nothing new: one idle headline, then leave it be for a while.
			if ( _idleHeadlines++ % 2 == 1 ) { HeadlineAt = now; return; }
			Headline = RampageNews.Pick( RampageNews.Idle );
		}
		HeadlineAt = now;
		Cue?.Invoke( "tick", 0 );
	}

	// ---- Shake and slow motion --------------------------------------------------------------------

	void OnImpact( float strength )
	{
		_shake = MathF.Min( _shake + Math.Clamp( strength, 0f, 1f ), MathF.Max( ShakeCap, 0f ) );
	}

	void UpdateShake( float dt )
	{
		if ( _shake <= 0.01f ) { _shake = 0f; return; }
		if ( Rampage.Player.IsValid() && ShakeInches > 0f )
		{
			// The controller's kick dies away by itself; feeding it a little every frame keeps it rattling.
			var jolt = new Vector3( Game.Random.Float( -1f, 1f ), Game.Random.Float( -1f, 1f ), Game.Random.Float( -1f, 1f ) );
			Rampage.Player.Kick( jolt * _shake * ShakeInches * MathF.Min( dt * 30f, 1f ) );
		}
		_shake *= MathF.Exp( -dt * MathF.Max( ShakeDecay, 0.1f ) );
	}

	/// <summary>A brief dip in the scene's speed. Never while one is running, soon after one, or while anybody else has the clock.</summary>
	void TrySlowMo( float seconds )
	{
		if ( !SlowMotion || _slowUntil > 0f || RealTime.Now < _slowReadyAt || ShowResults ) return;
		if ( MathF.Abs( Scene.TimeScale - 1f ) > 0.01f ) return;
		_slowScale = Math.Clamp( SlowMoScale, 0.05f, 1f );
		Scene.TimeScale = _slowScale;
		_slowUntil = RealTime.Now + MathF.Min( seconds, 2f );
	}

	void UpdateSlowMo( float now )
	{
		if ( _slowUntil > 0f && now >= _slowUntil ) EndSlowMo();
	}

	void EndSlowMo()
	{
		if ( _slowUntil <= 0f ) return;
		_slowUntil = 0f;
		_slowReadyAt = RealTime.Now + SlowMoCooldown;
		// Back to normal, unless somebody else has taken the clock since (then it is theirs to put back).
		if ( Scene is not null && MathF.Abs( Scene.TimeScale - _slowScale ) < 0.01f ) Scene.TimeScale = 1f;
	}

	// ---- Results ----------------------------------------------------------------------------------

	void ScheduleFinalResults()
	{
		if ( _finalDone ) return;
		_finalDone = true;
		_finalAt = RealTime.Now + FinalResultsDelay;
	}

	void UpdateResults( float now, float dt )
	{
		if ( Phase != RampagePhase.Rampage ) { ShowResults = false; return; }

		if ( _finalAt >= 0f && now >= _finalAt )
		{
			_finalAt = -1f;
			_finalOpen = true;
			SaveBest();
		}
		else if ( _finalOpen && Input.Pressed( ResultsAction ) ) _finalOpen = false;

		bool show = _finalOpen || Input.Down( ResultsAction );
		if ( show && !ShowResults ) Cue?.Invoke( NewRecord && _finalOpen ? "record" : "results", 0 );
		ShowResults = show;
		ResultsFinal = _finalOpen;

		float step = dt / MathF.Max( HoldSeconds, 0.1f );
		RestartHold = show && Input.Down( RestartAction ) ? RestartHold + step : 0f;
		LeaveHold = show && Input.Down( LeaveAction ) ? LeaveHold + step : 0f;
		if ( RestartHold >= 1f ) ChangeScene( Rampage.ScenePath );
		else if ( LeaveHold >= 1f ) ChangeScene( SumpScene );
	}

	void ChangeScene( string path )
	{
		RestartHold = LeaveHold = 0f;
		SaveBest();
		EndSlowMo();
		if ( Scene is not null ) Scene.TimeScale = 1f;
		UnlockPlayer();
		Game.ChangeScene( path );
	}

	/// <summary>The grade for this run so far.</summary>
	public (string Grade, string Line) Grade => RampageNews.Grade( Rampage.Tier );

	// ---- Best scores, kept with the Sump's save -----------------------------------------------------

	void LoadBest()
	{
		var parts = SumpState.GetNote( BestNote ).Split( '|' );
		BestDestruction = parts.Length > 0 ? ParseInt( parts[0], 0 ) : 0;
		BestTier = parts.Length > 1 ? ParseInt( parts[1], 0 ) : 0;
		BestComboEver = parts.Length > 2 ? ParseInt( parts[2], 0 ) : 0;
	}

	/// <summary>Keeps the best destruction, tier and combo of any run: "destruction|tier|combo".</summary>
	void SaveBest()
	{
		if ( Rampage.Destruction > BestDestruction )
		{
			if ( BestDestruction > 0f ) NewRecord = true;
			BestDestruction = MathF.Floor( Rampage.Destruction );
		}
		BestTier = Math.Max( BestTier, Rampage.Tier );
		BestComboEver = Math.Max( BestComboEver, BestCombo );
		try { SumpState.SetNote( BestNote, $"{(long)BestDestruction}|{BestTier}|{BestComboEver}" ); }
		catch ( Exception e ) { Log.Warning( $"Rampage best not saved: {e.Message}" ); }
	}

	static int ParseInt( string text, int fallback ) => int.TryParse( text, out int value ) ? value : fallback;
}