Sump/Misfits/MisfitBody.cs

A visual-only procedural body for 'misfit' creatures. Builds tinted box and sphere primitives from a MisfitProfile according to its BodyPlan (gas sac, crystal, swarm, jelly, insectoid, fungus, machine), then animates breathing, twitches, legs and wheels, a splitting body door with a glowing seam, and applies toy/fade states. Primitives come from a shared static pool and are returned when a body hides or is destroyed.

using System;
using System.Collections.Generic;

/// <summary>
/// The visible body of a misfit: a handful of tinted boxes and spheres, one silhouette and one
/// way of moving per <see cref="BodyPlan"/>. Purely for show: no colliders, no physics, nothing
/// saved. It animates itself, so whoever owns it (the hub misfit, a flashback, a graft, the finale
/// crowd) only has to move its object about and set <see cref="Agitation"/>.
/// Local space: feet at the origin, +X is the way it faces.
/// </summary>
[Title( "Misfit Body" ), Category( "Sump" ), Icon( "bubble_chart" )]
public sealed class MisfitBody : Component
{
	public MisfitProfile Profile { get; set; }

	/// <summary>Tag on the light inside a body door, so misfits afraid of light do not fear their own kind.</summary>
	public const string GlowTag = "misfit_glow";

	/// <summary>0 calm to 1 terrified: how hard it shakes and how fast it breathes.</summary>
	[Property, Range( 0f, 1f )] public float Agitation { get; set; }

	/// <summary>How fast its owner is moving it over the floor, in inches per second. Drives legs, wheels and trailing bits.</summary>
	[Property] public float MoveSpeed { get; set; }

	/// <summary>0 shut to 1 open: the body parts down the middle and a glowing seam shows (the dissected one's door).</summary>
	[Property, Range( 0f, 1f )] public float Open { get; set; }

	/// <summary>0 itself to 1 a small, perfectly still toy.</summary>
	[Property, Range( 0f, 1f )] public float Toy { get; set; }

	/// <summary>1 fully there to 0 gone (the one that only exists while watched).</summary>
	[Property, Range( 0f, 1f )] public float Fade { get; set; } = 1f;

	/// <summary>Further than this from the camera, it only animates every fourth frame.</summary>
	[Property] public float FarDistance { get; set; } = 1800f;

	/// <summary>
	/// Further than this from the camera (or behind it, or told to by its owner through
	/// <see cref="Asleep"/>), it is asleep: it only animates once every <see cref="SleepFrames"/> frames.
	/// </summary>
	[Property] public float SleepDistance { get; set; } = 3500f;

	/// <summary>How many frames a sleeping body lets go by between one animation step and the next.</summary>
	[Property] public int SleepFrames { get; set; } = 24;

	/// <summary>Set by its owner to put it to sleep whatever the camera is doing.</summary>
	public bool Asleep { get; set; }

	/// <summary>How small the toy pose is, against its full size.</summary>
	[Property] public float ToyScale { get; set; } = 0.35f;

	/// <summary>Seconds between tics, least and most.</summary>
	[Property] public Vector2 TicEvery { get; set; } = new( 3f, 7f );

	/// <summary>
	/// Shown or hidden as a whole. A hidden body costs nothing: its primitives go back to the
	/// shared pool for other bodies to use, and it takes a fresh set (the same shapes) when shown.
	/// </summary>
	public bool Visible
	{
		get => _visible;
		set
		{
			_visible = value;
			if ( _built )
			{
				if ( !value ) ReleaseParts();
				else if ( !_hasParts ) BuildParts();
			}
			ApplyVisible();
		}
	}

	/// <summary>Primitives in use by bodies right now, over the whole scene.</summary>
	public static int LiveParts { get; private set; }

	/// <summary>Primitives waiting in the pool to be used again.</summary>
	public static int PooledParts => _pool.Count;

	/// <summary>The pool keeps no more than this many spare primitives; beyond it they are destroyed.</summary>
	public static int MaxPooledParts { get; set; } = 1200;

	/// <summary>World position of its highest point, for name tags.</summary>
	public Vector3 Top => WorldPosition + Vector3.Up * (_height * WorldScale.z * Lerp( 1f, ToyScale, Toy ) + _hover);

	/// <summary>Every primitive it is made of, the clung object's included.</summary>
	public IReadOnlyList<GameObject> Parts => _parts;

	/// <summary>The little object it clings to (its parts sit under this), or null before it is built.</summary>
	public GameObject Prop => _prop;

	/// <summary>Builds a body for this profile under a parent. Used by the hub, the flashbacks, the grafts and the finale.</summary>
	public static MisfitBody Create( GameObject parent, MisfitProfile profile, float scale = 1f )
	{
		var go = new GameObject( parent, true, "Misfit Body" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalScale = new Vector3( MathF.Max( scale, 0.01f ) * MathF.Max( profile?.Size ?? 1f, 0.05f ) );

		var body = go.Components.Create<MisfitBody>();
		body.Profile = profile;
		body.Build();
		return body;
	}

	/// <summary>Makes it flinch now, whatever its tic timer says.</summary>
	public void Flinch() { _ticAt = Time.Now; _ticKind = Tic.Shiver; }

	// ---- What it is made of ---------------------------------------------------------------------

	enum BitKind
	{
		Static, Bladder, Tendril, Shard, Mote, Dome, Skirt, Segment, Leg, Antenna, Cap, Spore, Lamp, Cable, Plug, Wheel,
	}

	enum Tic { JerkLeft, JerkRight, Shiver, Hop, Tilt, Blink, Spin }

	sealed class Bit
	{
		public GameObject Go;
		public ModelRenderer Renderer;
		public BitKind Kind;
		public Vector3 Pos;                 // rest position, or the joint of a limb
		public Vector3 Scale;
		public Rotation Rot = Rotation.Identity;
		public Color Tint;
		public float Phase, Length, A, B;   // A and B mean different things per kind (see Animate)
		public int Index;
	}

	// ---- The shared pool of primitives ------------------------------------------------------------
	// Every part of every body is one object with one ModelRenderer. They are never destroyed with
	// the body: they are parked under a switched-off holder and handed to the next body that builds.

	static readonly Stack<GameObject> _pool = new();
	static Scene _poolScene;
	static GameObject _poolRoot;
	static int _poolGeneration;
	static ModelRenderer.ShadowRenderType? _shadowsOn; // what a new renderer starts with

	static GameObject PoolRoot( Scene scene )
	{
		if ( _poolScene == scene && _poolRoot.IsValid() ) return _poolRoot;

		// A new scene: whatever was pooled went with the old one.
		_pool.Clear();
		_poolScene = scene;
		_poolGeneration++;
		LiveParts = 0;
		_poolRoot = new GameObject( scene, false, "Misfit Part Pool" );
		_poolRoot.Flags |= GameObjectFlags.NotSaved;
		return _poolRoot;
	}

	GameObject TakePart( GameObject parent, string name, out ModelRenderer renderer )
	{
		PoolRoot( Scene );
		_generation = _poolGeneration;

		GameObject go = null;
		while ( _pool.Count > 0 && go is null )
		{
			var spare = _pool.Pop();
			if ( spare.IsValid() ) go = spare;
		}

		renderer = null;
		if ( go is not null )
		{
			go.SetParent( parent, false );
			go.Name = name;
			go.LocalRotation = Rotation.Identity;
			if ( !go.Enabled ) go.Enabled = true;
			renderer = go.Components.Get<ModelRenderer>();
		}
		else
		{
			go = new GameObject( parent, true, name );
			go.Flags |= GameObjectFlags.NotSaved;
		}

		if ( !renderer.IsValid() )
		{
			renderer = go.Components.Create<ModelRenderer>();
			_shadowsOn ??= renderer.RenderType;
		}

		LiveParts++;
		return go;
	}

	void ReturnPart( GameObject go )
	{
		if ( _generation == _poolGeneration ) LiveParts = Math.Max( LiveParts - 1, 0 );
		if ( !go.IsValid() ) return;
		if ( _generation != _poolGeneration || !_poolRoot.IsValid() || _pool.Count >= MaxPooledParts ) { go.Destroy(); return; }
		go.SetParent( _poolRoot, false );
		_pool.Push( go );
	}

	/// <summary>Hands every primitive back to the pool. The body keeps its place and can be built again.</summary>
	void ReleaseParts()
	{
		foreach ( var part in _parts ) ReturnPart( part );
		_parts.Clear();
		_bits.Clear();
		_hasParts = false;
		if ( _seam.IsValid() && _seam.Enabled ) _seam.Enabled = false;
	}

	readonly List<Bit> _bits = new();
	readonly List<GameObject> _parts = new();
	bool _hasParts;
	int _generation;
	GameObject _rig, _prop, _seam;
	PointLight _seamLight;
	Model _box, _sphere;
	Random _rng;
	BodyPlan _plan;
	Color _primary, _secondary;
	Vector3 _propRest, _limbEnd;
	bool _built, _visible = true, _wasOpen = true;
	float _height = 50f, _hover, _gait, _phase, _frozenTime;
	float _ticAt, _ticLength = 0.35f;
	Tic _ticKind, _ticOwn;
	int _frame;

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

	/// <summary>Builds the parts. Safe to call twice; the second call does nothing.</summary>
	public void Build()
	{
		if ( _built ) return;
		_built = true;

		Profile ??= new MisfitProfile();

		_box = Model.Load( "models/dev/box.vmdl" );       // a 50 unit cube
		_sphere = Model.Load( "models/dev/sphere.vmdl" ); // radius 32

		_rig = new GameObject( GameObject, true, "Rig" );
		_rig.Flags |= GameObjectFlags.NotSaved;

		if ( _visible ) BuildParts();
		_ticAt = Time.Now + Rand( TicEvery.x, TicEvery.y );
		ApplyVisible();
	}

	/// <summary>
	/// Throws the parts back in the pool and builds them again from the profile as it is now.
	/// For a body whose profile was swapped or changed after it was made.
	/// </summary>
	public void Rebuild()
	{
		if ( !_built ) { Build(); return; }
		ReleaseParts();
		if ( _visible ) BuildParts();
	}

	/// <summary>Takes the primitives for this profile from the pool. Seeded, so the same body comes back every time.</summary>
	void BuildParts()
	{
		var profile = Profile ??= new MisfitProfile();
		_hasParts = true;
		_wasOpen = true;
		_plan = profile.Plan;
		_primary = profile.Primary;
		_secondary = profile.Secondary;
		_rng = new Random( profile.Seed * 7919 + 13 );
		_phase = (float)_rng.NextDouble() * 20f;
		_frame = _rng.Next( 0, 4 );

		switch ( _plan )
		{
			case BodyPlan.GasSac: BuildGasSac(); break;
			case BodyPlan.CrystalLattice: BuildCrystal(); break;
			case BodyPlan.Swarm: BuildSwarm(); break;
			case BodyPlan.Jelly: BuildJelly(); break;
			case BodyPlan.Insectoid: BuildInsectoid(); break;
			case BodyPlan.Fungus: BuildFungus(); break;
			default: BuildMachine(); break;
		}

		BuildProp( profile.ClungObject ?? "" );

		_ticOwn = TicFor( profile.Twitch ?? "", profile.Seed );
		_ticKind = _ticOwn;
	}

	protected override void OnDestroy()
	{
		// The body is going; its primitives are not. (If the engine has already taken them, there is nothing to hand back.)
		try { ReleaseParts(); }
		catch ( Exception ) { _parts.Clear(); _bits.Clear(); }
	}

	float Rand( float min, float max ) => min + (float)(_rng ??= new Random( 1 )).NextDouble() * (max - min);
	static float Lerp( float a, float b, float t ) => a + (b - a) * Math.Clamp( t, 0f, 1f );
	static float Frac( float v ) => v - MathF.Floor( v );

	Bit Add( Model model, string name, BitKind kind, Vector3 position, Vector3 scale, Color tint, bool shadows, GameObject parent = null )
	{
		var go = TakePart( parent ?? _rig, name, out var renderer );
		go.LocalPosition = position;
		go.LocalScale = scale;

		renderer.Model = model;
		renderer.Tint = tint;
		renderer.RenderType = shadows ? (_shadowsOn ?? renderer.RenderType) : ModelRenderer.ShadowRenderType.Off;

		var bit = new Bit
		{
			Go = go, Renderer = renderer, Kind = kind, Pos = position, Scale = scale, Tint = tint,
			Phase = Rand( 0f, 6.28f ), Index = _bits.Count,
		};
		_parts.Add( go );
		if ( parent is null ) _bits.Add( bit ); // the prop's parts ride on their holder and are never animated one by one
		return bit;
	}

	/// <summary>A box, sized in inches.</summary>
	Bit Box( string name, BitKind kind, Vector3 position, Vector3 size, Color tint, bool shadows = false ) =>
		Add( _box, name, kind, position, size / 50f, tint, shadows );

	/// <summary>A sphere (or egg), radii in inches.</summary>
	Bit Ball( string name, BitKind kind, Vector3 position, Vector3 radii, Color tint, bool shadows = false ) =>
		Add( _sphere, name, kind, position, radii / 32f, tint, shadows );

	/// <summary>A thin box that swings about one end. Pitch 90 hangs down, 0 points ahead, negative is raised.</summary>
	Bit Limb( string name, BitKind kind, Vector3 joint, float length, float thickness, Color tint, float pitch, float yaw )
	{
		var bit = Box( name, kind, joint, new Vector3( length, thickness, thickness ), tint );
		bit.Length = length;
		bit.A = pitch;
		bit.B = yaw;
		Swing( bit, pitch, yaw );
		return bit;
	}

	void Swing( Bit bit, float pitch, float yaw )
	{
		var rotation = new Angles( pitch, yaw, 0f ).ToRotation();
		bit.Go.LocalRotation = rotation;
		_limbEnd = bit.Pos + rotation.Forward * bit.Length;
		bit.Go.LocalPosition = bit.Pos + rotation.Forward * (bit.Length * 0.5f);
	}

	void Turn( Bit bit, Rotation rotation )
	{
		bit.Rot = rotation;
		bit.Go.LocalRotation = rotation;
	}

	// ---- The seven bodies -----------------------------------------------------------------------

	/// <summary>A pale bladder that swells and sags, a darker collar under it, and tendrils trailing to the floor.</summary>
	void BuildGasSac()
	{
		_height = 64f;
		_propRest = new Vector3( 12f, 0f, 9f );
		var pale = Color.Lerp( _primary, Color.White, 0.45f ); // dev materials are opaque: pale stands in for translucent

		Ball( "Bladder", BitKind.Bladder, new Vector3( 0f, 0f, 40f ), new Vector3( 20f, 20f, 23f ), pale, true );
		Ball( "Collar", BitKind.Static, new Vector3( 0f, 0f, 20f ), new Vector3( 11f, 11f, 5f ), _secondary );
		Ball( "Nodule A", BitKind.Segment, new Vector3( 7f, 6f, 58f ), new Vector3( 5f ), _primary );
		Ball( "Nodule B", BitKind.Segment, new Vector3( -8f, -4f, 56f ), new Vector3( 3.5f ), _secondary );

		for ( int i = 0; i < 5; i++ )
		{
			float angle = i * 72f + Rand( -15f, 15f );
			var out_ = Rotation.FromYaw( angle ).Forward;
			Limb( "Tendril " + i, BitKind.Tendril, new Vector3( out_.x * 7f, out_.y * 7f, 18f ), Rand( 16f, 24f ), 1.6f,
				i % 2 == 0 ? _secondary : _primary, 90f, angle );
		}
	}

	/// <summary>A cluster of long angular shards that turn slowly about each other and flash as they chime.</summary>
	void BuildCrystal()
	{
		_height = 58f;
		_propRest = new Vector3( 15f, 0f, 8f );

		for ( int i = 0; i < 8; i++ )
		{
			float angle = i * 45f + Rand( -20f, 20f );
			var out_ = Rotation.FromYaw( angle ).Forward * Rand( 2f, 10f );
			float length = i == 0 ? 46f : Rand( 18f, 36f );
			float thick = Rand( 4f, 8f );
			var bit = Box( "Shard " + i, BitKind.Shard, new Vector3( out_.x, out_.y, length * 0.42f + Rand( 2f, 12f ) ),
				new Vector3( thick, thick * Rand( 0.6f, 1f ), length ), i % 3 == 2 ? _secondary : _primary, i < 3 );
			// Leaning out from the middle, each on its own skew.
			Turn( bit, new Angles( i == 0 ? 4f : Rand( 12f, 38f ), angle, Rand( 0f, 90f ) ).ToRotation() );
			bit.A = Rand( 8f, 26f ) * (i % 2 == 0 ? 1f : -1f); // degrees a second about its own length
		}
	}

	/// <summary>Twenty motes round a loose centre. Tight when calm, flung wide when scared.</summary>
	void BuildSwarm()
	{
		_height = 54f;
		_propRest = new Vector3( 0f, 0f, 30f ); // the swarm carries its object in the middle of itself

		for ( int i = 0; i < 20; i++ )
		{
			float radius = Rand( 1.6f, 3.2f );
			var bit = Ball( "Mote " + i, BitKind.Mote, new Vector3( 0f, 0f, 32f ), new Vector3( radius ), i % 4 == 0 ? _secondary : _primary );
			bit.Length = Rand( 9f, 20f );                               // orbit radius when calm
			bit.A = Rand( 1.3f, 2.8f ) * (i % 2 == 0 ? 1f : -1f);       // turns of the orbit
			bit.B = Rand( 0.9f, 2.2f );                                 // up and down
		}
	}

	/// <summary>A soft dome on a rippling skirt, squashing and stretching as it goes.</summary>
	void BuildJelly()
	{
		_height = 44f;
		_propRest = new Vector3( 19f, 0f, 9f );
		var pale = Color.Lerp( _primary, Color.White, 0.3f );

		Ball( "Dome", BitKind.Dome, new Vector3( 0f, 0f, 26f ), new Vector3( 20f, 20f, 17f ), pale, true );
		Ball( "Heart", BitKind.Segment, new Vector3( 4f, 0f, 41f ), new Vector3( 6f, 6f, 3f ), _secondary );

		for ( int i = 0; i < 9; i++ )
		{
			float angle = i * 40f;
			var out_ = Rotation.FromYaw( angle ).Forward;
			var bit = Ball( "Skirt " + i, BitKind.Skirt, new Vector3( out_.x * 17f, out_.y * 17f, 12f ), new Vector3( 5.5f, 5.5f, 9f ),
				i % 2 == 0 ? _primary : _secondary );
			bit.B = angle;
		}
	}

	/// <summary>Head, thorax and abdomen in a row, six stepping legs, two twitching antennae.</summary>
	void BuildInsectoid()
	{
		_height = 34f;
		_propRest = new Vector3( 27f, 0f, 9f );

		Ball( "Abdomen", BitKind.Segment, new Vector3( -19f, 0f, 19f ), new Vector3( 15f, 10f, 9f ), _primary, true );
		Ball( "Thorax", BitKind.Segment, new Vector3( 0f, 0f, 17f ), new Vector3( 9f, 8f, 7f ), _secondary, true );
		Ball( "Head", BitKind.Segment, new Vector3( 13f, 0f, 20f ), new Vector3( 6.5f, 6f, 6f ), _primary );

		for ( int i = 0; i < 6; i++ )
		{
			int row = i / 2;             // 0 front, 1 middle, 2 back
			float side = i % 2 == 0 ? 1f : -1f;
			var leg = Limb( "Leg " + i, BitKind.Leg, new Vector3( 6f - row * 7f, side * 6f, 16f ), 24f, 2.2f, _secondary,
				42f, side * (55f + row * 35f) );
			leg.Index = row + (side > 0f ? 0 : 1); // legs that step together share a parity
		}

		Limb( "Antenna L", BitKind.Antenna, new Vector3( 17f, 3f, 24f ), 16f, 1f, _secondary, -50f, 22f );
		Limb( "Antenna R", BitKind.Antenna, new Vector3( 17f, -3f, 24f ), 16f, 1f, _secondary, -50f, -22f );
	}

	/// <summary>A stalk and a wide cap, smaller caps budding off it, spores puffing up and away.</summary>
	void BuildFungus()
	{
		_height = 50f;
		_propRest = new Vector3( 13f, 0f, 5f );
		var stalk = Color.Lerp( _secondary, Color.White, 0.35f );

		Box( "Stalk", BitKind.Static, new Vector3( 0f, 0f, 16f ), new Vector3( 9f, 9f, 32f ), stalk, true );
		Ball( "Cap", BitKind.Cap, new Vector3( 0f, 0f, 37f ), new Vector3( 23f, 23f, 10f ), _primary, true );

		for ( int i = 0; i < 3; i++ )
		{
			float angle = 70f + i * 110f + Rand( -20f, 20f );
			var out_ = Rotation.FromYaw( angle ).Forward;
			float reach = Rand( 9f, 13f ), high = Rand( 10f, 24f ), size = Rand( 5f, 8f );
			var joint = new Vector3( out_.x * 3f, out_.y * 3f, high - 5f );
			Limb( "Bud Stalk " + i, BitKind.Static, joint, reach, 2.4f, stalk, -35f, angle );
			Ball( "Bud " + i, BitKind.Cap, _limbEnd + Vector3.Up * 1.5f, new Vector3( size, size, size * 0.5f ), i == 1 ? _secondary : _primary );
		}

		for ( int i = 0; i < 5; i++ )
			Ball( "Spore " + i, BitKind.Spore, new Vector3( Rand( -12f, 12f ), Rand( -12f, 12f ), 44f ), new Vector3( 1.5f ), Color.Lerp( _secondary, Color.White, 0.5f ) );
	}

	/// <summary>A dented probe: one long leg, one short leg on a wheel, a blinking lamp, a cable hanging loose.</summary>
	void BuildMachine()
	{
		_height = 50f;
		_propRest = new Vector3( 18f, -5f, 13f );
		var metal = Color.Lerp( _primary, new Color( 0.45f, 0.46f, 0.48f ), 0.5f );
		var dark = new Color( 0.12f, 0.12f, 0.14f );

		var hull = Box( "Hull", BitKind.Segment, new Vector3( 0f, 0f, 27f ), new Vector3( 26f, 20f, 15f ), metal, true );
		Turn( hull, new Angles( 3f, 0f, -6f ).ToRotation() ); // it sits crooked
		var dent = Box( "Dent", BitKind.Static, new Vector3( -5f, 8f, 33f ), new Vector3( 15f, 9f, 9f ), _primary.Darken( 0.35f ) );
		Turn( dent, new Angles( 14f, 25f, 20f ).ToRotation() );

		Limb( "Long Leg", BitKind.Leg, new Vector3( 8f, 9f, 22f ), 25f, 2.6f, dark, 62f, 40f ).Index = 0;
		Limb( "Short Leg", BitKind.Static, new Vector3( 8f, -9f, 21f ), 15f, 3.4f, dark, 75f, -30f );
		Box( "Wheel", BitKind.Wheel, _limbEnd.WithZ( 5f ), new Vector3( 10f, 3f, 10f ), _secondary );
		Limb( "Strut", BitKind.Static, new Vector3( -10f, 0f, 21f ), 16f, 2.6f, dark, 70f, 180f );
		Ball( "Castor", BitKind.Static, _limbEnd.WithZ( 4f ), new Vector3( 4f ), dark );

		Limb( "Mast", BitKind.Antenna, new Vector3( -8f, -6f, 34f ), 15f, 0.9f, dark, -80f, 0f );
		Ball( "Lamp", BitKind.Lamp, new Vector3( 12f, 3f, 37f ), new Vector3( 3.6f ), Color.Lerp( _secondary, Color.White, 0.4f ) );
		Limb( "Cable", BitKind.Cable, new Vector3( -13f, 7f, 23f ), 15f, 1.1f, dark, 90f, 160f );
		Ball( "Plug", BitKind.Plug, _limbEnd, new Vector3( 2.2f ), _secondary );
	}

	// ---- The object it clings to ----------------------------------------------------------------

	void BuildProp( string what )
	{
		if ( !_prop.IsValid() )
		{
			_prop = new GameObject( _rig, true, "Clung Object" );
			_prop.Flags |= GameObjectFlags.NotSaved;
		}
		_prop.Name = string.IsNullOrEmpty( what ) ? "Clung Object" : what;
		_prop.LocalPosition = _propRest;
		_prop.LocalRotation = new Angles( 0f, 0f, 12f ).ToRotation();

		string name = what.ToLowerInvariant();
		var plastic = new Color( 0.16f, 0.16f, 0.2f );
		var gold = new Color( 0.85f, 0.68f, 0.25f );
		var red = new Color( 0.86f, 0.14f, 0.12f );
		var yellow = new Color( 0.98f, 0.8f, 0.12f );
		var paper = new Color( 0.92f, 0.9f, 0.82f );

		// A stable colour for anything without a special case.
		int hash = 17;
		foreach ( char c in name ) hash = unchecked(hash * 31 + c);
		var own = new ColorHsv( Math.Abs( hash % 360 ), 0.6f, 0.85f, 1f ).ToColor();

		bool Is( params string[] words )
		{
			foreach ( var word in words ) if ( name.Contains( word ) ) return true;
			return false;
		}

		if ( Is( "walkman", "radio", "cassette", "tape", "phone", "pager", "game", "remote", "camera", "calculator" ) )
		{
			PropBox( "Case", new Vector3( 0f, 0f, 4.5f ), new Vector3( 2.4f, 6f, 9f ), plastic );
			PropBox( "Window", new Vector3( 1.3f, 0f, 5.5f ), new Vector3( 0.6f, 4f, 2.6f ), new Color( 0.6f, 0.7f, 0.75f ) );
			PropBox( "Button", new Vector3( 1.3f, 1.4f, 2f ), new Vector3( 0.6f, 1.4f, 1.2f ), red );
		}
		else if ( Is( "cruci", "cross", "rosary" ) )
		{
			PropBox( "Upright", new Vector3( 0f, 0f, 5.5f ), new Vector3( 1.3f, 1.5f, 11f ), gold );
			PropBox( "Arm", new Vector3( 0f, 0f, 7.6f ), new Vector3( 1.3f, 6.5f, 1.5f ), gold );
		}
		else if ( Is( "mcdonald", "happy meal", "toy", "doll", "bear", "duck", "figur", "puppet", "mascot" ) )
		{
			PropBall( "Body", new Vector3( 0f, 0f, 3.2f ), new Vector3( 3.2f, 3.2f, 3.4f ), red );
			PropBall( "Head", new Vector3( 0f, 0f, 8f ), new Vector3( 2.6f ), yellow );
			PropBox( "Base", new Vector3( 0f, 0f, 0.4f ), new Vector3( 5f, 5f, 0.8f ), yellow );
		}
		else if ( Is( "ball", "globe", "marble", "orb", "egg", "balloon" ) )
		{
			PropBall( "Ball", new Vector3( 0f, 0f, 4f ), new Vector3( 4f ), own );
			PropBox( "Stand", new Vector3( 0f, 0f, 0.5f ), new Vector3( 4f, 4f, 1f ), plastic );
		}
		else if ( Is( "key", "spoon", "fork", "pen", "tooth", "lighter", "whistle", "wand", "comb" ) )
		{
			PropBox( "Shaft", new Vector3( 0f, 0f, 4f ), new Vector3( 0.9f, 0.9f, 8f ), gold );
			PropBall( "Head", new Vector3( 0f, 0f, 8.6f ), new Vector3( 1f, 2.2f, 2.2f ), gold );
		}
		else if ( Is( "hat", "cap", "crown", "helmet", "wig" ) )
		{
			PropBall( "Brim", new Vector3( 0f, 0f, 1f ), new Vector3( 5.5f, 5.5f, 0.8f ), own );
			PropBall( "Crown", new Vector3( 0f, 0f, 3f ), new Vector3( 3.4f, 3.4f, 3.2f ), own );
		}
		else if ( Is( "book", "bible", "card", "photo", "ticket", "letter", "magazine", "receipt", "postcard", "map", "poster", "polaroid" ) )
		{
			PropBox( "Sheet", new Vector3( 0f, 0f, 4f ), new Vector3( 1f, 6f, 8f ), paper );
			PropBox( "Picture", new Vector3( 0.6f, 0f, 4.6f ), new Vector3( 0.3f, 4.4f, 4.6f ), own );
		}
		else if ( Is( "can", "bottle", "cup", "mug", "jar", "thermos", "flask" ) )
		{
			PropBox( "Can", new Vector3( 0f, 0f, 4f ), new Vector3( 3.6f, 3.6f, 8f ), own );
			PropBox( "Label", new Vector3( 0f, 0f, 4f ), new Vector3( 3.9f, 3.9f, 3f ), paper );
		}
		else
		{
			PropBox( "Thing", new Vector3( 0f, 0f, 3f ), new Vector3( 5f, 5f, 6f ), own );
			PropBox( "Band", new Vector3( 0f, 0f, 3f ), new Vector3( 5.4f, 1.4f, 6.4f ), paper );
		}
	}

	void PropBox( string name, Vector3 position, Vector3 size, Color tint ) =>
		Add( _box, name, BitKind.Static, position, size / 50f, tint, false, _prop );

	void PropBall( string name, Vector3 position, Vector3 radii, Color tint ) =>
		Add( _sphere, name, BitKind.Static, position, radii / 32f, tint, false, _prop );

	// ---- The tic ----------------------------------------------------------------------------------

	/// <summary>Reads the twitch's description for the sort of tic it is; anything unrecognised gets one picked by its seed.</summary>
	static Tic TicFor( string twitch, int seed )
	{
		string t = twitch.ToLowerInvariant();
		if ( t.Contains( "left" ) ) return Tic.JerkLeft;
		if ( t.Contains( "right" ) ) return Tic.JerkRight;
		if ( t.Contains( "shiver" ) || t.Contains( "shudder" ) || t.Contains( "trembl" ) || t.Contains( "shak" ) || t.Contains( "rattl" ) ) return Tic.Shiver;
		if ( t.Contains( "jump" ) || t.Contains( "hop" ) || t.Contains( "startl" ) || t.Contains( "duck" ) ) return Tic.Hop;
		if ( t.Contains( "head" ) || t.Contains( "tilt" ) || t.Contains( "nod" ) || t.Contains( "lean" ) ) return Tic.Tilt;
		if ( t.Contains( "blink" ) || t.Contains( "flicker" ) || t.Contains( "shrink" ) || t.Contains( "puls" ) || t.Contains( "wince" ) ) return Tic.Blink;
		if ( t.Contains( "spin" ) || t.Contains( "turn" ) || t.Contains( "circle" ) || t.Contains( "look" ) ) return Tic.Spin;
		return (Tic)(Math.Abs( seed ) % 7);
	}

	// ---- Moving -------------------------------------------------------------------------------------

	void ApplyVisible()
	{
		if ( !_rig.IsValid() ) return;
		bool show = _visible && Fade > 0.02f;
		if ( _rig.Enabled != show ) _rig.Enabled = show;
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || !_built || !_rig.IsValid() ) return;

		ApplyVisible();
		float dt = Time.Delta;
		_gait += dt * (1.5f + MathF.Min( MoveSpeed, 400f ) * 0.09f);
		if ( !_rig.Enabled ) return;

		// Asleep (told to be, a long way off, or behind the camera), it barely moves at all.
		// Merely far from the camera, every fourth frame is plenty.
		_frame++;
		var camera = Scene.Camera;
		bool asleep = Asleep;
		if ( camera.IsValid() )
		{
			var to = WorldPosition - camera.WorldPosition;
			float away = to.LengthSquared;
			asleep |= away > SleepDistance * SleepDistance || (away > 400f * 400f && Vector3.Dot( camera.WorldRotation.Forward, to ) < 0f);
			if ( !asleep && (_frame & 3) != 0 && away > FarDistance * FarDistance ) return;
		}
		if ( asleep && _frame % Math.Max( SleepFrames, 1 ) != 0 ) return;

		// A toy holds perfectly still: its clock stops.
		if ( Toy < 0.6f ) _frozenTime = Time.Now + _phase;
		Animate( _frozenTime );
	}

	void Animate( float t )
	{
		float a = Toy > 0.6f ? 0f : Math.Clamp( Agitation, 0f, 1f );
		float speed = Toy > 0.6f ? 0f : MathF.Min( MoveSpeed, 400f );
		float pace = 1f + a * 2.5f;                     // everything breathes faster when frightened
		float trail = MathF.Min( speed * 0.12f, 32f );  // hanging things swing back as it moves

		// ---- The whole body: hover, shake, tic ----
		var offset = Vector3.Zero;
		float roll = 0f, yaw = 0f, scale = 1f;

		_hover = 0f;
		if ( _plan == BodyPlan.GasSac ) _hover = 7f + MathF.Sin( t * 1.1f ) * 3f;
		else if ( _plan == BodyPlan.Jelly ) _hover = 1.5f + MathF.Sin( t * 2.2f * pace ) * 1.5f;
		offset.z += _hover * (1f - Toy);

		if ( a > 0.02f )
			offset += new Vector3( MathF.Sin( t * 47f + 1f ), MathF.Sin( t * 53f + 2f ), MathF.Sin( t * 41f ) * 0.5f ) * (a * a * 1.8f);

		float now = Time.Now;
		if ( now >= _ticAt && Toy < 0.6f )
		{
			float u = (now - _ticAt) / _ticLength;
			if ( u >= 1f )
			{
				// Frightened, the tic comes more often.
				_ticAt = now + Rand( TicEvery.x, TicEvery.y ) * Lerp( 1f, 0.35f, a );
				_ticKind = _ticOwn;
			}
			else
			{
				float k = MathF.Sin( u * MathF.PI );
				switch ( _ticKind )
				{
					case Tic.JerkLeft: offset.y += 5f * k; roll -= 12f * k; break;
					case Tic.JerkRight: offset.y -= 5f * k; roll += 12f * k; break;
					case Tic.Shiver: offset += new Vector3( MathF.Sin( now * 71f ), MathF.Cos( now * 63f ), 0f ) * (2.2f * k); break;
					case Tic.Hop: offset.z += 7f * k; break;
					case Tic.Tilt: roll += 20f * k; break;
					case Tic.Blink: scale -= 0.18f * k; break;
					case Tic.Spin: yaw += 360f * u * u * (3f - 2f * u); break;
				}
			}
		}

		_rig.LocalPosition = offset;
		_rig.LocalRotation = new Angles( 0f, yaw, roll ).ToRotation();
		_rig.LocalScale = new Vector3( MathF.Max( scale * Fade * Lerp( 1f, ToyScale, Toy ), 0.001f ) );

		// ---- Each part ----
		bool open = Open > 0.002f;
		bool resetStatics = open || _wasOpen;
		_wasOpen = open;
		float part = Open * 6f; // inches each half moves aside

		foreach ( var bit in _bits )
		{
			var go = bit.Go;
			float p = bit.Phase;

			switch ( bit.Kind )
			{
				case BitKind.Static:
					if ( !resetStatics ) continue;
					// A fixed limb hangs from its joint; anything else just sits at its place.
					go.LocalPosition = bit.Length > 0f ? bit.Pos + go.LocalRotation.Forward * (bit.Length * 0.5f) : bit.Pos;
					break;

				case BitKind.Bladder:
				{
					// Swells as it breathes in, sags as it lets go.
					float s = MathF.Sin( t * 1.3f * pace );
					go.LocalScale = new Vector3( bit.Scale.x * (1f + 0.1f * s), bit.Scale.y * (1f + 0.1f * s), bit.Scale.z * (1f - 0.13f * s) );
					go.LocalPosition = bit.Pos + Vector3.Down * (2.5f * s);
					break;
				}

				case BitKind.Tendril:
				case BitKind.Cable:
					Swing( bit, bit.A + trail + MathF.Sin( t * 1.7f + p ) * 10f * (1f + a), bit.B + MathF.Sin( t * 1.1f + p * 2f ) * 14f );
					break;

				case BitKind.Plug:
					go.LocalPosition = _limbEnd; // on the end of the cable swung just before it
					break;

				case BitKind.Shard:
				{
					go.LocalRotation = bit.Rot * Rotation.FromAxis( Vector3.Up, t * bit.A );
					float drift = 2.5f + a * 5f;
					go.LocalPosition = bit.Pos + new Vector3( MathF.Sin( t * 0.4f + p ), MathF.Cos( t * 0.33f + p * 2f ), MathF.Sin( t * 0.5f + p * 3f ) ) * drift;
					// A chime: each shard flashes white now and then, more often when frightened.
					float chime = MathF.Pow( MathF.Max( 0f, MathF.Sin( t * 0.9f * pace + p * 5f ) ), 24f );
					bit.Renderer.Tint = Color.Lerp( bit.Tint, Color.White, chime );
					break;
				}

				case BitKind.Mote:
				{
					float angle = t * bit.A * (1f + a) + p;
					float radius = bit.Length * (0.55f + a * 1.9f + 0.1f * MathF.Sin( t * 0.7f + p ));
					go.LocalPosition = bit.Pos + new Vector3( MathF.Cos( angle ) * radius, MathF.Sin( angle ) * radius, MathF.Sin( t * bit.B + p ) * radius * 0.65f );
					break;
				}

				case BitKind.Dome:
				{
					float q = MathF.Sin( t * 2.2f * pace ) * (0.07f + speed / 400f * 0.16f);
					go.LocalScale = new Vector3( bit.Scale.x * (1f - q * 0.6f), bit.Scale.y * (1f - q * 0.6f), bit.Scale.z * (1f + q) );
					go.LocalPosition = bit.Pos + Vector3.Up * (q * 7f);
					break;
				}

				case BitKind.Skirt:
				{
					// A wave running round the rim.
					float ripple = MathF.Sin( t * 4f * pace - bit.Index * 0.9f );
					var out_ = Rotation.FromYaw( bit.B ).Forward;
					go.LocalPosition = bit.Pos + out_ * (ripple * 2.5f) + Vector3.Up * (ripple * 3f);
					go.LocalScale = new Vector3( bit.Scale.x, bit.Scale.y, bit.Scale.z * (1f + ripple * 0.3f) );
					break;
				}

				case BitKind.Segment:
					go.LocalPosition = bit.Pos + Vector3.Up * (MathF.Sin( t * 3f * pace + p ) * 0.7f);
					break;

				case BitKind.Leg:
				{
					// Legs sharing a parity step together; the other three carry the weight.
					float beat = _gait + (bit.Index % 2) * MathF.PI;
					float stride = Math.Clamp( speed / 60f, 0.12f, 1f );
					Swing( bit, bit.A - MathF.Max( 0f, MathF.Cos( beat ) ) * 20f * stride, bit.B + MathF.Sin( beat ) * 22f * stride );
					break;
				}

				case BitKind.Antenna:
					Swing( bit, bit.A + MathF.Sin( t * 9f + p ) * 5f * (1f + a * 3f), bit.B + MathF.Sin( t * 5.3f + p ) * 10f );
					break;

				case BitKind.Cap:
				{
					// A slow breath, then a quick puff that flattens the cap.
					float puff = MathF.Pow( MathF.Max( 0f, MathF.Sin( t * 0.8f * pace + p ) ), 8f );
					go.LocalScale = new Vector3( bit.Scale.x * (1f + puff * 0.12f), bit.Scale.y * (1f + puff * 0.12f), bit.Scale.z * (1f - puff * 0.22f) );
					go.LocalPosition = bit.Pos;
					break;
				}

				case BitKind.Spore:
				{
					float f = Frac( t * 0.25f * pace + p );
					go.LocalPosition = bit.Pos + new Vector3( MathF.Sin( p * 9f + f * 4f ) * 7f, MathF.Cos( p * 7f + f * 3f ) * 7f, f * 34f );
					go.LocalScale = bit.Scale * MathF.Max( 1f - f, 0.02f );
					break;
				}

				case BitKind.Lamp:
					bit.Renderer.Tint = Frac( t * 0.7f * (1f + a * 3f) ) < 0.5f ? bit.Tint : bit.Tint.Darken( 0.8f );
					go.LocalPosition = bit.Pos;
					break;

				case BitKind.Wheel:
					go.LocalRotation = Rotation.FromAxis( Vector3.Left, _gait * 40f );
					go.LocalPosition = bit.Pos;
					break;
			}

			// The door: everything left of the middle goes left, everything right goes right.
			if ( open )
			{
				float side = bit.Pos.y > 1f ? 1f : bit.Pos.y < -1f ? -1f : (bit.Index % 2 == 0 ? 1f : -1f);
				go.LocalPosition += new Vector3( 0f, side * part, 0f );
			}
		}

		// The clung object, held close and turned over a little.
		if ( _prop.IsValid() )
		{
			_prop.LocalPosition = _propRest + Vector3.Up * (MathF.Sin( t * 1.6f ) * 0.8f);
			_prop.LocalRotation = new Angles( 0f, MathF.Sin( t * 0.6f ) * 25f, 12f + MathF.Sin( t * 1.3f ) * 6f ).ToRotation();
		}

		UpdateSeam( open );
	}

	/// <summary>The glowing seam of the body door, made the first time it opens.</summary>
	void UpdateSeam( bool open )
	{
		if ( !open )
		{
			if ( _seam.IsValid() && _seam.Enabled ) _seam.Enabled = false;
			return;
		}

		if ( !_seam.IsValid() )
		{
			_seam = new GameObject( _rig, true, "Seam" );
			_seam.Flags |= GameObjectFlags.NotSaved;
			_seam.Tags.Add( GlowTag );
			var renderer = _seam.Components.Create<ModelRenderer>();
			renderer.Model = _box;
			renderer.Tint = Color.Lerp( _secondary, Color.White, 0.75f );
			renderer.RenderType = ModelRenderer.ShadowRenderType.Off;

			_seamLight = _seam.Components.Create<PointLight>();
			_seamLight.LightColor = Color.Lerp( _secondary, Color.White, 0.5f );
			_seamLight.Shadows = false;
		}

		if ( !_seam.Enabled ) _seam.Enabled = true;
		float flicker = 0.85f + MathF.Sin( Time.Now * 23f ) * 0.15f;
		_seam.LocalPosition = new Vector3( 0f, 0f, _height * 0.5f );
		_seam.LocalScale = new Vector3( 22f, MathF.Max( Open * 9f * flicker, 0.2f ), _height * 0.82f ) / 50f;
		if ( _seamLight.IsValid() ) _seamLight.Radius = 60f + Open * 160f * flicker;
	}
}