Framework/Scripting/LuaRuntime.cs

Manages the framework's Lua realms. Builds a server realm and a client realm from a Lua source snapshot plus addons, publishes a content manifest the server sends to clients, runs Initialize/Shutdown/Think hooks, and handles reload, restore and leave-to-menu commands.

File AccessFile Access
using System;
using System.Linq;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Lua;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Owns the session's Lua realms. The server realm runs on the host (and offline); the client realm runs
/// wherever there is a local player. A listen host runs both. Realms live for one world session.
/// </summary>
public static class LuaRuntime
{
	public static LuaRealm Server { get; private set; }
	public static LuaRealm Client { get; private set; }

	/// <summary>Serialized content manifest the server sends to joining clients.</summary>
	internal static string ManifestJson { get; private set; }
	internal static System.Collections.Generic.List<ContentFile> ManifestFiles { get; private set; }
	internal static System.Collections.Generic.Dictionary<string, string> ManifestTexts { get; private set; }
	public static int ManifestFileCount => ManifestFiles?.Count ?? 0;

	public static string ActiveGamemode => Server?.Gamemode?.Id ?? Client?.Gamemode?.Id;
	public static string ActiveGamemodeVersion => Server?.Gamemode?.Version ?? Client?.Gamemode?.Version;

	/// <summary>
	/// Starts (or replaces) the server realm. The new scripts are loaded <i>before</i> the running realm is stopped,
	/// so a reload with a broken file leaves the previous scripts running.
	/// </summary>
	public static bool StartServer( string gamemodeId, out string error )
	{
		// A fresh snapshot of exactly the files this world runs (data-folder copies override built-in gamemodes).
		var fs = LuaSource.Snapshot();
		var registry = GamemodeRegistry.Discover( fs );

		var addons = ResolveAddons( fs, registry, gamemodeId, Bootstrap.FrameworkHost.Config.DisabledAddons );

		if ( Server is null ) LuaStorage.Begin( gamemodeId );
		var realm = new LuaRealm( LuaRealmKind.Server, fs );
		if ( !Load( realm, registry, gamemodeId, addons, out error ) ) return false;

		System.Collections.Generic.List<ContentFile> files;
		var texts = new System.Collections.Generic.Dictionary<string, string>();
		try
		{
			// Snapshot the texts now, so what clients download always matches the hashes even if files change later.
			files = LuaContent.Build( fs, registry, gamemodeId, texts, addons.LoadOrder );
		}
		catch ( Exception e )
		{
			error = $"could not build the content manifest: {e.Message}";
			RpLog.Error( "lua", error );
			return false;
		}

		// The new scripts loaded: retire the old realm (Shutdown hook, its entities) and switch over.
		StopRealm( LuaRealmKind.Server );
		LuaStorage.Begin( gamemodeId );
		ManifestFiles = files;
		ManifestTexts = texts;
		ManifestJson = Json.Serialize( files );
		Server = realm;
		AddonRegistry.Current = addons;
		addons.LogSummary();
		RpLog.Info( "lua", $"Server realm ready: {realm.Gamemode.Id} {realm.Gamemode.Version}, {realm.LoadedFiles.Count} files, {realm.Addons.Count( a => a.Loaded )} addon(s), manifest {ManifestFileCount} files" );
		realm.RunHook( "AddonsLoaded" );
		realm.RunHook( "Initialize" );
		return true;
	}

	/// <summary>Client realm on the authority itself (offline / listen host): the same snapshot the server runs.</summary>
	public static bool StartClient( string gamemodeId, out string error ) => StartClient( gamemodeId, LuaSource.Current ?? LuaSource.Snapshot(), out error );

	/// <summary>
	/// Client realm from a specific filesystem. <paramref name="fromServer"/>: a remote client's verified download, which
	/// holds exactly the server's active addons, so this machine's own DisabledAddons don't apply.
	/// </summary>
	public static bool StartClient( string gamemodeId, BaseFileSystem fs, out string error, bool fromServer = false )
	{
		StopRealm( LuaRealmKind.Client );
		var registry = GamemodeRegistry.Discover( fs, makeCurrent: false );
		var addons = ResolveAddons( fs, registry, gamemodeId, fromServer ? null : Bootstrap.FrameworkHost.Config.DisabledAddons );

		var realm = new LuaRealm( LuaRealmKind.Client, fs );
		if ( !Load( realm, registry, gamemodeId, addons, out error ) ) return false;

		Client = realm;
		RpLog.Info( "lua", $"Client realm ready: {realm.Gamemode.Id} {realm.Gamemode.Version}, {realm.LoadedFiles.Count} files, {realm.Addons.Count( a => a.Loaded )} addon(s)" );
		realm.RunHook( "AddonsLoaded" );
		realm.RunHook( "Initialize" );
		RunDevAutorun( realm );
		return true;
	}

	/// <summary>game.GetMap() → current map id ("minimal", "thieves.rpdowntown3t", ...).</summary>
	static void RegisterGameLibrary( LuaRealm realm )
	{
		var g = realm.State.GetOrCreateLibrary( "game" );
		LuaState.Register( g, "GetMap", ( L, a ) => new LuaValue[] { CurrentMapId() } );
		LuaState.Register( g, "IsDedicated", ( L, a ) => new LuaValue[] { Application.IsDedicatedServer } );
		// True when running inside the s&box editor (play mode), where e.g. F1-F4 never reach the game.
		LuaState.Register( g, "IsEditor", ( L, a ) => new LuaValue[] { Game.IsEditor } );
		// Session info for menus: server name ("" offline), networked at all, and whether this machine is the authority.
		LuaState.Register( g, "GetServerName", ( L, a ) => new LuaValue[] { Networking.IsActive ? (Net.SessionService.ActiveHost?.Name ?? Networking.ServerName ?? "") : "" } );
		LuaState.Register( g, "IsMultiplayer", ( L, a ) => new LuaValue[] { Networking.IsActive } );
		LuaState.Register( g, "IsHost", ( L, a ) => new LuaValue[] { !Networking.IsActive || Networking.IsHost } );

		if ( realm.Kind != LuaRealmKind.Client ) return;

		// game.LeaveToMenu(): disconnect (a host stops its server) and return to the main menu. Runs at the start of the
		// next frame, so the world isn't torn down while the calling Lua (e.g. a button handler) is still running.
		LuaState.Register( g, "LeaveToMenu", ( L, a ) => { _leaveRequested = true; return null; } );

		// gui: s&box's own overlays, under Garry's Mod names where they exist.
		var gui = realm.State.GetOrCreateLibrary( "gui" );
		LuaState.Register( gui, "ActivateGameUI", ( L, a ) => { Game.Overlay.ShowPauseMenu(); return null; } );
		LuaState.Register( gui, "HideGameUI", ( L, a ) => { Game.Overlay.Close(); return null; } );
		LuaState.Register( gui, "OpenSettings", ( L, a ) =>
		{
			var page = LuaState.Arg( a, 0 );
			var name = page.IsString ? page.AsString : null;
			if ( name is not null && name is not ("display" or "graphics" or "audio" or "controls" or "keybinds" or "game" or "storage" or "developer" or "about" or "video" or "input") )
				throw LuaState.ArgError( 0, "gui.OpenSettings", "expected display, graphics, audio, controls, keybinds, game, storage, developer or about" );
			Game.Overlay.ShowSettingsModal( name );
			return null;
		} );
		LuaState.Register( gui, "OpenBinds", ( L, a ) => { Game.Overlay.ShowBinds(); return null; } );
		LuaState.Register( gui, "OpenPlayerList", ( L, a ) => { Game.Overlay.ShowPlayerList(); return null; } );
	}

	static bool _leaveRequested;

	public static string CurrentMapId()
	{
		if ( !string.IsNullOrEmpty( Net.SessionService.CurrentMap ) ) return Net.SessionService.CurrentMap;
		var map = Players.WorldMap.Find( Game.ActiveScene );
		if ( map is not null && !string.IsNullOrEmpty( map.MapName ) ) return map.MapName;
		return Game.ActiveScene?.Name ?? "";
	}

	/// <summary>
	/// Reloads the running gamemode from its source (the data folder for server owners). The server realm is
	/// swapped only if the new scripts load; then players get PlayerInitialSpawn/PlayerSpawn again and remote
	/// clients re-download and restart their client scripts.
	/// </summary>
	public static string Reload()
	{
		var old = Server;
		if ( old is null ) return "No gamemode is running. Start or host a world first.";
		var gm = old.Gamemode.Id;

		if ( !StartServer( gm, out var error ) )
			return $"Reload failed - the previous scripts keep running. {error}";

		// The host's own client realm runs the same snapshot.
		if ( !Application.IsDedicatedServer && !StartClient( gm, out var cerr ) )
			RpLog.Error( "lua", $"Client scripts failed to reload: {cerr}" );

		Players.PlayerManager.Current?.OnLuaReloaded();

		int clients = 0;
		foreach ( var s in Players.PlayerSessions.All )
		{
			if ( s.State != Players.SessionState.Ready ) continue;
			var c = Connection.Find( s.ConnectionId );
			if ( c is null || c == Connection.Local ) continue;
			s.State = Players.SessionState.AwaitingContent;
			s.ConnectedAt = RealTime.NowDouble; // restart the content timeout
			LuaContent.SendManifestTo( c );
			clients++;
		}

		return $"Reloaded '{gm}' ({Server.LoadedFiles.Count} files, {Server.Addons.Count( a => a.Loaded )} addon(s) from {(LuaSource.Origins.TryGetValue( gm, out var o ) ? o : "?")}); {clients} remote client(s) are reloading theirs.";
	}

	[ConCmd( "rp_lua_reload", Help = "Reload the running gamemode's Lua (server/host only). Broken scripts are rejected and the old ones keep running." )]
	public static void ReloadCommand()
	{
		if ( !Core.RealmInfo.IsAuthority ) { RpLog.Warn( "lua", "Only the server can reload Lua." ); return; }
		RpLog.Info( "lua", Reload() );
	}

	[ConCmd( "rp_lua_restore", Help = "Replace your data-folder copy of a gamemode with the game's version (your copy is backed up first): rp_lua_restore <id>" )]
	public static void RestoreCommand( string id )
	{
		if ( !Core.RealmInfo.IsAuthority ) { RpLog.Warn( "lua", "Only the server can restore gamemodes." ); return; }
		RpLog.Info( "lua", LuaSource.Restore( id ) );
	}

	public const string DevAutorunPath = "roleplay/dev/autorun_client.lua";

	/// <summary>
	/// Development aid for multiplayer testing: when DevMode is on, a *remote client* runs
	/// data/roleplay/dev/autorun_client.lua (its own local file) after its scripts load. Off by default; the server
	/// never sends or trusts this file, and it can only do what any client Lua can do.
	/// </summary>
	static void RunDevAutorun( LuaRealm realm )
	{
		if ( !Bootstrap.FrameworkHost.Config.DevMode || Core.RealmInfo.Role != Core.ProcessRole.Client ) return;
		var fs = FileSystem.Data;
		if ( !fs.FileExists( DevAutorunPath ) ) return;

		RpLog.Warn( "lua", $"DevMode: running data/{DevAutorunPath} in the client realm" );
		try
		{
			var fn = realm.State.Load( fs.ReadAllText( DevAutorunPath ), "dev/autorun_client.lua" );
			realm.Call( LuaValue.FromFunction( fn ) );
		}
		catch ( LuaException e )
		{
			realm.Report( $"dev autorun failed: {e.Message}", null );
		}
	}

	static AddonRegistry ResolveAddons( BaseFileSystem fs, GamemodeRegistry registry, string gamemodeId, System.Collections.Generic.IEnumerable<string> disabled ) =>
		AddonRegistry.Resolve( fs, registry.LoadOrder( gamemodeId )?.ConvertAll( m => m.Id ), disabled );

	static bool Load( LuaRealm realm, GamemodeRegistry registry, string gamemodeId, AddonRegistry addons, out string error )
	{
		error = null;
		LuaPlayers.Register( realm );
		LuaEntities.Register( realm );
		LuaNet.Register( realm );
		GlobalNetVars.Register( realm );
		LuaStorage.Register( realm );
		LuaLog.Register( realm );
		LuaUi.Register( realm );
		LuaContentLib.Register( realm );
		RegisterGameLibrary( realm );
		if ( realm.Kind == LuaRealmKind.Client ) LuaHudModel.Register( realm );
		if ( realm.Kind == LuaRealmKind.Client ) LuaInput.Register( realm );
		LuaDraw.Register( realm );
		LuaClothing.RegisterLibrary( realm );
		LuaCookie.Register( realm );
		LuaKeybind.Register( realm );
		LuaJson.Register( realm );
		LuaConCommand.Register( realm );
		LuaDataFiles.Register( realm );
		LuaAddons.Register( realm );
		LuaPhysics.Register( realm );
		LuaRender.Register( realm );
		LuaView.Register( realm );

		try
		{
			realm.LoadFrameworkFiles();
			realm.LoadGamemode( registry, gamemodeId );
			// Addons after the gamemode: they can override GM functions and add hooks. A broken addon isn't fatal.
			realm.LoadAddons( addons?.LoadOrder ?? new System.Collections.Generic.List<AddonManifest>() );
			return true;
		}
		catch ( LuaRuntimeException e )
		{
			error = e.Message;
			realm.Report( $"Gamemode '{gamemodeId}' failed to load: {e.Message}", e.LuaTraceback );
		}
		catch ( LuaException e )
		{
			error = e.Message;
			realm.Report( $"Gamemode '{gamemodeId}' failed to load: {e.Message}", null );
		}
		return false;
	}

	public static void Tick()
	{
		if ( _leaveRequested )
		{
			_leaveRequested = false;
			Net.SessionService.LeaveToMenu();
			return;
		}

		var now = Time.Now;
		Server?.Tick( now );
		Client?.Tick( now );
		Server?.RunHook( "Think" );
		Client?.RunHook( "Think" );
		if ( Client is not null )
		{
			LuaKeybind.Tick( Client );
			LuaDraw.Frame( Client );
		}
		LuaCookie.Tick();
		LuaDevReload.Tick();
	}

	static void StopRealm( LuaRealmKind kind )
	{
		var realm = kind == LuaRealmKind.Server ? Server : Client;
		if ( realm is null ) return;
		realm.RunHook( "Shutdown" );

		// Entities the realm created belong to it: remove them, so a reload doesn't duplicate doors, props, ...
		int removed = 0;
		foreach ( var go in realm.CreatedObjects )
			if ( go.IsValid() ) { go.Destroy(); removed++; }
		if ( removed > 0 ) RpLog.Info( "lua", $"{realm.Name} realm removed {removed} entities it had created" );
		if ( kind == LuaRealmKind.Server ) { LuaPhysics.Clear(); Server = null; ManifestJson = null; ManifestFiles = null; ManifestTexts = null; }
		else { Client = null; LuaRender.Reset(); LuaView.Reset(); LuaHudModel.Clear(); LuaUi.Reset(); LuaKeybind.Reset(); LuaCookie.Flush(); }
		RpLog.Info( "lua", $"{realm.Name} realm stopped" );
	}

	public static void Shutdown()
	{
		StopRealm( LuaRealmKind.Client );
		StopRealm( LuaRealmKind.Server );
	}
}