Stadium/StadiumBuilder.cs

Builds the stadium scene at runtime: floor, stage, carpet, podium, generated stand and wall meshes, collision, exit tunnel, lights, sky and the white-out arrival lighting.

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

/// <summary>
/// Builds the colosseum of Scene 2 when play starts: the sand floor, the stage with its red carpet
/// and podium, the tiers of stone stands, the outer wall with its arcade, the exit tunnel and
/// doorway, the sun, the sky and the lights. Every measurement comes from
/// <see cref="StadiumLayout"/>. Put it on one empty object at the world origin; everything it
/// makes is an unsaved child of that object.
///
/// The stands and wall are a handful of generated meshes (one per colour) and one collision mesh,
/// not thousands of boxes. Only the small things (stage, podium, tunnel) are scaled boxes.
///
/// While the game is in its white-out arrival, the lights (and the camera's bloom, if it has one)
/// are driven far too bright and settle as the eyes adjust. Once it has cleared, every light is
/// held under a fixed ceiling (see <see cref="ApplyBrightness"/>), so no property value can
/// wash the arena out to white.
/// </summary>
[Title( "Stadium Builder" ), Category( "Stadium" ), Icon( "foundation" )]
public sealed class StadiumBuilder : Component
{
	// ---- Brightness ---------------------------------------------------------------------------
	/// <summary>Scales every light in the arena, the sun and the ambient light included.</summary>
	[Property, Group( "Brightness" )] public float Brightness { get; set; } = 1f;

	/// <summary>Flat light everywhere, so nothing in the arena is ever black.</summary>
	[Property, Group( "Brightness" )] public Color AmbientColor { get; set; } = new( 0.42f, 0.44f, 0.5f );

	/// <summary>Colour of the sunlight.</summary>
	[Property, Group( "Brightness" )] public Color SunColor { get; set; } = new( 1f, 0.9f, 0.74f );

	/// <summary>Strength of the sun.</summary>
	[Property, Group( "Brightness" )] public float SunIntensity { get; set; } = 1.5f;

	/// <summary>Which way the sun shines: pitch down from the horizon, and yaw.</summary>
	[Property, Group( "Brightness" )] public Angles SunAngles { get; set; } = new( 48f, 205f, 0f );

	/// <summary>Strength of each spotlight on the stage and the podium.</summary>
	[Property, Group( "Brightness" )] public float SpotIntensity { get; set; } = 70f;

	/// <summary>Strength of each fill light round the stage and in the exit.</summary>
	[Property, Group( "Brightness" )] public float FillIntensity { get; set; } = 22f;

	/// <summary>Strength of the green glow over the exit.</summary>
	[Property, Group( "Brightness" )] public float ExitGlowIntensity { get; set; } = 12f;

	/// <summary>How many of the stage spotlights cast shadows (they are the expensive ones).</summary>
	[Property, Group( "Brightness" ), Range( 0, 3 )] public int ShadowSpots { get; set; } = 2;

	// ---- Arrival ------------------------------------------------------------------------------
	/// <summary>At full white-out the lights are this many times brighter again (1 + Flash * this).</summary>
	[Property, Group( "Arrival" )] public float BlowoutBoost { get; set; } = 5f;

	/// <summary>Added to the camera's bloom strength at full white-out.</summary>
	[Property, Group( "Arrival" )] public float BloomBoost { get; set; } = 4f;

	// ---- Camera -------------------------------------------------------------------------------
	/// <summary>The main camera's far clip is pushed out to at least this, so the far stands draw.</summary>
	[Property, Group( "Camera" )] public float FarClip { get; set; } = 90000f;

	// ---- Colours ------------------------------------------------------------------------------
	[Property, Group( "Colours" )] public Color SandColor { get; set; } = new( 0.6f, 0.49f, 0.32f );
	[Property, Group( "Colours" )] public Color StoneColor { get; set; } = new( 0.78f, 0.68f, 0.52f );
	[Property, Group( "Colours" )] public Color StoneShadeColor { get; set; } = new( 0.66f, 0.57f, 0.43f );
	[Property, Group( "Colours" )] public Color OuterWallColor { get; set; } = new( 0.74f, 0.62f, 0.45f );
	[Property, Group( "Colours" )] public Color ArchColor { get; set; } = new( 0.16f, 0.12f, 0.09f );
	[Property, Group( "Colours" )] public Color StageColor { get; set; } = new( 0.45f, 0.29f, 0.16f );
	[Property, Group( "Colours" )] public Color CarpetColor { get; set; } = new( 0.95f, 0.04f, 0.05f );
	[Property, Group( "Colours" )] public Color TunnelColor { get; set; } = new( 0.05f, 0.05f, 0.06f );
	[Property, Group( "Colours" )] public Color ExitColor { get; set; } = new( 0.1f, 1f, 0.25f );

	/// <summary>True once the arena's collision, boxes and lights exist.</summary>
	public bool Built { get; private set; }

	/// <summary>The dev box is a cube this big, centred on its origin.</summary>
	const float BoxSize = 50f;
	const string BoxModel = "models/dev/box.vmdl";
	const string StoneMaterial = "materials/default/white.vmat";
	const string SkyMaterial = "materials/skybox/skybox_day_01.vmat";

	/// <summary>Thickness of the floor slab and of the tunnel's boxes.</summary>
	const float Shell = 50f;

	/// <summary>How far the dark tunnel runs behind the exit doorway.</summary>
	const float TunnelLength = 320f;

	/// <summary>How many straight pieces the stands are cut into, the way round.</summary>
	const int Segments = 96;

	/// <summary>Thickness of the outer wall, outside the back of the top tier.</summary>
	const float WallThickness = 260f;

	/// <summary>Arched insets per piece of the outer wall.</summary>
	const int ArchesPerSegment = 2;

	/// <summary>An unseen wall this high above the outer wall, with a lid, keeps climbers in the world.</summary>
	const float LidRise = 500f;

	/// <summary>How high above the stage its spotlights hang.</summary>
	const float StageRigHeight = 900f;

	/// <summary>The triangles of one colour, gathered before they become a mesh.</summary>
	sealed class Surface
	{
		public string Name;
		public Color Tint;
		public readonly List<Vertex> Verts = new();
		public readonly List<int> Indices = new();
		public readonly List<Vector3> Points = new();
	}

	Surface _sand, _stone, _stoneShade, _wall, _arch;
	List<Vector3> _colPos = new();
	List<int> _colTris = new();

	// Hold on to the generated meshes and models: if a managed Mesh is garbage collected its GPU
	// buffers go with it and the arena silently stops drawing.
	readonly List<Mesh> _meshes = new();
	readonly List<Model> _models = new();
	Model _collisionModel;
	bool _meshesBuilt;

	Model _box;
	GameObject _geometry, _lighting;
	AmbientLight _ambient;
	DirectionalLight _sun;
	PointLight _exitGlow;
	readonly List<SpotLight> _spots = new();
	readonly List<PointLight> _fills = new();

	Bloom _bloom;
	float _bloomStrength;
	StadiumGame _game;

	protected override void OnAwake()
	{
		// Built before anything's OnStart, so the player has a stage to stand on from the first frame.
		if ( Scene.IsEditor ) return;
		Build();
	}

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

	protected override void OnDisabled() => RestoreBloom();

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

	void Build()
	{
		if ( Built ) return;

		_box = Model.Load( BoxModel );
		_geometry = Group( "Geometry" );
		_lighting = Group( "Lighting" );

		// The big pale surfaces are held to a mid tone: lit by sun, sky and ambient together, a
		// tint much above this reads as blank white.
		_sand = new Surface { Name = "Sand", Tint = Capped( SandColor, 0.66f ) };
		_stone = new Surface { Name = "Stands", Tint = Capped( StoneColor, 0.8f ) };
		_stoneShade = new Surface { Name = "Stands Shade", Tint = Capped( StoneShadeColor, 0.7f ) };
		_wall = new Surface { Name = "Outer Wall", Tint = Capped( OuterWallColor, 0.76f ) };
		_arch = new Surface { Name = "Arches", Tint = ArchColor };

		BuildFloor();
		BuildStage();
		BuildStands();
		BuildWall();
		BuildExit();
		BuildLid();
		BuildCollision();
		BuildLights();

		Built = true;
		ApplyBrightness( 0f );
	}

	GameObject Group( string name )
	{
		var go = new GameObject( GameObject, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		return go;
	}

	GameObject Child( GameObject parent, string name )
	{
		var go = new GameObject( parent, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		return go;
	}

	/// <summary>One box of the arena, in world space. <paramref name="solid"/> gives it collision.</summary>
	GameObject Box( string name, Vector3 centre, Vector3 size, Color colour, bool solid = true )
	{
		var go = Child( _geometry, name );
		go.WorldPosition = centre;
		go.WorldScale = size / BoxSize;

		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = _box;
		renderer.Tint = colour;

		if ( solid )
		{
			// The collider's size is in local space, so the unscaled cube matches the scaled model.
			var collider = go.Components.Create<BoxCollider>();
			collider.Scale = new Vector3( BoxSize, BoxSize, BoxSize );
			collider.Static = true;
		}
		return go;
	}

	/// <summary>A box given by its two opposite corners instead of centre and size.</summary>
	GameObject BoxBetween( string name, Vector3 a, Vector3 b, Color colour, bool solid = true )
	{
		var size = new Vector3( MathF.Abs( b.x - a.x ), MathF.Abs( b.y - a.y ), MathF.Abs( b.z - a.z ) );
		return Box( name, (a + b) * 0.5f, size, colour, solid );
	}

	// ---- Generated geometry -------------------------------------------------------------------

	/// <summary>
	/// Corner <paramref name="k"/> (0..Segments) of the ellipse with these semi-axes. The corners run
	/// from one side of the exit tunnel the long way round to the other, so corner 0 is exactly on
	/// y = +AisleHalfWidth and the last on y = -AisleHalfWidth: the tunnel's walls come out flat.
	/// </summary>
	static Vector3 Ring( float a, float b, int k, float z )
	{
		float gap = MathF.Asin( StadiumLayout.AisleHalfWidth / b );
		float angle = gap + (MathF.PI * 2f - gap * 2f) * k / Segments;
		return StadiumLayout.EllipsePoint( a, b, angle, z );
	}

	/// <summary>Direction from a point level toward the middle of the arena.</summary>
	static Vector3 Inward( Vector3 p ) => (StadiumLayout.Center - p).WithZ( 0f ).Normal;

	/// <summary>
	/// A flat four-cornered face (corners in order round its edge), facing <paramref name="facing"/>.
	/// Drawn if <paramref name="surface"/> is given, solid if <paramref name="solid"/>.
	/// </summary>
	void Quad( Surface surface, Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 facing, bool solid = true )
	{
		Tri( surface, a, b, c, facing, solid );
		Tri( surface, a, c, d, facing, solid );
	}

	void Tri( Surface surface, Vector3 a, Vector3 b, Vector3 c, Vector3 facing, bool solid = true )
	{
		var n = Vector3.Cross( b - a, c - a );
		if ( n.LengthSquared < 1e-6f ) return;
		n = n.Normal;
		if ( Vector3.Dot( n, facing ) < 0f )
		{
			(b, c) = (c, b);
			n = -n;
		}

		if ( surface is not null )
		{
			var tangent = (b - a).Normal;
			int i = surface.Verts.Count;
			surface.Verts.Add( new Vertex( a, n, tangent, new Vector4( 0, 0, 0, 0 ) ) );
			surface.Verts.Add( new Vertex( b, n, tangent, new Vector4( 1, 0, 0, 0 ) ) );
			surface.Verts.Add( new Vertex( c, n, tangent, new Vector4( 1, 1, 0, 0 ) ) );
			surface.Points.Add( a ); surface.Points.Add( b ); surface.Points.Add( c );

			// Both windings, so it shows from either side.
			surface.Indices.Add( i ); surface.Indices.Add( i + 1 ); surface.Indices.Add( i + 2 );
			surface.Indices.Add( i ); surface.Indices.Add( i + 2 ); surface.Indices.Add( i + 1 );
		}

		if ( solid )
		{
			int i = _colPos.Count;
			_colPos.Add( a ); _colPos.Add( b ); _colPos.Add( c );
			_colTris.Add( i ); _colTris.Add( i + 1 ); _colTris.Add( i + 2 );
		}
	}

	/// <summary>The sand: drawn as a fan over the floor ellipse, solid as one big slab under everything.</summary>
	void BuildFloor()
	{
		const float a = StadiumLayout.FloorA, b = StadiumLayout.FloorB;
		var centre = StadiumLayout.Center;

		for ( int k = 0; k < Segments; k++ )
			Tri( _sand, centre, Ring( a, b, k, 0f ), Ring( a, b, k + 1, 0f ), Vector3.Up, solid: false );
		// The piece across the mouth of the tunnel, and the tunnel's own floor out through the wall.
		Tri( _sand, centre, Ring( a, b, Segments, 0f ), Ring( a, b, 0, 0f ), Vector3.Up, solid: false );

		const float aisle = StadiumLayout.AisleHalfWidth;
		float mouthX = Ring( a, b, 0, 0f ).x;
		float doorX = StadiumLayout.MaxX + WallThickness;
		Quad( _sand, new Vector3( mouthX, aisle, 0f ), new Vector3( doorX, aisle, 0f ),
			new Vector3( doorX, -aisle, 0f ), new Vector3( mouthX, -aisle, 0f ), Vector3.Up, solid: false );

		// One slab under the whole place, the stands and the wall included.
		float pad = WallThickness + Shell;
		var min = new Vector3( StadiumLayout.MinX - pad, -StadiumLayout.HalfWidth - pad, -Shell );
		var max = new Vector3( StadiumLayout.MaxX + pad, StadiumLayout.HalfWidth + pad, 0f );
		var slab = Child( _geometry, "Floor Slab" );
		slab.WorldPosition = (min + max) * 0.5f;
		var collider = slab.Components.Create<BoxCollider>();
		collider.Scale = max - min;
		collider.Static = true;
	}

	void BuildStage()
	{
		const float top = StadiumLayout.StageTop, half = StadiumLayout.StageHalfWidth;

		BoxBetween( "Stage", new Vector3( StadiumLayout.StageBackX, -half, 0f ), new Vector3( StadiumLayout.StageFrontX, half, top ), StageColor );

		// The carpet is only a skin on the stage: no collision, so there is no lip to catch on.
		const float carpetThickness = 1.5f;
		var from = StadiumLayout.CarpetStart;
		var to = StadiumLayout.CarpetEnd;
		float carpetHalf = StadiumLayout.CarpetWidth * 0.5f;
		BoxBetween( "Red Carpet",
			new Vector3( from.x, from.y - carpetHalf, top ),
			new Vector3( to.x, to.y + carpetHalf, top + carpetThickness ),
			CarpetColor, solid: false );

		// A waist-high lectern at the end of the carpet, with a wider top to rest notes on.
		var p = StadiumLayout.Podium;
		var dark = StageColor * 0.6f;
		Box( "Podium", p + Vector3.Up * 20f, new Vector3( 30f, 48f, 40f ), dark.WithAlpha( 1f ) );
		Box( "Podium Top", p + Vector3.Up * 43f, new Vector3( 40f, 60f, 6f ), StageColor );
	}

	/// <summary>The tiers: each a flat step and the riser in front of it, all the way round but for the tunnel.</summary>
	void BuildStands()
	{
		const float depth = StadiumLayout.TierDepth;
		const float aisle = StadiumLayout.AisleHalfWidth;

		for ( int tier = 0; tier < StadiumLayout.Tiers; tier++ )
		{
			float a0 = StadiumLayout.FloorA + tier * depth, b0 = StadiumLayout.FloorB + tier * depth;
			float a1 = a0 + depth, b1 = b0 + depth;
			float top = StadiumLayout.TierTop( tier );
			float below = tier == 0 ? 0f : StadiumLayout.TierTop( tier - 1 );

			// Alternate the shade a little so the steps read from a distance.
			var surface = tier % 2 == 0 ? _stone : _stoneShade;

			for ( int k = 0; k < Segments; k++ )
			{
				var in0 = Ring( a0, b0, k, top );
				var in1 = Ring( a0, b0, k + 1, top );
				Quad( surface, in0, in1, Ring( a1, b1, k + 1, top ), Ring( a1, b1, k, top ), Vector3.Up );
				Quad( surface, in0.WithZ( below ), in1.WithZ( below ), in1, in0, Inward( (in0 + in1) * 0.5f ) );
			}

			// The tunnel's two walls through this tier, floor to step.
			float x0 = Ring( a0, b0, 0, 0f ).x, x1 = Ring( a1, b1, 0, 0f ).x;
			foreach ( float side in new[] { -1f, 1f } )
			{
				float y = side * aisle;
				Quad( _wall, new Vector3( x0, y, 0f ), new Vector3( x1, y, 0f ), new Vector3( x1, y, top ), new Vector3( x0, y, top ),
					new Vector3( 0f, -side, 0f ) );
			}
		}
	}

	/// <summary>The outer wall behind the top tier, with a row of dark arches let into its inner face.</summary>
	void BuildWall()
	{
		const float a0 = StadiumLayout.OuterA, b0 = StadiumLayout.OuterB;
		const float a1 = a0 + WallThickness, b1 = b0 + WallThickness;
		float baseZ = StadiumLayout.TierTop( StadiumLayout.Tiers - 1 );
		const float topZ = StadiumLayout.Height;
		const float wallHeight = StadiumLayout.WallHeight;

		for ( int k = 0; k < Segments; k++ )
		{
			var in0 = Ring( a0, b0, k, baseZ );
			var in1 = Ring( a0, b0, k + 1, baseZ );
			var out0 = Ring( a1, b1, k, topZ );
			var out1 = Ring( a1, b1, k + 1, topZ );
			var inward = Inward( (in0 + in1) * 0.5f );

			Quad( _wall, in0, in1, in1.WithZ( topZ ), in0.WithZ( topZ ), inward );
			Quad( _wall, in0.WithZ( topZ ), in1.WithZ( topZ ), out1, out0, Vector3.Up );
			Quad( _wall, out0, out1, out1.WithZ( -Shell ), out0.WithZ( -Shell ), -inward );

			// Arches: a dark upright panel with a rounded head, just proud of the wall. Drawn only.
			var along = (in1 - in0).WithZ( 0f );
			float length = along.Length;
			var u = along / MathF.Max( length, 1f );
			var face = Vector3.Cross( Vector3.Up, u ).Normal;
			if ( Vector3.Dot( face, inward ) < 0f ) face = -face;

			float halfWidth = length / ArchesPerSegment * 0.3f;
			float sill = baseZ + wallHeight * 0.1f;
			float spring = baseZ + wallHeight * 0.5f;
			float rise = MathF.Min( halfWidth, wallHeight * 0.3f );
			const int headSteps = 8;

			for ( int j = 0; j < ArchesPerSegment; j++ )
			{
				var c = in0 + along * ((j + 0.5f) / ArchesPerSegment) + face * 6f;
				var left = c - u * halfWidth;
				var right = c + u * halfWidth;
				Quad( _arch, left.WithZ( sill ), right.WithZ( sill ), right.WithZ( spring ), left.WithZ( spring ), face, solid: false );

				var hub = c.WithZ( spring );
				for ( int s = 0; s < headSteps; s++ )
				{
					float t0 = MathF.PI * s / headSteps, t1 = MathF.PI * (s + 1) / headSteps;
					var p0 = hub + u * (MathF.Cos( t0 ) * halfWidth) + Vector3.Up * (MathF.Sin( t0 ) * rise);
					var p1 = hub + u * (MathF.Cos( t1 ) * halfWidth) + Vector3.Up * (MathF.Sin( t1 ) * rise);
					Tri( _arch, hub, p0, p1, face, solid: false );
				}
			}
		}
	}

	/// <summary>The doorway through the outer wall, the dark tunnel behind it, the green sign and its glow.</summary>
	void BuildExit()
	{
		const float aisle = StadiumLayout.AisleHalfWidth, door = StadiumLayout.ExitDoorHeight;
		const float topZ = StadiumLayout.Height;

		// The wall's inner face where the tunnel meets it, and its outer face (kept flat).
		float x0 = Ring( StadiumLayout.OuterA, StadiumLayout.OuterB, 0, 0f ).x;
		float x1 = StadiumLayout.MaxX + WallThickness;

		// Jambs: the tunnel's walls carried on through the thickness of the outer wall.
		foreach ( float side in new[] { -1f, 1f } )
		{
			float y = side * aisle;
			Quad( _wall, new Vector3( x0, y, 0f ), new Vector3( x1, y, 0f ), new Vector3( x1, y, door ), new Vector3( x0, y, door ),
				new Vector3( 0f, -side, 0f ) );
		}

		// The wall above the door: its face to the arena, its underside, its back and its top.
		Quad( _wall, new Vector3( x0, aisle, door ), new Vector3( x0, -aisle, door ), new Vector3( x0, -aisle, topZ ), new Vector3( x0, aisle, topZ ), Vector3.Backward );
		Quad( _wall, new Vector3( x0, aisle, door ), new Vector3( x0, -aisle, door ), new Vector3( x1, -aisle, door ), new Vector3( x1, aisle, door ), Vector3.Down );
		Quad( _wall, new Vector3( x1, aisle, door ), new Vector3( x1, -aisle, door ), new Vector3( x1, -aisle, topZ ), new Vector3( x1, aisle, topZ ), Vector3.Forward );
		Quad( _wall, new Vector3( x0, aisle, topZ ), new Vector3( x0, -aisle, topZ ), new Vector3( x1, -aisle, topZ ), new Vector3( x1, aisle, topZ ), Vector3.Up );

		// A short dark way out, closed at the far end so the lizard can't climb out of the world.
		// It starts at the wall's outer face; the main floor slab already covers the doorway itself.
		float t0 = x1, t1 = x1 + TunnelLength;
		BoxBetween( "Tunnel Floor", new Vector3( t0, -aisle - Shell, -Shell ), new Vector3( t1 + Shell, aisle + Shell, 0f ), TunnelColor );
		BoxBetween( "Tunnel Roof", new Vector3( t0, -aisle - Shell, door ), new Vector3( t1 + Shell, aisle + Shell, door + Shell ), TunnelColor );
		BoxBetween( "Tunnel Left", new Vector3( t0, aisle, 0f ), new Vector3( t1, aisle + Shell, door ), TunnelColor );
		BoxBetween( "Tunnel Right", new Vector3( t0, -aisle - Shell, 0f ), new Vector3( t1, -aisle, door ), TunnelColor );
		BoxBetween( "Tunnel End", new Vector3( t1, -aisle, 0f ), new Vector3( t1 + Shell, aisle, door ), TunnelColor );

		// The sign: a green slab on the wall above the door, lit by its own green light.
		const float signHeight = 46f;
		Box( "Exit Sign", new Vector3( x0 - 3f, 0f, door + 16f + signHeight * 0.5f ), new Vector3( 6f, 170f, signHeight ), ExitColor, solid: false );

		var glow = Child( _lighting, "Exit Glow" );
		glow.WorldPosition = new Vector3( x0 - 70f, 0f, door + 40f );
		_exitGlow = glow.Components.Create<PointLight>();
		_exitGlow.LightColor = ExitColor;
		_exitGlow.Radius = 900f;
		_exitGlow.Shadows = false;

		// The doorway itself is lit from inside, so it reads as the way out from across the arena.
		Fill( "Doorway Light", new Vector3( x1 + 40f, 0f, door * 0.6f ), 1100f );
		Fill( "Tunnel Mouth Light", new Vector3( x0 - 500f, 0f, door * 0.8f ), 1300f );
	}

	/// <summary>
	/// Nothing to see: the outer wall carried up a little further and closed over, as collision
	/// only. The arena is open to the sky, but a lizard that climbs the wall must not get out.
	/// </summary>
	void BuildLid()
	{
		const float a = StadiumLayout.OuterA, b = StadiumLayout.OuterB;
		const float z0 = StadiumLayout.Height, z1 = z0 + LidRise;
		var centre = StadiumLayout.Center.WithZ( z1 );

		for ( int k = 0; k <= Segments; k++ )
		{
			// The last piece closes the ring over the exit tunnel.
			var p0 = Ring( a, b, k, z0 );
			var p1 = Ring( a, b, k == Segments ? 0 : k + 1, z0 );
			Quad( null, p0, p1, p1.WithZ( z1 ), p0.WithZ( z1 ), Inward( (p0 + p1) * 0.5f ) );
			Tri( null, centre, p0.WithZ( z1 ), p1.WithZ( z1 ), Vector3.Down );
		}
	}

	void BuildCollision()
	{
		var go = Child( _geometry, "Stands Collision" );
		_collisionModel = Model.Builder.AddCollisionMesh( _colPos, _colTris ).Create();
		var collider = go.Components.Create<ModelCollider>();
		collider.Static = true;
		collider.Model = _collisionModel;
	}

	/// <summary>
	/// Turns the gathered triangles into one mesh per colour. Done on the first frame update, not
	/// while the scene is still waking: meshes made that early have been seen not to draw.
	/// </summary>
	void BuildRenderMeshes()
	{
		_meshesBuilt = true;

		var material = Material.Load( StoneMaterial );
		foreach ( var surface in new[] { _sand, _stone, _stoneShade, _wall, _arch } )
		{
			if ( surface is null || surface.Verts.Count == 0 ) continue;

			var mesh = new Mesh( material );
			mesh.CreateVertexBuffer( surface.Verts.Count, surface.Verts );
			mesh.CreateIndexBuffer( surface.Indices.Count, surface.Indices );
			mesh.Bounds = BBox.FromPoints( surface.Points );

			var model = Model.Builder.AddMesh( mesh ).Create();
			_meshes.Add( mesh );
			_models.Add( model );

			var go = Child( _geometry, surface.Name );
			var renderer = go.Components.Create<ModelRenderer>();
			renderer.Model = model;
			renderer.Tint = surface.Tint;
		}

		// The triangle lists are no longer needed; the meshes and models are what must be kept.
		_sand = _stone = _stoneShade = _wall = _arch = null;
		_colPos = null;
		_colTris = null;
	}

	// ---- Lighting -----------------------------------------------------------------------------

	void BuildLights()
	{
		// The sun, the sky and a flat ambient light do the work across the arena.
		var sun = Child( _lighting, "Sun" );
		sun.WorldRotation = SunAngles.ToRotation();
		_sun = sun.Components.Create<DirectionalLight>();
		_sun.LightColor = SunColor;
		_sun.Shadows = true;

		var ambient = Child( _lighting, "Ambient" );
		_ambient = ambient.Components.Create<AmbientLight>();

		var skyMaterial = Material.Load( SkyMaterial );
		if ( skyMaterial is not null )
		{
			var sky = Child( _lighting, "Sky" );
			var skybox = sky.Components.Create<SkyBox2D>();
			skybox.SkyMaterial = skyMaterial;
			skybox.SkyIndirectLighting = true;
		}

		float rig = StadiumLayout.StageTop + StageRigHeight;
		var carpetFrom = StadiumLayout.CarpetStart;
		var carpetTo = StadiumLayout.CarpetEnd;
		var podium = StadiumLayout.Podium;

		// Stage spotlights. The first ones made are the ones that cast shadows: the podium's key
		// light from out front, then two down the carpet.
		Spot( "Podium Key", new Vector3( podium.x + 520f, 0f, rig ), podium + Vector3.Up * 40f, 26f );
		Spot( "Carpet Spot Near", new Vector3( MathX.Lerp( carpetFrom.x, carpetTo.x, 0.75f ), 0f, rig ), Vector3.Lerp( carpetFrom, carpetTo, 0.75f ), 34f );
		Spot( "Carpet Spot Far", new Vector3( MathX.Lerp( carpetFrom.x, carpetTo.x, 0.25f ), 0f, rig ), Vector3.Lerp( carpetFrom, carpetTo, 0.25f ), 34f );
		Spot( "Carpet Spot Mid", new Vector3( MathX.Lerp( carpetFrom.x, carpetTo.x, 0.5f ), 0f, rig ), Vector3.Lerp( carpetFrom, carpetTo, 0.5f ), 34f );
		Spot( "Carpet Spot Start", new Vector3( carpetFrom.x + 40f, 0f, rig ), carpetFrom, 34f );

		// Two crossing from the sides onto the podium, and two washing the stage wings.
		const float cross = StadiumLayout.StageHalfWidth;
		Spot( "Podium Cross Left", new Vector3( podium.x + 380f, cross, rig ), podium + Vector3.Up * 40f, 24f );
		Spot( "Podium Cross Right", new Vector3( podium.x + 380f, -cross, rig ), podium + Vector3.Up * 40f, 24f );
		const float wing = StadiumLayout.StageHalfWidth * 0.6f;
		const float stageMid = (StadiumLayout.StageBackX + StadiumLayout.StageFrontX) * 0.5f;
		Spot( "Stage Wash Left", new Vector3( stageMid, wing, rig ), new Vector3( stageMid, wing, StadiumLayout.StageTop ), 42f );
		Spot( "Stage Wash Right", new Vector3( stageMid, -wing, rig ), new Vector3( stageMid, -wing, StadiumLayout.StageTop ), 42f );

		// Fill over the stage and the sand in front of it.
		const float fillZ = StadiumLayout.StageTop + 520f;
		Fill( "Stage Fill", new Vector3( stageMid, 0f, fillZ ), 1500f );
		Fill( "Front Fill Left", new Vector3( StadiumLayout.StageFrontX + 500f, wing * 1.6f, fillZ ), 1500f );
		Fill( "Front Fill Right", new Vector3( StadiumLayout.StageFrontX + 500f, -wing * 1.6f, fillZ ), 1500f );
	}

	void Spot( string name, Vector3 position, Vector3 target, float coneDegrees )
	{
		var go = Child( _lighting, name );
		go.WorldPosition = position;

		// Straight down has no sideways direction to keep level with, so give it one.
		var direction = (target - position).Normal;
		var up = MathF.Abs( direction.z ) > 0.98f ? Vector3.Forward : Vector3.Up;
		go.WorldRotation = Rotation.LookAt( direction, up );

		var light = go.Components.Create<SpotLight>();
		light.LightColor = Color.White;
		light.ConeOuter = coneDegrees;
		light.ConeInner = coneDegrees * 0.6f;
		light.Radius = position.Distance( target ) + 500f;
		light.Shadows = _spots.Count < ShadowSpots;
		_spots.Add( light );
	}

	void Fill( string name, Vector3 position, float radius )
	{
		var go = Child( _lighting, name );
		go.WorldPosition = position;

		var light = go.Components.Create<PointLight>();
		light.LightColor = Color.White;
		light.Radius = radius;
		light.Shadows = false;
		_fills.Add( light );
	}

	// ---- Brightness, the far clip and the blown-out arrival -------------------------------------

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

		if ( !_meshesBuilt ) BuildRenderMeshes();
		ExtendFarClip();

		// Overexposed while the white-out clears, then normal for the rest of the scene.
		if ( !_game.IsValid() ) _game = StadiumGame.Get( Scene );
		float flash = _game.IsValid() && _game.Phase == StadiumPhase.FlashIn ? Math.Clamp( _game.Flash, 0f, 1f ) : 0f;

		ApplyBrightness( flash );
		ApplyBloom( flash );
	}

	/// <summary>The arena is far bigger than a camera normally sees: push the main camera's far clip out.</summary>
	void ExtendFarClip()
	{
		var camera = Scene.Camera;
		if ( camera.IsValid() && camera.ZFar < FarClip ) camera.ZFar = FarClip;
	}

	// The most each kind of light is ever given once the arrival has cleared, whatever the
	// properties (or an old scene's saved copies of them) say. Past these the pale sand and stone
	// go to flat white. The arrival's white-out multiplies on top of them, on purpose.
	const float MaxBrightness = 1.4f;
	const float MaxAmbient = 0.5f;       // brightest channel of the ambient light
	const float MaxSun = 1.8f;
	const float MaxSpot = 80f;
	const float MaxFill = 26f;
	const float MaxExitGlow = 16f;
	const float MaxBlowout = 6f;
	const float MaxBloomBoost = 5f;

	/// <summary>A colour scaled down, if it has to be, until its brightest channel is no more than <paramref name="most"/>.</summary>
	static Color Capped( Color colour, float most )
	{
		float peak = MathF.Max( colour.r, MathF.Max( colour.g, colour.b ) );
		if ( !(peak > most) ) return new Color( MathF.Max( colour.r, 0f ), MathF.Max( colour.g, 0f ), MathF.Max( colour.b, 0f ), 1f );
		float k = most / peak;
		return new Color( colour.r * k, colour.g * k, colour.b * k, 1f );
	}

	static float Capped( float value, float most ) => float.IsNaN( value ) ? 0f : Math.Clamp( value, 0f, most );

	void ApplyBrightness( float flash )
	{
		float steady = Capped( Brightness, MaxBrightness );
		float level = steady * (1f + Math.Clamp( flash, 0f, 1f ) * Capped( BlowoutBoost, MaxBlowout ));

		if ( _ambient.IsValid() ) _ambient.Color = (Capped( AmbientColor * steady, MaxAmbient ) * (level / MathF.Max( steady, 0.0001f ))).WithAlpha( 1f );

		if ( _sun.IsValid() )
		{
			_sun.LightColor = Capped( SunColor, 1f );
			_sun.Intensity = Capped( SunIntensity * steady, MaxSun ) * (level / MathF.Max( steady, 0.0001f ));
			_sun.WorldRotation = SunAngles.ToRotation();
		}

		float boost = level / MathF.Max( steady, 0.0001f );
		for ( int i = 0; i < _spots.Count; i++ )
		{
			var spot = _spots[i];
			if ( !spot.IsValid() ) continue;
			spot.Intensity = Capped( SpotIntensity * steady, MaxSpot ) * boost;
			spot.Shadows = i < ShadowSpots;
		}

		foreach ( var fill in _fills )
			if ( fill.IsValid() ) fill.Intensity = Capped( FillIntensity * steady, MaxFill ) * boost;

		if ( _exitGlow.IsValid() )
		{
			_exitGlow.LightColor = ExitColor;
			_exitGlow.Intensity = Capped( ExitGlowIntensity * steady, MaxExitGlow );
		}
	}

	/// <summary>Pushes the camera's bloom up with the white-out, and puts it back once it has cleared.</summary>
	void ApplyBloom( float flash )
	{
		if ( flash <= 0f )
		{
			RestoreBloom();
			return;
		}

		if ( !_bloom.IsValid() )
		{
			// Prefer the bloom on the main camera; any bloom in the scene will do otherwise.
			var camera = Scene.Camera;
			_bloom = camera.IsValid() ? camera.Components.Get<Bloom>() : null;
			if ( !_bloom.IsValid() ) _bloom = Scene.GetAllComponents<Bloom>().FirstOrDefault();
			if ( !_bloom.IsValid() ) return;
			_bloomStrength = _bloom.Strength;
		}

		_bloom.Strength = _bloomStrength + Math.Clamp( flash, 0f, 1f ) * Capped( BloomBoost, MaxBloomBoost );
	}

	void RestoreBloom()
	{
		if ( _bloom.IsValid() ) _bloom.Strength = _bloomStrength;
		_bloom = null;
	}
}