Framework/Scripting/Api/LuaAppearance.cs

Lua scripting bindings for entity and player appearance. Resolves and validates model/material paths or package idents, then exposes SetModel, SetMaterial, SetSkin, bodygroup, NoDraw, bounds, scale and player color methods on the Lua method tables, plus util.IsValidModel, util.IsValidMaterial, Model() and Material() globals.

using System;
using System.Text.RegularExpressions;
using RoleplayFramework.Core;
using RoleplayFramework.Lua;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Models, materials and textures for Lua. Asset references are engine paths ("models/dev/box.vmdl",
/// "materials/dev/dev_measuregeneric01.vmat") or sbox.game package idents ("fish.barrel" = that package's main asset;
/// it must be mounted, see the content library).
///
/// Entity and Player methods (setters: server, or the client that owns a ClientsideModel):
///   SetModel(model) GetModel()  SetMaterial(mat|"") GetMaterial()  SetSkin(n) GetSkin() SkinCount()
///   SetBodygroup(name|index, value) GetBodygroup(name|index) GetBodygroups()  SetNoDraw(b) GetNoDraw()
///   GetModelBounds() → mins, maxs   SetModelScale(s) GetModelScale()   Player only: SetColor(Color) GetColor()
/// Globals: util.IsValidModel(model)  util.IsValidMaterial(mat)  Model(path) / Material(path) (validated path strings)
/// </summary>
public static class LuaAppearance
{
	static readonly Regex PathPattern = new( @"^[a-z0-9_\-./ ]{1,260}$" );

	/// <summary>Package ident → its main asset; otherwise the path itself, checked for shape and extension.</summary>
	public static string ResolvePath( string pathOrIdent, string extension, string fname )
	{
		var s = (pathOrIdent ?? "").Trim();
		bool looksLikeFile = s.EndsWith( ".vmdl", StringComparison.OrdinalIgnoreCase ) || s.EndsWith( ".vmat", StringComparison.OrdinalIgnoreCase )
			|| s.EndsWith( "_c", StringComparison.OrdinalIgnoreCase );
		if ( !looksLikeFile && !s.Contains( '/' ) && ContentPackages.IsValidIdent( ContentPackages.Normalize( s ) ) )
		{
			var id = ContentPackages.Normalize( s );
			var asset = ContentPackages.PrimaryAssetOf( id )
				?? throw new LuaRuntimeException( $"{fname}: package '{id}' is not mounted (add it with content.AddPackage, \"packages\" in gamemode.json or \"Packages\" in framework.json)" );
			if ( !asset.EndsWith( extension, StringComparison.OrdinalIgnoreCase ) )
				throw new LuaRuntimeException( $"{fname}: package '{id}' contains '{asset}', not a {extension}" );
			return asset;
		}

		s = s.Replace( '\\', '/' ).ToLowerInvariant();
		if ( !PathPattern.IsMatch( s ) || s.Contains( ".." ) || s.StartsWith( "/" ) )
			throw new LuaRuntimeException( $"{fname}: '{pathOrIdent}' is not a valid asset path" );
		if ( s.EndsWith( extension + "_c" ) ) s = s.Substring( 0, s.Length - 2 );
		if ( !s.EndsWith( extension ) ) throw new LuaRuntimeException( $"{fname}: '{pathOrIdent}' must be a {extension} file or a package ident" );
		return s;
	}

	public static (string Path, Model Model) LoadModel( string pathOrIdent, string fname )
	{
		var path = ResolvePath( pathOrIdent, ".vmdl", fname );
		var model = Model.Load( path );
		if ( model is null || model.IsError ) throw new LuaRuntimeException( $"{fname}: model not found: {path}" );
		return (path, model);
	}

	public static string LoadMaterialPath( string pathOrIdent, string fname )
	{
		var path = ResolvePath( pathOrIdent, ".vmat", fname );
		// Material.Load returns an error material for missing files, so check that the compiled file exists.
		var fs = FileSystem.Mounted;
		if ( !(fs.FileExists( path + "_c" ) || fs.FileExists( path )) || Material.Load( path ) is null ) throw new LuaRuntimeException( $"{fname}: material not found: {path}" );
		return path;
	}

	static bool TryValid( Func<object> f )
	{
		try { return f() is not null; }
		catch ( LuaRuntimeException ) { return false; }
	}

	public static void RegisterGlobals( LuaRealm realm )
	{
		var L = realm.State;
		var util = L.GetOrCreateLibrary( "util" );
		LuaState.Register( util, "IsValidModel", ( s, a ) =>
			new LuaValue[] { TryValid( () => LoadModel( LuaState.CheckString( a, 0, "util.IsValidModel" ), "util.IsValidModel" ).Model ) } );
		LuaState.Register( util, "IsValidMaterial", ( s, a ) =>
			new LuaValue[] { TryValid( () => LoadMaterialPath( LuaState.CheckString( a, 0, "util.IsValidMaterial" ), "util.IsValidMaterial" ) ) } );

		// GMod's Model()/Material() return their argument; here they also validate and resolve package idents.
		L.Register( "Model", ( s, a ) => new LuaValue[] { LoadModel( LuaState.CheckString( a, 0, "Model" ), "Model" ).Path } );
		L.Register( "Material", ( s, a ) => new LuaValue[] { LoadMaterialPath( LuaState.CheckString( a, 0, "Material" ), "Material" ) } );
	}

	/// <summary>Adds the appearance methods to the Entity or Player method table.</summary>
	/// <param name="resolve">Lua args → the object's GameObject (throws for invalid handles).</param>
	/// <param name="canWrite">Whether this realm may change that object.</param>
	public static void AddMethods( LuaTable methods, Func<LuaValue[], string, GameObject> resolve, Func<GameObject, bool> canWrite, bool isPlayer )
	{
		GameObject W( LuaValue[] a, string name )
		{
			var go = resolve( a, name );
			if ( !canWrite( go ) ) throw new LuaRuntimeException( $"{name} can only be called on the server (or on your own ClientsideModel)" );
			return go;
		}

		RpAppearance Look( GameObject go ) => RpAppearance.Ensure( go );
		ModelRenderer R( GameObject go ) => go.Components.Get<RpAppearance>()?.MainRenderer
			?? go.Components.Get<ModelRenderer>( FindMode.EverythingInSelfAndDescendants );

		LuaState.Register( methods, "SetModel", ( s, a ) =>
		{
			var go = W( a, "SetModel" );
			var (path, model) = LoadModel( LuaState.CheckString( a, 1, "SetModel" ), "SetModel" );
			Look( go ).ModelPath = path;

			// Entities: the collider follows the new model (players keep their capsule).
			if ( !isPlayer )
			{
				var holder = R( go )?.GameObject ?? go;
				var box = holder.Components.Get<BoxCollider>();
				if ( box is not null ) { box.Center = model.Bounds.Center; box.Scale = model.Bounds.Size; }
			}
			return null;
		} );
		LuaState.Register( methods, "GetModel", ( s, a ) =>
		{
			var go = resolve( a, "GetModel" );
			var look = go.Components.Get<RpAppearance>();
			if ( !string.IsNullOrEmpty( look?.ModelPath ) ) return new LuaValue[] { look.ModelPath };
			return new LuaValue[] { R( go )?.Model?.ResourcePath ?? "" };
		} );

		LuaState.Register( methods, "SetMaterial", ( s, a ) =>
		{
			var go = W( a, "SetMaterial" );
			var arg = LuaState.Arg( a, 1 );
			Look( go ).MaterialPath = arg.IsNil || (arg.IsString && arg.AsString == "") ? "" : LoadMaterialPath( LuaState.CheckString( a, 1, "SetMaterial" ), "SetMaterial" );
			return null;
		} );
		LuaState.Register( methods, "GetMaterial", ( s, a ) =>
			new LuaValue[] { resolve( a, "GetMaterial" ).Components.Get<RpAppearance>()?.MaterialPath ?? "" } );

		LuaState.Register( methods, "SetSkin", ( s, a ) =>
		{
			var go = W( a, "SetSkin" );
			Look( go ).Skin = Math.Clamp( (int)LuaState.CheckNumber( a, 1, "SetSkin" ), 0, 255 );
			return null;
		} );
		LuaState.Register( methods, "GetSkin", ( s, a ) =>
			new LuaValue[] { resolve( a, "GetSkin" ).Components.Get<RpAppearance>()?.Skin ?? 0 } );
		LuaState.Register( methods, "SkinCount", ( s, a ) =>
			new LuaValue[] { Math.Max( 1, R( resolve( a, "SkinCount" ) )?.Model?.MaterialGroupCount ?? 1 ) } );

		string GroupName( GameObject go, LuaValue v, string fname )
		{
			if ( v.IsString ) return v.AsString;
			if ( !v.IsNumber ) throw new LuaRuntimeException( $"{fname}: bodygroup name or index expected" );
			int i = 0, want = (int)v.Number;
			foreach ( var part in R( go )?.Model?.Parts?.All ?? Array.Empty<Model.BodyPart>() )
				if ( i++ == want ) return part.Name;
			throw new LuaRuntimeException( $"{fname}: model has no bodygroup {want}" );
		}

		LuaState.Register( methods, "SetBodygroup", ( s, a ) =>
		{
			var go = W( a, "SetBodygroup" );
			var name = GroupName( go, LuaState.Arg( a, 1 ), "SetBodygroup" );
			if ( name.Length > 64 || name.Contains( ';' ) || name.Contains( '=' ) ) throw new LuaRuntimeException( "SetBodygroup: invalid bodygroup name" );
			Look( go ).SetBodyGroup( name, Math.Clamp( (int)LuaState.CheckNumber( a, 2, "SetBodygroup" ), 0, 63 ) );
			return null;
		} );
		LuaState.Register( methods, "GetBodygroup", ( s, a ) =>
		{
			var go = resolve( a, "GetBodygroup" );
			var name = GroupName( go, LuaState.Arg( a, 1 ), "GetBodygroup" );
			var look = go.Components.Get<RpAppearance>();
			return new LuaValue[] { look?.GetBodyGroup( name ) ?? R( go )?.GetBodyGroup( name ) ?? 0 };
		} );
		LuaState.Register( methods, "GetBodygroups", ( s, a ) =>
		{
			// { { id = 0, name = "head", num = 3 }, ... } like GMod (num = number of choices)
			var t = new LuaTable();
			int i = 0;
			foreach ( var part in R( resolve( a, "GetBodygroups" ) )?.Model?.Parts?.All ?? Array.Empty<Model.BodyPart>() )
			{
				var e = new LuaTable();
				e.Set( "id", i++ );
				e.Set( "name", part.Name );
				e.Set( "num", part.Choices?.Count ?? 0 );
				t.Append( e );
			}
			return new LuaValue[] { t };
		} );

		LuaState.Register( methods, "SetNoDraw", ( s, a ) =>
		{
			Look( W( a, "SetNoDraw" ) ).NoDraw = LuaState.Arg( a, 1 ).IsTruthy;
			return null;
		} );
		LuaState.Register( methods, "GetNoDraw", ( s, a ) =>
			new LuaValue[] { resolve( a, "GetNoDraw" ).Components.Get<RpAppearance>()?.NoDraw ?? false } );

		LuaState.Register( methods, "GetModelBounds", ( s, a ) =>
		{
			var b = R( resolve( a, "GetModelBounds" ) )?.Model?.Bounds ?? new BBox( Vector3.Zero, Vector3.Zero );
			return new[] { LuaConvert.FromVector( s, b.Mins ), LuaConvert.FromVector( s, b.Maxs ) };
		} );

		if ( !isPlayer )
		{
			LuaState.Register( methods, "SetModelScale", ( s, a ) =>
			{
				var go = W( a, "SetModelScale" );
				go.WorldScale = (float)Math.Clamp( LuaState.CheckNumber( a, 1, "SetModelScale" ), 0.05, 20 );
				return null;
			} );
			LuaState.Register( methods, "GetModelScale", ( s, a ) => new LuaValue[] { resolve( a, "GetModelScale" ).WorldScale.x } );
		}
		else
		{
			LuaState.Register( methods, "SetColor", ( s, a ) =>
			{
				var go = W( a, "SetColor" );
				var c = LuaState.Arg( a, 1 );
				if ( !c.IsTable ) throw new LuaRuntimeException( "SetColor expects a Color" );
				var t = c.AsTable;
				float Ch( string k ) => LuaState.ToNumber( t.Get( k ), out var d ) ? (float)Math.Clamp( d / 255.0, 0, 1 ) : 1f;
				Look( go ).Tint = new Color( Ch( "r" ), Ch( "g" ), Ch( "b" ), Ch( "a" ) );
				return null;
			} );
		}

		LuaState.Register( methods, "GetColor", ( s, a ) =>
		{
			var go = resolve( a, "GetColor" );
			var c = go.Components.Get<LuaEntity>()?.Tint ?? go.Components.Get<RpAppearance>()?.Tint ?? Color.White;
			var ctor = s.Globals.Get( "Color" );
			return ctor.IsFunction
				? new[] { s.Call( ctor, Math.Round( c.r * 255 ), Math.Round( c.g * 255 ), Math.Round( c.b * 255 ), Math.Round( c.a * 255 ) )[0] }
				: new LuaValue[] { LuaValue.Nil };
		} );
	}
}