-
Notifications
You must be signed in to change notification settings - Fork 4
/
ReplayWorker.cs
256 lines (216 loc) · 9.28 KB
/
ReplayWorker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace RoboBot
{
public enum ReplayStatus
{
Success,
BadDemo,
NoMap,
GameError,
UnhandledException
}
public class ReplayEventArgs : EventArgs
{
public ReplayStatus Status { get; }
public string OutputPath { get; }
public string ErrorMessage { get; }
public ReplayEventArgs(ReplayStatus status, string outputPath, string errorMessage)
{
Status = status;
OutputPath = outputPath;
ErrorMessage = errorMessage;
}
}
public class ReplayWorker
{
private Process GameProcess = new Process();
public static readonly string HomeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
public static readonly string ExecutableFolder22 = Path.Combine(HomeDir, "SRB2");
public static readonly string ExecutableFolder21 = Path.Combine(HomeDir, "SRB21");
public static string ExecutableFolder = ExecutableFolder22;
public static readonly string DataFolder22 = Path.Combine(HomeDir, ".srb2");
public static readonly string DataFolder21 = Path.Combine(HomeDir, ".srb2", ".srb21");
public static string DataFolder = DataFolder22;
public static readonly string LogFilePath22 = Path.Combine(DataFolder, "latest-log.txt");
public static readonly string LogFilePath21 = Path.Combine(DataFolder21, "log.txt");
public string LogFilePath = LogFilePath22;
public string[] CurrentGifFiles;
public string[] PreviousGifFiles;
public DirectoryInfo GifDir = new DirectoryInfo(Path.Combine(DataFolder22, "movies"));
public delegate void ReplayEventHandler(object sender, ReplayEventArgs args);
public event ReplayEventHandler Processed;
private List<Tuple<JobInfo, string, string>> queue;
private bool isStarted;
public void StartProcessing()
{
isStarted = true;
queue = new List<Tuple<JobInfo, string, string>>();
Task replayProcessingTask = new Task(ReplayProcesssingLoop);
replayProcessingTask.Start();
}
public void StopProcessing()
{
isStarted = false;
}
public void AddToQueue(JobInfo jobInfo, string replayPath, string outputPath)
{
queue.Add(Tuple.Create(jobInfo, replayPath, outputPath));
}
private async void ReplayProcesssingLoop()
{
while (isStarted)
{
if (queue.Count != 0)
{
Tuple<JobInfo, string, string> queueElement = queue.First();
try
{
ProcessReplay(queueElement.Item1, queueElement.Item2, queueElement.Item3);
}
finally
{
queue.Remove(queueElement);
}
}
await Task.Delay(1000);
}
}
private void RecordReplay(JobInfo replayInfo, string replayPath, string outputPath)
{
FileInfo[] gifInfos = GifDir.GetFiles().OrderBy(file => file.LastWriteTime).ToArray();
PreviousGifFiles = new string[gifInfos.Length];
for (int i = 0; i < gifInfos.Length; i++)
{
PreviousGifFiles[i] = gifInfos[i].Name;
}
try
{
byte[] bytes = File.ReadAllBytes(replayPath);
if(bytes[12] == 202)
{
ExecutableFolder = ExecutableFolder22;
DataFolder = DataFolder22;
LogFilePath = LogFilePath22;
}
else
{
ExecutableFolder = ExecutableFolder21;
DataFolder = DataFolder21;
LogFilePath = LogFilePath21;
}
File.WriteAllBytes(Path.Combine(DataFolder, "replay", "downloaded.lmp"), bytes);
string addons = "";
if(replayInfo.HasAddons)
{
addons = "-file ";
List<string> charactersDirectoryFiles = new List<string>(Directory.GetFiles("/root/.srb2/addons/Characters")
.Select(Path.GetFileName));
List<string> levelsDirectoryFiles = new List<string>(Directory.GetFiles("/root/.srb2/addons/Levels")
.Select(Path.GetFileName));
foreach (var addonfname in replayInfo.AddonsFileNames)
{
string addonName = System.Text.Encoding.ASCII.GetString(addonfname);
var charMatch = charactersDirectoryFiles.Where(stringToCheck => stringToCheck == addonName);
if (charMatch.Any())
{
addons += "Characters/";
};
var levelMatch = levelsDirectoryFiles.Where(stringToCheck => stringToCheck == addonName);
if (levelMatch.Any())
{
addons += "Levels/";
};
addons += addonName + ' ';
}
}
GameProcess.StartInfo.Arguments = "./reptovid -home /root -playdemo replay/downloaded.lmp " + addons + " -force -- :1";
GameProcess.StartInfo.FileName = "xinit";
GameProcess.StartInfo.WorkingDirectory = ExecutableFolder;
GameProcess.Start();
bool nomap = false;
string errorMessage = "";
do
{
Thread.Sleep(2000);
string logFile = File.ReadAllText(LogFilePath);
if (logFile.Contains("I_Error()"))
{
nomap = true;
//File.WriteAllText(LogFilePath, "a");
try { GameProcess.Kill(true); }
catch { }
}
if (logFile.Contains("Process killed by signal: "))
{
errorMessage = logFile.Split("Process killed by signal: ")[1];
// File.WriteAllText(LogFilePath, "a");
try { GameProcess.Kill(true); }
catch { }
}
}
while (!GameProcess.HasExited);
gifInfos = GifDir.GetFiles().OrderBy(file => file.LastWriteTime).ToArray();
CurrentGifFiles = new string[gifInfos.Length];
for (int i = 0; i < gifInfos.Length; i++)
{
CurrentGifFiles[i] = gifInfos[i].Name;
}
if (!CurrentGifFiles.SequenceEqual(PreviousGifFiles))
{
string gifPath = gifInfos.Last().FullName;
if(!string.IsNullOrEmpty(errorMessage))
InvokeEventAndCleanup(ReplayStatus.GameError, replayPath, gifPath, outputPath, errorMessage);
InvokeEventAndCleanup(ReplayStatus.Success, replayPath, gifPath, outputPath);
}
else
{
if(nomap)
{
InvokeEventAndCleanup(ReplayStatus.NoMap, replayPath);
}
else
{
InvokeEventAndCleanup(ReplayStatus.BadDemo, replayPath);
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
InvokeEventAndCleanup(ReplayStatus.UnhandledException, replayPath);
}
}
private void ProcessReplay(JobInfo jobInfo, string replayPath, string outputPath)
{
FileInfo finfo = new FileInfo(replayPath);
if (finfo.Extension.ToLower() == ".lmp")
{
RecordReplay(jobInfo, replayPath, outputPath);
}
else
{
InvokeEventAndCleanup(ReplayStatus.BadDemo, replayPath);
}
}
private void InvokeEventAndCleanup(ReplayStatus status, string replayPath = "", string gifPath = "", string outputPath = "", string errorMessage = "")
{
if (!String.IsNullOrEmpty(replayPath) && File.Exists(replayPath))
File.Delete(replayPath);
if (!String.IsNullOrEmpty(gifPath) && File.Exists(gifPath))
{
if (status != ReplayStatus.GameError)
File.Move(gifPath, outputPath, true);
File.Delete(gifPath);
}
Processed?.Invoke(this, new ReplayEventArgs(status, outputPath, errorMessage));
}
}
}