Skins/SkinWearer.cs

Component on the lizard that lets it take the skin of a nearby dead humanoid on Use. Swaps the model for that person's, applies their speed, jump, camera, cling, tools and faction, drives basic citizen animgraph walk parameters, and restores everything on Drop, disable or shed.

using System;

/// <summary>
/// Goes on the lizard. Lets it wear the skin of a dead humanoid nearby (Use), which swaps its
/// look for that person's model and gives it their stats, tools and faction. Drop or Reload
/// sheds the skin and puts everything back as it was.
/// </summary>
[Title( "Skin Wearer" ), Category( "Skins" ), Icon( "theater_comedy" )]
public sealed class SkinWearer : Component
{
	/// <summary>How close a corpse has to be for its skin to be taken, in inches.</summary>
	[Property] public float TakeRange { get; set; } = 130f;

	/// <summary>The skin being worn, or null while a plain lizard.</summary>
	public SkinDefinition Current { get; private set; }
	public bool IsWearing => Current is not null;

	/// <summary>
	/// While a skin is worn, shows either the person or the lizard underneath. Used to make the
	/// skin flicker as it fails; it changes nothing but what is drawn.
	/// </summary>
	public void ShowSkin( bool person )
	{
		if ( !IsWearing ) return;
		if ( _skinObject.IsValid() && _skinObject.Enabled != person ) _skinObject.Enabled = person;
		// The same object Wear hid (it holds whichever lizard is in use, old body or rigged model).
		var body = Body;
		if ( body.IsValid() && body.Enabled == person ) body.Enabled = !person;
	}

	static bool HasToolIn( SkinDefinition definition, string name ) =>
		definition?.Tools is not null && definition.Tools.Exists( t => string.Equals( t, name, System.StringComparison.OrdinalIgnoreCase ) );

	/// <summary>Whether the worn skin grants the named tool or ability ("speak"). Case doesn't matter.</summary>
	public bool HasTool( string name ) =>
		Current?.Tools is not null && Current.Tools.Exists( t => string.Equals( t, name, StringComparison.OrdinalIgnoreCase ) );

	const float ScanInterval = 0.25f;

	Skin _nearby;
	TimeSince _sinceScan = 10f;
	GameObject _skinObject;
	SkinnedModelRenderer _skinRenderer;

	// The lizard's own values, remembered while a skin is worn.
	float _speed, _sprintSpeed, _jumpSpeed, _cameraHeight;
	bool _cling, _bodyWasEnabled;
	string _faction;

	ReptileController Controller => Components.Get<ReptileController>();
	GameObject Body => GameObject.Children.Find( c => c.Name == "Body" );

	const string Prompt = "E  wear the skin";

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

		if ( IsWearing )
		{
			AnimateSkin();
			if ( Input.Pressed( "Drop" ) ) Shed();
			return;
		}

		if ( _sinceScan > ScanInterval )
		{
			_sinceScan = 0f;
			_nearby = FindCorpse();
			// Shown a little longer than the gap between scans, so it stays up while in range.
			// It never talks over a story line: it waits until nothing else is on screen.
			var director = StoryDirector.Get( Scene );
			if ( _nearby.IsValid() && director is not null && (!director.MessageVisible || director.Message == Prompt) )
				director.ShowMessage( Prompt, ScanInterval * 2f );
		}

		if ( _nearby.IsValid() && Input.Pressed( "Use" ) )
		{
			var corpse = _nearby;
			_nearby = null;
			Wear( corpse.Definition );
			CorpseOf( corpse ).Destroy();
		}
	}

	/// <summary>The nearest dead body in range whose skin can be taken, or null.</summary>
	Skin FindCorpse()
	{
		Skin best = null;
		float bestDistance = TakeRange;
		foreach ( var skin in Scene.GetAllComponents<Skin>() )
		{
			if ( skin.Definition is null ) continue;
			var health = skin.Components.Get<Health>( FindMode.EverythingInSelfAndAncestors );
			if ( health is null || !health.IsDead ) continue;

			float distance = skin.WorldPosition.Distance( WorldPosition );
			if ( distance > bestDistance ) continue;
			best = skin;
			bestDistance = distance;
		}
		return best;
	}

	/// <summary>The whole body to remove: the object holding the Health (the skin's own or a parent).</summary>
	static GameObject CorpseOf( Skin skin ) =>
		skin.Components.Get<Health>( FindMode.EverythingInSelfAndAncestors )?.GameObject ?? skin.GameObject;

	/// <summary>Puts a skin on: its model, stats, tools and faction. Replaces any skin already worn.</summary>
	public void Wear( SkinDefinition definition )
	{
		definition?.EnsureLoaded();
		if ( definition is null ) return;
		if ( IsWearing ) Restore();
		Current = definition;

		// Hide the lizard and stand the person's model on the same spot.
		var body = Body;
		_bodyWasEnabled = body.IsValid() && body.Enabled;
		if ( body.IsValid() ) body.Enabled = false;

		_skinObject = new GameObject( GameObject, true, "Skin Model" );
		_skinObject.Flags |= GameObjectFlags.NotSaved;
		_skinObject.LocalPosition = Vector3.Zero;
		_skinObject.LocalRotation = Rotation.Identity;
		_skinRenderer = _skinObject.Components.Create<SkinnedModelRenderer>();
		_skinRenderer.Model = definition.Model;
		_skinAnimated = HasAnimGraph( definition.Model );
		_sentGrounded = -1;
		_sentX = _sentY = _sentSpeed = int.MinValue;

		// Tools the skin carries. A flashlight is a real torch at head height.
		if ( HasToolIn( definition, "flashlight" ) )
		{
			var torch = new GameObject( _skinObject, true, "Skin Flashlight" );
			torch.Flags |= GameObjectFlags.NotSaved;
			torch.LocalPosition = new Vector3( 18f, -9f, 58f );
			var light = torch.Components.Create<SpotLight>();
			light.LightColor = new Color( 0.85f, 0.92f, 1f );
			light.Intensity = 25f;
			light.ConeOuter = 16f;
			light.ConeInner = 10f;
			light.Radius = 1800f;
			light.Shadows = true;
			var shaft = torch.Components.Create<LightShaft>();
			shaft.MaxLength = 900f;
			shaft.Sprites = 16;
			shaft.Brightness = 0.003f;
			shaft.MaxBrightness = 0.07f;
		}

		var controller = Controller;
		if ( controller.IsValid() )
		{
			_speed = controller.Speed;
			_sprintSpeed = controller.SprintSpeed;
			_jumpSpeed = controller.JumpSpeed;
			_cameraHeight = controller.CameraHeight;
			_cling = controller.ClingEnabled;

			controller.Speed = _speed * definition.SpeedMultiplier;
			controller.SprintSpeed = _sprintSpeed * definition.SprintMultiplier;
			controller.JumpSpeed = _jumpSpeed * definition.JumpMultiplier;
			controller.ClingEnabled = definition.CanCling;
			if ( definition.CameraHeight > 0f ) controller.CameraHeight = definition.CameraHeight;
		}


		var tag = Components.GetOrCreate<FactionTag>();
		_faction = tag.Faction;
		if ( !string.IsNullOrEmpty( definition.Faction ) ) tag.Faction = definition.Faction;

		StoryDirector.Get( Scene )?.ShowMessage( $"You wear the {definition.Title}.  G  shed it", 4f );
	}

	/// <summary>Takes the skin off and goes back to being a lizard.</summary>
	public void Shed()
	{
		if ( !IsWearing ) return;
		Restore();
		StoryDirector.Get( Scene )?.ShowMessage( "You shed the skin.", 3f );
	}

	/// <summary>Puts back everything Wear changed and removes the skin's model.</summary>
	void Restore()
	{
		if ( !IsWearing ) return;
		Current = null;

		if ( _skinObject.IsValid() ) _skinObject.Destroy();
		_skinObject = null;
		_skinRenderer = null;

		var body = Body;
		if ( body.IsValid() ) body.Enabled = _bodyWasEnabled;

		var controller = Controller;
		if ( controller.IsValid() )
		{
			controller.Speed = _speed;
			controller.SprintSpeed = _sprintSpeed;
			controller.JumpSpeed = _jumpSpeed;
			controller.CameraHeight = _cameraHeight;
			controller.ClingEnabled = _cling;
		}


		var tag = Components.Get<FactionTag>();
		if ( tag.IsValid() ) tag.Faction = _faction;
	}

	/// <summary>
	/// Basic walk and idle for citizen-type models, from how the lizard is moving. These are the
	/// citizen animgraph's parameters; a model without them just ignores the calls.
	/// </summary>
	void AnimateSkin()
	{
		var controller = Controller;
		if ( !_skinAnimated || !_skinRenderer.IsValid() || !controller.IsValid() ) return;

		// Nothing to drive while the model is switched off (the skin flickering as it fails) or
		// has not been made yet. Setting parameters then fails inside the engine, every call.
		// (A model made afresh starts with no parameters, so everything is sent again after that.)
		if ( !_skinRenderer.Active || _skinRenderer.SceneModel is null )
		{
			_sentGrounded = -1;
			_sentX = _sentY = _sentSpeed = int.MinValue;
			return;
		}

		var velocity = controller.Velocity;
		var rotation = _skinRenderer.WorldRotation;
		float forward = Vector3.Dot( velocity, rotation.Forward );
		float sideward = Vector3.Dot( velocity, rotation.Right );

		// Only what has changed is sent, in steps of a few inches a second: walking at a steady
		// pace sends nothing at all, instead of seven calls every frame.
		int grounded = controller.Attached ? 1 : 0;
		int x = (int)MathF.Round( forward / 4f ), y = (int)MathF.Round( -sideward / 4f ), speed = (int)MathF.Round( velocity.Length / 4f );

		// The citizen model uses the older animation graph, driven through the renderer directly.
#pragma warning disable CS0618
		if ( grounded != _sentGrounded ) { _sentGrounded = grounded; _skinRenderer.Set( "b_grounded", grounded == 1 ); }
		if ( x != _sentX )
		{
			_sentX = x;
			_skinRenderer.Set( "move_x", x * 4f );
			_skinRenderer.Set( "wish_x", x * 4f );
		}
		if ( y != _sentY )
		{
			_sentY = y;
			_skinRenderer.Set( "move_y", y * 4f );
			_skinRenderer.Set( "wish_y", y * 4f );
		}
		if ( speed != _sentSpeed )
		{
			_sentSpeed = speed;
			_skinRenderer.Set( "move_groundspeed", speed * 4f );
			_skinRenderer.Set( "wish_groundspeed", speed * 4f );
		}
#pragma warning restore CS0618
	}

	bool _skinAnimated;
	int _sentGrounded = -1, _sentX = int.MinValue, _sentY = int.MinValue, _sentSpeed = int.MinValue;

	/// <summary>True if a model has an animation graph to take the walk parameters. One without would reject every call.</summary>
	static bool HasAnimGraph( Model model )
	{
		if ( model is null || model.IsError ) return false;
#pragma warning disable CS0618
		return model.AnimGraph is not null || model.AnimationGraph is not null;
#pragma warning restore CS0618
	}

	// Never leave the lizard stuck with a skin's stats if this component goes away.
	protected override void OnDisabled() => Restore();
}