Skip to content

Commit 39ca51c

Browse files
authored
Merge pull request #273 from spacevx/feat/dedicated-console
Feat/dedicated console
2 parents 1244215 + febda2c commit 39ca51c

6 files changed

Lines changed: 222 additions & 12 deletions

File tree

‎Source.Common/Utilities/UserConsoleInput.cs‎

Lines changed: 111 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,28 @@ namespace Source.Common.Utilities;
88

99
public class UserConsoleInput
1010
{
11-
readonly char[] consoleText = new char[2048];
11+
// note: 256 by default in GMod, raised to the longest command the command buffer accepts
12+
const int MAX_CONSOLE_TEXTLEN = 512;
13+
const int MAX_BUFFER_LINES = 30;
14+
15+
readonly Lock consoleLock = new();
16+
17+
readonly char[] consoleText = new char[MAX_CONSOLE_TEXTLEN];
1218
int consoleTextLen;
1319
int cursorPosition;
1420

21+
readonly char[] savedConsoleText = new char[MAX_CONSOLE_TEXTLEN];
22+
int savedConsoleTextLen;
23+
24+
readonly string?[] lineBuffer = new string?[MAX_BUFFER_LINES];
25+
int inputLine;
26+
int browseLine;
27+
int totalLines;
28+
1529
public event OnEnterFn? OnEnter;
1630

1731
public void RunFrame() {
32+
using Lock.Scope scope = consoleLock.EnterScope();
1833
while (!Console.IsInputRedirected && Console.KeyAvailable) {
1934
var key = Console.ReadKey(true);
2035
switch (key.Key) {
@@ -50,12 +65,87 @@ public void RunFrame() {
5065
}
5166
}
5267

68+
public void Print(ReadOnlySpan<char> msg) {
69+
using Lock.Scope scope = consoleLock.EnterScope();
70+
for (int len = consoleTextLen; len > 0; len--)
71+
Console.Out.Write("\b \b");
72+
73+
PrintRaw(msg);
74+
75+
if (consoleTextLen > 0)
76+
Console.Out.Write(consoleText, 0, consoleTextLen);
77+
}
78+
79+
static void PrintRaw(ReadOnlySpan<char> msg) {
80+
#if WIN32
81+
if (msg.Contains('\a')) {
82+
char[] temp = new char[msg.Length];
83+
msg.Replace(temp, '\a', '.');
84+
Console.Out.Write(temp);
85+
return;
86+
}
87+
#endif
88+
Console.Out.Write(msg);
89+
}
90+
91+
string GetBufferedLine(int line) => (uint)line < MAX_BUFFER_LINES ? lineBuffer[line] ?? "" : "";
92+
93+
void ShowBufferedLine() {
94+
string line = GetBufferedLine(browseLine);
95+
Console.Out.Write(line);
96+
line.CopyTo(consoleText);
97+
consoleTextLen = line.Length;
98+
}
99+
53100
private void ReceiveUpArrow() {
101+
int lastCommandInHistory = inputLine + 1;
102+
if (lastCommandInHistory > totalLines)
103+
lastCommandInHistory = 0;
54104

105+
if (browseLine == lastCommandInHistory)
106+
return;
107+
108+
if (browseLine == inputLine) {
109+
if (consoleTextLen > 0)
110+
consoleText.AsSpan(0, consoleTextLen).CopyTo(savedConsoleText);
111+
112+
savedConsoleTextLen = consoleTextLen;
113+
}
114+
115+
browseLine--;
116+
if (browseLine < 0)
117+
browseLine = totalLines - 1;
118+
119+
while (consoleTextLen-- > 0)
120+
Console.Out.Write("\b \b");
121+
122+
ShowBufferedLine();
123+
cursorPosition = consoleTextLen;
55124
}
56125

57126
private void ReceiveDownArrow() {
127+
if (browseLine == inputLine)
128+
return;
129+
130+
browseLine++;
131+
if (browseLine > totalLines)
132+
browseLine = 0;
133+
134+
while (consoleTextLen-- > 0)
135+
Console.Out.Write("\b \b");
136+
137+
if (browseLine == inputLine) {
138+
if (savedConsoleTextLen > 0) {
139+
savedConsoleText.AsSpan(0, savedConsoleTextLen).CopyTo(consoleText);
140+
Console.Out.Write(consoleText, 0, savedConsoleTextLen);
141+
}
142+
143+
consoleTextLen = savedConsoleTextLen;
144+
}
145+
else
146+
ShowBufferedLine();
58147

148+
cursorPosition = consoleTextLen;
59149
}
60150

61151
private void ReceiveLeftArrow() {
@@ -95,6 +185,8 @@ private void ReceiveBackspace() {
95185
Console.Write('\b');
96186
count--;
97187
}
188+
189+
browseLine = inputLine;
98190
}
99191

100192
private ReadOnlySpan<char> ReceiveNewLine() {
@@ -104,7 +196,21 @@ private ReadOnlySpan<char> ReceiveNewLine() {
104196
len = consoleTextLen;
105197
consoleTextLen = 0;
106198
cursorPosition = 0;
107-
return consoleText.AsSpan()[..len];
199+
200+
ReadOnlySpan<char> text = consoleText.AsSpan(0, len);
201+
if (inputLine == 0 || !text.SequenceEqual(GetBufferedLine(inputLine - 1))) {
202+
lineBuffer[inputLine] = new(text);
203+
inputLine++;
204+
205+
if (inputLine > totalLines)
206+
totalLines = inputLine;
207+
208+
if (inputLine >= MAX_BUFFER_LINES)
209+
inputLine = 0;
210+
}
211+
212+
browseLine = inputLine;
213+
return text;
108214
}
109215
else
110216
return null;
@@ -123,13 +229,15 @@ private void ReceiveStandardChar(char ch) {
123229

124230
consoleText[cursorPosition] = ch;
125231

126-
Console.Write(new string(new ReadOnlySpan<char>(consoleText))[cursorPosition..(cursorPosition + (consoleTextLen - cursorPosition + 1))]);
232+
Console.Out.Write(consoleText, cursorPosition, consoleTextLen - cursorPosition + 1);
127233
consoleTextLen++;
128234
cursorPosition++;
129235
count = consoleTextLen;
130236
while (count > cursorPosition) {
131237
Console.Write('\b');
132238
count--;
133239
}
240+
241+
browseLine = inputLine;
134242
}
135243
}

‎Source.Dedicated/Program.cs‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,20 @@
2727

2828
using Steamworks;
2929

30+
using System.Runtime.InteropServices;
31+
using System.Text;
32+
3033
namespace Source.Dedicated;
3134

3235
public class DedicatedExports(IDedicatedServerAPI engine) : IDedicatedExports
3336
{
3437
readonly UserConsoleInput consoleUserInput = new();
38+
#if POSIX
39+
int processCount;
40+
#endif
41+
#if WIN32
42+
double lastStatusUpdate;
43+
#endif
3544

3645
public void RunServer() {
3746
// Run 2 engine frames first to get the engine to load its resources.
@@ -45,8 +54,15 @@ public void RunServer() {
4554
consoleUserInput.OnEnter += ConsoleUserInput_OnEnter;
4655
bool done = false;
4756
while (!done) {
57+
#if POSIX
58+
if (!DoRunVGUIFrame() && ++processCount > 3) {
59+
processCount = 0;
60+
ProcessConsoleInput();
61+
}
62+
#else
4863
if (!DoRunVGUIFrame())
4964
ProcessConsoleInput();
65+
#endif
5066

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

6783
private void UpdateStatus(bool force) {
84+
#if WIN32
85+
double now = Platform.Time;
86+
if (!force && now - lastStatusUpdate < 0.5)
87+
return;
88+
89+
lastStatusUpdate = now;
6890

91+
Span<char> hostname = stackalloc char[128];
92+
engine.UpdateHostname(hostname);
93+
TextConsole.SetTitle(hostname.SliceNullTerminatedString());
94+
#endif
6995
}
7096

7197
private bool DoRunVGUIFrame(bool finished = false) {
7298
return false;
7399
}
74100

75101
public void Sys_Printf(ReadOnlySpan<char> text) {
76-
Console.Write(text);
102+
consoleUserInput.Print(text);
103+
}
104+
}
105+
106+
public static class TextConsole
107+
{
108+
#if WIN32
109+
static PosixSignalRegistration[]? ConsoleHandlers;
110+
111+
static bool AttachConsoleHandler() {
112+
try {
113+
ConsoleHandlers = [
114+
PosixSignalRegistration.Create(PosixSignal.SIGINT, static context => context.Cancel = true),
115+
PosixSignalRegistration.Create(PosixSignal.SIGQUIT, static context => context.Cancel = true),
116+
PosixSignalRegistration.Create(PosixSignal.SIGTERM, static context => context.Cancel = true)
117+
];
118+
return true;
119+
}
120+
catch (System.ComponentModel.Win32Exception) {
121+
return false;
122+
}
123+
}
124+
#endif
125+
126+
public static void SetTitle(ReadOnlySpan<char> title) => Console.Title = new(title);
127+
128+
public static void Init() {
129+
#if WIN32
130+
SetTitle("SOURCE.NET DEDICATED SERVER");
131+
#if GMOD_DLL
132+
try {
133+
Console.OutputEncoding = Encoding.UTF8;
134+
}
135+
catch (IOException) {
136+
}
137+
#endif
138+
if (!AttachConsoleHandler())
139+
Console.Write("WARNING! TextConsole.Init: Could not attach console hook.\n");
140+
#else
141+
Msg("\n");
142+
#endif
143+
Msg("Console initialized.\n");
77144
}
78145
}
79146

@@ -93,6 +160,8 @@ public Bootloader() {
93160
isTextMode = commandLine.CheckParm("-textmode");
94161
}
95162
public void Boot() {
163+
TextConsole.Init();
164+
96165
engineAPI = new EngineBuilder(commandLine)
97166
// These assemblies have no reference to them, so they must be manually loaded.
98167
.WithAssembly("Source.VTF")

‎Source.Engine/DedicatedServerAPI.cs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ static string GetModDirFromPath(string path) {
2929

3030
Mod? dedicatedServer = null;
3131
IEngine eng = null!;
32+
Host? host;
33+
Host Host => host ??= services.GetRequiredService<Host>();
3234

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

7880
public void UpdateStatus(out float fps, out int active, out int maxPlayers, Span<char> map) {
79-
throw new NotImplementedException();
81+
Host.GetHostInfo(out fps, out active, out maxPlayers, map);
8082
}
8183

8284
public void UpdateHostname(Span<char> hostname) {
83-
throw new NotImplementedException();
85+
if (!hostname.IsEmpty)
86+
strcpy(hostname, sv.GetName());
8487
}
8588
}

‎Source.Engine/Host.cs‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,6 @@ void _RunFrame(TimeUnit_t time) {
287287
// else
288288
// updatedynamicmodels
289289

290-
#if !SWDS
291290
if (!sv.IsDedicated()) {
292291
ClientDLL.Update();
293292
}
@@ -298,7 +297,6 @@ void _RunFrame(TimeUnit_t time) {
298297
FrameCount++;
299298
Time = TickCount * host_state.IntervalPerTick + cl.TickRemainder;
300299
PostFrameRate(FrameTime);
301-
#endif
302300
}
303301
}
304302
public static void DefaultMapFileName(ReadOnlySpan<char> fullMapName, Span<char> diskName) {
@@ -309,7 +307,19 @@ public static void DefaultMapFileName(ReadOnlySpan<char> fullMapName, Span<char>
309307
private void PostFrameRate(TimeUnit_t frameTime) {
310308
frameTime = Math.Clamp(frameTime, 0.0001, 1.0);
311309
TimeUnit_t fps = 1.0 / frameTime;
312-
FramesPerSecond = fps * FPS_AVG_FRAC + (1.0 - FPS_AVG_FRAC) * fps;
310+
FramesPerSecond = FramesPerSecond * FPS_AVG_FRAC + (1.0 - FPS_AVG_FRAC) * fps;
311+
}
312+
313+
public void GetHostInfo(out float fps, out int active, out int maxPlayers, Span<char> map) {
314+
int clients = sv.GetNumClients();
315+
316+
fps = (float)FramesPerSecond;
317+
active = clients;
318+
319+
if (!map.IsEmpty)
320+
strcpy(map, sv.GetMapName());
321+
322+
maxPlayers = sv.GetMaxClients();
313323
}
314324

315325
private void UpdateMapList() {
@@ -1450,12 +1460,23 @@ void quit(in TokenizedCommand args) {
14501460
// EngineVGui.ConfirmQuit();
14511461
return;
14521462
}
1463+
#endif
14531464

1454-
// TODO: game events.
1455-
HostState.Shutdown();
1465+
IGameEvent? ev = g_GameEventManager.CreateEvent("host_quit");
1466+
if (ev != null)
1467+
g_GameEventManager.FireEventClientSide(ev);
1468+
1469+
#if GMOD_DLL
1470+
if (args.FindArg("keep_players") != null)
1471+
sv.KeepPlayers = true;
14561472
#endif
1473+
1474+
HostState.Shutdown();
14571475
}
14581476

1477+
[ConCommand("exit", "Exit the engine.")]
1478+
void exit(in TokenizedCommand args) => quit(in args);
1479+
14591480
readonly ConVar voice_recordtofile = new("voice_recordtofile", "0", 0, "Record mic data and decompressed voice data into 'voice_micdata.wav' and 'voice_decompressed.wav'");
14601481
readonly ConVar voice_inputfromfile;
14611482
readonly ConVar sv_allow_voice_from_file;

‎Source.Engine/Server/BaseServer.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,9 @@ public virtual void Shutdown() {
714714
State = ServerState.Dead;
715715

716716
// Only drop clients if we have not cleared out entity data prior to this.
717+
#if GMOD_DLL
718+
if (!KeepPlayers)
719+
#endif
717720
for (int i = Clients.Count - 1; i >= 0; i--) {
718721
BaseClient cl = Clients[i];
719722
if (cl.IsConnected())
@@ -1530,6 +1533,9 @@ protected bool ValidInfoChallenge(NetAddress adr, ReadOnlySpan<char> nugget) {
15301533
public InlineArray64<char> MapFilename; // map filename, may bear no resemblance to map name
15311534
public InlineArray64<char> Skyname; // skybox name
15321535
public InlineArray32<char> Password; // server password
1536+
#if GMOD_DLL
1537+
public bool KeepPlayers;
1538+
#endif
15331539

15341540
public MD5Value WorldmapMD5; // For detecting that client has a hacked local copy of map, the client will be dropped if this occurs.
15351541

‎Source.Engine/Sys.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,10 @@ private void Write(string group, ReadOnlySpan<char> str, in Color color, bool ro
138138
int bufferIdx = 0;
139139
void writeTxt(ReadOnlySpan<char> sub, in Color color) {
140140
#if DBGFLAG_WRITE_TO_STDOUT
141-
Console.Write(sub.Pastel(color));
141+
if (dedicated != null)
142+
dedicated.Sys_Printf(sub.Pastel(color));
143+
else
144+
Console.Write(sub.Pastel(color));
142145
#endif
143146
if (routeInGame) {
144147
host.Con?.ColorPrintf(in color, sub);

0 commit comments

Comments
 (0)