Sump/Finale/FinaleCells.cs

The grip host and cell bookkeeping for the Sump finale. FinaleCellHost implements ICrowdHost, spawns five invisible grip anchors that ride around the lizard, tracks up to one grip per cell with strain, pinning, speed slow and leash state, and can drop or calm everything at once. FinaleCell wraps a CrowdPerson with home spot, chase and pale-out state plus a Spawn factory.

using System;
using System.Collections.Generic;

/// <summary>
/// The host of the humans in the deep layers and the heart: what <see cref="StadiumGame"/> is to
/// the stadium and <see cref="FlashbackCrowd"/> to a memory. The people are the stadium's own
/// <see cref="CrowdPerson"/> and grab, pin and pile on exactly as they do there (the grip numbers
/// are the stadium's). What is different down here is <see cref="Calm"/>: when the player stops
/// "not belonging", everybody holding on simply lets go, without being thrown.
/// Sits on the layer's root, so it goes when the layer goes.
/// </summary>
[Title( "Finale Cells" ), Category( "Sump" ), Icon( "bubble_chart" )]
public sealed class FinaleCellHost : Component, ICrowdHost
{
	// ---- Grips (the stadium's numbers) ----------------------------------------------------------
	[Property, Group( "Grips" )] public float BreakForce { get; set; } = 5200f;
	[Property, Group( "Grips" )] public float ForcePerExtraGrip { get; set; } = 0.35f;
	[Property, Group( "Grips" )] public float StrainRate { get; set; } = 3.2f;
	[Property, Group( "Grips" )] public float BuckForce { get; set; } = 5200f;
	[Property, Group( "Grips" )] public float MouseShakeForce { get; set; } = 1.2f;
	/// <summary>With this many grips on, the player is pinned to the spot.</summary>
	[Property, Group( "Grips" )] public int PinGrips { get; set; } = 2;
	[Property, Group( "Grips" )] public float SlowPerGrip { get; set; } = 0.45f;
	/// <summary>Seconds after the last grip goes during which nobody can grab.</summary>
	[Property, Group( "Grips" )] public float FreeSeconds { get; set; } = 1.5f;
	/// <summary>Seconds the cells stand slack after losing interest.</summary>
	[Property, Group( "Grips" )] public float CalmSeconds { get; set; } = 0.5f;

	/// <summary>True while the layer is being played: the cells move. False: they are statues.</summary>
	public bool Live { get; set; }
	public ReptileController Player { get; set; }

	// ---- The floor they stand on ----------------------------------------------------------------
	public Vector3 Centre { get; set; }
	public float HalfX { get; set; } = 1000f;
	public float HalfY { get; set; } = 1000f;
	public float FloorZ { get; set; }

	sealed class Grip
	{
		public GameObject Holder;
		public int Limb;
		public float Strain;
	}

	readonly List<Grip> _grips = new();
	GameObject[] _anchors;
	TimeSince _sinceFree = 100f;
	float _graceUntil, _calmUntil;
	Vector3 _pinPosition;
	Vector3 _lastVelocity;
	float _buck;

	// Where the hands find something to hold, round the lizard (its own frame).
	static readonly Vector3[] AnchorOffsets =
	{
		new( 14f, 12f, 14f ), new( 14f, -12f, 14f ), new( -12f, 12f, 12f ), new( -12f, -12f, 12f ), new( -22f, 0f, 14f ),
	};

	public int Grabbers => _grips.Count;
	public bool Held => _grips.Count > 0;
	public bool Pinned => _grips.Count >= PinGrips;
	/// <summary>How long the player has been pinned without a break, in seconds.</summary>
	public float PinnedSeconds { get; private set; }
	public float ShakeForce { get; private set; }
	public float ForceNeeded => BreakForce * (1f + ForcePerExtraGrip * MathF.Max( _grips.Count - 1, 0 ));
	public bool Slippery => _sinceFree < FreeSeconds || Time.Now < _graceUntil;

	public event Action<GameObject> GripBroken;

	// ---- ICrowdHost -----------------------------------------------------------------------------
	// "Over" is what makes a holder let go quietly (see CrowdPerson.HangOn), so that is what the
	// crowd is told for a moment whenever it loses interest.
	public CrowdPhase CrowdPhase => !Live ? CrowdPhase.Waiting : Time.Now < _calmUntil ? CrowdPhase.Over : CrowdPhase.Chasing;
	public float ShiftProgress => 1f;
	public Vector3 Focus => Centre;
	public float GroundHeight( Vector3 point ) => FloorZ;
	public bool InExit( Vector3 point ) => false;
	public Vector3 ExitRoute( Vector3 from ) => WanderPoint();
	public Vector3 WanderPoint() => Centre + new Vector3( Game.Random.Float( -HalfX, HalfX ) * 0.8f, Game.Random.Float( -HalfY, HalfY ) * 0.8f, 0f );
	public Vector3 Contain( Vector3 p ) => new(
		Math.Clamp( p.x, Centre.x - HalfX + 40f, Centre.x + HalfX - 40f ),
		Math.Clamp( p.y, Centre.y - HalfY + 40f, Centre.y + HalfY - 40f ), p.z );

	public bool TryGrab( GameObject holder, out GameObject anchor )
	{
		anchor = null;
		if ( CrowdPhase != CrowdPhase.Chasing || Slippery || !Player.IsValid() || !holder.IsValid() || _anchors is null ) 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 == PinGrips ) _pinPosition = Player.WorldPosition;
		return true;
	}

	public void ReleaseGrab( GameObject holder )
	{
		int removed = _grips.RemoveAll( g => g.Holder == holder );
		if ( removed > 0 && _grips.Count == 0 ) _sinceFree = 0;
	}

	/// <summary>Everybody loses interest: holders let go without a struggle and nobody grabs for a while.</summary>
	public void Calm( float graceSeconds = 3f )
	{
		_calmUntil = Time.Now + CalmSeconds;
		Grace( graceSeconds );
	}

	/// <summary>Every grip is dropped at once, with no throwing (the player is being moved).</summary>
	public void DropAll()
	{
		_grips.Clear();
		PinnedSeconds = 0f;
		_sinceFree = 0;
		_calmUntil = Time.Now + CalmSeconds;
		FreePlayer();
	}

	/// <summary>Nobody can grab for this many seconds.</summary>
	public void Grace( float seconds ) => _graceUntil = MathF.Max( _graceUntil, Time.Now + seconds );

	/// <summary>Takes the player on: makes the things the hands hold on to.</summary>
	public void Adopt( ReptileController player )
	{
		Player = player;
		CrowdHosts.Fallback = this;
		if ( _anchors is not null || !player.IsValid() ) return;

		_anchors = new GameObject[AnchorOffsets.Length];
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			var go = new GameObject( GameObject, true, "Grip Anchor " + 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 body

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

			_anchors[i] = go;
		}
	}

	protected override void OnUpdate()
	{
		// A buck: one sharp heave against whoever is holding on. It works. It is not the point.
		if ( Held && Input.Pressed( "Jump" ) ) _buck = MathF.Min( _buck + BuckForce, BuckForce * 2f );
	}

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

		// The anchors ride round the body.
		var at = Player.WorldPosition;
		var turn = Rotation.FromYaw( Player.WorldRotation.Angles().yaw );
		for ( int i = 0; i < _anchors.Length; i++ )
			if ( _anchors[i].IsValid() ) _anchors[i].WorldPosition = at + turn * AnchorOffsets[i];

		// The force of the thrashing, as in the stadium.
		var velocity = Player.Velocity;
		float force = (velocity - _lastVelocity).Length / dt + 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 ( !Live )
		{
			if ( _grips.Count > 0 ) DropAll();
			PinnedSeconds = 0f;
			return;
		}

		// Holders that are gone (or frozen by a price tag) let go.
		for ( int i = _grips.Count - 1; i >= 0; i-- )
		{
			var holder = _grips[i].Holder;
			if ( holder.IsValid() && !holder.Tags.Has( Patchwork.PricedTag ) ) continue;
			_grips.RemoveAt( i );
			if ( _grips.Count == 0 ) _sinceFree = 0;
		}

		// One grip at a time takes the strain.
		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 ) _sinceFree = 0;
			}
		}

		Player.SpeedScale = 1f / (1f + SlowPerGrip * _grips.Count);
		Player.Leash = Pinned ? _pinPosition : null;
		Player.ClearView = Held;
		PinnedSeconds = Pinned ? PinnedSeconds + dt : MathF.Max( PinnedSeconds - dt * 2f, 0f );
	}

	void FreePlayer()
	{
		if ( !Player.IsValid() ) return;
		Player.Leash = null;
		Player.SpeedScale = 1f;
		Player.ClearView = false;
	}

	protected override void OnDestroy()
	{
		if ( ReferenceEquals( CrowdHosts.Fallback, this ) ) CrowdHosts.Fallback = null;
		_grips.Clear();
		FreePlayer();
	}
}

/// <summary>
/// One of the planet's cells: a pale, silent human (a <see cref="CrowdPerson"/>) with the little
/// extra the finale needs to know about it. It drifts until something that does not belong comes
/// near; what it does then is decided by the layer, which only flips the person between passive
/// (drift, or walk to a spot) and not passive (come for the player).
/// </summary>
public sealed class FinaleCell
{
	public CrowdPerson Person;
	/// <summary>Which chamber it came out of.</summary>
	public int Chamber;
	/// <summary>The middle of the patch it drifts about in, and how far it strays.</summary>
	public Vector3 Home;
	public float Roam = 600f;
	/// <summary>True while it is after the player.</summary>
	public bool Chasing;
	/// <summary>The misfit it has been sent to fetch, or null.</summary>
	public FinaleFollower Prey;
	/// <summary>Part of a wall of cells: stands at <see cref="Spot"/> and never chases.</summary>
	public bool Standing;
	public Vector3 Spot;
	public float Born;
	public float NextWander;
	public bool Paled;

	public bool Alive => Person.IsValid() && Person.State != CrowdState.Dead;
	/// <summary>False while a price tag has it frozen.</summary>
	public bool Awake => Alive && Person.Enabled && !Person.GameObject.Tags.Has( Patchwork.PricedTag );
	public Vector3 Position => Person.IsValid() ? Person.WorldPosition : Home;
	public Vector3 Eye => Position + Vector3.Up * 60f;
	public Vector3 Facing => Person.IsValid() ? Person.WorldRotation.Forward : Vector3.Forward;

	/// <summary>Bleaches the clothes and skin it was given, once its body has been built.</summary>
	public void Pale( Color pale, float amount )
	{
		if ( Paled || !Person.IsValid() || Time.Now < Born + 0.25f ) return;
		Paled = true;
		foreach ( var renderer in Person.GameObject.Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
			renderer.Tint = Color.Lerp( renderer.Tint, pale, amount );
	}

	/// <summary>Drift (or walk) to a spot, not interested in the player.</summary>
	public void GoTo( Vector3 spot, float speed, Vector3? lookAt = null )
	{
		if ( !Person.IsValid() ) return;
		Person.Passive = true;
		Person.GoTo = spot;
		Person.PassiveSpeed = speed;
		Person.LookAt = lookAt;
		Chasing = false;
	}

	/// <summary>Come for the player.</summary>
	public void Chase()
	{
		if ( !Person.IsValid() ) return;
		Person.Passive = false;
		Chasing = true;
	}

	/// <summary>Makes one cell under a parent. It is a statue until its host is live.</summary>
	public static FinaleCell Spawn( GameObject parent, FinaleCellHost host, Vector3 at, float yaw, Color shirt, Color trousers, float runSpeed )
	{
		var go = new GameObject( parent, true, "Cell" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.WorldPosition = at + Vector3.Up;
		go.WorldRotation = Rotation.FromYaw( yaw );

		var person = go.Components.Create<CrowdPerson>();
		person.Host = host;
		person.GrabberChance = 1f;        // every cell will take hold, once it has noticed you
		person.LeaveThroughExit = false;
		person.Passive = true;
		person.RunSpeed = runSpeed;
		person.PassiveSpeed = 40f;
		person.LeapCooldown = 4.5f;
		person.TripChance = 0.15f;
		person.ShirtTint = shirt;
		person.TrouserTint = trousers;

		return new FinaleCell { Person = person, Home = at, Spot = at, Born = Time.Now };
	}
}