Triforce v0.8.5

A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-28 10:54:41 -06:00
parent 2df08c751e
commit b527e29adb
203 changed files with 18821 additions and 2051 deletions

View File

@@ -118,7 +118,7 @@ public sealed class Benchmark : IBenchmarkRunner
if (target != null && ctx.AllowedForGame(target))
{
if (backup == "none") File.Delete(target);
else if (backup != null && File.Exists(backup)) File.Copy(backup, target, true);
else if (backup != null && File.Exists(backup)) BenchIni.Restore(backup, target);
ctx.Log.Write("benchmark: the options file put back after a cut-off run: " + target);
}
File.Delete(Marker);
@@ -251,7 +251,7 @@ public sealed class Benchmark : IBenchmarkRunner
{
try
{
if (hadOptions) File.Copy(backup, ini, true); else if (File.Exists(ini)) File.Delete(ini);
if (hadOptions) BenchIni.Restore(backup, ini); else if (File.Exists(ini)) File.Delete(ini);
File.Delete(Marker);
}
catch (Exception e) { ctx.Log.Write("benchmark: putting the options back: " + e.Message); }
@@ -374,8 +374,9 @@ public sealed class Benchmark : IBenchmarkRunner
var tested = run.Scenes.Where(p => p.Helpers != null).ToList();
if (tested.Count == 0) return "";
static string Pct(HelperHalves h) => (h.OnFps / h.OffFps - 1).ToString("+0%;-0%;0%", CultureInfo.InvariantCulture);
var faster = tested.Where(p => p.Helpers!.Verdict == 1).Select(p => p.Place + " " + Pct(p.Helpers!)).ToList();
var slower = tested.Where(p => p.Helpers!.Verdict == -1).Select(p => p.Place + " " + Pct(p.Helpers!)).ToList();
// ((Triforce, 11-26) the verdict is HTML on the page: the places' names, read from the game's results file, encoded)
var faster = tested.Where(p => p.Helpers!.Verdict == 1).Select(p => Html(p.Place) + " " + Pct(p.Helpers!)).ToList();
var slower = tested.Where(p => p.Helpers!.Verdict == -1).Select(p => Html(p.Place) + " " + Pct(p.Helpers!)).ToList();
var s = $" With the {threads} replay helper threads on: ";
if (faster.Count == tested.Count) return s + $"faster everywhere ({string.Join(", ", faster)}).";
if (faster.Count == 0)
@@ -386,7 +387,9 @@ public sealed class Benchmark : IBenchmarkRunner
/// <summary>((Triforce, 11-19) the verdict's note for places left out ("" when none)</summary>
public static string SkippedNote(IReadOnlyList<string> skipped) => skipped.Count == 0 ? ""
: " " + string.Join(" and ", skipped) + (skipped.Count == 1 ? " was" : " were") + " left out: the game would not take Link there from your save.";
: " " + string.Join(" and ", skipped.Select(Html)) + (skipped.Count == 1 ? " was" : " were") + " left out: the game would not take Link there from your save.";
static string Html(string? s) => System.Net.WebUtility.HtmlEncode(s ?? "");
public static string Summary(IReadOnlyList<PlaceResult> p1, IReadOnlyList<PlaceResult>? p2, string? second)
{
@@ -396,8 +399,8 @@ public sealed class Benchmark : IBenchmarkRunner
if (p2 != null && second != null)
{
var w2 = p2.Min(r => r.OnePercentLow);
s += w2 >= w1 * 1.15 ? $" With {second} the slowest place holds {w2:0}, so it is worth turning on."
: $" {second} changed little here ({w2:0}), so it stays as it is.";
s += w2 >= w1 * 1.15 ? $" With {Html(second)} the slowest place holds {w2:0}, so it is worth turning on."
: $" {Html(second)} changed little here ({w2:0}), so it stays as it is.";
}
return s;
}
@@ -453,15 +456,34 @@ public static class BenchIni
return d;
}
/// <summary>((Triforce, 11-26) Every line of a key set, not only the first: the game reads the last one, so with a key twice the
/// value set was not the one used. The file's bytes kept as they are (Latin-1 round-trips every byte, as GameOptionsFile reads
/// it) and its line ends too.</summary>
public static void Set(string path, IReadOnlyDictionary<string, int> keys)
{
var lines = File.Exists(path) ? File.ReadAllLines(path).ToList() : new List<string>();
var left = new Dictionary<string, int>(keys);
var text = File.Exists(path) ? File.ReadAllText(path, Encoding.Latin1) : "";
var nl = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
var lines = text.Length == 0 ? new List<string>() : text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').ToList();
if (lines.Count > 0 && lines[^1].Length == 0) lines.RemoveAt(lines.Count - 1);
var done = new HashSet<string>(StringComparer.Ordinal);
for (var n = 0; n < lines.Count; n++)
if (lines[n].IndexOf('=') is var i and > 0 && left.Remove(lines[n][..i].Trim(), out var v)) lines[n] = lines[n][..i].Trim() + "=" + v.ToString(CultureInfo.InvariantCulture);
foreach (var (k, v) in left) lines.Add(k + "=" + v.ToString(CultureInfo.InvariantCulture));
if (lines[n].IndexOf('=') is var i and > 0 && lines[n][..i].Trim() is var k && keys.TryGetValue(k, out var v))
{
lines[n] = k + "=" + v.ToString(CultureInfo.InvariantCulture);
done.Add(k);
}
foreach (var (k, v) in keys) if (!done.Contains(k)) lines.Add(k + "=" + v.ToString(CultureInfo.InvariantCulture));
var fresh = path + ".new";
File.WriteAllText(fresh, string.Join("\n", lines) + "\n");
File.WriteAllText(fresh, string.Join(nl, lines) + nl, Encoding.Latin1);
File.Move(fresh, path, true);
}
/// <summary>((Triforce, 11-26) A backup put back in one step (through .new, then a move): a copy cut off half way left the
/// options file half written.</summary>
public static void Restore(string backup, string path)
{
var fresh = path + ".new";
File.Copy(backup, fresh, true);
File.Move(fresh, path, true);
}
}

View File

@@ -101,9 +101,11 @@ public static class BuildProtocol
var d = new Dictionary<string, double>();
foreach (var part in text.Split(", "))
{
var m = Regex.Match(part.Trim(), @"^(.*\S)\s+(\d+(?::\d{1,2}){1,2})$");
// ((Triforce, 11-26) digits 0-9, at most 9 of them in the first part: "x 99999999999:00" threw OverflowException in the
// build's output reader, which ended the launcher)
var m = Regex.Match(part.Trim(), @"^(.*\S)\s+([0-9]{1,9}(?::[0-9]{1,2}){1,2})$");
if (!m.Success) continue;
var secs = m.Groups[2].Value.Split(':').Aggregate(0.0, (acc, x) => acc * 60 + int.Parse(x));
var secs = m.Groups[2].Value.Split(':').Aggregate(0.0, (acc, x) => acc * 60 + int.Parse(x, System.Globalization.CultureInfo.InvariantCulture));
d[m.Groups[1].Value] = secs;
}
return d;

View File

@@ -166,6 +166,13 @@ public sealed class BuildRunner
// (stdout and stderr come on two threads: the state is changed under the lock, the App's handlers run outside it)
void Take(string l)
{
// ((Triforce, 11-26) a line that cannot be read, or a handler that throws, is logged: thrown in stderr's reader it
// ended the launcher, and in stdout's it was taken for a build that could not start while the build ran on unseen)
try { TakeOne(l); }
catch (Exception x) { try { ctx.Log.Write("build: a line of its output was not taken (" + x.GetType().Name + ": " + x.Message + "): " + (l.Length > 200 ? l.Substring(0, 200) : l)); } catch (Exception) { } }
}
void TakeOne(string l)
{
BuildEvent e;
string? was;

View File

@@ -355,7 +355,12 @@ public sealed class GameOptionsFile : IGameOptionValues
}
bool GpuNameDiffers(int v) =>
GameOptionsSchema.GpuNameOf(v) is { } name && (Raw(GameOptionsSchema.GpuNameKey) ?? "").Trim() != name;
GameOptionsSchema.GpuNameOf(v) is { } name && (Raw(GameOptionsSchema.GpuNameKey) ?? "").Trim() != AsFileText(name);
/// <summary>((Triforce, 11-26) A text as the file holds it: its UTF-8 bytes, each one char of the Latin-1 text the file is read and
/// written as. Written as Latin-1 directly, a GPU name with (R) or (TM) signs came out as other bytes, and the game, which reads the
/// file as UTF-8, did not find the card by its name.</summary>
static string AsFileText(string s) => Encoding.Latin1.GetString(Encoding.UTF8.GetBytes(s));
/// <summary>The benchmark's recommendations (key to value), each with Set's rules, in the order given. KeyNotFoundException,
/// and nothing set, for a key that is no row (nor a merged row's part). Returns the values afterwards, for the keys given.
@@ -411,7 +416,7 @@ public sealed class GameOptionsFile : IGameOptionValues
// ((Triforce) 11-20) the GPU device row's card by its name too: the game finds it by the name first, so the number
// counted in Windows' order (no triforce_gpus.txt before the game's first run) no longer picks another card. Auto: empty
if (set.TryGetValue(GameOptionsSchema.GpuKey, out var gpu))
write[GameOptionsSchema.GpuNameKey] = (GameOptionsSchema.GpuNameOf(gpu) ?? "").Replace('\r', ' ').Replace('\n', ' ');
write[GameOptionsSchema.GpuNameKey] = AsFileText((GameOptionsSchema.GpuNameOf(gpu) ?? "").Replace('\r', ' ').Replace('\n', ' '));
// (Custom's size is its two sides together: the launcher shows the pair as the game takes it (Effective: 7680x4320 in
// the file is 5120x2880), so a change of one side is a change of that pair. Written with only the changed side,
// 3840 beside the file's 4320 would be another size than the one shown. Both sides whenever either is written)

View File

@@ -686,17 +686,17 @@ public static class GameOptionsSchema
"The fullest picture the game can give, for a powerful PC: SMAA Ultra edges, 16x texture filtering, every texture whole, the shadows of distant grass and leaves as the game draws them, and soft shadows in corners and creases (ambient occlusion), and the grass, plants, flowers and stones drawn 4 times as far (in the areas you enter after it is turned on). Your own choices in those rows come back when it is off. F2 turns it on and off."),
// ((Triforce) Auto (this PC): auto_settings.h; its state is auto_tune and auto_for, kept keys)
Row(GameOptionTab.Graphics, "This PC", "Auto (this PC)", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
"On: the Upscaler, Render resolution, Texture detail, Shadow resolution and Grass distance are set for this PC's graphics card, memory and processor, and adjusted in the first minutes of play to hold the Frame rate cap. Changing one of those rows yourself turns it Off. The Render resolution and Upscaler apply after a restart."),
"On: the Upscaler, Render resolution, Texture detail, Shadow resolution and Grass distance are set for this PC's graphics card, memory and processor, and adjusted in the first minutes of play to hold the Frame rate cap. Changing one of those rows yourself turns it Off. The Upscaler and Render resolution take effect after Apply."),
Row(GameOptionTab.Graphics, "Upscaling", "Upscaler", 0, 9, 1, 0, GameOptionKind.Choice, TxUpscaler, false, false,
"What draws the 3D up to the Output resolution."),
"What draws the 3D up to the Output resolution. Takes effect after Apply."),
Row(GameOptionTab.Graphics, "Upscaling", "DLSS model", 0, 3, 1, 0, GameOptionKind.Choice, TxDlssModel, false, true,
"Which of NVIDIA's DLSS networks draws the picture."),
Row(GameOptionTab.Graphics, "Upscaling", "FSR 4 model", 0, 1, 1, 0, GameOptionKind.Choice, TxFsr4Model, false, true,
"The FSR 4 network: Auto lets AMD pick for this GPU, Lite is the faster INT8 network."),
Row(GameOptionTab.Graphics, "Upscaling", "Render resolution", 0, 6, 1, 0, GameOptionKind.Choice, TxResolution, true, false,
"The size the 3D is drawn at; the upscaler fills in the rest. Applies after a restart."),
Row(GameOptionTab.Graphics, "Upscaling", "Upscale before bloom", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, true, true,
"On: the upscaler works on the scene before the game's glow and tone mapping, which are then made at full size. Applies after a restart."),
Row(GameOptionTab.Graphics, "Upscaling", "Render resolution", 0, 6, 1, 0, GameOptionKind.Choice, TxResolution, false, false,
"The size the 3D is drawn at; the upscaler fills in the rest. Takes effect after Apply."),
Row(GameOptionTab.Graphics, "Upscaling", "Upscale before bloom", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
"On: the upscaler works on the scene before the game's glow and tone mapping, which are then made at full size. Evil HD's ambient occlusion and light shafts are not drawn with this on. Takes effect after Apply."),
Row(GameOptionTab.Graphics, "Upscaling", "Sharpness", 0, 100, 10, 0, GameOptionKind.Slider, TxPercent, false, false,
"With DLSS, DLAA or AMD FSR as the Upscaler, the 3D before the HUD (FSR's own sharpening; AMD's RCAS for DLSS); with the game's own upscaler, the picture at the window. 0 is off. Too much shows halos around edges."),
Row(GameOptionTab.Graphics, "Anti-aliasing", "Anti-aliasing", 0, 3, 1, 0, GameOptionKind.Choice, TxAa, false, true,
@@ -712,7 +712,7 @@ public static class GameOptionsSchema
"The most frames the game renders a second; made frames come on top. 60 is the safe choice: past it some cutscenes and bosses can misbehave. 30, 40 and 45 are for a PC that holds one of them where 60 swings. Monitor's rate: the refresh rate of the screen the game starts on. Uncapped: as fast as the PC can, still at real time; with VSync on, the screen's refresh rate is the limit. Changes at once."),
Row(GameOptionTab.Graphics, "Frame rate & latency", "VSync", 0, 2, 1, 1, GameOptionKind.Choice, TxVsync, false, true,
"Whether a finished frame waits for the screen's next refresh. Off: a little less delay, and the picture can tear. Every refresh: always the screen's own pacing (FIFO), for a display that tears or stutters otherwise. Changes at once."),
Merged(GameOptionTab.Graphics, "Frame rate & latency", "Frame pacing", 0, 3, 1, MergePacing, TxPacing, true, false,
Merged(GameOptionTab.Graphics, "Frame rate & latency", "Frame pacing", 0, 3, 1, MergePacing, TxPacing, false, false,
"When each frame is shown. Steady paces the game to a rate this PC holds where you are: steadier, at some frame rate."),
Merged(GameOptionTab.Graphics, "Frame rate & latency", "Low latency", 0, 2, 1, MergeLatency, TxLatency, false, false,
"Each frame starts as late as it can, for less input delay: NVIDIA Reflex on NVIDIA cards, AMD Anti-Lag 2 on AMD ones."),

View File

@@ -38,9 +38,14 @@ public sealed class Downloader
response.Headers.ETag is { IsWeak: false } tag ? tag.ToString()
: response.Content.Headers.LastModified is { } changed ? changed.UtcDateTime.ToString("r") : "";
/// <summary>url to file, with progress. size is what the release lists for it, 0 when it lists none.</summary>
public async Task ToFileAsync(HttpClient http, string url, string file, long size, Action<DownloadProgress>? progress, CancellationToken token)
/// <summary>url to file, with progress. size is what the release lists for it, 0 when it lists none. most: when size is 0, the
/// most the file may be (0: no limit); a server that offers or sends more is refused and nothing is kept. Only https.</summary>
public async Task ToFileAsync(HttpClient http, string url, string file, long size, Action<DownloadProgress>? progress, CancellationToken token, long most = 0)
{
// ((Triforce, 11-26) an address from a release feed or GameBanana's answer that is not https is not fetched: only the size
// was checked after it, which anyone on the way could match. A test's own server (http://127.0.0.1) in test runs only)
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && !(ctx.TestRoot != null && url.StartsWith("http://127.0.0.1", StringComparison.Ordinal)))
throw new IOException("Not downloaded: " + Path.GetFileName(file) + " is offered over an address that is not https (" + url + ").");
var name = Path.GetFileName(file);
var part = file + ".part";
var note = part + ".of";
@@ -103,6 +108,11 @@ public sealed class Downloader
Forget();
throw new IOException("The server offers " + other + " bytes as " + name + ", and the release lists " + size + ". Nothing was downloaded.");
}
if (size <= 0 && most > 0 && told is { } offered && offered > most)
{
Forget();
throw new IOException("The server offers " + Mb(offered) + " MB as " + name + ", more than the " + Mb(most) + " MB it can be. Nothing was downloaded.");
}
var total = size > 0 ? size : told ?? 0;
if (total > 0 && ctx.SpaceProblem(name, total - have, file) is { } none) throw new NoRoomException(none);
if (have == 0)
@@ -139,7 +149,7 @@ public sealed class Downloader
await to.WriteAsync(buffer.AsMemory(0, n), CancellationToken.None).ConfigureAwait(false);
have += n;
// (a server that sends more than the file would fill the disk)
if (total > 0 && have > total) { tooMuch = true; break; }
if (total > 0 && have > total || size <= 0 && most > 0 && have > most) { tooMuch = true; break; }
if (DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(150))
{
shown = DateTime.UtcNow;
@@ -161,7 +171,7 @@ public sealed class Downloader
if (tooMuch)
{
Forget();
throw new IOException("The server sent more than the " + total + " bytes of " + name + ". Nothing of it was kept.");
throw new IOException("The server sent more than the " + (total > 0 ? total : most) + " bytes of " + name + ". Nothing of it was kept.");
}
if (total > 0 && have < total)
throw new CutOffException("The download of " + name + " ended early, after " + Mb(have) + " of " + Mb(total) + " MB. Try again: it goes on from there.");
@@ -188,6 +198,22 @@ public sealed class Downloader
Say(1, have, have);
}
/// <summary>((Triforce, 11-26) A text answer (JSON) read whole, but no more than max bytes once unpacked: a compressed answer
/// of a few KB could unpack to gigabytes in ReadAsStringAsync. UTF-8, as the JSON answers are.</summary>
public static async Task<string> TextAsync(HttpContent content, int max, CancellationToken token)
{
if (content.Headers.ContentLength is { } n && n > max) throw new IOException("The server's answer is " + n + " bytes, more than the " + max + " it can be.");
await using var s = await content.ReadAsStreamAsync(token).ConfigureAwait(false);
using var m = new MemoryStream();
var buffer = new byte[81920];
for (int read; (read = await s.ReadAsync(buffer, token).ConfigureAwait(false)) > 0;)
{
m.Write(buffer, 0, read);
if (m.Length > max) throw new IOException("The server's answer is more than the " + max + " bytes it can be.");
}
return System.Text.Encoding.UTF8.GetString(m.GetBuffer(), 0, (int)m.Length);
}
/// <summary>The HttpClient every release request goes through: no overall timeout (a 300 MB download takes what it takes; the
/// release check has its own 20 s), the launcher's User-Agent (old Shell.cs Http).</summary>
public static HttpClient CreateHttp()

View File

@@ -7,7 +7,9 @@ namespace Triforce.Logic;
/// moved aside as &lt;name&gt;.old and removed after (a folder), and moved back when the new one cannot go in.</summary>
public sealed class Partial
{
public const string Suffix = ".partial", Aside = ".old";
// ((Triforce, 11-26) names only the launcher makes: with ".partial" and ".old", a copy into a save folder removed a folder the
// player had named "<save>.old" beside it, their own backup)
public const string Suffix = ".triforce-partial", Aside = ".triforce-old";
readonly IPlatform platform;
public Partial(IPlatform platform) { this.platform = platform; }

View File

@@ -94,8 +94,9 @@ public sealed class Uninstaller
/// <summary>The launcher's own files in its folder (del patterns): its exe, the copies an update or a handover leaves
/// (TriforceSetup.old.exe, TriforceSetup.exe.partial), and its log.</summary>
public static readonly string[] OwnFiles = { "TriforceSetup*.exe", "TriforceSetup*.exe.*", "setup.log", "setup.log.*" };
/// <summary>The folders it makes there (TriforceContext ToolsFolder, DownloadsFolder, NgxSdkFolder); save-backups stays (saves).</summary>
public static readonly string[] OwnFolders = { "tools", "downloads", "ngx-sdk" };
/// <summary>The folders it makes there (TriforceContext ToolsFolder, DownloadsFolder, NgxSdkFolder, Randomizer.WorkFolder: the
/// randomizer's kept choices and work); save-backups stays (saves). The seeds themselves are in the game's mods folder.</summary>
public static readonly string[] OwnFolders = { "tools", "downloads", "ngx-sdk", Randomizer.WorkFolder };
/// <summary>Is dir a folder of the launcher's alone, where its folders' names (downloads, tools) can only be its own? The
/// default install folder, or one named Triforce that is not a drive's root, the account's folder or one above it, nor one

View File

@@ -87,7 +87,8 @@ public sealed class GameBanana
{
using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
if (!r.IsSuccessStatusCode) throw new HttpRequestException("GameBanana answered " + (int)r.StatusCode, null, r.StatusCode);
return await r.Content.ReadAsStringAsync(token).ConfigureAwait(false);
// ((Triforce, 11-26) at most 8 MB unpacked: the answers come compressed, and one of a few KB could unpack to gigabytes)
return await Downloader.TextAsync(r.Content, 8 << 20, token).ConfigureAwait(false);
}
async Task<string> GetWithRetriesAsync(string url, bool retry, CancellationToken token)

View File

@@ -127,7 +127,8 @@ public sealed class GameBananaInstaller
{
var name = Path.GetFileName(d);
if (name.StartsWith('.')) continue;
if (ModManager.ReadInfo(d) is not { } info || info.GameBananaId != m.Id) continue;
// ((Triforce, 11-26) the same id and the same kind: GameBanana's mods and works in progress are numbered apart)
if (ModManager.ReadInfo(d) is not { } info || info.GameBananaId != m.Id || info.Wip != m.Wip) continue;
if (old.Count == 0)
{
var (off, num, _) = Mods.Parse(name);
@@ -137,10 +138,20 @@ public sealed class GameBananaInstaller
old.Add(d);
}
var aside = new List<(string Was, string Gone)>();
for (var k = 0; k < old.Count; k++) // (out of the way first: removed once the new one is in, put back if it fails)
// ((Triforce, 11-26) out of the way first, into mods\.removed as the Mods page's Remove does: kept there once the new one
// is in (a copy the player made and edited is never lost), put back if it fails)
var bin = Path.Combine(root, Mods.Removed);
for (var k = 0; k < old.Count; k++)
{
var gone = Path.Combine(stage, "old-" + k);
try { Directory.Move(old[k], gone); aside.Add((old[k], gone)); } catch (Exception e) { ctx.Log.Write("mods: the old " + old[k] + " could not be moved aside: " + e.Message); }
try
{
Directory.CreateDirectory(bin);
var gone = ModManager.Free(bin, Path.GetFileName(old[k]).TrimStart('-', '_') is { Length: > 0 } n ? n : "mod");
ctx.Require(gone);
Directory.Move(old[k], gone);
aside.Add((old[k], gone));
}
catch (Exception e) { ctx.Log.Write("mods: the old " + old[k] + " could not be moved aside: " + e.Message); }
}
var label0 = SafeName(m.Name);
if (number == 0) number = NextNumber(root);
@@ -168,6 +179,10 @@ public sealed class GameBananaInstaller
ctx.Log.Write("mods: installed " + m.Name + " (" + m.Id + ") into " + placed.Count + " folder(s), the first " + placed[0]);
var msg = "Installed into mods" + Path.DirectorySeparatorChar + Path.GetFileName(placed[0]) + ".";
if (placed.Count > 1) msg += " It came with " + placed.Count + " options: the first is on, the others are off. Choose on the Mods page.";
if (aside.Count > 0) msg += " The version before is kept in mods" + Path.DirectorySeparatorChar + Mods.Removed + ".";
// (code patches are built into the game: said, so a player knows what this one changes and when)
if (placed.Any(p => Directory.Exists(Path.Combine(p, "exefs")) && Directory.EnumerateFileSystemEntries(Path.Combine(p, "exefs")).Any()))
msg += " It changes the game's code (exefs): build the game again to apply it.";
return msg;
}
finally { Partial.Remove(stage); }
@@ -184,8 +199,10 @@ public sealed class GameBananaInstaller
ctx.Log.Write("mods: installing " + m.Name + " (" + m.Id + "), file " + f.Name + " (" + f.Bytes + " bytes) from " + f.Url);
try
{
// (the size the server names: GameBanana's listed size is not trusted to the byte)
await new Downloader(ctx).ToFileAsync(http, f.Url, archive, 0, progress, token).ConfigureAwait(false);
// (the size the server names: GameBanana's listed size is not trusted to the byte, but a server that offers or sends far
// more than it lists is refused, before the disk fills)
var most = f.Bytes > 0 ? f.Bytes * 2 + (256L << 20) : 16L << 30;
await new Downloader(ctx).ToFileAsync(http, f.Url, archive, 0, progress, token, most).ConfigureAwait(false);
var unpacked = Path.Combine(stage, "unpacked");
await Task.Run(() => mods.Unpack(within, archive, unpacked, null), token).ConfigureAwait(false);
return unpacked;

View File

@@ -82,8 +82,10 @@ public static class Mods
{
var off = folder.Length > 0 && (folder[0] == '-' || folder[0] == '_');
var rest = folder.TrimStart('-', '_');
var m = Regex.Match(rest, @"^(\d{2,3})-(.+)$", RegexOptions.Singleline);
return m.Success ? (off, int.Parse(m.Groups[1].Value), m.Groups[2].Value) : (off, null, rest);
// ((Triforce, 11-26) the digits 0 to 9 only: \d takes any script's digits ("01-" in full width), which int.Parse refuses,
// and one such folder emptied the Mods page and the seed list)
var m = Regex.Match(rest, @"^([0-9]{2,3})-(.+)$", RegexOptions.Singleline);
return m.Success ? (off, int.Parse(m.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture), m.Groups[2].Value) : (off, null, rest);
}
/// <summary>As the game compares names (host/mods.c mod_cmp, _stricmp): byte by byte, the letters A to Z without case.</summary>

View File

@@ -37,6 +37,10 @@ public sealed class LinuxPlatform : PlatformBase
Path.Combine(TestRoot == null && Env("HOOKSHOT_BUILDER_HOME") is { Length: > 0 } b ? b : DataHome, "triforce", "builder");
public override string WorkFolder => Path.Combine(CacheHome, "triforce-build");
/// <summary>((Triforce, 11-26) xdg-open from the system's folder when it is there: a bare name is looked up in the launcher's own
/// folder and the current one first, where any program of that name would run.</summary>
public static string XdgOpen => File.Exists("/usr/bin/xdg-open") ? "/usr/bin/xdg-open" : "xdg-open";
public override string DefaultGameFolder => Path.Combine(HomeDir, "Games", "Triforce");
public override string LogFolder(string home) => Path.Combine(StateHome, "triforce");
// (hookshot_builder.py ngx_sdk_dir: beside the builder's versions, kept across updates)
@@ -108,7 +112,7 @@ public sealed class LinuxPlatform : PlatformBase
}
protected override void OpenFolderNow(string folder) =>
Process.Start(new ProcessStartInfo("xdg-open") { ArgumentList = { folder }, UseShellExecute = false })?.Dispose();
Process.Start(new ProcessStartInfo(XdgOpen) { ArgumentList = { folder }, UseShellExecute = false })?.Dispose();
// ---- processes ----

View File

@@ -98,7 +98,7 @@ public sealed class WindowsPlatform : PlatformBase
try
{
if (process.HasExited) return;
using var k = Process.Start(new ProcessStartInfo("taskkill", "/PID " + process.Id + " /T /F") { CreateNoWindow = true, UseShellExecute = false });
using var k = Process.Start(new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "taskkill.exe"), "/PID " + process.Id + " /T /F") { CreateNoWindow = true, UseShellExecute = false });
k?.WaitForExit(5000);
}
catch (Exception)

View File

@@ -0,0 +1,237 @@
// (Triforce) OOTRR, the Ocarina of Time Remake Randomizer (github.com/ootrando/ootrr, GPL-3.0 as Triforce is), as the launcher's
// Randomizer page uses it: one release of its command-line program, downloaded on first use and checked against the SHA-256 this
// file names, then run for its settings (settings-dump), a seed (generate) and the seed's files (build, NX2navi's layout:
// <game>\mods\<name>\romfs, which host/mods.c reads). Nothing of OOTRR is in Triforce's source or its release.
//
// randomizer\ootrr\<version>\ootrr(.exe) the program, with its LICENSE, NOTICE and README, and portable.txt (OOTRR keeps its
// caches in a data folder beside itself, not in the user's profile). Not in tools:
// an update of the tools replaces that folder whole (11-26)
// downloads\ootrr\<release file> the release file while it downloads (Downloader: a stopped download goes on from its .part)
//
// A file whose hash is not the pinned one is deleted and never unpacked; only the program's own few files are taken out of it,
// flat into the folder, so nothing in the archive can reach outside it. Another OOTRR release is another pin here.
using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
namespace Triforce.Logic;
/// <summary>One file of an OOTRR release for one system: its name, size and SHA-256 (from the release's SHA256SUMS.txt, which
/// GitHub's build attestation ties to the tagged source).</summary>
public sealed record OotrrFile(string Name, long Size, string Sha256);
/// <summary>What OOTRR said when it did not do what it was asked: a whole sentence for the page.</summary>
public sealed class OotrrException : Exception
{
/// <summary>The code the program ended with, when it ran and refused; null when it never ran (not installed, not started) or
/// the launcher itself says no.</summary>
public int? Exit { get; }
public OotrrException(string message, int? exit = null) : base(message) { Exit = exit; }
}
/// <summary>A run of the program: its exit code and everything it printed.</summary>
public sealed record OotrrRun(int Exit, string Out, string Err);
public sealed class Ootrr
{
/// <summary>The release the launcher uses. To move to another: its version, and each file's size and SHA-256 from its
/// SHA256SUMS.txt (check them with `gh attestation verify &lt;file&gt; --repo ootrando/ootrr`).</summary>
public const string Version = "0.8.2";
public const string Repo = "https://github.com/ootrando/ootrr";
public static readonly OotrrFile Windows = new("OOTRR-0.8.2-windows-x64-portable.zip", 4694013, "0598aa5f7e3fe93e690437d936456a92c00e6d20b59a9bcd24fb2948afb6fbae");
public static readonly OotrrFile Linux = new("OOTRR-0.8.2-linux-x86_64.tar.gz", 4760078, "715ee19e1c6e2e487e1800106f8694fc7a756ebc725bd1b501e1256959c79136");
/// <summary>The files the launcher takes out of a release (the program by its name on each system; the others as they are).</summary>
static readonly string[] Keep = { "LICENSE", "NOTICE", "README.md", "portable.txt" };
const string Stamp = ".triforce-ootrr";
readonly TriforceContext ctx;
readonly Downloader downloader;
readonly OotrrFile? file;
/// <summary>file: the release file to fetch in place of the pinned one for this system (a test's own).</summary>
public Ootrr(TriforceContext ctx, Downloader? downloader = null, OotrrFile? file = null)
{
this.ctx = ctx;
this.downloader = downloader ?? new Downloader(ctx);
this.file = file;
}
public OotrrFile File => file ?? (ctx.IsWindows ? Windows : Linux);
public string ExeName => ctx.IsWindows ? "ootrr.exe" : "ootrr";
public string Folder => Path.Combine(ctx.Home, Randomizer.WorkFolder, "ootrr", Version);
/// <summary>Where the release file comes from: TRIFORCE_OOTRR_URL over GitHub's release page (a test's own server).</summary>
public string Url => (Env("TRIFORCE_OOTRR_URL") is { } u ? u.TrimEnd('/') : Repo + "/releases/download/v" + Version) + "/" + File.Name;
string? Env(string name) => ctx.Env(name) is { Length: > 0 } v ? v.Trim() : null;
/// <summary>The program to run: TRIFORCE_OOTRR_EXE (a test's or a developer's own: in a test run or a local build only, as it
/// runs any program), else the downloaded one. Null before the download (or when the folder holds a program that is not the
/// pinned release's).</summary>
public string? Exe
{
get
{
if (Env("TRIFORCE_OOTRR_EXE") is { } own && (ctx.TestRoot != null || BuildInfo.IsDev || ctx.Env("TRIFORCE_DEV") == "1"))
return System.IO.File.Exists(own) ? own : null;
var exe = Path.Combine(Folder, ExeName);
return System.IO.File.Exists(exe) && ReadStamp() == File.Sha256 ? exe : null;
}
}
public bool Have => Exe != null;
string? ReadStamp()
{
try { return System.IO.File.ReadAllText(Path.Combine(Folder, Stamp)).Trim(); } catch (Exception) { return null; }
}
/// <summary>Downloads the pinned release file, checks its hash and unpacks the program. progress: 0..1 of the download.</summary>
public async Task InstallAsync(HttpClient http, Action<DownloadProgress>? progress, CancellationToken token)
{
if (Have) return;
var f = File;
var file = Path.Combine(ctx.DownloadsFolder, "ootrr", f.Name);
ctx.Require(file);
ctx.Require(Folder);
await downloader.ToFileAsync(http, Url, file, f.Size, progress, token).ConfigureAwait(false);
string hash;
await using (var s = System.IO.File.OpenRead(file)) hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(s, token).ConfigureAwait(false));
if (hash != f.Sha256)
{
try { System.IO.File.Delete(file); } catch (Exception) { }
throw new OotrrException("The randomizer's download is not the file Triforce expects (its SHA-256 is " + hash + "). It was deleted and nothing was installed. Try again later.");
}
var temp = Folder + ".new";
if (Directory.Exists(temp)) Directory.Delete(temp, true);
Directory.CreateDirectory(temp);
try
{
if (f.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) UnpackZip(file, temp);
else await UnpackTarGz(file, temp, token).ConfigureAwait(false);
if (!System.IO.File.Exists(Path.Combine(temp, ExeName))) throw new OotrrException("The randomizer's download holds no " + ExeName + ". Nothing was installed.");
// (portable: OOTRR keeps its caches in a data folder beside itself, so removing the folder removes all of it)
var portable = Path.Combine(temp, "portable.txt");
if (!System.IO.File.Exists(portable)) System.IO.File.WriteAllText(portable, "OOTRR portable (written by Triforce's launcher)\n");
System.IO.File.WriteAllText(Path.Combine(temp, Stamp), f.Sha256 + "\n");
if (Directory.Exists(Folder)) Directory.Delete(Folder, true);
Directory.Move(temp, Folder);
}
catch
{
try { Directory.Delete(temp, true); } catch (Exception) { }
throw;
}
try { System.IO.File.Delete(file); } catch (Exception) { }
ctx.Log.Write("randomizer: OOTRR " + Version + " installed in " + Folder);
}
/// <summary>The name a release entry is taken out under (flat, in the folder), or null for an entry that is not kept.</summary>
internal string? KeptName(string entry)
{
var name = entry.Replace('\\', '/').TrimEnd('/');
var depth = name.Count(c => c == '/');
if (depth > 2 || name.Split('/').Any(p => p == ".." || p == ".")) return null;
var leaf = name.Substring(name.LastIndexOf('/') + 1);
if (leaf == ExeName) return leaf;
return Keep.FirstOrDefault(k => string.Equals(k, leaf, StringComparison.OrdinalIgnoreCase));
}
void UnpackZip(string file, string to)
{
using var zip = ZipFile.OpenRead(file);
foreach (var e in zip.Entries)
{
if (e.FullName.EndsWith('/')) continue;
var name = KeptName(e.FullName);
if (name == null) continue;
if (e.Length > 256L << 20) throw new OotrrException("The randomizer's download holds a file far larger than the program. Nothing was installed.");
e.ExtractToFile(Path.Combine(to, name), true);
}
}
async Task UnpackTarGz(string file, string to, CancellationToken token)
{
await using var s = System.IO.File.OpenRead(file);
await using var gz = new GZipStream(s, CompressionMode.Decompress);
using var tar = new TarReader(gz);
for (TarEntry? e; (e = await tar.GetNextEntryAsync(false, token).ConfigureAwait(false)) != null;)
{
if (e.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) continue;
var name = KeptName(e.Name);
if (name == null || e.DataStream == null) continue;
if (e.Length > 256L << 20) throw new OotrrException("The randomizer's download holds a file far larger than the program. Nothing was installed.");
var path = Path.Combine(to, name);
await using (var o = System.IO.File.Create(path)) await e.DataStream.CopyToAsync(o, token).ConfigureAwait(false);
if (!OperatingSystem.IsWindows() && name == ExeName)
System.IO.File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |
UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute);
}
}
/// <summary>Removes the downloaded program (the folder of this version, its data folder with it).</summary>
public void Remove()
{
ctx.Require(Folder);
if (Directory.Exists(Folder)) Directory.Delete(Folder, true);
}
// ---------------- running it ----------------
/// <summary>Runs the program with these arguments (each one whole, never through a shell) in its own folder. line: each line
/// it prints, as it prints it. Cancelling ends it. Throws OotrrException when it is not there or ends with an error, with the
/// error it printed.</summary>
public async Task<OotrrRun> RunAsync(IEnumerable<string> args, Action<string>? line, CancellationToken token)
{
var exe = Exe ?? throw new OotrrException("The randomizer is not installed yet.");
var si = new ProcessStartInfo(exe)
{
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8,
WorkingDirectory = Path.GetDirectoryName(Path.GetFullPath(exe))!,
};
foreach (var a in args) si.ArgumentList.Add(a);
// (OOTRR's own update check and browser stay off: the launcher runs commands, never its web page)
si.Environment["NO_COLOR"] = "1";
using var p = new Process { StartInfo = si };
var o = new StringBuilder();
var e = new StringBuilder();
// (a line handler that throws is logged: thrown on the reader's thread it would end the launcher)
p.OutputDataReceived += (_, d) =>
{
if (d.Data == null) return;
lock (o) o.AppendLine(d.Data);
try { line?.Invoke(d.Data); } catch (Exception x) { ctx.Log.Write("randomizer: a line of its output was not taken: " + x.Message); }
};
p.ErrorDataReceived += (_, d) => { if (d.Data == null) return; lock (e) e.AppendLine(d.Data); };
try { p.Start(); }
catch (Exception x) when (x is System.ComponentModel.Win32Exception || x is IOException)
{
throw new OotrrException("The randomizer could not be started: " + x.Message);
}
p.BeginOutputReadLine();
p.BeginErrorReadLine();
try { await p.WaitForExitAsync(token).ConfigureAwait(false); }
catch (OperationCanceledException)
{
// (it is gone before the caller takes its folders away: a build still writing would keep files open in them)
try { p.Kill(true); p.WaitForExit(5000); } catch (Exception) { }
throw;
}
p.WaitForExit(); // (the last lines of both streams are read)
var run = new OotrrRun(p.ExitCode, o.ToString(), e.ToString());
if (run.Exit != 0) throw new OotrrException(ErrorOf(run), run.Exit);
return run;
}
/// <summary>What a failed run says: its last line on the error stream that is not a warning, else on its output.</summary>
internal static string ErrorOf(OotrrRun run)
{
static string? Last(string text, bool skipWarnings) => text.Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0 &&
!(skipWarnings && l.StartsWith("warning:", StringComparison.OrdinalIgnoreCase))).LastOrDefault();
var why = Last(run.Err, true) ?? Last(run.Out, false) ?? "it ended with code " + run.Exit;
if (why.StartsWith("error:", StringComparison.OrdinalIgnoreCase)) why = why.Substring(6).Trim();
return "The randomizer stopped: " + why;
}
}

View File

@@ -0,0 +1,301 @@
// (Triforce) OOTRR's settings as its own `settings-dump` describes them, so the Randomizer page draws them as OOTRR has them
// (groups, labels, tips, choices, limits, what each depends on) and is right for whatever release Ootrr.cs pins:
// {schema_version, string_prefix, groups:[{id,label,tip}], settings:[{id,num,label,group,kind,tag,tip,default,choices?,min?,
// max?,max_by?,step?,times?,max_items?,deps:[{on,is|not|in}],disabled?,legacy?,unsupported?}], menu, presets:[{id,name,tip,
// order,settings}]}
// A setting whose dependencies do not hold is either left out (it means nothing then) or, when it names a "disabled" value, held
// at that value. The values the page keeps are a plain map id -> value; what goes to OOTRR (generate's settings file) is the
// values that differ from the defaults, after the held ones. OOTRR's menu (the dump's "menu") marks the options its build cannot
// apply yet ("live": false), its own presets among them in 0.8.2: those values are refused, and a preset or a pasted string that
// asks for one gets the default there, and says so (Gaps).
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Triforce.Logic;
public sealed record RandoGroup(string Id, string Label, string Tip);
public sealed record RandoChoice(string Id, string Label, string Tip);
/// <summary>One dependency: the setting on, and the values it must have (Not: must not have).</summary>
public sealed record RandoDep(string On, bool Not, IReadOnlyList<JsonNode?> Values);
public sealed class RandoSetting
{
public string Id { get; init; } = "";
public int Num { get; init; }
public string Label { get; init; } = "";
public string Group { get; init; } = "";
/// <summary>toggle, choice, multi, number or list.</summary>
public string Kind { get; init; } = "";
public string Tag { get; init; } = "";
public string Tip { get; init; } = "";
public JsonNode? Default { get; init; }
public IReadOnlyList<RandoChoice> Choices { get; init; } = Array.Empty<RandoChoice>();
public long Min { get; init; }
public long Max { get; init; }
public long Step { get; init; } = 1;
public string? MaxBy { get; init; }
/// <summary>A number that stands for a multiple: the value over Times (enemy health 150 with Times 100 is 1.5x). 0: a plain number.</summary>
public long Times { get; init; }
public int MaxItems { get; init; }
public IReadOnlyList<RandoDep> Deps { get; init; } = Array.Empty<RandoDep>();
/// <summary>The value held while the dependencies do not hold (null: the setting is left out then).</summary>
public JsonNode? Disabled { get; init; }
public bool HasDisabled { get; init; }
public bool Legacy { get; init; }
/// <summary>OOTRR's build does not apply it yet (its own menu marks it so).</summary>
public bool Unsupported { get; init; }
/// <summary>Values OOTRR's own menu marks as not working yet in this release (its "live": false options): a choice's id, or
/// "true" / "false" for a toggle. They are refused as values, so no seed asks the build for what it cannot do.</summary>
public IReadOnlySet<string> NotLive { get; init; } = new HashSet<string>();
public bool IsLive(string choice) => !NotLive.Contains(choice);
}
public sealed record RandoPreset(string Id, string Name, string Tip, int Order, JsonObject Settings);
/// <summary>How a setting shows with the values as they are: left out, held at a value (and why), or open.</summary>
public enum RandoState { Hidden, Held, Open }
public sealed class RandoSchema
{
public int Version { get; init; }
public string StringPrefix { get; init; } = "";
public IReadOnlyList<RandoGroup> Groups { get; init; } = Array.Empty<RandoGroup>();
public IReadOnlyList<RandoSetting> Settings { get; init; } = Array.Empty<RandoSetting>();
public IReadOnlyList<RandoPreset> Presets { get; init; } = Array.Empty<RandoPreset>();
public RandoSetting? Find(string id) => Settings.FirstOrDefault(s => s.Id == id);
static string Str(JsonNode? n, string key) => n?[key] is JsonValue v && v.TryGetValue<string>(out var s) ? s : "";
static long Num(JsonNode? n, string key, long otherwise) => n?[key] is JsonValue v && v.TryGetValue<long>(out var x) ? x : otherwise;
static bool Flag(JsonNode? n, string key) => n?[key] is JsonValue v && v.TryGetValue<bool>(out var b) && b;
/// <summary>settings-dump's JSON; FormatException for one without groups or settings.</summary>
public static RandoSchema Parse(string json)
{
JsonNode? root;
try { root = JsonNode.Parse(json); } catch (JsonException e) { throw new FormatException("The randomizer's settings could not be read: " + e.Message); }
if (root?["groups"] is not JsonArray groups || root["settings"] is not JsonArray settings || settings.Count == 0)
throw new FormatException("The randomizer's settings could not be read: no groups or no settings.");
var gs = groups.Select(g => new RandoGroup(Str(g, "id"), Str(g, "label"), Str(g, "tip"))).Where(g => g.Id.Length > 0).ToList();
var dead = new Dictionary<string, HashSet<string>>();
NotLiveIn(root["menu"], dead);
var ss = new List<RandoSetting>();
foreach (var s in settings)
{
if (s == null || Str(s, "id").Length == 0) continue;
var deps = (s["deps"] as JsonArray ?? new JsonArray()).Select(d =>
{
if (d?["in"] is JsonArray any) return new RandoDep(Str(d, "on"), false, any.Select(x => x?.DeepClone()).ToList());
if (d != null && ((JsonObject)d).ContainsKey("not")) return new RandoDep(Str(d, "on"), true, new[] { d["not"]?.DeepClone() });
return new RandoDep(Str(d, "on"), false, new[] { d?["is"]?.DeepClone() });
}).Where(d => d.On.Length > 0).ToList();
var obj = (JsonObject)s;
ss.Add(new RandoSetting
{
Id = Str(s, "id"), Num = (int)Num(s, "num", 0), Label = Str(s, "label"), Group = Str(s, "group"), Kind = Str(s, "kind"),
Tag = Str(s, "tag"), Tip = Str(s, "tip"), Default = s["default"]?.DeepClone(),
Choices = (s["choices"] as JsonArray ?? new JsonArray()).Select(c => new RandoChoice(Str(c, "id"), Str(c, "label"), Str(c, "tip"))).ToList(),
Min = Num(s, "min", 0), Max = Num(s, "max", 0), Step = Math.Max(1, Num(s, "step", 1)), MaxBy = Str(s, "max_by") is { Length: > 0 } mb ? mb : null, Times = Math.Max(0, Num(s, "times", 0)),
MaxItems = (int)Num(s, "max_items", 0), Deps = deps,
HasDisabled = obj.ContainsKey("disabled") && s["disabled"] != null, Disabled = s["disabled"]?.DeepClone(),
Legacy = Flag(s, "legacy"), Unsupported = Flag(s, "unsupported"),
NotLive = dead.TryGetValue(Str(s, "id"), out var nl) ? nl : new HashSet<string>(),
});
}
var ps = (root["presets"] as JsonArray ?? new JsonArray()).Where(p => p?["settings"] is JsonObject)
.Select(p => new RandoPreset(Str(p, "id"), Str(p, "name"), Str(p, "tip"), (int)Num(p, "order", 0), (JsonObject)p!["settings"]!.DeepClone()))
.OrderBy(p => p.Order).ToList();
return new RandoSchema { Version = (int)Num(root, "schema_version", 0), StringPrefix = Str(root, "string_prefix"), Groups = gs, Settings = ss, Presets = ps };
}
/// <summary>The menu's items with a setting's id and a view whose options say "live": false, anywhere in it: id -> those
/// options' values ("ours"; one with none stands for no value of OOTRR's and is not a choice).</summary>
static void NotLiveIn(JsonNode? n, Dictionary<string, HashSet<string>> dead)
{
if (n is JsonArray a) { foreach (var x in a) NotLiveIn(x, dead); return; }
if (n is not JsonObject o) return;
if (Str(o, "id") is { Length: > 0 } id && o["view"]?["opts"] is JsonArray opts)
foreach (var opt in opts)
if (Str(opt, "ours") is { Length: > 0 } ours && opt?["live"] is JsonValue lv && lv.TryGetValue<bool>(out var live) && !live)
(dead.TryGetValue(id, out var set) ? set : dead[id] = new HashSet<string>()).Add(ours);
foreach (var (_, v) in o) NotLiveIn(v, dead);
}
/// <summary>What a map asks for that this release cannot apply yet, or does not know: (the setting's label, the value asked
/// for, the value it gets). For a preset (each value it names) or a settings string read back.</summary>
public List<(string Setting, string Asked, string Gets)> Gaps(JsonObject asked)
{
var o = new List<(string, string, string)>();
foreach (var (k, v) in asked)
if (Find(k) is { } s && !s.Legacy && Clean(s, v) == null)
o.Add((s.Label, Show(s, v), Show(s, s.Default)));
return o;
}
public RandoPreset? Preset(string id) => Presets.FirstOrDefault(p => p.Id == id);
/// <summary>Every setting at its default.</summary>
public JsonObject Defaults()
{
var o = new JsonObject();
foreach (var s in Settings) o[s.Id] = s.Default?.DeepClone();
return o;
}
/// <summary>The defaults with a preset's values over them (a preset names only what it changes).</summary>
public JsonObject WithPreset(string id)
{
var o = Defaults();
var p = Presets.FirstOrDefault(x => x.Id == id) ?? throw new FormatException("The randomizer has no preset " + id + ".");
foreach (var (k, v) in p.Settings) if (Find(k) is { } s) o[k] = Clean(s, v) ?? s.Default?.DeepClone();
return o;
}
/// <summary>A saved map read back against this schema: settings it does not know are dropped, values it would refuse are the
/// defaults, missing ones the defaults.</summary>
public JsonObject Adopt(JsonObject? saved)
{
var o = Defaults();
if (saved == null) return o;
foreach (var (k, v) in saved) if (Find(k) is { } s && Clean(s, v) is { } ok) o[k] = ok;
return o;
}
static bool Same(JsonNode? a, JsonNode? b) => JsonNode.DeepEquals(a, b);
/// <summary>Does one dependency hold for these values?</summary>
static bool Holds(RandoDep d, JsonObject values)
{
var v = values[d.On];
var any = d.Values.Any(x => Same(x, v));
return d.Not ? !any : any;
}
public bool DepsHold(RandoSetting s, JsonObject values) => s.Deps.All(d => Holds(d, values));
/// <summary>How a setting shows with these values (its dependencies read from the values as held, in one pass in order).</summary>
public RandoState StateOf(RandoSetting s, JsonObject values) =>
DepsHold(s, values) ? RandoState.Open : s.HasDisabled ? RandoState.Held : RandoState.Hidden;
/// <summary>The values as OOTRR takes them: each held setting at its held value.</summary>
public JsonObject Effective(JsonObject values)
{
var o = (JsonObject)values.DeepClone();
// (a held value can make another's dependency fail: a few passes settle it, as the chain is short)
for (var pass = 0; pass < 4; pass++)
{
var changed = false;
foreach (var s in Settings)
if (s.HasDisabled && !DepsHold(s, o) && !Same(o[s.Id], s.Disabled)) { o[s.Id] = s.Disabled?.DeepClone(); changed = true; }
if (!changed) break;
}
// (a number no higher than another's value (max_by) comes down to it, on its own step, when that one is lower now: the
// value kept goes back up with it)
foreach (var s in Settings)
if (s.Kind == "number" && s.MaxBy != null && Whole(o[s.Id]) is { } n && n > MaxOf(s, o))
o[s.Id] = JsonValue.Create(Snap(s, MaxOf(s, o)));
return o;
}
/// <summary>The highest value on a number's step that is not above v (and not below its minimum).</summary>
public static long Snap(RandoSetting s, long v) => Math.Max(s.Min, s.Min + (long)Math.Floor((v - s.Min) / (double)Math.Max(1, s.Step)) * Math.Max(1, s.Step));
/// <summary>The settings file for generate: the effective values that differ from the defaults (legacy settings left out).</summary>
public JsonObject ForOotrr(JsonObject values)
{
var eff = Effective(values);
var o = new JsonObject();
// (a setting left out with the values as they are means nothing: it is not told, so it goes back to its default)
foreach (var s in Settings)
if (!s.Legacy && StateOf(s, eff) != RandoState.Hidden && eff[s.Id] is var v && !Same(v, s.Default)) o[s.Id] = v?.DeepClone();
return o;
}
/// <summary>The highest value a number may take with these values (max_by: no higher than another setting's value).</summary>
public long MaxOf(RandoSetting s, JsonObject values) =>
s.MaxBy != null && Whole(values[s.MaxBy]) is { } by ? Math.Min(s.Max, by) : s.Max;
/// <summary>A JSON number that is a whole number (5 or 5.0), whatever .NET type holds it; null for anything else.</summary>
public static long? Whole(JsonNode? v)
{
if (v is not JsonValue jv || jv.GetValueKind() != JsonValueKind.Number) return null;
var text = jv.ToJsonString();
if (long.TryParse(text, System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.CultureInfo.InvariantCulture, out var l)) return l;
return double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) &&
Math.Abs(d - Math.Round(d)) < 1e-9 && Math.Abs(d) < 1e15 ? (long)Math.Round(d) : null;
}
/// <summary>A value for a setting, as the setting takes it, or null when it does not (a toggle takes true or false; a choice one of
/// its ids; multi a list of its ids, each once; a number a whole number in its range and step; a list strings, so many at most).</summary>
public static JsonNode? Clean(RandoSetting s, JsonNode? v)
{
switch (s.Kind)
{
case "toggle":
return v is JsonValue b && b.TryGetValue<bool>(out var on) && s.IsLive(on ? "true" : "false") ? JsonValue.Create(on) : null;
case "choice":
return v is JsonValue c && c.TryGetValue<string>(out var id) && s.Choices.Any(x => x.Id == id) && s.IsLive(id) ? JsonValue.Create(id) : null;
case "multi":
if (v is not JsonArray m) return null;
var picked = new List<string>();
foreach (var x in m)
{
if (x is not JsonValue xv || !xv.TryGetValue<string>(out var xid) || !s.Choices.Any(ch => ch.Id == xid)) return null;
if (!picked.Contains(xid)) picked.Add(xid);
}
// (in the order OOTRR lists them, so a map compares equal whichever order they were ticked in)
return new JsonArray(s.Choices.Where(ch => picked.Contains(ch.Id)).Select(ch => (JsonNode?)JsonValue.Create(ch.Id)).ToArray());
case "number":
if (Whole(v) is not { } n || n < s.Min || n > s.Max || (n - s.Min) % s.Step != 0) return null;
return JsonValue.Create(n);
case "list":
if (v is not JsonArray a || a.Count > Math.Max(0, s.MaxItems)) return null;
var items = new JsonArray();
foreach (var x in a)
{
if (x is not JsonValue xv || !xv.TryGetValue<string>(out var t) || t.Length == 0 || t.Length > 200) return null;
items.Add(t);
}
return items;
default:
return null;
}
}
/// <summary>A value as the page shows it in a row: On / Off, a choice's label, the labels ticked (or None), the number.</summary>
public static string Show(RandoSetting s, JsonNode? v)
{
switch (s.Kind)
{
case "toggle": return v is JsonValue b && b.TryGetValue<bool>(out var on) && on ? "On" : "Off";
case "choice":
var id = v is JsonValue c && c.TryGetValue<string>(out var x) ? x : "";
return s.Choices.FirstOrDefault(ch => ch.Id == id)?.Label ?? id;
case "multi":
case "list":
var ids = (v as JsonArray ?? new JsonArray()).Select(n => n is JsonValue nv && nv.TryGetValue<string>(out var t) ? t : "").Where(t => t.Length > 0).ToList();
if (ids.Count == 0) return "None";
var labels = ids.Select(i => s.Choices.FirstOrDefault(ch => ch.Id == i)?.Label ?? i).ToList();
return labels.Count <= 3 ? string.Join(", ", labels) : string.Join(", ", labels.Take(2)) + " and " + (labels.Count - 2) + " more";
case "number": return Whole(v) is { } n ? Number(s, n) : v?.ToJsonString() ?? "";
default: return v?.ToJsonString() ?? "";
}
}
/// <summary>A number as the page shows it: a multiple as 1.5x, else the number.</summary>
public static string Number(RandoSetting s, long n) =>
s.Times > 0 ? (n / (double)s.Times).ToString("0.##", System.Globalization.CultureInfo.InvariantCulture) + "×" : n.ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>The preset these values are, or null (Custom).</summary>
public string? PresetOf(JsonObject values)
{
var eff = Effective(values);
foreach (var p in Presets)
{
var want = Effective(WithPreset(p.Id));
// (what either leaves out does not count)
if (Settings.All(s => StateOf(s, eff) == RandoState.Hidden && StateOf(s, want) == RandoState.Hidden || Same(eff[s.Id], want[s.Id]))) return p.Id;
}
return null;
}
}

View File

@@ -0,0 +1,382 @@
// (Triforce) The Randomizer page's seeds: made with OOTRR (Ootrr.cs) from the built game folder's own romfs and put in its mods
// folder as one mod each, so the game, the Mods page and a player arranging folders by hand all see the same thing:
// <game>\mods\Randomizer <seed>\romfs\... the seed's game files (OOTRR's build, NX2navi's layout)
// <game>\mods\Randomizer <seed>\ootrr\seed.ootrr the seed file (its settings string inside), spoiler.txt, settings.json
// <game>\mods\Randomizer <seed>\triforce_rando.json what the page lists it by: seed, settings string, OOTRR's version
// <game>\mods\Randomizer <seed>\triforce_mod.json its name, author and page on the Mods page
// The game reads only romfs (and exefs, cheats) under a mod, so the other files lie there unread. One seed is on at a time: making
// or choosing one switches the others off (ModManager's rename, "-" in front). Nothing is made while the game runs.
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Triforce.Logic;
/// <summary>The cosmetics OOTRR applies at build time (its --music, --sfx, --colors, --no-title-logo).</summary>
public sealed record RandoCosmetics(string Music = "off", string Sfx = "off", string Colors = "off", bool Title = true)
{
public static readonly string[] Shuffles = { "off", "grouped", "anywhere" };
public static readonly string[] ColorModes = { "off", "random" };
public RandoCosmetics Clean() => new(Shuffles.Contains(Music) ? Music : "off", Shuffles.Contains(Sfx) ? Sfx : "off", ColorModes.Contains(Colors) ? Colors : "off", Title);
}
/// <summary>A seed in the mods folder.</summary>
public sealed record RandoSeed(Mod Mod, string Seed, string Settings, string Version, DateTime? Made, RandoCosmetics Cosmetics, string Preset = "")
{
public string Files => Path.Combine(Mod.Path, Randomizer.FilesFolder);
public string Spoiler => Path.Combine(Files, "spoiler.txt");
public string SeedFile => Path.Combine(Files, "seed.ootrr");
}
/// <summary>A seed just made: it, and the mods that are on and carry some of its files (Wins: that mod sorts after it, so the game
/// takes that mod's copy).</summary>
public sealed record RandoMade(RandoSeed Seed, IReadOnlyList<(string Name, int Files, bool Wins)> Shared);
/// <summary>What the page keeps between runs: the settings, the seed text and the cosmetics (randomizer\choices.json in the launcher's folder).</summary>
public sealed class RandoChoices
{
public JsonObject? Values { get; set; }
public string Seed { get; set; } = "";
public RandoCosmetics Cosmetics { get; set; } = new();
}
public sealed class Randomizer
{
public const string Marker = "triforce_rando.json";
public const string FilesFolder = "ootrr";
public const string Prefix = "Randomizer ";
readonly TriforceContext ctx;
public Ootrr Tool { get; }
public ModManager Manager { get; }
public Randomizer(TriforceContext ctx, Ootrr? tool = null, ModManager? mods = null)
{
this.ctx = ctx;
Tool = tool ?? new Ootrr(ctx);
Manager = mods ?? new ModManager(ctx);
}
// ---------------- the settings OOTRR has ----------------
/// <summary>OOTRR's settings, from the installed program (settings-dump).</summary>
public async Task<RandoSchema> SchemaAsync(CancellationToken token)
{
var run = await Tool.RunAsync(new[] { "settings-dump", "--compact" }, null, token).ConfigureAwait(false);
return RandoSchema.Parse(run.Out);
}
/// <summary>A settings string (OOTRR1-...) read by OOTRR into values over the defaults, and what it warned about.</summary>
public async Task<(JsonObject Values, IReadOnlyList<string> Warnings)> DecodeAsync(RandoSchema schema, string text, CancellationToken token)
{
text = text.Trim();
if (text.Length == 0 || text.Length > 4000 || text.Any(char.IsWhiteSpace))
throw new OotrrException("That is not a settings string: one comes as a single word that starts with " + (schema.StringPrefix.Length > 0 ? schema.StringPrefix : "OOTRR") + ".");
var run = await Tool.RunAsync(new[] { "settings-dump", "--decode", text, "--compact" }, null, token).ConfigureAwait(false);
JsonNode? root;
try { root = JsonNode.Parse(run.Out); } catch (JsonException) { throw new OotrrException("The randomizer's answer could not be read."); }
var warnings = (root?["warnings"] as JsonArray ?? new JsonArray()).Select(w => w?.ToString() ?? "").Where(w => w.Length > 0).ToList();
var raw = root?["settings"] as JsonObject;
// (what this OOTRR cannot apply yet, or would refuse: the default there, and said)
if (raw != null) warnings.AddRange(schema.Gaps(raw).Select(g => g.Setting + ": " + g.Asked + " cannot be used with OOTRR " + Ootrr.Version + ", so it is " + g.Gets));
return (schema.Adopt(raw), warnings);
}
string? checkedFor, checkedSays;
/// <summary>Can OOTRR make a seed with these settings? It places a throwaway seed (a fraction of a second: generate only, no
/// build), so what it refuses is said before anything is written: null when it can, else what it says, in the settings' own
/// words (Friendly). OOTRR 0.8.2 refuses three of its own five presets this way. The answer is kept for the same settings, when
/// OOTRR gave one: a program that could not be run throws (OotrrException without Exit) and is asked again next time.</summary>
public async Task<string?> CheckAsync(RandoSchema schema, JsonObject values, CancellationToken token)
{
var settings = schema.ForOotrr(values).ToJsonString();
if (settings == checkedFor) return checkedSays;
var work = Path.Combine(ctx.Home, WorkFolder, "check");
ctx.Require(work);
Directory.CreateDirectory(work);
var file = Path.Combine(work, "settings.json");
await File.WriteAllTextAsync(file, settings, token).ConfigureAwait(false);
string? says = null;
try { await Tool.RunAsync(new[] { "generate", file, "check", Path.Combine(work, "check.ootrr") }, null, token).ConfigureAwait(false); }
catch (OotrrException e) when (e.Exit != null) { says = Friendly(schema, e.Message.StartsWith("The randomizer stopped: ", StringComparison.Ordinal) ? e.Message.Substring(24) : e.Message); }
(checkedFor, checkedSays) = (settings, says);
return says;
}
static readonly System.Text.RegularExpressions.Regex IsValue = new(@"\b([a-z][a-z0-9_]*) is ([a-z0-9_]+)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
static readonly System.Text.RegularExpressions.Regex Only = new(@"\(only ([a-z0-9_, ]+?) (and ([a-z0-9_]+) )?(works?)\)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>OOTRR's "bridge is stones, which this build cannot apply yet (only vanilla and dungeons work)" with the setting's and
/// its choices' labels: "Rainbow Bridge is Stones, which ... (only Vanilla and Rewards work)".</summary>
public static string Friendly(RandoSchema schema, string message)
{
var m = IsValue.Match(message);
if (!m.Success || schema.Find(m.Groups[1].Value) is not { } s) return message;
string Label(string id) => s.Choices.FirstOrDefault(c => c.Id == id.Trim())?.Label ?? id.Trim();
var o = message.Substring(0, m.Index) + s.Label + " is " + Label(m.Groups[2].Value) + message.Substring(m.Index + m.Length);
return Only.Replace(o, x =>
{
var list = x.Groups[1].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(Label).ToList();
if (x.Groups[3].Success) list.Add(Label(x.Groups[3].Value));
return "(only " + (list.Count > 1 ? string.Join(", ", list.Take(list.Count - 1)) + " and " + list[^1] : list.FirstOrDefault() ?? "") + " " + x.Groups[4].Value + ")";
});
}
// ---------------- what the page keeps ----------------
/// <summary>The launcher's own folder for the randomizer (in its folder, beside tools: Uninstaller.OwnFolders): the kept choices,
/// the check's throwaway seed, each seed's work while it is made.</summary>
public const string WorkFolder = "randomizer";
string ChoicesFile => Path.Combine(ctx.Home, WorkFolder, "choices.json");
public RandoChoices LoadChoices()
{
try
{
if (!File.Exists(ChoicesFile)) return new RandoChoices();
// (a file that is not an object of objects, written by hand or cut short, is no choices: the defaults)
if (JsonNode.Parse(File.ReadAllText(ChoicesFile)) is not JsonObject root) return new RandoChoices();
var cos = root["cosmetics"] as JsonObject;
string S(JsonObject? n, string k, string otherwise) => n?[k] is JsonValue v && v.TryGetValue<string>(out var s) ? s : otherwise;
return new RandoChoices
{
Values = root["values"] as JsonObject is { } vals ? (JsonObject)vals.DeepClone() : null,
Seed = S(root, "seed", "") is var seed && seed.Length <= MaxSeed && !seed.Any(char.IsControl) ? seed.Trim() : "",
Cosmetics = new RandoCosmetics(S(cos, "music", "off"), S(cos, "sfx", "off"), S(cos, "colors", "off"),
!(cos?["title"] is JsonValue t && t.TryGetValue<bool>(out var on) && !on)).Clean(),
};
}
catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException || e is InvalidOperationException)
{
ctx.Log.Write("randomizer: " + ChoicesFile + " could not be read: " + e.Message);
return new RandoChoices();
}
}
public void SaveChoices(RandoChoices c)
{
if (ctx.NoWrites || !ctx.Allowed(ChoicesFile)) return;
var o = new JsonObject
{
["values"] = c.Values?.DeepClone(),
["seed"] = c.Seed,
["cosmetics"] = new JsonObject { ["music"] = c.Cosmetics.Music, ["sfx"] = c.Cosmetics.Sfx, ["colors"] = c.Cosmetics.Colors, ["title"] = c.Cosmetics.Title },
};
try
{
Directory.CreateDirectory(Path.GetDirectoryName(ChoicesFile)!);
var tmp = ChoicesFile + ".new";
File.WriteAllText(tmp, o.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
File.Move(tmp, ChoicesFile, true);
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { ctx.Log.Write("randomizer: choices not kept: " + e.Message); }
}
// ---------------- seeds ----------------
/// <summary>A seed text for a new seed: eight letters and digits that read clearly (no 0/O, 1/I).</summary>
public static string RandomSeed()
{
const string abc = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
return string.Concat(Enumerable.Range(0, 8).Select(_ => abc[RandomNumberGenerator.GetInt32(abc.Length)]));
}
/// <summary>A seed text as a folder may carry it (OOTRR takes a mod name of letters, digits, space, _ - ! . and at most 64 of them;
/// the game leaves out a folder that starts with - or _).</summary>
public static string FolderName(string seed)
{
var chars = seed.Trim().Select(c => char.IsAsciiLetterOrDigit(c) || c == '-' || c == '!' ? c : c == ' ' || c == '_' || c == '.' ? ' ' : '-').ToArray();
var clean = string.Join(" ", new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries)).Trim('-', ' ');
while (clean.Contains("--")) clean = clean.Replace("--", "-");
if (clean.Length == 0) clean = "seed";
var name = Prefix + clean;
return name.Length <= 60 ? name : name.Substring(0, 60).TrimEnd(' ', '-');
}
/// <summary>A folder name for a new seed that no folder of the mods folder has yet, on or off (" 2", " 3" ... after it).</summary>
internal static string FreeName(string mods, string name)
{
bool Taken(string n) => new[] { n, "-" + n, "_" + n }.Any(x => Directory.Exists(Path.Combine(mods, x)) || File.Exists(Path.Combine(mods, x)));
if (!Taken(name)) return name;
for (var k = 2; ; k++) if (!Taken(name + " " + k)) return name + " " + k;
}
/// <summary>The seeds in a game folder's mods folder, in the game's order.</summary>
public List<RandoSeed> Seeds(string game)
{
var list = new List<RandoSeed>();
foreach (var m in Manager.ListGame(game, false))
if (Read(m) is { } s) list.Add(s);
return list;
}
static RandoSeed? Read(Mod m)
{
try
{
var file = Path.Combine(m.Path, Marker);
if (!File.Exists(file)) return null;
if (JsonNode.Parse(File.ReadAllText(file)) is not JsonObject r) return null;
// (the file lies in a folder anyone can write to: its texts are kept short, and the cosmetics are only the known ones)
string S(string k, int max = 400) => r[k] is JsonValue v && v.TryGetValue<string>(out var s) ? (s.Length <= max ? s : s.Substring(0, max)) : "";
DateTime? made = DateTime.TryParse(S("made"), null, System.Globalization.DateTimeStyles.RoundtripKind, out var d) ? d : null;
return new RandoSeed(m, S("seed", MaxSeed), S("settings", 8000), S("ootrr", 40), made,
new RandoCosmetics(S("music"), S("sfx"), S("colors"), !(r["title"] is JsonValue t && t.TryGetValue<bool>(out var on) && !on)).Clean(), S("preset", 80));
}
catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException || e is InvalidOperationException) { return null; }
}
static readonly string[] RomfsNeeds = { "Pack", "Banc", "Event", "System" };
/// <summary>The folder a seed is built in before it gets its name: a dot in front, so neither the game (host/mods.c) nor the
/// Mods page looks at it. A build stopped by anything (Stop, the launcher closed, the PC off) leaves only such a folder, and
/// the next seed takes it away: a half-made seed is never one the game loads.</summary>
public const string Making = ".making-";
/// <summary>The room a seed needs in the mods folder (a seed is 80 to 90 MB; with music or sounds shuffled, more).</summary>
public const long Room = 400L << 20;
/// <summary>The longest seed text taken.</summary>
public const int MaxSeed = 200;
/// <summary>Makes a seed and puts it in the game's mods folder, on, with every other seed off. preset: the name its settings
/// go by (a preset's, or Custom), kept with it. progress: a line for the page as OOTRR works.</summary>
public async Task<RandoMade> MakeAsync(string game, RandoSchema schema, JsonObject values, string seed, RandoCosmetics cos, Action<string>? progress, CancellationToken token, string? preset = null)
{
seed = seed.Trim();
if (seed.Length == 0) seed = RandomSeed();
if (seed.Length > MaxSeed) throw new OotrrException("That seed is too long: " + MaxSeed + " letters at most.");
if (seed.Any(char.IsControl)) throw new OotrrException("A seed cannot hold line breaks or other control characters.");
cos = cos.Clean();
var romfs = Path.Combine(game, "romfs");
if (!RomfsNeeds.All(d => Directory.Exists(Path.Combine(romfs, d))))
throw new OotrrException("The game folder has no complete romfs folder, which the randomizer reads. Build the game again first.");
if (Manager.GameRuns(game)) throw new OotrrException("Close the game first: it reads its mods when it starts.");
if (!Tool.Have) throw new OotrrException("The randomizer is not installed yet.");
var mods = Mods.FolderOf(game);
ctx.Require(mods);
Directory.CreateDirectory(mods);
if (ctx.SpaceProblem("The seed", Room, mods) is { } room) throw new OotrrException(room);
LeftOvers(mods);
var staging = Making + Guid.NewGuid().ToString("N").Substring(0, 10);
var building = Path.Combine(mods, staging);
var work = Path.Combine(ctx.Home, WorkFolder, "work", Guid.NewGuid().ToString("N").Substring(0, 12));
ctx.Require(work);
Directory.CreateDirectory(work);
string folder;
try
{
var settingsFile = Path.Combine(work, "settings.json");
var seedFile = Path.Combine(work, "seed.ootrr");
var spoiler = Path.Combine(work, "spoiler.txt");
await File.WriteAllTextAsync(settingsFile, schema.ForOotrr(values).ToJsonString(new JsonSerializerOptions { WriteIndented = true }), token).ConfigureAwait(false);
progress?.Invoke("Placing the items");
await Tool.RunAsync(new[] { "generate", settingsFile, seed, seedFile, "--spoiler", spoiler }, null, token).ConfigureAwait(false);
if (!File.Exists(seedFile)) throw new OotrrException("The randomizer made no seed file.");
string settingsString = "", generator = "";
try
{
var sf = JsonNode.Parse(await File.ReadAllTextAsync(seedFile, token).ConfigureAwait(false));
settingsString = sf?["settings"]?.ToString() ?? "";
generator = sf?["generator"]?.ToString() ?? "";
}
catch (JsonException) { }
progress?.Invoke("Writing the seed's game files");
var args = new List<string> { "build", seedFile, romfs, mods, staging, "--host", "nx2navi", "--music", cos.Music, "--sfx", cos.Sfx, "--colors", cos.Colors };
if (!cos.Title) args.Add("--no-title-logo");
await Tool.RunAsync(args, l => { if (l.Trim() is { Length: > 0 } t && t.Length < 200) progress?.Invoke(t); }, token).ConfigureAwait(false);
if (!Directory.Exists(Path.Combine(building, "romfs")) || !Directory.EnumerateFiles(Path.Combine(building, "romfs"), "*", SearchOption.AllDirectories).Any())
throw new OotrrException("The randomizer wrote no game files for the seed.");
// (an empty exefs folder from the build carries nothing: it goes, so the Mods page does not list one)
var exefs = Path.Combine(building, "exefs");
if (Directory.Exists(exefs) && !Directory.EnumerateFileSystemEntries(exefs).Any()) Directory.Delete(exefs);
var files = Path.Combine(building, FilesFolder);
Directory.CreateDirectory(files);
File.Copy(seedFile, Path.Combine(files, "seed.ootrr"), true);
File.Copy(settingsFile, Path.Combine(files, "settings.json"), true);
if (File.Exists(spoiler)) File.Copy(spoiler, Path.Combine(files, "spoiler.txt"), true);
var opts = new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
await File.WriteAllTextAsync(Path.Combine(building, Marker), new JsonObject
{
["seed"] = seed, ["settings"] = settingsString, ["ootrr"] = Ootrr.Version, ["generator"] = generator, ["preset"] = preset ?? "",
["made"] = DateTime.UtcNow.ToString("o"), ["music"] = cos.Music, ["sfx"] = cos.Sfx, ["colors"] = cos.Colors, ["title"] = cos.Title,
}.ToJsonString(opts), token).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(building, "triforce_mod.json"), new JsonObject
{
["name"] = "Randomizer · " + seed, ["author"] = "OOTRR " + Ootrr.Version, ["page"] = Ootrr.Repo,
}.ToJsonString(opts), token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
// (whole, it gets its name, off: "-" in front. Use then switches the other seeds off before this one on, so the game
// never finds two seeds on, even when a folder cannot be renamed. A folder of that name made meanwhile: the next free one)
folder = Path.Combine(mods, "-" + FreeName(mods, FolderName(seed)));
Directory.Move(building, folder);
}
finally
{
if (Directory.Exists(building))
try { Directory.Delete(building, true); } catch (Exception e) { ctx.Log.Write("randomizer: half-made " + building + " left (the game does not read it): " + e.Message); }
try { Directory.Delete(work, true); } catch (Exception) { }
}
var mine = Manager.ListGame(game, false).FirstOrDefault(m => SamePlace(m.Path, folder))
?? throw new OotrrException("The seed's folder is not where it was written: " + folder);
var s = Read(mine) ?? throw new OotrrException("The seed's folder has no " + Marker + ".");
string on;
try { on = Use(game, s); }
catch (Exception e) when (e is ModsException || e is IOException || e is UnauthorizedAccessException)
{
ctx.Log.Write("randomizer: seed " + seed + " made in " + folder + ", left off: " + e.Message);
throw new OotrrException("Seed " + seed + " is made, but it stays off: " + e.Message + " Turn it on in Your seeds once that is fixed.");
}
ctx.Log.Write("randomizer: seed " + seed + " made in " + on);
var now = Seeds(game).FirstOrDefault(x => SamePlace(x.Mod.Path, on)) ?? throw new OotrrException("The seed's folder is not where it was switched on: " + on);
return new RandoMade(now, Shared(game, now.Mod.Rel));
}
static bool SamePlace(string a, string b) =>
string.Equals(Path.GetFullPath(a).TrimEnd('\\', '/'), Path.GetFullPath(b).TrimEnd('\\', '/'), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>Takes away what a stopped build left in the mods folder (.making-*): never a folder the game reads. The page calls
/// it when it opens (while no seed is made), Make before each seed.</summary>
public void LeftOvers(string mods)
{
if (!ctx.Allowed(mods) || !Directory.Exists(mods)) return;
try
{
foreach (var d in Directory.GetDirectories(mods, Making + "*"))
try { Directory.Delete(d, true); ctx.Log.Write("randomizer: a stopped build's " + d + " taken away"); }
catch (Exception e) { ctx.Log.Write("randomizer: " + d + " could not be taken away: " + e.Message); }
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { }
}
/// <summary>The mods that are on and carry some of a seed's files, and whether each wins them.</summary>
public IReadOnlyList<(string Name, int Files, bool Wins)> Shared(string game, string rel)
{
var on = Manager.ListGame(game, true).Where(m => m.On).ToList();
var mod = on.FirstOrDefault(m => m.Rel == rel);
if (mod == null) return Array.Empty<(string, int, bool)>();
// (Mods.Shared says whether the seed wins; here it is whether the other mod does)
return Mods.Shared(mod, on, Mods.Conflicts(on)).Select(x => (x.Other.Info?.Name is { Length: > 0 } n ? n : x.Other.Name, x.Files, !x.Wins)).ToList();
}
/// <summary>Switches a seed on and every other seed off, the others first: a rename that fails leaves no two seeds on. Returns
/// the seed's folder now.</summary>
public string Use(string game, RandoSeed seed)
{
var mods = Mods.FolderOf(game);
foreach (var other in Seeds(game).Where(x => x.Mod.On && x.Mod.Rel != seed.Mod.Rel)) Manager.SetOn(mods, other.Mod, false);
// (switching the others off renames only their folders: this one is where it was)
var now = Seeds(game).FirstOrDefault(x => x.Mod.Rel == seed.Mod.Rel) ?? seed;
return now.Mod.On ? now.Mod.Path : Manager.SetOn(mods, now.Mod, true);
}
/// <summary>Switches every seed off: the game is the plain game again.</summary>
public void Off(string game)
{
var mods = Mods.FolderOf(game);
foreach (var s in Seeds(game).Where(x => x.Mod.On)) Manager.SetOn(mods, s.Mod, false);
}
/// <summary>Takes a seed out: its folder goes to mods\.removed, as the Mods page's Remove does.</summary>
public void Remove(string game, RandoSeed seed) => Manager.Remove(Mods.FolderOf(game), seed.Mod);
}

View File

@@ -102,7 +102,7 @@ public sealed class Release
using var response = await http.GetAsync(ApiUrl(ctx), both.Token).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.NotFound) throw new NoReleaseException();
response.EnsureSuccessStatusCode();
var r = Parse(await response.Content.ReadAsStringAsync(both.Token).ConfigureAwait(false));
var r = Parse(await Downloader.TextAsync(response.Content, 4 << 20, both.Token).ConfigureAwait(false));
if (r.Tag.Length == 0) throw new NoReleaseException(); // (an empty list: nothing published)
return r;
}
@@ -143,7 +143,8 @@ public static class ReleaseNotes
/// <summary>Markdown out: [text](link) -> text, `code` -> code, ** and __ gone, &amp;amp; and the like read.</summary>
public static string Plain(string s)
{
s = Regex.Replace(s, @"\[([^\]]*)\]\([^)]*\)", "$1");
// ((Triforce, 11-26) without backtracking: a long line of "[" took the regex quadratic time)
s = Regex.Replace(s, @"\[([^\]]*)\]\([^)]*\)", "$1", RegexOptions.NonBacktracking);
s = s.Replace("**", "").Replace("__", "").Replace("`", "");
s = WebUtility.HtmlDecode(s);
return Regex.Replace(s, @"\s+", " ").Trim();

View File

@@ -343,6 +343,8 @@ public sealed class Saves
var dst = Path.GetFullPath(to).TrimEnd('\\', '/');
ctx.Require(dst);
if (TriforceContext.SamePath(src, dst)) throw new InvalidOperationException("That is the same save folder.");
// ((Triforce, 11-26) one inside the other: the copy would copy itself without end, or replace the folder it reads)
if (TriforceContext.Inside(src, dst) || TriforceContext.Inside(dst, src)) throw new InvalidOperationException("One of those save folders is inside the other.");
var locking = ctx.Env("TRIFORCE_SAVE_LOCK") != "0";
using var dstLock = locking ? SaveLock.Take(dst) : null;
using var srcLock = locking && !string.Equals(SaveLock.PathOf(src), SaveLock.PathOf(dst), StringComparison.OrdinalIgnoreCase) ? SaveLock.Take(src) : null;
@@ -350,15 +352,27 @@ public sealed class Saves
Partial.Recover(dst);
var staged = partial.Stage(src, dst);
string? backup = null;
var safe = string.Concat(label.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c == ' ' ? '-' : c));
var stamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
try
{
if (Directory.Exists(dst) && Directory.EnumerateFileSystemEntries(dst).Any())
{
var safe = string.Concat(label.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c == ' ' ? '-' : c));
backup = Path.Combine(backupRoot, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + safe);
backup = Path.Combine(backupRoot, stamp + "_" + safe);
ctx.Require(backup);
Directory.CreateDirectory(backup);
CopyTree(dst, backup);
}
// ((Triforce, 11-26) into Triforce: a finished commit still waiting (save-tx\<uid>\ready-n) is the newest save, the one
// the game would load next, and it is taken away below. It is backed up too, as a save of its own)
if (WaitingCommit(dst) is { } waiting)
{
var newest = Path.Combine(backupRoot, stamp + "_" + safe + "-newest");
ctx.Require(newest);
Directory.CreateDirectory(newest);
CopyTree(waiting, newest);
backup ??= newest;
}
}
catch (Exception)
{
@@ -373,6 +387,20 @@ public sealed class Saves
return backup;
}
/// <summary>The newest finished commit waiting beside a Triforce save folder (save-tx\&lt;uid&gt;\ready-n), or null.</summary>
static string? WaitingCommit(string save)
{
try
{
if (TriforceTx(save) is not { } tx || !Directory.Exists(tx)) return null;
return Directory.GetDirectories(tx, "ready-*")
.Select(d => (Dir: d, M: Regex.Match(Path.GetFileName(d), @"^ready-(\d{1,9})$")))
.Where(r => r.M.Success && IsSaveSet(r.Dir))
.OrderByDescending(r => long.Parse(r.M.Groups[1].Value)).FirstOrDefault().Dir;
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { return null; }
}
static void CopyTree(string from, string to)
{
Directory.CreateDirectory(to);

View File

@@ -31,7 +31,8 @@ public sealed class TexturePack
{
public const string FolderName = "triforce_texpack";
public const string StateName = ".pack.json";
static readonly Regex FileName = new(@"^[0-9a-f]{16}(_m\d{1,2})?\.png$", RegexOptions.CultureInvariant);
// ((Triforce, 11-26) \z, not $: $ also matches before a last line break, so a name ending in a line break passed)
static readonly Regex FileName = new(@"^[0-9a-f]{16}(_m[0-9]{1,2})?\.png\z", RegexOptions.CultureInvariant);
static readonly Regex PartName = new(@"^[A-Za-z0-9._-]{1,80}\.zip$", RegexOptions.CultureInvariant);
readonly TriforceContext ctx;
@@ -78,7 +79,7 @@ public sealed class TexturePack
{
using var r = await http.GetAsync(BaseUrl + "/manifest.json", token).ConfigureAwait(false);
r.EnsureSuccessStatusCode();
return Parse(await r.Content.ReadAsStringAsync(token).ConfigureAwait(false));
return Parse(await Downloader.TextAsync(r.Content, 4 << 20, token).ConfigureAwait(false));
}
sealed record State(string Id, List<string> Done, bool Whole);
@@ -184,19 +185,30 @@ public sealed class TexturePack
{
if (e.FullName.EndsWith('/')) continue;
if (!FileName.IsMatch(e.FullName)) throw new InvalidDataException("a file Evil HD's textures do not have: " + e.FullName);
// (one picture is a few MB: an entry far larger is no picture of the pack's, whatever its name)
if (e.Length > 256L << 20) throw new InvalidDataException("a file far larger than a texture: " + e.FullName);
var dst = Path.Combine(folder, e.FullName);
e.ExtractToFile(dst + ".new", true);
File.Move(dst + ".new", dst, true);
}
}
/// <summary>The folder gone (the pack's pictures and its list); the game then draws its own textures.</summary>
/// <summary>The pack gone (its pictures, their .new leftovers and its list); the game then draws its own textures. ((Triforce,
/// 11-26) only files with a pack picture's name: anything else a player keeps in the folder (in folders of its own, or with
/// other names) stays, and the folder goes only when nothing is left in it.</summary>
public void Remove(string game)
{
var f = Folder(game);
if (!Directory.Exists(f)) return;
// (a link to a folder elsewhere, the lab's: only the link goes)
if (new DirectoryInfo(f).LinkTarget != null) { Directory.Delete(f); return; }
Directory.Delete(f, true);
foreach (var file in Directory.EnumerateFiles(f).ToList())
{
var name = Path.GetFileName(file);
if (name == StateName || FileName.IsMatch(name) || name.EndsWith(".new", StringComparison.Ordinal) && FileName.IsMatch(name.Substring(0, name.Length - 4)))
File.Delete(file);
}
if (!Directory.EnumerateFileSystemEntries(f).Any()) Directory.Delete(f);
else ctx.Log.Write("texture pack: removed; other files in " + f + " are kept");
}
}

View File

@@ -43,21 +43,25 @@ public sealed class Tools
try { return File.Exists(file) ? File.ReadLines(file).FirstOrDefault()?.Trim() : null; } catch (Exception) { return null; }
}
/// <summary>The tools to run make_game with, null when there are none. Windows: &lt;install&gt;\tools with its python\python.exe (or
/// "python" from the PATH when that file is missing); else, outside a test run, a development checkout above the exe
/// (TRIFORCE_PYTHON or "python"). Linux: HOOKSHOT_TOOLS, with HOOKSHOT_PYTHON or the image's usr/python/bin/python3.</summary>
/// <summary>The tools to run make_game with, null when there are none. Windows: &lt;install&gt;\tools with its python\python.exe;
/// else, in a local build outside a test run, a development checkout above the exe (TRIFORCE_PYTHON or "python"). Linux:
/// HOOKSHOT_TOOLS, with HOOKSHOT_PYTHON or the image's usr/python/bin/python3.</summary>
public ToolSet? Find()
{
var bundled = Folder;
if (File.Exists(Path.Combine(bundled, "nx2", "make_game.py")))
{
// ((Triforce, 11-26) Windows: the tools' own Python, by its full path even when it is missing (antivirus: GameIntake says
// so, and the start fails plainly). A bare "python" was looked up in the launcher's folder and the current folder first,
// where any python.exe would have run, or found the Store's alias, which ran nothing)
var py = ctx.IsWindows ? Path.Combine(bundled, "python", "python.exe") : Path.Combine(bundled, "python", "bin", "python3");
return new ToolSet(bundled, File.Exists(py) ? py : ctx.IsWindows ? "python" : "python3");
return new ToolSet(bundled, File.Exists(py) || ctx.IsWindows ? py : "python3");
}
if (!ctx.IsWindows && LinuxTools() is { } lt) return lt;
// (a development copy: the launcher run from inside a checkout uses its sources and the PC's Python. Never in a test run,
// which has its own tools or none)
if (ctx.TestRoot != null) return null;
// which has its own tools or none; ((Triforce, 11-26) and only for a local build or TRIFORCE_DEV=1: a release looked in
// every folder above its own, up to the drive's root, where another account could have put an nx2\make_game.py)
if (ctx.TestRoot != null || !(BuildInfo.IsDev || ctx.Env("TRIFORCE_DEV") == "1")) return null;
for (var d = new DirectoryInfo(ctx.SelfDir); d != null; d = d.Parent)
if (File.Exists(Path.Combine(d.FullName, "nx2", "make_game.py")))
return new ToolSet(d.FullName, ctx.Env("TRIFORCE_PYTHON") ?? (ctx.IsWindows ? "python" : "python3"));