Stadium/CrowdPerson.cs

One crowd member (patron or guard) in a stadium game. Builds itself from box and sphere primitives on a single rigidbody and capsule, then runs a state machine: statue while waiting, recoiling during the shift, then either fleeing to an exit or running and leaping at the player lizard to grab a limb with a spring joint. Handles tripping, knockdowns, health and death, and procedural limb posing.

using System;

/// <summary>What one member of the crowd is doing with its body.</summary>
public enum CrowdState
{
	/// <summary>On its feet: standing at its spot, recoiling, running.</summary>
	Standing,
	/// <summary>Fallen over and flailing. Gets up again after a moment.</summary>
	Down,
	/// <summary>Has hold of one of the lizard's limbs and is hauling back on it.</summary>
	Holding,
	/// <summary>Killed. A limp body left where it fell.</summary>
	Dead,
}

/// <summary>
/// One person in the stadium: a patron or a guard. A cheap body of boxes and a sphere on a single
/// rigid body and capsule, so people really shove and pile up. Stands and bobs until the lizard
/// shows itself, recoils during the shift, then either walks and leaps at the lizard to seize one
/// of its limbs, or runs away and gets in everybody's way. They are held upright and only go
/// over when they trip on each other. Made by <see cref="CrowdSpawner"/>.
/// </summary>
[Title( "Crowd Person" ), Category( "Stadium" ), Icon( "directions_run" )]
public sealed class CrowdPerson : Component, Component.ICollisionListener
{
	/// <summary>Guards are bigger, tougher, faster, wear navy and a cap, and always go for the lizard.</summary>
	[Property] public bool IsGuard { get; set; }

	/// <summary>Chance that a patron runs at the lizard instead of away from it.</summary>
	[Property, Range( 0f, 1f )] public float GrabberChance { get; set; } = 0.4f;

	/// <summary>How close (flat distance, inches) a grabber has to be to take hold.</summary>
	[Property, Group( "Grabbing" )] public float GrabRange { get; set; } = 64f;

	/// <summary>Seconds it has to stay in range before the grab lands. Short: limbs are easy to catch.</summary>
	[Property, Group( "Grabbing" )] public float GrabWindup { get; set; } = 0.12f;

	/// <summary>No more than this many people hold the lizard at once (it has five limbs to hold).</summary>
	[Property, Group( "Grabbing" )] public int MaxPile { get; set; } = 5;

	/// <summary>How hard a holder hauls back against the lizard, in inches per second.</summary>
	[Property, Group( "Grabbing" )] public float CounterweightSpeed { get; set; } = 95f;

	/// <summary>A holder is this many times heavier while it hangs on.</summary>
	[Property, Group( "Grabbing" )] public float CounterweightMass { get; set; } = 1.8f;

	/// <summary>Stretched further than this from the limb, the grip is lost.</summary>
	[Property, Group( "Grabbing" )] public float GripSnapDistance { get; set; } = 170f;

	/// <summary>A grabber leaps at the lizard from between these distances.</summary>
	[Property, Group( "Leaping" )] public float LeapMinRange { get; set; } = 110f;
	[Property, Group( "Leaping" )] public float LeapMaxRange { get; set; } = 330f;

	/// <summary>Forward and upward speed of a leap.</summary>
	[Property, Group( "Leaping" )] public float LeapSpeed { get; set; } = 430f;
	[Property, Group( "Leaping" )] public float LeapUp { get; set; } = 250f;

	/// <summary>Seconds between one person's leaps (it varies a little).</summary>
	[Property, Group( "Leaping" )] public float LeapCooldown { get; set; } = 2.4f;

	/// <summary>Speed holders are thrown off at when the lizard breaks free.</summary>
	[Property, Group( "Grabbing" )] public float ThrowSpeed { get; set; } = 520f;

	/// <summary>Walking speed toward the lizard (fleers go half as fast again).</summary>
	[Property, Group( "Movement" )] public float RunSpeed { get; set; } = 140f;
	[Property, Group( "Movement" )] public float GuardSpeed { get; set; } = 175f;

	/// <summary>How quickly it reaches its walking speed (higher is snappier).</summary>
	[Property, Group( "Movement" )] public float Acceleration { get; set; } = 6f;

	/// <summary>Upward speed of the hop it does when blocked by a pile (grows if it stays blocked).</summary>
	[Property, Group( "Movement" )] public float HopSpeed { get; set; } = 300f;

	/// <summary>Scales how long anyone stays on the floor after a fall. Small: they are up again fast.</summary>
	[Property, Group( "Balance" )] public float DownTimeScale { get; set; } = 0.3f;

	/// <summary>How quickly it turns to face where it is looking.</summary>
	[Property, Group( "Balance" )] public float UprightGrip { get; set; } = 6f;

	/// <summary>
	/// Chance that a hard bump from another person trips it (guards: less than half that). This
	/// is the only way anyone falls over: on their own they are held upright.
	/// </summary>
	[Property, Group( "Balance" ), Range( 0f, 1f )] public float TripChance { get; set; } = 0.5f;

	/// <summary>How hard a bump has to be to trip it, in inches per second.</summary>
	[Property, Group( "Balance" )] public float TripSpeed { get; set; } = 120f;

	[Property, Group( "Health" )] public float PatronHealth { get; set; } = 30f;
	[Property, Group( "Health" )] public float GuardHealth { get; set; } = 70f;

	/// <summary>Fleers that make it into the exit doorway are gone, so the door doesn't jam for good.</summary>
	[Property] public bool LeaveThroughExit { get; set; } = true;

	public CrowdState State { get; private set; } = CrowdState.Standing;

	/// <summary>Which shirt colour to wear; below zero picks one at random.</summary>
	public int ShirtIndex { get; set; } = -1;

	/// <summary>When the lizard last ran this person down.</summary>
	public float LastBowled { get; private set; } = -100f;

	/// <summary>
	/// Shouldered or leaned on by the lizard: pushed with this change of velocity but left on its
	/// feet. <paramref name="stagger"/> seconds of not steering, if it was a proper shove.
	/// </summary>
	public void Push( Vector3 velocity, float stagger, float now )
	{
		if ( State == CrowdState.Dead || !_body.IsValid() ) return;
		if ( stagger > 0f ) LastBowled = now;
		_awake = true;
		_body.MotionEnabled = true;
		_body.Velocity += velocity;
		if ( stagger > 0f && State == CrowdState.Standing ) Stagger( stagger, 4f );
	}

	/// <summary>
	/// Run down by the charging lizard: knocked off its feet and thrown with this velocity, as a
	/// free physics body. It gets up again shortly.
	/// </summary>
	public void Bowl( Vector3 velocity, float now )
	{
		LastBowled = now;
		if ( State == CrowdState.Dead || !_body.IsValid() ) return;
		if ( State == CrowdState.Holding ) { EndGrip(); if ( _game.IsValid() ) _game.ReleaseGrab( GameObject ); }

		_awake = true;
		_body.MotionEnabled = true;
		StandUpright( false );
		_body.Velocity += velocity;
		_body.AngularVelocity += Vector3.Random * 8f;
		_leapUntil = 0f;
		FallDown( Game.Random.Float( 2.5f, 4.5f ) );
	}

	/// <summary>True if this one goes for the lizard once the panic starts.</summary>
	public bool IsGrabber { get; private set; }

	// ---- For hosts other than the stadium (the Sump's flashbacks). All off by default. -----------

	/// <summary>Who runs this crowd. Left empty it is found: the stadium's rules, else <see cref="CrowdHosts.Fallback"/>.</summary>
	public ICrowdHost Host { get; set; }

	/// <summary>
	/// While set, this one neither chases nor runs away during the chase: it stands where it is,
	/// or walks to <see cref="GoTo"/>. Clear it and it behaves like anybody else in the crowd.
	/// </summary>
	public bool Passive { get; set; }

	/// <summary>Where a <see cref="Passive"/> person walks to (a patrol point). Empty to stand still.</summary>
	public Vector3? GoTo { get; set; }

	/// <summary>What a <see cref="Passive"/> person faces while standing still. Empty to keep facing the way it was.</summary>
	public Vector3? LookAt { get; set; }

	/// <summary>Walking speed of a <see cref="Passive"/> person, in inches per second.</summary>
	public float PassiveSpeed { get; set; } = 70f;

	/// <summary>
	/// A way round walls, for places that have one (a flashback's <see cref="FlashbackNav"/>): given
	/// where it stands and where it is going, the point to walk at next. Its own position means
	/// wait. Empty in the stadium, where everybody walks straight.
	/// </summary>
	public Func<Vector3, Vector3, Vector3> Steer { get; set; }

	/// <summary>Asks <see cref="Steer"/> the way: turns the wish at the next point, or stops if told to wait. True if that is not straight at the goal.</summary>
	bool SteerRound( Vector3 me, Vector3 goal, ref Vector3 wish, ref float speed )
	{
		var via = Steer( me, goal );
		if ( (via - goal).WithZ( 0f ).LengthSquared < 1f ) return false;
		var to = (via - me).WithZ( 0f );
		float distance = to.Length;
		if ( distance > 1f ) wish = to / distance;
		else { wish = Vector3.Zero; speed = 0f; }
		return true;
	}

	/// <summary>True while a <see cref="Passive"/> person has nowhere further to walk.</summary>
	public bool AtGoal => GoTo is not { } goal || (goal - WorldPosition).WithZ( 0f ).Length < 34f;

	// ---- For the Rampage's town (RampagePopulace). All off by default. ---------------------------

	/// <summary>Keeps somebody who is down on the floor for this long from now (dazed), instead of the usual quick scramble up.</summary>
	public void DownFor( float seconds )
	{
		if ( State == CrowdState.Down ) _getUpAt = Time.Now + seconds;
	}

	/// <summary>Makes this one go for the lizard, or lose its nerve and run. Not while it has hold of a limb.</summary>
	public void SetGrabber( bool on )
	{
		if ( State != CrowdState.Holding ) IsGrabber = on;
	}

	/// <summary>What a <see cref="Passive"/> person does with its arms: 0 nothing, 1 a salute, 2 holding something out in front (a phone, a microphone), 3 a wave, 4 playing an instrument.</summary>
	public int Gesture { get; set; }

	/// <summary>Dress, by tint and accessory only: a shirt and trouser colour, a hat, a coat over the shirt. Set before it starts.</summary>
	public Color? ShirtTint { get; set; }
	public Color? TrouserTint { get; set; }
	public Color? HatTint { get; set; }
	public Color? CoatTint { get; set; }
	/// <summary>The hat has a wide brim all round (a straw hat) instead of a peak.</summary>
	public bool WideHat { get; set; }

	// ---- The body, in inches from the feet (before the guard's extra size) ----------------------
	const float CapsuleRadius = 12f;
	const float BodyHeight = 68f;
	const float ArmLength = 24f;
	const float LegLength = 28f;
	static readonly Vector3 ShoulderL = new( 0f, 14f, 52f );
	static readonly Vector3 ShoulderR = new( 0f, -14f, 52f );
	static readonly Vector3 HipL = new( 0f, 6f, 28f );
	static readonly Vector3 HipR = new( 0f, -6f, 28f );

	static readonly Color[] Shirts =
	{
		new( 0.85f, 0.22f, 0.2f ), new( 0.95f, 0.75f, 0.15f ), new( 0.2f, 0.6f, 0.85f ), new( 0.3f, 0.75f, 0.35f ),
		new( 0.9f, 0.45f, 0.75f ), new( 0.95f, 0.55f, 0.15f ), new( 0.9f, 0.9f, 0.88f ), new( 0.55f, 0.35f, 0.8f ),
		new( 0.15f, 0.7f, 0.65f ), new( 0.75f, 0.15f, 0.4f ),
	};
	static readonly Color[] Skins =
	{
		new( 0.96f, 0.8f, 0.68f ), new( 0.87f, 0.67f, 0.52f ), new( 0.72f, 0.5f, 0.36f ), new( 0.5f, 0.33f, 0.23f ), new( 0.35f, 0.23f, 0.17f ),
	};
	static readonly Color[] Trousers =
	{
		new( 0.16f, 0.2f, 0.36f ), new( 0.2f, 0.2f, 0.22f ), new( 0.45f, 0.38f, 0.28f ), new( 0.3f, 0.34f, 0.4f ),
	};
	static readonly Color Navy = new( 0.07f, 0.09f, 0.2f );

	ICrowdHost _game;
	Rigidbody _body;
	CapsuleCollider _collider;
	Health _health;
	GameObject _visual, _armL, _armR, _legL, _legR;

	bool _awake;            // false while it is a statue at its spot, before the shapeshift
	bool _panicker;         // a fleer that just runs about, not for the exit
	bool _reaching;         // winding up a grab: arms raised
	bool _lizardNear;       // close enough to stretch the arms out at it
	bool _limp;             // dead and done flailing
	float _phase;           // so the crowd doesn't move in step
	float _pace;            // personal speed factor
	float _speed;           // flat speed last physics step
	float _scale = 1f;
	float _windup, _stuck, _nextThink, _nextWander, _nextTrip, _staggerUntil, _getUpAt, _diedAt;
	int _hops, _frame;
	Vector3 _target;

	GameObject _anchor;      // the limb it has hold of
	SpringJoint _joint;      // the grip itself
	float _baseMass;
	float _nextLeap, _leapUntil;

	IGrabTurns _turns;       // the host's one-at-a-time grab queue, if it keeps one
	bool _hasTurn;           // it is this one's turn to grab
	float _telegraph;        // 0..1 through the warning before its grab lands
	bool _lunged;            // its warning is over and it has thrown itself at the lizard
	float _lungeUntil;       // when that lunge counts as a miss

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

		_phase = Game.Random.Float( 0f, 20f );
		_pace = Game.Random.Float( 0.8f, 1.15f );
		IsGrabber = IsGuard || Game.Random.Float( 0f, 1f ) < GrabberChance;
		_panicker = Game.Random.Float( 0f, 1f ) < 0.45f;
		_nextThink = Time.Now + Game.Random.Float( 0f, 0.25f );
		_target = WorldPosition;

		if ( IsGuard ) { _scale = 1.12f; WorldScale = _scale; }
		GameObject.Tags.Add( "crowd" );
		if ( IsGuard ) GameObject.Tags.Add( "guard" );

		BuildBody();

		_collider = Components.GetOrCreate<CapsuleCollider>();
		_collider.Start = new Vector3( 0f, 0f, CapsuleRadius );
		_collider.End = new Vector3( 0f, 0f, BodyHeight - CapsuleRadius );
		_collider.Radius = CapsuleRadius;
		_collider.Friction = 0.4f;

		// A statue until the lizard shows itself: nobody slowly tips off a tier during the speech.
		_body = Components.GetOrCreate<Rigidbody>();
		_baseMass = IsGuard ? 90f : 60f;
		_body.MassOverride = _baseMass;
		_body.AngularDamping = 1.5f;
		_body.LinearDamping = 0.2f;
		_body.EnhancedCcd = true;   // fast bodies must not tunnel through the floor
		_body.MotionEnabled = false;
		StandUpright( true );
		_nextLeap = Time.Now + Game.Random.Float( 0.5f, LeapCooldown );

		_health = Components.GetOrCreate<Health>();
		_health.MaxHealth = IsGuard ? GuardHealth : PatronHealth;
		_health.Killed += OnKilled;
		_health.Damaged += OnDamaged;

		_game = Host ?? CrowdHosts.Find( Scene );
		if ( _game.IsValid() ) _game.GripBroken += OnGripBroken;
		_turns = _game as IGrabTurns;
	}

	/// <summary>
	/// On: the body cannot tip (pitch and roll are locked), so nothing but a trip can put it on
	/// the floor. Off: it is free to tumble.
	/// </summary>
	void StandUpright( bool on )
	{
		if ( !_body.IsValid() ) return;
		var locking = _body.Locking;
		locking.Pitch = on;
		locking.Roll = on;
		_body.Locking = locking;
	}

	protected override void OnDestroy()
	{
		if ( _health is not null ) { _health.Killed -= OnKilled; _health.Damaged -= OnDamaged; }
		if ( _hasTurn ) { _hasTurn = false; _turns?.EndGrabTurn( GameObject ); }
		if ( _game is not null )
		{
			_game.GripBroken -= OnGripBroken;
			if ( State == CrowdState.Holding && _game.IsValid() ) _game.ReleaseGrab( GameObject );
		}
	}

	// ---- Building the body ----------------------------------------------------------------------

	void BuildBody()
	{
		var box = Model.Load( "models/dev/box.vmdl" );      // a 50 unit cube
		var sphere = Model.Load( "models/dev/sphere.vmdl" ); // radius 32

		var shirt = IsGuard ? Navy : Shirts[ShirtIndex >= 0 ? ShirtIndex % Shirts.Length : Game.Random.Next( Shirts.Length )];
		var skin = Skins[Game.Random.Next( Skins.Length )];
		var legs = IsGuard ? Navy : Trousers[Game.Random.Next( Trousers.Length )];
		if ( ShirtTint is { } shirtTint ) shirt = shirtTint;
		if ( TrouserTint is { } trouserTint ) legs = trouserTint;

		_visual = new GameObject( GameObject, true, "Body" );
		_visual.Flags |= GameObjectFlags.NotSaved;

		Part( box, "Torso", new Vector3( 0f, 0f, 41f ), new Vector3( 12f, 22f, 26f ) / 50f, shirt, true );
		Part( sphere, "Head", new Vector3( 0f, 0f, 61.5f ), new Vector3( 7.5f / 32f ), skin, true );

		// Limbs are long along their own +X, so pointing one is just turning it. Pitch 90 hangs down.
		_legL = Part( box, "Leg L", HipL, new Vector3( LegLength, 8f, 8f ) / 50f, legs, false );
		_legR = Part( box, "Leg R", HipR, new Vector3( LegLength, 8f, 8f ) / 50f, legs, false );
		_armL = Part( box, "Arm L", ShoulderL, new Vector3( ArmLength, 6f, 6f ) / 50f, shirt, false );
		_armR = Part( box, "Arm R", ShoulderR, new Vector3( ArmLength, 6f, 6f ) / 50f, shirt, false );
		RestPose();

		if ( IsGuard )
		{
			Part( box, "Cap", new Vector3( 0f, 0f, 68.5f ), new Vector3( 16f, 16f, 4f ) / 50f, Navy, false );
			Part( box, "Cap Brim", new Vector3( 10f, 0f, 67f ), new Vector3( 8f, 14f, 1.5f ) / 50f, Navy, false );
		}

		// Dress for other places than the stadium: a hat and a coat, by colour.
		if ( HatTint is { } hat )
		{
			Part( box, "Hat", new Vector3( 0f, 0f, 69f ), new Vector3( 15f, 15f, 5f ) / 50f, hat, false );
			if ( WideHat ) Part( box, "Hat Brim", new Vector3( 0f, 0f, 67f ), new Vector3( 30f, 30f, 1.5f ) / 50f, hat, false );
			else Part( box, "Hat Peak", new Vector3( 10f, 0f, 67f ), new Vector3( 8f, 14f, 1.5f ) / 50f, hat, false );
		}
		if ( CoatTint is { } coat )
			Part( box, "Coat", new Vector3( 0f, 0f, 37f ), new Vector3( 13.5f, 23.5f, 35f ) / 50f, coat, false );
	}

	GameObject Part( Model model, string name, Vector3 position, Vector3 scale, Color tint, bool shadows )
	{
		var go = new GameObject( _visual, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalPosition = position;
		go.LocalScale = scale;

		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = model;
		renderer.Tint = tint;
		if ( !shadows ) renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
		return go;
	}

	/// <summary>Arms and legs hanging straight down.</summary>
	void RestPose()
	{
		Limb( _legL, HipL, LegLength, 90f, 0f );
		Limb( _legR, HipR, LegLength, 90f, 0f );
		Limb( _armL, ShoulderL, ArmLength, 90f, 0f );
		Limb( _armR, ShoulderR, ArmLength, 90f, 0f );
	}

	/// <summary>Swings a limb about its joint. Pitch 90 hangs down, 0 points ahead, negative is raised.</summary>
	static void Limb( GameObject limb, Vector3 joint, float length, float pitch, float yaw ) =>
		Limb( limb, joint, length, new Angles( pitch, yaw, 0f ).ToRotation() );

	static void Limb( GameObject limb, Vector3 joint, float length, Rotation rotation )
	{
		if ( !limb.IsValid() ) return;
		limb.LocalRotation = rotation;
		limb.LocalPosition = joint + rotation.Forward * (length * 0.5f);
	}

	// ---- Physics: balance, running, falling, grabbing --------------------------------------------

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

		var phase = _game.CrowdPhase;
		if ( phase == CrowdPhase.Waiting ) return;
		if ( State != CrowdState.Dead && !_awake ) WakeUp();

		KeepAboveGround();
		if ( State == CrowdState.Dead ) return;
		if ( State == CrowdState.Holding ) { HangOn(); return; }

		// It is over: no more balancing or running. Bodies just settle.
		if ( phase == CrowdPhase.Over ) { DropTurn(); return; }

		float now = Time.Now;
		float dt = Time.Delta;
		var me = WorldPosition;
		var rotation = WorldRotation;
		var up = rotation.Up;

		if ( State == CrowdState.Down )
		{
			// Back on its feet quickly: as soon as its time is up and it is not being flung about.
			if ( now >= _getUpAt && (_body.Velocity.Length < 320f || now >= _getUpAt + 1f) ) GetUp();
			return;
		}

		var player = _game.Player;
		var lizard = player.IsValid() ? player.WorldPosition : _game.Focus;
		var toLizard = (lizard - me).WithZ( 0f );
		float lizardDistance = toLizard.Length;

		if ( now >= _nextThink )
		{
			_nextThink = now + 0.25f;
			if ( me.z < _game.GroundHeight( me ) - 600f ) { GameObject.Destroy(); return; } // fell out of the hall
			if ( phase == CrowdPhase.Chasing && !IsGrabber && !Passive )
			{
				if ( LeaveThroughExit && _game.InExit( me ) ) { GameObject.Destroy(); return; }
				ChooseFleeTarget( me, lizard, lizardDistance, now );
			}
		}

		// Where to go, how fast, and which way to face.
		Vector3 wish;
		float speed;
		var face = lizardDistance > 1f ? toLizard / lizardDistance : rotation.Forward.WithZ( 0f ).Normal;
		bool detour = false;   // walking round a wall (only where there is a Steer)

		if ( phase == CrowdPhase.Recoiling )
		{
			// Backing away from the thing on the stage, faster as it gets worse.
			wish = -face;
			speed = 45f * _game.ShiftProgress;
			_lizardNear = false;
		}
		else
		{
			var to = IsGrabber ? toLizard : (_target - me).WithZ( 0f );
			float distance = to.Length;
			wish = distance > 1f ? to / distance : Vector3.Zero;
			// Grabbers walk; people running away run.
			float pace = IsGuard ? GuardSpeed : RunSpeed * _pace;
			speed = distance > 30f ? (IsGrabber ? pace : pace * 1.5f) : 0f;
			if ( Steer is not null && !Passive && speed > 0f ) detour = SteerRound( me, me + to, ref wish, ref speed );
			if ( !IsGrabber && speed > 0f ) face = wish; // fleers look where they run
			_lizardNear = lizardDistance < 260f;

			// Nobody runs straight (but nearly, on the way round a wall).
			float wobble = MathF.Sin( now * 3.1f + _phase ) * (detour ? 0.15f : 0.4f);
			float cos = MathF.Cos( wobble ), sin = MathF.Sin( wobble );
			wish = new Vector3( wish.x * cos - wish.y * sin, wish.x * sin + wish.y * cos, 0f );

			// Not part of the chase (a flashback's patrol, or somebody just standing about): walks
			// straight to where it was sent, or stands, and does not stare at the lizard.
			if ( Passive )
			{
				var goal = GoTo.HasValue ? (GoTo.Value - me).WithZ( 0f ) : Vector3.Zero;
				float left = goal.Length;
				wish = left > 1f ? goal / left : Vector3.Zero;
				speed = left > 30f ? PassiveSpeed : 0f;
				if ( Steer is not null && speed > 0f ) detour = SteerRound( me, GoTo.Value, ref wish, ref speed );
				_lizardNear = false;

				var ahead = rotation.Forward.WithZ( 0f );
				face = ahead.Length > 0.01f ? ahead.Normal : Vector3.Forward;
				if ( speed > 0f ) face = wish;
				else if ( LookAt.HasValue )
				{
					var look = (LookAt.Value - me).WithZ( 0f );
					if ( look.Length > 1f ) face = look.Normal;
				}
			}
		}

		var velocity = _body.Velocity;
		bool grounded = MathF.Abs( velocity.z ) < 45f;
		bool leaping = now < _leapUntil;

		// The leap: from a few strides out, a grabber throws itself at the lizard. (Where grabs
		// are taken in turns, the only leap is the lunge at the end of a turn's warning: below.)
		if ( _turns is null && phase == CrowdPhase.Chasing && IsGrabber && !Passive && !detour && !leaping && grounded && now >= _nextLeap
			&& lizardDistance > LeapMinRange * _scale && lizardDistance < LeapMaxRange && !_game.Slippery )
		{
			_nextLeap = now + LeapCooldown * Game.Random.Float( 0.7f, 1.4f );
			_leapUntil = now + 0.85f;
			_body.Velocity = face * LeapSpeed + Vector3.Up * LeapUp;
			_stuck = 0f;
			DropTurn();
			return;
		}

		// In the air on a leap it keeps the speed it jumped with.
		var flat = leaping
			? velocity.WithZ( 0f )
			: Vector3.Lerp( velocity.WithZ( 0f ), wish * speed, MathF.Min( dt * Acceleration, 1f ) );
		_speed = flat.Length;

		// Driving but getting nowhere: blocked by a pile (or the stage). Clamber over it.
		bool blocked = phase == CrowdPhase.Chasing && speed > 50f && _speed < speed * 0.25f && MathF.Abs( velocity.z ) < 40f;
		if ( blocked ) _stuck += dt;
		else { _stuck = MathF.Max( _stuck - dt * 2f, 0f ); if ( _speed > speed * 0.6f ) _hops = 0; }

		if ( _stuck > 0.6f )
		{
			_stuck = 0f;
			velocity.z = HopSpeed * (1f + 0.2f * Math.Min( _hops, 3 ));
			flat += wish * 130f;
			_hops++;
		}
		_body.Velocity = flat.WithZ( velocity.z );

		// Facing: the body is locked upright, so all there is to do is turn toward where it looks.
		if ( now >= _staggerUntil ) TurnToward( face, dt );

		// Grabbing: a limb in reach is seized almost at once, and straight away out of a leap.
		bool wasReaching = _reaching;
		_reaching = false;
		if ( phase != CrowdPhase.Chasing || !IsGrabber || Passive || !player.IsValid() || _game.Slippery ) { DropTurn(); return; }

		// Once the arms are up it follows through a little further than it would start from.
		float rise = lizard.z - me.z;
		float range = GrabRange * _scale * (wasReaching ? 1.3f : 1f);
		bool level = rise > -50f && rise < 95f && _game.Grabbers < MaxPile;
		bool inReach = lizardDistance < range && level;

		if ( _turns is not null )
		{
			// One at a time, with a warning. Whoever is near enough asks for the turn. With it,
			// the arms go up for a beat (the tell). Then the grab: at once if the lizard is in
			// reach, otherwise a lunge at where it is heading, and the grip lands only if that
			// lunge gets there. Out of the way by then: a miss, and somebody else's turn.
			bool near = level && lizardDistance < MathF.Max( LeapMaxRange, range );
			if ( !near && !_lunged ) { DropTurn(); return; }
			if ( !_turns.RequestGrabTurn( GameObject, out float progress ) ) { DropTurn(); return; }

			_hasTurn = true;
			_reaching = true;
			_telegraph = progress;
			if ( progress < 1f ) return;

			if ( inReach )
			{
				if ( _game.TryGrab( GameObject, out var held ) ) TakeHold( held );
				DropTurn();
				return;
			}

			if ( !_lunged )
			{
				// The lunge, at where the lizard will be in a moment.
				_lunged = true;
				_lungeUntil = now + 0.95f;
				var lead = (lizard + player.Velocity.WithZ( 0f ) * 0.3f - me).WithZ( 0f );
				var aim = lead.Length > 1f ? lead.Normal : face;
				_leapUntil = now + 0.85f;
				_nextLeap = now + LeapCooldown;
				_body.Velocity = aim * LeapSpeed + Vector3.Up * LeapUp;
				_stuck = 0f;
				return;
			}

			if ( now >= _lungeUntil ) DropTurn();   // it missed
			return;
		}

		if ( !inReach ) { DropTurn(); return; }
		_reaching = true;
		_windup += dt;
		_telegraph = Math.Clamp( _windup / MathF.Max( GrabWindup, 0.01f ), 0f, 1f );
		if ( _windup < GrabWindup && !leaping ) return;
		_windup = 0f;
		if ( _game.TryGrab( GameObject, out var anchor ) ) TakeHold( anchor );
	}

	/// <summary>Stops winding up a grab, and gives the turn back if it had it.</summary>
	void DropTurn()
	{
		_windup = 0f;
		_telegraph = 0f;
		_reaching = false;
		_lunged = false;
		if ( !_hasTurn ) return;
		_hasTurn = false;
		_turns?.EndGrabTurn( GameObject );
	}

	/// <summary>Spins about the vertical to face a flat direction.</summary>
	void TurnToward( Vector3 face, float dt )
	{
		var forward = WorldRotation.Forward.WithZ( 0f );
		float turn = forward.x * face.y - forward.y * face.x;
		if ( forward.x * face.x + forward.y * face.y < 0f ) turn = turn >= 0f ? 1f : -1f;
		_body.AngularVelocity = Vector3.Lerp( _body.AngularVelocity, Vector3.Up * (turn * 6f), MathF.Min( dt * UprightGrip, 1f ) );
	}

	/// <summary>
	/// Nobody ends up under the floor, the stage or the stands. If collision ever lets a body
	/// through, it is put back on top and stops falling.
	/// </summary>
	void KeepAboveGround()
	{
		var p = WorldPosition;
		float ground = _game.GroundHeight( p );
		if ( p.z >= ground - 8f ) return;

		WorldPosition = p.WithZ( ground + 1f );
		var velocity = _body.Velocity;
		if ( velocity.z < 0f ) _body.Velocity = velocity.WithZ( 0f );
	}

	/// <summary>The statue comes alive: the lizard has shown itself.</summary>
	void WakeUp()
	{
		_awake = true;
		if ( State == CrowdState.Holding ) return;
		_body.MotionEnabled = true;
	}

	/// <summary>A fleer picks somewhere to run: away from the lizard if it is close, else out or just about.</summary>
	void ChooseFleeTarget( Vector3 me, Vector3 lizard, float lizardDistance, float now )
	{
		if ( lizardDistance < (_panicker ? 650f : 220f) )
		{
			var away = (me - lizard).WithZ( 0f );
			away = away.Length > 1f ? away.Normal : Vector3.Forward;
			_target = Contain( me + away * 400f );
			_nextWander = now + 1f;
			return;
		}

		if ( !_panicker ) { _target = _game.ExitRoute( me ); return; }

		// Headless chicken: somewhere else on the floor, every few seconds.
		if ( now < _nextWander ) return;
		_nextWander = now + Game.Random.Float( 2f, 4f );
		_target = _game.WanderPoint();
	}

	// Where the way out is, and where the walls are, is the host's business (see ICrowdHost).
	Vector3 Contain( Vector3 p ) => _game.Contain( p );

	void FallDown( float seconds )
	{
		State = CrowdState.Down;
		_getUpAt = Time.Now + seconds * DownTimeScale;
		DropTurn();
		_stuck = 0f;
	}

	/// <summary>Scrambles back onto its feet: snapped upright where it lies, with a small hop.</summary>
	void GetUp()
	{
		var middle = WorldTransform.PointToWorld( new Vector3( 0f, 0f, BodyHeight * 0.5f ) );
		var forward = WorldRotation.Up.WithZ( 0f ); // lying down, the head points the way it will face
		if ( forward.Length < 0.1f ) forward = WorldRotation.Forward.WithZ( 0f );

		WorldRotation = Rotation.LookAt( forward.Length > 0.01f ? forward.Normal : Vector3.Forward, Vector3.Up );
		WorldPosition = middle + Vector3.Down * (CapsuleRadius * _scale - 3f);
		_body.Velocity = new Vector3( 0f, 0f, 150f );
		_body.AngularVelocity = Vector3.Zero;

		State = CrowdState.Standing;
		_staggerUntil = 0f;
		_hops = 0;
		StandUpright( true );
		RestPose();
	}

	/// <summary>Knocked off its stride for a moment: it stops steering, but stays on its feet.</summary>
	void Stagger( float seconds, float spin )
	{
		_staggerUntil = Time.Now + seconds;
		_body.AngularVelocity += Vector3.Up * (Game.Random.Float( -1f, 1f ) * spin);
	}

	/// <summary>Trips over somebody: the upright lock comes off and it goes down in a tumble.</summary>
	void Trip( Vector3 push )
	{
		StandUpright( false );
		var axis = new Vector3( Game.Random.Float( -1f, 1f ), Game.Random.Float( -1f, 1f ), 0f );
		_body.AngularVelocity += axis.Normal * 7f;
		_body.Velocity += push.WithZ( 0f ) * 0.4f + Vector3.Up * 60f;
		_leapUntil = 0f;
		FallDown( Game.Random.Float( 1.5f, 3.5f ) );
	}

	public void OnCollisionStart( Collision collision )
	{
		// Tripping over somebody else is the only way anyone goes down.
		if ( State != CrowdState.Standing || !_awake || Time.Now < _nextTrip || !_game.IsValid() ) return;
		if ( _game.CrowdPhase == CrowdPhase.Over ) return;
		_nextTrip = Time.Now + 0.25f;

		if ( MathF.Abs( collision.Contact.NormalSpeed ) < TripSpeed ) return;
		var other = collision.Other.GameObject;
		if ( !other.IsValid() || !other.Tags.Has( "crowd" ) ) return;
		if ( Game.Random.Float( 0f, 1f ) > TripChance * (IsGuard ? 0.4f : 1f) ) return;

		Trip( _body.Velocity );
	}

	public void OnCollisionUpdate( Collision collision ) { }
	public void OnCollisionStop( CollisionStop collision ) { }

	// ---- Holding a limb -------------------------------------------------------------------------

	/// <summary>Seizes the limb: ties a spring joint from its hands to the limb and digs in.</summary>
	void TakeHold( GameObject anchor )
	{
		State = CrowdState.Holding;
		_reaching = false;
		_anchor = anchor;
		_leapUntil = 0f;

		// The grip itself: a short, stiff spring from in front of its chest to the limb. It does
		// not break by itself; the game decides when the lizard has shaken hard enough.
		_joint = Components.Create<SpringJoint>();
		_joint.Attachment = Joint.AttachmentMode.LocalFrames;
		_joint.LocalFrame1 = new Transform( new Vector3( 16f, 0f, 48f ) );
		_joint.LocalFrame2 = new Transform( Vector3.Zero );
		_joint.MinLength = 0f;
		_joint.MaxLength = 16f;
		_joint.RestLength = 6f;
		_joint.Frequency = 5f;
		_joint.Damping = 0.7f;
		_joint.EnableCollision = false;
		_joint.Body = anchor;

		// Dead weight on the end of the limb.
		_body.MassOverride = _baseMass * CounterweightMass;
		_body.LinearDamping = 1.2f;
	}

	/// <summary>
	/// Hanging on: leans back and hauls against the lizard, as a counterweight, still on its feet
	/// and still solid. Lets go if the limb is torn out of reach.
	/// </summary>
	void HangOn()
	{
		var player = _game.Player;
		if ( !player.IsValid() || !_anchor.IsValid() || _game.CrowdPhase != CrowdPhase.Chasing ) { LetGo(); return; }

		var me = WorldPosition;
		var toLimb = _anchor.WorldPosition - me;
		if ( (_joint.IsValid() && _joint.IsBroken) || toLimb.Length > GripSnapDistance ) { LetGo(); return; }

		// Pull the opposite way to wherever the lizard is trying to go; if it is still, straight back.
		var away = player.Velocity.WithZ( 0f );
		away = away.Length > 30f ? -away.Normal : -toLimb.WithZ( 0f ).Normal;
		float dt = Time.Delta;
		var velocity = _body.Velocity;
		var flat = Vector3.Lerp( velocity.WithZ( 0f ), away * CounterweightSpeed, MathF.Min( dt * Acceleration, 1f ) );
		_body.Velocity = flat.WithZ( velocity.z );
		_speed = flat.Length;

		var face = toLimb.WithZ( 0f );
		if ( face.Length > 1f ) TurnToward( face.Normal, dt );
	}

	/// <summary>Lets go without being thrown: the grip just ends.</summary>
	void LetGo()
	{
		EndGrip();
		if ( _game.IsValid() ) _game.ReleaseGrab( GameObject );
		if ( State == CrowdState.Holding ) State = CrowdState.Standing;
	}

	/// <summary>Removes the joint and the extra weight.</summary>
	void EndGrip()
	{
		if ( _joint.IsValid() ) _joint.Destroy();
		_joint = null;
		_anchor = null;
		if ( _body.IsValid() ) { _body.MassOverride = _baseMass; _body.LinearDamping = 0.2f; }
	}

	void OnGripBroken( GameObject holder )
	{
		if ( holder == GameObject && State == CrowdState.Holding ) ThrowOff( 1f );
	}

	/// <summary>Shaken off: flung away from the lizard and up, to tumble and lie there for a while.</summary>
	void ThrowOff( float strength )
	{
		var player = _game.IsValid() ? _game.Player : null;
		var out_ = player.IsValid() ? (WorldPosition - player.WorldPosition).WithZ( 0f ) : Vector3.Zero;
		out_ = out_.Length > 1f ? out_.Normal : -WorldRotation.Forward.WithZ( 0f ).Normal;

		EndGrip();
		StandUpright( false );
		_awake = true;
		_body.MotionEnabled = true;
		_body.Velocity = (out_ * Game.Random.Float( 0.7f, 1.1f ) + Vector3.Up * Game.Random.Float( 0.5f, 0.9f )) * ThrowSpeed * strength;
		_body.AngularVelocity = Vector3.Random * 9f;

		FallDown( Game.Random.Float( 2f, 3.5f ) );
	}

	// ---- Being bitten ----------------------------------------------------------------------------

	void OnDamaged( float amount, GameObject attacker )
	{
		// The killing bite is handled in OnKilled, which comes straight after this.
		if ( State != CrowdState.Standing || !_body.IsValid() || (_health.IsValid() && _health.Current <= 0f) ) return;

		// Survived a bite (a guard): knocked back and off its stride, but still standing.
		_body.MotionEnabled = true;
		_awake = true;
		_body.Velocity += ShoveFrom( attacker ) * 220f + Vector3.Up * 120f;
		Stagger( 0.9f, 6f );
	}

	void OnKilled( GameObject attacker )
	{
		if ( State == CrowdState.Dead ) return;
		bool wasHolding = State == CrowdState.Holding;

		State = CrowdState.Dead;
		IsGrabber = false;
		DropTurn();
		_diedAt = Time.Now;
		if ( _game.IsValid() ) _game.ReleaseGrab( GameObject );
		if ( !_body.IsValid() ) return;

		// Fully limp from here: no balance, no running, just a body thrown away from the teeth.
		if ( wasHolding ) EndGrip();
		StandUpright( false );
		_body.MotionEnabled = true;
		_awake = true;
		_body.Velocity += ShoveFrom( attacker ) * 300f + Vector3.Up * 190f;
		_body.AngularVelocity = Vector3.Random * 7f;
	}

	Vector3 ShoveFrom( GameObject attacker )
	{
		var away = attacker.IsValid() ? (WorldPosition - attacker.WorldPosition).WithZ( 0f ) : Vector3.Zero;
		return away.Length > 1f ? away.Normal : -WorldRotation.Forward.WithZ( 0f ).Normal;
	}

	// ---- Looks: bobbing, arms, legs ---------------------------------------------------------------

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

		// People far from the lizard only move their limbs every fourth frame.
		_frame++;
		var player = _game.Player;
		var lizard = player.IsValid() ? player.WorldPosition : _game.Focus;
		if ( (_frame & 3) != 0 && (lizard - WorldPosition).LengthSquared > 1000f * 1000f ) return;

		float t = Time.Now + _phase;
		var phase = _game.CrowdPhase;

		if ( State == CrowdState.Dead )
		{
			// A last twitch, then still.
			float life = 1f - (Time.Now - _diedAt) / 1.2f;
			if ( life > 0f ) { Flail( t, life ); return; }
			Limb( _armL, ShoulderL, ArmLength, 150f, 30f );
			Limb( _armR, ShoulderR, ArmLength, 60f, -40f );
			Limb( _legL, HipL, LegLength, 100f, 15f );
			Limb( _legR, HipR, LegLength, 75f, -10f );
			_limp = true;
			return;
		}

		if ( State == CrowdState.Down ) { Flail( t, 1f ); return; }

		if ( State == CrowdState.Holding )
		{
			// Both hands on the limb, legs braced wide and scrabbling as it hauls back.
			if ( _anchor.IsValid() )
			{
				var grip = _anchor.WorldPosition;
				var back = WorldRotation.Inverse;
				Limb( _armL, ShoulderL, ArmLength, PointAt( back, ShoulderL, grip ) );
				Limb( _armR, ShoulderR, ArmLength, PointAt( back, ShoulderR, grip ) );
			}
			float brace = MathF.Sin( t * 14f ) * 14f;
			Limb( _legL, HipL, LegLength, 65f + brace, 12f );
			Limb( _legR, HipR, LegLength, 65f - brace, -12f );
			return;
		}

		if ( phase == CrowdPhase.Waiting )
		{
			// Waiting for the speech: shifting from foot to foot.
			_visual.LocalPosition = new Vector3( 0f, 0f, MathF.Sin( t * 2.2f ) * 1.2f );
			return;
		}

		if ( phase == CrowdPhase.Recoiling )
		{
			// The hands come up as it dawns on them, shaking.
			float p = _game.ShiftProgress;
			float raise = 90f - 160f * p + MathF.Sin( t * 31f ) * 6f * p;
			_visual.LocalPosition = Vector3.Zero;
			Limb( _armL, ShoulderL, ArmLength, raise, 18f * p );
			Limb( _armR, ShoulderR, ArmLength, raise, -18f * p );
			return;
		}

		if ( phase == CrowdPhase.Over ) return;

		// Walking (or running) legs.
		float stride = MathF.Sin( t * 11f ) * 38f * Math.Clamp( _speed / 120f, 0f, 1f );
		Limb( _legL, HipL, LegLength, 90f + stride, 0f );
		Limb( _legR, HipR, LegLength, 90f - stride, 0f );

		if ( Time.Now < _leapUntil )
		{
			// Mid-leap: arms thrown out in front, legs trailing.
			Limb( _armL, ShoulderL, ArmLength, -15f, 8f );
			Limb( _armR, ShoulderR, ArmLength, -15f, -8f );
			Limb( _legL, HipL, LegLength, 140f, 0f );
			Limb( _legR, HipR, LegLength, 125f, 0f );
		}
		else if ( _reaching )
		{
			// The warning, then the snatch: both arms thrown up over the head and shaking, held
			// there for the beat, then swung down onto the lizard as the grip lands.
			float swing = _telegraph * _telegraph * _telegraph;
			float pitch = -95f + 105f * swing + MathF.Sin( t * 34f ) * 7f * (1f - swing);
			float spread = 26f - 16f * swing;
			Limb( _armL, ShoulderL, ArmLength, pitch, spread );
			Limb( _armR, ShoulderR, ArmLength, pitch, -spread );
		}
		else if ( Passive )
		{
			// Just walking about (or standing): arms swinging at its sides.
			Limb( _armL, ShoulderL, ArmLength, 90f - stride * 0.5f, 0f );
			Limb( _armR, ShoulderR, ArmLength, 90f + stride * 0.5f, 0f );
			if ( Gesture == 1 ) Limb( _armR, ShoulderR, ArmLength, -50f, 55f );
			else if ( Gesture == 2 ) { Limb( _armL, ShoulderL, ArmLength, -8f, -14f ); Limb( _armR, ShoulderR, ArmLength, -8f, 14f ); }
			else if ( Gesture == 3 ) Limb( _armR, ShoulderR, ArmLength, -70f + MathF.Sin( t * 9f ) * 22f, -30f );
			else if ( Gesture == 4 ) { Limb( _armL, ShoulderL, ArmLength, 15f + MathF.Sin( t * 8f ) * 12f, -18f ); Limb( _armR, ShoulderR, ArmLength, 15f - MathF.Sin( t * 8f ) * 12f, 18f ); }
		}
		else if ( IsGrabber && _lizardNear )
		{
			// Arms stretched straight at the lizard.
			var inverse = WorldRotation.Inverse;
			var aim = lizard + Vector3.Up * 6f;
			Limb( _armL, ShoulderL, ArmLength, PointAt( inverse, ShoulderL, aim ) );
			Limb( _armR, ShoulderR, ArmLength, PointAt( inverse, ShoulderR, aim ) );
		}
		else if ( IsGrabber )
		{
			// Walking at it, arms out in front.
			Limb( _armL, ShoulderL, ArmLength, 8f + stride * 0.3f, 6f );
			Limb( _armR, ShoulderR, ArmLength, 8f - stride * 0.3f, -6f );
		}
		else
		{
			// Running away with the hands in the air.
			float wave = MathF.Sin( t * 11f ) * 22f;
			Limb( _armL, ShoulderL, ArmLength, -65f + wave, 25f );
			Limb( _armR, ShoulderR, ArmLength, -65f - wave, -25f );
		}
	}

	/// <summary>The turn, in the body's own frame, that points a limb from its joint at a world position.</summary>
	Rotation PointAt( Rotation inverse, Vector3 joint, Vector3 aim )
	{
		var local = inverse * (aim - WorldTransform.PointToWorld( joint ));
		return local.LengthSquared > 0.01f ? Rotation.LookAt( local.Normal ) : Rotation.Identity;
	}

	/// <summary>Arms and legs thrashing about. <paramref name="amount"/> 1 is full flail, 0 is still.</summary>
	void Flail( float t, float amount )
	{
		Limb( _armL, ShoulderL, ArmLength, 20f + MathF.Sin( t * 17f ) * 85f * amount, 20f + MathF.Sin( t * 9f ) * 30f * amount );
		Limb( _armR, ShoulderR, ArmLength, 20f + MathF.Sin( t * 15f + 2f ) * 85f * amount, -20f + MathF.Sin( t * 11f ) * 30f * amount );
		Limb( _legL, HipL, LegLength, 90f + MathF.Sin( t * 14f + 1f ) * 55f * amount, 0f );
		Limb( _legR, HipR, LegLength, 90f + MathF.Sin( t * 16f + 4f ) * 55f * amount, 0f );
	}
}