From 7d2e6ceae2cea9c40ca579791dca4dea18f8d5bf Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:45:50 +0100 Subject: [PATCH 1/9] Run host frame end on dedicated and implement server status --- Source.Engine/DedicatedServerAPI.cs | 5 +++-- Source.Engine/Host.cs | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Source.Engine/DedicatedServerAPI.cs b/Source.Engine/DedicatedServerAPI.cs index 2502307d7..caa7cda3c 100644 --- a/Source.Engine/DedicatedServerAPI.cs +++ b/Source.Engine/DedicatedServerAPI.cs @@ -76,10 +76,11 @@ public void AddConsoleText(ReadOnlySpan text) { } public void UpdateStatus(out float fps, out int active, out int maxPlayers, Span map) { - throw new NotImplementedException(); + services.GetRequiredService().GetHostInfo(out fps, out active, out maxPlayers, map); } public void UpdateHostname(Span hostname) { - throw new NotImplementedException(); + if (!hostname.IsEmpty) + strcpy(hostname, sv.GetName()); } } diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index bee23c953..98e064bc8 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -287,7 +287,6 @@ void _RunFrame(TimeUnit_t time) { // else // updatedynamicmodels -#if !SWDS if (!sv.IsDedicated()) { ClientDLL.Update(); } @@ -298,7 +297,6 @@ void _RunFrame(TimeUnit_t time) { FrameCount++; Time = TickCount * host_state.IntervalPerTick + cl.TickRemainder; PostFrameRate(FrameTime); -#endif } } public static void DefaultMapFileName(ReadOnlySpan fullMapName, Span diskName) { @@ -309,7 +307,19 @@ public static void DefaultMapFileName(ReadOnlySpan fullMapName, Span private void PostFrameRate(TimeUnit_t frameTime) { frameTime = Math.Clamp(frameTime, 0.0001, 1.0); TimeUnit_t fps = 1.0 / frameTime; - FramesPerSecond = fps * FPS_AVG_FRAC + (1.0 - FPS_AVG_FRAC) * fps; + FramesPerSecond = FramesPerSecond * FPS_AVG_FRAC + (1.0 - FPS_AVG_FRAC) * fps; + } + + public void GetHostInfo(out float fps, out int active, out int maxPlayers, Span map) { + int clients = sv.GetNumClients(); + + fps = (float)FramesPerSecond; + active = clients; + + if (!map.IsEmpty) + strcpy(map, sv.GetMapName()); + + maxPlayers = sv.GetMaxClients(); } private void UpdateMapList() { From e76f6b624192d0317dfeb609dd8c48756fe8e484 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:45:50 +0100 Subject: [PATCH 2/9] Fix quit on dedicated server and add exit --- Source.Engine/Host.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index 98e064bc8..dae961214 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -1437,12 +1437,22 @@ void quit(in TokenizedCommand args) { // EngineVGui.ConfirmQuit(); return; } +#endif - // TODO: game events. - HostState.Shutdown(); + IGameEvent? ev = g_GameEventManager.CreateEvent("host_quit"); + if (ev != null) + g_GameEventManager.FireEventClientSide(ev); + +#if GMOD_DLL + // todo: keep_players argument #endif + + HostState.Shutdown(); } + [ConCommand("exit", "Exit the engine.")] + void exit(in TokenizedCommand args) => quit(in args); + readonly ConVar voice_recordtofile = new("voice_recordtofile", "0", 0, "Record mic data and decompressed voice data into 'voice_micdata.wav' and 'voice_decompressed.wav'"); readonly ConVar voice_inputfromfile; readonly ConVar sv_allow_voice_from_file; From 998df8cab66da3438d81f0a8eb9233328cbef080 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:45:50 +0100 Subject: [PATCH 3/9] Port dedicated server console --- Source.Common/Utilities/UserConsoleInput.cs | 113 +++++++++++++++++++- Source.Dedicated/Program.cs | 64 ++++++++++- Source.Engine/Sys.cs | 5 +- 3 files changed, 177 insertions(+), 5 deletions(-) diff --git a/Source.Common/Utilities/UserConsoleInput.cs b/Source.Common/Utilities/UserConsoleInput.cs index 153bd6d88..71ea521b2 100644 --- a/Source.Common/Utilities/UserConsoleInput.cs +++ b/Source.Common/Utilities/UserConsoleInput.cs @@ -8,13 +8,27 @@ namespace Source.Common.Utilities; public class UserConsoleInput { - readonly char[] consoleText = new char[2048]; + const int MAX_CONSOLE_TEXTLEN = 256; + const int MAX_BUFFER_LINES = 30; + + readonly Lock consoleLock = new(); + + readonly char[] consoleText = new char[MAX_CONSOLE_TEXTLEN]; int consoleTextLen; int cursorPosition; + readonly char[] savedConsoleText = new char[MAX_CONSOLE_TEXTLEN]; + int savedConsoleTextLen; + + readonly string?[] lineBuffer = new string?[MAX_BUFFER_LINES]; + int inputLine; + int browseLine; + int totalLines; + public event OnEnterFn? OnEnter; public void RunFrame() { + using Lock.Scope scope = consoleLock.EnterScope(); while (!Console.IsInputRedirected && Console.KeyAvailable) { var key = Console.ReadKey(true); switch (key.Key) { @@ -50,12 +64,87 @@ public void RunFrame() { } } + public void Print(ReadOnlySpan msg) { + using Lock.Scope scope = consoleLock.EnterScope(); + for (int len = consoleTextLen; len > 0; len--) + Console.Out.Write("\b \b"); + + PrintRaw(msg); + + if (consoleTextLen > 0) + Console.Out.Write(consoleText, 0, consoleTextLen); + } + + static void PrintRaw(ReadOnlySpan msg) { +#if WIN32 + if (msg.Contains('\a')) { + char[] temp = new char[msg.Length]; + msg.Replace(temp, '\a', '.'); + Console.Out.Write(temp); + return; + } +#endif + Console.Out.Write(msg); + } + + string GetBufferedLine(int line) => (uint)line < MAX_BUFFER_LINES ? lineBuffer[line] ?? "" : ""; + + void ShowBufferedLine() { + string line = GetBufferedLine(browseLine); + Console.Out.Write(line); + line.CopyTo(consoleText); + consoleTextLen = line.Length; + } + private void ReceiveUpArrow() { + int lastCommandInHistory = inputLine + 1; + if (lastCommandInHistory > totalLines) + lastCommandInHistory = 0; + if (browseLine == lastCommandInHistory) + return; + + if (browseLine == inputLine) { + if (consoleTextLen > 0) + consoleText.AsSpan(0, consoleTextLen).CopyTo(savedConsoleText); + + savedConsoleTextLen = consoleTextLen; + } + + browseLine--; + if (browseLine < 0) + browseLine = totalLines - 1; + + while (consoleTextLen-- > 0) + Console.Out.Write("\b \b"); + + ShowBufferedLine(); + cursorPosition = consoleTextLen; } private void ReceiveDownArrow() { + if (browseLine == inputLine) + return; + + browseLine++; + if (browseLine > totalLines) + browseLine = 0; + + while (consoleTextLen-- > 0) + Console.Out.Write("\b \b"); + + if (browseLine == inputLine) { + if (savedConsoleTextLen > 0) { + savedConsoleText.AsSpan(0, savedConsoleTextLen).CopyTo(consoleText); + Console.Out.Write(consoleText, 0, savedConsoleTextLen); + } + + consoleTextLen = savedConsoleTextLen; + } + else + ShowBufferedLine(); + cursorPosition = consoleTextLen; } private void ReceiveLeftArrow() { @@ -95,6 +184,8 @@ private void ReceiveBackspace() { Console.Write('\b'); count--; } + + browseLine = inputLine; } private ReadOnlySpan ReceiveNewLine() { @@ -104,7 +195,21 @@ private ReadOnlySpan ReceiveNewLine() { len = consoleTextLen; consoleTextLen = 0; cursorPosition = 0; - return consoleText.AsSpan()[..len]; + + ReadOnlySpan text = consoleText.AsSpan(0, len); + if (inputLine == 0 || !text.SequenceEqual(GetBufferedLine(inputLine - 1))) { + lineBuffer[inputLine] = new(text); + inputLine++; + + if (inputLine > totalLines) + totalLines = inputLine; + + if (inputLine >= MAX_BUFFER_LINES) + inputLine = 0; + } + + browseLine = inputLine; + return text; } else return null; @@ -123,7 +228,7 @@ private void ReceiveStandardChar(char ch) { consoleText[cursorPosition] = ch; - Console.Write(new string(new ReadOnlySpan(consoleText))[cursorPosition..(cursorPosition + (consoleTextLen - cursorPosition + 1))]); + Console.Out.Write(consoleText, cursorPosition, consoleTextLen - cursorPosition + 1); consoleTextLen++; cursorPosition++; count = consoleTextLen; @@ -131,5 +236,7 @@ private void ReceiveStandardChar(char ch) { Console.Write('\b'); count--; } + + browseLine = inputLine; } } diff --git a/Source.Dedicated/Program.cs b/Source.Dedicated/Program.cs index 7a7f00776..10f7dc7fa 100644 --- a/Source.Dedicated/Program.cs +++ b/Source.Dedicated/Program.cs @@ -27,11 +27,20 @@ using Steamworks; +using System.Runtime.InteropServices; +using System.Text; + namespace Source.Dedicated; public class DedicatedExports(IDedicatedServerAPI engine) : IDedicatedExports { readonly UserConsoleInput consoleUserInput = new(); +#if GMOD_DLL + int processCount; +#endif +#if WIN32 + double lastStatusUpdate; +#endif public void RunServer() { // Run 2 engine frames first to get the engine to load its resources. @@ -45,8 +54,15 @@ public void RunServer() { consoleUserInput.OnEnter += ConsoleUserInput_OnEnter; bool done = false; while (!done) { +#if GMOD_DLL + if (!DoRunVGUIFrame() && ++processCount > 3) { + processCount = 0; + ProcessConsoleInput(); + } +#else if (!DoRunVGUIFrame()) ProcessConsoleInput(); +#endif if (!engine.RunFrame()) done = true; @@ -65,7 +81,17 @@ private int ProcessConsoleInput() { } private void UpdateStatus(bool force) { +#if WIN32 + double now = Platform.Time; + if (!force && now - lastStatusUpdate < 0.5) + return; + + lastStatusUpdate = now; + Span hostname = stackalloc char[128]; + engine.UpdateHostname(hostname); + TextConsole.SetTitle(hostname.SliceNullTerminatedString()); +#endif } private bool DoRunVGUIFrame(bool finished = false) { @@ -73,7 +99,41 @@ private bool DoRunVGUIFrame(bool finished = false) { } public void Sys_Printf(ReadOnlySpan text) { - Console.Write(text); + consoleUserInput.Print(text); + } +} + +public static class TextConsole +{ +#if WIN32 + delegate bool ConsoleCtrlHandler(uint ctrlType); + static readonly ConsoleCtrlHandler ConsoleHandlerRoutine = static _ => true; + + [DllImport("kernel32.dll")] + static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandler handlerRoutine, bool add); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + static extern bool SetConsoleTitleW(string title); + + public static void SetTitle(ReadOnlySpan title) => SetConsoleTitleW(new(title)); +#endif + + public static void Init() { +#if WIN32 + SetTitle("SOURCE DEDICATED SERVER"); +#if GMOD_DLL + try { + Console.OutputEncoding = Encoding.UTF8; + } + catch (IOException) { + } +#endif + if (!SetConsoleCtrlHandler(ConsoleHandlerRoutine, true)) + Console.Write("WARNING! TextConsole::Init: Could not attach console hook.\n"); +#else + Msg("\n"); +#endif + Msg("Console initialized.\n"); } } @@ -93,6 +153,8 @@ public Bootloader() { isTextMode = commandLine.CheckParm("-textmode"); } public void Boot() { + TextConsole.Init(); + engineAPI = new EngineBuilder(commandLine) // These assemblies have no reference to them, so they must be manually loaded. .WithAssembly("Source.VTF") diff --git a/Source.Engine/Sys.cs b/Source.Engine/Sys.cs index 4ad000a9a..0b469c01f 100644 --- a/Source.Engine/Sys.cs +++ b/Source.Engine/Sys.cs @@ -138,7 +138,10 @@ private void Write(string group, ReadOnlySpan str, in Color color, bool ro int bufferIdx = 0; unsafe void writeTxt(ReadOnlySpan sub, in Color color) { #if DBGFLAG_WRITE_TO_STDOUT - Console.Write(sub.Pastel(color)); + if (dedicated != null) + dedicated.Sys_Printf(sub.Pastel(color)); + else + Console.Write(sub.Pastel(color)); #endif if (routeInGame) { host.Con?.ColorPrintf(in color, sub); From d2d6f80b54c7f615eb1b9ff5cada54b6fe32365d Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:53:02 +0100 Subject: [PATCH 4/9] Add keep_players argument to quit --- Source.Engine/Host.cs | 3 ++- Source.Engine/Server/BaseServer.cs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index dae961214..01c0460e1 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -1444,7 +1444,8 @@ void quit(in TokenizedCommand args) { g_GameEventManager.FireEventClientSide(ev); #if GMOD_DLL - // todo: keep_players argument + if (args.FindArg("keep_players") != null) + sv.KeepPlayers = true; #endif HostState.Shutdown(); diff --git a/Source.Engine/Server/BaseServer.cs b/Source.Engine/Server/BaseServer.cs index 0305e5642..1aef8e6db 100644 --- a/Source.Engine/Server/BaseServer.cs +++ b/Source.Engine/Server/BaseServer.cs @@ -714,6 +714,9 @@ public virtual void Shutdown() { State = ServerState.Dead; // Only drop clients if we have not cleared out entity data prior to this. +#if GMOD_DLL + if (!KeepPlayers) +#endif for (int i = Clients.Count - 1; i >= 0; i--) { BaseClient cl = Clients[i]; if (cl.IsConnected()) @@ -1521,6 +1524,9 @@ protected bool ValidInfoChallenge(NetAddress adr, ReadOnlySpan nugget) { public InlineArray64 MapFilename; // map filename, may bear no resemblance to map name public InlineArray64 Skyname; // skybox name public InlineArray32 Password; // server password +#if GMOD_DLL + public bool KeepPlayers; +#endif public MD5Value WorldmapMD5; // For detecting that client has a hacked local copy of map, the client will be dropped if this occurs. From b13fe5b3d7459aeb27009ac242297afb8844254c Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:21:42 +0100 Subject: [PATCH 5/9] Read dedicated console input every 4th frame only on POSIX --- Source.Dedicated/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source.Dedicated/Program.cs b/Source.Dedicated/Program.cs index 10f7dc7fa..cf59b2c8a 100644 --- a/Source.Dedicated/Program.cs +++ b/Source.Dedicated/Program.cs @@ -35,7 +35,7 @@ namespace Source.Dedicated; public class DedicatedExports(IDedicatedServerAPI engine) : IDedicatedExports { readonly UserConsoleInput consoleUserInput = new(); -#if GMOD_DLL +#if POSIX int processCount; #endif #if WIN32 @@ -54,7 +54,7 @@ public void RunServer() { consoleUserInput.OnEnter += ConsoleUserInput_OnEnter; bool done = false; while (!done) { -#if GMOD_DLL +#if POSIX if (!DoRunVGUIFrame() && ++processCount > 3) { processCount = 0; ProcessConsoleInput(); From 978c9d341e791d87d5d5fe984ab0f3f7cd8a8e15 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:25:47 +0100 Subject: [PATCH 6/9] Cache Host in DedicatedServerAPI --- Source.Engine/DedicatedServerAPI.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Source.Engine/DedicatedServerAPI.cs b/Source.Engine/DedicatedServerAPI.cs index caa7cda3c..303828a1b 100644 --- a/Source.Engine/DedicatedServerAPI.cs +++ b/Source.Engine/DedicatedServerAPI.cs @@ -29,6 +29,8 @@ static string GetModDirFromPath(string path) { Mod? dedicatedServer = null; IEngine eng = null!; + Host? host; + Host Host => host ??= services.GetRequiredService(); public bool ModInit(in StartupInfo info) { ConVar.Register(); @@ -76,7 +78,7 @@ public void AddConsoleText(ReadOnlySpan text) { } public void UpdateStatus(out float fps, out int active, out int maxPlayers, Span map) { - services.GetRequiredService().GetHostInfo(out fps, out active, out maxPlayers, map); + Host.GetHostInfo(out fps, out active, out maxPlayers, map); } public void UpdateHostname(Span hostname) { From 9f7123f8622260a5d2b4e74a348ebec079e4736a Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:29:17 +0100 Subject: [PATCH 7/9] Set the dedicated console title with Console.Title --- Source.Dedicated/Program.cs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Source.Dedicated/Program.cs b/Source.Dedicated/Program.cs index cf59b2c8a..638dd27bc 100644 --- a/Source.Dedicated/Program.cs +++ b/Source.Dedicated/Program.cs @@ -111,16 +111,13 @@ public static class TextConsole [DllImport("kernel32.dll")] static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandler handlerRoutine, bool add); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - static extern bool SetConsoleTitleW(string title); - - public static void SetTitle(ReadOnlySpan title) => SetConsoleTitleW(new(title)); #endif + public static void SetTitle(ReadOnlySpan title) => Console.Title = new(title); + public static void Init() { #if WIN32 - SetTitle("SOURCE DEDICATED SERVER"); + SetTitle("SOURCE.NET DEDICATED SERVER"); #if GMOD_DLL try { Console.OutputEncoding = Encoding.UTF8; From d05a623e8682e4f2157756579283ee1593847370 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:32:29 +0100 Subject: [PATCH 8/9] Swallow console signals with PosixSignalRegistration --- Source.Dedicated/Program.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Source.Dedicated/Program.cs b/Source.Dedicated/Program.cs index 638dd27bc..16b7e6c5a 100644 --- a/Source.Dedicated/Program.cs +++ b/Source.Dedicated/Program.cs @@ -106,11 +106,21 @@ public void Sys_Printf(ReadOnlySpan text) { public static class TextConsole { #if WIN32 - delegate bool ConsoleCtrlHandler(uint ctrlType); - static readonly ConsoleCtrlHandler ConsoleHandlerRoutine = static _ => true; + static PosixSignalRegistration[]? ConsoleHandlers; - [DllImport("kernel32.dll")] - static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandler handlerRoutine, bool add); + static bool AttachConsoleHandler() { + try { + ConsoleHandlers = [ + PosixSignalRegistration.Create(PosixSignal.SIGINT, static context => context.Cancel = true), + PosixSignalRegistration.Create(PosixSignal.SIGQUIT, static context => context.Cancel = true), + PosixSignalRegistration.Create(PosixSignal.SIGTERM, static context => context.Cancel = true) + ]; + return true; + } + catch (System.ComponentModel.Win32Exception) { + return false; + } + } #endif public static void SetTitle(ReadOnlySpan title) => Console.Title = new(title); @@ -125,8 +135,8 @@ public static void Init() { catch (IOException) { } #endif - if (!SetConsoleCtrlHandler(ConsoleHandlerRoutine, true)) - Console.Write("WARNING! TextConsole::Init: Could not attach console hook.\n"); + if (!AttachConsoleHandler()) + Console.Write("WARNING! TextConsole.Init: Could not attach console hook.\n"); #else Msg("\n"); #endif From febda2c13ca7d923cc505b6e2ba3f3160c4dfc73 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:36:32 +0100 Subject: [PATCH 9/9] Raise the dedicated console line limit to 512 --- Source.Common/Utilities/UserConsoleInput.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Source.Common/Utilities/UserConsoleInput.cs b/Source.Common/Utilities/UserConsoleInput.cs index 71ea521b2..0d1f5af74 100644 --- a/Source.Common/Utilities/UserConsoleInput.cs +++ b/Source.Common/Utilities/UserConsoleInput.cs @@ -8,7 +8,8 @@ namespace Source.Common.Utilities; public class UserConsoleInput { - const int MAX_CONSOLE_TEXTLEN = 256; + // note: 256 by default in GMod, raised to the longest command the command buffer accepts + const int MAX_CONSOLE_TEXTLEN = 512; const int MAX_BUFFER_LINES = 30; readonly Lock consoleLock = new();