ReptileBody.cs

Procedural fallback reptile body built from ellipsoids and a tapered tail, generated as meshes at runtime. Poses separate head, arm, leg and tail parts from ReptileController state (gait phase, reach, bite strike) and hides itself when the rigged model is showing.

using System;
using System.Collections.Generic;

/// <summary>
/// The original lizard, built from simple shapes: hunched upright torso on two bent legs, two
/// arms, wedge head with eye bumps and a tapering tail. The head, limbs and tail are separate
/// pieces: the legs step and plant with the stride, the arms reach for grips, and the head and
/// claws snap forward in a bite. Local +X is forward, +Z up, origin on the ground.
///
/// It is the fallback only. The game's lizard is the rigged model (<see cref="LizardRig"/>,
/// chosen by <see cref="ReptileController.UseNewModel"/>, on by default); while that is showing
/// this body is <see cref="Hidden"/> and does nothing but keep its pieces.
/// </summary>
[Title( "Reptile Body" ), Category( "Player" ), Icon( "pets" )]
public sealed class ReptileBody : Component, Component.ExecuteInEditor
{
	[RequireComponent] public ModelRenderer Renderer { get; set; }

	[Property] public Material Material { get; set; }

	/// <summary>Overall size multiplier.</summary>
	[Property, Range( 0.3f, 4f )] public float Size { get; set; } = 1f;

	/// <summary>Inches covered by one repeat of the skin texture.</summary>
	[Property] public float TextureScale { get; set; } = 14f;

	/// <summary>How far the legs and arms swing at full sprint, in degrees.</summary>
	[Property, Range( 0, 70 )] public float StrideAngle { get; set; } = 42f;

	// Bump when the shape code changes so open editors rebuild after a hotload.
	const int ShapeVersion = 4;

	// Held so generated meshes aren't garbage collected (they would stop drawing).
	readonly List<Mesh> _meshes = new();
	readonly List<Model> _models = new();
	readonly Dictionary<string, GameObject> _parts = new();
	int _built;
	Model _coreModel;
	float _stride;
	ReptileController _controller;

	protected override void OnEnabled() => _built = 0;
	protected override void OnDisabled() => ClearParts();

	// Built during the frame update: meshes created in OnEnabled don't draw in the editor.
	protected override void OnUpdate()
	{
		// Rebuild when a setting changes, and also when something else has replaced our mesh or
		// removed the limbs (the editor does both when it refreshes a prefab instance).
		int settings = HashCode.Combine( Material, Size, TextureScale, ShapeVersion );
		if ( Renderer is not null && (settings != _built || Renderer.Model != _coreModel || LimbsMissing()) )
		{
			_built = settings;
			Build();
		}
		// Hidden behind the rigged model it is not posed either: nothing is looking at it, and
		// anything that asks where a limb is gets the rig's answer first (and this body's last
		// pose if the rig has none).
		if ( !Hidden ) Animate();
		ApplyHidden();
	}

	/// <summary>
	/// Set while the rigged model (<see cref="LizardRig"/>) is standing in for this body: nothing
	/// of it is drawn or animated, but its pieces stay where they were, so a limb can still be found.
	/// </summary>
	public bool Hidden { get; set; }
	bool _hiddenApplied;

	void ApplyHidden()
	{
		if ( Hidden == _hiddenApplied && !Hidden ) return;
		_hiddenApplied = Hidden;
		if ( Renderer.IsValid() && Renderer.Enabled == Hidden ) Renderer.Enabled = !Hidden;
		foreach ( var part in _parts.Values )
		{
			if ( !part.IsValid() ) continue;
			var renderer = part.Components.Get<ModelRenderer>( FindMode.EverythingInSelf );
			if ( renderer.IsValid() && renderer.Enabled == Hidden ) renderer.Enabled = !Hidden;
		}
	}

	bool LimbsMissing()
	{
		if ( _parts.Count == 0 ) return true;
		foreach ( var go in _parts.Values )
			if ( !go.IsValid() ) return true;
		return false;
	}

	void Animate()
	{
		_controller ??= Components.Get<ReptileController>( FindMode.EverythingInSelfAndAncestors );
		bool has = _controller.IsValid();
		if ( has && !_attack.IsValid() ) _attack = _controller.Components.Get<LizardAttack>();

		float speed = has ? _controller.Velocity.Length : 0f;
		float run = Math.Clamp( speed / 620f, 0f, 1f );
		float effort = MathF.Sqrt( run );
		bool climbing = has && _controller.Attached && _controller.Up.z < 0.7f;

		// Limbs follow the controller's stride, so the hands plant when its movement holds.
		if ( has ) _stride = _controller.GaitPhase;
		float idle = MathF.Sin( Time.Now * 1.6f );

		// A stepping gait, not a pendulum: each limb snaps through its swing and then holds at
		// the end of it (planted) while the other one moves. Flattening the sine does that.
		float wave = MathF.Sin( _stride );
		float step = MathF.Sign( wave ) * MathF.Pow( MathF.Abs( wave ), 0.45f );
		float swing = step * StrideAngle * effort;

		// The foot that is travelling forward is lifted clear; the planted one is down.
		float liftL = MathF.Max( 0f, MathF.Cos( _stride ) ) * 5f * effort;
		float liftR = MathF.Max( 0f, -MathF.Cos( _stride ) ) * 5f * effort;

		// Legs: stride, or pulled right up under the body while it swings round a grip.
		float tuck = has ? _controller.LegTuck : 0f;
		if ( has && _controller.FeetHolding )
		{
			// Feet still gripping the old face: both legs stretch back to it as the body pulls away.
			PoseLimb( "leg_l", LegRest, _controller.FootPoint, Rotation.FromPitch( swing ), 1f );
			PoseLimb( "leg_r", LegRest, _controller.FootPoint, Rotation.FromPitch( -swing ), 1f );
		}
		else
		{
			Pose( "leg_l", Rotation.FromPitch( swing * (1f - tuck) - 75f * tuck ), Vector3.Up * liftL );
			Pose( "leg_r", Rotation.FromPitch( -swing * (1f - tuck) - 75f * tuck ), Vector3.Up * liftR );
		}

		// The bite: -0.3 in the wind-up, 1 at the snap, back to 0.
		float strike = _attack.IsValid() ? _attack.Strike : 0f;

		// Arms: stride (reaching hand over hand when climbing), stretched out to the grip point
		// while reaching or holding, or raking forward in a bite.
		float armSwing = swing * (climbing ? 1.5f : 0.7f);
		var armL = Rotation.FromPitch( -armSwing + idle * 2f - (climbing ? 35f : 0f) );
		var armR = Rotation.FromPitch( armSwing + idle * 2f - (climbing ? 35f : 0f) );
		if ( strike != 0f )
		{
			// Both claws come up and rake inward across the front.
			armL = Rotation.FromPitch( -85f * strike ) * Rotation.FromYaw( -28f * strike );
			armR = Rotation.FromPitch( -85f * strike ) * Rotation.FromYaw( 28f * strike );
		}
		float reach = has && _controller.IsReaching && strike == 0f ? _controller.ReachAmount : 0f;
		var grip = has ? _controller.GripPoint : Vector3.Zero;
		PoseLimb( "arm_l", ArmRest, grip, armL, reach );
		PoseLimb( "arm_r", ArmRest, grip, armR, reach );

		// Head and neck: a slow idle look-about, a nod with each step, and the snap of the bite
		// (drawn back, then thrown forward and down past where it started).
		float nod = MathF.Abs( wave ) * 4f * effort;
		Pose( "head",
			Rotation.FromPitch( idle * 1.5f + nod + strike * 26f ) * Rotation.FromYaw( MathF.Sin( Time.Now * 0.7f ) * 4f * (1f - run) ),
			Vector3.Forward * (strike * 11f) + Vector3.Down * (MathF.Max( strike, 0f ) * 3f) );

		Pose( "tail", Rotation.FromYaw( MathF.Sin( _stride * 0.5f + Time.Now * 1.3f ) * (8f + 14f * run) ) * Rotation.FromPitch( -8f * run - 25f * tuck + strike * 14f ) );
	}

	LizardAttack _attack;
	readonly Dictionary<string, Vector3> _rest = new();

	// Directions from joint to tip in each limb's rest pose (local space): shoulder to hand, hip to foot.
	static readonly Vector3 ArmRest = new Vector3( 15f, 0f, -21.5f ).Normal;
	static readonly Vector3 LegRest = new Vector3( 5f, 0f, -24f ).Normal;

	/// <summary>Names of the parts something can take hold of.</summary>
	public static readonly string[] GrabbableLimbs = { "arm_l", "arm_r", "leg_l", "leg_r", "tail" };

	/// <summary>World position of the end of a limb (hand, foot, or the middle of the tail).</summary>
	public Vector3 LimbTip( string part )
	{
		if ( !_parts.TryGetValue( part, out var go ) || !go.IsValid() ) return WorldPosition + WorldRotation.Up * (25f * Size);

		var reach = part.StartsWith( "arm" ) ? ArmRest * 26f : part.StartsWith( "leg" ) ? LegRest * 24f : Vector3.Backward * 34f;
		return go.WorldPosition + go.WorldRotation * (reach * Size);
	}

	/// <summary>Blends a limb from its stride pose toward pointing its tip at a world point.</summary>
	void PoseLimb( string part, Vector3 rest, Vector3 target, Rotation stride, float amount )
	{
		if ( !_parts.TryGetValue( part, out var go ) || !go.IsValid() ) return;
		if ( amount <= 0.001f ) { go.LocalRotation = stride; return; }

		var toTarget = WorldRotation.Inverse * (target - go.WorldPosition);
		if ( toTarget.Length < 0.01f ) { go.LocalRotation = stride; return; }

		float dot = Math.Clamp( Vector3.Dot( rest, toTarget.Normal ), -1f, 1f );
		var axis = Vector3.Cross( rest, toTarget.Normal );
		var aim = axis.Length < 0.0001f ? Rotation.Identity : Rotation.FromAxis( axis.Normal, MathF.Acos( dot ) * 180f / MathF.PI );
		go.LocalRotation = Rotation.Slerp( stride, aim, Math.Clamp( amount, 0f, 1f ) );
	}

	/// <summary>Turns a part about its joint, optionally shifting the joint itself (in inches, body space).</summary>
	void Pose( string part, Rotation rotation, Vector3 offset = default )
	{
		if ( !_parts.TryGetValue( part, out var go ) || !go.IsValid() ) return;
		go.LocalRotation = rotation;
		if ( _rest.TryGetValue( part, out var rest ) ) go.LocalPosition = rest + offset * Size;
	}

	void Build()
	{
		ClearParts();
		var pos = new List<Vector3>();
		var tris = new List<int>();

		// Core: upright but hunched torso.
		Ellipsoid( pos, tris, new Vector3( -2, 0, 25 ), new Vector3( 8, 8, 7 ) );                  // hips
		Ellipsoid( pos, tris, new Vector3( 6, 0, 35 ), new Vector3( 14, 8.5f, 7 ), -50 );          // torso
		_coreModel = MakeModel( pos, tris, Vector3.Zero );
		Renderer.Model = _coreModel;

		// Head and neck are one piece hinged at the base of the neck, so they can snap forward.
		pos.Clear(); tris.Clear();
		Ellipsoid( pos, tris, new Vector3( 15.5f, 0, 46 ), new Vector3( 6.5f, 4.5f, 4.5f ), -40 ); // neck
		Ellipsoid( pos, tris, new Vector3( 22, 0, 51 ), new Vector3( 9, 6, 4.6f ) );               // head
		Ellipsoid( pos, tris, new Vector3( 31, 0, 49.5f ), new Vector3( 8, 4.4f, 2.8f ), 8 );      // snout
		Ellipsoid( pos, tris, new Vector3( 23, 4.6f, 54.3f ), new Vector3( 2.2f, 2f, 2f ) );       // eyes
		Ellipsoid( pos, tris, new Vector3( 23, -4.6f, 54.3f ), new Vector3( 2.2f, 2f, 2f ) );
		AddPart( "head", pos, tris, new Vector3( 11, 0, 42 ) );

		foreach ( float side in new[] { -1f, 1f } )
		{
			string suffix = side > 0 ? "_l" : "_r";

			pos.Clear(); tris.Clear();
			Ellipsoid( pos, tris, new Vector3( 13, 10.5f * side, 35 ), new Vector3( 8, 3, 3 ), 75 );       // upper arm
			Ellipsoid( pos, tris, new Vector3( 19, 11 * side, 25 ), new Vector3( 7, 2.6f, 2.6f ), 35 );    // forearm
			Ellipsoid( pos, tris, new Vector3( 26, 11 * side, 20.5f ), new Vector3( 4.5f, 3, 1.6f ), 20 ); // hand
			AddPart( "arm" + suffix, pos, tris, new Vector3( 11, 10.5f * side, 42 ) );

			pos.Clear(); tris.Clear();
			Ellipsoid( pos, tris, new Vector3( 2, 6.5f * side, 18 ), new Vector3( 9.5f, 4.6f, 5 ), 60 );    // thigh
			Ellipsoid( pos, tris, new Vector3( 1, 7 * side, 7.5f ), new Vector3( 7.5f, 3.2f, 3.2f ), -65 ); // shin
			Ellipsoid( pos, tris, new Vector3( 6, 7.5f * side, 1.3f ), new Vector3( 9, 4.5f, 1.4f ) );      // foot
			AddPart( "leg" + suffix, pos, tris, new Vector3( -1, 6.5f * side, 25 ) );
		}

		pos.Clear(); tris.Clear();
		Tail( pos, tris, new Vector3( -7, 0, 25 ), 58f, 6.5f );
		AddPart( "tail", pos, tris, new Vector3( -7, 0, 25 ) );
	}

	/// <summary>Makes a child object holding one limb, pivoting at its joint.</summary>
	void AddPart( string name, List<Vector3> pos, List<int> tris, Vector3 pivot )
	{
		var go = new GameObject( GameObject, true, name );
		go.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.Hidden;
		go.LocalPosition = pivot * Size;
		go.Components.Create<ModelRenderer>().Model = MakeModel( pos, tris, pivot );
		_parts[name] = go;
		_rest[name] = pivot * Size;
	}

	void ClearParts()
	{
		foreach ( var go in _parts.Values )
			if ( go.IsValid() ) go.Destroy();
		_parts.Clear();
		_rest.Clear();
		_meshes.Clear();
		_models.Clear();
	}

	Model MakeModel( List<Vector3> pos, List<int> tris, Vector3 pivot )
	{
		// Smooth normals pointing out of each shape.
		var normals = new Vector3[pos.Count];
		for ( int i = 0; i < tris.Count; i += 3 )
		{
			var n = Vector3.Cross( pos[tris[i + 1]] - pos[tris[i]], pos[tris[i + 2]] - pos[tris[i]] );
			normals[tris[i]] += n; normals[tris[i + 1]] += n; normals[tris[i + 2]] += n;
		}

		var verts = new List<Vertex>( pos.Count );
		var bounds = new BBox( Vector3.Zero, Vector3.Zero );
		for ( int i = 0; i < pos.Count; i++ )
		{
			var world = pos[i] * Size;
			var p = (pos[i] - pivot) * Size;
			var n = normals[i].Normal;
			var tangent = (Vector3.Forward - n * Vector3.Dot( Vector3.Forward, n )).Normal;
			verts.Add( new Vertex( p, n, tangent, new Vector4( world.x / TextureScale, (world.y + world.z) / TextureScale, 0, 0 ) ) );
			bounds = i == 0 ? new BBox( p, p ) : bounds.AddPoint( p );
		}

		// Both windings, so it shows whichever way the renderer culls.
		var indices = new List<int>( tris.Count * 2 );
		for ( int i = 0; i < tris.Count; i += 3 )
			indices.AddRange( new[] { tris[i], tris[i + 1], tris[i + 2], tris[i], tris[i + 2], tris[i + 1] } );

		var mesh = new Mesh( Material );
		mesh.CreateVertexBuffer( verts.Count, verts );
		mesh.CreateIndexBuffer( indices.Count, indices );
		mesh.Bounds = bounds;

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

	/// <summary>An ellipsoid whose long (X) axis is pitched by the given degrees; positive points the front down.</summary>
	static void Ellipsoid( List<Vector3> pos, List<int> tris, Vector3 center, Vector3 radii, float pitch = 0f )
	{
		const int segments = 10, rings = 7;
		var rot = Rotation.FromPitch( pitch );
		int start = pos.Count;
		for ( int r = 0; r <= rings; r++ )
		{
			float v = r / (float)rings * MathF.PI;
			for ( int s = 0; s < segments; s++ )
			{
				float u = s / (float)segments * MathF.PI * 2f;
				pos.Add( center + rot * new Vector3( MathF.Cos( v ) * radii.x, MathF.Sin( v ) * MathF.Cos( u ) * radii.y, MathF.Sin( v ) * MathF.Sin( u ) * radii.z ) );
			}
		}
		for ( int r = 0; r < rings; r++ )
			for ( int s = 0; s < segments; s++ )
			{
				int a = start + r * segments + s, b = start + r * segments + (s + 1) % segments;
				tris.AddRange( new[] { a, b, b + segments, a, b + segments, a + segments } );
			}
	}

	/// <summary>A tapering tube running backwards (-X) with a gentle S-bend and droop.</summary>
	static void Tail( List<Vector3> pos, List<int> tris, Vector3 root, float length, float radius )
	{
		const int segments = 8, rings = 9;
		int start = pos.Count;
		for ( int r = 0; r <= rings; r++ )
		{
			float t = r / (float)rings;
			var c = root + new Vector3( -length * t, MathF.Sin( t * MathF.PI * 1.5f ) * 6f, -17f * t * t );
			float rad = radius * (1f - t) + 0.4f;
			for ( int s = 0; s < segments; s++ )
			{
				float u = s / (float)segments * MathF.PI * 2f;
				pos.Add( c + new Vector3( 0, MathF.Cos( u ) * rad, MathF.Sin( u ) * rad * 0.8f ) );
			}
		}
		for ( int r = 0; r < rings; r++ )
			for ( int s = 0; s < segments; s++ )
			{
				int a = start + r * segments + s, b = start + r * segments + (s + 1) % segments;
				tris.AddRange( new[] { a, b + segments, b, a, a + segments, b + segments } );
			}
	}
}