Stadium/CrowdSpawner.cs

Crowd filler for the stadium level. Bakes the stands and floor crowd into chunk meshes that bob, wakes floor cells near the lizard into pooled stand-in objects that steer with flocking rules, and promotes the closest ones into real CrowdPerson physics bodies that get demoted back when left behind.

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

/// <summary>
/// Fills the colosseum with tens of thousands of people without paying for them all at once.
/// Three levels, by distance from the lizard:
///
///  1. Far (the stands, and floor cells nobody has reached): people are baked into a few big
///     meshes, one per sector and shirt colour, that jump up and down. No objects, no physics.
///  2. Near (a floor cell the lizard has come close to): each person becomes a cheap stand-in,
///     one object with no physics, that walks at the lizard or runs about.
///  3. Right on top of the lizard: a stand-in is swapped for a real <see cref="CrowdPerson"/>
///     with a rigid body, to be charged through, tripped over and grabbed by. Only a few dozen
///     exist at any moment; they turn back into stand-ins when the lizard has left them behind.
/// </summary>
[Title( "Crowd Spawner" ), Category( "Stadium" ), Icon( "groups" )]
public sealed class CrowdSpawner : Component
{
	/// <summary>Gap between people standing on the arena floor. Smaller is a denser crowd.</summary>
	[Property, Group( "Numbers" )] public float FloorSpacing { get; set; } = 210f;

	/// <summary>Gap between people along a row in the stands.</summary>
	[Property, Group( "Numbers" )] public float SeatSpacing { get; set; } = 110f;

	/// <summary>Nobody stands on the floor within this distance of the front of the stage.</summary>
	[Property, Group( "Numbers" )] public float PitClearance { get; set; } = 380f;

	/// <summary>A guard on each guard post.</summary>
	[Property, Group( "Numbers" )] public bool SpawnGuards { get; set; } = true;

	/// <summary>Chance that someone goes for the lizard instead of running about.</summary>
	[Property, Group( "Numbers" ), Range( 0f, 1f )] public float GrabberChance { get; set; } = 0.6f;

	/// <summary>How long somebody has to stay within reach before their grab lands, and how far they can reach.</summary>
	[Property, Group( "Numbers" )] public float GrabWindup { get; set; } = 0.55f;
	[Property, Group( "Numbers" )] public float GrabRange { get; set; } = 50f;

	/// <summary>The floor is cut into square cells this big; a cell wakes up as a whole.</summary>
	[Property, Group( "Loading" )] public float CellSize { get; set; } = 2000f;

	/// <summary>A cell wakes (its people become stand-ins that move) when the lizard is this close to it.</summary>
	[Property, Group( "Loading" )] public float WakeRadius { get; set; } = 2300f;

	/// <summary>A woken stand-in left this far behind is removed for good.</summary>
	[Property, Group( "Loading" )] public float CullRadius { get; set; } = 5200f;

	/// <summary>Never more moving stand-ins than this at once.</summary>
	[Property, Group( "Loading" )] public int MaxAwake { get; set; } = 1100;

	/// <summary>A stand-in this close to where the lizard is heading becomes a real physics body.</summary>
	[Property, Group( "Loading" )] public float PhysicsRadius { get; set; } = 520f;

	/// <summary>A physics body this far from the lizard turns back into a stand-in.</summary>
	[Property, Group( "Loading" )] public float DemoteRadius { get; set; } = 900f;

	/// <summary>Never more real physics bodies than this at once.</summary>
	[Property, Group( "Loading" )] public int MaxPhysical { get; set; } = 70;

	/// <summary>Most physics bodies made in one frame, so a charge into a thick crowd does not hitch.</summary>
	[Property, Group( "Loading" )] public int SpawnPerFrame { get; set; } = 4;

	/// <summary>Walking speed of a stand-in heading for the lizard.</summary>
	[Property, Group( "Movement" )] public float WalkSpeed { get; set; } = 150f;

	// ---- What it made ------------------------------------------------------------------------
	[Property, ReadOnly, Group( "Spawned" )] public int InStands { get; private set; }
	[Property, ReadOnly, Group( "Spawned" )] public int OnFloor { get; private set; }
	[Property, ReadOnly, Group( "Spawned" )] public int Awake => _awake.Count;
	[Property, ReadOnly, Group( "Spawned" )] public int Physical => _physical.Count;
	public int Total => InStands + OnFloor;

	const int Colors = 5;
	const int Sectors = 40;
	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.9f, 0.9f, 0.88f ), new( 0.55f, 0.35f, 0.8f ),
	};
	// Where those five colours sit in CrowdPerson's own shirt list, so a stand-in keeps its colour.
	static readonly int[] PersonShirt = { 0, 1, 2, 6, 7 };
	static readonly Color[] Skins = { new( 0.9f, 0.72f, 0.58f ), new( 0.72f, 0.5f, 0.36f ), new( 0.45f, 0.3f, 0.22f ) };

	enum Level : byte { Asleep, StandIn, Physical, Gone }

	struct Agent
	{
		public Vector3 Position, Velocity;
		public float Yaw, Phase, Pace, Panic;
		public byte Color;
		public Level Level;
		public bool Grabber;
		public GameObject StandIn;
		public CrowdPerson Body;
	}

	sealed class Cell
	{
		public Vector3 Center;
		public List<int> Agents = new();
		public List<GameObject> Chunks = new();
		public bool Awake;
	}

	/// <summary>One baked lump of crowd that jumps as a whole.</summary>
	struct Bobber { public GameObject Object; public float Phase, Rate, Angle; public bool Stand; }

	sealed class MeshBuffer
	{
		public List<Vertex> Vertices = new();
		public List<int> Indices = new();
		public Vector3 Mins = new( float.MaxValue ), Maxs = new( float.MinValue );
	}

	Agent[] _agents = Array.Empty<Agent>();
	readonly List<Cell> _cells = new();
	readonly List<int> _awake = new();
	readonly List<int> _physical = new();
	readonly List<Bobber> _bobbers = new();
	readonly Stack<GameObject> _pool = new();

	// Generated meshes and models have to be held on to, or they are collected.
	readonly List<Mesh> _meshes = new();
	readonly List<Model> _models = new();
	Model _bodyModel, _headModel;
	Material _material;

	// Neighbour lookup for the stand-ins: a hash grid rebuilt every frame, as linked lists.
	const float GridSize = 80f;
	readonly Dictionary<long, int> _grid = new();
	int[] _gridNext = Array.Empty<int>();

	/// <summary>Stand-ins further from the lizard than this update at half rate.</summary>
	[Property, Group( "Loading" )] public float HalfRateDistance { get; set; } = 1300f;
	int _frame;

	StadiumGame _game;
	GameObject _root;
	bool _built;

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		_game = StadiumGame.Get( Scene );

		if ( SpawnGuards )
			foreach ( var post in StadiumLayout.GuardPosts() )
				SpawnPerson( post, FacingPodium( post ), true, -1 );
	}

	protected override void OnDestroy()
	{
		if ( _root.IsValid() ) _root.Destroy();
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		if ( !_game.IsValid() ) { _game = StadiumGame.Get( Scene ); if ( !_game.IsValid() ) return; }

		// Meshes made before the first frame may not draw, so everything is built here.
		if ( !_built ) { Build(); _built = true; }

		var player = _game.Player;
		if ( !player.IsValid() ) return;

		var phase = _game.Phase;
		Bob( phase );
		if ( phase < StadiumPhase.Shapeshift ) return;

		if ( !Consistent() ) return;

		var lizard = player.WorldPosition;
		WakeCells( lizard );
		UpdateStandIns( lizard, player.Velocity.WithZ( 0f ), phase );
		UpdatePhysical( lizard );
	}

	int _checkedAgents = -1;

	/// <summary>
	/// The lists below index into <see cref="_agents"/> every frame. If that array has been
	/// swapped or emptied under them (a hotload mid-play), anything pointing outside it is dropped
	/// here, once, instead of throwing for every person on every frame.
	/// </summary>
	bool Consistent()
	{
		_agents ??= Array.Empty<Agent>();
		if ( _checkedAgents == _agents.Length && _gridNext is not null && _gridNext.Length == _agents.Length ) return true;

		int count = _agents.Length;
		_checkedAgents = count;
		if ( _gridNext is null || _gridNext.Length != count ) _gridNext = new int[count];
		_grid.Clear();
		for ( int n = _awake.Count - 1; n >= 0; n-- )
			if ( _awake[n] < 0 || _awake[n] >= count ) _awake.RemoveAt( n );
		for ( int n = _physical.Count - 1; n >= 0; n-- )
			if ( _physical[n] < 0 || _physical[n] >= count ) _physical.RemoveAt( n );
		foreach ( var cell in _cells )
			for ( int n = cell.Agents.Count - 1; n >= 0; n-- )
				if ( cell.Agents[n] < 0 || cell.Agents[n] >= count ) cell.Agents.RemoveAt( n );
		return true;
	}

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

	void Build()
	{
		_root = new GameObject( GameObject, true, "Horde" );
		_root.Flags |= GameObjectFlags.NotSaved;

		_material = Model.Load( "models/dev/box.vmdl" ).Materials.FirstOrDefault();

		// The one-person models the stand-ins share.
		var body = new MeshBuffer();
		AddBody( body, Vector3.Zero, 0f );
		_bodyModel = MakeModel( body );
		var head = new MeshBuffer();
		AddHead( head, Vector3.Zero, 0f );
		_headModel = MakeModel( head );

		BuildStands();
		BuildFloor();
	}

	/// <summary>The stands: everybody baked into meshes by sector and colour. They never wake.</summary>
	// The baked stands, kept for the whole session: building 20,000 spectators takes a moment,
	// and "try again" would otherwise do it every time. Not carried across a hotload.
	sealed class BakedStand
	{
		public Model Bodies, Heads;
		public int Color, Sector;
		public float Phase;
	}
	[SkipHotload] static readonly List<BakedStand> _bakedStands = new();
	[SkipHotload] static float _bakedSpacing;
	[SkipHotload] static int _bakedCount;

	void BuildStands()
	{
		if ( _bakedStands.Count == 0 || _bakedSpacing != SeatSpacing || _bakedStands.Any( b => b.Bodies is null || !b.Bodies.IsValid ) )
			BakeStands();
		InStands = _bakedCount;

		foreach ( var baked in _bakedStands )
		{
			var chunk = ChunkOf( baked.Bodies, Shirts[baked.Color], baked.Phase );
			if ( baked.Heads is not null ) PartOf( chunk, baked.Heads, Skins[baked.Sector % Skins.Length] );

			var bobber = _bobbers[^1];
			bobber.Stand = true;
			bobber.Angle = (baked.Sector + 0.5f) / Sectors * MathF.PI * 2f - MathF.PI;
			_bobbers[^1] = bobber;
		}
	}

	/// <summary>Builds the stands' meshes: everybody by sector and colour.</summary>
	void BakeStands()
	{
		_bakedStands.Clear();
		_bakedSpacing = SeatSpacing;
		_bakedCount = 0;

		var bodies = new MeshBuffer[Sectors, Colors];
		var heads = new MeshBuffer[Sectors];

		foreach ( var seat in StadiumLayout.Seats( SeatSpacing ) )
		{
			float angle = MathF.Atan2( seat.y, seat.x - StadiumLayout.CenterX );
			int sector = Math.Clamp( (int)((angle + MathF.PI) / (MathF.PI * 2f) * Sectors), 0, Sectors - 1 );
			int color = Game.Random.Next( Colors );
			var at = seat + new Vector3( Game.Random.Float( -20f, 20f ), Game.Random.Float( -20f, 20f ), 0f );
			float yaw = angle + MathF.PI + Game.Random.Float( -0.4f, 0.4f ); // facing the arena

			AddBody( bodies[sector, color] ??= new MeshBuffer(), at, yaw );
			AddHead( heads[sector] ??= new MeshBuffer(), at, yaw );
			_bakedCount++;
		}

		for ( int sector = 0; sector < Sectors; sector++ )
		{
			if ( heads[sector] is null ) continue;
			float sectorPhase = Game.Random.Float( 0f, 10f );
			bool first = true;
			for ( int c = 0; c < Colors; c++ )
			{
				if ( bodies[sector, c] is null ) continue;
				// Heads ride with the first colour's bodies; near enough from the floor.
				_bakedStands.Add( new BakedStand
				{
					Bodies = MakeModel( bodies[sector, c] ),
					Heads = first ? MakeModel( heads[sector] ) : null,
					Color = c,
					Sector = sector,
					Phase = sectorPhase + c * 1.7f,
				} );
				first = false;
			}
		}
	}

	GameObject ChunkOf( Model model, Color tint, float phase )
	{
		var go = new GameObject( _root, true, "Crowd Chunk" );
		go.Flags |= GameObjectFlags.NotSaved;
		PartOf( go, model, tint );
		_bobbers.Add( new Bobber { Object = go, Phase = phase, Rate = Game.Random.Float( 0.8f, 1.25f ) } );
		return go;
	}

	void PartOf( GameObject go, Model model, Color tint )
	{
		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = model;
		renderer.Tint = tint;
		renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
	}

	/// <summary>The floor: everybody is an agent, baked into its cell's meshes until the cell wakes.</summary>
	void BuildFloor()
	{
		var agents = new List<Agent>();
		var cells = new Dictionary<(int, int), Cell>();

		foreach ( var spot in StadiumLayout.PitSpots( FloorSpacing ) )
		{
			if ( spot.x < StadiumLayout.StageFrontX + PitClearance && MathF.Abs( spot.y ) < StadiumLayout.StageHalfWidth + PitClearance ) continue;
			if ( spot.Distance( StadiumLayout.FatGuyStart ) < 200f ) continue;

			float jitter = FloorSpacing * 0.4f;
			var at = spot + new Vector3( Game.Random.Float( -jitter, jitter ), Game.Random.Float( -jitter, jitter ), 0f );
			if ( !StadiumLayout.OnFloor( at ) ) continue;

			var key = ((int)MathF.Floor( at.x / CellSize ), (int)MathF.Floor( at.y / CellSize ));
			if ( !cells.TryGetValue( key, out var cell ) )
			{
				cell = new Cell { Center = new Vector3( (key.Item1 + 0.5f) * CellSize, (key.Item2 + 0.5f) * CellSize, 0f ) };
				cells[key] = cell;
				_cells.Add( cell );
			}

			cell.Agents.Add( agents.Count );
			agents.Add( new Agent
			{
				Position = at,
				Yaw = FacingPodium( at ) + Game.Random.Float( -0.5f, 0.5f ),
				Phase = Game.Random.Float( 0f, 20f ),
				Pace = Game.Random.Float( 0.8f, 1.2f ),
				Color = (byte)Game.Random.Next( Colors ),
				Grabber = Game.Random.Float( 0f, 1f ) < GrabberChance,
			} );
		}

		_agents = agents.ToArray();
		_gridNext = new int[_agents.Length];
		OnFloor = _agents.Length;

		foreach ( var cell in _cells )
		{
			var bodies = new MeshBuffer[Colors];
			var heads = new MeshBuffer();
			foreach ( int i in cell.Agents )
			{
				ref var a = ref _agents[i];
				AddBody( bodies[a.Color] ??= new MeshBuffer(), a.Position, a.Yaw );
				AddHead( heads, a.Position, a.Yaw );
			}

			float cellPhase = Game.Random.Float( 0f, 10f );
			bool first = true;
			for ( int c = 0; c < Colors; c++ )
			{
				if ( bodies[c] is null ) continue;
				var chunk = Chunk( bodies[c], Shirts[c], cellPhase + c * 1.7f );
				if ( first ) ChunkPart( chunk, heads, Skins[_cells.Count % Skins.Length] );
				first = false;
				cell.Chunks.Add( chunk );
			}
		}
	}

	/// <summary>One baked lump of crowd, as an object that can be bobbed up and down.</summary>
	GameObject Chunk( MeshBuffer buffer, Color tint, float phase )
	{
		var go = new GameObject( _root, true, "Crowd Chunk" );
		go.Flags |= GameObjectFlags.NotSaved;
		ChunkPart( go, buffer, tint );
		_bobbers.Add( new Bobber { Object = go, Phase = phase, Rate = Game.Random.Float( 0.8f, 1.25f ) } );
		return go;
	}

	void ChunkPart( GameObject go, MeshBuffer buffer, Color tint )
	{
		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = MakeModel( buffer );
		renderer.Tint = tint;
		renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
	}

	Model MakeModel( MeshBuffer buffer )
	{
		var mesh = new Mesh( _material );
		mesh.CreateVertexBuffer( buffer.Vertices.Count, buffer.Vertices );
		mesh.CreateIndexBuffer( buffer.Indices.Count, buffer.Indices );
		mesh.Bounds = new BBox( buffer.Mins, buffer.Maxs );
		var model = Model.Builder.AddMesh( mesh ).Create();
		_meshes.Add( mesh );
		_models.Add( model );
		return model;
	}

	// A person from far away: a block for the body and a block for the head.
	static void AddBody( MeshBuffer m, Vector3 feet, float yaw ) => AddBox( m, feet, yaw, 6f, 11f, 0f, 54f, false );
	static void AddHead( MeshBuffer m, Vector3 feet, float yaw ) => AddBox( m, feet, yaw, 7f, 7f, 55f, 69f, true );

	/// <summary>A box standing on <paramref name="feet"/>, turned about the vertical. Both windings, so it shows whichever way the engine culls.</summary>
	static void AddBox( MeshBuffer m, Vector3 feet, float yaw, float hx, float hy, float z0, float z1, bool bottom )
	{
		float cos = MathF.Cos( yaw ), sin = MathF.Sin( yaw );
		Vector3 P( float x, float y, float z ) => feet + new Vector3( x * cos - y * sin, x * sin + y * cos, z );
		Vector3 N( float x, float y ) => new( x * cos - y * sin, x * sin + y * cos, 0f );

		Quad( m, P( hx, -hy, z0 ), P( hx, hy, z0 ), P( hx, hy, z1 ), P( hx, -hy, z1 ), N( 1f, 0f ) );
		Quad( m, P( -hx, hy, z0 ), P( -hx, -hy, z0 ), P( -hx, -hy, z1 ), P( -hx, hy, z1 ), N( -1f, 0f ) );
		Quad( m, P( hx, hy, z0 ), P( -hx, hy, z0 ), P( -hx, hy, z1 ), P( hx, hy, z1 ), N( 0f, 1f ) );
		Quad( m, P( -hx, -hy, z0 ), P( hx, -hy, z0 ), P( hx, -hy, z1 ), P( -hx, -hy, z1 ), N( 0f, -1f ) );
		Quad( m, P( -hx, -hy, z1 ), P( hx, -hy, z1 ), P( hx, hy, z1 ), P( -hx, hy, z1 ), Vector3.Up );
		if ( bottom ) Quad( m, P( -hx, hy, z0 ), P( hx, hy, z0 ), P( hx, -hy, z0 ), P( -hx, -hy, z0 ), Vector3.Down );
	}

	static void Quad( MeshBuffer m, Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 normal )
	{
		int i = m.Vertices.Count;
		var tangent = MathF.Abs( normal.z ) > 0.5f ? Vector3.Forward : Vector3.Up;
		m.Vertices.Add( new Vertex( a, normal, tangent, new Vector4( 0f, 0f, 0f, 0f ) ) );
		m.Vertices.Add( new Vertex( b, normal, tangent, new Vector4( 1f, 0f, 0f, 0f ) ) );
		m.Vertices.Add( new Vertex( c, normal, tangent, new Vector4( 1f, 1f, 0f, 0f ) ) );
		m.Vertices.Add( new Vertex( d, normal, tangent, new Vector4( 0f, 1f, 0f, 0f ) ) );

		m.Indices.Add( i ); m.Indices.Add( i + 1 ); m.Indices.Add( i + 2 );
		m.Indices.Add( i ); m.Indices.Add( i + 2 ); m.Indices.Add( i + 3 );
		m.Indices.Add( i ); m.Indices.Add( i + 2 ); m.Indices.Add( i + 1 );
		m.Indices.Add( i ); m.Indices.Add( i + 3 ); m.Indices.Add( i + 2 );

		m.Mins = Vector3.Min( m.Mins, Vector3.Min( Vector3.Min( a, b ), Vector3.Min( c, d ) ) );
		m.Maxs = Vector3.Max( m.Maxs, Vector3.Max( Vector3.Max( a, b ), Vector3.Max( c, d ) ) );
	}

	static float FacingPodium( Vector3 from ) => MathF.Atan2( StadiumLayout.Podium.y - from.y, StadiumLayout.Podium.x - from.x );

	// ---- The far crowd: jumping lumps --------------------------------------------------------

	void Bob( StadiumPhase phase )
	{
		// Shuffling during the speech, rising through the shift, going wild in the chase.
		float wild = phase < StadiumPhase.Shapeshift ? 0f : phase == StadiumPhase.Shapeshift ? _game.ShiftProgress : 1f;
		float height = 1.5f + 17f * wild;
		float rate = 2.2f + 5.5f * wild;
		float now = Time.Now;

		// Two things run round the stands: a wave that laps the whole ring, and a roar that
		// follows the lizard, loudest in the seats nearest to it.
		float wave = now * 0.55f;
		var player = _game.Player;
		float lizardAngle = player.IsValid() ? MathF.Atan2( player.WorldPosition.y, player.WorldPosition.x - StadiumLayout.CenterX ) : 0f;

		for ( int i = _bobbers.Count - 1; i >= 0; i-- )
		{
			var b = _bobbers[i];
			if ( !b.Object.IsValid() ) { _bobbers.RemoveAt( i ); continue; }

			float lift = height;
			if ( b.Stand )
			{
				float crest = MathF.Max( MathF.Cos( b.Angle - wave ), 0f );
				float roar = MathF.Max( MathF.Cos( b.Angle - lizardAngle ), 0f );
				lift = height * (0.45f + 1.6f * crest * crest * crest * crest + 0.9f * roar * roar * wild) + 26f * crest * crest * crest * crest * crest * crest;
			}

			float jump = MathF.Abs( MathF.Sin( now * rate * b.Rate + b.Phase ) );
			b.Object.WorldPosition = new Vector3( 0f, 0f, jump * lift );
		}
	}

	// ---- The near crowd: stand-ins ------------------------------------------------------------

	void WakeCells( Vector3 lizard )
	{
		float reach = WakeRadius + CellSize * 0.71f;
		foreach ( var cell in _cells )
		{
			if ( cell.Awake ) continue;
			if ( (cell.Center - lizard).WithZ( 0f ).LengthSquared > reach * reach ) continue;
			if ( _awake.Count + cell.Agents.Count > MaxAwake ) continue;

			cell.Awake = true;
			foreach ( var chunk in cell.Chunks ) if ( chunk.IsValid() ) chunk.Destroy();
			cell.Chunks.Clear();

			foreach ( int i in cell.Agents )
			{
				ref var a = ref _agents[i];
				a.Level = Level.StandIn;
				a.StandIn = TakeStandIn( a.Color, a.Position, a.Yaw );
				_awake.Add( i );
			}
		}
	}

	GameObject TakeStandIn( int color, Vector3 position, float yaw )
	{
		// A pooled stand-in may have been destroyed under us (a hotload, the horde being cleared).
		GameObject go = null;
		while ( _pool.Count > 0 && !go.IsValid() ) go = _pool.Pop();

		if ( go.IsValid() )
		{
			go.Enabled = true;
		}
		else
		{
			go = new GameObject( _root, true, "Stand-in" );
			go.Flags |= GameObjectFlags.NotSaved;
			var body = go.Components.Create<ModelRenderer>();
			body.Model = _bodyModel;
			body.RenderType = ModelRenderer.ShadowRenderType.Off;
			var head = go.Components.Create<ModelRenderer>();
			head.Model = _headModel;
			head.Tint = Skins[Game.Random.Next( Skins.Length )];
			head.RenderType = ModelRenderer.ShadowRenderType.Off;
		}

		var shirt = go.Components.Get<ModelRenderer>();
		if ( shirt.IsValid() ) shirt.Tint = Shirts[color % Shirts.Length];
		go.WorldPosition = position;
		go.WorldRotation = Rotation.FromYaw( yaw * 180f / MathF.PI );
		return go;
	}

	void ReturnStandIn( ref Agent a )
	{
		if ( a.StandIn.IsValid() ) { a.StandIn.Enabled = false; _pool.Push( a.StandIn ); }
		a.StandIn = null;
	}

	static long GridKey( int x, int y ) => ((long)x << 32) ^ (uint)y;

	/// <summary>
	/// The moving crowd. Nobody is scripted: each stand-in steers by a few local rules and the
	/// crowd's behaviour comes out of them. They keep clear of each other, so the pack spreads
	/// into a ring round the lizard instead of a queue. Fear spreads from person to person, so a
	/// scare ripples outward faster than anyone can see the lizard. Frightened people run with
	/// whoever is running beside them, which makes stampedes; hunters aim at where the lizard
	/// will be, not where it is; and people in the path of a charge dive out of it.
	/// </summary>
	void UpdateStandIns( Vector3 lizard, Vector3 lizardVelocity, StadiumPhase phase )
	{
		float dt = Time.Delta;
		float now = Time.Now;
		bool chase = phase == StadiumPhase.Escape;
		_frame++;

		// Real bodies are made round where the lizard is about to be, not where it was.
		var ahead = lizard + lizardVelocity * 0.45f;
		int spawned = 0;
		float physics2 = PhysicsRadius * PhysicsRadius, cull2 = CullRadius * CullRadius;

		float lizardSpeed = lizardVelocity.Length;
		var lizardHeading = lizardSpeed > 1f ? lizardVelocity / lizardSpeed : Vector3.Zero;
		bool charging = lizardSpeed > 420f;
		var cutscene = _game.Cutscene;

		// Who is next to whom.
		_grid.Clear();
		for ( int n = 0; n < _awake.Count; n++ )
		{
			int i = _awake[n];
			long key = GridKey( (int)MathF.Floor( _agents[i].Position.x / GridSize ), (int)MathF.Floor( _agents[i].Position.y / GridSize ) );
			_gridNext[i] = _grid.TryGetValue( key, out int first ) ? first : -1;
			_grid[key] = i;
		}

		for ( int n = _awake.Count - 1; n >= 0; n-- )
		{
			int i = _awake[n];
			ref var a = ref _agents[i];

			var to = (lizard - a.Position).WithZ( 0f );
			float distance2 = to.LengthSquared;

			// Left far behind: gone for good.
			if ( distance2 > cull2 )
			{
				ReturnStandIn( ref a );
				a.Level = Level.Gone;
				RemoveAwake( n );
				continue;
			}

			// On top of the lizard: time to be real.
			if ( chase && spawned < SpawnPerFrame && _physical.Count < MaxPhysical && (ahead - a.Position).WithZ( 0f ).LengthSquared < physics2 )
			{
				ReturnStandIn( ref a );
				a.Body = SpawnPerson( a.Position, a.Yaw, false, PersonShirt[a.Color] );
				a.Level = Level.Physical;
				_physical.Add( i );
				RemoveAwake( n );
				spawned++;
				continue;
			}

			// Far from the lizard, a stand-in thinks and moves every other frame (taking a double
			// step), half of them on each frame. Nobody can tell at that distance.
			float step = dt;
			if ( distance2 > HalfRateDistance * HalfRateDistance )
			{
				if ( ((i + _frame) & 1) != 0 ) continue;
				step = dt * 2f;
			}

			float distance = MathF.Sqrt( distance2 );
			var toward = distance > 1f ? to / distance : Vector3.Forward;
			float hop;

			if ( chase )
			{
				// ---- The neighbours: keep apart, and feel what they feel.
				var apart = Vector3.Zero;
				var flow = Vector3.Zero;
				float fear = 0f;
				int near = 0;
				int cx = (int)MathF.Floor( a.Position.x / GridSize ), cy = (int)MathF.Floor( a.Position.y / GridSize );
				for ( int gx = cx - 1; gx <= cx + 1; gx++ )
					for ( int gy = cy - 1; gy <= cy + 1; gy++ )
					{
						if ( !_grid.TryGetValue( GridKey( gx, gy ), out int j ) ) continue;
						for ( ; j >= 0; j = _gridNext[j] )
						{
							if ( j == i ) continue;
							var away = (a.Position - _agents[j].Position).WithZ( 0f );
							float gap2 = away.LengthSquared;
							if ( gap2 > GridSize * GridSize || gap2 < 0.01f ) continue;
							float gap = MathF.Sqrt( gap2 );
							apart += away / gap * (1f - gap / GridSize);
							flow += _agents[j].Velocity;
							fear += _agents[j].Panic;
							near++;
						}
					}

				// ---- Fear: from the lizard itself, worse if it is bearing down, and caught from others.
				float scare = Math.Clamp( 1f - distance / 1300f, 0f, 1f );
				float bearing = Vector3.Dot( -toward, lizardHeading );          // 1 = it is coming straight at me
				if ( charging && bearing > 0.75f && distance < 1500f ) scare = 1f;
				if ( near > 0 ) scare = MathF.Max( scare, fear / near * 0.93f );
				a.Panic += (scare - a.Panic) * MathF.Min( step * (scare > a.Panic ? 5f : 0.5f), 1f );

				// ---- What it wants.
				Vector3 wish;
				float speed;
				if ( a.Grabber )
				{
					// Hunts where the lizard is going to be, and comes round the side rather than queueing.
					var aim = lizard + lizardVelocity * MathF.Min( distance / 400f, 1.4f ) * 0.5f;
					var toAim = (aim - a.Position).WithZ( 0f );
					wish = toAim.LengthSquared > 1f ? toAim.Normal : toward;
					if ( distance < 800f )
					{
						float round = ((i & 1) == 0 ? 1f : -1f) * 0.45f;
						wish += new Vector3( -toward.y, toward.x, 0f ) * round;
					}
					speed = distance > PhysicsRadius * 0.85f ? WalkSpeed * a.Pace * (1f + 0.3f * a.Panic) : 0f;
				}
				else if ( a.Panic > 0.2f )
				{
					// Runs from it, and with whoever is running alongside: a stampede.
					wish = -toward;
					if ( near > 0 && flow.LengthSquared > 100f ) wish += flow.Normal * 0.9f;
					speed = WalkSpeed * a.Pace * (0.7f + 1.5f * a.Panic);
				}
				else
				{
					// Not frightened yet: milling about.
					float heading = MathF.Sin( now * 0.31f + a.Phase ) * 6f + a.Phase;
					wish = new Vector3( MathF.Cos( heading ), MathF.Sin( heading ), 0f );
					speed = WalkSpeed * 0.45f * a.Pace;
				}

				// In the path of a charge: dive out of it, to whichever side is nearer.
				if ( charging && !a.Grabber && distance < 750f && bearing > 0.5f )
				{
					float across = -to.x * -lizardHeading.y + -to.y * lizardHeading.x;   // side of the lizard's line
					if ( MathF.Abs( across ) < 170f )
					{
						var sideways = new Vector3( -lizardHeading.y, lizardHeading.x, 0f ) * (across >= 0f ? 1f : -1f);
						wish = sideways * 1.6f + wish * 0.3f;
						speed = MathF.Max( speed, WalkSpeed * 2.4f );
					}
				}

				wish += apart * 1.7f;
				float length = wish.Length;
				if ( length > 1f ) wish /= length;
				if ( speed <= 0f && apart.LengthSquared > 0.01f ) speed = WalkSpeed * 0.5f;   // still shuffles apart in the scrum

				a.Velocity = Vector3.Lerp( a.Velocity, wish * speed, MathF.Min( step * 4.5f, 1f ) );
				var next = a.Position + a.Velocity * step;
				if ( StadiumLayout.EllipseRadius( next, StadiumLayout.FloorA - 40f, StadiumLayout.FloorB - 40f ) < 1f && StadiumLayout.GroundHeight( next ) <= 0f )
					a.Position = next;
				else
					a.Velocity = (StadiumLayout.Center - a.Position).WithZ( 0f ).Normal * a.Velocity.Length;   // off the wall, back into the arena

				// Faces the way it runs; a hunter standing its ground faces the lizard.
				float moving = a.Velocity.Length;
				float face = moving > 25f ? MathF.Atan2( a.Velocity.y, a.Velocity.x ) : MathF.Atan2( toward.y, toward.x );
				float turn = (face - a.Yaw) % (MathF.PI * 2f);
				if ( turn > MathF.PI ) turn -= MathF.PI * 2f;
				if ( turn < -MathF.PI ) turn += MathF.PI * 2f;
				a.Yaw += turn * MathF.Min( step * 9f, 1f );

				hop = MathF.Abs( MathF.Sin( now * (6f + 3f * a.Panic + a.Pace * 2f) + a.Phase ) ) * (a.Grabber ? 8f : 4f + 11f * a.Panic);
			}
			else
			{
				hop = MathF.Abs( MathF.Sin( now * 5f + a.Phase ) ) * 6f;
			}

			if ( a.StandIn.IsValid() )
			{
				// Nobody stands in the way of the Fat Guy's big moment.
				bool hidden = cutscene.HasValue && (cutscene.Value - a.Position).WithZ( 0f ).LengthSquared < 320f * 320f;
				if ( a.StandIn.Enabled == hidden ) a.StandIn.Enabled = !hidden;
				a.StandIn.WorldPosition = a.Position.WithZ( hop );
				a.StandIn.WorldRotation = Rotation.FromYaw( a.Yaw * 180f / MathF.PI );
			}
		}
	}

	void RemoveAwake( int n )
	{
		_awake[n] = _awake[^1];
		_awake.RemoveAt( _awake.Count - 1 );
	}

	// ---- The crowd on top of the lizard: real bodies ------------------------------------------

	void UpdatePhysical( Vector3 lizard )
	{
		float demote2 = DemoteRadius * DemoteRadius;
		for ( int n = _physical.Count - 1; n >= 0; n-- )
		{
			int i = _physical[n];
			ref var a = ref _agents[i];
			bool remove = false;

			if ( !a.Body.IsValid() )
			{
				a.Level = Level.Gone;   // died and was cleared away, or left through the exit
				remove = true;
			}
			else
			{
				a.Position = a.Body.WorldPosition;
				bool far = (lizard - a.Position).WithZ( 0f ).LengthSquared > demote2;
				if ( far && a.Body.State == CrowdState.Dead )
				{
					a.Body.GameObject.Destroy();
					a.Level = Level.Gone;
					remove = true;
				}
				else if ( far && a.Body.State != CrowdState.Holding )
				{
					// Left behind: back to a stand-in, if there is room for one.
					a.Yaw = a.Body.WorldRotation.Yaw() * MathF.PI / 180f;
					a.Body.GameObject.Destroy();
					a.Body = null;
					a.Position = a.Position.WithZ( 0f );
					if ( _awake.Count < MaxAwake && StadiumLayout.OnFloor( a.Position ) )
					{
						a.Level = Level.StandIn;
						a.StandIn = TakeStandIn( a.Color, a.Position, a.Yaw );
						_awake.Add( i );
					}
					else a.Level = Level.Gone;
					remove = true;
				}
			}

			if ( !remove ) continue;
			_physical[n] = _physical[^1];
			_physical.RemoveAt( _physical.Count - 1 );
		}
	}

	/// <summary>One real person at a spot. It builds its own body when it starts.</summary>
	CrowdPerson SpawnPerson( Vector3 feet, float yaw, bool guard, int shirt )
	{
		var go = new GameObject( GameObject, true, guard ? "Guard" : "Patron" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.WorldPosition = feet.WithZ( StadiumLayout.GroundHeight( feet ) + 1f );
		go.WorldRotation = Rotation.FromYaw( yaw * 180f / MathF.PI );

		var person = go.Components.Create<CrowdPerson>();
		person.IsGuard = guard;
		person.GrabberChance = GrabberChance;
		person.GrabWindup = GrabWindup;
		person.GrabRange = GrabRange;
		person.ShirtIndex = shirt;
		return person;
	}
}