Sump/Hub/HubKit.cs

Building kit for the hub: HubBuilder places tinted boxes, balls, rods, rings and lights inside a structure's local space, HubRng wraps a seeded Random, HubFlame holds flicker state for a point light, HubRise animates a finished structure assembling itself bottom-up, and HubKit holds shared colours and !small parse/format helpers.

using System;
using System.Collections.Generic;

// The hub's building kit: a builder that places tinted boxes and balls in a structure's own
// space, the "rising" animation that makes a new structure assemble itself piece by piece, and
// the few colours and small helpers every hub file shares.

/// <summary>
/// Builds one structure out of primitives, in the structure's own space: +X is its front, +Y its
/// left, +Z up, with the origin on the ground. Everything it makes is an unsaved child of
/// <see cref="Root"/>, so the whole structure moves, hides and is destroyed as one object.
/// </summary>
public sealed class HubBuilder
{
	public GameObject Root { get; }

	public HubBuilder( GameObject root ) { Root = root; }

	/// <summary>A new structure standing at a world position, its front turned to a yaw in degrees.</summary>
	public static HubBuilder At( GameObject parent, string name, Vector3 world, float yaw )
	{
		var go = Sump.Spawn( name, world, parent );
		go.WorldRotation = Rotation.FromYaw( yaw );
		return new HubBuilder( go );
	}

	/// <summary>A part of this structure with its own position, turn and (uniform) scale.</summary>
	public HubBuilder Group( string name, Vector3 local, Rotation? rotation = null, float scale = 1f )
	{
		var go = Sump.Spawn( name, Root.WorldPosition, Root );
		go.LocalPosition = local;
		go.LocalRotation = rotation ?? Rotation.Identity;
		go.LocalScale = new Vector3( scale, scale, scale );
		return new HubBuilder( go );
	}

	/// <summary>Where a point of this structure is in the world.</summary>
	public Vector3 World( Vector3 local ) => Root.WorldPosition + Root.WorldRotation * (local * Root.WorldScale.x);

	/// <summary>A tinted box. Size in inches, position is its middle. Solid only when asked.</summary>
	public GameObject Box( string name, Vector3 local, Vector3 size, Color tint, bool solid = false, Rotation? rotation = null )
	{
		var go = Sump.Box( Root, name, Root.WorldPosition, size, tint, solid );
		go.LocalPosition = local;
		go.LocalRotation = rotation ?? Rotation.Identity;
		go.LocalScale = size / 50f;
		return go;
	}

	/// <summary>A tinted ball. Radii in inches, so it can be squashed into an egg, a dome or a disc.</summary>
	public GameObject Ball( string name, Vector3 local, Vector3 radii, Color tint, Rotation? rotation = null )
	{
		var go = Sump.Ball( Root, name, Root.WorldPosition, radii, tint );
		go.LocalPosition = local;
		go.LocalRotation = rotation ?? Rotation.Identity;
		go.LocalScale = radii / 32f;
		return go;
	}

	/// <summary>A round ball of one radius.</summary>
	public GameObject Ball( string name, Vector3 local, float radius, Color tint ) => Ball( name, local, new Vector3( radius, radius, radius ), tint );

	/// <summary>A thin square bar from one point to another.</summary>
	public GameObject Rod( string name, Vector3 from, Vector3 to, float thick, Color tint )
	{
		var along = to - from;
		float length = along.Length;
		if ( length < 0.01f ) return Box( name, from, new Vector3( thick, thick, thick ), tint );

		var dir = along / length;
		var up = MathF.Abs( dir.z ) > 0.9f ? Vector3.Forward : Vector3.Up;
		return Box( name, (from + to) * 0.5f, new Vector3( length + thick * 0.5f, thick, thick ), tint, false, Rotation.LookAt( dir, up ) );
	}

	/// <summary>
	/// A ring, or part of one, made of short bars. Upright and facing the front by default (0
	/// degrees is the structure's left, 90 is straight up); <paramref name="flat"/> lays it down.
	/// </summary>
	public void Ring( string name, Vector3 centre, float radius, float thick, Color tint, float from = 0f, float to = 360f, int segments = 10, bool flat = false )
	{
		var a = flat ? new Vector3( 1f, 0f, 0f ) : new Vector3( 0f, 1f, 0f );
		var b = flat ? new Vector3( 0f, 1f, 0f ) : new Vector3( 0f, 0f, 1f );
		segments = Math.Max( segments, 2 );

		Vector3 Point( int i )
		{
			float angle = (from + (to - from) * i / segments) * MathF.PI / 180f;
			return centre + (a * MathF.Cos( angle ) + b * MathF.Sin( angle )) * radius;
		}

		for ( int i = 0; i < segments; i++ )
			Rod( name, Point( i ), Point( i + 1 ), thick, tint );
	}

	/// <summary>A disc: facing the front by default, or lying flat.</summary>
	public GameObject Disc( string name, Vector3 centre, float radius, float thin, Color tint, bool flat = false )
		=> Ball( name, centre, flat ? new Vector3( radius, radius, thin ) : new Vector3( thin, radius, radius ), tint );

	/// <summary>A small point light without shadows.</summary>
	public PointLight Light( string name, Vector3 local, Color color, float radius )
	{
		var go = Sump.Spawn( name, Root.WorldPosition, Root );
		go.LocalPosition = local;
		var light = go.Components.Create<PointLight>();
		light.Radius = radius;
		light.Shadows = false;
		light.LightColor = color.WithAlpha( 1f );
		return light;
	}
}

/// <summary>Seeded random numbers with the two calls the hub uses everywhere.</summary>
public sealed class HubRng
{
	readonly Random _random;
	public HubRng( int seed ) { _random = new Random( seed ); }

	public float R( float a, float b ) => a + (float)_random.NextDouble() * (b - a);
	public int Next( int count ) => count <= 0 ? 0 : _random.Next( count );
	public T Pick<T>( T[] from ) => from[_random.Next( from.Length )];
	public bool Chance( float odds ) => _random.NextDouble() < odds;
}

/// <summary>A hub light that flickers like a flame, and flares when something is done at it.</summary>
public sealed class HubFlame
{
	public PointLight Light;
	public Color Base;
	public float Phase, Speed = 7f, Depth = 0.25f;
	/// <summary>Extra brightness on top, 0 to 1; fades by itself.</summary>
	public float Boost;
	/// <summary>Multiplies the whole light; the way down raises it as the chains come off.</summary>
	public float Level = 1f;
}

/// <summary>
/// The building animation. Takes a finished structure, hides every piece of it, and then puts the
/// pieces back from the ground up over a few seconds, each popping in with a little overshoot.
/// The lights come on last.
/// </summary>
public sealed class HubRise
{
	const float PopSeconds = 0.28f;
	const int PiecesPerTick = 9;

	readonly List<GameObject> _pieces = new();
	readonly List<Vector3> _scales = new();
	readonly List<float> _born = new();
	readonly float _seconds;
	float _clock;
	int _shown, _settled;

	public bool Done => _settled >= _pieces.Count;

	public HubRise( GameObject root, float seconds )
	{
		_seconds = MathF.Max( seconds, 0.2f );
		var found = new List<(GameObject Piece, float Order)>();
		Collect( root, found );
		found.Sort( ( a, b ) => a.Order.CompareTo( b.Order ) );

		foreach ( var (piece, _) in found )
		{
			_pieces.Add( piece );
			_scales.Add( piece.LocalScale );
			_born.Add( 0f );
			piece.Enabled = false;
		}
	}

	/// <summary>Finds everything that can be seen: models in height order, lights after them all.</summary>
	static void Collect( GameObject go, List<(GameObject, float)> found )
	{
		if ( !go.IsValid() ) return;
		if ( go.Components.Get<PointLight>() is not null ) { found.Add( (go, 1000000f + go.WorldPosition.z) ); return; }
		if ( go.Components.Get<ModelRenderer>() is not null ) { found.Add( (go, go.WorldPosition.z) ); return; }
		foreach ( var child in go.Children )
			Collect( child, found );
	}

	public void Update( float dt )
	{
		_clock += dt;
		int want = Math.Min( (int)(_pieces.Count * Math.Clamp( _clock / _seconds, 0f, 1f )) + 1, _pieces.Count );

		for ( ; _shown < want; _shown++ )
		{
			var piece = _pieces[_shown];
			_born[_shown] = _clock;
			if ( !piece.IsValid() ) continue;
			piece.Enabled = true;
			if ( _shown % PiecesPerTick == 0 ) Sump.Sfx( "hub_build_tick", piece.WorldPosition, 0.35f );
		}

		for ( int i = _settled; i < _shown; i++ )
		{
			var piece = _pieces[i];
			float k = (_clock - _born[i]) / PopSeconds;
			if ( !piece.IsValid() ) continue;
			piece.LocalScale = k >= 1f ? _scales[i] : _scales[i] * ((0.4f + 0.6f * k) * (1f + 0.22f * MathF.Sin( k * MathF.PI )));
		}

		while ( _settled < _shown && _clock - _born[_settled] >= PopSeconds )
			_settled++;
	}

	/// <summary>Shows everything at once (the hub is being hidden, or torn down).</summary>
	public void Finish()
	{
		for ( int i = 0; i < _pieces.Count; i++ )
		{
			if ( !_pieces[i].IsValid() ) continue;
			_pieces[i].Enabled = true;
			_pieces[i].LocalScale = _scales[i];
		}
		_shown = _settled = _pieces.Count;
	}
}

/// <summary>Colours and small sums shared by the hub's files.</summary>
public static class HubKit
{
	public static readonly Color Wood = new( 0.34f, 0.23f, 0.13f );
	public static readonly Color DarkWood = new( 0.19f, 0.13f, 0.08f );
	public static readonly Color Iron = new( 0.13f, 0.13f, 0.15f );
	public static readonly Color Rust = new( 0.4f, 0.2f, 0.11f );
	public static readonly Color Tin = new( 0.5f, 0.53f, 0.55f );
	public static readonly Color Paper = new( 0.86f, 0.82f, 0.68f );
	public static readonly Color Wax = new( 0.9f, 0.86f, 0.74f );
	public static readonly Color Flame = new( 1f, 0.62f, 0.2f );
	public static readonly Color Ink = new( 0.08f, 0.07f, 0.09f );
	public static readonly Color Rock = new( 0.12f, 0.115f, 0.11f );

	/// <summary>What people throw away, by colour.</summary>
	public static readonly Color[] Junk =
	{
		new( 0.42f, 0.32f, 0.2f ),   // cardboard
		new( 0.38f, 0.19f, 0.11f ),  // rust
		new( 0.62f, 0.64f, 0.62f ),  // fridge white
		new( 0.16f, 0.16f, 0.18f ),  // dead television
		new( 0.14f, 0.24f, 0.38f ),  // blue crate
		new( 0.5f, 0.12f, 0.1f ),    // red plastic
		new( 0.55f, 0.46f, 0.12f ),  // yellow tub
	};

	/// <summary>Fairy-light colours for strings of bulbs and lamp jars.</summary>
	public static readonly Color[] Bulbs =
	{
		new( 1f, 0.75f, 0.3f ),
		new( 1f, 0.4f, 0.3f ),
		new( 0.45f, 0.95f, 0.6f ),
		new( 0.4f, 0.7f, 1f ),
		new( 1f, 0.5f, 0.85f ),
	};

	/// <summary>A colour made darker or brighter, keeping it opaque.</summary>
	public static Color Shade( Color c, float k ) => new( c.r * k, c.g * k, c.b * k, 1f );

	/// <summary>Yaw in degrees that faces from one point toward another.</summary>
	public static float YawToward( Vector3 from, Vector3 to )
	{
		var d = (to - from).WithZ( 0f );
		return d.Length < 0.5f ? 0f : MathF.Atan2( d.y, d.x ) * 180f / MathF.PI;
	}

	/// <summary>The point at a yaw and distance from another, at the same height.</summary>
	public static Vector3 Around( Vector3 centre, float yaw, float distance ) => centre + Rotation.FromYaw( yaw ).Forward * distance;

	/// <summary>Puts a point on the cavern floor.</summary>
	public static Vector3 OnFloor( Vector3 point ) => point.WithZ( SumpCavern.FloorHeightAt( point ) );

	/// <summary>"x,y,z,yaw" in whole inches and degrees, for a saved note.</summary>
	public static string WritePlace( Vector3 at, float yaw )
		=> $"{(int)MathF.Round( at.x )},{(int)MathF.Round( at.y )},{(int)MathF.Round( at.z )},{(int)MathF.Round( yaw )}";

	public static bool ReadPlace( string note, out Vector3 at, out float yaw )
	{
		at = default;
		yaw = 0f;
		if ( string.IsNullOrEmpty( note ) ) return false;
		var parts = note.Split( ',' );
		if ( parts.Length < 4 ) return false;
		if ( !int.TryParse( parts[0], out int x ) || !int.TryParse( parts[1], out int y ) || !int.TryParse( parts[2], out int z ) || !int.TryParse( parts[3], out int turn ) ) return false;
		at = new Vector3( x, y, z );
		yaw = turn;
		return true;
	}

	/// <summary>A comma list of whole numbers, for a saved note.</summary>
	public static List<int> ReadInts( string note )
	{
		var list = new List<int>();
		if ( string.IsNullOrEmpty( note ) ) return list;
		foreach ( var part in note.Split( ',' ) )
			if ( int.TryParse( part, out int value ) && !list.Contains( value ) ) list.Add( value );
		return list;
	}
}