The per-world player manager for the RoleplayFramework. Implements Component.INetworkListener to track connections, locks down client spawn/destroy rights, spawns one networked RpPlayer body per ready session, moves players to spawn points (farthest from other players) and destroys bodies on disconnect. It also drives the world loading sequence (content packages, cloud map, gamemode Lua realms, lobby) and runs the PlayerInitialSpawn/PlayerSpawn hooks, plus an offline local body for editor play.
using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Net;
using RoleplayFramework.Scripting;
namespace RoleplayFramework.Players;
/// <summary>
/// Lives in every world scene. On the host it owns the player lifecycle: it tracks connections, waits for
/// each client's handshake, spawns one networked body per ready connection at a safe spawn point, and removes
/// it on disconnect. Offline (no networking) it spawns a local body so the world can be tested in the editor.
/// </summary>
public sealed class PlayerManager : Component, Component.INetworkListener
{
/// <summary>Prefab for a player's body. Must contain an <see cref="RpPlayer"/> component.</summary>
[Property] public GameObject PlayerPrefab { get; set; }
public static PlayerManager Current { get; private set; }
readonly Dictionary<Guid, GameObject> _bodies = new();
GameObject _offlineBody;
bool _offlineInitialSpawnDone;
TimeSince _sinceTimeoutCheck;
bool _wasClient;
bool _metadataPublished;
protected override void OnAwake()
{
Current = this;
}
protected override void OnDestroy()
{
if ( Current == this ) Current = null;
LuaRuntime.Shutdown();
LuaStorage.Flush();
Rp.Audit.Flush();
if ( Networking.IsHost ) PlayerSessions.Clear();
}
protected override void OnStart()
{
if ( PlayerPrefab is null )
RpLog.Error( "players", "PlayerManager has no PlayerPrefab assigned; players cannot spawn" );
bool hosting = SessionService.PendingHost is not null;
// Remote clients load their realm later, after verifying the server's content manifest.
if ( !hosting && Networking.IsActive )
{
if ( !Application.IsDedicatedServer )
{
Core.LoadingProgress.Begin( string.IsNullOrWhiteSpace( Networking.ServerName ) ? "Joining server" : Networking.ServerName.Trim(), "" );
Core.LoadingProgress.Phase( "Connecting to the server", 0f, 0.05f );
}
return;
}
_ = StartAuthorityAsync( hosting );
}
/// <summary>
/// The authority's world start, in order: map (cloud maps can take a while to download), gamemode (server realm,
/// plus the client realm when there is a local player), then the lobby or the offline body. Nobody can join a
/// half-loaded world, because the lobby is created last.
/// </summary>
async System.Threading.Tasks.Task StartAuthorityAsync( bool hosting )
{
var gamemode = SessionService.PendingHost?.Gamemode ?? Bootstrap.FrameworkHost.Config.DefaultGamemode;
var map = hosting ? SessionService.PendingHost.Map : OfflineMap( gamemode );
SessionService.CurrentMap = map;
var loading = !Application.IsDedicatedServer;
if ( loading )
{
Core.LoadingProgress.Begin( hosting ? SessionService.PendingHost.Name : "Offline", $"{gamemode} · {map}" );
Core.LoadingProgress.Phase( "Finding content", 0f, 0.05f );
}
// Cloud content the server and gamemode require: mount before anything that might use it.
// Packages + collections (URLs / JSON files) from framework.json and the gamemode chain.
var luaFs = LuaSource.Snapshot();
var registry = GamemodeRegistry.Discover( luaFs );
var addons = AddonRegistry.Resolve( luaFs, registry.LoadOrder( gamemode )?.Select( m => m.Id ).ToList(), Bootstrap.FrameworkHost.Config.DisabledAddons );
var packages = await Core.ContentPackages.ResolveAsync( registry, gamemode, luaFs, addons.LoadOrder );
if ( !this.IsValid() ) return;
Core.LoadingProgress.Phase( "Mounting content", 0.05f, 0.6f, $"{packages.Count} package(s)" );
await Core.ContentPackages.MountRequired( packages, ( i, n, id ) =>
{
// A world that was left while loading must not move the next one's bar.
if ( this.IsValid() ) Core.LoadingProgress.Step( (float)i / Math.Max( 1, n ), $"{Core.ContentPackages.TitleOrIdent( id )} ({i + 1}/{n})" );
} );
if ( !this.IsValid() ) return;
if ( Core.MapCatalog.IsCloud( map ) )
{
Core.LoadingProgress.Phase( "Loading map", 0.6f, 0.75f, $"{map} - the first time this downloads the map" );
string mapError;
try { mapError = await WorldMap.LoadAsync( Scene, map ); }
catch ( Exception e ) { mapError = e.Message; }
if ( !this.IsValid() ) return; // world was left while loading
if ( mapError is not null )
{
SessionService.OnConnectionLost( $"Map failed to load: {mapError}" );
return;
}
}
// Compiling the gamemode blocks for a moment: draw the screen first.
Core.LoadingProgress.Phase( "Starting the gamemode", 0.75f, 0.86f, gamemode );
await Core.LoadingProgress.Show();
if ( !this.IsValid() ) return;
if ( !LuaRuntime.StartServer( gamemode, out var error ) )
{
SessionService.OnConnectionLost( $"Gamemode '{gamemode}' failed to load: {error}" );
return;
}
// This process also has a local player, so it runs the client realm too (same files, no transfer needed).
// A dedicated server has no local player and no client realm.
Core.LoadingProgress.Phase( "Loading client scripts", 0.86f, 0.95f );
await Core.LoadingProgress.Show();
if ( !this.IsValid() ) return;
if ( !Application.IsDedicatedServer && !LuaRuntime.StartClient( gamemode, out error ) )
{
SessionService.OnConnectionLost( $"Gamemode '{gamemode}' client scripts failed to load: {error}" );
return;
}
// Content the gamemode added from Lua while loading (content.AddPackage / AddCollection): mounted before anyone joins.
if ( Core.ContentPackages.Busy )
{
Core.LoadingProgress.Phase( "Mounting content the gamemode added", 0.95f, 0.99f );
await Core.ContentPackages.WhenIdle( 300 );
if ( !this.IsValid() ) return;
}
Core.LoadingProgress.Phase( hosting ? "Opening the server" : "Spawning", 0.99f, 1f );
Core.LoadingProgress.Step( 1f, "" );
if ( hosting )
{
PlayerSessions.Clear();
SessionService.OnWorldReady();
Core.LoadingProgress.EndAfter( 8 ); // until our body is in the world (RpPlayer)
return;
}
RpLog.Info( "players", "Offline: spawning a local player" );
_offlineBody = SpawnBody( null );
Core.LoadingProgress.End();
}
/// <summary>
/// Map when the world was opened directly (editor play, no host settings): a built-in scene is its own map;
/// the cloud world scene uses the configured map or the gamemode's default.
/// </summary>
string OfflineMap( string gamemode )
{
if ( WorldMap.Find( Scene ) is null ) return Scene.Name;
var configured = Bootstrap.FrameworkHost.Config.Map;
if ( !string.IsNullOrEmpty( configured ) ) return configured;
var reg = GamemodeRegistry.Current;
var def = reg.Valid.TryGetValue( gamemode, out var gm ) ? gm.DefaultMap : "minimal";
return Core.MapCatalog.IsCloud( def ) ? def : (gm?.AvailableMaps.FirstOrDefault( Core.MapCatalog.IsCloud ) ?? def);
}
protected override void OnUpdate()
{
LuaRuntime.Tick();
LuaInput.Tick();
LuaView.Tick();
if ( LuaRuntime.Server is not null )
{
LuaStorage.Tick();
Rp.Audit.Tick();
}
// A remote client whose connection ended (host left, kicked, timed out) goes back to the menu
// instead of being left in a dead world.
if ( Networking.IsActive && !Networking.IsHost ) _wasClient = true;
else if ( _wasClient && !Networking.IsActive )
{
_wasClient = false;
SessionService.OnConnectionLost( "The connection to the server was closed." );
return;
}
if ( !Networking.IsHost ) return;
// Publish browser metadata once the lobby exists. (A dedicated server has no local player connection,
// so this can't wait for the host's own OnActive.)
if ( !_metadataPublished && Networking.IsActive )
{
_metadataPublished = true;
SessionService.PublishLobbyMetadata();
}
if ( _sinceTimeoutCheck < 1f ) return;
_sinceTimeoutCheck = 0;
PlayerSessions.EnforceHelloTimeout();
}
// ------------------------------------------------------------ network events (host)
bool Component.INetworkListener.AcceptConnection( Connection channel, ref string reason )
{
// Room for bans / whitelists later. The engine enforces MaxPlayers and the lobby password.
return true;
}
void Component.INetworkListener.OnConnected( Connection channel )
{
if ( !Networking.IsHost ) return;
// Clients may not create, refresh or destroy networked objects themselves: the host does that.
if ( channel != Connection.Local )
{
channel.CanSpawnObjects = false;
channel.CanRefreshObjects = false;
channel.CanDestroyObjects = false;
}
var s = PlayerSessions.Ensure( channel );
RpLog.Info( "players", $"Connected: {s.DisplayName} ({s.SteamId})" );
}
void Component.INetworkListener.OnActive( Connection channel )
{
if ( !Networking.IsHost ) return;
var s = PlayerSessions.Ensure( channel );
s.IsActive = true;
if ( channel == Connection.Local )
{
// We just became a networked host: replace the offline body with a networked one.
if ( _offlineBody.IsValid() ) _offlineBody.Destroy();
_offlineBody = null;
}
RpLog.Info( "players", $"Active: {s.DisplayName} (handshake: {s.State})" );
if ( s.State == SessionState.Ready ) EnsureBody( channel );
}
void Component.INetworkListener.OnDisconnected( Connection channel )
{
if ( !Networking.IsHost ) return;
var s = PlayerSessions.Get( channel.Id );
RpLog.Info( "players", $"Disconnected: {s?.DisplayName ?? channel.DisplayName}" );
// Tell the gamemode while the player's handle is still valid.
if ( s is { InitialSpawnDone: true } && LuaRuntime.Server is { } realm )
realm.RunHook( "PlayerDisconnected", LuaPlayers.Wrap( realm, channel.Id ) );
if ( _bodies.Remove( channel.Id, out var body ) && body.IsValid() )
body.Destroy();
PlayerSessions.Remove( channel.Id );
}
void Component.INetworkListener.OnBecameHost( Connection previousHost ) { }
void Component.INetworkListener.OnHostChanged( Connection previousHost, Connection newHost ) { }
// ------------------------------------------------------------ spawning (host)
/// <summary>Called after a client's handshake succeeds.</summary>
internal void OnSessionReady( Connection c )
{
var s = PlayerSessions.Get( c.Id );
if ( s is not { IsActive: true } ) return;
// Already in the world (Lua reload): just let the new gamemode scripts meet them.
if ( _bodies.TryGetValue( c.Id, out var body ) && body.IsValid() )
{
if ( !s.InitialSpawnDone ) RunSpawnHooks( c.Id );
return;
}
EnsureBody( c );
}
void EnsureBody( Connection c )
{
if ( _bodies.TryGetValue( c.Id, out var existing ) && existing.IsValid() ) return;
var body = SpawnBody( c );
if ( body is not null ) _bodies[c.Id] = body;
}
/// <summary>Moves an existing player to a spawn point (or spawns one if missing).</summary>
internal void Respawn( Connection c ) => Respawn( c.Id );
/// <summary>Moves a player to a spawn point and runs PlayerSpawn. Guid.Empty is the offline player.</summary>
internal void Respawn( Guid id )
{
GameObject body = id == Guid.Empty ? _offlineBody : _bodies.GetValueOrDefault( id );
if ( !body.IsValid() )
{
var c = Connection.Find( id );
if ( c is not null ) EnsureBody( c );
return;
}
var t = PickSpawn( exclude: body );
var rp = body.Components.Get<RpPlayer>();
// The owning client simulates its own movement, so it must be the one to move.
rp.Teleport( t.Position, t.Rotation.Angles() );
RpLog.Info( "players", $"Respawned {rp.DisplayName}" );
RunSpawnHooks( id );
}
GameObject SpawnBody( Connection owner )
{
if ( PlayerPrefab is null ) return null;
var t = PickSpawn( exclude: null );
var body = PlayerPrefab.Clone( t, name: owner is null ? "Player (offline)" : $"Player - {owner.DisplayName}" );
var identity = body.Components.Get<RpPlayer>();
if ( identity is null )
{
RpLog.Error( "players", "Player prefab has no RpPlayer component" );
body.Destroy();
return null;
}
// Every player body carries its look, so the default (the player's own avatar from the s&box menu) is dressed
// explicitly on every machine; Lua (ply:SetOutfit, a job's uniform) changes it from there.
body.Components.GetOrCreate<Scripting.RpAppearance>();
// Noclip / frozen movement for Lua (ply:SetMoveType).
body.Components.GetOrCreate<RpMoveMode>();
// Weapon in the hand / first-person view model (ply:SetWeaponModels).
body.Components.GetOrCreate<RpHeldWeapon>();
if ( owner is not null )
{
var s = PlayerSessions.Get( owner.Id );
identity.ConnectionId = owner.Id;
identity.SteamId = s?.SteamId ?? owner.SteamId.ToString();
identity.DisplayName = s?.DisplayName ?? PlayerSessions.SanitizeName( owner.DisplayName );
body.NetworkSpawn( owner );
body.Network.SetOwnerTransfer( OwnerTransfer.Fixed );
body.Network.SetOrphanedMode( NetworkOrphaned.Destroy );
}
else
{
identity.DisplayName = "Offline Player";
}
RpLog.Info( "players", $"Spawned {identity.DisplayName} at {t.Position}" );
RunSpawnHooks( owner?.Id ?? Guid.Empty );
return body;
}
/// <summary>After rp_lua_reload: the new gamemode scripts meet every player again (PlayerInitialSpawn + PlayerSpawn).</summary>
internal void OnLuaReloaded()
{
_offlineInitialSpawnDone = false;
if ( _offlineBody.IsValid() ) RunSpawnHooks( Guid.Empty );
foreach ( var (id, body) in _bodies.ToList() )
{
if ( !body.IsValid() ) continue;
var s = PlayerSessions.Get( id );
if ( s is not null ) s.InitialSpawnDone = false;
// Remote players are reloading their client scripts: they get their hooks once ContentReady arrives
// (OnSessionReady), so nothing the gamemode sends them is lost mid-swap.
if ( Connection.Find( id ) is { } c && c != Connection.Local ) continue;
RunSpawnHooks( id );
}
}
/// <summary>GM lifecycle: PlayerInitialSpawn once per session, then PlayerSpawn on every spawn.</summary>
void RunSpawnHooks( Guid id )
{
if ( LuaRuntime.Server is not { } realm ) return;
var ply = LuaPlayers.Wrap( realm, id );
bool first;
if ( id == Guid.Empty ) { first = !_offlineInitialSpawnDone; _offlineInitialSpawnDone = true; }
else
{
var s = PlayerSessions.Get( id );
first = s is not null && !s.InitialSpawnDone;
if ( s is not null ) s.InitialSpawnDone = true;
}
if ( first ) realm.RunHook( "PlayerInitialSpawn", ply );
realm.RunHook( "PlayerSpawn", ply );
}
/// <summary>Chooses the spawn point farthest from other players, so spawns don't stack.</summary>
Transform PickSpawn( GameObject exclude )
{
var all = Scene.GetAllComponents<SpawnPoint>().ToList();
// A loaded cloud map brings its own spawn points; prefer those over the scene's fallback ones.
var mapPoints = all.Where( sp => sp.GameObject.Components.GetInAncestorsOrSelf<MapInstance>() is not null ).ToList();
var points = mapPoints.Count > 0 ? mapPoints : all;
if ( points.Count == 0 )
{
RpLog.Warn( "players", "No SpawnPoint in the scene; spawning at the PlayerManager's position" );
return new Transform( WorldPosition + Vector3.Up * 16, WorldRotation );
}
var others = RpPlayer.All( Scene ).Where( p => p.GameObject != exclude ).Select( p => p.WorldPosition ).ToList();
if ( others.Count == 0 ) return points[Random.Shared.Next( points.Count )].WorldTransform;
var best = points
.OrderByDescending( sp => others.Min( o => o.Distance( sp.WorldPosition ) ) )
.First();
return best.WorldTransform;
}
}