Stadium/FatGuy.cs

The Fat Guy hazard in the stadium game. Builds a body out of scaled dev sphere and box models, ambles after the player during the Escape phase, marches straight at a pinned lizard, and when close enough runs a scripted crush cutscene that sets Scene.TimeScale, takes over Scene.Camera and flattens the player. Also has a static cameo mode for flashback scenes.

using System;

/// <summary>
/// The Fat Guy: the one person in the stadium you really don't want to meet. Big, slow and
/// bright pink. He ambles after the lizard while it is loose, marches straight at it while it
/// is pinned, and if he gets there he hops up and sits on it, which is the end of the game.
/// Builds himself out of spheres and boxes at the start; has no physics, and just slides along
/// the pit floor (z = 0).
/// </summary>
[Title( "Fat Guy" ), Category( "Stadium" ), Icon( "airline_seat_recline_extra" )]
public sealed class FatGuy : Component
{
	// ---- Movement ----------------------------------------------------------------------------
	/// <summary>Speed while the lizard is loose, in inches per second.</summary>
	[Property, Group( "Movement" )] public float AmbleSpeed { get; set; } = 45f;

	/// <summary>Speed while the lizard is pinned.</summary>
	[Property, Group( "Movement" )] public float MarchSpeed { get; set; } = 95f;

	/// <summary>How close (level distance) he must be to a pinned lizard to jump on it.</summary>
	[Property, Group( "Movement" )] public float SitRange { get; set; } = 70f;

	/// <summary>Degrees per second he can turn.</summary>
	[Property, Group( "Movement" )] public float TurnSpeed { get; set; } = 140f;

	/// <summary>How far he wanders off the straight line while ambling, in inches.</summary>
	[Property, Group( "Movement" )] public float AmbleWander { get; set; } = 220f;

	// ---- Walk --------------------------------------------------------------------------------
	/// <summary>Inches covered per footstep.</summary>
	[Property, Group( "Walk" )] public float StepLength { get; set; } = 34f;

	/// <summary>Degrees he rolls from side to side as he walks.</summary>
	[Property, Group( "Walk" )] public float WaddleDegrees { get; set; } = 9f;

	/// <summary>How far each step nudges the player's camera while he is marching (0 = off).</summary>
	[Property, Group( "Walk" )] public float StepKick { get; set; } = 2f;

	/// <summary>Beyond this distance his steps don't shake the camera.</summary>
	[Property, Group( "Walk" )] public float StepKickRange { get; set; } = 900f;

	// ---- The sit -----------------------------------------------------------------------------
	[Property, Group( "Sit" )] public float HopHeight { get; set; } = 70f;
	[Property, Group( "Sit" )] public float HopSeconds { get; set; } = 0.6f;

	/// <summary>How hard the landing throws the player's camera down.</summary>
	[Property, Group( "Sit" )] public float SitKick { get; set; } = 30f;

	// ---- Look and sound ----------------------------------------------------------------------
	[Property, Group( "Look" )] public Color SuitColor { get; set; } = new( 1f, 0.08f, 0.58f );
	[Property, Group( "Look" )] public Color SkinColor { get; set; } = new( 0.95f, 0.72f, 0.6f );
	[Property, Group( "Look" )] public Color TrimColor { get; set; } = Color.White;

	[Property, Group( "Sound" )] public string StepSound { get; set; } = "sounds/stadium/fat_step.sound";
	[Property, Group( "Sound" )] public string SitSound { get; set; } = "sounds/stadium/fat_sit.sound";
	[Property, Group( "Sound" ), Range( 0f, 2f )] public float StepVolume { get; set; } = 1f;

	// ---- Cameo (the Sump's flashbacks): he is only there to be seen ----------------------------
	/// <summary>
	/// A walk-on part: he does not chase and never sits on anybody. He stays where he is put,
	/// seated or standing, and only moves if told to with <see cref="CameoWalkTo"/>.
	/// </summary>
	[Property, Group( "Cameo" )] public bool CameoOnly { get; set; }

	/// <summary>In a cameo: sitting down, legs out in front (asleep on a hay bale, eating his lunch).</summary>
	[Property, Group( "Cameo" )] public bool CameoSeated { get; set; }

	/// <summary>In a cameo: sways gently where he is.</summary>
	[Property, Group( "Cameo" )] public bool CameoWobble { get; set; } = true;

	/// <summary>In a cameo: true once he has got to where <see cref="CameoWalkTo"/> sent him (or was never sent).</summary>
	public bool CameoArrived => _cameoGoal is null;

	/// <summary>In a cameo: stands up and waddles to a spot, then stays there.</summary>
	public void CameoWalkTo( Vector3 where )
	{
		CameoSeated = false;
		_cameoGoal = where;
	}

	Vector3? _cameoGoal;

	/// <summary>True once he has landed on the lizard. He never gets up.</summary>
	public bool Sitting { get; private set; }

	/// <summary>True while he is in the air on his way down onto it.</summary>
	public bool Jumping => _state == State.Hopping;

	enum State { Idle, Walking, Hopping, Crushing, Sat }

	// ---- The crush cutscene (seconds are real time: the world is in slow motion for part of it) --
	/// <summary>How high he launches himself before coming down.</summary>
	[Property, Group( "Crush" )] public float CrushHeight { get; set; } = 560f;
	[Property, Group( "Crush" )] public float CrushCrouchSeconds { get; set; } = 0.7f;
	[Property, Group( "Crush" )] public float CrushRiseSeconds { get; set; } = 0.9f;
	[Property, Group( "Crush" )] public float CrushFallSeconds { get; set; } = 2.4f;

	/// <summary>How slow the world runs while he is coming down.</summary>
	[Property, Group( "Crush" ), Range( 0.05f, 1f )] public float CrushSlowMotion { get; set; } = 0.25f;

	GameObject _cheekL, _cheekR;
	float _crushStart;       // real time the cutscene began
	float _crushLanded = -1f; // real time he hit, or below zero while still in the air
	float _cheekSpread;      // 0 = cheeks together, 1 = parted
	Vector3 _crushAt;        // where the lizard is
	Vector3 _crushSide;      // which way the side-on camera sits
	float _lift;             // how high he is, for the camera
	bool _viewCleared;       // the crowd and the lizard's own body are out of the shot
	readonly System.Collections.Generic.List<ModelRenderer> _hidden = new();
	State _state = State.Idle;

	// Proportions. The sphere model has a radius of 32, the box model is a 50-unit cube.
	const float SphereRadius = 32f, BoxSize = 50f;
	static readonly Vector3 BellyScale = new( 1.5f, 1.75f, 1.3f );
	const float LegHeight = 22f;

	StadiumGame _game;
	GameObject _body, _belly, _head, _band, _stripe, _legL, _legR, _armL, _armR;
	float _yaw = 180f;       // facing the stage
	float _stride;           // footsteps walked, as a running count
	float _squash;           // 1 = flattened by a landing, 0 = round
	float _fold;             // 0 = legs under him, 1 = legs out in front (sitting)
	float _wanderSeed;
	TimeSince _sinceHop;
	Vector3 _hopFrom, _hopTo;
	bool _rebuilding;

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

		GameObject.Tags.Add( "fatguy" );
		if ( CameoOnly ) _yaw = WorldRotation.Angles().yaw;   // stays where he was put, facing as he was put
		else WorldPosition = StadiumLayout.FatGuyStart;
		WorldRotation = Rotation.FromYaw( _yaw );
		_wanderSeed = Game.Random.Float( 0f, 100f );
		Build();
	}

	protected override void OnDisabled() => EndCutscene();

	protected override void OnDestroy()
	{
		EndCutscene();
		if ( _body.IsValid() ) _body.Destroy();
		_body = null;
	}

	/// <summary>
	/// Gives back everything the crush took, if he goes away part-way through it (a restart, a
	/// scene change): the clock, the camera's lens, the lizard's hidden body and its shape.
	/// </summary>
	void EndCutscene()
	{
		if ( _state != State.Crushing && _crushLanded < 0f ) return;

		if ( Scene is not null )
		{
			if ( _state == State.Crushing ) Scene.TimeScale = 1f;
			var cam = Scene.Camera;
			if ( cam.IsValid() && _savedFov > 0f ) cam.FieldOfView = _savedFov;
		}
		_savedFov = 0f;
		ShowTheLizard();

		var player = _game?.Player;
		if ( player.IsValid() ) player.GameObject.WorldScale = Vector3.One;
	}

	float _savedFov;   // the camera's own field of view, taken when the cutscene first changes it

	// ---- Building ----------------------------------------------------------------------------

	void Build()
	{
		if ( _body.IsValid() ) _body.Destroy();

		// Everything hangs off one pivot at his feet, so the waddle, the hop and the sit move him whole.
		_body = new GameObject( GameObject, true, "Fat Guy Body" );
		_body.Flags |= GameObjectFlags.NotSaved;

		_belly = Part( "Belly", "models/dev/sphere.vmdl", SuitColor );
		_stripe = Part( "Zip", "models/dev/box.vmdl", TrimColor );
		_head = Part( "Head", "models/dev/sphere.vmdl", SkinColor );
		_band = Part( "Sweatband", "models/dev/box.vmdl", SuitColor );
		_legL = Part( "Left Leg", "models/dev/box.vmdl", SuitColor );
		_legR = Part( "Right Leg", "models/dev/box.vmdl", SuitColor );
		_armL = Part( "Left Arm", "models/dev/box.vmdl", SuitColor );
		_armR = Part( "Right Arm", "models/dev/box.vmdl", SuitColor );

		// The business end. Only shown for the crush.
		var seat = new Color( SuitColor.r * 0.8f, SuitColor.g * 0.8f, SuitColor.b * 0.8f );
		_cheekL = Part( "Left Cheek", "models/dev/sphere.vmdl", seat );
		_cheekR = Part( "Right Cheek", "models/dev/sphere.vmdl", seat );
		_cheekL.Enabled = _cheekR.Enabled = false;

		_head.LocalScale = 0.42f;
		_band.LocalScale = new Vector3( 28f, 28f, 5f ) / BoxSize;
		_legL.LocalScale = _legR.LocalScale = new Vector3( 20f, 20f, LegHeight ) / BoxSize;
		_armL.LocalScale = _armR.LocalScale = new Vector3( 16f, 16f, 34f ) / BoxSize;

		Pose( 0f, 0f, 0f );
	}

	GameObject Part( string name, string model, Color tint )
	{
		var go = new GameObject( _body, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.Tags.Add( "fatguy" );
		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = Model.Load( model );
		renderer.Tint = tint;
		return go;
	}

	/// <summary>
	/// Puts every part where it belongs. <paramref name="lift"/> raises the whole body (the hop),
	/// <paramref name="roll"/> tips it sideways (the waddle), <paramref name="swing"/> is -1..1
	/// through a pair of steps and lifts each foot in turn.
	/// </summary>
	void Pose( float lift, float roll, float swing )
	{
		if ( !_body.IsValid() ) return;

		// Every part is needed below. If any has gone (a hotload, something clearing children),
		// build him again rather than fail on every frame.
		if ( !_belly.IsValid() || !_stripe.IsValid() || !_head.IsValid() || !_band.IsValid()
			|| !_legL.IsValid() || !_legR.IsValid() || !_armL.IsValid() || !_armR.IsValid() )
		{
			if ( _rebuilding ) return;
			_rebuilding = true;
			Build();
			_rebuilding = false;
			return;
		}

		_body.LocalPosition = Vector3.Up * lift;
		_body.LocalRotation = Rotation.From( 0f, 0f, roll );

		// The belly: wider and flatter when squashed, and a slow wobble all the time.
		float wobble = MathF.Sin( Time.Now * 1.7f ) * 0.035f;
		float flat = _squash * 0.45f + wobble;
		var scale = new Vector3( BellyScale.x * (1f + flat * 0.6f), BellyScale.y * (1f + flat * 0.8f), BellyScale.z * (1f - flat) );
		float halfHeight = SphereRadius * scale.z;
		float halfWidth = SphereRadius * scale.y;
		float halfDepth = SphereRadius * scale.x;

		// Standing, the belly hangs just over the legs; sitting, it is on the ground.
		float bottom = Lerp( LegHeight - 8f, 0f, _fold );
		float centre = bottom + halfHeight;

		_belly.LocalPosition = Vector3.Up * centre;
		_belly.LocalScale = scale;

		if ( _cheekL.IsValid() && _cheekL.Enabled )
		{
			float apart = 15f + 9f * _cheekSpread;
			// Big, and hanging well below the belly, so from underneath they are the whole view.
			float size = 0.85f * (1f + _squash * 0.25f);
			apart += 5f;
			float drop = _state == State.Crushing ? -6f : SphereRadius * size * 0.5f;
			_cheekL.LocalPosition = new Vector3( -2f, apart, bottom + drop );
			_cheekR.LocalPosition = new Vector3( -2f, -apart, bottom + drop );
			_cheekL.LocalScale = _cheekR.LocalScale = new Vector3( size * 1.15f, size, size * 0.9f );
		}

		// The zip: a white stripe down the front of the tracksuit.
		_stripe.LocalPosition = new Vector3( halfDepth - 3f, 0f, centre );
		_stripe.LocalScale = new Vector3( 8f, 7f, halfHeight * 1.1f ) / BoxSize;

		float headZ = centre + halfHeight * 0.9f + 10f;
		_head.LocalPosition = new Vector3( 4f, 0f, headZ );
		_band.LocalPosition = new Vector3( 4f, 0f, headZ + 6f );

		// Legs: under him when standing (lifting in turn as he walks), stuck out in front when sitting.
		float liftL = MathF.Max( swing, 0f ) * 9f * (1f - _fold);
		float liftR = MathF.Max( -swing, 0f ) * 9f * (1f - _fold);
		var legRotation = Rotation.From( -90f * _fold, 0f, 0f );
		_legL.LocalPosition = Vector3.Lerp( new Vector3( 0f, 24f, LegHeight * 0.5f + liftL ), new Vector3( halfDepth + 4f, 30f, 10f ), _fold );
		_legR.LocalPosition = Vector3.Lerp( new Vector3( 0f, -24f, LegHeight * 0.5f + liftR ), new Vector3( halfDepth + 4f, -30f, 10f ), _fold );
		_legL.LocalRotation = _legR.LocalRotation = legRotation;

		// Arms: short, sticking out at the sides; they fly up in the air during the hop.
		float raise = Math.Clamp( lift / MathF.Max( HopHeight, 1f ), 0f, 1f ) * 70f + swing * 8f;
		_armL.LocalPosition = new Vector3( 0f, halfWidth + 3f, centre + 10f );
		_armR.LocalPosition = new Vector3( 0f, -halfWidth - 3f, centre + 10f );
		if ( _state == State.Crushing && _fold > 0.5f )
		{
			_legL.LocalPosition = new Vector3( 6f, halfWidth + 22f, centre );
			_legR.LocalPosition = new Vector3( 6f, -halfWidth - 22f, centre );
			_legL.LocalRotation = Rotation.From( 0f, 0f, -80f );
			_legR.LocalRotation = Rotation.From( 0f, 0f, 80f );
			raise = 80f;
		}
		_armL.LocalRotation = Rotation.From( 0f, 0f, -35f - raise );
		_armR.LocalRotation = Rotation.From( 0f, 0f, 35f + raise );
	}

	// ---- Behaviour ---------------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || !_body.IsValid() ) return;
		if ( CameoOnly ) { Cameo(); return; }

		_game ??= StadiumGame.Get( Scene );

		// The belly springs back from a landing, but stays a bit spread while he sits.
		if ( _state != State.Crushing && _crushLanded < 0f )
			_squash = Lerp( _squash, Sitting ? 0.35f : 0f, Math.Clamp( Time.Delta * 5f, 0f, 1f ) );
		if ( _state != State.Crushing )
			_fold = Lerp( _fold, Sitting ? 1f : 0f, Math.Clamp( Time.Delta * 14f, 0f, 1f ) );

		switch ( _state )
		{
			case State.Idle:
				if ( _game is not null && _game.Phase == StadiumPhase.Escape ) _state = State.Walking;
				Pose( 0f, 0f, 0f );
				break;

			case State.Walking: Walk(); break;
			case State.Hopping: Hop(); break;
			case State.Crushing: Crush(); break;
			case State.Sat: if ( _crushLanded >= 0f ) Grind(); else Pose( 0f, 0f, 0f ); break;
		}
	}

	/// <summary>The walk-on part: sits or stands where he is, swaying, or waddles to where he was sent.</summary>
	void Cameo()
	{
		float dt = Time.Delta;
		_squash = Lerp( _squash, CameoSeated ? 0.35f : 0f, Math.Clamp( dt * 5f, 0f, 1f ) );
		_fold = Lerp( _fold, CameoSeated ? 1f : 0f, Math.Clamp( dt * 6f, 0f, 1f ) );

		if ( _cameoGoal is { } goal && !CameoSeated )
		{
			var to = (goal - WorldPosition).WithZ( 0f );
			if ( to.Length < 8f ) _cameoGoal = null;
			else
			{
				float wantYaw = MathF.Atan2( to.y, to.x ) * (180f / MathF.PI);
				float difference = AngleDifference( _yaw, wantYaw );
				_yaw += Math.Clamp( difference, -TurnSpeed * dt, TurnSpeed * dt );
				float facing = MathF.Max( MathF.Cos( difference * (MathF.PI / 180f) ), 0.15f );
				float moved = MathF.Min( AmbleSpeed * 1.4f * facing * dt, to.Length );
				WorldPosition += Rotation.FromYaw( _yaw ).Forward * moved;
				WorldRotation = Rotation.FromYaw( _yaw );

				float before = _stride;
				_stride += moved / MathF.Max( StepLength, 1f );
				if ( MathF.Floor( _stride ) > MathF.Floor( before ) ) Step( false, null );

				float swing = MathF.Sin( _stride * MathF.PI );
				Pose( MathF.Abs( swing ) * 2.5f, swing * WaddleDegrees, swing );
				return;
			}
		}

		float sway = CameoWobble ? MathF.Sin( Time.Now * 1.3f + _wanderSeed ) * (CameoSeated ? 3.5f : 2f) : 0f;
		Pose( 0f, sway, 0f );
	}

	void Walk()
	{
		var player = _game?.Player;
		if ( _game is null || _game.Phase != StadiumPhase.Escape || !player.IsValid() )
		{
			// The chase is over (won, or the scene is ending): he stops where he is.
			_state = State.Idle;
			return;
		}

		bool pinned = _game.Pinned;
		var goal = player.WorldPosition.WithZ( 0f );
		var toPlayer = goal - WorldPosition.WithZ( 0f );

		// The arena is vast and he is slow: he is never further off than this, pinned or not.
		float furthest = pinned ? 900f : 2200f;
		if ( toPlayer.Length > furthest * 1.25f )
		{
			WorldPosition = (goal - toPlayer.Normal * furthest).WithZ( 0f );
			toPlayer = goal - WorldPosition.WithZ( 0f );
		}

		// Close enough to a pinned lizard: up he goes.
		if ( pinned && toPlayer.Length <= SitRange )
		{
			StartHop( player.WorldPosition );
			return;
		}

		// Loose lizard: he only heads roughly the right way, drifting from side to side.
		if ( !pinned && toPlayer.Length > 1f )
		{
			var side = new Vector3( -toPlayer.y, toPlayer.x, 0f ).Normal;
			float drift = MathF.Sin( Time.Now * 0.23f + _wanderSeed ) * MathF.Min( AmbleWander, toPlayer.Length * 0.6f );
			goal += side * drift;
		}

		var to = goal - WorldPosition.WithZ( 0f );
		float speed = pinned ? MarchSpeed : AmbleSpeed;
		float moved = 0f;

		if ( to.Length > 4f )
		{
			// Turn toward where he is going, and walk the way he faces: he corners like a barge.
			float wantYaw = MathF.Atan2( to.y, to.x ) * (180f / MathF.PI);
			float difference = AngleDifference( _yaw, wantYaw );
			_yaw += Math.Clamp( difference, -TurnSpeed * Time.Delta, TurnSpeed * Time.Delta );

			float facing = MathF.Max( MathF.Cos( difference * (MathF.PI / 180f) ), 0.15f );
			var forward = Rotation.FromYaw( _yaw ).Forward;
			var next = Contain( WorldPosition + forward * speed * facing * Time.Delta, WorldPosition );
			moved = (next - WorldPosition).Length;
			WorldPosition = next;
			WorldRotation = Rotation.FromYaw( _yaw );
		}

		// Footsteps: every StepLength inches a foot comes down.
		float before = _stride;
		_stride += moved / MathF.Max( StepLength, 1f );
		if ( MathF.Floor( _stride ) > MathF.Floor( before ) ) Step( pinned, player );

		float swing = MathF.Sin( _stride * MathF.PI );
		Pose( MathF.Abs( swing ) * 2.5f, swing * WaddleDegrees * (pinned ? 1.3f : 1f), swing );
	}

	void Step( bool marching, ReptileController player )
	{
		var step = StorySound.Play( StepSound, WorldPosition + Vector3.Up * 10f );
		if ( step.IsValid() ) step.Volume *= StepVolume * (marching ? 1f : 0.6f);

		// The floor shakes as he comes for you: stronger the closer he is.
		if ( !marching || StepKick <= 0f || !player.IsValid() ) return;
		float near = 1f - Math.Clamp( player.WorldPosition.Distance( WorldPosition ) / MathF.Max( StepKickRange, 1f ), 0f, 1f );
		if ( near > 0f ) player.Kick( Vector3.Down * StepKick * (0.4f + 0.6f * near) );
	}

	/// <summary>Keeps him on the pit floor: off the stage, out of the stands, and inside the aisle past the pit.</summary>
	static Vector3 Contain( Vector3 next, Vector3 from )
	{
		const float margin = 70f;
		float aisle = StadiumLayout.AisleHalfWidth - 60f;
		float pitEnd = StadiumLayout.PitEndX - margin;

		next.z = 0f;
		next.x = MathF.Max( next.x, StadiumLayout.StageFrontX + margin );

		if ( from.x > pitEnd )
		{
			// Already in the aisle: stay between the end stands.
			next.y = Math.Clamp( next.y, -aisle, aisle );
			next.x = MathF.Min( next.x, StadiumLayout.MaxX - margin );
		}
		else
		{
			next.y = Math.Clamp( next.y, -StadiumLayout.PitHalfWidth + margin, StadiumLayout.PitHalfWidth - margin );
			if ( MathF.Abs( next.y ) > aisle ) next.x = MathF.Min( next.x, pitEnd );
		}
		return next;
	}

	// ---- The sit -----------------------------------------------------------------------------

	void StartHop( Vector3 onto )
	{
		StartCrush( onto );
	}

	// ---- The crush: the long way down ---------------------------------------------------------

	/// <summary>
	/// He has a pinned lizard at his feet. From here it is a cutscene and there is no way out:
	/// a crouch, a launch far too high, then the slow fall seen from underneath as the two cheeks
	/// fill the sky, the landing, and a side-on look at what is left.
	/// </summary>
	void StartCrush( Vector3 onto )
	{
		_state = State.Crushing;
		_crushStart = RealTime.Now;
		_crushLanded = -1f;
		_crushAt = onto.WithZ( StadiumLayout.GroundHeight( onto ) );
		_hopFrom = WorldPosition;

		var to = (_crushAt - WorldPosition).WithZ( 0f );
		if ( to.Length > 1f ) _yaw = MathF.Atan2( to.y, to.x ) * (180f / MathF.PI);
		WorldRotation = Rotation.FromYaw( _yaw );
		var forward = WorldRotation.Forward;
		_crushSide = new Vector3( -forward.y, forward.x, 0f );

		var player = _game?.Player;
		if ( player.IsValid() ) player.InputLocked = true;
		if ( _cheekL.IsValid() ) _cheekL.Enabled = _cheekR.Enabled = true;
		if ( _game is not null ) _game.Cutscene = _crushAt;
		_viewCleared = false;
	}

	/// <summary>
	/// Nothing comes between the lizard's eyes and what is descending on them: the people piled on
	/// it are blown clear by his take-off, anyone left close is taken out of the picture, and the
	/// lizard's own body (the camera is inside it) is not drawn until he lands.
	/// </summary>
	void ClearTheView()
	{
		_viewCleared = true;
		float now = Time.Now;
		foreach ( var person in Scene.GetAllComponents<CrowdPerson>() )
		{
			var away = (person.WorldPosition - _crushAt).WithZ( 0f );
			float distance = away.Length;
			if ( distance > 420f ) continue;
			if ( distance < 190f ) { person.GameObject.Enabled = false; continue; }
			person.Bowl( away / distance * 520f + Vector3.Up * 260f, now );
		}

		var player = _game?.Player;
		if ( !player.IsValid() ) return;
		foreach ( var renderer in player.GameObject.Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
		{
			if ( !renderer.Enabled ) continue;
			renderer.Enabled = false;
			_hidden.Add( renderer );
		}
	}

	void ShowTheLizard()
	{
		foreach ( var renderer in _hidden )
			if ( renderer.IsValid() ) renderer.Enabled = true;
		_hidden.Clear();
	}

	void Crush()
	{
		float t = RealTime.Now - _crushStart;
		float rise = CrushCrouchSeconds + CrushRiseSeconds;

		if ( t < CrushCrouchSeconds )
		{
			// The crouch: he gathers himself, belly spreading, right over it.
			float k = t / CrushCrouchSeconds;
			_squash = k;
			WorldPosition = Vector3.Lerp( _hopFrom, _crushAt, k * 0.6f );
			_lift = 0f;
			_cheekSpread = 0f;
			Pose( 0f, MathF.Sin( t * 40f ) * 2f * k, 0f );
			return;
		}

		if ( t < rise )
		{
			// Up. Far too high.
			float k = (t - CrushCrouchSeconds) / CrushRiseSeconds;
			_squash = 0f;
			WorldPosition = Vector3.Lerp( _hopFrom, _crushAt, 0.6f + 0.4f * k );
			_lift = CrushHeight * (1f - (1f - k) * (1f - k));
			Pose( _lift, 0f, 0f );
			return;
		}

		if ( !_viewCleared ) ClearTheView();

		// Down, in slow motion: legs out, cheeks parting as they arrive.
		float fall = Math.Clamp( (t - rise) / MathF.Max( CrushFallSeconds, 0.1f ), 0f, 1f );
		Scene.TimeScale = CrushSlowMotion;
		WorldPosition = _crushAt;
		_fold = 1f;
		_cheekSpread = fall;
		_lift = CrushHeight * (1f - fall * fall);

		// The dark closes in as the cheeks do, and is complete at the instant they clap shut on it.
		if ( _game is not null ) _game.CrushFade = Math.Clamp( (fall - 0.55f) / 0.45f, 0f, 1f );
		Pose( _lift, MathF.Sin( t * 3f ) * 4f, 0f );
		if ( fall < 1f ) return;

		// Contact.
		if ( _game is not null ) _game.CrushFade = 1f;
		ShowTheLizard();
		Scene.TimeScale = 1f;
		_crushLanded = RealTime.Now;
		_lift = 0f;
		_squash = 1f;
		Sitting = true;
		_state = State.Sat;
		StorySound.Play( SitSound, WorldPosition );

		var player = _game?.Player;
		if ( player.IsValid() ) player.Kick( Vector3.Down * SitKick );
		_game?.FatGuySat();
	}

	/// <summary>Sat on it: the cheeks close, and he settles in with a slow grind from side to side.</summary>
	void Grind()
	{
		float since = RealTime.Now - _crushLanded;
		_cheekSpread = MathF.Max( 1f - since * 2.5f, 0f );
		_squash = 0.35f + 0.65f * MathF.Exp( -since * 3f ) + MathF.Sin( since * 5f ) * 0.08f;
		WorldRotation = Rotation.FromYaw( _yaw + MathF.Sin( since * 4f ) * 14f * MathF.Min( since, 1f ) );
		Pose( 0f, MathF.Sin( since * 4f ) * 5f, 0f );

		// What is underneath goes flat and wide.
		var player = _game?.Player;
		if ( player.IsValid() )
		{
			float flat = Math.Clamp( since * 8f, 0f, 1f );
			player.GameObject.WorldScale = new Vector3( 1f + 0.9f * flat, 1f + 0.9f * flat, 1f - 0.9f * flat );
		}
	}

	/// <summary>The cutscene's camera, set after everything else has had its say.</summary>
	protected override void OnPreRender()
	{
		if ( Scene.IsEditor || (_state != State.Crushing && _crushLanded < 0f) ) return;
		var cam = Scene.Camera;
		if ( !cam.IsValid() ) return;

		float t = RealTime.Now - _crushStart;
		float rise = CrushCrouchSeconds + CrushRiseSeconds;
		var forward = Rotation.FromYaw( _yaw ).Forward;
		if ( _savedFov <= 0f ) _savedFov = cam.FieldOfView;

		// No cut after he lands: the view stays the lizard's own, under him, in the dark.
		if ( _crushLanded >= 0f )
		{
			cam.WorldPosition = _crushAt + Vector3.Up * 6f;
			cam.WorldRotation = Rotation.LookAt( Vector3.Up, forward );
			return;
		}

		if ( t < rise )
		{
			// Wide and low from beside the lizard, tilting up after him as he goes.
			var eye = _crushAt + _crushSide * 150f - forward * 120f + Vector3.Up * 18f;
			var look = WorldPosition + Vector3.Up * (60f + _lift);
			cam.WorldPosition = eye;
			cam.WorldRotation = Rotation.LookAt( (look - eye).Normal, Vector3.Up );
			cam.FieldOfView = 75f;
			return;
		}

		// The lizard's own view, flat on its back, straight up at what is coming. It shudders
		// harder the nearer he gets.
		float near = 1f - Math.Clamp( _lift / MathF.Max( CrushHeight, 1f ), 0f, 1f );
		cam.WorldPosition = _crushAt + Vector3.Up * 6f + Vector3.Random * (3f * near * near);
		cam.WorldRotation = Rotation.LookAt( Vector3.Up, forward ) * Rotation.From( 0f, 0f, MathF.Sin( t * 2f ) * 3f );
		cam.FieldOfView = 95f - 20f * near;
	}

	void OldHop( Vector3 onto )
	{
		_state = State.Hopping;
		_sinceHop = 0f;
		_hopFrom = WorldPosition;
		_hopTo = onto;

		var to = (onto - WorldPosition).WithZ( 0f );
		if ( to.Length > 1f ) _yaw = MathF.Atan2( to.y, to.x ) * (180f / MathF.PI);
		WorldRotation = Rotation.FromYaw( _yaw );
	}

	void Hop()
	{
		float t = Math.Clamp( _sinceHop / MathF.Max( HopSeconds, 0.05f ), 0f, 1f );
		WorldPosition = Vector3.Lerp( _hopFrom, _hopTo, t );
		Pose( MathF.Sin( t * MathF.PI ) * HopHeight, 0f, 0f );
		if ( t < 1f ) return;

		// Down. Whatever is underneath, the floor knows about it.
		_squash = 1f;
		StorySound.Play( SitSound, WorldPosition );

		var player = _game?.Player;
		bool caught = _game is not null && _game.Phase == StadiumPhase.Escape && _game.Pinned;
		if ( player.IsValid() ) player.Kick( Vector3.Down * SitKick * (caught ? 1f : 0.4f) );

		if ( caught )
		{
			Sitting = true;
			_state = State.Sat;
			_game.FatGuySat();
		}
		else
		{
			// It wriggled out while he was in the air. Back on his feet (the floor is z = 0) and after it.
			WorldPosition = WorldPosition.WithZ( 0f );
			_state = State.Walking;
		}
	}

	// ---- Small maths -------------------------------------------------------------------------

	static float Lerp( float a, float b, float t ) => a + (b - a) * t;

	/// <summary>Shortest way round from one yaw to another, in degrees (-180..180).</summary>
	static float AngleDifference( float from, float to )
	{
		float d = (to - from) % 360f;
		if ( d > 180f ) d -= 360f;
		if ( d < -180f ) d += 360f;
		return d;
	}
}