Sump/Generator/MisfitGenerator.cs

Deterministic generator for a Sump's misfit characters. Rolls them in casts of nine from a seed, using a stable hash mix for per-slot randomness, and ensures no repeated first contact, body plan, object, name, nickname, fear, twitch or story inside a cast. Also holds Mix and Hash helpers used by other modules.

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

/// <summary>
/// Rolls the misfits of a Sump. Same seed and index give the same misfit, always.
///
/// Misfits are rolled as a cast of nine so that one Sump has variety: every first contact at
/// least once, each flashback genre at least twice, no body plan repeated until all seven are
/// used, and no shared object, name, nickname, role, fear or twitch. Index 9 and up start a
/// second cast from the same seed (the guarantees hold inside each cast of nine).
/// </summary>
public static class MisfitGenerator
{
	public const int CastSize = 9;

	public static MisfitProfile Roll( int seed, int index )
	{
		if ( index < 0 ) index = -(index + 1);
		var cast = RollCast( seed, index / CastSize );
		return cast[index % CastSize];
	}

	/// <summary>All nine misfits of a seed at once (page 0 is indices 0 to 8).</summary>
	public static MisfitProfile[] RollCast( int seed, int page = 0 )
	{
		var plan = new Random( Mix( seed, page, 0x51ED ) );

		// First contacts: all five, one more Dissected (so the lab genre appears twice; farm and
		// talk show already do), then three different extras. Nobody appears more than three times.
		var all = new[] { FirstContact.ShotOnFarm, FirstContact.Dissected, FirstContact.WorshippedThenSold, FirstContact.BecameMeme, FirstContact.AdoptedThenForgotten };
		var contacts = new List<FirstContact>( all ) { FirstContact.Dissected };
		contacts.AddRange( Shuffled( all, plan ).Take( CastSize - contacts.Count ) );
		Shuffle( contacts, plan );

		// Body plans: all seven in a random order, then two different ones again.
		var plans = new[] { BodyPlan.GasSac, BodyPlan.CrystalLattice, BodyPlan.Swarm, BodyPlan.Jelly, BodyPlan.Insectoid, BodyPlan.Fungus, BodyPlan.Machine };
		var bodies = Shuffled( plans, plan );
		bodies.AddRange( Shuffled( plans, plan ).Take( CastSize - bodies.Count ) );

		var roles = Shuffled( MisfitTables.Roles, plan );

		var used = new Used();
		var cast = new MisfitProfile[CastSize];
		for ( int slot = 0; slot < CastSize; slot++ )
		{
			int index = page * CastSize + slot;
			var rng = new Random( Mix( seed, index, 0x9E37 ) );
			cast[slot] = Build( seed, index, rng, contacts[slot], bodies[slot], roles[slot % roles.Count], used );
		}
		return cast;
	}

	/// <summary>What has been handed out already in this cast.</summary>
	sealed class Used
	{
		public readonly HashSet<string> Objects = new();
		public readonly HashSet<string> Names = new();
		public readonly HashSet<string> Nicknames = new();
		public readonly HashSet<string> Fears = new();
		public readonly HashSet<string> Twitches = new();
		public readonly HashSet<string> Stories = new();
		public readonly Dictionary<string, int> Tics = new();
	}

	static MisfitProfile Build( int seed, int index, Random rng, FirstContact contact, BodyPlan body, MisfitTables.RoleEntry role, Used used )
	{
		var p = new MisfitProfile
		{
			// A seed of its own, so other modules can build their own Random for this misfit.
			Seed = Math.Max( 1, Mix( seed, index, 0x0B1D ) ),
			Index = index,
			Plan = body,
			Contact = contact,
			Ability = MisfitTables.AbilityFor( contact ),
			Genre = MisfitTables.GenreFor( contact ),
			Role = role.Name,
		};

		// The object: usually one that belongs to its first contact, sometimes any sad thing.
		var ownThings = MisfitTables.ThingsFor( contact );
		var thing = PickUnused( rng.NextDouble() < 0.65 ? ownThings : MisfitTables.AnyThings, t => t.Name, used.Objects, rng )
			?? PickUnused( MisfitTables.AnyThings, t => t.Name, used.Objects, rng )
			?? PickUnused( ownThings, t => t.Name, used.Objects, rng )
			?? ownThings[rng.Next( ownThings.Length )];
		used.Objects.Add( thing.Name );
		p.ClungObject = thing.Name;

		p.Name = RollName( rng, body, contact, used );

		// Scars
		var fears = MisfitTables.FearsFor( contact );
		var fearPick = PickUnused( fears.Select( f => f.Phrase ).ToArray(), f => f, used.Fears, rng ) ?? fears[rng.Next( fears.Length )].Phrase;
		used.Fears.Add( fearPick );
		p.Fear = fearPick;
		p.FearKind = fears.First( f => f.Phrase == fearPick ).Kind;

		var twitchPool = rng.NextDouble() < 0.45 ? MisfitTables.TwitchesFor( body ) : MisfitTables.Twitches;
		p.Twitch = PickUnused( twitchPool, t => t, used.Twitches, rng )
			?? PickUnused( MisfitTables.Twitches, t => t, used.Twitches, rng )
			?? twitchPool[rng.Next( twitchPool.Length )];
		used.Twitches.Add( p.Twitch );

		p.SpeechTic = RollTic( rng, contact, used );

		// Story
		var stories = MisfitTables.StoriesFor( contact );
		var story = PickUnused( stories, s => s, used.Stories, rng ) ?? stories[rng.Next( stories.Length )];
		used.Stories.Add( story );
		p.Backstory = story
			.Replace( "{Arole}", Capital( role.A ) )
			.Replace( "{arole}", role.A )
			.Replace( "{mission}", role.Mission )
			.Replace( "{obj}", thing.With );

		// Looks
		var palette = MisfitTables.PaletteFor( body );
		var pair = palette[rng.Next( palette.Length )];
		p.Primary = Tint( pair.Primary, rng );
		p.Secondary = Tint( pair.Secondary, rng );
		var size = MisfitTables.SizeFor( body );
		p.Size = Math.Clamp( MathF.Round( size.Min + (float)rng.NextDouble() * (size.Max - size.Min), 2 ), 0.6f, 1.6f );

		return p;
	}

	static string RollTic( Random rng, FirstContact contact, Used used )
	{
		var pool = MisfitTables.TicsFor( contact );
		string tic = "none";
		// No tic more than twice in one Sump, and at most one misfit who speaks plainly.
		for ( int attempt = 0; attempt < 40; attempt++ )
		{
			tic = pool[rng.Next( pool.Length )];
			used.Tics.TryGetValue( tic, out int count );
			if ( count < (tic == "none" ? 1 : 2) ) break;
		}
		used.Tics.TryGetValue( tic, out int had );
		used.Tics[tic] = had + 1;
		return tic;
	}

	static string RollName( Random rng, BodyPlan body, FirstContact contact, Used used )
	{
		string alien = null;
		for ( int attempt = 0; attempt < 60; attempt++ )
		{
			alien = AlienName( rng, body );
			if ( !used.Names.Contains( alien ) ) break;
		}
		// Out of luck after sixty tries: a number makes it unique.
		while ( used.Names.Contains( alien ) ) alien += "-" + rng.Next( 2, 99 );
		used.Names.Add( alien );

		if ( rng.NextDouble() >= 0.7 ) return alien;

		var pool = rng.NextDouble() < 0.75 ? MisfitTables.NicknamesFor( contact ) : MisfitTables.AnyNicknames;
		var nick = PickUnused( pool, n => n, used.Nicknames, rng ) ?? PickUnused( MisfitTables.AnyNicknames, n => n, used.Nicknames, rng );
		if ( nick is null ) return alien;
		used.Nicknames.Add( nick );

		return rng.NextDouble() < 0.8 ? $"{alien} \"{nick}\"" : $"{alien}, called {nick}";
	}

	static string AlienName( Random rng, BodyPlan body )
	{
		if ( body == BodyPlan.Machine )
		{
			const string letters = "BCDFGHJKLMNPQRSTVWXZ";
			var suffix = MisfitTables.MachineSuffixes[rng.Next( MisfitTables.MachineSuffixes.Length )];
			return $"{letters[rng.Next( letters.Length )]}{letters[rng.Next( letters.Length )]}-{rng.Next( 2, 99 )}{suffix}";
		}

		// A swarm is usually a "we"; sometimes it just buzzes.
		if ( body == BodyPlan.Swarm && rng.NextDouble() < 0.75 )
			return MisfitTables.SwarmNames[rng.Next( MisfitTables.SwarmNames.Length )];

		var s = MisfitTables.SyllablesFor( body );
		return s.Start[rng.Next( s.Start.Length )] + s.Mid[rng.Next( s.Mid.Length )] + s.End[rng.Next( s.End.Length )];
	}

	static Color Tint( float[] rgb, Random rng )
	{
		float Jitter( float v ) => Math.Clamp( v + ((float)rng.NextDouble() - 0.5f) * 0.1f, 0f, 1f );
		return new Color( Jitter( rgb[0] ), Jitter( rgb[1] ), Jitter( rgb[2] ), 1f );
	}

	// ------------------------------------------------------------------ helpers

	static T PickUnused<T>( IReadOnlyList<T> pool, Func<T, string> key, HashSet<string> used, Random rng ) where T : class
	{
		var free = new List<T>();
		foreach ( var item in pool )
			if ( !used.Contains( key( item ) ) ) free.Add( item );
		return free.Count == 0 ? null : free[rng.Next( free.Count )];
	}

	static List<T> Shuffled<T>( IEnumerable<T> items, Random rng )
	{
		var list = items.ToList();
		Shuffle( list, rng );
		return list;
	}

	static void Shuffle<T>( List<T> list, Random rng )
	{
		for ( int i = list.Count - 1; i > 0; i-- )
		{
			int j = rng.Next( i + 1 );
			(list[i], list[j]) = (list[j], list[i]);
		}
	}

	static string Capital( string s ) => string.IsNullOrEmpty( s ) ? s : char.ToUpperInvariant( s[0] ) + s.Substring( 1 );

	/// <summary>A stable, never-negative mix of three numbers (the same on every machine and every run).</summary>
	public static int Mix( int a, int b, int c = 0 )
	{
		unchecked
		{
			uint h = 2166136261;
			h = (h ^ (uint)a) * 16777619; h ^= h >> 15;
			h = (h ^ (uint)b) * 16777619; h ^= h >> 13;
			h = (h ^ (uint)c) * 16777619; h ^= h >> 16;
			h *= 2246822519; h ^= h >> 13;
			return (int)(h & 0x7FFFFFFF);
		}
	}

	/// <summary>A stable hash of a string (string.GetHashCode changes between runs).</summary>
	public static int Hash( string s )
	{
		unchecked
		{
			uint h = 2166136261;
			if ( s is not null )
				foreach ( char ch in s ) h = (h ^ ch) * 16777619;
			return (int)(h & 0x7FFFFFFF);
		}
	}
}