Framework/Scripting/Api/LuaView.cs
using System;
using System.Linq;
using RoleplayFramework.Lua;
using RoleplayFramework.Players;

namespace RoleplayFramework.Scripting;

/// <summary>
/// The local player's view and raw mouse input, for weapons like scopes and the physics gun (client only).
///
///   LocalPlayer():SetFOV(fov [, seconds])   zoom to a field of view (0 or nil = back to the player's setting)
///   LocalPlayer():GetFOV()                  the current field of view
///   input.GetMouseDelta() → x, y            mouse movement this frame (pixels)
///   input.GetMouseWheel() → n               wheel movement this frame (+ up, - down)
///   input.SetLookScale(scale)               multiplies mouse look (0 = view locked, 1 = normal); kept until changed
///
/// Everything resets when the client realm stops, so a broken script can't leave the view zoomed or locked.
/// </summary>
public static class LuaView
{
	static float _fovTarget;          // 0 = player's own setting
	static float _fovFrom, _fovStart, _fovTime;
	static float _lookScale = 1f;
	static bool _active;

	public static void Register( LuaRealm realm )
	{
		if ( realm.Kind != LuaRealmKind.Client ) return;
		var ply = realm.MethodTables["Player"];

		LuaState.Register( ply, "SetFOV", ( s, a ) =>
		{
			Local( a, "SetFOV" );
			float fov = LuaState.ToNumber( LuaState.Arg( a, 1 ), out var f ) ? (float)f : 0f;
			if ( fov != 0 && (fov < 1 || fov > 170) ) throw LuaState.ArgError( 1, "SetFOV", "field of view must be 1-170 (0 = default)" );
			float time = LuaState.ToNumber( LuaState.Arg( a, 2 ), out var t ) ? (float)Math.Clamp( t, 0, 10 ) : 0f;
			_fovFrom = Game.ActiveScene?.Camera?.FieldOfView ?? 90f;
			_fovTarget = fov;
			_fovStart = RealTime.Now;
			_fovTime = time;
			_active = true;
			return null;
		} );
		LuaState.Register( ply, "GetFOV", ( s, a ) =>
		{
			Local( a, "GetFOV" );
			return new LuaValue[] { Game.ActiveScene?.Camera?.FieldOfView ?? 90f };
		} );

		var input = realm.State.GetOrCreateLibrary( "input" );
		LuaState.Register( input, "GetMouseDelta", ( s, a ) =>
		{
			if ( LuaUi.IsTyping ) return new LuaValue[] { 0, 0 };
			var d = Input.MouseDelta;
			return new LuaValue[] { d.x, d.y };
		} );
		LuaState.Register( input, "GetMouseWheel", ( s, a ) => new LuaValue[] { LuaUi.IsTyping ? 0 : Input.MouseWheel.y } );
		LuaState.Register( input, "SetLookScale", ( s, a ) =>
		{
			var v = LuaState.CheckNumber( a, 0, "input.SetLookScale" );
			_lookScale = (float)Math.Clamp( v, 0, 4 );
			_active = true;
			return null;
		} );
	}

	static void Local( LuaValue[] a, string m )
	{
		var id = LuaPlayers.HandleOf( LuaState.Arg( a, 0 ) ) ?? throw new LuaRuntimeException( $"calling '{m}' on a non-player value" );
		var p = LuaPlayers.Find( id );
		if ( p is null || !p.IsLocalPlayer ) throw new LuaRuntimeException( $"{m} only works on LocalPlayer()" );
	}

	static PlayerController LocalController() =>
		Game.ActiveScene?.GetAllComponents<RpPlayer>().FirstOrDefault( p => p.IsLocalPlayer )?.Controller;

	/// <summary>Every frame: applies zoom and look scale to the local player's controller and camera.</summary>
	public static void Tick()
	{
		if ( !_active ) return;
		var pc = LocalController();
		if ( pc is null ) return;
		var cam = pc.Scene.Camera;

		if ( pc.LookSensitivity != _lookScale ) pc.LookSensitivity = _lookScale;

		if ( _fovTarget > 0 || (_fovTime > 0 && RealTime.Now - _fovStart < _fovTime) )
		{
			pc.UseFovFromPreferences = false;
			float goal = _fovTarget > 0 ? _fovTarget : Preferences.FieldOfView;
			float k = _fovTime <= 0 ? 1f : Math.Clamp( (RealTime.Now - _fovStart) / _fovTime, 0f, 1f );
			if ( cam is not null ) cam.FieldOfView = MathX.Lerp( _fovFrom, goal, k );
		}
		else if ( !pc.UseFovFromPreferences )
		{
			pc.UseFovFromPreferences = true;
		}

		if ( _fovTarget <= 0 && _lookScale == 1f && pc.UseFovFromPreferences ) _active = false;
	}

	/// <summary>Client realm stopped: give the player their normal view back.</summary>
	public static void Reset()
	{
		_fovTarget = 0;
		_fovTime = 0;
		_lookScale = 1f;
		var pc = LocalController();
		if ( pc is not null ) { pc.LookSensitivity = 1f; pc.UseFovFromPreferences = true; }
		_active = false;
	}
}