Sump/Misfits/Misfit.cs

The Misfit component: one NPC in the Sump hub that hides near a home spot, reacts to the player's speed, gaze, light, noise or crowding depending on its fear, builds trust over calm company, talks when the player presses Use, and once healed follows the player in a ring or keeps its own hub post. It is kinematic, moves with raycasts and floor traces, sleeps when far or unseen, and spawns/ticks its MisfitAbility components.

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

/// <summary>
/// One misfit living in the hub. It hides near its home spot and peeks out; how it takes the
/// player depends on its fear. Stay near without frightening it and it comes to trust you, then
/// talks, then asks you into its first contact. Healed, it stops hiding and walks with you.
/// Kinematic: it moves its own object and keeps itself on the floor with a ray; no rigid body.
/// The body is a <see cref="MisfitBody"/>. Its twisted abilities are separate components
/// (<see cref="MisfitAbility"/>) that it creates, ticks and feeds a strength. Far from the player,
/// or out of view for a while, it goes to sleep and costs next to nothing.
/// Made by <see cref="MisfitSpawner"/>, which also decides which misfit the player is talking to.
/// </summary>
[Title( "Misfit" ), Category( "Sump" ), Icon( "psychology_alt" )]
public sealed class Misfit : Component
{
	public MisfitProfile Profile { get; set; }

	/// <summary>The spot it hides at and comes back to. Its position when it starts, unless set.</summary>
	public Vector3? Home { get; set; }

	// ---- Noticing the player ----
	/// <summary>Inside this distance it reacts to how the player moves.</summary>
	[Property, Group( "Hiding" )] public float NoticeRange { get; set; } = 800f;
	/// <summary>The player moving faster than this (inches per second) inside notice range frightens it.</summary>
	[Property, Group( "Hiding" )] public float ScareSpeed { get; set; } = 380f;
	/// <summary>Nearer than this is too near. Much more for one afraid of touch; less as trust grows.</summary>
	[Property, Group( "Hiding" )] public float PersonalSpace { get; set; } = 150f;
	/// <summary>How far out from home it creeps toward the player when it feels bold.</summary>
	[Property, Group( "Hiding" )] public float PeekDistance { get; set; } = 150f;
	/// <summary>Seconds of the player being still or looking away before it is fully out.</summary>
	[Property, Group( "Hiding" )] public float CreepOutSeconds { get; set; } = 4f;
	/// <summary>How far behind home it runs when it bolts, and for how long.</summary>
	[Property, Group( "Hiding" )] public float FleeDistance { get; set; } = 260f;
	[Property, Group( "Hiding" )] public float FleeSeconds { get; set; } = 2.5f;
	/// <summary>The camera counts as looking straight at it above this (cosine of the angle).</summary>
	[Property, Group( "Hiding" ), Range( 0f, 1f )] public float StareDot { get; set; } = 0.93f;
	/// <summary>One afraid of crowds will not come out while another misfit is this near.</summary>
	[Property, Group( "Hiding" )] public float CrowdRange { get; set; } = 320f;
	/// <summary>One afraid of noise bolts when the player lands falling faster than this.</summary>
	[Property, Group( "Hiding" )] public float HardLanding { get; set; } = 520f;
	/// <summary>A place counts as lit inside this fraction of a point light's radius.</summary>
	[Property, Group( "Hiding" ), Range( 0f, 1f )] public float LitFraction { get; set; } = 0.55f;

	// ---- Moving ----
	[Property, Group( "Movement" )] public float CreepSpeed { get; set; } = 45f;
	[Property, Group( "Movement" )] public float FleeSpeed { get; set; } = 280f;
	[Property, Group( "Movement" )] public float FollowSpeed { get; set; } = 240f;
	/// <summary>It will not step up anything taller than this.</summary>
	[Property, Group( "Movement" )] public float StepHeight { get; set; } = 28f;
	/// <summary>Further than this from the player it only thinks a couple of times a second.</summary>
	[Property, Group( "Movement" )] public float FarDistance { get; set; } = 2200f;

	// ---- Sleeping ----
	/// <summary>Further than this from the player it goes to sleep: no behaviour, no traces, the body all but still.</summary>
	[Property, Group( "Sleep" )] public float SleepDistance { get; set; } = 3000f;
	/// <summary>Nearer than this it is always awake. Between the two it sleeps only when out of view.</summary>
	[Property, Group( "Sleep" )] public float WakeDistance { get; set; } = 1300f;
	/// <summary>Seconds out of view (and outside the wake distance) before it goes to sleep.</summary>
	[Property, Group( "Sleep" )] public float SleepAfter { get; set; } = 5f;
	/// <summary>It counts as in view when the camera is on it at least this squarely (cosine of the angle).</summary>
	[Property, Group( "Sleep" ), Range( -1f, 1f )] public float ViewDot { get; set; } = 0.35f;
	/// <summary>Seconds between a sleeper's checks on whether to wake.</summary>
	[Property, Group( "Sleep" )] public float SleepCheckSeconds { get; set; } = 0.5f;

	// ---- Trust and talking ----
	/// <summary>The player has to be this near for trust to grow.</summary>
	[Property, Group( "Trust" )] public float TrustRange { get; set; } = 380f;
	/// <summary>Seconds of calm company for trust to go from nothing to full.</summary>
	[Property, Group( "Trust" )] public float TrustSeconds { get; set; } = 10f;
	/// <summary>Trust needed (0 to 1) before it will talk.</summary>
	[Property, Group( "Trust" ), Range( 0f, 1f )] public float TalkTrust { get; set; } = 0.6f;
	[Property, Group( "Trust" )] public float TalkRange { get; set; } = 240f;
	/// <summary>How squarely the camera must be on it to talk (cosine of the angle).</summary>
	[Property, Group( "Trust" ), Range( 0f, 1f )] public float TalkDot { get; set; } = 0.9f;

	// ---- Healed ----
	/// <summary>How far from the player a healed misfit keeps, and how far it lets the player get before it moves.</summary>
	[Property, Group( "Healed" )] public float FollowDistance { get; set; } = 330f;
	[Property, Group( "Healed" )] public float FollowSlack { get; set; } = 110f;
	/// <summary>Healed misfits stand in three depths, this far apart, so a group spreads out.</summary>
	[Property, Group( "Healed" )] public float FollowRingGap { get; set; } = 90f;
	/// <summary>Nobody stands within this many degrees of the line from the lizard to the camera.</summary>
	[Property, Group( "Healed" ), Range( 0f, 150f )] public float CameraWedge { get; set; } = 65f;
	/// <summary>Left further behind than this, it simply turns up beside the player.</summary>
	[Property, Group( "Healed" )] public float CatchUpDistance { get; set; } = 2600f;
	/// <summary>
	/// While the player is within this of one of its own places in the hub (its market stall, its
	/// shrine, its spot at the radio), a healed misfit goes and keeps that place instead of trailing
	/// along. It rejoins the player once they are half as far again away. 0 turns this off.
	/// </summary>
	[Property, Group( "Healed" )] public float PostRange { get; set; } = 800f;

	/// <summary>0 a stranger to 1 trusted.</summary>
	public float Trust { get; private set; }
	/// <summary>0 calm to 1 terrified, right now.</summary>
	public float Scare { get; private set; }
	public bool Healed => Profile is not null && Profile.Healed;
	public MisfitBody Body => _body;

	/// <summary>Asleep: too far or too long unseen to bother behaving. It wakes when the player comes near or looks.</summary>
	public bool Asleep { get; private set; }
	/// <summary>Flat distance to the player, as it last knew it. Very large while the player cannot be seen ("sump_unseen").</summary>
	public float PlayerDistance { get; private set; } = 100000f;
	/// <summary>The spot it hides at, after it has settled in.</summary>
	public Vector3 HomePosition => _home;
	/// <summary>The twisted abilities it carries, one component each.</summary>
	public IReadOnlyList<MisfitAbility> Abilities => _abilities;

	/// <summary>While the player's object has this tag, the misfit behaves as if the player were not there.</summary>
	public const string UnseenTag = "sump_unseen";

	/// <summary>Gives it one more twisted ability, from the table in <see cref="MisfitAbilities"/>.</summary>
	public MisfitAbility AddAbility( TwistedAbility kind )
	{
		var ability = MisfitAbilities.Add( GameObject, kind, Profile );
		if ( ability.IsValid() ) _abilities.Add( ability );
		return ability;
	}

	/// <summary>The player is close, looking at it, and it is willing: the spawner may show its prompt.</summary>
	public bool WantsTalk { get; private set; }
	/// <summary>The player is close and looking, but it does not trust them yet.</summary>
	public bool WantsHint { get; private set; }
	/// <summary>How squarely the camera is on it, 1 dead centre.</summary>
	public float LookDot { get; private set; }

	/// <summary>Every misfit in the scene.</summary>
	public static IReadOnlyList<Misfit> All => _all;
	static readonly List<Misfit> _all = new();

	public static Misfit Find( MisfitProfile profile ) => _all.FirstOrDefault( m => m.IsValid() && m.Profile == profile );

	MisfitBody _body;
	Random _rng;
	string _fear = "";
	string _name = "Nobody";
	Vector3 _home;
	float _bold, _speed;
	float _fleeUntil, _nextFarThink, _lastThink, _nextLight, _nextFlinch, _nextUse, _stuckFor, _lastFall;
	float _drowsy, _nextSleepCheck;
	bool _lit, _thanked, _homeChecked, _following, _shown = true;
	Vector3 _lightAt;
	float _lightRadius;
	int _talkStage, _healedLine;
	Vector3? _post;
	float _nextPostThink;

	readonly List<MisfitAbility> _abilities = new();

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

		Profile ??= new MisfitProfile();
		_name = string.IsNullOrEmpty( Profile.Name ) ? "Nobody" : Profile.Name;
		_fear = (Profile.FearKind ?? "").ToLowerInvariant();
		_rng = new Random( Profile.Seed * 31 + 7 );
		_home = Home ?? WorldPosition;
		_thanked = Profile.Healed; // healed in an earlier sitting: it has said its thanks already
		WorldRotation = Rotation.FromYaw( Rand( 0f, 360f ) );

		_body = MisfitBody.Create( GameObject, Profile );
		AddAbility( Profile.Ability );
		_all.Add( this );
	}

	protected override void OnDestroy()
	{
		_all.Remove( this );
	}

	float Rand( float min, float max ) => min + (float)_rng.NextDouble() * (max - min);
	static float Approach( float value, float target, float step ) =>
		value < target ? MathF.Min( value + step, target ) : MathF.Max( value - step, target );

	// ---- Every frame --------------------------------------------------------------------------------

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

		// A sleeper does nothing at all between its checks.
		float now = Time.Now;
		if ( Asleep && now < _nextSleepCheck ) return;

		WantsTalk = false;
		WantsHint = false;

		// It lives in the hub only. During a flashback or the finale it is out of sight and does nothing.
		var mode = Sump.Mode;
		bool here = mode == SumpMode.Hub;
		bool shown = here || mode == SumpMode.Arrival || mode == SumpMode.Ended;
		if ( _body.Visible != shown ) _body.Visible = shown;
		if ( _shown != here )
		{
			_shown = here;
			foreach ( var ability in _abilities )
				if ( ability.IsValid() ) { ability.SetShown( here ); if ( !here ) ability.Strength = 0f; }
		}
		if ( !here ) { _nextSleepCheck = now + SleepCheckSeconds; return; }

		var player = Sump.Player;
		var camera = Scene.Camera;
		if ( !player.IsValid() || !camera.IsValid() ) return;

		float dt = Time.Delta;
		var me = WorldPosition;
		var toPlayer = (player.WorldPosition - me).WithZ( 0f );
		float distance = toPlayer.Length;
		var toward = distance > 1f ? toPlayer / distance : WorldRotation.Forward.WithZ( 0f ).Normal;

		// Hidden from everything in the Sump: to a misfit, the player is simply not there.
		bool unseen = player.GameObject.Tags.Has( UnseenTag );
		PlayerDistance = unseen ? 100000f : distance;

		if ( UpdateSleep( camera, me, distance, now, dt ) ) return;

		// Far away, a couple of thoughts a second is plenty.
		if ( distance > FarDistance )
		{
			if ( now < _nextFarThink ) return;
			_nextFarThink = now + 0.4f;
			dt = Math.Clamp( now - _lastThink, MathF.Min( dt, 0.6f ), 0.6f );
		}
		_lastThink = now;

		var chest = (me + _body.Top) * 0.5f;
		var sight = chest - camera.WorldPosition;
		LookDot = sight.LengthSquared > 1f ? Vector3.Dot( camera.WorldRotation.Forward, sight.Normal ) : 1f;

		if ( Profile.Healed ) UpdateHealed( player, toward, distance, dt, unseen );
		else UpdateHiding( player, toward, distance, dt, unseen );

		// Its abilities: each its own component, stronger the more worked up it is.
		float strength = 0.35f + 0.65f * Math.Clamp( _body.Agitation, 0f, 1f );
		foreach ( var ability in _abilities )
		{
			if ( !ability.IsValid() ) continue;
			ability.Strength = strength;
			ability.Tick( this, _body, dt );
		}

		_body.MoveSpeed = _speed;
	}

	// ---- Sleeping -------------------------------------------------------------------------------------

	/// <summary>
	/// Decides whether it is asleep, and returns true if it is. Asleep, nothing else runs: no
	/// behaviour, no traces, no abilities, and the body animates at its sleeping rate. Healed
	/// ones walk with the player and so never sleep.
	/// </summary>
	bool UpdateSleep( CameraComponent camera, Vector3 me, float distance, float now, float dt )
	{
		var sight = me + Vector3.Up * 25f - camera.WorldPosition;
		bool inView = sight.LengthSquared < 1f || Vector3.Dot( camera.WorldRotation.Forward, sight.Normal ) >= ViewDot;

		if ( Asleep )
		{
			_nextSleepCheck = now + SleepCheckSeconds;
			if ( Profile.Healed || distance < WakeDistance || (inView && distance < SleepDistance) ) Wake( now );
			return Asleep;
		}

		if ( Profile.Healed || now < _fleeUntil ) { _drowsy = 0f; return false; }

		bool far = distance > SleepDistance;
		if ( far || (!inView && distance > WakeDistance) ) _drowsy += dt;
		else _drowsy = 0f;

		if ( _drowsy > (far ? 0.5f : SleepAfter) ) Sleep( now );
		return Asleep;
	}

	void Sleep( float now )
	{
		Asleep = true;
		_drowsy = 0f;
		_speed = 0f;
		// Not all on the same frame.
		_nextSleepCheck = now + SleepCheckSeconds * (0.5f + (float)_rng.NextDouble());
		_body.Asleep = true;
		_body.MoveSpeed = 0f;
		foreach ( var ability in _abilities )
			if ( ability.IsValid() ) ability.Strength = 0f;
	}

	void Wake( float now )
	{
		Asleep = false;
		_drowsy = 0f;
		_lastThink = now;
		_body.Asleep = false;
	}

	// ---- Hiding ---------------------------------------------------------------------------------------

	void UpdateHiding( ReptileController player, Vector3 toward, float distance, float dt, bool unseen )
	{
		float now = Time.Now;
		var me = WorldPosition;
		var velocity = unseen ? Vector3.Zero : player.Velocity;
		if ( unseen ) distance = 100000f; // nobody there: nothing to fear, nobody to trust or talk to
		float look = unseen ? -1f : LookDot;
		float playerSpeed = velocity.Length;
		bool still = playerSpeed < 40f;
		bool lookingAway = look < 0.3f;
		bool stared = look > StareDot && distance < NoticeRange * 1.5f;
		bool toy = _body.Toy > 0.6f;

		// One that has faded right out (it only exists while watched) is simply not here.
		if ( _body.Fade < 0.05f )
		{
			_speed = 0f;
			Scare = Approach( Scare, 0f, dt * 0.35f );
			return;
		}

		CheckLight( now, me );
		if ( !_homeChecked ) SettleHome();

		// Trust makes it braver about closeness.
		float space = PersonalSpace * (_fear == "touch" ? 2.2f : 1f) * (1f - 0.6f * Trust);

		// ---- How frightening is the player right now? ----
		float threat = 0f;
		if ( distance < NoticeRange && playerSpeed > ScareSpeed ) threat = MathF.Max( threat, 0.35f + 0.6f * (1f - distance / NoticeRange) );
		if ( distance < space ) threat = MathF.Max( threat, 1f - 0.5f * distance / MathF.Max( space, 1f ) );
		threat *= 1f - 0.4f * Trust;

		bool bolt = false, frozen = false, crowded = false;
		switch ( _fear )
		{
			case "noise":
			{
				// Running feet and hard landings.
				bool landed = _lastFall < -HardLanding && velocity.z > -60f;
				if ( distance < NoticeRange * 1.3f && (playerSpeed > ScareSpeed * 0.8f || landed) ) bolt = true;
				break;
			}
			case "eyes":
				// Looked straight at: it freezes at a distance, and runs up close.
				if ( stared )
				{
					if ( distance < 320f * (1f - 0.6f * Trust) ) bolt = true;
					else { frozen = Trust < TalkTrust; threat = MathF.Max( threat, 0.55f * (1f - Trust) ); }
				}
				break;
			case "light":
				if ( _lit )
				{
					threat = MathF.Max( threat, 0.7f );
					if ( now >= _nextFlinch ) { _nextFlinch = now + 2f; _body.Flinch(); }
				}
				break;
			case "crowds":
				crowded = OthersNear( me, CrowdRange );
				if ( crowded ) threat = MathF.Max( threat, 0.3f );
				break;
		}
		_lastFall = velocity.z;

		if ( (bolt || threat > 0.85f) && now >= _fleeUntil ) Bolt( now );
		bool fleeing = now < _fleeUntil;
		if ( fleeing ) threat = 1f;

		Scare = Approach( Scare, threat, dt * (threat > Scare ? 4f : 0.35f) );

		// ---- Boldness: out when the player is still, looking away or far off; back in when not ----
		if ( threat > 0.3f ) _bold -= dt * 1.5f;
		else if ( !crowded && !(_fear == "light" && _lit) && (still || lookingAway || distance > NoticeRange || Trust >= TalkTrust) ) _bold += dt / MathF.Max( CreepOutSeconds, 0.1f );
		else _bold -= dt * 0.12f;
		_bold = Math.Clamp( _bold, 0f, 1f );

		// ---- Trust: calm company ----
		if ( distance < TrustRange && Scare < 0.3f && !fleeing && playerSpeed < ScareSpeed )
			Trust = MathF.Min( Trust + dt / MathF.Max( TrustSeconds, 0.1f ) * (still ? 1.5f : 1f), 1f );

		// ---- Where to be ----
		Vector3 target;
		float speed;
		if ( toy || frozen )
		{
			target = me;
			speed = 0f;
		}
		else if ( fleeing )
		{
			var from = _fear == "light" && _lit ? (me - _lightAt).WithZ( 0f ).Normal : -toward;
			target = _home + from * FleeDistance;
			speed = FleeSpeed;
		}
		else
		{
			// Out from home toward the player, as far as it dares. One afraid of the open barely leaves cover.
			var out_ = (player.WorldPosition - _home).WithZ( 0f );
			out_ = out_.Length > 1f ? out_.Normal : toward;
			target = unseen ? _home : _home + out_ * (PeekDistance * _bold * (_fear == "open" ? 0.3f : 1f));
			speed = CreepSpeed * (1f + Scare * 3f);

			// Never nearer than it can stand.
			if ( distance < space ) { target = me - toward * (space - distance + 20f); speed = CreepSpeed * 3f; }
			if ( _fear == "light" && IsLit( target, out _, out _ ) ) target = _home;
		}

		MoveToward( target, speed, dt, player );

		// Running, it looks where it goes; otherwise it watches the player.
		var face = fleeing && _speed > 10f ? (target - me).WithZ( 0f ).Normal : toward;
		if ( !toy && !frozen && !(unseen && _speed < 10f) ) Face( face, dt );

		_body.Agitation = MathF.Max( Scare * (1f - 0.4f * Trust), 0.1f * (1f - Trust) );

		// ---- Talking ----
		bool near = distance < TalkRange && look > TalkDot && _body.Fade > 0.5f && Scare < 0.5f;
		WantsTalk = near && Trust >= TalkTrust;
		WantsHint = near && !WantsTalk;
	}

	/// <summary>Runs for it: full fright, a little trust lost.</summary>
	void Bolt( float now )
	{
		_fleeUntil = now + FleeSeconds;
		Scare = 1f;
		_bold = 0f;
		Trust = MathF.Max( Trust - 0.15f, 0f );
		_body.Flinch();
	}

	bool OthersNear( Vector3 me, float range )
	{
		foreach ( var other in _all )
		{
			if ( other == this || !other.IsValid() ) continue;
			if ( (other.WorldPosition - me).LengthSquared < range * range ) return true;
		}
		return false;
	}

	/// <summary>
	/// Once, when the hub is first up: one afraid of the open moves its home against the nearest
	/// wall or junk, and one afraid of light moves its home out of any light.
	/// </summary>
	void SettleHome()
	{
		_homeChecked = true;

		if ( _fear == "open" )
		{
			float best = 400f;
			Vector3? spot = null;
			for ( int i = 0; i < 8; i++ )
			{
				var direction = Rotation.FromYaw( i * 45f ).Forward;
				var from = _home + Vector3.Up * 24f;
				var tr = Scene.Trace.Ray( from, from + direction * 400f ).IgnoreGameObjectHierarchy( GameObject ).Run();
				if ( !tr.Hit || tr.Distance >= best || tr.Distance < 20f ) continue;
				best = tr.Distance;
				spot = _home + direction * (tr.Distance - 30f);
			}
			if ( spot.HasValue && FloorAt( spot.Value, null ) is Vector3 floor ) _home = floor;
		}
		else if ( _fear == "light" && IsLit( _home, out var light, out float radius ) )
		{
			var away = (_home - light).WithZ( 0f );
			away = away.Length > 1f ? away.Normal : Rotation.FromYaw( Rand( 0f, 360f ) ).Forward;
			if ( FloorAt( _home + away * radius * 0.7f, null ) is Vector3 floor ) _home = floor;
		}
	}

	// ---- Light ----------------------------------------------------------------------------------------

	static readonly List<PointLight> _lights = new();
	static float _lightsAt = -100f;
	static Scene _lightsScene;

	void CheckLight( float now, Vector3 me )
	{
		if ( _fear != "light" || now < _nextLight ) return;
		_nextLight = now + 0.5f;
		_lit = IsLit( me, out _lightAt, out _lightRadius );
	}

	/// <summary>True if a point light reaches this place. The list of lights is shared and refreshed every few seconds.</summary>
	bool IsLit( Vector3 position, out Vector3 lightAt, out float radius )
	{
		if ( _lightsScene != Scene || Time.Now - _lightsAt > 3f || Time.Now < _lightsAt )
		{
			_lightsScene = Scene;
			_lightsAt = Time.Now;
			_lights.Clear();
			_lights.AddRange( Scene.GetAllComponents<PointLight>() );
		}

		foreach ( var light in _lights )
		{
			if ( !light.IsValid() || !light.Active || light.GameObject.Tags.Has( MisfitBody.GlowTag ) ) continue;
			float reach = light.Radius * LitFraction;
			var at = light.WorldPosition;
			if ( (at - position).LengthSquared > reach * reach ) continue;
			lightAt = at;
			radius = light.Radius;
			return true;
		}

		lightAt = default;
		radius = 0f;
		return false;
	}

	// ---- Healed: walking with the player ------------------------------------------------------------------

	/// <summary>
	/// Where a healed misfit stands: its own place in a wide, loose ring round the player, each
	/// a good turn on from the last and in one of three depths, so they spread out instead of
	/// bunching. The side the camera is on is kept clear: a place that would fall between the
	/// camera and the lizard is moved round to the edge of that wedge.
	/// </summary>
	Vector3 FollowSlot( ReptileController player, Vector3 feet, int rank )
	{
		float yaw = 150f + rank * 137.5f;
		float ring = FollowDistance + (rank % 3) * FollowRingGap + rank * 10f;

		// The camera looks along the player's look yaw, so it sits the opposite way from the lizard.
		float camera = player.Look.yaw + 180f;
		float from = ((yaw - camera) % 360f + 540f) % 360f - 180f;   // -180..180 round from the camera's side
		float clear = Math.Clamp( CameraWedge, 0f, 150f );
		if ( MathF.Abs( from ) < clear )
		{
			float side = from > 0f || (from == 0f && (rank & 1) == 0) ? 1f : -1f;
			yaw = camera + side * (clear + (rank % 3) * 12f);
		}

		return feet + Rotation.FromYaw( yaw ).Forward * ring;
	}

	/// <summary>
	/// Its stall, shrine or radio spot (<see cref="SumpHub"/>), whichever is nearest the player,
	/// if the player is near enough for it to be worth keeping; otherwise null and it follows.
	/// </summary>
	Vector3? ChoosePost( Vector3 feet )
	{
		if ( PostRange <= 0f || Sump.Mode != SumpMode.Hub ) return null;

		// Already keeping one: it stays until the player has gone a fair way off.
		float range = _post.HasValue ? PostRange * 1.5f : PostRange;
		Vector3? best = null;
		float bestDistance = range;
		Consider( SumpHub.StallFor( Profile ) );
		Consider( SumpHub.ShrineFor( Profile ) );
		Consider( SumpHub.RadioSpotFor( Profile ) );
		return best;

		void Consider( Vector3? place )
		{
			if ( place is not { } at ) return;
			float d = (at - feet).WithZ( 0f ).Length;
			if ( d < bestDistance && MathF.Abs( at.z - feet.z ) < 400f ) { bestDistance = d; best = at; }
		}
	}

	void UpdateHealed( ReptileController player, Vector3 toward, float distance, float dt, bool unseen )
	{
		// Its thanks, once, the moment it is back in the hub.
		if ( !_thanked )
		{
			_thanked = true;
			Sump.Say( _name, MisfitVoice.Thanks( Profile ), 6f );
		}

		Scare = Approach( Scare, 0f, dt * 0.8f );
		_bold = 1f;
		Trust = 1f;
		_fleeUntil = 0f;
		_body.Agitation = MathF.Max( Scare, 0.03f );

		// Each healed one has its own place in a loose ring round the player.
		int rank = 0;
		foreach ( var other in _all )
			if ( other != this && other.IsValid() && other.Healed && other.Profile.Index < Profile.Index ) rank++;

		var me = WorldPosition;
		var feet = player.WorldPosition;
		var slot = FollowSlot( player, feet, rank );

		// In the hub it has places of its own: with the player nearby, it keeps one of them.
		if ( Time.Now >= _nextPostThink )
		{
			_nextPostThink = Time.Now + 0.5f;
			_post = ChoosePost( feet );
		}
		if ( _post is { } post ) slot = post;

		float off = (slot - me).WithZ( 0f ).Length;

		if ( off > FollowSlack ) _following = true;
		else if ( off < 20f ) _following = false;

		if ( _following )
		{
			MoveToward( slot, FollowSpeed * (off > 500f ? 2.2f : 1f), dt, player );
			_stuckFor = _speed < 5f ? _stuckFor + dt : 0f;
		}
		else
		{
			_speed = 0f;
			_stuckFor = 0f;
		}

		// Lost, or shut out by the cave: it just turns up near the player.
		if ( distance > CatchUpDistance || _stuckFor > 3f || MathF.Abs( feet.z - me.z ) > 700f )
		{
			_stuckFor = 0f;
			WorldPosition = FloorAt( slot, player ) ?? FloorAt( feet, player ) ?? feet;
		}

		Face( _following && _speed > 10f ? (slot - me).WithZ( 0f ).Normal : toward, dt );

		WantsTalk = !unseen && distance < TalkRange && LookDot > TalkDot;
	}

	// ---- Moving over the floor ------------------------------------------------------------------------

	void MoveToward( Vector3 target, float speed, float dt, ReptileController player )
	{
		var me = WorldPosition;
		var to = (target - me).WithZ( 0f );
		float distance = to.Length;
		if ( distance < 4f || speed <= 0f || dt <= 0f ) { _speed = 0f; return; }

		var direction = to / distance;
		float step = MathF.Min( speed * dt, distance );

		// A wall in the way: slide along it, or stop.
		var chest = Vector3.Up * 18f;
		var wall = Trace( me + chest, me + chest + direction * (step + 14f), player );
		if ( wall.Hit )
		{
			var normal = wall.Normal.WithZ( 0f );
			if ( normal.Length < 0.1f ) { _speed = 0f; return; }
			normal = normal.Normal;
			var slide = direction - normal * Vector3.Dot( direction, normal );
			if ( slide.Length < 0.15f ) { _speed = 0f; return; }
			direction = slide.Normal;
			step *= 0.7f;
		}

		var floor = FloorAt( me + direction * step, player );
		if ( !floor.HasValue || floor.Value.z - me.z > StepHeight ) { _speed = 0f; return; }

		WorldPosition = floor.Value;
		_speed = step / dt;
	}

	SceneTraceResult Trace( Vector3 from, Vector3 to, ReptileController player )
	{
		var trace = Scene.Trace.Ray( from, to ).IgnoreGameObjectHierarchy( GameObject );
		if ( player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( player.GameObject );
		return trace.Run();
	}

	/// <summary>The floor under (or just above) a position, if there is any.</summary>
	Vector3? FloorAt( Vector3 position, ReptileController player )
	{
		var tr = Trace( position + Vector3.Up * 40f, position + Vector3.Down * 160f, player );
		return tr.Hit && !tr.StartedSolid ? tr.HitPosition : null;
	}

	void Face( Vector3 direction, float dt )
	{
		direction = direction.WithZ( 0f );
		if ( direction.LengthSquared < 0.01f ) return;
		WorldRotation = Rotation.Slerp( WorldRotation, Rotation.LookAt( direction.Normal, Vector3.Up ), MathF.Min( dt * 6f, 1f ) );
	}

	// ---- Talking ------------------------------------------------------------------------------------------

	/// <summary>What the "press E" line should say while the player is looking at it.</summary>
	public string PromptText => !Healed && _talkStage >= 4 ? $"E  enter {_name}'s first contact" : $"E  talk to {_name}";

	/// <summary>Shown instead of the prompt while it does not trust the player enough to talk.</summary>
	public string HintText => $"{_name} is watching you. Stay near, stay slow, and try not to dangle at it.";

	/// <summary>
	/// The player pressed Use on it. Unhealed: its greeting, its object, its fear, its plea, and
	/// after that the way into its first contact. Healed: a word about its orders, or its thanks.
	/// </summary>
	public void Use()
	{
		float now = Time.Now;
		if ( now < _nextUse || Profile is null ) return;
		_nextUse = now + 0.45f;

		if ( Profile.Healed )
		{
			Sump.Say( _name, _healedLine++ % 2 == 0 ? MisfitVoice.OrdersLine( Profile ) : MisfitVoice.Thanks( Profile ) );
			return;
		}

		switch ( _talkStage )
		{
			case 0: Sump.Say( _name, MisfitVoice.Greeting( Profile, Math.Abs( Profile.Seed ) % 3 ) ); break;
			case 1: Sump.Say( _name, MisfitVoice.AboutObject( Profile ) ); break;
			case 2: Sump.Say( _name, MisfitVoice.AboutFear( Profile ) ); break;
			case 3: Sump.Say( _name, MisfitVoice.AskForHelp( Profile ), 6f ); break;
			default: Sump.RequestFlashback( Profile ); return;
		}
		_talkStage++;
	}

	/// <summary>Called by the spawner when the Sump says this one was healed just now.</summary>
	public void OnHealed()
	{
		_fleeUntil = 0f;
		if ( Asleep ) Wake( Time.Now );
		foreach ( var ability in _abilities )
			if ( ability.IsValid() ) ability.OnHealed( _body );
	}
}