Session service for the framework: HostSettings (name, max players, password, privacy, gamemode, map) with validation, and the static SessionService that validates and loads the world scene, creates the lobby once the world scene is up, publishes packed lobby metadata (gamemode|version|protocol|map) under one key, handles dedicated server auto-hosting from FrameworkConfig plus launch args, and returns to the menu on leave or unexpected disconnect. Also exposes the rp_leave console command.
using System;
using System.Collections.Generic;
using RoleplayFramework.Bootstrap;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
using Sandbox.Network;
namespace RoleplayFramework.Net;
/// <summary>Settings for a locally hosted (listen) server, as chosen in the Create Local Server form.</summary>
public sealed class HostSettings
{
public string Name { get; set; } = "Roleplay Server";
public int MaxPlayers { get; set; } = 32;
public string Password { get; set; } = "";
public LobbyPrivacy Privacy { get; set; } = LobbyPrivacy.Public;
public string Gamemode { get; set; } = "darkrp";
/// <summary>Map id (see <see cref="MapCatalog"/>). Empty = the gamemode's default map.</summary>
public string Map { get; set; } = "";
public static HostSettings FromConfig( FrameworkConfig c ) => new()
{
Name = c.ServerName,
MaxPlayers = c.MaxPlayers,
Gamemode = c.DefaultGamemode,
Map = c.Map,
};
/// <summary>The chosen map, or the gamemode's default when none is chosen.</summary>
public string ResolvedMap
{
get
{
if ( !string.IsNullOrWhiteSpace( Map ) ) return Map.Trim();
return Scripting.GamemodeRegistry.Current.Valid.TryGetValue( Gamemode ?? "", out var gm ) ? gm.DefaultMap : "minimal";
}
}
public List<string> Validate()
{
var errors = new List<string>();
var name = (Name ?? "").Trim();
if ( name.Length < 3 ) errors.Add( "Server name must be at least 3 characters." );
if ( name.Length > 64 ) errors.Add( "Server name must be at most 64 characters." );
if ( MaxPlayers < 1 || MaxPlayers > FrameworkConfig.ProjectMaxPlayers ) errors.Add( $"Max players must be between 1 and {FrameworkConfig.ProjectMaxPlayers}." );
if ( (Password ?? "").Length > 64 ) errors.Add( "Password must be at most 64 characters." );
if ( !Scripting.GamemodeRegistry.Current.Valid.ContainsKey( Gamemode ?? "" ) )
errors.Add( $"Gamemode '{Gamemode}' is not available. Check Diagnostics for rejected gamemodes." );
if ( MapCatalog.Validate( ResolvedMap ) is { } badMap ) errors.Add( badMap );
return errors;
}
}
/// <summary>
/// Session lifecycle: host locally, leave to menu. Hosting is two steps because a lobby must be created
/// from inside the world scene: <see cref="StartLocalHost"/> remembers the settings and loads the world,
/// then the world's PlayerManager calls <see cref="OnWorldReady"/>, which creates the lobby.
/// </summary>
public static class SessionService
{
public const string MenuScene = "scenes/menu.scene";
/// <summary>Map of the running world (set when hosting; on clients from the lobby metadata).</summary>
public static string CurrentMap { get; internal set; }
/// <summary>
/// Lobby metadata for the server browser, packed into ONE key: "gamemode|frameworkVersion|protocol|map".
/// The engine already uses most of the lobby's data slots; in testing only the first two of four separate keys
/// survived, so everything goes in a single value.
/// </summary>
public const string DataKey = "rp";
public static string PackMetadata( string gamemode, string version, int protocol, string map ) =>
string.Join( "|", Clean( gamemode ), Clean( version ), protocol, Clean( map ) );
public static (string Gamemode, string Version, int Protocol, string Map) UnpackMetadata( string packed )
{
var p = (packed ?? "").Split( '|' );
int.TryParse( p.Length > 2 ? p[2] : "0", out var proto );
return (p.Length > 0 && p[0] != "" ? p[0] : "unknown", p.Length > 1 && p[1] != "" ? p[1] : "?", proto, p.Length > 3 && p[3] != "" ? p[3] : "-");
}
static string Clean( string s ) => (s ?? "").Replace( "|", "" ).Trim();
public static HostSettings PendingHost { get; private set; }
/// <summary>Why the last session ended unexpectedly; shown once by the main menu, then cleared.</summary>
public static string LastDisconnectReason { get; set; }
public static HostSettings ActiveHost { get; private set; }
/// <summary>Validates settings and starts loading the world. Returns false with a user-facing error otherwise.</summary>
public static bool StartLocalHost( HostSettings settings, out string error )
{
error = null;
if ( FrameworkHost.State != StartupState.Ready )
{
error = "The framework is not ready. Check Diagnostics.";
return false;
}
if ( Networking.IsActive )
{
error = "Already in a multiplayer session.";
return false;
}
var errors = settings.Validate();
if ( errors.Count > 0 )
{
error = string.Join( " ", errors );
return false;
}
settings.Name = settings.Name.Trim();
settings.Map = settings.ResolvedMap;
var scene = MapCatalog.SceneFor( settings.Map );
var options = new SceneLoadOptions { ShowLoadingScreen = true };
if ( !options.SetScene( scene ) )
{
error = $"World scene '{scene}' could not be found.";
RpLog.Error( "session", error );
return false;
}
PendingHost = settings;
RpLog.Info( "session", $"Starting {(Application.IsDedicatedServer ? "dedicated" : "local")} server '{settings.Name}' (gamemode {settings.Gamemode}, map {settings.Map}, max {settings.MaxPlayers}, {settings.Privacy}, password: {(string.IsNullOrEmpty( settings.Password ) ? "no" : "yes")})" );
Game.ActiveScene.Load( options );
return true;
}
/// <summary>Called by the world's PlayerManager once the scene is running. Creates the lobby if a host was requested.</summary>
internal static void OnWorldReady()
{
var s = PendingHost;
if ( s is null || Networking.IsActive ) return;
PendingHost = null;
var config = new LobbyConfig
{
Name = s.Name,
MaxPlayers = s.MaxPlayers,
Password = string.IsNullOrEmpty( s.Password ) ? null : s.Password,
Privacy = s.Privacy,
DestroyWhenHostLeaves = true,
};
Networking.CreateLobby( config );
ActiveHost = s;
RpLog.Info( "session", $"Lobby requested: '{s.Name}'" );
}
/// <summary>Publishes framework metadata on the lobby. Called once the host's own connection is active.</summary>
internal static void PublishLobbyMetadata()
{
if ( !Networking.IsHost ) return;
// Steam limits a dedicated server's tags (all lobby data together) to 128 characters. The engine already
// publishes the map of a MapInstance itself (LobbyInformation.Map, which the browser reads first), so only
// built-in scene maps go into our value.
var map = string.IsNullOrEmpty( Networking.MapName ) ? (CurrentMap ?? Game.ActiveScene?.Name) : "";
var packed = PackMetadata( Scripting.LuaRuntime.ActiveGamemode ?? ActiveHost?.Gamemode ?? FrameworkHost.Config.DefaultGamemode,
FrameworkInfo.Version, FrameworkInfo.ProtocolVersion, map );
Networking.SetData( DataKey, packed );
RpLog.Info( "session", $"Published lobby metadata: {packed}" );
}
/// <summary>Disconnects (if networked) and returns to the main menu.</summary>
public static void LeaveToMenu()
{
RpLog.Info( "session", Networking.IsActive ? "Leaving session" : "Returning to menu" );
Core.LoadingProgress.End();
PendingHost = null;
ActiveHost = null;
Players.PlayerSessions.Clear();
if ( Networking.IsActive ) Networking.Disconnect();
var options = new SceneLoadOptions { ShowLoadingScreen = true };
if ( options.SetScene( MenuScene ) ) Game.ActiveScene.Load( options );
else RpLog.Error( "session", $"Menu scene '{MenuScene}' could not be found" );
}
/// <summary>
/// Dedicated server entry point: the engine boots into the startup scene with nobody to press "Create Local
/// Server", so the server hosts itself using the framework config (and +hostname if given).
/// </summary>
internal static void StartDedicated()
{
if ( Networking.IsActive || PendingHost is not null ) return;
var c = FrameworkHost.Config;
var settings = HostSettings.FromConfig( c );
if ( !string.IsNullOrWhiteSpace( Networking.ServerName ) ) settings.Name = Networking.ServerName.Trim();
settings.Password = c.ServerPassword ?? "";
settings.Privacy = LobbyPrivacy.Public;
// "+game <game> <map>" on the command line wins over the config.
if ( !string.IsNullOrWhiteSpace( LaunchArguments.Map ) )
{
if ( MapCatalog.Validate( LaunchArguments.Map ) is null ) settings.Map = LaunchArguments.Map;
else RpLog.Warn( "session", $"Ignoring launch map '{LaunchArguments.Map}': {MapCatalog.Validate( LaunchArguments.Map )}" );
}
if ( !StartLocalHost( settings, out var error ) )
RpLog.Error( "session", $"Dedicated server could not start: {error}" );
}
/// <summary>Used when the connection drops on its own (host left, kicked, timed out).</summary>
internal static void OnConnectionLost( string reason )
{
LastDisconnectReason = reason;
RpLog.Warn( "session", $"Disconnected: {reason}" );
LeaveToMenu();
}
[ConCmd( "rp_leave", Help = "Leave the current session and return to the main menu" )]
public static void LeaveCommand() => LeaveToMenu();
}