Stadium/StadiumGame.cs

The rules component for the stadium escape scene. Drives the FlashIn, Speech, Shapeshift, Escape and ending phases, tracks crowd grips on the lizard's limbs with turn-based grab telegraphs, converts buck/mouse-thrash into break force, and handles win, game-over and restart scene flow.

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

/// <summary>Where Scene 2 has got to.</summary>
public enum StadiumPhase
{
	/// <summary>White-out. You are walking down the carpet in the envoy's skin; your eyes adjust.</summary>
	FlashIn,
	/// <summary>You can move. The stadium waits for the speech.</summary>
	Speech,
	/// <summary>The skin is failing: you shift back, the crowd gasps, then screams.</summary>
	Shapeshift,
	/// <summary>Get out. The crowd and the guards come for you.</summary>
	Escape,
	/// <summary>The Fat Guy sat on you. Fade to black, "Try again?".</summary>
	GameOver,
	/// <summary>You reached the exit.</summary>
	Won,
}

/// <summary>
/// The rules of Scene 2, one per scene. Runs the opening beats, tracks who has hold of which of
/// the lizard's limbs and how hard it is shaking, and the win and lose endings. The crowd, the Fat Guy and the HUD
/// all talk to this.
/// </summary>
[Title( "Stadium Game" ), Category( "Stadium" ), Icon( "stadium" )]
public sealed class StadiumGame : Component, ICrowdHost, IGrabTurns
{
	public static StadiumGame Get( Scene scene ) => scene?.GetAllComponents<StadiumGame>().FirstOrDefault();

	// ---- Timing -----------------------------------------------------------------------------
	/// <summary>Seconds of walking down the carpet while the white-out clears.</summary>
	[Property, Group( "Opening" )] public float FlashInSeconds { get; set; } = 6.5f;

	/// <summary>Seconds you have at the podium before the skin starts to fail (sooner if you reach the podium).</summary>
	[Property, Group( "Opening" )] public float SpeechSeconds { get; set; } = 9f;

	/// <summary>Seconds the shift back to lizard takes.</summary>
	[Property, Group( "Opening" )] public float ShapeshiftSeconds { get; set; } = 4.5f;

	[Property, Group( "Opening" )] public string SkinPath { get; set; } = "skins/envoy.skin";

	// ---- Grips ------------------------------------------------------------------------------
	/// <summary>
	/// Force needed to shake off a grip when it is the only one, measured as the acceleration of
	/// the lizard's body in inches per second squared. A hard reversal at a run is about 8000.
	/// </summary>
	[Property, Group( "Grips" )] public float BreakForce { get; set; } = 3400f;

	/// <summary>How much more force each further grip adds, as a fraction of <see cref="BreakForce"/>.</summary>
	[Property, Group( "Grips" )] public float ForcePerExtraGrip { get; set; } = 0.35f;

	/// <summary>How quickly a grip gives under enough force. Higher breaks sooner.</summary>
	[Property, Group( "Grips" )] public float StrainRate { get; set; } = 3.2f;

	/// <summary>Force added by one press of SPACE (a buck).</summary>
	[Property, Group( "Grips" )] public float BuckForce { get; set; } = 5200f;

	/// <summary>Force added by shaking the mouse, per pixel per second of movement.</summary>
	[Property, Group( "Grips" )] public float MouseShakeForce { get; set; } = 1.2f;

	/// <summary>With this many grips on it the lizard is pinned to the spot (and the Fat Guy comes).</summary>
	[Property, Group( "Grips" )] public int PinGrips { get; set; } = 3;

	/// <summary>How much each grip slows the lizard: speed is divided by 1 + this per grip.</summary>
	[Property, Group( "Grips" )] public float SlowPerGrip { get; set; } = 0.25f;

	/// <summary>Seconds after the last grip breaks during which nobody can grab.</summary>
	[Property, Group( "Grips" )] public float FreeSeconds { get; set; } = 2f;

	/// <summary>
	/// Seconds between one hand landing and the next at the start of the chase. Grips come one at
	/// a time, at a steady beat, never all at once.
	/// </summary>
	[Property, Group( "Grips" )] public float GrabBeatSeconds { get; set; } = 2.4f;

	/// <summary>The beat tightens to this many seconds between grips as the chase goes on.</summary>
	[Property, Group( "Grips" )] public float GrabGapMinSeconds { get; set; } = 1f;

	/// <summary>Seconds of chase over which the beat tightens from <see cref="GrabBeatSeconds"/> to <see cref="GrabGapMinSeconds"/>.</summary>
	[Property, Group( "Grips" )] public float GrabTightenSeconds { get; set; } = 75f;

	/// <summary>
	/// The warning: whoever is about to grab has their arms up for this long first, and only they
	/// can grab. Then they snatch (if in reach) or lunge. Be somewhere else by then and it misses.
	/// </summary>
	[Property, Group( "Grips" )] public float GrabTelegraphSeconds { get; set; } = 0.65f;

	/// <summary>Seconds after a missed grab before the next person may wind one up.</summary>
	[Property, Group( "Grips" )] public float GrabMissSeconds { get; set; } = 0.4f;
	TimeSince _sinceGrab = 10f;

	/// <summary>Seconds between grips right now.</summary>
	public float GrabGap
	{
		get
		{
			float first = MathF.Max( GrabBeatSeconds, 0.1f );
			float last = Math.Clamp( GrabGapMinSeconds, 0.1f, first );
			float t = Phase == StadiumPhase.Escape ? Math.Clamp( TimeInPhase / MathF.Max( GrabTightenSeconds, 1f ), 0f, 1f ) : 0f;
			return first + (last - first) * t;
		}
	}

	// ---- Whose turn it is to grab (IGrabTurns) ---------------------------------------------------
	GameObject _turnHolder;
	TimeSince _sinceTurnBegan = 10f, _sinceTurnEnded = 10f;

	/// <summary>0 while nobody is winding up a grab, rising to 1 at the moment it lands. For the HUD.</summary>
	public float GrabWarning => _turnHolder.IsValid() && Phase == StadiumPhase.Escape
		? Math.Clamp( _sinceTurnBegan / MathF.Max( GrabTelegraphSeconds, 0.05f ), 0f, 1f ) : 0f;

	/// <summary>
	/// A person in reach asks to be the one who grabs next. True while it is their turn, with how
	/// far through the warning they are (1: the grab may land now). Only one person has the turn.
	/// </summary>
	public bool RequestGrabTurn( GameObject who, out float progress )
	{
		progress = 0f;
		if ( Phase != StadiumPhase.Escape || Slippery || !who.IsValid() || Cutscene.HasValue ) return false;

		// A turn nobody is using any more (its holder went down, wandered off or was removed) lapses.
		float telegraph = MathF.Max( GrabTelegraphSeconds, 0.05f );
		if ( _turnHolder is not null && (!_turnHolder.IsValid() || _sinceTurnBegan > telegraph + 1.2f) ) ClearTurn();

		if ( _turnHolder is null )
		{
			// One attempt per beat, hit or miss, with the warning timed to end as the gap since
			// the last grip does: so hands land on the beat, and the beat is what tightens.
			if ( _sinceTurnEnded < GrabMissSeconds || _sinceTurnBegan < GrabGap || _sinceGrab < GrabGap - telegraph ) return false;
			foreach ( var grip in _grips )
				if ( grip.Holder == who ) return false;
			_turnHolder = who;
			_sinceTurnBegan = 0f;
		}

		if ( _turnHolder != who ) return false;
		progress = Math.Clamp( _sinceTurnBegan / telegraph, 0f, 1f );
		return true;
	}

	/// <summary>The person whose turn it was has grabbed, missed or given up.</summary>
	public void EndGrabTurn( GameObject who )
	{
		if ( _turnHolder == who ) ClearTurn();
	}

	void ClearTurn()
	{
		_turnHolder = null;
		_sinceTurnEnded = 0f;
	}

	[Property, Group( "Ending" )] public string ScenePath { get; set; } = "scenes/stadium.scene";

	// ---- State ------------------------------------------------------------------------------
	public StadiumPhase Phase { get; private set; } = StadiumPhase.FlashIn;
	public float TimeInPhase { get; private set; }

	/// <summary>Raised each time the phase changes.</summary>
	public event Action<StadiumPhase> PhaseChanged;

	/// <summary>True from the moment the crowd turns on you.</summary>
	public bool Panic => Phase == StadiumPhase.Escape;

	/// <summary>0..1 through the shapeshift, for the crowd's reaction (gasps early, screams late).</summary>
	public float ShiftProgress => Phase == StadiumPhase.Shapeshift ? Math.Clamp( TimeInPhase / MathF.Max( ShapeshiftSeconds, 0.1f ), 0f, 1f ) : Phase > StadiumPhase.Shapeshift ? 1f : 0f;

	public ReptileController Player { get; private set; }

	// ---- Screen effects, read by the HUD -----------------------------------------------------
	/// <summary>1 = the screen is pure white, 0 = clear.</summary>
	public float Flash { get; private set; } = 1f;

	/// <summary>1 = the screen is black, 0 = clear.</summary>
	public float Fade { get; private set; }

	public string Message { get; private set; }
	public bool MessageVisible => _messageLeft > 0f && !string.IsNullOrEmpty( Message );
	float _messageLeft;

	public void ShowMessage( string text, float seconds = 4f )
	{
		Message = text;
		_messageLeft = seconds;
	}

	// ---- Grips on the lizard's limbs ---------------------------------------------------------

	/// <summary>One person's hold on one limb.</summary>
	public sealed class Grip
	{
		public GameObject Holder;
		public int Limb;
		/// <summary>0 = firm, 1 = about to give.</summary>
		public float Strain;
	}

	readonly List<Grip> _grips = new();
	GameObject[] _anchors;
	ReptileBody _lizardBody;

	/// <summary>How many people have hold of a limb.</summary>
	public int Grabbers => _grips.Count;

	/// <summary>True while anyone has hold of the lizard at all.</summary>
	public bool Held => _grips.Count > 0;

	/// <summary>True while enough people have hold that it can't leave the spot.</summary>
	public bool Pinned => _grips.Count >= PinGrips;

	/// <summary>The force the lizard's thrashing is producing right now.</summary>
	public float ShakeForce { get; private set; }

	/// <summary>The force needed to break a grip right now. Rises with every grip on the lizard.</summary>
	public float ForceNeeded => BreakForce * (1f + ForcePerExtraGrip * MathF.Max( _grips.Count - 1, 0 ));

	/// <summary>How close the grip being worked on is to breaking (0..1), for the HUD.</summary>
	public float Struggle => _grips.Count > 0 ? _grips[0].Strain : 0f;
	public float StruggleNeeded => 1f;

	/// <summary>True for a moment after the last grip breaks: nobody can grab.</summary>
	public bool Slippery => _sinceFree < FreeSeconds || (Charge.IsValid() && Charge.Untouchable);

	/// <summary>Where the Fat Guy's crush is happening, once it has begun. The crowd and the HUD keep out of its way.</summary>
	public Vector3? Cutscene { get; set; }

	/// <summary>The scene loaded once the lizard is out through the exit. Empty to stay on the win card.</summary>
	[Property] public string NextScene { get; set; } = "scenes/sump.scene";
	bool _leaving;

	/// <summary>0 to 1: how far the two cheeks of darkness have closed over the screen during the crush.</summary>
	public float CrushFade { get; set; }

	/// <summary>How dark the cheek-shaped fade is right now, whichever part of the ending drives it.</summary>
	public float CheekFade => Phase == StadiumPhase.GameOver ? Fade : CrushFade;

	/// <summary>Seconds into game over before the card comes up. Short after the crush: the screen is already black.</summary>
	public float CardDelay => Cutscene.HasValue ? 1.4f : 3f;

	/// <summary>The lizard's charge through the crowd.</summary>
	public LizardCharge Charge { get; private set; }

	/// <summary>Raised when one grip is shaken off: that holder is flung away.</summary>
	public event Action<GameObject> GripBroken;

	/// <summary>Raised when the last grip goes and the lizard is loose again.</summary>
	public event Action BrokeFree;

	TimeSince _sinceFree = 100f;
	Vector3 _pinPosition;
	Vector3 _lastVelocity;
	float _buck;

	/// <summary>
	/// A person tries to take hold of the nearest free limb. On success <paramref name="anchor"/>
	/// is the physics object riding on that limb, for the holder to tie a joint to.
	/// </summary>
	public bool TryGrab( GameObject holder, out GameObject anchor )
	{
		anchor = null;
		if ( Phase != StadiumPhase.Escape || Slippery || !Player.IsValid() || !holder.IsValid() || _anchors is null ) return false;
		// Only the person whose turn it is, and only once their warning has run its course.
		if ( _turnHolder != holder || _sinceTurnBegan < GrabTelegraphSeconds ) return false;

		int limb = -1;
		float nearest = float.MaxValue;
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			bool taken = false;
			foreach ( var grip in _grips )
			{
				if ( grip.Holder == holder ) return false; // one limb each
				if ( grip.Limb == i ) taken = true;
			}
			if ( taken || !_anchors[i].IsValid() ) continue;

			float d = (_anchors[i].WorldPosition - holder.WorldPosition).LengthSquared;
			if ( d < nearest ) { nearest = d; limb = i; }
		}
		if ( limb < 0 ) return false;

		_grips.Add( new Grip { Holder = holder, Limb = limb } );
		anchor = _anchors[limb];

		if ( _grips.Count == 1 ) ShowMessage( "Hands! Unwashed ones!  SPACE  buck them off (or thrash the mouse)", 4f );
		if ( _grips.Count == PinGrips )
		{
			_pinPosition = Player.WorldPosition;
			ShowMessage( "Three of them. You are going nowhere.  SPACE  buck, and quickly", 3f );
		}
		_sinceGrab = 0f;
		ClearTurn();
		return true;
	}

	/// <summary>A holder lets go (it died, lost its grip, or was pulled off).</summary>
	public void ReleaseGrab( GameObject holder )
	{
		int removed = _grips.RemoveAll( g => g.Holder == holder );
		if ( removed > 0 && _grips.Count == 0 && Phase == StadiumPhase.Escape ) Loose();
	}

	void Loose()
	{
		_sinceFree = 0;
		BrokeFree?.Invoke();
		ShowMessage( "Free! Keep your hands to yourselves!", 1.5f );
	}

	/// <summary>A small physics body riding on each limb, for the grips' joints to hold.</summary>
	void CreateAnchors()
	{
		_lizardBody = Player.Components.Get<ReptileBody>( FindMode.EverythingInDescendants | FindMode.Disabled );
		_anchors = new GameObject[ReptileBody.GrabbableLimbs.Length];
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			var go = new GameObject( true, "Grip Anchor " + ReptileBody.GrabbableLimbs[i] );
			go.Flags |= GameObjectFlags.NotSaved;
			go.WorldPosition = Player.WorldPosition;

			var body = go.Components.Create<Rigidbody>();
			body.Gravity = false;
			body.MotionEnabled = false; // moved by hand to follow the limb

			var shape = go.Components.Create<SphereCollider>();
			shape.Radius = 2f;
			shape.IsTrigger = true;

			_anchors[i] = go;
		}
	}

	protected override void OnFixedUpdate()
	{
		if ( Scene.IsEditor || !Player.IsValid() || _anchors is null ) return;
		float dt = MathF.Max( Time.Delta, 0.001f );

		// The anchors ride on the limbs.
		var rig = Player.Rig;
		int limbs = Math.Min( _anchors.Length, ReptileBody.GrabbableLimbs.Length );
		for ( int i = 0; i < limbs; i++ )
		{
			if ( !_anchors[i].IsValid() ) continue;
			// On the new model the limbs are real bones; on the old one, the body's own pieces.
			if ( rig.IsValid() && rig.TryLimbTip( ReptileBody.GrabbableLimbs[i], out var tip ) )
				_anchors[i].WorldPosition = tip;
			else
				_anchors[i].WorldPosition = _lizardBody.IsValid() && _lizardBody.Active
					? _lizardBody.LimbTip( ReptileBody.GrabbableLimbs[i] )
					: Player.WorldPosition + Vector3.Up * 20f;
		}

		// The force of the thrashing: how violently the body is changing its motion, plus the
		// mouse being shaken, plus any buck. It holds its peaks for a moment so a sharp jerk counts.
		var velocity = Player.Velocity;
		// Thrashing only counts when it is the player's doing: being jostled by the crowd is not
		// shaking free, and on its own it can never be enough to break a grip.
		bool steering = Input.AnalogMove.Length > 0.1f && !Player.InputLocked;
		float thrash = steering ? MathF.Min( (velocity - _lastVelocity).Length / dt, BreakForce * 0.6f ) : 0f;
		float force = thrash + Input.MouseDelta.Length / dt * MouseShakeForce + _buck;
		_lastVelocity = velocity;
		_buck = MathF.Max( _buck - BuckForce * 5f * dt, 0f );
		ShakeForce = MathF.Max( force, ShakeForce * MathF.Exp( -8f * dt ) );

		if ( Phase != StadiumPhase.Escape )
		{
			Player.SpeedScale = 1f;
			Player.Leash = null;
			Player.ClearView = false;
			return;
		}

		// Holders that are gone let go.
		for ( int i = _grips.Count - 1; i >= 0; i-- )
			if ( !_grips[i].Holder.IsValid() ) { _grips.RemoveAt( i ); if ( _grips.Count == 0 ) Loose(); }

		// One grip at a time takes the strain. Enough force for long enough and it gives; with
		// more hands on, more force is needed, so a pile has to be peeled off one by one.
		if ( _grips.Count > 0 )
		{
			var grip = _grips[0];
			float ratio = ShakeForce / MathF.Max( ForceNeeded, 1f );
			grip.Strain = ratio > 0.5f ? grip.Strain + ratio * StrainRate * dt : MathF.Max( grip.Strain - 0.5f * dt, 0f );

			if ( grip.Strain >= 1f )
			{
				_grips.RemoveAt( 0 );
				GripBroken?.Invoke( grip.Holder );
				Player.Kick( Vector3.Random * 6f );
				if ( _grips.Count == 0 ) Loose();
			}
		}

		// Dragging people about is slow, and a pile holds it to the spot.
		Player.SpeedScale = (Charge.IsValid() ? Charge.SpeedBoost : 1f) / (1f + SlowPerGrip * _grips.Count);
		Player.Leash = Pinned ? _pinPosition : null;
		Player.ClearView = Held;
	}

	// ---- Endings -----------------------------------------------------------------------------

	/// <summary>Called by the Fat Guy when he sits on the pinned lizard.</summary>
	public void FatGuySat()
	{
		if ( Phase != StadiumPhase.Escape || !Player.IsValid() ) return;
		Player.InputLocked = true;
		Player.ForcedWish = null;
		ClearTurn();
		SetPhase( StadiumPhase.GameOver );
	}

	/// <summary>Starts Scene 2 again from the top.</summary>
	public void Restart() => Game.ChangeScene( ScenePath );

	// ---- Flow --------------------------------------------------------------------------------

	SkinWearer _wearer;

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;

		Player = Scene.GetAllComponents<ReptileController>().FirstOrDefault();
		if ( !Player.IsValid() ) return;

		// You arrive as the envoy, already walking.
		_wearer = Player.Components.Get<SkinWearer>();
		var skin = ResourceLibrary.Get<SkinDefinition>( SkinPath );
		if ( _wearer.IsValid() && skin is not null ) _wearer.Wear( skin );

		Player.SetLook( new Angles( 4f, 0f, 0f ) );
		Player.InputLocked = true;
		Player.ForcedWish = Vector3.Forward;

		// Nothing in this hall is below the floor, the stage or the stands.
		Player.FloorHeight = StadiumLayout.GroundHeight;
		Charge = Player.Components.GetOrCreate<LizardCharge>();
		CreateAnchors();
	}

	protected override void OnDestroy()
	{
		// Whatever state the scene was in, the lizard and the clock are handed back as they were found.
		if ( Scene is not null ) Scene.TimeScale = 1f;
		if ( Player.IsValid() )
		{
			Player.InputLocked = false;
			Player.ForcedWish = null;
			Player.SpeedScale = 1f;
			Player.Leash = null;
			Player.ClearView = false;
			Player.FloorHeight = null;
		}
		_grips.Clear();
		_turnHolder = null;

		if ( _anchors is null ) return;
		foreach ( var anchor in _anchors )
			if ( anchor.IsValid() ) anchor.Destroy();
		_anchors = null;
	}

	void SetPhase( StadiumPhase phase )
	{
		if ( phase == Phase ) return;
		Phase = phase;
		TimeInPhase = 0f;
		PhaseChanged?.Invoke( phase );
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || !Player.IsValid() ) return;

		TimeInPhase += Time.Delta;
		if ( _messageLeft > 0f ) _messageLeft -= Time.Delta;

		switch ( Phase )
		{
			case StadiumPhase.FlashIn: UpdateFlashIn(); break;
			case StadiumPhase.Speech: UpdateSpeech(); break;
			case StadiumPhase.Shapeshift: UpdateShapeshift(); break;
			case StadiumPhase.Escape: UpdateEscape(); break;
			case StadiumPhase.GameOver: UpdateGameOver(); break;
			case StadiumPhase.Won:
				// Through the door the floor is gone: down the shaft, into the Sump.
				Fade = MathF.Min( Fade + Time.Delta * 0.6f, 1f );
				if ( TimeInPhase > 2.6f && !_leaving && !string.IsNullOrEmpty( NextScene ) )
				{
					_leaving = true;
					Scene.TimeScale = 1f;
					Game.ChangeScene( NextScene );
				}
				break;
		}
	}

	void UpdateFlashIn()
	{
		// Pure white for a beat, then the eyes adjust: fast at first, then a long tail.
		float t = Math.Clamp( (TimeInPhase - 0.6f) / MathF.Max( FlashInSeconds - 0.6f, 0.1f ), 0f, 1f );
		Flash = MathF.Pow( 1f - t, 2.2f );

		// Stop walking before the end of the carpet whatever happens.
		bool atEnd = Player.WorldPosition.x > StadiumLayout.CarpetEnd.x - 160f;
		if ( TimeInPhase < FlashInSeconds && !atEnd ) return;

		Flash = 0f;
		Player.ForcedWish = null;
		Player.InputLocked = false;
		ShowMessage( "30,000 people are waiting for your speech. You have not written a speech.", 5f );
		SetPhase( StadiumPhase.Speech );
	}

	void UpdateSpeech()
	{
		bool atPodium = Player.WorldPosition.Distance( StadiumLayout.Podium ) < 110f;
		if ( TimeInPhase < SpeechSeconds && !(atPodium && TimeInPhase > 2f) ) return;

		Player.InputLocked = true;
		Player.ForcedWish = null;
		ShowMessage( "Something is wrong with the skin. It is coming off at the back.", 3f );
		SetPhase( StadiumPhase.Shapeshift );
	}

	void UpdateShapeshift()
	{
		// The skin flickers on and off, faster and faster, the lizard showing through.
		float p = ShiftProgress;
		if ( _wearer.IsValid() && _wearer.IsWearing )
		{
			float rate = 3f + 22f * p * p;
			bool human = MathF.Sin( TimeInPhase * rate ) > (p * 1.6f - 0.8f);
			_wearer.ShowSkin( human );
		}

		if ( TimeInPhase < ShapeshiftSeconds ) return;

		if ( _wearer.IsValid() ) { _wearer.ShowSkin( true ); _wearer.Shed(); }
		Player.InputLocked = false;
		ShowMessage( "RUN. Get to the exit. Do not stop to explain.", 4f );
		SetPhase( StadiumPhase.Escape );
	}

	void UpdateEscape()
	{
		// Out through the doorway: the win. Not while a pile has you.
		if ( !Pinned && StadiumLayout.InExit( Player.WorldPosition ) )
		{
			ShowMessage( "You got out. Nobody claps.", 60f );
			Player.InputLocked = true;
			Player.ForcedWish = null;
			_grips.Clear();
			ClearTurn();
			SetPhase( StadiumPhase.Won );
			return;
		}

		// A buck: one sharp heave against whoever is hanging on.
		if ( Held && Input.Pressed( "Jump" ) ) _buck = MathF.Min( _buck + BuckForce, BuckForce * 2f );
	}

	// ---- The crowd's host (ICrowdHost): the stadium's phases and floor, as the crowd asks for them ----

	CrowdPhase ICrowdHost.CrowdPhase =>
		Phase < StadiumPhase.Shapeshift ? CrowdPhase.Waiting
		: Phase == StadiumPhase.Shapeshift ? CrowdPhase.Recoiling
		: Phase == StadiumPhase.Escape ? CrowdPhase.Chasing
		: CrowdPhase.Over;

	Vector3 ICrowdHost.Focus => StadiumLayout.Podium;
	float ICrowdHost.GroundHeight( Vector3 point ) => StadiumLayout.GroundHeight( point );
	bool ICrowdHost.InExit( Vector3 point ) => StadiumLayout.InExit( point );

	/// <summary>The next point on the way out: the mouth of the aisle, then the door.</summary>
	Vector3 ICrowdHost.ExitRoute( Vector3 me )
	{
		float aisle = StadiumLayout.AisleHalfWidth - 40f;
		if ( me.x < StadiumLayout.PitEndX - 50f )
			return new Vector3( StadiumLayout.PitEndX - 20f, Math.Clamp( me.y, -aisle, aisle ), 0f );
		if ( MathF.Abs( me.y ) > aisle )
			return new Vector3( me.x, Math.Clamp( me.y, -aisle * 0.5f, aisle * 0.5f ), 0f ); // in the end stands: sideways into the aisle
		return StadiumLayout.Exit;
	}

	Vector3 ICrowdHost.WanderPoint() => new(
		Game.Random.Float( StadiumLayout.StageFrontX + 80f, StadiumLayout.PitEndX - 60f ),
		Game.Random.Float( -StadiumLayout.PitHalfWidth + 60f, StadiumLayout.PitHalfWidth - 60f ), 0f );

	Vector3 ICrowdHost.Contain( Vector3 p ) => new(
		Math.Clamp( p.x, StadiumLayout.StageFrontX + 40f, StadiumLayout.MaxX - 60f ),
		Math.Clamp( p.y, -StadiumLayout.HalfWidth + 60f, StadiumLayout.HalfWidth - 60f ), p.z );

	void UpdateGameOver()
	{
		// After the crush the cheeks have already closed: it is black from the moment he lands.
		Fade = Cutscene.HasValue ? 1f : Math.Clamp( (TimeInPhase - 1.6f) / 1.4f, 0f, 1f );
		if ( TimeInPhase > CardDelay + 0.4f && (Input.Pressed( "Jump" ) || Input.Pressed( "Use" ) || Input.Pressed( "Attack1" )) ) Restart();
	}
}