Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 111 additions & 3 deletions Source.Common/Utilities/UserConsoleInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Comment thread
marchc1 marked this conversation as resolved.
Resolved
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) {
Expand Down Expand Up @@ -50,12 +65,87 @@ public void RunFrame() {
}
}

public void Print(ReadOnlySpan<char> 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<char> 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() {
Expand Down Expand Up @@ -95,6 +185,8 @@ private void ReceiveBackspace() {
Console.Write('\b');
count--;
}

browseLine = inputLine;
}

private ReadOnlySpan<char> ReceiveNewLine() {
Expand All @@ -104,7 +196,21 @@ private ReadOnlySpan<char> ReceiveNewLine() {
len = consoleTextLen;
consoleTextLen = 0;
cursorPosition = 0;
return consoleText.AsSpan()[..len];

ReadOnlySpan<char> 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;
Expand All @@ -123,13 +229,15 @@ private void ReceiveStandardChar(char ch) {

consoleText[cursorPosition] = ch;

Console.Write(new string(new ReadOnlySpan<char>(consoleText))[cursorPosition..(cursorPosition + (consoleTextLen - cursorPosition + 1))]);
Console.Out.Write(consoleText, cursorPosition, consoleTextLen - cursorPosition + 1);
consoleTextLen++;
cursorPosition++;
count = consoleTextLen;
while (count > cursorPosition) {
Console.Write('\b');
count--;
}

browseLine = inputLine;
}
}
71 changes: 70 additions & 1 deletion Source.Dedicated/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -45,8 +54,15 @@ public void RunServer() {
consoleUserInput.OnEnter += ConsoleUserInput_OnEnter;
bool done = false;
while (!done) {
#if POSIX
if (!DoRunVGUIFrame() && ++processCount > 3) {
Comment thread
marchc1 marked this conversation as resolved.
Resolved
processCount = 0;
ProcessConsoleInput();
}
#else
if (!DoRunVGUIFrame())
ProcessConsoleInput();
#endif

if (!engine.RunFrame())
done = true;
Expand All @@ -65,15 +81,66 @@ private int ProcessConsoleInput() {
}

private void UpdateStatus(bool force) {
#if WIN32
double now = Platform.Time;
if (!force && now - lastStatusUpdate < 0.5)
return;

lastStatusUpdate = now;

Span<char> hostname = stackalloc char[128];
engine.UpdateHostname(hostname);
TextConsole.SetTitle(hostname.SliceNullTerminatedString());
#endif
}

private bool DoRunVGUIFrame(bool finished = false) {
return false;
}

public void Sys_Printf(ReadOnlySpan<char> 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<char> 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");
}
}

Expand All @@ -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")
Expand Down
7 changes: 5 additions & 2 deletions Source.Engine/DedicatedServerAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ static string GetModDirFromPath(string path) {

Mod? dedicatedServer = null;
IEngine eng = null!;
Host? host;
Host Host => host ??= services.GetRequiredService<Host>();

public bool ModInit(in StartupInfo info) {
ConVar.Register();
Expand Down Expand Up @@ -76,10 +78,11 @@ public void AddConsoleText(ReadOnlySpan<char> text) {
}

public void UpdateStatus(out float fps, out int active, out int maxPlayers, Span<char> map) {
throw new NotImplementedException();
Host.GetHostInfo(out fps, out active, out maxPlayers, map);
}

public void UpdateHostname(Span<char> hostname) {
throw new NotImplementedException();
if (!hostname.IsEmpty)
strcpy(hostname, sv.GetName());
}
}
31 changes: 26 additions & 5 deletions Source.Engine/Host.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,6 @@ void _RunFrame(TimeUnit_t time) {
// else
// updatedynamicmodels

#if !SWDS
if (!sv.IsDedicated()) {
ClientDLL.Update();
}
Expand All @@ -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<char> fullMapName, Span<char> diskName) {
Expand All @@ -309,7 +307,19 @@ public static void DefaultMapFileName(ReadOnlySpan<char> fullMapName, Span<char>
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<char> map) {
int clients = sv.GetNumClients();

fps = (float)FramesPerSecond;
active = clients;

if (!map.IsEmpty)
strcpy(map, sv.GetMapName());

maxPlayers = sv.GetMaxClients();
}

private void UpdateMapList() {
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions Source.Engine/Server/BaseServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -1521,6 +1524,9 @@ protected bool ValidInfoChallenge(NetAddress adr, ReadOnlySpan<char> nugget) {
public InlineArray64<char> MapFilename; // map filename, may bear no resemblance to map name
public InlineArray64<char> Skyname; // skybox name
public InlineArray32<char> 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.

Expand Down
5 changes: 4 additions & 1 deletion Source.Engine/Sys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,10 @@ private void Write(string group, ReadOnlySpan<char> str, in Color color, bool ro
int bufferIdx = 0;
unsafe void writeTxt(ReadOnlySpan<char> 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);
Expand Down
Loading