ReptileController.cs

Player controller for a lizard that clings to floors, walls and ceilings. Moves a sphere with scene traces, keeps the surface normal as its up, steers input relative to the camera, and runs a hands-then-feet latch animation (reach, grip, pull, foot swing) for switching surfaces, plus a hand-aimed long reach on the right mouse button. Also owns the third-person camera, mouse capture, body dip/gait posing and switching between the rigged and primitive models.

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

/// <summary>
/// Fast lizard movement that clings to whatever it touches: floor, walls and ceiling. The creature
/// is a sphere moved with traces, its "up" is the normal of the surface it is on, and input is
/// steered relative to the camera. Jump pushes off the surface; Run sprints.
/// Changing surface is a grip and pivot, not a roll, and both ends hold in turn: the feet grip
/// while the hands reach and latch the new face, the hands haul the body round, then the feet let
/// go, swing through and latch. Holding the right mouse button aims the reach by hand.
/// The mouse is captured while playing; Escape frees it and a click takes it back.
/// </summary>
[Title( "Reptile Controller" ), Category( "Player" ), Icon( "pest_control" )]
public sealed class ReptileController : Component
{
	[Property, Group( "Movement" )] public float Speed { get; set; } = 300f;
	[Property, Group( "Movement" )] public float SprintSpeed { get; set; } = 620f;

	/// <summary>How quickly velocity reaches the wanted speed (higher is snappier).</summary>
	[Property, Group( "Movement" )] public float Acceleration { get; set; } = 16f;

	/// <summary>How quickly it stops when the keys are released (higher is less floaty).</summary>
	[Property, Group( "Movement" )] public float Braking { get; set; } = 30f;

	/// <summary>How quickly the body turns to face its movement.</summary>
	[Property, Group( "Movement" )] public float TurnSpeed { get; set; } = 18f;
	[Property, Group( "Movement" )] public float JumpSpeed { get; set; } = 420f;
	[Property, Group( "Movement" )] public float Gravity { get; set; } = 900f;

	/// <summary>Radius of the collision sphere, which also sets how low the body rides.</summary>
	[Property, Group( "Movement" )] public float Radius { get; set; } = 9f;

	/// <summary>How far below itself it looks for a surface to stay stuck to.</summary>
	[Property, Group( "Movement" )] public float StickDistance { get; set; } = 26f;

	/// <summary>When off it can only stand on floors, like a person (used while wearing a skin).</summary>
	[Property, Group( "Movement" )] public bool ClingEnabled { get; set; } = true;

	/// <summary>How far ahead the hands feel for a new surface to latch onto, in inches.</summary>
	[Property, Group( "Grip" )] public float ReachDistance { get; set; } = 46f;

	/// <summary>Seconds the hands take to reach the grip point before they latch.</summary>
	[Property, Group( "Grip" )] public float ReachSeconds { get; set; } = 0.04f;

	/// <summary>Seconds the hands pull the front of the body onto the new face while the feet still hold the old one.</summary>
	[Property, Group( "Grip" )] public float PullSeconds { get; set; } = 0.07f;

	/// <summary>Seconds the feet take to let go, swing through and latch onto the new face.</summary>
	[Property, Group( "Grip" )] public float FootSeconds { get; set; } = 0.1f;

	/// <summary>How sharp a change of surface has to be before it is a latch and not just a bump, in degrees.</summary>
	[Property, Group( "Grip" ), Range( 20f, 80f )] public float LatchAngle { get; set; } = 62f;

	/// <summary>How far away a hand-aimed latch (hold Q) can reach, in inches.</summary>
	[Property, Group( "Grip" )] public float AimReach { get; set; } = 330f;

	/// <summary>Speed of the pull toward a far, hand-aimed grip, in inches per second.</summary>
	[Property, Group( "Grip" )] public float PullSpeed { get; set; } = 1100f;

	/// <summary>How much movement surges and holds with each stride on walls and ceilings (0 = glide).</summary>
	[Property, Group( "Grip" ), Range( 0f, 0.9f )] public float GripPulse { get; set; } = 0.55f;

	/// <summary>Input action held to aim the reach by hand. "Attack2" is the right mouse button.</summary>
	[Property, Group( "Grip" )] public string AimAction { get; set; } = "Attack2";

	/// <summary>Thud played when the hands latch.</summary>
	[Property, Group( "Grip" )] public string LatchSound { get; set; } = "sounds/opening/latch_thud.sound";

	/// <summary>Soft claw taps while moving on rock.</summary>
	[Property, Group( "Movement" )] public string StepSound { get; set; } = "sounds/opening/claw_step.sound";

	[Property, Group( "Camera" )] public float CameraDistance { get; set; } = 190f;
	[Property, Group( "Camera" )] public float CameraHeight { get; set; } = 26f;

	/// <summary>The visual body, wiggled side to side while running.</summary>
	[Property] public GameObject Body { get; set; }

	/// <summary>
	/// The one switch between the two lizards. On (the default): the rigged, animated model from
	/// Blender (see <see cref="LizardRig"/>). Off: the original body built from simple shapes.
	/// Can be flipped while playing.
	/// </summary>
	[Property] public bool UseNewModel { get; set; } = true;

	/// <summary>
	/// How the new model picks up and loses speed and how fast it turns. Lower than the old
	/// body's values, so it has momentum: it leans into a run, carries on a little when you let
	/// go, and swings round instead of snapping. Only used while <see cref="UseNewModel"/> is on.
	/// </summary>
	[Property, Group( "New Model Feel" )] public float NewAcceleration { get; set; } = 7.5f;
	[Property, Group( "New Model Feel" )] public float NewBraking { get; set; } = 9f;
	[Property, Group( "New Model Feel" )] public float NewTurnSpeed { get; set; } = 9f;
	LizardRig _rig;

	/// <summary>Normal of the surface being clung to (world up while airborne).</summary>
	public Vector3 Up { get; private set; } = Vector3.Up;
	public bool Attached { get; private set; }
	public Vector3 Velocity => _velocity;

	// ---- Grip state, read by the body to pose the hands and legs ------------------------------

	/// <summary>True from the moment the hands start reaching until the legs have planted.</summary>
	public bool IsLatching { get; private set; }

	// ---- Hooks for cutscenes and for being grabbed ------------------------------------------

	/// <summary>While true the player's keys and buttons do nothing (the camera still turns).</summary>
	public bool InputLocked { get; set; }

	/// <summary>While true the mouse does not turn the camera (something else is reading it: a weapon being aimed by hand).</summary>
	public bool LookLocked { get; set; }

	/// <summary>While set (and input is locked) the lizard walks this way by itself. World direction, length 0..1.</summary>
	public Vector3? ForcedWish { get; set; }

	/// <summary>True while something is holding the lizard down.</summary>
	public bool IsPinned { get; private set; }

	/// <summary>Holds the lizard flat on the ground at a spot until <see cref="Unpin"/>.</summary>
	public void Pin( Vector3 feet )
	{
		IsPinned = true;
		IsLatching = false; FeetHolding = false; ReachAmount = 0f; LegTuck = 0f;
		Up = Vector3.Up;
		_center = feet + Vector3.Up * Radius;
		_velocity = Vector3.Zero;
		Attached = true;
	}

	public void Unpin() => IsPinned = false;

	/// <summary>Multiplies how fast it can go. Below 1 while things are hanging off its limbs.</summary>
	public float SpeedScale { get; set; } = 1f;

	// Named speed factors, so several systems can each slow or speed the lizard without
	// overwriting one another. They multiply together, and with SpeedScale.
	readonly Dictionary<string, float> _speedFactors = new();
	float _speedFactor = 1f;

	/// <summary>Sets (or with 1, clears) one named multiplier on movement speed.</summary>
	public void SetSpeedFactor( string name, float factor )
	{
		if ( MathF.Abs( factor - 1f ) < 0.0001f ) _speedFactors.Remove( name );
		else _speedFactors[name] = factor;
		_speedFactor = 1f;
		foreach ( var f in _speedFactors.Values ) _speedFactor *= f;
	}

	/// <summary>Where the camera is looking (pitch, yaw).</summary>
	public Angles Look => _look;

	/// <summary>Puts the lizard somewhere else at once (feet position), dropping whatever it was doing.</summary>
	public void Teleport( Vector3 feet, float? yaw = null )
	{
		_center = feet + Vector3.Up * Radius;
		_velocity = Vector3.Zero;
		Attached = false;
		IsLatching = false;
		Up = Vector3.Up;
		_visualUp = Vector3.Up;
		_cameraPrimed = false;
		if ( yaw.HasValue )
		{
			_look = new Angles( 8f, yaw.Value, 0f );
			_facing = Rotation.FromYaw( yaw.Value ).Forward;
			WorldRotation = Rotation.FromYaw( yaw.Value );
		}
		WorldPosition = feet;
	}

	/// <summary>While set, it can't get further than <see cref="LeashRadius"/> from this spot (held down by a pile).</summary>
	public Vector3? Leash { get; set; }
	public float LeashRadius { get; set; } = 40f;

	/// <summary>
	/// Optional: the height of the solid ground at a point. When set, the lizard is never allowed
	/// below it, whatever happens with collision.
	/// </summary>
	public Func<Vector3, float> FloorHeight { get; set; }

	/// <summary>Points the camera (pitch, yaw).</summary>
	public void SetLook( Angles angles ) => _look = angles.WithRoll( 0 );

	/// <summary>True while the grab button is held, whether or not there is something to grab.</summary>
	public bool IsReaching => _aimHeld || IsLatching;

	/// <summary>False after Escape frees the mouse, until a click in the window takes it back.</summary>
	public bool MouseCaptured => !_mouseFree;

	/// <summary>Time since a click re-captured the mouse. That click must not also attack or grab.</summary>
	public TimeSince SinceRecapture { get; private set; } = 10f;

	/// <summary>How far the body is pressed toward its surface right now (a landing or a plant), in inches.</summary>
	public float BodyDip => _dip;

	/// <summary>True while the grab button is held and a valid grip point is under the camera.</summary>
	public bool IsAiming { get; private set; }

	/// <summary>Where the hands are reaching to or holding (valid while latching or aiming).</summary>
	public Vector3 GripPoint { get; private set; }

	/// <summary>0 = arms relaxed, 1 = hands on the grip point.</summary>
	public float ReachAmount { get; private set; }

	/// <summary>0 = legs down, 1 = legs pulled right up under the body (mid-swing).</summary>
	public float LegTuck { get; private set; }

	/// <summary>True while the feet are still gripping the old surface during a latch.</summary>
	public bool FeetHolding { get; private set; }

	/// <summary>Where the feet are gripping while <see cref="FeetHolding"/>.</summary>
	public Vector3 FootPoint { get; private set; }

	/// <summary>Stride phase in radians, advanced by distance moved. The body's limbs follow it.</summary>
	public float GaitPhase { get; private set; }

	Vector3 _center;
	Vector3 _velocity;
	Vector3 _facing = Vector3.Forward;
	Angles _look;
	bool _jumpQueued;
	bool _steering;
	Vector3 _visualUp = Vector3.Up;
	Vector3 _spawn;
	TimeSince _sinceJump = 10f;
	CaveGenerator _cave;

	/// <summary>Off while the lizard is somewhere a cave in the scene must not pull it back into (a memory, the descent).</summary>
	public bool StayInCaves { get; set; } = true;
	Vector3 _lastContained;
	TimeSince _sinceContained = 10f;

	// Latch in progress: hands reach, latch, then the body swings round them.
	Vector3 _gripNormal, _latchFromCenter, _latchFromUp, _carryDirection;
	float _latchTime, _pullSeconds, _carrySpeed;
	bool _latchImpactDone;
	TimeSince _sinceLatch = 10f;

	// Hand-aimed reach.
	Vector3 _aimNormal;
	bool _aimHeld;
	GameObject _aimMarker;
	Vector3 _cameraKick;

	bool _mouseFree;
	float _dip, _dipVelocity;
	Vector3 _cameraTarget;
	bool _cameraPrimed;
	LizardAttack _attack;

	protected override void OnStart()
	{
		_look = WorldRotation.Angles().WithRoll( 0 );
		_facing = WorldRotation.Forward;
		_center = WorldPosition + Vector3.Up * Radius;
		_spawn = _center;

		if ( !Body.IsValid() )
			Body = Components.Get<ReptileBody>( FindMode.EverythingInDescendants )?.GameObject;
	}

	protected override void OnUpdate()
	{
		UpdateMouseCapture();
		UpdateModelChoice();

		if ( Input.Pressed( "Jump" ) && !InputLocked && !IsPinned ) _jumpQueued = true;

		UpdateAim();

		if ( MouseCaptured && !LookLocked )
		{
			_look += Input.AnalogLook;
			_look.pitch = Math.Clamp( _look.pitch, -85f, 85f );
			_look.roll = 0;
		}

		UpdateCamera();
		UpdateBodyPose();
	}

	/// <summary>
	/// The game owns the mouse while playing: hidden, locked to the window, turning the camera.
	/// Escape lets it go (to reach the editor); clicking back in the window takes it again.
	/// </summary>
	void UpdateMouseCapture()
	{
		if ( Input.EscapePressed ) _mouseFree = true;

		if ( _mouseFree && (Input.Pressed( "Attack1" ) || Input.Pressed( "Attack2" )) )
		{
			_mouseFree = false;
			SinceRecapture = 0;
		}

		Mouse.Visibility = _mouseFree ? MouseVisibility.Visible : MouseVisibility.Hidden;
	}

	/// <summary>
	/// The weight of the body on top of where it stands: pressed down by landings and plants and
	/// springing back, lurching into a bite, and swaying side to side at a run.
	/// </summary>
	void UpdateBodyPose()
	{
		// A damped spring: knocked toward the surface, it overshoots a little and settles.
		// (In small steps, so one long frame cannot make the spring run away.)
		float dt = MathF.Min( Time.Delta, 0.1f );
		int steps = Math.Clamp( (int)MathF.Ceiling( dt * 120f ), 1, 12 );
		float h = dt / steps;
		for ( int step = 0; step < steps; step++ )
		{
			_dipVelocity += (-_dip * 260f - _dipVelocity * 18f) * h;
			_dip += _dipVelocity * h;
		}
		_dip = Math.Clamp( _dip, -4f, 9f );
		_dipVelocity = Math.Clamp( _dipVelocity, -400f, 400f );

		if ( !Body.IsValid() ) return;

		if ( !_attack.IsValid() ) _attack = Components.Get<LizardAttack>();
		float lurch = _attack.IsValid() ? _attack.Strike : 0f;

		float run = Math.Clamp( _velocity.Length / SprintSpeed, 0f, 1f );
		float sway = MathF.Sin( GaitPhase ) * 7f * run;
		float bob = MathF.Abs( MathF.Sin( GaitPhase ) ) * 1.6f * run;

		Body.LocalRotation = Rotation.FromYaw( sway ) * Rotation.FromPitch( lurch * 16f + _dip * 1.2f );
		Body.LocalPosition = Vector3.Forward * (lurch * 9f) + Vector3.Down * (_dip + bob);
	}

	/// <summary>Presses the body toward its surface, as when it lands or plants. It springs back.</summary>
	void Thump( float strength ) => _dipVelocity += 95f * strength;

	protected override void OnFixedUpdate()
	{
		float dt = Time.Delta;

		// Held down: going nowhere.
		if ( IsPinned )
		{
			_velocity = Vector3.Zero;
			_jumpQueued = false;
			UpdateTransform( dt );
			return;
		}

		// Mid-latch the swing drives everything; a jump lets go.
		if ( IsLatching )
		{
			if ( _jumpQueued )
			{
				_jumpQueued = false;
				IsLatching = false;
				ReachAmount = 0f; LegTuck = 0f; FeetHolding = false;
				ShoveSurface();
				_velocity = Up * JumpSpeed;
				Attached = false;
				_sinceJump = 0;
			}
			else
			{
				UpdateLatch( dt );
				if ( KeepInside() ) { IsLatching = false; FeetHolding = false; ReachAmount = 0f; LegTuck = 0f; }
				UpdateTransform( dt );
				return;
			}
		}

		var wish = WishDirection();
		_steering = wish.Length > 0.1f;
		float speed = (Input.Down( "Run" ) && !InputLocked ? SprintSpeed : Speed) * SpeedScale * _speedFactor;

		if ( Attached )
		{
			// On walls and ceilings movement surges with each stride and holds as the hands
			// plant, instead of gliding. On floors it only breathes a little.
			float steep = 1f - Math.Clamp( (Up.z - 0.5f) / 0.35f, 0f, 1f );
			float pulse = 1f - GripPulse * (0.25f + 0.75f * steep) * (0.5f + 0.5f * MathF.Cos( GaitPhase * 2f ));
			float before = GaitPhase;
			GaitPhase += _velocity.Length * dt * 0.055f;

			// A claw tap each time a foot comes down (twice per stride), louder at a run.
			if ( MathF.Floor( GaitPhase / MathF.PI ) != MathF.Floor( before / MathF.PI ) && !string.IsNullOrEmpty( StepSound ) )
			{
				var step = Sound.Play( StepSound, _center - Up * Radius );
				if ( step.IsValid() ) step.Volume = 0.25f + 0.5f * Math.Clamp( _velocity.Length / SprintSpeed, 0f, 1f );
			}

			_velocity = Flatten( _velocity, Up );
			// Bite into a run quickly and stop quicker still, so it never feels like sliding on ice.
			float response = UseNewModel
				? (wish.Length > 0.1f ? NewAcceleration : NewBraking)
				: (wish.Length > 0.1f ? Acceleration : Braking);
			_velocity = Vector3.Lerp( _velocity, wish * speed * pulse, 1f - MathF.Exp( -response * dt ) );

			// Reach: feel ahead for a new face (wall, rock, formation) and latch onto it.
			if ( !_jumpQueued && !_aimHeld && _sinceLatch > 0.12f && _velocity.Length > 30f && TryAutoReach() )
			{
				UpdateTransform( dt );
				return;
			}

			if ( _jumpQueued )
			{
				// Push off whatever we're on. Off a wall or ceiling that's away from it, then falling.
				ShoveSurface();
				_velocity += Up * JumpSpeed;
				Attached = false;
				_sinceJump = 0;
			}
		}
		else
		{
			_velocity += Vector3.Down * Gravity * dt;
			_velocity += wish * speed * 1.5f * dt;
		}
		_jumpQueued = false;

		Move( _velocity * dt );
		if ( Attached && !IsLatching ) StickToSurface();
		KeepInside();
		KeepOnLeash();
		KeepAboveFloor();
		UpdateTransform( dt );
	}

	/// <summary>Held down by a pile: it can thrash about a spot but not leave it.</summary>
	void KeepOnLeash()
	{
		if ( Leash is not { } post ) return;

		var from = _center - (post + Vector3.Up * Radius);
		float distance = from.Length;
		if ( distance <= LeashRadius ) return;

		var outward = from / distance;
		_center = post + Vector3.Up * Radius + outward * LeashRadius;
		float away = Vector3.Dot( _velocity, outward );
		if ( away > 0f ) _velocity -= outward * away;
	}

	/// <summary>Never below the ground, whatever collision let through.</summary>
	void KeepAboveFloor()
	{
		if ( FloorHeight is null ) return;

		float floor = FloorHeight( _center );
		if ( _center.z >= floor + Radius * 0.6f ) return;

		_center = _center.WithZ( floor + Radius + 0.2f );
		if ( _velocity.z < 0f ) _velocity = _velocity.WithZ( 0f );
		if ( !Attached ) { Attached = true; Up = Vector3.Up; }
	}

	/// <summary>Turns the body to face its movement on the (smoothed) surface and places it.</summary>
	void UpdateTransform( float dt )
	{
		// Face where we are being steered, not where a landing or a slope happens to slide us.
		if ( _velocity.Length > 20f && (_steering || IsLatching) ) _facing = _velocity.Normal;
		if ( !Attached && !IsLatching ) Up = Vector3.Lerp( Up, Vector3.Up, dt * 4f ).Normal;

		// The surface normal jumps from one rock face to the next; smooth it for the body so it
		// doesn't twitch or flip on every step.
		_visualUp = Vector3.Lerp( _visualUp, Up, Math.Clamp( dt * 10f, 0f, 1f ) );
		if ( _visualUp.Length < 0.01f ) _visualUp = Up;
		_visualUp = _visualUp.Normal;

		// A worn skin can't cling, and a person stands upright whatever the slope.
		if ( !ClingEnabled ) _visualUp = Vector3.Up;
		var up = _visualUp;

		var forward = Flatten( _facing, up );
		if ( forward.Length < 0.01f ) forward = Flatten( WorldRotation.Forward, up );
		if ( forward.Length < 0.01f ) forward = Flatten( Vector3.Forward, up );

		WorldRotation = Rotation.Slerp( WorldRotation, Rotation.LookAt( forward.Normal, up ), Math.Clamp( dt * (UseNewModel ? NewTurnSpeed : TurnSpeed), 0f, 1f ) );
		WorldPosition = _center - Up * Radius;
	}

	// ---- Grip and pivot -----------------------------------------------------------------------

	/// <summary>Throws the body in a direction (a bite), keeping it on its surface if it is on one.</summary>
	public void Lunge( Vector3 direction, float speed )
	{
		if ( IsLatching ) return;
		_velocity += (Attached ? Flatten( direction, Up ) : direction) * speed;
	}

	/// <summary>Shakes the lizard off whatever it is holding (used by the orbit-capture jolt). On a floor it only staggers.</summary>
	public void ShakeLoose( Vector3 push )
	{
		IsLatching = false; FeetHolding = false; ReachAmount = 0f; LegTuck = 0f;
		if ( Up.z > 0.7f ) { _velocity += Flatten( push, Up ); return; }
		Attached = false;
		_velocity = push;
		_sinceJump = 0;
	}

	/// <summary>Jolts the camera by an offset that quickly settles back.</summary>
	public void Kick( Vector3 offset ) => _cameraKick += offset;

	/// <summary>Feels ahead along our movement for a face to latch onto. True if a latch began.</summary>
	bool TryAutoReach()
	{
		var ahead = _velocity.Normal;
		var probe = Sphere( _center, _center + ahead * ReachDistance );
		if ( !probe.Hit || probe.StartedSolid ) return false;
		if ( Vector3.Dot( probe.Normal, Up ) > MathF.Cos( LatchAngle * MathF.PI / 180f ) ) return false;   // same surface, just bumpy

		// Don't swing straight back onto the face we just came off: that is how it gets trapped
		// bouncing between two faces at a crease.
		if ( _sinceLatch < 0.8f && Vector3.Dot( probe.Normal, _latchFromUp ) > 0.85f ) return false;
		if ( !CanStandOn( probe.Normal ) ) return false;

		BeginLatch( probe.HitPosition, probe.Normal );
		return true;
	}

	/// <summary>
	/// Starts a latch. Both ends of the body hold rock in turn, so it is never loose:
	///   1. Reach  - feet grip where they stand; hands go out to the new point.
	///   2. Latch  - hands hit the new face (thud). Both ends are now holding.
	///   3. Pull   - hands haul the front of the body round; the body bridges the two faces.
	///   4. Swing  - feet let go, tuck, swing through and latch onto the new face (thud).
	/// </summary>
	void BeginLatch( Vector3 grip, Vector3 normal )
	{
		// A far, hand-aimed grip must not drag the body through rock: if something standable is
		// in the way, latch onto that instead.
		var end = grip + normal * (Radius + 0.2f);
		float distance = (end - _center).Length;
		if ( distance > ReachDistance * 1.5f )
		{
			var path = Sphere( _center, end );
			if ( path.Hit && !path.StartedSolid && path.Distance < distance - Radius * 2f && CanStandOn( path.Normal ) )
			{
				grip = path.HitPosition;
				normal = path.Normal;
				end = grip + normal * (Radius + 0.2f);
				distance = (end - _center).Length;
			}
		}

		IsLatching = true;
		GripPoint = grip;
		_gripNormal = normal;
		_latchFromCenter = _center;
		_latchFromUp = Up;
		_latchTime = 0f;
		_latchImpactDone = false;

		// The feet hold where they are (only if they are actually on something).
		FeetHolding = Attached;
		FootPoint = _center - Up * Radius;

		// A near grip is a quick pull; a far one takes as long as the distance needs.
		_pullSeconds = MathF.Max( PullSeconds, distance * 0.5f / MathF.Max( PullSpeed, 1f ) );

		// Come out moving along the new face: keep our heading if it survives there, otherwise
		// carry on "over the top" (up a wall we ran into, down a ledge we went over).
		float speed = _velocity.Length;
		var carry = Flatten( _velocity, normal );
		if ( carry.Length < speed * 0.5f ) carry = Flatten( Up, normal ) * (Vector3.Dot( _velocity, normal ) < 0f ? 1f : -1f);
		_carryDirection = carry.Length > 0.01f ? carry.Normal : Vector3.Zero;
		_carrySpeed = MathF.Max( speed * 0.85f, Speed * 0.5f );
		_velocity = Vector3.Zero;
	}

	void UpdateLatch( float dt )
	{
		_latchTime += dt;

		// 1. Reach: the hands go out to the grip point; feet hold, body holds.
		if ( _latchTime < ReachSeconds )
		{
			ReachAmount = _latchTime / MathF.Max( ReachSeconds, 0.001f );
			return;
		}

		// 2. Latch: hands hit the rock. Both ends hold.
		if ( !_latchImpactDone )
		{
			_latchImpactDone = true;
			ReachAmount = 1f;
			LatchImpact( GripPoint, _gripNormal, 1f );
			Thump( 0.45f );
		}

		// How far round the swing we are, 0..1. The pull takes it to the halfway "bridge" quickly
		// and eases to a stop there; the foot swing then snaps the rest.
		float t = _latchTime - ReachSeconds;
		float e, turn;
		if ( t < _pullSeconds )
		{
			float p = t / MathF.Max( _pullSeconds, 0.001f );
			e = 0.5f * (1f - (1f - p) * (1f - p));
			turn = e;
		}
		else
		{
			// 4. Swing: feet let go of the old face.
			if ( FeetHolding )
			{
				FeetHolding = false;
				LatchImpact( FootPoint, _latchFromUp, 0.2f );
			}

			float p = Math.Clamp( (t - _pullSeconds) / MathF.Max( FootSeconds, 0.001f ), 0f, 1f );
			e = 0.5f + 0.5f * p * p * (3f - 2f * p);
			LegTuck = MathF.Sin( p * MathF.PI );

			// The body's turn runs a little ahead of its position and swings past before it
			// settles, so the plant has some whip to it.
			float q = p - 1f;
			turn = 0.5f + 0.5f * (1f + 2.6f * q * q * q + 1.6f * q * q);
		}

		var from = _latchFromCenter - GripPoint;
		var to = _gripNormal * (Radius + 0.2f);
		float length = from.Length + (to.Length - from.Length) * e;
		var direction = from.Length > 0.01f ? SlerpDirection( from.Normal, to.Normal, e ) : to.Normal;
		_center = GripPoint + direction * length;
		Up = SlerpDirection( _latchFromUp, _gripNormal, turn );

		if ( e < 1f ) return;

		// Feet latch on the new face: planted, free to move.
		IsLatching = false;
		FeetHolding = false;
		ReachAmount = 0f;
		LegTuck = 0f;
		Up = _gripNormal;
		Attached = true;
		_velocity = _carryDirection * _carrySpeed;
		_sinceLatch = 0;
		LatchImpact( _center - Up * Radius, Up, 0.6f );
		Thump( 1f );
	}

	/// <summary>The feel of grabbing rock: a soft thud and a small camera nudge toward the surface.</summary>
	void LatchImpact( Vector3 point, Vector3 normal, float strength )
	{
		_cameraKick -= normal * 8f * strength;
		if ( !string.IsNullOrEmpty( LatchSound ) )
		{
			var sound = Sound.Play( LatchSound, point );
			if ( sound.IsValid() ) sound.Volume = 0.6f * strength;
		}
	}

	/// <summary>Hold the grab button to pick the grip point by eye; release to latch and pull.</summary>
	void UpdateAim()
	{
		bool usable = MouseCaptured && SinceRecapture > 0.2f && !IsLatching && !InputLocked && !IsPinned;
		bool held = usable && !string.IsNullOrEmpty( AimAction ) && Input.Down( AimAction );
		bool released = _aimHeld && !held;
		bool hadTarget = IsAiming;
		_aimHeld = held;

		if ( released && hadTarget && !IsLatching )
		{
			IsAiming = false;
			ShowAimMarker( false );
			BeginLatch( GripPoint, _aimNormal );
			return;
		}

		IsAiming = false;
		if ( held && Scene.Camera.IsValid() )
		{
			// The point under the crosshair, if the hands could reach and hold it.
			var cam = Scene.Camera;
			var forward = cam.WorldRotation.Forward;
			var tr = Scene.Trace.Ray( cam.WorldPosition, cam.WorldPosition + forward * (CameraDistance + AimReach) )
				.IgnoreGameObjectHierarchy( GameObject ).WithoutTags( "debris" ).Run();
			if ( tr.Hit && (tr.HitPosition - _center).Length <= AimReach && CanStandOn( tr.Normal ) )
			{
				IsAiming = true;
				GripPoint = tr.HitPosition;
				_aimNormal = tr.Normal;
			}
			else
			{
				// Nothing in reach: the arms still go out, groping along the line of sight.
				GripPoint = _center + forward * 60f;
			}
		}

		// Arms out while held: stretched at a real grip point, searching when there is none.
		if ( !IsLatching ) ReachAmount = held ? (IsAiming ? 0.95f : 0.7f) : 0f;
		ShowAimMarker( IsAiming );
	}

	/// <summary>A small glowing dot on the rock where the hands will latch.</summary>
	void ShowAimMarker( bool show )
	{
		if ( !show )
		{
			if ( _aimMarker.IsValid() ) _aimMarker.Enabled = false;
			return;
		}

		if ( !_aimMarker.IsValid() )
		{
			_aimMarker = new GameObject( true, "Grip Marker" );
			_aimMarker.Flags |= GameObjectFlags.NotSaved;
			var renderer = _aimMarker.Components.Create<ModelRenderer>();
			renderer.Model = Model.Load( "models/dev/sphere.vmdl" );
			renderer.Tint = new Color( 0.5f, 1f, 0.6f );
			renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
			_aimMarker.WorldScale = 0.12f;
		}

		_aimMarker.Enabled = true;
		_aimMarker.WorldPosition = GripPoint + _aimNormal * 3f;
	}

	protected override void OnDisabled()
	{
		if ( _aimMarker.IsValid() ) _aimMarker.Destroy();
		Mouse.Visibility = MouseVisibility.Auto;
		if ( _bodyHiddenForCamera ) HideBodyForCamera( false );
		_cameraDistance = -1f;
	}

	/// <summary>Turns one direction toward another along the shortest arc, even through 180 degrees.</summary>
	static Vector3 SlerpDirection( Vector3 a, Vector3 b, float t )
	{
		float dot = Math.Clamp( Vector3.Dot( a, b ), -1f, 1f );
		float angle = MathF.Acos( dot ) * 180f / MathF.PI;
		if ( angle < 0.01f ) return b;
		var axis = Vector3.Cross( a, b );
		if ( axis.Length < 0.0001f ) axis = Vector3.Cross( a, MathF.Abs( a.z ) < 0.9f ? Vector3.Up : Vector3.Forward );
		return Rotation.FromAxis( axis.Normal, angle * t ) * a;
	}

	/// <summary>Moves the sphere, grabbing onto or sliding along whatever it runs into.</summary>
	void Move( Vector3 delta )
	{
		var hit = Sphere( _center, _center + delta );

		// Touching or slightly embedded (common on bumpy rock): keep moving and ease out along
		// our up. If that ever carries us through the rock, KeepInside() puts us back.
		if ( hit.StartedSolid )
		{
			_center += delta + Up * 0.5f;
			return;
		}

		// Nothing ahead, or only grazing the surface we're leaving.
		if ( !hit.Hit || Vector3.Dot( delta, hit.Normal ) >= 0f )
		{
			_center += delta;
			return;
		}

		_center = hit.EndPosition + hit.Normal * 0.2f;

		// Can't cling to it (or we only just jumped): slide along it.
		if ( !CanStandOn( hit.Normal ) || _sinceJump < 0.2f )
		{
			_velocity = Flatten( _velocity, hit.Normal );
			return;
		}

		if ( !Attached )
		{
			// Caught something out of the air: grab on at once, with the thud.
			Up = hit.Normal;
			Attached = true;
			_velocity = Flatten( _velocity, Up );
			_sinceLatch = 0;
			LatchImpact( hit.HitPosition, hit.Normal, 0.8f );
			Thump( 1.3f );
			return;
		}

		// Already on a surface. Small changes of slope are handled by StickToSurface; only a real
		// corner (floor into wall) switches surface here, carrying our speed up the new face so
		// we run up walls instead of stopping dead at their base.
		if ( Vector3.Dot( hit.Normal, Up ) < 0.8f )
		{
			float speed = _velocity.Length;
			var along = Flatten( Up, hit.Normal );
			Up = hit.Normal;
			_velocity = Flatten( _velocity, Up );
			if ( along.Length > 0.01f && _velocity.Length < speed * 0.6f )
				_velocity = along.Normal * speed * 0.7f;
		}
		else
		{
			_velocity = Flatten( _velocity, hit.Normal );
		}
	}

	/// <summary>
	/// Last line of defence: whatever happened with collision this tick, the lizard ends it inside
	/// the cave shell. If it was outside it is put back just inside and left to fall and re-grab.
	/// </summary>
	bool KeepInside()
	{
		if ( !StayInCaves ) return false;
		if ( !_cave.IsValid() || !_cave.Active ) _cave = Scene.GetAllComponents<CaveGenerator>().FirstOrDefault();

		// Resting on rock the centre is a full radius clear of it, so only a centre that is nearly
		// in the rock (or beyond it) counts as outside.
		// The shell test is the costly part, so skip it while we haven't gone anywhere (the rock can
		// still move under us when it is reshaped, so look again a few times a second regardless).
		bool moved = false;
		if ( _cave.IsValid() && ((_center - _lastContained).LengthSquared > 0.25f || _sinceContained > 0.25f) )
		{
			moved = _cave.Contain( ref _center, Radius * 0.3f, Radius + 4f );
			_lastContained = _center;
			_sinceContained = 0;
		}

		// No cave (test scenes), or something went badly wrong: don't fall forever.
		if ( !moved && _center.z < _spawn.z - 6000f )
		{
			_center = _spawn;
			moved = true;
		}

		if ( !moved ) return false;
		_velocity = Vector3.Zero;
		Attached = false;
		Up = Vector3.Up;
		return true;
	}

	/// <summary>Keeps the body pressed to the surface, including round corners and over edges.</summary>
	void StickToSurface()
	{
		var down = Sphere( _center, _center - Up * StickDistance );
		_surface = down.Hit ? down.GameObject : null;
		if ( down.Hit && !down.StartedSolid && !CanStandOn( down.Normal ) )
		{
			Attached = false;
			return;
		}
		if ( down.Hit && !down.StartedSolid )
		{
			_center = down.EndPosition + down.Normal * 0.2f;
			Up = down.Normal;
			return;
		}

		// Nothing below: we ran off an outside edge. Look back underneath for the next face.
		var probe = _center - Up * StickDistance;
		var back = _velocity.Length > 1f ? _velocity.Normal : _facing;
		var wrap = Sphere( probe, probe - back * StickDistance * 1.5f );
		if ( wrap.Hit && !wrap.StartedSolid && CanStandOn( wrap.Normal ) )
		{
			// Reach over the edge, grip the face below and swing round onto it.
			BeginLatch( wrap.HitPosition, wrap.Normal );
			return;
		}

		Attached = false;
	}

	/// <summary>Movement input steered by the camera, laid flat on the current surface.</summary>
	Vector3 WishDirection()
	{
		// A cutscene has the controls: walk where it says, or stand still.
		if ( InputLocked )
		{
			if ( ForcedWish is not { } forced ) return Vector3.Zero;
			var flat = Flatten( forced, Up );
			return flat.Length > 1f ? flat.Normal : flat;
		}

		var move = Input.AnalogMove;
		if ( move.Length < 0.01f ) return Vector3.Zero;

		// W means "away from the camera along the surface" when the camera looks across the
		// surface (running on a floor), and "toward the top of the screen along the surface" when
		// the camera looks into it (climbing a wall, crossing an overhang or a ceiling). Blending
		// between the two by how squarely the camera faces the surface keeps W carrying on up and
		// over edges instead of steering back the way it came.
		var cam = Rotation.From( _look );
		float into = -Vector3.Dot( cam.Forward, Up );
		float w = Math.Clamp( (into - 0.25f) / 0.35f, 0f, 1f );
		w = w * w * (3f - 2f * w);

		var across = Flatten( cam.Forward, Up );
		var screenUp = Flatten( cam.Up, Up );
		if ( across.Length > 0.01f ) across = across.Normal;
		if ( screenUp.Length > 0.01f ) screenUp = screenUp.Normal;

		var forward = across * (1f - w) + screenUp * w;
		if ( forward.Length < 0.05f ) forward = screenUp.Length > 0.05f ? screenUp : across;
		if ( forward.Length < 0.05f ) forward = Flatten( Vector3.Up, Up );
		forward = forward.Normal;
		var left = Vector3.Cross( Up, forward );

		var wish = forward * move.x + left * move.y;
		return wish.Length > 1f ? wish.Normal : wish;
	}

	/// <summary>
	/// Set while people have hold of the lizard: the camera lifts and backs off so it looks down
	/// over the scrum instead of into somebody's back. People never block the camera either way.
	/// </summary>
	public bool ClearView { get; set; }
	float _clearView;
	StoryDirector _director;
	TimeSince _sinceDirectorLook = 10f;

	/// <summary>Below this much room behind it, the camera stops drawing the lizard's own body and rides at its head.</summary>
	[Property, Group( "Camera" )] public float CameraHideDistance { get; set; } = 62f;

	/// <summary>How quickly the camera backs out again once there is room (higher is quicker).</summary>
	[Property, Group( "Camera" )] public float CameraEaseOut { get; set; } = 3.5f;

	/// <summary>True while the camera is so close that the body is not being drawn.</summary>
	public bool CameraInside => _bodyHiddenForCamera;

	// Named camera-distance factors, like the speed factors: a mode can ask for a closer (below 1)
	// or wider (above 1) camera without overwriting anyone else, and clears it by setting 1.
	readonly Dictionary<string, float> _cameraZooms = new();
	float _cameraZoom = 1f;
	float _cameraDistance = -1f;

	/// <summary>Sets (or with 1, clears) one named multiplier on the camera's distance.</summary>
	public void SetCameraZoom( string name, float factor )
	{
		if ( MathF.Abs( factor - 1f ) < 0.0001f ) _cameraZooms.Remove( name );
		else _cameraZooms[name] = Math.Clamp( factor, 0.1f, 4f );
		_cameraZoom = 1f;
		foreach ( var f in _cameraZooms.Values ) _cameraZoom *= f;
	}

	// The body's renderers while the camera is too close to draw them, with what each was set to.
	readonly List<(ModelRenderer Renderer, ModelRenderer.ShadowRenderType Was)> _hiddenForCamera = new();
	bool _bodyHiddenForCamera;
	TimeSince _sinceHideScan = 10f;

	/// <summary>
	/// Stops (or resumes) drawing everything on the lizard without disabling anything: the
	/// renderers only cast shadows. While hidden it is called again now and then to catch parts
	/// added since (a graft, a skin).
	/// </summary>
	void HideBodyForCamera( bool hide )
	{
		_sinceHideScan = 0f;
		if ( hide )
		{
			_bodyHiddenForCamera = true;
			foreach ( var renderer in Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
			{
				if ( !renderer.IsValid() || renderer.RenderType == ModelRenderer.ShadowRenderType.ShadowsOnly ) continue;
				_hiddenForCamera.Add( (renderer, renderer.RenderType) );
				renderer.RenderType = ModelRenderer.ShadowRenderType.ShadowsOnly;
			}
			return;
		}

		_bodyHiddenForCamera = false;
		foreach ( var (renderer, was) in _hiddenForCamera )
			if ( renderer.IsValid() && renderer.RenderType == ModelRenderer.ShadowRenderType.ShadowsOnly ) renderer.RenderType = was;
		_hiddenForCamera.Clear();
	}

	void UpdateCamera()
	{
		var cam = Scene.Camera;
		if ( !cam.IsValid() ) return;

		var rot = Rotation.From( _look );

		// The camera's anchor trails the body very slightly, so sudden moves (a latch, a lunge)
		// are felt as the body pulling away and the camera catching up.
		_clearView = _clearView + ((ClearView ? 1f : 0f) - _clearView) * Math.Clamp( Time.Delta * 5f, 0f, 1f );
		// The rigged model stands a little taller than the body it rides on; the camera goes with it.
		float standLift = UseNewModel && Rig.IsValid() ? Rig.StandLift : 0f;
		var anchor = _center + _visualUp * (CameraHeight + standLift) + Vector3.Up * (60f * _clearView);
		bool fresh = !_cameraPrimed || (anchor - _cameraTarget).Length > 300f;
		if ( fresh ) { _cameraTarget = anchor; _cameraPrimed = true; }
		_cameraTarget = Vector3.Lerp( _cameraTarget, anchor, Math.Clamp( Time.Delta * 22f, 0f, 1f ) );
		var target = _cameraTarget;
		float wantedDistance = MathF.Max( (CameraDistance + 80f * _clearView) * _cameraZoom, 0f );
		// Keep the look-at point itself out of the rock (on a ceiling it hangs below the lizard).
		var lift = Scene.Trace.Sphere( 6f, _center, target ).IgnoreGameObjectHierarchy( GameObject ).WithoutTags( "crowd", "fatguy", "debris" ).Run();
		if ( lift.Hit ) target = lift.StartedSolid ? _center : lift.EndPosition;

		// How much room there is behind. The camera comes in at once (it is never left inside
		// rock) and eases back out, so a bumpy tunnel does not make it pump in and out.
		var tr = Scene.Trace.Sphere( 6f, target, target - rot.Forward * wantedDistance ).IgnoreGameObjectHierarchy( GameObject ).WithoutTags( "crowd", "fatguy", "debris" ).Run();
		float room = !tr.Hit ? wantedDistance : tr.StartedSolid ? 0f : MathF.Min( tr.Distance, wantedDistance );
		if ( fresh || _cameraDistance < 0f || room < _cameraDistance ) _cameraDistance = room;
		else _cameraDistance += (room - _cameraDistance) * Math.Clamp( Time.Delta * CameraEaseOut, 0f, 1f );

		// In a tight space the camera ends up on top of the lizard. Below CameraHideDistance the
		// body is not drawn (it still casts its shadow) and the camera rides just behind and above
		// the head, instead of looking at the inside of a leg.
		float hideAt = MathF.Max( CameraHideDistance, 1f );
		bool hide = _cameraDistance < (_bodyHiddenForCamera ? hideAt * 1.25f : hideAt);
		if ( hide != _bodyHiddenForCamera || (hide && _sinceHideScan > 0.5f) ) HideBodyForCamera( hide );

		var position = target - rot.Forward * _cameraDistance;
		float close = 1f - Math.Clamp( _cameraDistance / hideAt, 0f, 1f );
		if ( close > 0.01f )
		{
			var raised = position + _visualUp * (10f * close);
			var rise = Scene.Trace.Sphere( 4f, position, raised ).IgnoreGameObjectHierarchy( GameObject ).WithoutTags( "crowd", "fatguy", "debris" ).Run();
			position = !rise.Hit ? raised : rise.StartedSolid ? position : rise.EndPosition;
		}

		// (Looked for now and then, not every frame: most scenes have no director at all.)
		if ( !_director.IsValid() && _sinceDirectorLook > 1f )
		{
			_sinceDirectorLook = 0f;
			_director = StoryDirector.Get( Scene );
		}
		var shake = _director.IsValid() ? _director.ShakeOffset : Vector3.Zero;
		_cameraKick = Vector3.Lerp( _cameraKick, Vector3.Zero, Math.Clamp( Time.Delta * 14f, 0f, 1f ) );
		cam.WorldPosition = position + shake + _cameraKick;
		cam.WorldRotation = rot;
	}

	/// <summary>Shows whichever lizard <see cref="UseNewModel"/> asks for.</summary>
	void UpdateModelChoice()
	{
		bool showing = _rig.IsValid() && _rig.GameObject.Enabled;
		if ( UseNewModel == showing ) return;

		if ( UseNewModel )
		{
			if ( !_rig.IsValid() ) _rig = LizardRig.Attach( this );
			else _rig.GameObject.Enabled = true;
		}
		else if ( _rig.IsValid() ) _rig.GameObject.Enabled = false;

		var holder = Body.IsValid() ? Body : GameObject;
		var old = holder.Components.Get<ReptileBody>( FindMode.EverythingInSelfAndDescendants );
		if ( old.IsValid() ) old.Hidden = UseNewModel && _rig.IsValid();
	}

	/// <summary>The new model's rig, while it is the one showing.</summary>
	public LizardRig Rig => UseNewModel && _rig.IsValid() ? _rig : null;

	bool CanStandOn( Vector3 normal ) => ClingEnabled || normal.z > 0.55f;

	/// <summary>How hard a jump kicks a loose body it pushes off from, as mass times jump speed.</summary>
	[Property, Group( "Movement" )] public float JumpShoveMass { get; set; } = 55f;

	GameObject _surface; // what the feet are on

	/// <summary>Jumping off something that can move (a person) kicks it the other way, for real.</summary>
	void ShoveSurface()
	{
		if ( !_surface.IsValid() ) return;
		var body = _surface.Components.Get<Rigidbody>( FindMode.EverythingInSelfAndAncestors );
		if ( !body.IsValid() || !body.MotionEnabled ) return;
		body.ApplyImpulseAt( _center - Up * Radius, -Up * JumpSpeed * JumpShoveMass );
		_surface = null;
	}

	/// <summary>While set, people (anything tagged "crowd") do not block or carry the lizard: it goes through them.</summary>
	public bool PassCrowd { get; set; }

	SceneTraceResult Sphere( Vector3 from, Vector3 to )
	{
		var trace = Scene.Trace.Sphere( Radius, from, to ).IgnoreGameObjectHierarchy( GameObject );
		return (PassCrowd ? trace.WithoutTags( "debris", "crowd" ) : trace.WithoutTags( "debris" )).Run();
	}

	static Vector3 Flatten( Vector3 v, Vector3 normal ) => v - normal * Vector3.Dot( v, normal );
}