Framework/Scripting/Api/LuaRender.cs
using System;
using System.Collections.Generic;
using RoleplayFramework.Lua;
using RoleplayFramework.Players;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Weapon visuals and immediate 3D lines for Lua.
///
/// Client: <c>render.DrawBeam(start, end, width [, color])</c> / <c>render.DrawLine(start, end [, color])</c>, only inside
/// PostDrawOpaqueRenderables / PostDrawTranslucentRenderables (like GMod). Pooled line renderers, max 512 per frame.
/// Players: <c>ply:SetWeaponModels{...}</c> (server), <c>ply:WeaponAnim(param [, skipOwner])</c>,
/// <c>ply:GetMuzzlePos()</c> - see <see cref="RpHeldWeapon"/>.
/// </summary>
public static class LuaRender
{
	public const int MaxBeamsPerFrame = 512;

	static readonly List<LineRenderer> _pool = new();
	static int _used;

	public static void Register( LuaRealm realm )
	{
		var server = realm.Kind == LuaRealmKind.Server;
		var ply = realm.MethodTables["Player"];

		// ply:SetWeaponModels({ world =, view =, hold =, hand =, offset =, angles =, viewBodygroups =, lowered =, viewOffset = })
		// (server). world/view: model path or package ident ("" = none; view "arms" = arms only). hold: GMod or animgraph
		// hold type. hand: "both", "right", "left". offset/angles: world model relative to the hand bone. viewOffset: view
		// model shift in view space (x forward, y left, z up).
		// The positional form SetWeaponModels(world, view, hold [, offset [, angles]]) also works.
		LuaState.Register( ply, "SetWeaponModels", ( s, a ) =>
		{
			if ( !server ) throw new LuaRuntimeException( "SetWeaponModels can only be called on the server" );
			var p = Player( a, "SetWeaponModels" );
			var held = p.Components.GetOrCreate<RpHeldWeapon>();
			LuaValue world, view, hold, hand = LuaValue.Nil, offset, angles, bodygroups = LuaValue.Nil, lowered = LuaValue.Nil, viewOffset = LuaValue.Nil;
			if ( LuaState.Arg( a, 1 ).IsTable )
			{
				var t = LuaState.Arg( a, 1 ).AsTable;
				world = t.Get( "world" ); view = t.Get( "view" ); hold = t.Get( "hold" ); hand = t.Get( "hand" );
				offset = t.Get( "offset" ); angles = t.Get( "angles" ); bodygroups = t.Get( "viewBodygroups" ); lowered = t.Get( "lowered" );
				viewOffset = t.Get( "viewOffset" );
			}
			else
			{
				world = LuaState.Arg( a, 1 ); view = LuaState.Arg( a, 2 ); hold = LuaState.Arg( a, 3 );
				offset = LuaState.Arg( a, 4 ); angles = LuaState.Arg( a, 5 );
			}
			var worldPath = ModelArg( world, "SetWeaponModels" );
			var viewPath = view.IsString && view.AsString == "arms" ? "arms" : ModelArg( view, "SetWeaponModels" );
			var off = offset.IsNil ? Vector3.Zero : LuaConvert.ToVector( offset, "offset" );
			if ( off.Length > 100 ) throw LuaState.ArgError( 1, "SetWeaponModels", "offset must be within 100 units of the hand" );
			held.WorldModel = worldPath;
			held.ViewModel = viewPath;
			held.HoldType = RpHeldWeapon.HoldTypeOf( hold.IsString ? hold.AsString : "none" );
			held.Handedness = RpHeldWeapon.HandednessOf( hand.IsString ? hand.AsString : "both" );
			held.WorldOffset = off;
			held.WorldAngles = angles.IsNil ? Angles.Zero : LuaConvert.ToAngles( angles, "angles" );
			held.ViewBodyGroups = LuaState.ToNumber( bodygroups, out var bg ) && bg >= 0 ? (ulong)bg : 0;
			held.Lowered = lowered.IsTruthy;
			var vo = viewOffset.IsNil ? Vector3.Zero : LuaConvert.ToVector( viewOffset, "viewOffset" );
			if ( vo.Length > 30 ) throw LuaState.ArgError( 1, "SetWeaponModels", "viewOffset must be within 30 units" );
			held.ViewOffset = vo;
			return null;
		} );

		// ply:WeaponAnim(param [, skipOwner]) - server: on every machine (skipOwner: not on the owner, who predicted
		// it). Client: on this machine only, for the local player (prediction).
		LuaState.Register( ply, "WeaponAnim", ( s, a ) =>
		{
			var p = Player( a, "WeaponAnim" );
			var param = LuaState.CheckString( a, 1, "WeaponAnim" );
			if ( param.Length > 32 ) throw LuaState.ArgError( 1, "WeaponAnim", "parameter name too long" );
			var held = p.Components.GetOrCreate<RpHeldWeapon>();
			if ( server ) held.PlayAnim( param, LuaState.Arg( a, 2 ).IsTruthy );
			else if ( p.IsLocalPlayer ) held.AnimLocal( param );
			else throw new LuaRuntimeException( "WeaponAnim on the client only works on LocalPlayer()" );
			return null;
		} );

		// ply:SetViewModelParam(name, bool|number|nil) - client, LocalPlayer(): a view model animgraph parameter kept set
		// (e.g. "b_empty" while the magazine is empty, "ironsights" 0-1). nil clears it.
		LuaState.Register( ply, "SetViewModelParam", ( s, a ) =>
		{
			if ( server ) throw new LuaRuntimeException( "SetViewModelParam is client-only (LocalPlayer())" );
			var p = Player( a, "SetViewModelParam" );
			if ( !p.IsLocalPlayer ) throw new LuaRuntimeException( "SetViewModelParam only works on LocalPlayer()" );
			var name = LuaState.CheckString( a, 1, "SetViewModelParam" );
			if ( name.Length > 48 ) throw LuaState.ArgError( 1, "SetViewModelParam", "name too long" );
			var v = LuaState.Arg( a, 2 );
			object value = v.IsNil ? null : v.Type == LuaType.Boolean ? v.IsTruthy : LuaState.ToNumber( v, out var n ) ? (float)n : throw LuaState.ArgError( 2, "SetViewModelParam", "boolean, number or nil expected" );
			p.Components.GetOrCreate<RpHeldWeapon>().SetViewParam( name, value );
			return null;
		} );

		// ply:SetViewModelVisible(b) - client, LocalPlayer(): show or hide the first-person view model (scopes).
		LuaState.Register( ply, "SetViewModelVisible", ( s, a ) =>
		{
			if ( server ) throw new LuaRuntimeException( "SetViewModelVisible is client-only (LocalPlayer())" );
			var p = Player( a, "SetViewModelVisible" );
			if ( !p.IsLocalPlayer ) throw new LuaRuntimeException( "SetViewModelVisible only works on LocalPlayer()" );
			p.Components.GetOrCreate<RpHeldWeapon>().ViewHidden = !LuaState.Arg( a, 1 ).IsTruthy;
			return null;
		} );

		// ply:GetMuzzlePos() -> Vector, Angle: the weapon's muzzle (view model in first person, else world model,
		// else the eyes). Both realms.
		LuaState.Register( ply, "GetMuzzlePos", ( s, a ) =>
		{
			var t = Player( a, "GetMuzzlePos" ).Components.GetOrCreate<RpHeldWeapon>().MuzzleTransform();
			return new[] { LuaConvert.FromVector( s, t.Position ), LuaConvert.FromAngles( s, t.Rotation.Angles() ) };
		} );

		// util.Effect(name, pos [, scale]) - a short visual effect: "Explosion" (fireball light), "Flash" (small light),
		// "Sparks". Server: everyone sees it. Client: only this client.
		var util = realm.State.GetOrCreateLibrary( "util" );
		LuaState.Register( util, "Effect", ( s, a ) =>
		{
			var name = LuaState.CheckString( a, 0, "util.Effect" );
			if ( !RpEffect.IsKnown( name ) ) throw LuaState.ArgError( 0, "util.Effect", $"unknown effect '{name}' (Explosion, Flash, Sparks)" );
			var pos = LuaConvert.ToVector( LuaState.Arg( a, 1 ), "position" );
			float scale = LuaState.ToNumber( LuaState.Arg( a, 2 ), out var sc ) ? (float)Math.Clamp( sc, 0.1, 10 ) : 1f;
			if ( server && Networking.IsActive ) RpEffect.Broadcast( name, pos, scale );
			else RpEffect.Play( name, pos, scale );
			return null;
		} );

		if ( server ) return;

		var render = realm.State.GetOrCreateLibrary( "render" );
		LuaNativeFunction beam = ( s, a ) =>
		{
			if ( !LuaDraw.InHook ) throw new LuaRuntimeException( "render.DrawBeam can only be used inside PostDrawOpaqueRenderables or PostDrawTranslucentRenderables" );
			var start = LuaConvert.ToVector( LuaState.Arg( a, 0 ), "start" );
			var end = LuaConvert.ToVector( LuaState.Arg( a, 1 ), "end" );
			float width = LuaState.ToNumber( LuaState.Arg( a, 2 ), out var w ) ? (float)Math.Clamp( w, 0.05, 64 ) : 1f;
			var color = ColorOf( LuaState.Arg( a, 3 ) );
			Draw( start, end, width, color );
			return null;
		};
		LuaState.Register( render, "DrawBeam", beam );
		LuaState.Register( render, "DrawLine", ( s, a ) => beam( s, new[] { LuaState.Arg( a, 0 ), LuaState.Arg( a, 1 ), 0.3, LuaState.Arg( a, 2 ) } ) );
	}

	static string ModelArg( LuaValue v, string fname )
	{
		if ( v.IsNil || (v.IsString && v.AsString == "") ) return "";
		if ( !v.IsString ) throw new LuaRuntimeException( $"{fname}: model path, package ident or \"\" expected" );
		return LuaAppearance.LoadModel( v.AsString, fname ).Item1;
	}

	static RpPlayer Player( LuaValue[] a, string m )
	{
		var id = LuaPlayers.HandleOf( LuaState.Arg( a, 0 ) ) ?? throw new LuaRuntimeException( $"calling '{m}' on a non-player value" );
		return LuaPlayers.Find( id ) ?? throw new LuaRuntimeException( $"calling '{m}' on a disconnected player" );
	}

	static Color ColorOf( LuaValue v )
	{
		if ( !v.IsTable ) return Color.White;
		var t = v.AsTable;
		float Ch( string k ) => LuaState.ToNumber( t.Get( k ), out var x ) ? (float)Math.Clamp( x / 255.0, 0, 1 ) : 1f;
		return new Color( Ch( "r" ), Ch( "g" ), Ch( "b" ), Ch( "a" ) );
	}

	static void Draw( Vector3 start, Vector3 end, float width, Color color )
	{
		if ( _used >= MaxBeamsPerFrame ) return;
		LineRenderer line;
		if ( _used < _pool.Count && _pool[_used].IsValid() ) line = _pool[_used];
		else
		{
			var go = new GameObject( true, "lua beam" ) { NetworkMode = NetworkMode.Never };
			line = go.Components.Create<LineRenderer>();
			line.UseVectorPoints = true;
			if ( _used < _pool.Count ) _pool[_used] = line; else _pool.Add( line );
		}
		_used++;
		line.VectorPoints = new List<Vector3> { start, end };
		line.Width = width;
		line.Color = color;
		if ( !line.GameObject.Enabled ) line.GameObject.Enabled = true;
	}

	internal static void BeginFrame() => _used = 0;

	internal static void EndFrame()
	{
		for ( int i = _used; i < _pool.Count; i++ )
			if ( _pool[i].IsValid() && _pool[i].GameObject.Enabled ) _pool[i].GameObject.Enabled = false;
	}

	internal static void Reset()
	{
		foreach ( var l in _pool ) if ( l.IsValid() ) l.GameObject.Destroy();
		_pool.Clear();
		_used = 0;
	}
}

/// <summary>Short-lived local effects (lights) started by <c>util.Effect</c>.</summary>
public sealed class RpEffect : Component
{
	public float Duration { get; set; } = 0.2f;
	public float Radius { get; set; } = 200f;
	public Color Tint { get; set; } = Color.White;
	PointLight _light;
	TimeSince _age;

	public static bool IsKnown( string name ) => name is "Explosion" or "Flash" or "Sparks";

	[Rpc.Broadcast( NetFlags.HostOnly )]
	public static void Broadcast( string name, Vector3 pos, float scale )
	{
		if ( IsKnown( name ) ) Play( name, pos, Math.Clamp( scale, 0.1f, 10f ) );
	}

	public static void Play( string name, Vector3 pos, float scale )
	{
		if ( Game.ActiveScene is null ) return;
		var (dur, radius, color) = name switch
		{
			"Explosion" => (0.45f, 520f, new Color( 1f, 0.55f, 0.2f ) * 6f),
			"Sparks" => (0.08f, 70f, new Color( 1f, 0.85f, 0.5f ) * 3f),
			_ => (0.12f, 180f, new Color( 1f, 0.95f, 0.85f ) * 3f),
		};
		var go = new GameObject( true, "effect " + name ) { NetworkMode = NetworkMode.Never };
		go.WorldPosition = pos;
		var e = go.Components.Create<RpEffect>();
		e.Duration = dur;
		e.Radius = radius * scale;
		e.Tint = color;
	}

	protected override void OnStart()
	{
		_light = Components.Create<PointLight>();
		_light.Shadows = false;
		_light.Radius = Radius;
		_light.LightColor = Tint;
		_age = 0;
	}

	protected override void OnUpdate()
	{
		float k = _age / Duration;
		if ( k >= 1f ) { GameObject.Destroy(); return; }
		if ( _light.IsValid() ) _light.LightColor = Tint * (1f - k);
	}
}