Skip to content

Commit ba8fa01

Browse files
committed
Auto-generate configuration dialog, fix logger names, prepare for async initialization
1 parent 3f6f077 commit ba8fa01

50 files changed

Lines changed: 1945 additions & 582 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎NLog.config‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
<target xsi:type="File" name="keen" layout="${var:logStamp} ${logger}: ${var:logContent}" fileName="Logs\Keen-${shortdate}.log" />
1010
<target xsi:type="File" name="main" layout="${var:logStamp} ${logger}: ${var:logContent}" fileName="Logs\Torch-${shortdate}.log" />
1111
<target xsi:type="File" name="chat" layout="${longdate} ${message}" fileName="Logs\Chat.log" />
12-
<target xsi:type="ColoredConsole" name="console" layout="${var:logStamp} ${logger}: ${var:logContent}" />
12+
<target xsi:type="ColoredConsole" name="console" layout="${var:logStamp} ${logger:shortName=true}: ${var:logContent}" />
1313
<target xsi:type="File" name="patch" layout="${var:logContent}" fileName="Logs\patch.log"/>
1414
</targets>
1515

‎Torch.Server/Initializer.cs‎

Lines changed: 93 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ public class Initializer
2323
private const string STEAMCMD_ZIP = "temp.zip";
2424
private static readonly string STEAMCMD_PATH = $"{STEAMCMD_DIR}\\steamcmd.exe";
2525
private static readonly string RUNSCRIPT_PATH = $"{STEAMCMD_DIR}\\runscript.txt";
26+
2627
private const string RUNSCRIPT = @"force_install_dir ../
2728
login anonymous
2829
app_update 298740
@@ -69,7 +70,6 @@ public bool Initialize(string[] args)
6970
Console.Write(".");
7071
Thread.Sleep(1000);
7172
}
72-
7373
}
7474
catch
7575
{
@@ -86,17 +86,27 @@ public void Run()
8686
_server = new TorchServer(_config);
8787
try
8888
{
89-
_server.Init();
9089

90+
var initTask = Task.Run(() => { _server.Init(); });
9191
if (!_config.NoGui)
9292
{
93-
var ui = new TorchUI(_server);
94-
if (_config.Autostart)
93+
_server.Init();
94+
95+
if (!_config.NoGui)
96+
{
97+
var ui = new TorchUI(_server);
98+
if (_config.Autostart)
99+
_server.Start();
100+
ui.ShowDialog();
101+
}
102+
else
95103
_server.Start();
96-
ui.ShowDialog();
97104
}
98105
else
106+
{
107+
initTask.Wait();
99108
_server.Start();
109+
}
100110
}
101111
finally
102112
{
@@ -106,100 +116,101 @@ public void Run()
106116
}
107117
}
108118

109-
private TorchConfig InitConfig()
110-
{
111-
var configName = "Torch.cfg";
112-
var configPath = Path.Combine(Directory.GetCurrentDirectory(), configName);
113-
if (File.Exists(configName))
119+
private TorchConfig InitConfig()
114120
{
115-
Log.Info($"Loading config {configPath}");
116-
return TorchConfig.LoadFrom(configPath);
117-
}
118-
else
119-
{
120-
Log.Info($"Generating default config at {configPath}");
121-
var config = new TorchConfig { InstancePath = Path.GetFullPath("Instance") };
122-
config.Save(configPath);
123-
return config;
121+
var configName = "Torch.cfg";
122+
var configPath = Path.Combine(Directory.GetCurrentDirectory(), configName);
123+
if (File.Exists(configName))
124+
{
125+
Log.Info($"Loading config {configPath}");
126+
return TorchConfig.LoadFrom(configPath);
127+
}
128+
else
129+
{
130+
Log.Info($"Generating default config at {configPath}");
131+
var config = new TorchConfig {InstancePath = Path.GetFullPath("Instance")};
132+
config.Save(configPath);
133+
return config;
134+
}
124135
}
125-
}
126136

127-
private static void RunSteamCmd()
128-
{
129-
var log = LogManager.GetLogger("SteamCMD");
130-
131-
if (!Directory.Exists(STEAMCMD_DIR))
137+
private static void RunSteamCmd()
132138
{
133-
Directory.CreateDirectory(STEAMCMD_DIR);
134-
}
139+
var log = LogManager.GetLogger("SteamCMD");
135140

136-
if (!File.Exists(RUNSCRIPT_PATH))
137-
File.WriteAllText(RUNSCRIPT_PATH, RUNSCRIPT);
141+
if (!Directory.Exists(STEAMCMD_DIR))
142+
{
143+
Directory.CreateDirectory(STEAMCMD_DIR);
144+
}
138145

139-
if (!File.Exists(STEAMCMD_PATH))
140-
{
141-
try
146+
if (!File.Exists(RUNSCRIPT_PATH))
147+
File.WriteAllText(RUNSCRIPT_PATH, RUNSCRIPT);
148+
149+
if (!File.Exists(STEAMCMD_PATH))
142150
{
143-
log.Info("Downloading SteamCMD.");
144-
using (var client = new WebClient())
145-
client.DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", STEAMCMD_ZIP);
151+
try
152+
{
153+
log.Info("Downloading SteamCMD.");
154+
using (var client = new WebClient())
155+
client.DownloadFile("https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip", STEAMCMD_ZIP);
146156

147-
ZipFile.ExtractToDirectory(STEAMCMD_ZIP, STEAMCMD_DIR);
148-
File.Delete(STEAMCMD_ZIP);
149-
log.Info("SteamCMD downloaded successfully!");
157+
ZipFile.ExtractToDirectory(STEAMCMD_ZIP, STEAMCMD_DIR);
158+
File.Delete(STEAMCMD_ZIP);
159+
log.Info("SteamCMD downloaded successfully!");
160+
}
161+
catch
162+
{
163+
log.Error("Failed to download SteamCMD, unable to update the DS.");
164+
return;
165+
}
150166
}
151-
catch
167+
168+
log.Info("Checking for DS updates.");
169+
var steamCmdProc = new ProcessStartInfo(STEAMCMD_PATH, "+runscript runscript.txt")
170+
{
171+
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), STEAMCMD_DIR),
172+
UseShellExecute = false,
173+
RedirectStandardOutput = true,
174+
StandardOutputEncoding = Encoding.ASCII
175+
};
176+
var cmd = Process.Start(steamCmdProc);
177+
178+
// ReSharper disable once PossibleNullReferenceException
179+
while (!cmd.HasExited)
152180
{
153-
log.Error("Failed to download SteamCMD, unable to update the DS.");
154-
return;
181+
log.Info(cmd.StandardOutput.ReadLine());
182+
Thread.Sleep(100);
155183
}
156184
}
157185

158-
log.Info("Checking for DS updates.");
159-
var steamCmdProc = new ProcessStartInfo(STEAMCMD_PATH, "+runscript runscript.txt")
186+
private void LogException(Exception ex)
160187
{
161-
WorkingDirectory = Path.Combine(Directory.GetCurrentDirectory(), STEAMCMD_DIR),
162-
UseShellExecute = false,
163-
RedirectStandardOutput = true,
164-
StandardOutputEncoding = Encoding.ASCII
165-
};
166-
var cmd = Process.Start(steamCmdProc);
167-
168-
// ReSharper disable once PossibleNullReferenceException
169-
while (!cmd.HasExited)
170-
{
171-
log.Info(cmd.StandardOutput.ReadLine());
172-
Thread.Sleep(100);
173-
}
174-
}
188+
if (ex.InnerException != null)
189+
{
190+
LogException(ex.InnerException);
191+
}
175192

176-
private void LogException(Exception ex)
177-
{
178-
if (ex.InnerException != null)
179-
{
180-
LogException(ex.InnerException);
193+
Log.Fatal(ex);
194+
if (ex is ReflectionTypeLoadException exti)
195+
foreach (Exception exl in exti.LoaderExceptions)
196+
LogException(exl);
181197
}
182-
Log.Fatal(ex);
183-
if (ex is ReflectionTypeLoadException exti)
184-
foreach (Exception exl in exti.LoaderExceptions)
185-
LogException(exl);
186-
187-
}
188198

189-
private void HandleException(object sender, UnhandledExceptionEventArgs e)
190-
{
191-
var ex = (Exception)e.ExceptionObject;
192-
LogException(ex);
193-
Console.WriteLine("Exiting in 5 seconds.");
194-
Thread.Sleep(5000);
195-
LogManager.Flush();
196-
if (_config.RestartOnCrash)
199+
private void HandleException(object sender, UnhandledExceptionEventArgs e)
197200
{
198-
var exe = typeof(Program).Assembly.Location;
199-
_config.WaitForPID = Process.GetCurrentProcess().Id.ToString();
200-
Process.Start(exe, _config.ToString());
201+
var ex = (Exception)e.ExceptionObject;
202+
LogException(ex);
203+
Console.WriteLine("Exiting in 5 seconds.");
204+
Thread.Sleep(5000);
205+
LogManager.Flush();
206+
if (_config.RestartOnCrash)
207+
{
208+
var exe = typeof(Program).Assembly.Location;
209+
_config.WaitForPID = Process.GetCurrentProcess().Id.ToString();
210+
Process.Start(exe, _config.ToString());
211+
}
212+
213+
Process.GetCurrentProcess().Kill();
201214
}
202-
Process.GetCurrentProcess().Kill();
203215
}
204-
}
205-
}
216+
}

‎Torch.Server/Managers/InstanceManager.cs‎

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public void LoadInstance(string path, bool validate = true)
5959
var worldFolders = Directory.EnumerateDirectories(Path.Combine(Torch.Config.InstancePath, "Saves"));
6060

6161
foreach (var f in worldFolders)
62-
DedicatedConfig.Worlds.Add(new WorldViewModel(f, true));
62+
DedicatedConfig.Worlds.Add(new WorldViewModel(f));
6363

6464
if (DedicatedConfig.Worlds.Count == 0)
6565
{
@@ -92,7 +92,7 @@ private void ImportWorldConfig(WorldViewModel world, bool modsOnly = true)
9292
foreach (var mod in world.Checkpoint.Mods)
9393
sb.AppendLine(mod.PublishedFileId.ToString());
9494

95-
DedicatedConfig.Mods = sb.ToString();
95+
DedicatedConfig.Mods = world.Checkpoint.Mods.Select(x => x.PublishedFileId).ToList(); //sb.ToString();
9696

9797
Log.Debug("Loaded mod list from world");
9898

@@ -115,15 +115,15 @@ private void ImportWorldConfig(bool modsOnly = true)
115115
MyObjectBuilderSerializer.DeserializeXML(sandboxPath, out MyObjectBuilder_Checkpoint checkpoint, out ulong sizeInBytes);
116116
if (checkpoint == null)
117117
{
118-
Log.Error($"Failed to load {DedicatedConfig.LoadWorld}, checkpoint null ({sizeInBytes} bytes, instance {TorchBase.Instance.Config.InstancePath})");
118+
Log.Error($"Failed to load {DedicatedConfig.LoadWorld}, checkpoint null ({sizeInBytes} bytes, instance {Torch.Config.InstancePath})");
119119
return;
120120
}
121121

122122
var sb = new StringBuilder();
123123
foreach (var mod in checkpoint.Mods)
124124
sb.AppendLine(mod.PublishedFileId.ToString());
125125

126-
DedicatedConfig.Mods = sb.ToString();
126+
DedicatedConfig.Mods = checkpoint.Mods.Select(x => x.PublishedFileId).ToList(); //sb.ToString();
127127

128128
Log.Debug("Loaded mod list from world");
129129

@@ -144,18 +144,23 @@ public void SaveConfig()
144144

145145
try
146146
{
147-
MyObjectBuilderSerializer.DeserializeXML(Path.Combine(DedicatedConfig.LoadWorld, "Sandbox.sbc"), out MyObjectBuilder_Checkpoint checkpoint, out ulong sizeInBytes);
147+
var sandboxPath = Path.Combine(DedicatedConfig.LoadWorld, "Sandbox.sbc");
148+
MyObjectBuilderSerializer.DeserializeXML(sandboxPath, out MyObjectBuilder_Checkpoint checkpoint, out ulong sizeInBytes);
148149
if (checkpoint == null)
149150
{
150-
Log.Error($"Failed to load {DedicatedConfig.LoadWorld}, checkpoint null ({sizeInBytes} bytes, instance {TorchBase.Instance.Config.InstancePath})");
151+
Log.Error($"Failed to load {DedicatedConfig.LoadWorld}, checkpoint null ({sizeInBytes} bytes, instance {Torch.Config.InstancePath})");
151152
return;
152153
}
154+
155+
checkpoint.SessionName = DedicatedConfig.WorldName;
153156
checkpoint.Settings = DedicatedConfig.SessionSettings;
154157
checkpoint.Mods.Clear();
155158
foreach (var modId in DedicatedConfig.Model.Mods)
156159
checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(modId));
157160

158-
MyLocalCache.SaveCheckpoint(checkpoint, DedicatedConfig.LoadWorld);
161+
MyObjectBuilderSerializer.SerializeXML(sandboxPath, false, checkpoint);
162+
163+
//MyLocalCache.SaveCheckpoint(checkpoint, DedicatedConfig.LoadWorld);
159164
Log.Info("Saved world config.");
160165
}
161166
catch (Exception e)
@@ -185,35 +190,36 @@ public class WorldViewModel : ViewModel
185190
{
186191
public string FolderName { get; set; }
187192
public string WorldPath { get; }
193+
public long WorldSizeKB { get; }
188194
private string _checkpointPath;
189195
public CheckpointViewModel Checkpoint { get; private set; }
190196

191-
public WorldViewModel(string worldPath, bool loadCheckpointAsync = false)
197+
public WorldViewModel(string worldPath)
192198
{
193199
WorldPath = worldPath;
200+
WorldSizeKB = new DirectoryInfo(worldPath).GetFiles().Sum(x => x.Length) / 1024;
194201
_checkpointPath = Path.Combine(WorldPath, "Sandbox.sbc");
195202
FolderName = Path.GetFileName(worldPath);
196-
LoadCheckpointAsync();
203+
BeginLoadCheckpoint();
197204
}
198205

199206
public async Task SaveCheckpointAsync()
200207
{
201208
await Task.Run(() =>
202209
{
203210
using (var f = File.Open(_checkpointPath, FileMode.Create))
204-
MyObjectBuilderSerializer.SerializeXML(f, (MyObjectBuilder_Checkpoint)Checkpoint);
211+
MyObjectBuilderSerializer.SerializeXML(f, Checkpoint);
205212
});
206213
}
207214

208-
public async Task<CheckpointViewModel> LoadCheckpointAsync()
215+
private void BeginLoadCheckpoint()
209216
{
210-
Checkpoint = await Task.Run(() =>
217+
Task.Run(() =>
211218
{
212219
MyObjectBuilderSerializer.DeserializeXML(_checkpointPath, out MyObjectBuilder_Checkpoint checkpoint);
213-
return new CheckpointViewModel(checkpoint);
220+
Checkpoint = new CheckpointViewModel(checkpoint);
221+
OnPropertyChanged(nameof(Checkpoint));
214222
});
215-
OnPropertyChanged("Checkpoint");
216-
return Checkpoint;
217223
}
218224
}
219225
}

0 commit comments

Comments
 (0)