forked from Ellendar/Z2Randomizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
203 lines (173 loc) · 7.21 KB
/
Program.cs
File metadata and controls
203 lines (173 loc) · 7.21 KB
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
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using CrossPlatformUI;
using Desktop.Common;
using McMaster.Extensions.CommandLineUtils;
using NLog;
using Z2Randomizer.RandomizerCore;
using Z2Randomizer.RandomizerCore.Sidescroll;
namespace Z2Randomizer.CommandLine;
[RequiresUnreferencedCode("Newtonsoft.Json uses reflection")]
public class Program
{
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Program))]
public static int Main(string[] args)
=> CommandLineApplication.Execute<Program>(args);
[Option(ShortName = "f", Description = "Flag string")]
public string? Flags { get; set; }
[Option(ShortName = "r", Description = "Path to the base ROM file")]
public string? Rom { get; }
[Option(ShortName = "c", Description = "Path to a file containing the JSON for a RandomizerConfiguration. See the included examples.")]
public string? Configuration { get; }
[Option(ShortName = "o", Description = "Path to the folder to save the ROM")]
public string? OutputPath { get; }
[Option(ShortName = "s", Description = "[Optional] Seed used to generate the shuffled ROM")]
public int? Seed { get; set; }
[Option(ShortName = "po", Description = "[Optional] Specifies a player options file to use for misc settings")]
public string? PlayerOptions { get; }
private RandomizerConfiguration? configuration;
private byte[]? vanillaRomData;
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Program))]
public int OnExecute()
{
SetNlogLogLevel(LogLevel.Info);
if (Configuration == null)
{
if (string.IsNullOrEmpty(Flags))
{
logger.Error("The flag string is required");
return -1;
}
configuration = new RandomizerConfiguration(Flags);
}
else
{
if (!File.Exists(Configuration))
{
logger.Error($"The specified Configuration file does not exist: {Configuration}");
return -4;
}
string configurationString = File.ReadAllText(Configuration);
configuration = JsonSerializer.Deserialize(configurationString, SerializationContext.Default.RandomizerConfiguration);
}
if (!Seed.HasValue)
{
var r = new Random();
Seed = r.Next(1000000000);
}
configuration!.Seed = Seed.Value.ToString();
if (string.IsNullOrEmpty(Rom))
{
logger.Error("The ROM path is required");
return -2;
}
if (!File.Exists(Rom))
{
logger.Error($"The specified ROM file does not exist: {Rom}");
return -3;
}
vanillaRomData = File.ReadAllBytes(Rom);
try
{
var playerOptionsService = new PlayerOptionsService();
var playerOptions = playerOptionsService.LoadFromFile(this.PlayerOptions);
if (playerOptions == null)
{
throw new Exception("Could not load player options");
}
playerOptionsService.ApplyOptionsToConfiguration(playerOptions, configuration);
}
catch (Exception exception)
{
logger.Fatal(exception);
return -4;
}
if (Flags == null)
{
Flags = configuration.SerializeFlags();
}
logger.Info($"Flags: {Flags}");
logger.Info($"Rom: {Rom}");
logger.Info($"Seed: {Seed}");
Randomize().Wait();
return 0;
}
public async Task Randomize()
{
// Exception? generationException = null;
// var worker = new BackgroundWorker();
// worker.DoWork += new DoWorkEventHandler(RandomizationWorker!);
// worker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker1_ProgressChanged!);
// worker.WorkerReportsProgress = true;
// worker.WorkerSupportsCancellation = true;
// worker.RunWorkerCompleted += (completed_sender, completed_event) =>
// {
// generationException = completed_event.Error;
// };
// worker.RunWorkerAsync();
var cts = new CancellationTokenSource();
Hyrule.NewAssemblerFn createAsm = (opts, debug) => new DesktopJsEngine(opts, debug);
var roomsJson = RandomizerCore.Util.ReadAllTextFromFile("PalaceRooms.json");
var customJson = configuration!.UseCustomRooms ? RandomizerCore.Util.ReadAllTextFromFile("CustomRooms.json") : null;
var palaceRooms = new PalaceRooms(configuration!.UseCustomRooms ? customJson! : roomsJson, configuration!.UseCustomRooms);
var randomizer = new Hyrule(createAsm,palaceRooms);
var rom = await randomizer.Randomize(vanillaRomData!, configuration, UpdateProgress, cts.Token);
if (rom.romdata != null)
{
char os_sep = Path.DirectorySeparatorChar;
var filename = Rom!;
var outpath = OutputPath;
if (outpath == null)
{
// Try to get the file path of the input rom, if that fails, then just use the current dir.
outpath = filename.LastIndexOf(os_sep) != -1
? filename[..filename.LastIndexOf(os_sep)]
: Directory.GetCurrentDirectory();
}
string newFileName = $"{outpath}/Z2_{Seed}_{Flags}.nes";
await File.WriteAllBytesAsync(newFileName, rom.romdata);
logger.Info($"File {newFileName} has been created!");
if (rom.debuginfo != null)
{
var mlbfile = $"{outpath}/Z2_{Seed}_{Flags}.mlb";
await File.WriteAllTextAsync(mlbfile, rom.debuginfo);
logger.Info($"File {mlbfile} has been created!");
}
}
else
{
logger.Error("An exception occurred generating the rom");
}
}
private async Task UpdateProgress(string str)
{
await Task.Run(() => logger.Info(str));
}
private static void SetNlogLogLevel(LogLevel level)
{
// Uncomment these to enable NLog logging. NLog exceptions are swallowed by default.
////NLog.Common.InternalLogger.LogFile = @"C:\Temp\nlog.debug.log";
////NLog.Common.InternalLogger.LogLevel = LogLevel.Debug;
if (level == LogLevel.Off)
{
LogManager.SuspendLogging();
}
else
{
if (!LogManager.IsLoggingEnabled())
{
LogManager.SuspendLogging();
}
foreach (var rule in LogManager.Configuration!.LoggingRules)
{
// Iterate over all levels up to and including the target, (re)enabling them.
for (int i = level.Ordinal; i <= 5; i++)
{
rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
}
LogManager.ReconfigExistingLoggers();
}
}