diff --git a/Source.Common/Utilities/UserConsoleInput.cs b/Source.Common/Utilities/UserConsoleInput.cs index 153bd6d8..0d1f5af7 100644 --- a/Source.Common/Utilities/UserConsoleInput.cs +++ b/Source.Common/Utilities/UserConsoleInput.cs @@ -8,13 +8,28 @@ namespace Source.Common.Utilities; public class UserConsoleInput { - readonly char[] consoleText = new char[2048]; + // 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(); + + 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 +65,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 +185,8 @@ private void ReceiveBackspace() { Console.Write('\b'); count--; } + + browseLine = inputLine; } private ReadOnlySpan ReceiveNewLine() { @@ -104,7 +196,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 +229,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 +237,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 7a7f0077..16b7e6c5 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 POSIX + 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 POSIX + 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,48 @@ private bool DoRunVGUIFrame(bool finished = false) { } public void Sys_Printf(ReadOnlySpan text) { - Console.Write(text); + consoleUserInput.Print(text); + } +} + +public static class TextConsole +{ +#if WIN32 + static PosixSignalRegistration[]? ConsoleHandlers; + + 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); + + public static void Init() { +#if WIN32 + SetTitle("SOURCE.NET DEDICATED SERVER"); +#if GMOD_DLL + try { + Console.OutputEncoding = Encoding.UTF8; + } + catch (IOException) { + } +#endif + if (!AttachConsoleHandler()) + Console.Write("WARNING! TextConsole.Init: Could not attach console hook.\n"); +#else + Msg("\n"); +#endif + Msg("Console initialized.\n"); } } @@ -93,6 +160,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/DedicatedServerAPI.cs b/Source.Engine/DedicatedServerAPI.cs index 2502307d..303828a1 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,10 +78,11 @@ public void AddConsoleText(ReadOnlySpan text) { } public void UpdateStatus(out float fps, out int active, out int maxPlayers, Span map) { - throw new NotImplementedException(); + Host.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 bee23c95..01c0460e 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() { @@ -1427,12 +1437,23 @@ 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 + if (args.FindArg("keep_players") != null) + sv.KeepPlayers = true; #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; diff --git a/Source.Engine/Server/BaseServer.cs b/Source.Engine/Server/BaseServer.cs index 0305e564..1aef8e6d 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. diff --git a/Source.Engine/Sys.cs b/Source.Engine/Sys.cs index 4ad000a9..0b469c01 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);