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

@@ -60,20 +60,32 @@ public sealed partial class Backend
"bench.go", new[] { ("no", "Not now", false), ("helpers", "With the helper-thread test", false), ("go", "Start", true) });
}
// ((Triforce, 11-26) 1 while a run is on its way: two clicks on Start ran two, and the second backed up the options the
// first had already changed, so the player's own settings were not put back)
int benchBusy;
async Task RunBench(bool compare, bool helperTest = false)
{
var g = GameDir;
if (g == null || benchCts != null) return;
if (g == null) return;
if (compare && benchRun == null) return;
using var cts = benchCts = new CancellationTokenSource();
var pic = new Saves(ctx).Newest(g) is { } newest ? SavePicUrl(newest) : null;
if (Interlocked.CompareExchange(ref benchBusy, 1, 0) != 0) return;
try { await RunBenchOne(g, compare, helperTest); }
finally { Interlocked.Exchange(ref benchBusy, 0); }
}
async Task RunBenchOne(string g, bool compare, bool helperTest)
{
var bm = new Benchmark(ctx);
(int, string)? second = null;
// (before the run is marked as running: a refusal here left benchCts set, and the page showed an empty run for good)
if (compare)
{
second = benchSecond ?? bm.SecondPass(g, BenchIni.Read(Path.Combine(g, GameOptionsSchema.FileName)));
if (second == null) { Toast("You already use an upscaler: there is nothing to compare it with.", "error"); return; }
}
using var cts = benchCts = new CancellationTokenSource();
var pic = new Saves(ctx).Newest(g) is { } newest ? SavePicUrl(newest) : null;
var t0 = DateTime.UtcNow;
void Running(string line) => Send(new JsonObject
{

View File

@@ -21,6 +21,13 @@ public sealed partial class Backend
// the working screen
CancellationTokenSource? workCts;
// ((Triforce, 11-26) 1 from the click that starts a build, a rebuild or an update until it ends: each command runs on a
// worker of its own, so a double click (or Enter held on Build the game) started two builds into one folder, and Stop
// reached only one. Taken with TakeWork, before anything else is done)
int workBusy;
bool TakeWork() => Interlocked.CompareExchange(ref workBusy, 1, 0) == 0;
void FreeWork() => Interlocked.Exchange(ref workBusy, 0);
int playStarting;
BuildRunner? runner;
string? workKind; // "build" | "update"
Func<Task>? retry;
@@ -72,12 +79,13 @@ public sealed partial class Backend
var d = new Dlss(ctx);
if (d.Chosen) { d.TurnOff(); SendReveal(); break; }
Ask("NVIDIA DLSS", "<p>" + H(d.LicenseText).Replace("\n\n", "</p><p>").Replace("\n", "<br>") + "</p>", "dlssanswer",
new[] { ("no", "Leave it out", false), ("yes", Dlss.AcceptLabel, true) });
new[] { ("no", "Leave it out", false), ("yes", Dlss.AcceptLabel, true) }, AskKey(ref dlssKey));
break;
}
});
On("lang", m => { if ((string?)m["id"] is { } code) { ctx.Settings.Language = code; SendReveal(); } });
On("dlssanswer", m => { if ((string?)m["id"] == "yes") new Dlss(ctx).Accept(); SendReveal(); });
// (only a language the game has: the code goes to the registry or builder.ini, which other programs read)
On("lang", m => { if (Languages.Find((string?)m["id"]) is { } l) { ctx.Settings.Language = l.Code; SendReveal(); } });
On("dlssanswer", m => { if ((string?)m["id"] == "yes" && Answered(ref dlssKey, m)) new Dlss(ctx).Accept(); SendReveal(); });
On("screen", _ => { });
On("open", m => OpenThing((string?)m["arg"] ?? ""));
On("report", _ => Copy(Report.ForBuild(ctx, lastResult, runner?.Details ?? "", new Tools(ctx).InstalledVersion, lastFailure)));
@@ -94,6 +102,7 @@ public sealed partial class Backend
On("uninstallanswer", m =>
{
if ((string?)m["id"] != "yes") { host.Close(); return; }
if (!Answered(ref uninstallKey, m)) return;
new Uninstaller(ctx).Run();
host.Close();
});
@@ -123,7 +132,7 @@ public sealed partial class Backend
{
var plan = new Uninstaller(ctx).Describe();
Ask("Uninstall Triforce?", "<p><b>Removes</b> " + H(string.Join(", ", plan.Removes)) + "</p><p><b>Keeps</b> " + H(string.Join(", ", plan.Keeps)) + "</p>",
"uninstallanswer", new[] { ("no", "Keep it", false), ("yes", "Uninstall", true) });
"uninstallanswer", new[] { ("no", "Keep it", false), ("yes", "Uninstall", true) }, AskKey(ref uninstallKey));
return;
}
var game = GameDir;
@@ -173,6 +182,12 @@ public sealed partial class Backend
Ask(workKind == "update" ? "Close Triforce and stop the update?" : "Close Triforce and stop the build?",
"<p>What is done so far is kept: next time it carries on from where it stopped.</p>", "closeanswer",
new[] { ("no", "Keep going", true), ("yes", "Stop and close", false) });
// ((Triforce, 11-25) a randomizer seed being made, or OOTRR being downloaded: asked too. A seed stopped part way is
// never one the game reads: it is built under a hidden name and named only when whole)
else if (randoCts != null || randoToolBusy)
Ask(randoCts != null ? "Close Triforce and stop the seed?" : "Close Triforce and stop the randomizer's download?",
randoCts != null ? "<p>The seed being made is not kept. Make it again any time.</p>" : "<p>It goes on from where it stopped next time.</p>", "closeanswer",
new[] { ("no", "Keep going", true), ("yes", "Stop and close", false) });
else host.Close();
}
@@ -180,6 +195,7 @@ public sealed partial class Backend
{
try { workCts?.Cancel(); } catch { }
try { runner?.Stop(); } catch { }
try { randoCts?.Cancel(); } catch { } // (a seed being made: OOTRR is ended, its half-made folder taken away)
}
// ---------------- first run: the game handed over ----------------
@@ -252,6 +268,13 @@ public sealed partial class Backend
async Task BuildFirst()
{
if (source == null) { Go("welcome"); return; }
if (!TakeWork()) { Go("work"); return; }
try { await BuildFirstOne(); }
finally { FreeWork(); }
}
async Task BuildFirstOne()
{
var space = new GameIntake(ctx).Space(outFolder!);
if (space.TooLittle) { Toast("Not enough room on " + H(space.Disk) + ": the build needs " + (space.NeedWhileBuilding >> 30) + " GB free.", "error"); return; }
retry = BuildFirst;
@@ -281,20 +304,24 @@ public sealed partial class Backend
{
var g = GameDir;
if (g == null) { Go("welcome"); return; }
if (workCts != null) { Go("work"); return; }
if (!TakeWork()) { Go("work"); return; }
_ = Guarded("rebuild", async () =>
{
retry = () => { StartRebuild(); return Task.CompletedTask; };
workKind = "update";
using var cts = workCts = new CancellationTokenSource();
try
{
await EnsureTools(cts.Token);
await RunBuild(BuildRequest.Update(g), cts.Token);
retry = () => { StartRebuild(); return Task.CompletedTask; };
workKind = "update";
using var cts = workCts = new CancellationTokenSource();
try
{
await EnsureTools(cts.Token);
await RunBuild(BuildRequest.Update(g), cts.Token);
}
catch (OperationCanceledException) { WorkStopped(); }
catch (Exception e) { WorkFailed("The build stopped", Failure.Of(e, false).Note, e); }
finally { workCts = null; }
}
catch (OperationCanceledException) { WorkStopped(); }
catch (Exception e) { WorkFailed("The build stopped", Failure.Of(e, false).Note, e); }
finally { workCts = null; }
finally { FreeWork(); }
});
}
@@ -486,7 +513,13 @@ public sealed partial class Backend
// ---------------- update ----------------
async Task UpdateNow(string? folder)
{
if (workCts != null) { Go("work"); return; }
if (!TakeWork()) { Go("work"); return; }
try { await UpdateNowOne(folder); }
finally { FreeWork(); }
}
async Task UpdateNowOne(string? folder)
{
if (release == null) await CheckRelease();
if (release == null) { Toast("Could not reach the update server. You can still play.", "error"); return; }
var rel = release;
@@ -570,6 +603,9 @@ public sealed partial class Backend
: new JsonObject { ["text"] = release != null ? "Up to date · " + built?.TrimStart('v') : built?.TrimStart('v') ?? "", ["dot"] = "" };
}
if (running) { home["button"] = "Running"; home["off"] = true; pill = new JsonObject { ["text"] = "Playing", ["dot"] = "blue" }; }
// ((Triforce, 11-25) a randomizer seed that is on, said where Play is, whatever else the screen says: a save of the
// plain game does not match it)
if (g != null && RandoSeedOn(g) is { } seed) links.Add(new JsonObject { ["html"] = "<b>&#9670; Randomizer seed " + H(seed) + "</b> is on", ["act"] = "go:rando" });
home["links"] = links;
if (release?.NewIn is { Count: > 0 } ni)
{
@@ -601,9 +637,18 @@ public sealed partial class Backend
// ---------------- Play ----------------
void Play()
{
// ((Triforce, 11-26) one start at a time: two clicks on Play started two games before the first was seen running)
if (Interlocked.CompareExchange(ref playStarting, 1, 0) != 0) return;
try { PlayOne(); }
finally { Interlocked.Exchange(ref playStarting, 0); }
}
void PlayOne()
{
var g = GameDir;
if (g == null) { Go("welcome"); return; }
if (Volatile.Read(ref workBusy) != 0) { Go("work"); return; } // (a build or an update is writing the game folder)
var game = new Game(ctx);
if (game.IsRunning(g)) { Go("playing"); ShowGame(); return; }
gameProc = game.Play(g);
@@ -643,6 +688,19 @@ public sealed partial class Backend
[System.Runtime.InteropServices.DllImport("user32")] static extern bool SetForegroundWindow(IntPtr h);
[System.Runtime.InteropServices.DllImport("user32")] static extern bool ShowWindow(IntPtr h, int c);
// ---------------- answers ----------------
// ((Triforce, 11-26) the questions whose yes cannot be undone (uninstall, the NVIDIA licence) carry a key of their own, made
// when they are asked and good once: a 'yes' the page sends without the question shown (a script that got into the page)
// does nothing. As saves.confirm does)
string? uninstallKey, dlssKey;
static string AskKey(ref string? slot) => slot = Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16));
static bool Answered(ref string? slot, JsonNode m)
{
var want = Interlocked.Exchange(ref slot, null);
var got = m["ctx"] is JsonValue v && v.TryGetValue<string>(out var s) ? s : null;
return want != null && got == want;
}
// ---------------- links ----------------
void OpenThing(string what)
{
@@ -652,7 +710,8 @@ public sealed partial class Backend
"changes" => release?.PageUrl ?? BuildInfo.Home,
_ => what.StartsWith("https://", StringComparison.Ordinal) ? what : null,
};
if (url != null) { try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch { } return; }
// (through OpenLink: https only, whatever the release feed or the page says; a test run opens nothing)
if (url != null) { OpenLink(url); return; }
var folder = what switch
{
"game" => GameDir,

View File

@@ -53,7 +53,16 @@ public sealed partial class Backend
});
}
// ((Triforce, 11-26) one change of the options file at a time: two sliders' values sent together each read, changed and
// wrote the file through one .new file, and one was lost or failed)
readonly object gameOptsGate = new();
void SetGameOption(string key, int v)
{
lock (gameOptsGate) SetGameOptionOne(key, v);
}
void SetGameOptionOne(string key, int v)
{
if (!CanChangeGame(out var f) || GameOptionsSchema.ByKey(key) == null) { RefreshSettingsState(); return; }
f!.Set(key, v);

View File

@@ -41,6 +41,20 @@ public sealed partial class Backend
});
}
/// <summary>((Triforce, 11-26) 1 while a GameBanana file is installed: two at once shared the mods folder's download folder,
/// and the second took away the first one's download and the version it had moved aside</summary>
int gbInstalling;
/// <summary>((Triforce, 11-26) A build or an update reads the mods folder (and records which code patches it built in): no
/// mod changes meanwhile. Says so and is true when refused.</summary>
bool RefusedWhileBuilding()
{
if (Volatile.Read(ref workBusy) == 0) return false;
Toast("Wait for the build to end: it reads the mods folder.", "error");
SendMods();
return true;
}
static string CardKey(GbMod m) => "gb:" + (m.Wip ? "w" : "m") + ":" + m.Id;
GbMod? CardOf(string id) { lock (modsGate) return gbCards.FirstOrDefault(c => CardKey(c) == id); }
@@ -283,7 +297,7 @@ public sealed partial class Backend
{
if (id == null) return;
if (GameDir is not { } game) { Toast("Build the game first: mods go into its mods folder.", "error"); return; }
if (modsBusy.ContainsKey(id)) return;
if (modsBusy.ContainsKey(id) || RefusedWhileBuilding()) return;
if (id.StartsWith("m:", StringComparison.Ordinal))
{
var mod = MineMods(game, true).FirstOrDefault(m => "m:" + m.Rel == id);
@@ -344,7 +358,9 @@ public sealed partial class Backend
async Task Install(string game, GbMod card, GbFile file)
{
var key = CardKey(card);
if (!modsBusy.TryAdd(key, "Downloading " + Size(file.Bytes))) return;
if (RefusedWhileBuilding()) return;
if (Interlocked.CompareExchange(ref gbInstalling, 1, 0) != 0) { Toast("One download at a time: wait for the one on its way.", "error"); return; }
if (!modsBusy.TryAdd(key, "Downloading " + Size(file.Bytes))) { Interlocked.Exchange(ref gbInstalling, 0); return; }
SendMods();
var last = DateTime.MinValue;
void Progress(DownloadProgress p)
@@ -367,6 +383,7 @@ public sealed partial class Backend
finally
{
modsBusy.TryRemove(key, out _);
Interlocked.Exchange(ref gbInstalling, 0);
SendMods();
}
}
@@ -390,7 +407,7 @@ public sealed partial class Backend
void ModsRemove(string? id)
{
if (id == null || GameDir is not { } game) return;
if (id == null || GameDir is not { } game || RefusedWhileBuilding()) return;
var all = MineMods(game, true);
List<Mod> list;
if (id.StartsWith("m:", StringComparison.Ordinal)) list = all.Where(m => "m:" + m.Rel == id).ToList();

View File

@@ -0,0 +1,520 @@
using System.Text.Json.Nodes;
using Triforce.Logic;
namespace Triforce.Launcher;
/// <summary>((Triforce, 11-25) The Randomizer page: OOTRR (Triforce.Logic.Ootrr, downloaded on first use and checked against its
/// pinned SHA-256) makes seeds of the game that can be beaten, from OOTRR's own settings (its settings-dump: groups, presets,
/// what depends on what), into the game folder's mods folder (Triforce.Logic.Randomizer). New seed: a preset or any setting, the
/// seed's text, cosmetics, a pasted settings string. Your seeds: one on at a time, its spoiler log (asked first), its settings
/// string, removed to mods\.removed as the Mods page does.</summary>
public sealed partial class Backend
{
Randomizer? rando;
Randomizer Rando => rando ??= new Randomizer(ctx);
RandoSchema? randoSchema;
RandoChoices randoChoices = new();
JsonObject randoValues = new();
int randoSchemaV;
bool randoLoaded, randoSchemaSent;
CancellationTokenSource? randoCts;
string randoLine = "", randoToolLine = "";
double randoToolFrac;
bool randoToolBusy;
readonly object randoGate = new();
/// <summary>What OOTRR says against the settings as they are (Randomizer.CheckAsync), null when it can make them.</summary>
string? randoProblem;
CancellationTokenSource? randoCheckCts;
readonly SemaphoreSlim randoCheckGate = new(1, 1);
/// <summary>Why OOTRR's settings could not be read (the page offers to try again), null when they were or no try was made.</summary>
string? randoSchemaError;
readonly SemaphoreSlim randoSchemaGate = new(1, 1);
/// <summary>1 while a seed is made / OOTRR is downloaded: two clicks (each command runs on a worker of its own) start one.</summary>
int randoMaking, randoInstalling;
void RegisterRandomizer()
{
OnAsync("rando.open", _ => RandoOpen());
OnAsync("rando.install", _ => RandoInstallAsk());
OnAsync("rando.install.go", m => (string?)m["id"] == "go" ? RandoInstall() : Task.CompletedTask);
On("rando.set", m => RandoSet((string?)m["id"], m["value"]));
// (the page's choice sheets answer {id: the choice, ctx: what it was for})
On("rando.pick", m => RandoSet((string?)m["ctx"], JsonValue.Create((string?)m["id"])));
On("rando.preset", m => RandoPreset((string?)m["id"]));
On("rando.preset.pick", m => RandoPreset((string?)m["id"]));
On("rando.cos.pick", m => RandoCos((string?)m["ctx"], (string?)m["id"]));
On("rando.reset", _ => { if (randoSchema is { } s) { lock (randoGate) randoValues = s.Defaults(); RandoKeep(); RandoCheckSoon(); } SendRando(); });
On("rando.seed", m => RandoSeedText((string?)m["text"] ?? ""));
On("rando.reseed", _ => { randoChoices.Seed = Randomizer.RandomSeed(); RandoKeep(); SendRando(); });
On("rando.cos", m => RandoCos((string?)m["key"], (string?)m["value"]));
OnAsync("rando.decode", m => RandoDecode((string?)m["text"] ?? ""));
OnAsync("rando.make", _ => RandoMake());
On("rando.stop", _ => { try { randoCts?.Cancel(); } catch { } });
On("rando.use", m => RandoSeedDo((string?)m["id"], "use"));
On("rando.off", _ => RandoAllOff());
On("rando.remove", m => RandoSeedDo((string?)m["id"], "remove"));
On("rando.copy", m => RandoSeedDo((string?)m["id"], "copy"));
On("rando.folder", m => RandoSeedDo((string?)m["id"], "folder"));
On("rando.spoiler", m =>
{
var id = (string?)m["id"];
if (RandoFind(id) == null) return;
Ask("Open the spoiler log?", "<p>It lists where every item of this seed is, and one way through the game. Open it only if you want to know.</p>",
"rando.spoiler.go", new[] { ("no", "Keep it closed", false), ("go", "Open it", true) }, id);
});
On("rando.spoiler.go", m => { if ((string?)m["id"] == "go") RandoSeedDo((string?)m["ctx"], "spoiler"); });
On("rando.page", _ => OpenLink(Ootrr.Repo));
}
// ---------------- state ----------------
/// <summary>The page's state. The settings' descriptions (labels, tips, choices) go once per program, the values each time.</summary>
JsonObject RandoPageState(bool withSchema)
{
var g = GameDir;
var tool = Rando.Tool;
var o = new JsonObject
{
["tool"] = new JsonObject
{
["have"] = tool.Have, ["version"] = Ootrr.Version, ["size"] = Size(tool.File.Size), ["busy"] = randoToolBusy,
["frac"] = randoToolFrac, ["line"] = randoToolLine,
},
["game"] = g != null, ["busy"] = randoCts != null, ["line"] = randoLine, ["schemaV"] = randoSchemaV, ["problem"] = randoProblem,
["schemaError"] = randoSchemaError, ["maxSeed"] = Randomizer.MaxSeed,
["seed"] = randoChoices.Seed,
["cos"] = new JsonObject { ["music"] = randoChoices.Cosmetics.Music, ["sfx"] = randoChoices.Cosmetics.Sfx, ["colors"] = randoChoices.Cosmetics.Colors, ["title"] = randoChoices.Cosmetics.Title },
};
var s = randoSchema;
if (s != null)
{
JsonObject values;
lock (randoGate) values = (JsonObject)randoValues.DeepClone();
var eff = s.Effective(values);
var rows = new JsonObject();
foreach (var x in s.Settings)
{
if (x.Legacy) continue;
var st = s.StateOf(x, eff);
var row = new JsonObject
{
["st"] = st switch { RandoState.Open => "open", RandoState.Held => "held", _ => "hidden" },
["v"] = eff[x.Id]?.DeepClone(), ["show"] = RandoSchema.Show(x, eff[x.Id]),
};
if (x.Kind == "number") row["max"] = s.MaxOf(x, eff);
if (st == RandoState.Held) row["why"] = "Set by " + string.Join(", ", x.Deps.Select(d => s.Find(d.On)?.Label ?? d.On).Distinct());
rows[x.Id] = row;
}
o["rows"] = rows;
o["preset"] = s.PresetOf(values);
o["changed"] = s.ForOotrr(values).Count;
if (withSchema)
{
o["schema"] = new JsonObject
{
["prefix"] = s.StringPrefix,
["groups"] = new JsonArray(s.Groups.Select(x => (JsonNode)new JsonObject { ["id"] = x.Id, ["label"] = x.Label, ["tip"] = x.Tip }).ToArray()),
["presets"] = new JsonArray(s.Presets.Select(x => (JsonNode)new JsonObject { ["id"] = x.Id, ["name"] = x.Name, ["tip"] = x.Tip }).ToArray()),
["settings"] = new JsonArray(s.Settings.Where(x => !x.Legacy && x.Kind != "list").Select(x =>
{
var j = new JsonObject
{
["id"] = x.Id, ["label"] = x.Label, ["group"] = x.Group, ["kind"] = x.Kind, ["tip"] = x.Tip, ["tag"] = x.Tag,
["unsupported"] = x.Unsupported,
};
if (x.Choices.Count > 0)
j["choices"] = new JsonArray(x.Choices.Select(c => (JsonNode)new JsonObject { ["id"] = c.Id, ["label"] = c.Label, ["tip"] = c.Tip, ["live"] = x.IsLive(c.Id) }).ToArray());
if (x.Kind == "toggle" && !x.IsLive("true")) j["noOn"] = true;
if (x.Kind == "number") { j["min"] = x.Min; j["max"] = x.Max; j["step"] = x.Step; if (x.Times > 0) j["times"] = x.Times; }
return (JsonNode)j;
}).ToArray()),
};
randoSchemaSent = true;
}
}
o["seeds"] = RandoSeedsState(g);
o["note"] = g == null ? "Build the game first: seeds go into its mods folder." : "";
return o;
}
JsonArray RandoSeedsState(string? g)
{
var arr = new JsonArray();
if (g == null) return arr;
List<RandoSeed> seeds;
try { seeds = Rando.Seeds(g); } catch (Exception e) { Log.Write("randomizer: seeds: " + e.Message); return arr; }
foreach (var x in seeds.OrderByDescending(x => x.Made ?? DateTime.MinValue))
{
var parts = new List<string> { x.Mod.On ? "On" : "Off" };
if (x.Preset.Length > 0) parts.Add(x.Preset);
if (x.Made is { } d) parts.Add("made " + d.ToLocalTime().ToString("d MMM yyyy, HH:mm", System.Globalization.CultureInfo.InvariantCulture));
if (x.Version.Length > 0) parts.Add("OOTRR " + x.Version);
if (x.Mod.OffAbove != null) parts.Add("off with its folder " + x.Mod.OffAbove);
arr.Add(new JsonObject
{
["id"] = x.Mod.Rel, ["seed"] = x.Seed, ["on"] = x.Mod.On, ["sub"] = string.Join(" · ", parts),
["settings"] = x.Settings, ["spoiler"] = File.Exists(x.Spoiler),
["cos"] = string.Join(", ", new[] { x.Cosmetics.Music != "off" ? "music " + x.Cosmetics.Music : "", x.Cosmetics.Sfx != "off" ? "sounds " + x.Cosmetics.Sfx : "",
x.Cosmetics.Colors != "off" ? "colors " + x.Cosmetics.Colors : "" }.Where(t => t.Length > 0)),
});
}
return arr;
}
void SendRando(bool withSchema = false)
{
JsonObject state;
try { state = RandoPageState(withSchema || !randoSchemaSent); }
// (the note is text: the page escapes it)
catch (Exception e) { Log.Write("randomizer: " + e); state = new JsonObject { ["note"] = e.Message, ["seeds"] = new JsonArray() }; }
SendState(new JsonObject { ["rando"] = state });
}
void RandoKeep()
{
// ((Triforce, 11-26) one save at a time: the page's commands run on workers of their own, and two saves wrote one .new file)
lock (randoGate)
{
randoChoices.Values = randoSchema != null ? randoSchema.ForOotrr(randoValues) : randoChoices.Values;
try { Rando.SaveChoices(randoChoices); } catch (Exception e) { Log.Write("randomizer: " + e.Message); }
}
}
/// <summary>The page opened: the kept choices, and OOTRR's settings once it is installed (read once a run).</summary>
async Task RandoOpen()
{
if (!randoLoaded)
{
randoChoices = Rando.LoadChoices();
if (randoChoices.Seed.Length == 0) randoChoices.Seed = Randomizer.RandomSeed();
randoLoaded = true;
}
// (a seed stopped by the launcher's close left its hidden build folder: it goes now, while no seed is made)
if (GameDir is { } g && Volatile.Read(ref randoMaking) == 0) Rando.LeftOvers(Mods.FolderOf(g));
await RandoLoadSchema();
SendRando(true);
}
async Task RandoLoadSchema()
{
if (randoSchema != null || !Rando.Tool.Have) return;
// (the page opened twice at once, or the download's end and an open: one read)
await randoSchemaGate.WaitAsync();
try
{
if (randoSchema != null) return;
var s = await Rando.SchemaAsync(CancellationToken.None);
lock (randoGate)
{
randoSchema = s;
// (the kept values are the ones that differed from the defaults: they go over this release's defaults; the first
// time, OOTRR's first preset)
randoValues = randoChoices.Values == null && s.Presets.Count > 0 ? s.WithPreset(s.Presets[0].Id) : s.Adopt(randoChoices.Values);
randoSchemaV++;
randoSchemaError = null;
}
RandoCheckSoon();
}
catch (Exception e) when (e is not OperationCanceledException)
{
Log.Write("randomizer: settings: " + e);
randoSchemaError = e.Message;
Toast("The randomizer's settings could not be read: " + H(e.Message), "error");
}
finally { randoSchemaGate.Release(); }
}
/// <summary>The seed's text, as typed: no longer than a seed may be, no line breaks.</summary>
void RandoSeedText(string text)
{
var t = new string(text.Where(c => !char.IsControl(c)).ToArray()).Trim();
if (t.Length > Randomizer.MaxSeed) { t = t.Substring(0, Randomizer.MaxSeed).Trim(); Toast("A seed is " + Randomizer.MaxSeed + " letters at most: the rest was left out."); }
randoChoices.Seed = t;
RandoKeep();
SendRando();
}
// ---------------- installing OOTRR ----------------
Task RandoInstallAsk()
{
if (Rando.Tool.Have || randoToolBusy) return Task.CompletedTask;
Ask("Get the randomizer",
"<p>Triforce's randomizer is <b>OOTRR</b>, the Ocarina of Time Remake Randomizer by its own team (free software, GPL-3.0, as Triforce is).</p>" +
"<p><b>" + H(Rando.Tool.File.Name) + "</b>, " + Size(Rando.Tool.File.Size) + ", is downloaded from its release on GitHub, checked against the fingerprint " +
"Triforce knows for it, and unpacked into the launcher's tools folder. It reads your game files on this PC only; nothing is uploaded.</p>",
"rando.install.go", new[] { ("no", "Not now", false), ("go", "Download", true) });
return Task.CompletedTask;
}
async Task RandoInstall()
{
if (Rando.Tool.Have || Interlocked.CompareExchange(ref randoInstalling, 1, 0) != 0) return;
randoToolBusy = true; randoToolFrac = 0; randoToolLine = "Downloading";
SendRando();
var last = DateTime.MinValue;
try
{
await Rando.Tool.InstallAsync(http, p =>
{
randoToolFrac = p.Fraction; randoToolLine = "Downloading, " + (int)(p.Fraction * 100) + " %";
if ((DateTime.UtcNow - last).TotalMilliseconds < 400) return;
last = DateTime.UtcNow;
SendRando();
}, CancellationToken.None);
randoToolLine = "Reading its settings";
SendRando();
await RandoLoadSchema();
Toast("<b>&#9670;</b> The randomizer is ready · OOTRR " + H(Ootrr.Version), "success");
Sfx("success");
}
catch (Exception e) when (e is OotrrException || e is HttpRequestException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException || e is TaskCanceledException || e is NoRoomException || e is InvalidDataException)
{
Log.Write("randomizer: install: " + e);
Toast("The randomizer could not be installed: " + H(e.Message), "error");
}
finally { randoToolBusy = false; randoToolLine = ""; Interlocked.Exchange(ref randoInstalling, 0); SendRando(true); }
}
// ---------------- the settings ----------------
void RandoSet(string? id, JsonNode? value)
{
var s = randoSchema;
if (s == null || id == null || s.Find(id) is not { } x) return;
if (x.Legacy) return;
var v = RandoSchema.Clean(x, value);
if (v == null)
{
var asked = value is JsonValue jv && jv.TryGetValue<string>(out var sid) ? sid : value?.ToJsonString() ?? "";
Toast(!x.IsLive(asked) ? "OOTRR " + H(Ootrr.Version) + " cannot apply <b>" + H(RandoSchema.Show(x, value)) + "</b> for " + H(x.Label) + " yet."
: "That value does not fit " + H(x.Label) + ".", "error");
SendRando();
return;
}
if (x.Kind == "number" && RandoSchema.Whole(v) is { } n)
{
JsonObject now;
lock (randoGate) now = s.Effective(randoValues);
if (n > s.MaxOf(x, now)) v = JsonValue.Create(RandoSchema.Snap(x, s.MaxOf(x, now)));
}
lock (randoGate) randoValues[id] = v;
RandoKeep();
RandoCheckSoon();
SendRando();
}
/// <summary>Asks OOTRR, a moment after the last change, whether it can make the settings as they are; the card says what it
/// refuses and Make the seed waits until it can.</summary>
void RandoCheckSoon()
{
var s = randoSchema;
if (s == null || !Rando.Tool.Have) return;
try { randoCheckCts?.Cancel(); } catch { }
var cts = randoCheckCts = new CancellationTokenSource();
JsonObject values;
lock (randoGate) values = (JsonObject)randoValues.DeepClone();
_ = Task.Run(async () =>
{
try
{
await Task.Delay(250, cts.Token);
await randoCheckGate.WaitAsync(cts.Token);
string? says;
try { says = await Rando.CheckAsync(s, values, cts.Token); }
finally { randoCheckGate.Release(); }
if (cts.IsCancellationRequested) return;
if (says != randoProblem) { randoProblem = says; SendRando(); }
}
catch (OperationCanceledException) { }
catch (Exception e) { Log.Write("randomizer: check: " + e.Message); }
});
}
void RandoPreset(string? id)
{
var s = randoSchema;
if (s == null || id == null || s.Presets.All(p => p.Id != id)) return;
lock (randoGate) randoValues = s.WithPreset(id);
RandoKeep();
RandoCheckSoon();
var p = s.Presets.First(x => x.Id == id);
var gaps = s.Gaps(p.Settings);
Toast("Settings: <b>" + H(p.Name) + "</b>" + (gaps.Count == 0 ? "" : " · " + H(string.Join("; ", gaps.Select(g => g.Setting + " is " + g.Gets + " (" + g.Asked + " needs a newer OOTRR)")))));
SendRando();
}
void RandoCos(string? key, string? value)
{
var c = randoChoices.Cosmetics;
randoChoices.Cosmetics = (key switch
{
"music" => c with { Music = value ?? "off" },
"sfx" => c with { Sfx = value ?? "off" },
"colors" => c with { Colors = value ?? "off" },
"title" => c with { Title = value == "on" },
_ => c,
}).Clean();
RandoKeep();
SendRando();
}
async Task RandoDecode(string text)
{
var s = randoSchema;
if (s == null) { Toast("Get the randomizer first.", "error"); return; }
try
{
var (values, warnings) = await Rando.DecodeAsync(s, text, CancellationToken.None);
lock (randoGate) randoValues = values;
RandoKeep();
RandoCheckSoon();
Toast(warnings.Count == 0 ? "Settings taken from the string"
: "Settings taken from the string · " + H(string.Join("; ", warnings.Take(3))) + (warnings.Count > 3 ? " · and " + (warnings.Count - 3) + " more (the launcher's log has them)" : ""),
warnings.Count == 0 ? "success" : null);
foreach (var w in warnings) Log.Write("randomizer: settings string: " + w);
}
catch (OotrrException e) { Toast(H(e.Message), "error"); }
SendRando();
}
// ---------------- making a seed ----------------
async Task RandoMake()
{
var s = randoSchema;
if (s == null) { Toast("Get the randomizer first.", "error"); return; }
if (GameDir is not { } game) { Toast("Build the game first: seeds go into its mods folder.", "error"); return; }
// ((Triforce, 11-26) a build or an update rewrites the romfs a seed is made from, and reads the mods folder)
if (RefusedWhileBuilding()) { SendRando(); return; }
if (Interlocked.CompareExchange(ref randoMaking, 1, 0) != 0) return;
try { await RandoMakeOne(s, game); }
finally { Interlocked.Exchange(ref randoMaking, 0); }
}
async Task RandoMakeOne(RandoSchema s, string game)
{
if (randoChoices.Seed.Length == 0) randoChoices.Seed = Randomizer.RandomSeed();
JsonObject values;
lock (randoGate) values = (JsonObject)randoValues.DeepClone();
// (what OOTRR says now, not what an earlier check said: a check may be on its way)
string? says;
await randoCheckGate.WaitAsync();
try { says = await Rando.CheckAsync(s, values, CancellationToken.None); }
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException) { says = null; Log.Write("randomizer: check before make: " + e.Message); }
finally { randoCheckGate.Release(); }
if (says != null)
{
randoProblem = says;
Toast("OOTRR cannot make these settings yet: " + H(says), "error");
SendRando();
return;
}
var preset = s.Preset(s.PresetOf(values) ?? "")?.Name ?? "Custom";
var used = randoChoices.Seed;
using var cts = randoCts = new CancellationTokenSource();
randoLine = "Starting";
SendRando();
var last = DateTime.MinValue;
try
{
var made = await Rando.MakeAsync(game, s, values, used, randoChoices.Cosmetics, l =>
{
randoLine = l;
if ((DateTime.UtcNow - last).TotalMilliseconds < 300) return;
last = DateTime.UtcNow;
SendRando();
}, cts.Token, preset);
var wins = made.Shared.Where(x => x.Wins).ToList();
var msg = "<b>&#9670;</b> Seed <b>" + H(made.Seed.Seed) + "</b> is on · start a <b>new game</b> in an empty file";
if (wins.Count > 0) msg += " · " + H(string.Join(", ", wins.Select(x => x.Name))) + " " + (wins.Count == 1 ? "changes" : "change") + " some of the same files and " + (wins.Count == 1 ? "wins" : "win") + " them (Mods page)";
Toast(msg, "success");
Sfx("success");
// (the next seed gets a new text: the one just used is kept with its seed. One typed while this one was made stays)
if (randoChoices.Seed == used) randoChoices.Seed = Randomizer.RandomSeed();
RandoKeep();
SendState(new JsonObject { ["randoMade"] = made.Seed.Mod.Rel });
}
catch (OperationCanceledException) { Toast("Stopped · no seed was made"); }
catch (Exception e) when (e is OotrrException || e is ModsException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException)
{
Log.Write("randomizer: make: " + e);
Toast(H(e.Message), "error");
}
finally { randoCts = null; randoLine = ""; SendRando(); RefreshHome(); }
}
// ---------------- your seeds ----------------
/// <summary>The seed text of the seed that is on in a game folder, or null (the home screen's line).</summary>
string? RandoSeedOn(string game)
{
try { return Rando.Seeds(game).FirstOrDefault(x => x.Mod.On)?.Seed; }
catch (Exception e) { Log.Write("randomizer: " + e.Message); return null; }
}
RandoSeed? RandoFind(string? id) => id != null && GameDir is { } g ? Rando.Seeds(g).FirstOrDefault(x => x.Mod.Rel == id) : null;
void RandoSeedDo(string? id, string what)
{
if (GameDir is not { } game) return;
if (what is "use" or "remove" && RefusedWhileBuilding()) { SendRando(); return; }
var x = RandoFind(id);
if (x == null) { Toast("That seed is no longer in the mods folder.", "error"); SendRando(); return; }
try
{
switch (what)
{
case "use":
Rando.Use(game, x);
Toast("Seed <b>" + H(x.Seed) + "</b> is on · its saves are the ones you make with it on", "success");
break;
case "remove":
if (randoCts != null) { Toast("Wait for the seed being made.", "error"); return; }
Rando.Remove(game, x);
Toast("Seed <b>" + H(x.Seed) + "</b> is removed. Its folder is kept in mods" + Path.DirectorySeparatorChar + Mods.Removed + ".", "success");
break;
case "copy":
if (x.Settings.Length == 0) { Toast("This seed has no settings string.", "error"); return; }
Copy(x.Settings);
break;
case "folder":
OpenPlace(x.Mod.Path);
break;
case "spoiler":
RandoOpenFile(x.Spoiler);
break;
}
}
catch (Exception e) when (e is ModsException || e is IOException || e is InvalidOperationException) { Toast(H(e.Message), "error"); }
SendRando();
if (what is "use" or "remove") RefreshHome(); // (the Play screen says which seed is on)
}
void RandoAllOff()
{
if (GameDir is not { } game || RefusedWhileBuilding()) { SendRando(); return; }
try { Rando.Off(game); Toast("Every seed is off: the game is the game as it comes", "success"); }
catch (Exception e) when (e is ModsException || e is IOException || e is InvalidOperationException) { Toast(H(e.Message), "error"); }
SendRando();
RefreshHome();
}
/// <summary>A text file in the system's own program for it. A test run opens nothing: it says so instead.</summary>
void RandoOpenFile(string file)
{
if (!File.Exists(file)) { Toast("That file is not there: " + H(file), "error"); return; }
if (ctx.TestRoot != null) { Toast("Test run: no window opens. " + H(file)); Log.Write("open file (test run, not opened): " + file); return; }
try
{
if (OperatingSystem.IsWindows()) System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(file) { UseShellExecute = true })?.Dispose();
else
{
var si = new System.Diagnostics.ProcessStartInfo(LinuxPlatform.XdgOpen) { UseShellExecute = false };
si.ArgumentList.Add(file);
System.Diagnostics.Process.Start(si)?.Dispose();
}
}
catch (Exception e) { Log.Write("open " + file + ": " + e.Message); Toast("The file could not be opened: " + H(file), "error"); }
}
}

View File

@@ -123,8 +123,10 @@ public sealed partial class Backend
PickThen(true, into ? "Choose the folder with your saves" : "Choose where the saves go", path => SavesFolderPicked(into, path));
return;
}
if (!id.StartsWith('s') || !int.TryParse(id.AsSpan(1), out var i) || i < 0 || i >= savesFound.Count) return;
SavesAsk(into, savesFound[i]);
// ((Triforce, 11-26) the list as it is now, once: another worker may put a new list in its place between the check and the read)
var found = savesFound;
if (!id.StartsWith('s') || !int.TryParse(id.AsSpan(1), out var i) || i < 0 || i >= found.Count) return;
SavesAsk(into, found[i]);
}
void SavesFolderPicked(bool into, string path)
@@ -212,7 +214,7 @@ public sealed partial class Backend
if (OperatingSystem.IsWindows()) System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true })?.Dispose();
else
{
var si = new System.Diagnostics.ProcessStartInfo("xdg-open") { UseShellExecute = false };
var si = new System.Diagnostics.ProcessStartInfo(LinuxPlatform.XdgOpen) { UseShellExecute = false };
si.ArgumentList.Add(url);
System.Diagnostics.Process.Start(si)?.Dispose();
}

View File

@@ -20,14 +20,14 @@ public sealed partial class Backend
On("settings.lang", m => LanguageChosen((string?)m["id"]));
On("settings.dlss", m =>
{
if ((string?)m["id"] != "yes") return;
if ((string?)m["id"] != "yes" || !Answered(ref dlssKey, m)) return;
new Dlss(ctx).Accept();
Toast("NVIDIA DLSS is included from the next build.", "success");
SendSettings();
});
On("settings.uninstall", m =>
{
if ((string?)m["id"] != "yes") return;
if ((string?)m["id"] != "yes" || !Answered(ref uninstallKey, m)) return;
Log.Write("uninstall from Settings");
try { new Uninstaller(ctx).Run(); }
catch (Exception e) { Log.Write("uninstall: " + e); Toast("Triforce could not be removed: " + H(e.Message), "error"); return; }
@@ -173,7 +173,7 @@ public sealed partial class Backend
return;
}
var html = string.Join("", dlss.LicenseText.Split("\n\n").Select(p => "<p>" + H(p).Replace("\n", "<br>") + "</p>"));
Ask("NVIDIA DLSS", html, "settings.dlss", new[] { ("no", "Cancel", false), ("yes", Dlss.AcceptLabel, true) });
Ask("NVIDIA DLSS", html, "settings.dlss", new[] { ("no", "Cancel", false), ("yes", Dlss.AcceptLabel, true) }, AskKey(ref dlssKey));
break;
}
case "rebuild":
@@ -207,7 +207,7 @@ public sealed partial class Backend
var plan = new Uninstaller(ctx).Describe();
string List(IEnumerable<string> l) => "<ul style=\"margin:4px 0 0 20px\">" + string.Join("", l.Select(x => "<li>" + H(Capital(x)) + "</li>")) + "</ul>";
Ask("Uninstall Triforce", "<p>This removes:</p>" + List(plan.Removes) + "<p>This keeps:</p>" + List(plan.Keeps), "settings.uninstall",
new[] { ("no", "Keep Triforce", false), ("yes", "Uninstall", true) });
new[] { ("no", "Keep Triforce", false), ("yes", "Uninstall", true) }, AskKey(ref uninstallKey));
break;
}
}

View File

@@ -80,7 +80,17 @@ public sealed partial class Backend
"texpack.go", new[] { ("no", "Not now", false), ("go", have == TexturePackHave.Partial ? "Continue" : "Download", true) });
}
// ((Triforce, 11-26) 1 while the pack downloads: two clicks started two installs into one folder)
int packBusy;
async Task RunPack()
{
if (Interlocked.CompareExchange(ref packBusy, 1, 0) != 0) return;
try { await RunPackOne(); }
finally { Interlocked.Exchange(ref packBusy, 0); }
}
async Task RunPackOne()
{
var g = GameDir;
if (g == null || packCts != null || packManifest == null) return;

View File

@@ -10,7 +10,8 @@ namespace Triforce.Launcher;
/// Backend.Core.cs first run, build, home, update, Play (RegisterCore)
/// Backend.Saves.cs the Saves page (RegisterSaves)
/// Backend.Mods.cs the Mods page (RegisterMods)
/// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings)</summary>
/// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings)
/// Backend.Randomizer.cs the Randomizer page (OOTRR's seeds) (RegisterRandomizer)</summary>
public sealed partial class Backend
{
readonly IHost host;
@@ -25,7 +26,7 @@ public sealed partial class Backend
this.host = host; this.content = content; this.ctx = ctx; this.start = start; this.dataDir = dataDir;
content.Media = MediaFor;
content.SavePicture = SavePicture;
RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack();
RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack(); RegisterRandomizer();
}
partial void RegisterSaves();
@@ -50,14 +51,16 @@ public sealed partial class Backend
public void OnMessage(string json, string[] files)
{
JsonNode? m;
try { m = JsonNode.Parse(json); } catch { Log.Write("bad message " + json); return; }
if (m == null) return;
var t = (string?)m["t"];
try { m = JsonNode.Parse(json); } catch { Log.Write("bad message " + (json.Length > 200 ? json.Substring(0, 200) + "..." : json)); return; }
// ((Triforce, 11-26) only an object with a string t: an array or a number threw out of the window's message event)
if (m is not JsonObject || m["t"] is not JsonValue tv || !tv.TryGetValue<string>(out var t)) { Log.Write("bad message (not a command)"); return; }
try
{
switch (t)
{
case "ready": OnReady(); break;
// (on a worker, as commands are: reading the game's art and music, the saves and the settings rows took the
// window's own thread, and the window hung until they were done)
case "ready": _ = Guarded("ready", () => Task.Run(OnReady)); break;
case "win":
switch ((string?)m["a"])
{

View File

@@ -110,6 +110,8 @@ public sealed class WinHost : IHost
// Only our own page lives in this window; a link elsewhere opens in the player's browser.
if (!e.Uri.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; OpenUrl(e.Uri); }
};
// ((Triforce, 11-26) no frame of another site inside the page: the page has none, and one could post messages)
web.FrameNavigationStarting += (_, e) => { if (!e.Uri.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) e.Cancel = true; };
web.ProcessFailed += (_, e) => Log.Write("webview process failed: " + e.ProcessFailedKind);
web.Navigate(Origin + "ui/index.html" + Environment.GetEnvironmentVariable("TRIFORCE_START"));
ctl.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
@@ -122,17 +124,28 @@ public sealed class WinHost : IHost
}
}
/// <summary>((Triforce, 11-26) What the page may load and run: its own scripts only (no inline script, no eval), styles of its
/// own and inline ones (style attributes), pictures of its own and over https (GameBanana's), no frames, no plugins. A text
/// that got into the page unescaped then cannot run a script, nor load one.</summary>
const string Csp = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; " +
"media-src 'self' blob: data:; font-src 'self' data:; connect-src 'self'; object-src 'none'; frame-src 'none'; " +
"base-uri 'none'; form-action 'none'";
void OnRequest(object? sender, CoreWebView2WebResourceRequestedEventArgs e)
{
var path = new Uri(e.Request.Uri).AbsolutePath;
var got = content.Get(path);
// (no Access-Control-Allow-Origin: only the page itself, on this origin, reads what is served here)
e.Response = got is { } g
? env!.CreateWebResourceResponse(new MemoryStream(g.data), 200, "OK", "Content-Type: " + g.mime + "\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: *")
? env!.CreateWebResourceResponse(new MemoryStream(g.data), 200, "OK", "Content-Type: " + g.mime + "\r\nCache-Control: no-store" +
(g.mime.StartsWith("text/html", StringComparison.OrdinalIgnoreCase) ? "\r\nContent-Security-Policy: " + Csp : ""))
: env!.CreateWebResourceResponse(null, 404, "Not Found", "Cache-Control: no-store");
}
void OnMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
// ((Triforce, 11-26) only the launcher's own page speaks to the launcher)
if (!e.Source.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) { Log.Write("message from " + e.Source + " left out"); return; }
string json;
try { json = e.TryGetWebMessageAsString(); } catch { json = e.WebMessageAsJson; }
var files = new List<string>();

View File

@@ -1540,9 +1540,10 @@ public static class Astc
{
if (blockWidth < 4 || blockWidth > 12 || blockHeight < 4 || blockHeight > 12)
throw new NotSupportedException("ASTC block " + blockWidth + "x" + blockHeight);
ImageLimits.Check(width, height);
var rows = (height + blockHeight - 1) / blockHeight;
var cols = (width + blockWidth - 1) / blockWidth;
if (data.Length < rows * cols * 16)
if (data.Length < (long)rows * cols * 16)
throw new InvalidDataException("ASTC data is shorter than the image");
var output = new byte[width * height * 4];
Parallel.For(0, rows, () => new Scratch(), (yIndex, _, scratch) =>

View File

@@ -42,6 +42,11 @@ public static class BlockLinear
{
if (bytesPerElement is not (1 or 2 or 4 or 8 or 16))
throw new NotSupportedException(bytesPerElement + " bytes per element");
// ((Triforce, 11-26) the sizes checked before anything is allocated: a header could ask for 2 GB, then be refused)
ImageLimits.Check(width, height);
if ((long)width * bytesPerElement * height > int.MaxValue || blockHeightLog2 is < 0 or > 5) throw new InvalidDataException("a texture larger than the game has");
if (Size(width, height, bytesPerElement, blockHeightLog2) > input.Length)
throw new InvalidDataException("the texture's data is shorter than its size calls for");
var pitch = width * bytesPerElement;
var output = new byte[pitch * height];
var gobsInX = (pitch + 63) >> GobSizeXShift;
@@ -49,9 +54,6 @@ public static class BlockLinear
var blockHeightMask = (1 << blockHeightLog2) - 1;
var xShift = GobSizeShift + blockHeightLog2;
if (Size(width, height, bytesPerElement, blockHeightLog2) > input.Length)
throw new InvalidDataException("the texture's data is shorter than its size calls for");
for (var y = 0; y < height; y++)
{
var swizzledY = SwizzleY(y);

View File

@@ -40,14 +40,22 @@ public sealed class Bntx
throw new InvalidDataException("not a BNTX archive");
var count = U32(0x24);
var table = (long)U64(0x28);
// ((Triforce, 11-26) the count and the names as the file says them, checked: a few KB that named 131072 textures, each
// with a 64K-character name, asked for about 17 GB)
if (count > 4096 || table < 0 || table > data.Length || table + 8L * count > data.Length)
throw new InvalidDataException("BNTX texture table out of the file");
var list = new List<BntxTexture>();
var seen = new HashSet<long>();
for (var i = 0; i < count; i++)
{
var p = (long)U64(table + 8 * i);
if (p < 0 || p + 0x80 > data.Length || !seen.Add(p)) throw new InvalidDataException("BNTX texture " + i + " is out of the file, or named twice");
if (data[p] != 'B' || data[p + 1] != 'R' || data[p + 2] != 'T' || data[p + 3] != 'I')
throw new InvalidDataException("BNTX texture " + i + " has no BRTI header");
var nameAt = (long)U64(p + 0x60);
if (nameAt < 0 || nameAt + 2 > data.Length) throw new InvalidDataException("BNTX texture " + i + "'s name is out of the file");
var nameLength = U16(nameAt);
if (nameLength > 1024 || nameAt + 2 + nameLength > data.Length) throw new InvalidDataException("BNTX texture " + i + "'s name is too long");
var name = Encoding.UTF8.GetString(data, (int)nameAt + 2, nameLength);
var mips = (long)U64(p + 0x70);
var tex = new BntxTexture(name, (int)U32(p + 0x24), (int)U32(p + 0x28), U32(p + 0x1C), U16(p + 0x16), U16(p + 0x12),
@@ -188,6 +196,7 @@ public static class BlockCompression
var bytesPerBlock = kind is Kind.BC1 or Kind.BC4 ? 8 : 16;
var wBlocks = (width + 3) / 4;
var hBlocks = (height + 3) / 4;
ImageLimits.Check(width, height);
var output = new byte[width * height * 4];
Span<byte> texels = stackalloc byte[64];
Span<byte> channel = stackalloc byte[16];

View File

@@ -0,0 +1,16 @@
// ((Triforce, 11-26) The sizes a texture of the game may have. A texture's width and height come from its file's header: before
// they size an output buffer (width * height * 4, in int), they are checked, so a damaged or crafted file is refused with a
// reason instead of asking for gigabytes, wrapping to a negative size, or throwing OverflowException.
namespace Triforce.Core.GameFiles;
public static class ImageLimits
{
/// <summary>The widest and tallest texture taken (the game's largest are far smaller; 16384 x 16384 x 4 bytes fits an int).</summary>
public const int MaxSide = 16384;
public static void Check(int width, int height)
{
if (width <= 0 || height <= 0 || width > MaxSide || height > MaxSide)
throw new InvalidDataException("a texture of " + width + " x " + height + ", which no texture of the game is");
}
}

View File

@@ -127,6 +127,8 @@ public sealed class NupSource : IGameSource
string Name(uint offset, uint count)
{
// ((Triforce, 11-26) a name inside the strings area and of a name's length: a damaged index made each read a megabyte)
if (count > 1024 || stringsAt + (long)offset + count > index.Capacity) throw new InvalidDataException("the package's index names something outside its names");
var bytes = new byte[count];
index.ReadArray(stringsAt + offset, bytes, 0, (int)count);
return Encoding.UTF8.GetString(bytes);
@@ -145,6 +147,10 @@ public sealed class NupSource : IGameSource
return known;
var first = index.ReadUInt32(dirsAt + 24L * dir + 8);
var count = index.ReadUInt32(dirsAt + 24L * dir + 12);
// ((Triforce, 11-26) the children inside the children's table (between kidsAt and the names), before anything is
// allocated for them: a 300-byte file asked for tens of GB here)
if ((long)first + count > (stringsAt - kidsAt) / 4 || count > dirCount + fileCount)
throw new InvalidDataException("the package's index lists children outside its table");
var kids = new uint[count];
index.ReadArray(kidsAt + 4L * first, kids, 0, (int)count);
var names = new Dictionary<string, uint>((int)count, StringComparer.Ordinal);
@@ -241,6 +247,7 @@ public sealed class NupSource : IGameSource
if (stored <= 0 || stored > length - offset)
throw new InvalidDataException(romfsPath + ": its compressed data runs past the end of the package");
var frame = ReadAt(offset, (int)stored);
if (size > Zs.MaxUnpacked) throw new InvalidDataException(romfsPath + ": larger than any file of the game");
var output = new byte[size];
using var z = new Decompressor();
if (z.Unwrap(frame, output) != size)

View File

@@ -48,14 +48,19 @@ public sealed class Zs
return Decompress(data, dict);
}
/// <summary>((Triforce, 11-26) The most one frame may unpack to: the game's largest file is far smaller. A frame that says more,
/// or unpacks to more, is refused: a header of a few bytes could ask for 2 GB, and a frame that names no size grew without end.</summary>
public const int MaxUnpacked = 1 << 30;
/// <summary>One zstd frame unpacked, with a dictionary or none.</summary>
public static byte[] Decompress(ReadOnlySpan<byte> data, byte[]? dictionary)
public static byte[] Decompress(ReadOnlySpan<byte> data, byte[]? dictionary, int max = MaxUnpacked)
{
using var z = new Decompressor();
if (dictionary != null)
z.LoadDictionary(dictionary);
var size = Decompressor.GetDecompressedSize(data);
if (size > 0 && size <= int.MaxValue)
if ((ulong)size > (ulong)max) throw new InvalidDataException("a zstd frame that unpacks to " + size + " bytes, more than a game file is");
if (size > 0)
{
var output = new byte[size];
var n = z.Unwrap(data, output);
@@ -66,7 +71,12 @@ public sealed class Zs
if (dictionary != null)
stream.LoadDictionary(dictionary);
using var into = new MemoryStream();
stream.CopyTo(into);
var buffer = new byte[1 << 16];
for (int n; (n = stream.Read(buffer, 0, buffer.Length)) > 0;)
{
into.Write(buffer, 0, n);
if (into.Length > max) throw new InvalidDataException("a zstd frame that unpacks to more than " + max + " bytes, more than a game file is");
}
return into.ToArray();
}

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"));

View File

@@ -3,6 +3,8 @@
using System.Diagnostics;
using Triforce.LogicTests;
// ((Triforce, 11-25) copied in as ootrr.exe: the stand-in for OOTRR's program (Tests.Randomizer.cs)
if (Path.GetFileNameWithoutExtension(Environment.ProcessPath ?? "") == "ootrr") return FakeOotrr.Run(args);
if (args.Length >= 2 && args[0] == "-I" && args[1].EndsWith("make_game.py", StringComparison.Ordinal)) return Fakes.MakeGame(args.Skip(2).ToArray());
if (args.Contains("--romfs") && args.Contains("--user")) return Fakes.FakeGame(args);
if (Environment.GetEnvironmentVariable("LOGICTESTS_CHILD") is { Length: > 0 } mode && args.Contains("--relaunched")) return Fakes.NewSetup(mode, args);

View File

@@ -33,6 +33,16 @@ static partial class Tests
yield return ("tools: update from the fake server with progress", ToolsUpdate);
yield return ("texture pack: download, stop and go on, hashes, names, replace, remove", TexturePackInstall);
yield return ("texture pack: the real pack end to end (TEXPACK_E2E)", TexturePackRealPack);
yield return Sync("randomizer: OOTRR's settings: dependencies, held values, kinds, presets, what goes to OOTRR", RandoSchemaRules);
yield return Sync("randomizer: folder names, the release's kept files, OOTRR's errors", RandoNames);
yield return ("randomizer: OOTRR downloaded, its hash checked, zip and tar.gz unpacked, nothing else", RandoInstall);
yield return ("randomizer: seeds made into the mods folder, one on, use, off, remove, shared files, kept choices", RandoSeeds);
yield return ("randomizer: a failed or stopped seed leaves nothing; settings strings; the game running; no romfs", RandoFailures);
yield return ("randomizer: the real OOTRR end to end (OOTRR_E2E)", RandoRealOotrr);
yield return Sync("hardening: folder names, step times, verdict HTML, release notes, the launcher's own names", HardeningNames);
yield return ("hardening: https only, the most a download may be, JSON answers capped", HardeningDownloads);
yield return Sync("hardening: the benchmark's settings writes, the texture pack's Remove keeps the player's files", HardeningFiles);
yield return Sync("hardening: crafted texture archives, zstd frames and texture sizes refused at once", HardeningParsers);
yield return Sync("build: @@ protocol from a recorded transcript", Protocol);
yield return Sync("build: estimates from history and without", Estimates);
yield return Sync("build: time left, slow first part of the shaders then fast", EtaSlowStart);
@@ -451,6 +461,7 @@ static partial class Tests
Check(c.EndsWith(@"rmdir ""C:\Users\Ann\Downloads"" 2>nul"), "the folder itself only when empty (no /s)");
var c2 = Uninstaller.RemoveCommand(def, true);
Check(c2.Contains(@"rmdir /s /q """ + def + @"\tools""") && c2.Contains(@"rmdir /s /q """ + def + @"\downloads"""), "its own folders go in its own folder");
Check(c2.Contains(@"rmdir /s /q """ + def + @"\randomizer""") && !c.Contains("randomizer"), "the randomizer's choices and work with them, only from a folder of its own");
Check(!c2.Contains(@"rmdir /s /q """ + def + @""""), "but never the folder whole");
// (a Setup that is not installed, run from Downloads beside the player's files: nothing of that folder goes)

View File

@@ -71,7 +71,7 @@ static partial class Tests
Equal(3, saves.Slots(game).Count(s => s.Used), "three files now");
Check(!Directory.Exists(Path.Combine(game, "user", "save-tx", Saves.TriforceUid)), "the old save's transaction removed");
Check(File.Exists(Path.Combine(game, "user", "save.lock")), "the game's lock was taken across the copy");
Check(!Directory.Exists(saves.TriforceFolder(game) + ".partial") && !Directory.Exists(saves.TriforceFolder(game) + ".old"), "no partial left");
Check(!Directory.Exists(saves.TriforceFolder(game) + Partial.Suffix) && !Directory.Exists(saves.TriforceFolder(game) + Partial.Aside), "no partial left");
// (out: a waiting commit is the newest save)
var ready = Path.Combine(game, "user", "save-tx", Saves.TriforceUid, "ready-2");
MakeSave(ready, "ready", 2);
@@ -86,6 +86,20 @@ static partial class Tests
await ThrowsAsync<InvalidOperationException>(() => saves.ExportAsync(game, Saves.Describe("lab", Path.Combine(LabGame, "user", "save", Saves.TriforceUid))), "a test run writes no save outside its root");
Equal(navi, Saves.FindIn(Path.Combine(root, "Local", "Programs", "NX2navi", "game")), "a chosen NX2navi game folder");
Equal(eden, Saves.FindIn(Path.Combine(root, "Roaming", "eden")), "a chosen emulator folder, searched down");
// ((Triforce, 11-26) in again with a commit still waiting: that newest save is backed up too, before it is taken away)
Check(Directory.Exists(ready), "the waiting commit is still there");
var b3 = await saves.ImportAsync(found.First(f => f.Name == "Eden"), game);
var newest = Directory.GetDirectories(ctx.SaveBackupsFolder, "*-newest").SingleOrDefault();
Check(newest != null && File.ReadAllText(Path.Combine(newest, "option.sav")) == "ready", "the waiting commit backed up: " + newest);
Check(b3 != null && File.ReadAllText(Path.Combine(b3, "option.sav")) == "eden", "and the save folder as before");
Check(!Directory.Exists(ready), "then taken away, as the game would put it over the copy");
// (one save folder inside the other: refused)
Throws<InvalidOperationException>(() => saves.Copy(eden, Path.Combine(eden, "inner"), ctx.SaveBackupsFolder, "x"), "into a folder inside the source");
// (a player's own "<save>.old" beside the save folder is theirs: a copy does not touch it)
var mine = saves.TriforceFolder(game) + ".old";
MakeSave(mine, "my own backup", 1);
await saves.ImportAsync(found.First(f => f.Name == "Eden"), game);
Equal("my own backup", File.ReadAllText(Path.Combine(mine, "option.sav")), "the player's .old folder kept");
}
// ---- mods ----
@@ -280,11 +294,17 @@ static partial class Tests
// (switched off, then updated: the new one takes its place and its switch)
mm.SetOn(mods, mm.List(mods).First(m => m.Name == "Fancy Hat"), false);
s.Add("/dl/2", ZipBytes(z => Put(z, "romfs/UI/hat2.bntx", "hat2")));
await inst.InstallAsync(http, mod, file with { Url = s.Url + "/dl/2", Added = 1800000000 }, game, null, CancellationToken.None);
var now = mm.List(mods).Where(m => m.Info?.GameBananaId == 101).ToList();
// ((Triforce, 11-26) a work in progress with the same number is another thing on GameBanana: the update leaves it alone)
MakeMod(mods, "05-Wip hat", ("romfs/w", "w"), ("triforce_mod.json", "{\"name\":\"Wip hat\",\"gamebanana_id\":101,\"gamebanana_model\":\"Wip\"}"));
var upd = await inst.InstallAsync(http, mod, file with { Url = s.Url + "/dl/2", Added = 1800000000 }, game, null, CancellationToken.None);
var now = mm.List(mods).Where(m => m.Info?.GameBananaId == 101 && m.Info?.Wip == false).ToList();
Equal(1, now.Count, "one folder for the mod after its update");
Check(now[0].Folder.StartsWith("_02-") && !now[0].On, "its place and its off kept: " + now[0].Folder);
Equal("ui/hat2.bntx", now[0].Files.Single(), "the new files");
Check(Directory.Exists(Path.Combine(mods, "05-Wip hat")), "the work in progress of the same number is not touched");
Check(Directory.EnumerateDirectories(Path.Combine(mods, Mods.Removed)).Any(d => ModManager.ReadInfo(d) is { GameBananaId: 101, Wip: false }) &&
upd.Contains(Mods.Removed), "the version before is kept in mods\\.removed, and said: " + upd);
await ThrowsAsync<IOException>(() => inst.InstallAsync(http, mod with { Id = 7 }, file with { Url = "http://example.invalid/hat.zip" }, game, null, CancellationToken.None), "a download address that is not https");
s.Add("/dl/3", ZipBytes(z => Put(z, "docs/readme.txt", "x")));
await ThrowsAsync<ModsException>(() => inst.InstallAsync(http, mod with { Id = 5 }, file with { Url = s.Url + "/dl/3" }, game, null, CancellationToken.None), "no romfs: refused");
// (bare game folders, no romfs above them: wrapped)

View File

@@ -0,0 +1,139 @@
using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using Triforce.Core.GameFiles;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
/// <summary>((Triforce, 11-26) The launcher's security and edge-case audit: what a crafted or damaged input, a server that sends
/// more than it says, or a name the launcher did not expect now does (refused with a reason, never a crash or a lost file).</summary>
static partial class Tests
{
// ---------------- names and numbers from folders and output ----------------
static void HardeningNames()
{
// (a mods folder whose number is in another script's digits: a name, not a crash that empties the Mods page)
var (_, num, name) = Mods.Parse("01-Skins");
Equal(null, num, "full-width digits are no number");
Equal("01-Skins", name, "the name whole");
Equal(1, Mods.Parse("-01-Skins").Number, "ASCII digits still are");
// (the build's step times: a number too large for an int is no time, not an exception in the output reader)
var steps = BuildProtocol.ParseSteps("x 99999999999:00, read 1:32");
Check(!steps.ContainsKey("x") && steps["read"] == 92, "an overlong number left out, the rest read");
// (the benchmark's verdict is HTML on the page: a place's name from the results file is encoded)
Check(Benchmark.SkippedNote(new[] { "<img src=x>" }).Contains("&lt;img src=x&gt;"), "a place's name encoded");
// (release notes: a long line of [ no longer takes quadratic time)
var sw = Stopwatch.StartNew();
ReleaseNotes.Plain(new string('[', 60000));
Check(sw.Elapsed < TimeSpan.FromSeconds(2), "a long line of [ read in " + sw.ElapsedMilliseconds + " ms");
// (names only the launcher makes beside a save folder: a player's own "<save>.old" is never taken for its)
Check(Partial.Suffix == ".triforce-partial" && Partial.Aside == ".triforce-old", "the launcher's own names");
Check(Uninstaller.OwnFolders.Contains(Randomizer.WorkFolder), "the randomizer's folder goes with an uninstall");
var root = NewRoot("hardening-names");
Check(new Ootrr(Ctx(root)).Folder.StartsWith(Path.Combine(Ctx(root).Home, Randomizer.WorkFolder), StringComparison.OrdinalIgnoreCase),
"OOTRR lives in the randomizer's folder, not in tools (which a tools update replaces whole)");
}
// ---------------- downloads ----------------
static async Task HardeningDownloads()
{
using var s = new FakeServer();
var root = NewRoot("hardening-downloads");
var ctx = Ctx(root);
using var http = Downloader.CreateHttp();
var d = new Downloader(ctx);
// (an address that is not https is not fetched; a test's own 127.0.0.1 server only in a test run)
var plain = Path.Combine(root, "plain.bin");
await ThrowsAsync<IOException>(() => d.ToFileAsync(http, "http://example.invalid/x.zip", plain, 0, null, CancellationToken.None), "plain http refused");
Equal(0, s.Requests, "nothing asked of any server");
// (no size listed: the most it may be; a server that offers more is refused, nothing kept)
s.Add("/big", new byte[100_000]);
var big = Path.Combine(root, "big.bin");
var e = await ThrowsAsync<IOException>(() => d.ToFileAsync(http, s.Url + "/big", big, 0, null, CancellationToken.None, most: 50_000), "more than the most");
Check(e.Message.Contains("more than"), "said: " + e.Message);
Check(!File.Exists(big) && !File.Exists(big + ".part"), "nothing of it kept");
await d.ToFileAsync(http, s.Url + "/big", big, 0, null, CancellationToken.None, most: 200_000);
Equal(100_000L, new FileInfo(big).Length, "within the most: downloaded");
// (a JSON answer read whole, but no more than its limit once unpacked)
await ThrowsAsync<IOException>(() => Downloader.TextAsync(new ByteArrayContent(new byte[5000]), 4000, CancellationToken.None), "an answer over its limit");
Equal("{\"a\":1}", await Downloader.TextAsync(new StringContent("{\"a\":1}"), 4000, CancellationToken.None), "an answer within it");
}
// ---------------- files the launcher changes ----------------
static void HardeningFiles()
{
var root = NewRoot("hardening-files");
// (the benchmark's settings: every line of a key set, the file's bytes and line ends kept)
var ini = Path.Combine(root, "triforce_options.ini");
File.WriteAllBytes(ini, Encoding.Latin1.GetBytes("a=1\r\nb=2\r\na=3\r\nname=café\r\n"));
BenchIni.Set(ini, new Dictionary<string, int> { ["a"] = 9, ["c"] = 4 });
Equal("a=9\r\nb=2\r\na=9\r\nname=café\r\nc=4\r\n", Encoding.Latin1.GetString(File.ReadAllBytes(ini)), "both a lines, CRLF and the byte 0xE9 kept, c added");
var back = Path.Combine(root, "backup.ini");
File.WriteAllText(back, "x=1\n");
BenchIni.Restore(back, ini);
Check(File.ReadAllText(ini) == "x=1\n" && !File.Exists(ini + ".new"), "put back in one step");
// (the texture pack's Remove: its own pictures and list go; what else a player keeps there stays)
var game = Path.Combine(root, "game");
var pack = TexturePack.Folder(game);
Directory.CreateDirectory(Path.Combine(pack, "mine"));
File.WriteAllText(Path.Combine(pack, "0123456789abcdef.png"), "p");
File.WriteAllText(Path.Combine(pack, "0123456789abcdef_m1.png.new"), "p");
File.WriteAllText(Path.Combine(pack, TexturePack.StateName), "{}");
File.WriteAllText(Path.Combine(pack, "notes.txt"), "mine");
File.WriteAllText(Path.Combine(pack, "mine", "x.png"), "mine");
new TexturePack(Ctx(root)).Remove(game);
Check(!File.Exists(Path.Combine(pack, "0123456789abcdef.png")) && !File.Exists(Path.Combine(pack, TexturePack.StateName)) &&
!File.Exists(Path.Combine(pack, "0123456789abcdef_m1.png.new")), "the pack's files gone");
Check(File.Exists(Path.Combine(pack, "notes.txt")) && File.Exists(Path.Combine(pack, "mine", "x.png")), "the player's files kept");
Directory.Delete(Path.Combine(pack, "mine"), true);
File.Delete(Path.Combine(pack, "notes.txt"));
File.WriteAllText(Path.Combine(pack, "0123456789abcdef.png"), "p");
new TexturePack(Ctx(root)).Remove(game);
Check(!Directory.Exists(pack), "nothing else in it: the folder goes");
}
// ---------------- game files that are damaged or made to harm ----------------
static void HardeningParsers()
{
// (a texture archive that names 131072 textures in a few bytes: refused at once, not 17 GB of names)
var bntx = new byte[0x40];
"BNTX"u8.CopyTo(bntx);
BinaryPrimitives.WriteUInt32LittleEndian(bntx.AsSpan(0x24), 131072);
BinaryPrimitives.WriteUInt64LittleEndian(bntx.AsSpan(0x28), 0x30);
var sw = Stopwatch.StartNew();
Throws<InvalidDataException>(() => new Bntx(bntx), "a texture table larger than the file");
// (two entries that point at one texture: refused)
var twice = new byte[0x200];
"BNTX"u8.CopyTo(twice);
BinaryPrimitives.WriteUInt32LittleEndian(twice.AsSpan(0x24), 2);
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x28), 0x30);
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x30), 0x80);
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x38), 0x80);
"BRTI"u8.CopyTo(twice.AsSpan(0x80));
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x80 + 0x60), 0x180);
Throws<InvalidDataException>(() => new Bntx(twice), "one texture named twice");
// (a texture name longer than a name is)
BinaryPrimitives.WriteUInt32LittleEndian(twice.AsSpan(0x24), 1);
BinaryPrimitives.WriteUInt16LittleEndian(twice.AsSpan(0x180), 0xFFFF);
Throws<InvalidDataException>(() => new Bntx(twice), "a 64K-character name");
Check(sw.Elapsed < TimeSpan.FromSeconds(2), "refused at once: " + sw.ElapsedMilliseconds + " ms");
// (a zstd frame that unpacks to more than it may: refused, whether it says its size or not)
var frame = new ZstdSharp.Compressor().Wrap(new byte[100_000]).ToArray();
Throws<InvalidDataException>(() => Zs.Decompress(frame, null, 10_000), "a frame that says it is larger than the most");
Equal(100_000, Zs.Decompress(frame, null).Length, "within the most: unpacked");
// (a texture's sizes from its header, checked before anything is allocated)
Throws<InvalidDataException>(() => ImageLimits.Check(0, 16), "no width");
Throws<InvalidDataException>(() => ImageLimits.Check(70000, 16), "wider than any texture");
Throws<InvalidDataException>(() => BlockCompression.Decode(new byte[64], 40000, 40000, BlockCompression.Kind.BC1), "a BC1 texture of 40000 x 40000");
Throws<InvalidDataException>(() => BlockLinear.Deswizzle(new byte[64], 16384, 32767, 4, 0), "a 2 GB deswizzle from a 64-byte texture");
}
}

View File

@@ -0,0 +1,517 @@
using System.Formats.Tar;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
/// <summary>((Triforce, 11-25) A stand-in for OOTRR's program (this test program, copied in as ootrr.exe): settings-dump, its
/// --decode, generate and build, as OOTRR 0.8.2 answers them, with what it was asked written to ootrr-calls.txt beside it.
/// A seed text "fail" makes generate fail; "slow" makes build wait (to be stopped), a file of its build held open.</summary>
static class FakeOotrr
{
public const string Schema = """
{"schema_version":1,"string_prefix":"OOTRR1-",
"groups":[{"id":"world","label":"World","tip":"How the world starts."},{"id":"goal","label":"Goals","tip":""},{"id":"starting","label":"Starting items","tip":""}],
"settings":[
{"id":"open_forest","num":3,"label":"Kokiri Forest","group":"world","kind":"choice","tag":"common","tip":"t","default":"closed","choices":[{"id":"open","label":"Open"},{"id":"closed","label":"Closed"}],"deps":[]},
{"id":"open_kakariko","num":4,"label":"Kakariko Gate","group":"world","kind":"choice","tag":"common","tip":"t","default":"closed","choices":[{"id":"open","label":"Open"},{"id":"closed","label":"Closed"}],"deps":[{"on":"open_forest","is":"open"}],"disabled":"closed"},
{"id":"open_door_of_time","num":5,"label":"Door of Time (old)","group":"world","kind":"toggle","tag":"common","tip":"t","default":false,"deps":[],"legacy":true},
{"id":"starting_age","num":2,"label":"Starting Age","group":"world","kind":"choice","tag":"core","tip":"t","default":"child","choices":[{"id":"child","label":"Child"},{"id":"adult","label":"Adult"}],"deps":[],"unsupported":true},
{"id":"bridge","num":24,"label":"Rainbow Bridge","group":"goal","kind":"choice","tag":"core","tip":"t","default":"vanilla","choices":[{"id":"open","label":"Open"},{"id":"vanilla","label":"Vanilla"},{"id":"dungeons","label":"Rewards"},{"id":"tokens","label":"Tokens"}],"deps":[]},
{"id":"bridge_rewards","num":27,"label":"Rewards for the bridge","group":"goal","kind":"number","tag":"common","tip":"t","default":9,"min":0,"max":9,"deps":[{"on":"bridge","is":"dungeons"}]},
{"id":"skip_ganon_trials","num":30,"label":"Skip trials","group":"goal","kind":"toggle","tag":"common","tip":"t","default":false,"deps":[]},
{"id":"trials","num":31,"label":"Trials","group":"goal","kind":"number","tag":"common","tip":"t","default":6,"min":0,"max":6,"deps":[{"on":"skip_ganon_trials","is":false}]},
{"id":"triforce_count","num":33,"label":"Pieces","group":"goal","kind":"number","tag":"common","tip":"t","default":30,"min":1,"max":999,"deps":[]},
{"id":"triforce_goal","num":34,"label":"Pieces needed","group":"goal","kind":"number","tag":"common","tip":"t","default":20,"min":1,"max":999,"max_by":"triforce_count","deps":[]},
{"id":"door_song","num":134,"label":"Door song","group":"world","kind":"toggle","tag":"common","tip":"t","default":true,"deps":[{"on":"bridge","not":"open"},{"on":"bridge","not":"tokens"}]},
{"id":"early_beds","num":77,"label":"Beds","group":"world","kind":"toggle","tag":"common","tip":"t","default":false,"deps":[{"on":"bridge","in":["vanilla","dungeons"]}]},
{"id":"enemy_health","num":110,"label":"Enemy health","group":"goal","kind":"number","tag":"common","tip":"t","default":100,"min":50,"max":500,"step":10,"times":100,"deps":[]},
{"id":"starting_items","num":36,"label":"Starting items","group":"starting","kind":"multi","tag":"common","tip":"t","default":[],"choices":[{"id":"ocarina","label":"Ocarina"},{"id":"bow","label":"Bow"},{"id":"hookshot","label":"Hookshot"},{"id":"hover_boots","label":"Hover Boots"}],"deps":[]},
{"id":"disabled_locations","num":13,"label":"Excluded","group":"starting","kind":"list","tag":"core","tip":"t","default":[],"max_items":2,"deps":[]}
],
"menu":[{"id":"win","label":"Logic","sections":[{"label":"Goal","items":[{"id":"bridge","view":{"label":"Bridge","opts":[{"label":"Open","ours":"open","live":false},{"label":"Vanilla","ours":"vanilla","live":true},{"label":"Trigger-Dungeons","ours":"","live":false}],"kind":"pick"}},{"stub":"Win Condition","kind":"choice"}]}]}],
"presets":[{"id":"default","name":"Default","tip":"d","order":0,"settings":{}},{"id":"easy","name":"Easy","tip":"e","order":10,"settings":{"open_forest":"open","open_kakariko":"open","bridge":"dungeons","bridge_rewards":3,"skip_ganon_trials":true}},
{"id":"open_world","name":"Open world","tip":"o","order":20,"settings":{"open_forest":"open","bridge":"open"}}]}
""";
public static int Run(string[] a)
{
var dir = AppContext.BaseDirectory;
File.AppendAllText(Path.Combine(dir, "ootrr-calls.txt"), string.Join("\u001f", a) + "\n");
string Arg(int i) => i < a.Length ? a[i] : "";
switch (Arg(0))
{
case "settings-dump" when Arg(1) == "--decode":
if (!Arg(2).StartsWith("OOTRR1-", StringComparison.Ordinal)) { Console.Error.WriteLine("error: not a settings string"); return 1; }
Console.WriteLine("{\"settings\":{\"open_forest\":\"open\",\"bridge\":\"tokens\",\"made_up\":1,\"trials\":99},\"warnings\":[\"one setting was dropped\"]}");
return 0;
case "settings-dump":
Console.WriteLine(Schema.Replace("\n", " "));
return 0;
case "generate":
{
var seed = Arg(2);
if (seed == "fail") { Console.Error.WriteLine("warning: something"); Console.Error.WriteLine("error: no placement could be found"); return 1; }
var settings = File.ReadAllText(Arg(1));
if (System.Text.Json.Nodes.JsonNode.Parse(settings)?["bridge"]?.ToString() == "tokens")
{
Console.Error.WriteLine("error: bridge is tokens, which this build cannot apply yet (only vanilla and dungeons work)");
return 1;
}
File.WriteAllText(Arg(3), "{\"format\":\"ootrr-seed\",\"version\":1,\"generator\":\"ootrr-core fake\",\"seed\":" + System.Text.Json.JsonSerializer.Serialize(seed) +
",\"settings\":\"OOTRR1-FAKE" + settings.Length + "\",\"placements\":{}}");
if (Arg(4) == "--spoiler") File.WriteAllText(Arg(5), "Spoiler of " + seed + "\n");
Console.WriteLine("Chest shuffle slice, seed \"" + seed + "\"");
Console.WriteLine("seed file: " + Arg(3));
return 0;
}
case "build":
{
var seed = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(Arg(1)))?["seed"]?.ToString() ?? "";
var root = Path.Combine(Arg(3), Arg(4));
Directory.CreateDirectory(Path.Combine(root, "romfs", "Event", "EventFlow"));
Directory.CreateDirectory(Path.Combine(root, "exefs"));
if (seed == "slow")
{
// (a file it writes, held open as a real build's would be, while it waits to be stopped)
using var held = new FileStream(Path.Combine(root, "romfs", "held.bin"), FileMode.Create, FileAccess.Write, FileShare.None);
Console.WriteLine("Writing flows");
Thread.Sleep(30000);
}
Console.WriteLine("Writing flows");
File.WriteAllText(Path.Combine(root, "romfs", "Event", "EventFlow", "Dm_Kokiri_0000.bfevfl.zs"), "flow of " + seed);
File.WriteAllText(Path.Combine(root, "romfs", "Event", "x.txt"), "x");
Console.WriteLine("changed 3 of 4 placed chests");
return 0;
}
}
Console.Error.WriteLine("error: unknown command " + Arg(0));
return 2;
}
}
static partial class Tests
{
static RandoSchema TestSchema() => RandoSchema.Parse(FakeOotrr.Schema);
// ---------------- the settings ----------------
static void RandoSchemaRules()
{
var s = TestSchema();
Equal(3, s.Groups.Count, "groups");
Equal("OOTRR1-", s.StringPrefix, "the settings strings' prefix");
Equal(3, s.Presets.Count, "presets");
var d = s.Defaults();
Equal("closed", d["open_forest"]!.ToString(), "a choice's default");
Equal(0, s.ForOotrr(d).Count, "the defaults: nothing to tell OOTRR");
// (dependencies: is, not, in; a held value; hidden)
var kak = s.Find("open_kakariko")!;
Equal(RandoState.Held, s.StateOf(kak, d), "the gate is held while the forest is closed");
d["open_kakariko"] = "open";
Equal("closed", s.Effective(d)["open_kakariko"]!.ToString(), "a held setting takes its held value");
Equal(0, s.ForOotrr(d).Count, "a held value that is the default is not told");
d["open_forest"] = "open";
Equal(RandoState.Open, s.StateOf(kak, d), "open forest: the gate opens up");
Equal("open", s.ForOotrr(d)["open_kakariko"]!.ToString(), "and its value goes to OOTRR");
Equal(RandoState.Hidden, s.StateOf(s.Find("bridge_rewards")!, d), "a setting whose dependency fails, with no held value, is left out");
d["bridge"] = "tokens";
Equal(RandoState.Hidden, s.StateOf(s.Find("door_song")!, d), "not: tokens is one of the values it must not have");
Equal(RandoState.Hidden, s.StateOf(s.Find("early_beds")!, d), "in: tokens is not one of its values");
d["bridge"] = "dungeons";
Equal(RandoState.Open, s.StateOf(s.Find("door_song")!, d), "not, met");
Equal(RandoState.Open, s.StateOf(s.Find("early_beds")!, d), "in, met");
// (values as each kind takes them)
var fo = s.Find("open_forest")!;
Check(RandoSchema.Clean(fo, JsonValue.Create("nope")) == null, "a choice that is not one is refused");
Check(RandoSchema.Clean(s.Find("skip_ganon_trials")!, JsonValue.Create("true")) == null, "a toggle takes true or false only");
var hp = s.Find("enemy_health")!;
Equal("120", RandoSchema.Clean(hp, JsonNode.Parse("120"))!.ToJsonString(), "a number in range and step");
Equal("120", RandoSchema.Clean(hp, JsonNode.Parse("120.0"))!.ToJsonString(), "a whole number written as 120.0");
Check(RandoSchema.Clean(hp, JsonNode.Parse("125")) == null, "off its step");
Check(RandoSchema.Clean(hp, JsonNode.Parse("510")) == null, "above its range");
var multi = s.Find("starting_items")!;
Equal("[\"ocarina\",\"bow\"]", RandoSchema.Clean(multi, JsonNode.Parse("[\"bow\",\"ocarina\",\"bow\"]"))!.ToJsonString(), "multi: in OOTRR's order, each once");
Check(RandoSchema.Clean(multi, JsonNode.Parse("[\"bow\",\"sword\"]")) == null, "multi: an item it does not have is refused");
var list = s.Find("disabled_locations")!;
Check(RandoSchema.Clean(list, JsonNode.Parse("[\"a\",\"b\",\"c\"]")) == null, "a list longer than its most");
Equal("Ocarina, Bow", RandoSchema.Show(multi, JsonNode.Parse("[\"ocarina\",\"bow\"]")), "multi shown by its labels");
Equal("None", RandoSchema.Show(multi, new JsonArray()), "an empty multi");
Equal("Ocarina, Bow and 2 more", RandoSchema.Show(multi, JsonNode.Parse("[\"ocarina\",\"bow\",\"hookshot\",\"hover_boots\"]")), "a long multi");
Equal(100L, hp.Times, "a multiple's times");
Equal("1.5\u00d7", RandoSchema.Show(hp, JsonNode.Parse("150")), "a multiple shown as one");
Equal("1\u00d7", RandoSchema.Show(hp, JsonNode.Parse("100")), "a whole multiple");
Equal("6", RandoSchema.Show(s.Find("trials")!, JsonNode.Parse("6")), "a plain number");
// (max_by: no higher than another setting; a value above it comes down to it, and goes back up with it)
var goal = s.Find("triforce_goal")!;
d["triforce_count"] = 12;
Equal(12L, s.MaxOf(goal, d), "max_by caps the most");
Equal("12", s.Effective(d)["triforce_goal"]!.ToJsonString(), "the default 20, above 12: 12");
Equal("12", s.ForOotrr(d)["triforce_goal"]!.ToJsonString(), "and that is what OOTRR is told");
d["triforce_count"] = 40;
Equal("20", s.Effective(d)["triforce_goal"]!.ToJsonString(), "the value kept, once the other is higher again");
Equal(120L, RandoSchema.Snap(hp, 125), "a number brought onto its step, down");
Equal(50L, RandoSchema.Snap(hp, 40), "never below its least");
// (presets and a saved map read back)
var easy = s.WithPreset("easy");
Equal("easy", s.PresetOf(easy), "a preset's values are that preset");
Equal("default", s.PresetOf(s.Defaults()), "the defaults are Default");
easy["trials"] = 3; // (a setting that is hidden under easy: held values decide, so it is still Easy)
Equal("easy", s.PresetOf(easy), "a change that the preset hides does not leave it");
easy["open_forest"] = "closed";
Equal(null, s.PresetOf(easy), "a change it shows: Custom");
var adopted = s.Adopt(JsonNode.Parse("{\"open_forest\":\"open\",\"not_there\":1,\"trials\":99,\"open_door_of_time\":true}") as JsonObject);
Equal("open", adopted["open_forest"]!.ToString(), "a saved value kept");
Equal("6", adopted["trials"]!.ToJsonString(), "a saved value it would refuse: the default");
Check(!adopted.ContainsKey("not_there"), "a setting it does not know is dropped");
Check(!s.ForOotrr(adopted).ContainsKey("open_door_of_time"), "a legacy setting is never told");
Throws<FormatException>(() => RandoSchema.Parse("{\"groups\":[]}"), "a dump without settings");
// (an option OOTRR's menu marks as not live: refused, and a preset that asks for it gets the default there, said)
var bridge = s.Find("bridge")!;
Check(!bridge.IsLive("open") && bridge.IsLive("vanilla") && bridge.IsLive("dungeons"), "the menu's live flags (an option with no value of OOTRR's is no choice)");
Check(RandoSchema.Clean(bridge, JsonValue.Create("open")) == null, "a value the build cannot apply yet is refused");
var ow = s.WithPreset("open_world");
Equal("vanilla", ow["bridge"]!.ToString(), "the preset's not-live value: the default");
Equal("open", ow["open_forest"]!.ToString(), "its other values kept");
var gaps = s.Gaps(s.Preset("open_world")!.Settings);
Check(gaps.Count == 1 && gaps[0] == ("Rainbow Bridge", "Open", "Vanilla"), "said: " + string.Join(";", gaps));
// (OOTRR's refusals in the settings' own words)
Equal("Rainbow Bridge is Open, which this build cannot apply yet (only Vanilla, Rewards and Tokens work)",
Randomizer.Friendly(s, "bridge is open, which this build cannot apply yet (only vanilla, dungeons and tokens work)"), "a list of choices");
Equal("Rainbow Bridge is Open, which this build cannot apply yet (only Vanilla works)",
Randomizer.Friendly(s, "bridge is open, which this build cannot apply yet (only vanilla works)"), "one choice");
Equal("something else entirely", Randomizer.Friendly(s, "something else entirely"), "a message it does not know stays");
}
static void RandoNames()
{
Equal("Randomizer K7QW2MPA", Randomizer.FolderName("K7QW2MPA"), "a plain seed");
Equal("Randomizer my seed for Saturday", Randomizer.FolderName(" my_seed.for Saturday "), "space, _ and . become spaces");
Equal("Randomizer a-b-c", Randomizer.FolderName("a/b\\c"), "path characters cannot leave the folder");
Equal("Randomizer seed", Randomizer.FolderName("::"), "nothing left: seed");
Check(Randomizer.FolderName(new string('x', 300)).Length <= 60, "a long seed is cut");
Check(Randomizer.FolderName("../../x").IndexOf("..", StringComparison.Ordinal) < 0, "no .. in a name");
var root = NewRoot("rando-names");
Directory.CreateDirectory(Path.Combine(root, "-Randomizer x"));
Equal("Randomizer x 2", Randomizer.FreeName(root, "Randomizer x"), "a name an off folder has is taken");
var r = Randomizer.RandomSeed();
Check(r.Length == 8 && r.All(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c)), "a random seed: eight letters and digits");
var o = new Ootrr(Ctx(root));
Equal("ootrr.exe", o.KeptName("OOTRR-0.8.2-windows-x64-portable/ootrr.exe"), "the program, one folder down");
Equal("LICENSE", o.KeptName("OOTRR-0.8.2-windows-x64-portable/LICENSE"), "its licence");
Equal(null, o.KeptName("OOTRR/../ootrr.exe"), "a name that climbs out");
Equal(null, o.KeptName("a/b/c/ootrr.exe"), "too deep");
Equal(null, o.KeptName("OOTRR/evil.dll"), "anything else");
Equal("The randomizer stopped: no placement could be found", Ootrr.ErrorOf(new OotrrRun(1, "", "warning: x\nerror: no placement could be found\n")), "an error line, warnings skipped");
}
// ---------------- installing ----------------
static byte[] TarGz(params (string Name, string Text)[] files)
{
using var m = new MemoryStream();
using (var gz = new GZipStream(m, CompressionLevel.Fastest, true))
using (var tar = new TarWriter(gz, TarEntryFormat.Pax, true))
foreach (var (name, text) in files)
tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, name) { DataStream = new MemoryStream(Encoding.UTF8.GetBytes(text)) });
return m.ToArray();
}
static async Task RandoInstall()
{
using var server = new FakeServer();
var root = NewRoot("rando-install");
var ctx = Ctx(root, env: new() { ["TRIFORCE_OOTRR_URL"] = server.Url + "/rel" });
using var http = Downloader.CreateHttp();
// (a zip as the Windows release is: one folder, the program and its papers; plus names that must not come out)
var exe = ctx.IsWindows ? "ootrr.exe" : "ootrr";
var zip = Zip(("OOTRR-0.8.2-windows-x64-portable/" + exe, "PROGRAM"), ("OOTRR-0.8.2-windows-x64-portable/LICENSE", "GPL"),
("OOTRR-0.8.2-windows-x64-portable/README.md", "readme"), ("../outside.txt", "no"), ("../" + exe, "CLIMBED"), ("x/../../" + exe, "CLIMBED"),
("OOTRR-0.8.2-windows-x64-portable/data/cache.bin", "no"));
var f = new OotrrFile("OOTRR-test.zip", zip.Length, Convert.ToHexStringLower(SHA256.HashData(zip)));
server.Add("/rel/OOTRR-test.zip", zip);
var o = new Ootrr(ctx, null, f);
{
Check(!o.Have, "nothing yet");
await o.InstallAsync(http, null, CancellationToken.None);
Check(o.Have, "installed");
Equal("PROGRAM", File.ReadAllText(Path.Combine(o.Folder, exe)), "the program");
Check(File.Exists(Path.Combine(o.Folder, "LICENSE")) && File.Exists(Path.Combine(o.Folder, "portable.txt")), "its licence, and portable.txt written");
Check(!File.Exists(Path.Combine(root, "outside.txt")) && !File.Exists(Path.Combine(o.Folder, "cache.bin")), "nothing else came out");
Check(!File.Exists(Path.Combine(Path.GetDirectoryName(o.Folder)!, exe)) && !File.Exists(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(o.Folder)!)!, exe)),
"a program named with .. lands nowhere: not above the folder");
Check(!File.Exists(Path.Combine(ctx.DownloadsFolder, "ootrr", "OOTRR-test.zip")), "the download is deleted once unpacked");
var seen = server.Requests;
await o.InstallAsync(http, null, CancellationToken.None);
Equal(seen, server.Requests, "installed: no second download");
// (a program in the folder that is not the pinned release's is not run)
Check(!new Ootrr(ctx, null, f with { Sha256 = new string('0', 64) }).Have, "another pin: not the program it expects");
o.Remove();
Check(!o.Have && !Directory.Exists(o.Folder), "removed");
}
// (a file whose hash is wrong: deleted, nothing unpacked)
var bad = new OotrrFile("OOTRR-bad.zip", zip.Length, new string('a', 64));
server.Add("/rel/OOTRR-bad.zip", zip);
var ob = new Ootrr(ctx, null, bad);
var e = await ThrowsAsync<OotrrException>(() => ob.InstallAsync(http, null, CancellationToken.None), "a wrong hash");
Check(e.Message.Contains("SHA-256"), "it says why");
Check(!File.Exists(Path.Combine(ctx.DownloadsFolder, "ootrr", "OOTRR-bad.zip")) && !ob.Have && !Directory.Exists(ob.Folder), "nothing kept");
// (the Linux release, a .tar.gz: the program by its name on this system)
var tgz = TarGz(("OOTRR-0.8.2-linux-x86_64/" + exe, "PROGRAM2"), ("OOTRR-0.8.2-linux-x86_64/NOTICE", "n"), ("OOTRR-0.8.2-linux-x86_64/install.sh", "no"));
var ft = new OotrrFile("OOTRR-test.tar.gz", tgz.Length, Convert.ToHexStringLower(SHA256.HashData(tgz)));
server.Add("/rel/OOTRR-test.tar.gz", tgz);
var ot = new Ootrr(ctx, null, ft);
await ot.InstallAsync(http, null, CancellationToken.None);
Equal("PROGRAM2", File.ReadAllText(Path.Combine(ot.Folder, exe)), "the program out of the tar");
Check(File.Exists(Path.Combine(ot.Folder, "NOTICE")) && !File.Exists(Path.Combine(ot.Folder, "install.sh")), "only the kept files");
}
// ---------------- seeds ----------------
/// <summary>A test root with a built game folder (its romfs folders) and the stand-in OOTRR; the randomizer for it.</summary>
static (TriforceContext Ctx, string Game, Randomizer R, string Calls) RandoSetup(string name)
{
var root = NewRoot(name);
var tool = Path.Combine(root, "fake-ootrr");
CopySelf(tool, "ootrr.exe");
var game = Path.Combine(root, "game");
foreach (var d in new[] { "Pack", "Banc", "Event", "System" }) Directory.CreateDirectory(Path.Combine(game, "romfs", d));
var ctx = Ctx(root, env: new() { ["TRIFORCE_OOTRR_EXE"] = Path.Combine(tool, "ootrr.exe") });
var mm = new ModManager(ctx) { GameRuns = _ => false };
return (ctx, game, new Randomizer(ctx, null, mm), Path.Combine(tool, "ootrr-calls.txt"));
}
static async Task RandoSeeds()
{
var (ctx, game, r, calls) = RandoSetup("rando-seeds");
var s = await r.SchemaAsync(CancellationToken.None);
Equal(15, s.Settings.Count, "the settings, from the program's settings-dump");
var values = s.WithPreset("easy");
values["starting_items"] = JsonNode.Parse("[\"hookshot\"]");
var lines = new List<string>();
// (what a stopped build left: taken away by the next seed; never read by the game or listed)
var left = Path.Combine(game, "mods", Randomizer.Making + "old1", "romfs", "Event");
Directory.CreateDirectory(left);
File.WriteAllText(Path.Combine(left, "half.txt"), "half");
Check(r.Manager.ListGame(game).All(m => !m.Path.Contains(Randomizer.Making)), "a build folder is no mod");
var made = await r.MakeAsync(game, s, values, "Saturday race!", new RandoCosmetics("grouped", "off", "random", false), lines.Add, CancellationToken.None, "Easy");
Check(!Directory.EnumerateDirectories(Path.Combine(game, "mods"), Randomizer.Making + "*").Any(), "no build folder left, the old one taken away");
Equal("Easy", made.Seed.Preset, "the preset it went by, kept");
var folder = Path.Combine(game, "mods", "Randomizer Saturday race!");
Equal(folder, made.Seed.Mod.Path, "the seed's folder");
Check(made.Seed.Mod.On, "on");
Equal("flow of Saturday race!", File.ReadAllText(Path.Combine(folder, "romfs", "Event", "EventFlow", "Dm_Kokiri_0000.bfevfl.zs")), "the seed's game files");
Check(!Directory.Exists(Path.Combine(folder, "exefs")), "the build's empty exefs is not kept");
Check(File.Exists(made.Seed.SeedFile) && File.ReadAllText(made.Seed.Spoiler) == "Spoiler of Saturday race!\n", "the seed file and spoiler beside it");
Equal("OOTRR1-FAKE", made.Seed.Settings.Substring(0, 11), "the settings string, from the seed file");
var sent = JsonNode.Parse(File.ReadAllText(Path.Combine(made.Seed.Files, "settings.json")))!.AsObject();
Equal("open", sent["open_forest"]!.ToString(), "the preset's values went to generate");
Equal("[\"hookshot\"]", sent["starting_items"]!.ToJsonString(), "and the changed one");
Check(!sent.ContainsKey("trials") && !sent.ContainsKey("triforce_count"), "only what differs from the defaults");
Check(lines.Contains("Placing the items") && lines.Contains("changed 3 of 4 placed chests"), "progress lines, the program's own among them");
var build = File.ReadAllLines(calls).Select(l => l.Split('\u001f')).Last(a => a[0] == "build");
Equal(Path.Combine(game, "romfs"), build[2], "built from the game folder's romfs");
Equal(Path.Combine(game, "mods"), build[3], "into its mods folder");
Check(build[4].StartsWith(Randomizer.Making, StringComparison.Ordinal), "under a hidden name first: " + build[4]);
var opt = string.Join(" ", build.Skip(5));
Check(opt.Contains("--host nx2navi") && opt.Contains("--music grouped") && opt.Contains("--colors random") && opt.Contains("--no-title-logo"), "host and cosmetics: " + opt);
Equal("Randomizer · Saturday race!", ModManager.ReadInfo(folder)!.Name, "its name on the Mods page");
Check(!Directory.Exists(Path.Combine(ctx.Home, "randomizer", "work")) || !Directory.EnumerateFileSystemEntries(Path.Combine(ctx.Home, "randomizer", "work")).Any(), "the work folder is cleaned");
// (a second seed: on, the first off; the same seed again gets a folder of its own)
var second = await r.MakeAsync(game, s, s.Defaults(), "Saturday race!", new RandoCosmetics(), null, CancellationToken.None);
Equal("Randomizer Saturday race! 2", second.Seed.Mod.Name, "the same seed's second folder");
var seeds = r.Seeds(game);
Equal(2, seeds.Count, "two seeds");
Equal(1, seeds.Count(x => x.Mod.On), "one on");
Check(seeds.Single(x => x.Mod.On).Mod.Name == "Randomizer Saturday race! 2", "the new one");
Check(Directory.Exists(Path.Combine(game, "mods", "-Randomizer Saturday race!")), "the first switched off by its folder's name");
r.Use(game, seeds.Single(x => !x.Mod.On));
Equal("Randomizer Saturday race!", r.Seeds(game).Single(x => x.Mod.On).Mod.Name, "Use: that one on, the other off");
r.Off(game);
Check(r.Seeds(game).All(x => !x.Mod.On), "Off: every seed off");
r.Remove(game, r.Seeds(game).First(x => x.Mod.Name == "Randomizer Saturday race! 2"));
Equal(1, r.Seeds(game).Count, "removed");
Check(Directory.EnumerateDirectories(Path.Combine(game, "mods", Mods.Removed)).Any(), "into mods\\.removed");
// (another mod that is on and carries one of the seed's files, sorting after it, wins it: said)
r.Use(game, r.Seeds(game).Single());
var other = Path.Combine(game, "mods", "Tall grass", "romfs", "Event", "EventFlow");
Directory.CreateDirectory(other);
File.WriteAllText(Path.Combine(other, "Dm_Kokiri_0000.bfevfl.zs"), "other");
var shared = r.Shared(game, r.Seeds(game).Single().Mod.Rel);
Check(shared.Count == 1 && shared[0].Name == "Tall grass" && shared[0].Wins, "the other mod that wins a file");
// (a seed whose other seed cannot be switched off: it is made, and stays off; never two seeds on)
var onNow = r.Seeds(game).Single(x => x.Mod.On);
Directory.CreateDirectory(Path.Combine(game, "mods", "-" + onNow.Mod.Folder)); // (where switching it off would rename it to)
var stuck = await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "Sunday", new RandoCosmetics(), null, CancellationToken.None), "the other seed cannot be switched off");
Check(stuck.Message.StartsWith("Seed Sunday is made, but it stays off: ", StringComparison.Ordinal), "said: " + stuck.Message);
Equal(1, r.Seeds(game).Count(x => x.Mod.On), "still one seed on");
Check(r.Seeds(game).Single(x => x.Seed == "Sunday") is { Mod.On: false } sunday && sunday.Mod.Folder == "-Randomizer Sunday", "the new one is there, off");
Directory.Delete(Path.Combine(game, "mods", "-" + onNow.Mod.Folder));
r.Use(game, r.Seeds(game).Single(x => x.Seed == "Sunday"));
Check(r.Seeds(game).Single(x => x.Mod.On).Seed == "Sunday", "and can be switched on once that is fixed");
// (a seed's file is anyone's to write: its cosmetics are only ever the known ones, its texts kept short)
var marker = Path.Combine(r.Seeds(game).Single(x => x.Seed == "Sunday").Mod.Path, Randomizer.Marker);
File.WriteAllText(marker, "{\"seed\":\"Sunday\",\"music\":\"<img src=x onerror=alert(1)>\",\"colors\":\"random\",\"preset\":\"" + new string('p', 500) + "\"}");
var junk = r.Seeds(game).Single(x => x.Seed == "Sunday");
Equal("off", junk.Cosmetics.Music, "an unknown music value: off");
Equal("random", junk.Cosmetics.Colors, "a known one kept");
Check(junk.Preset.Length <= 80, "a long preset name cut");
File.WriteAllText(marker, "[\"not an object\"]");
Check(r.Seeds(game).All(x => x.Seed != "Sunday"), "a seed file that is no object: not listed as a seed");
// (the kept choices)
r.SaveChoices(new RandoChoices { Values = s.ForOotrr(values), Seed = "abc", Cosmetics = new RandoCosmetics("anywhere", "grouped", "random", false) });
var back = r.LoadChoices();
Equal("abc", back.Seed, "the seed text kept");
Equal(new RandoCosmetics("anywhere", "grouped", "random", false), back.Cosmetics, "the cosmetics kept");
Equal("open", s.Adopt(back.Values)["open_forest"]!.ToString(), "the values kept");
var choices = Path.Combine(ctx.Home, Randomizer.WorkFolder, "choices.json");
Check(File.Exists(choices), "kept in the launcher's randomizer folder (which the uninstall takes away)");
foreach (var bad in new[] { "[1,2]", "\"text\"", "5", "{\"cosmetics\":[1],\"seed\":5,\"values\":\"x\"}", "{\"seed\":\"two\\nlines\"}", "{broken" })
{
File.WriteAllText(choices, bad);
var b = r.LoadChoices();
Check(b.Seed == "" && b.Values == null && b.Cosmetics == new RandoCosmetics(), "a choices file that is not one: the defaults (" + bad + ")");
}
Check(Uninstaller.OwnFolders.Contains(Randomizer.WorkFolder), "the uninstall takes the randomizer's folder away");
}
static async Task RandoFailures()
{
var (_, game, r, _) = RandoSetup("rando-fail");
var s = await r.SchemaAsync(CancellationToken.None);
var e = await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "fail", new RandoCosmetics(), null, CancellationToken.None), "generate fails");
Equal("The randomizer stopped: no placement could be found", e.Message, "OOTRR's own error");
Check(!Directory.Exists(Path.Combine(game, "mods", "Randomizer fail")), "no folder left");
// (stopped while the build writes, a file of its own held open: the program is gone before its folder is taken away)
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)))
await ThrowsAsync<OperationCanceledException>(() => r.MakeAsync(game, s, s.Defaults(), "slow", new RandoCosmetics(), l => { if (l == "Writing flows") cts.Cancel(); }, cts.Token), "stopped part way");
Check(!Directory.Exists(Path.Combine(game, "mods", "Randomizer slow")) && !Directory.Exists(Path.Combine(game, "mods", "-Randomizer slow")), "a stopped build leaves no half-made seed");
Check(!Directory.EnumerateDirectories(Path.Combine(game, "mods"), Randomizer.Making + "*").Any(), "nor its build folder (the file it held let go)");
await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "two\nlines", new RandoCosmetics(), null, CancellationToken.None), "a line break in a seed");
await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), new string('x', Randomizer.MaxSeed + 1), new RandoCosmetics(), null, CancellationToken.None), "a seed too long");
var full = Ctx(Path.GetDirectoryName(game)!, env: new() { ["TRIFORCE_OOTRR_EXE"] = r.Tool.Exe });
full.FreeBytes = _ => 10L << 20;
var cramped = new Randomizer(full, null, new ModManager(full) { GameRuns = _ => false });
var room = await ThrowsAsync<OotrrException>(() => cramped.MakeAsync(game, s, s.Defaults(), "room", new RandoCosmetics(), null, CancellationToken.None), "a disk without room");
Check(room.Message.Length > 0 && !Directory.Exists(Path.Combine(game, "mods", "Randomizer room")), "refused before anything is written: " + room.Message);
// (the check before a seed: what OOTRR refuses, in the settings' words; nothing written in the mods folder)
var refused = s.Defaults();
refused["bridge"] = "tokens";
Equal("Rainbow Bridge is Tokens, which this build cannot apply yet (only Vanilla and Rewards work)", await r.CheckAsync(s, refused, CancellationToken.None), "refused");
Equal(null, await r.CheckAsync(s, s.Defaults(), CancellationToken.None), "the defaults can be made");
Check(!Directory.Exists(Path.Combine(game, "mods")) || !Directory.EnumerateFileSystemEntries(Path.Combine(game, "mods")).Any(), "the check writes no seed");
// (a program that cannot be started is no answer about the settings: it throws, and is asked again next time)
var notYet = Path.Combine(Path.GetDirectoryName(game)!, "not-yet", "ootrr.exe");
var nctx = Ctx(Path.GetDirectoryName(game)!, env: new() { ["TRIFORCE_OOTRR_EXE"] = notYet });
var nr = new Randomizer(nctx, null, new ModManager(nctx) { GameRuns = _ => false });
var gone = await ThrowsAsync<OotrrException>(() => nr.CheckAsync(s, refused, CancellationToken.None), "no program");
Check(gone.Exit == null, "not a refusal of OOTRR's");
Directory.CreateDirectory(Path.GetDirectoryName(notYet)!);
File.WriteAllText(notYet, "not a program");
var bad = await ThrowsAsync<OotrrException>(() => nr.CheckAsync(s, refused, CancellationToken.None), "a program that cannot be started");
Check(bad.Exit == null && bad.Message.StartsWith("The randomizer could not be started", StringComparison.Ordinal), "said: " + bad.Message);
CopySelf(Path.GetDirectoryName(notYet)!, "ootrr.exe");
Equal("Rainbow Bridge is Tokens, which this build cannot apply yet (only Vanilla and Rewards work)", await nr.CheckAsync(s, refused, CancellationToken.None), "asked again: OOTRR's answer");
var (values, warnings) = await r.DecodeAsync(s, "OOTRR1-ABC", CancellationToken.None);
Equal("tokens", values["bridge"]!.ToString(), "a settings string read by OOTRR");
Equal("6", values["trials"]!.ToJsonString(), "a value it would refuse: the default");
Equal(2, warnings.Count, "its warning, and the value it would refuse: " + string.Join(" | ", warnings));
Check(warnings[1].StartsWith("Trials: 99 cannot be used", StringComparison.Ordinal), "which one");
await ThrowsAsync<OotrrException>(() => r.DecodeAsync(s, "hello there", CancellationToken.None), "not a settings string");
await ThrowsAsync<OotrrException>(() => r.DecodeAsync(s, "NOPE", CancellationToken.None), "OOTRR refuses it");
var mm = new ModManager(Ctx(Path.GetDirectoryName(game)!)) { GameRuns = _ => true };
var running = new Randomizer(Ctx(Path.GetDirectoryName(game)!, env: new() { ["TRIFORCE_OOTRR_EXE"] = r.Tool.Exe }), null, mm);
await ThrowsAsync<OotrrException>(() => running.MakeAsync(game, s, s.Defaults(), "x", new RandoCosmetics(), null, CancellationToken.None), "the game runs");
Directory.Delete(Path.Combine(game, "romfs", "Banc"));
var e2 = await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "x", new RandoCosmetics(), null, CancellationToken.None), "no complete romfs");
Check(e2.Message.Contains("romfs"), "it says so");
}
/// <summary>OOTRR_E2E=&lt;ootrr.exe&gt;|&lt;built game folder&gt;: the real program, a real seed built from the real romfs into a copy of
/// the game folder's layout (its romfs read in place; nothing written in the game folder). Skipped without it.</summary>
static async Task RandoRealOotrr()
{
var spec = Environment.GetEnvironmentVariable("OOTRR_E2E");
if (string.IsNullOrEmpty(spec) || spec.Split('|') is not { Length: 2 } parts) { Console.WriteLine(" (skipped: OOTRR_E2E=<ootrr.exe>|<game folder> not set)"); return; }
var root = NewRoot("rando-e2e");
var game = Path.Combine(root, "game");
Directory.CreateDirectory(game);
// (the real romfs through a junction: read in place, never copied, never written)
var link = Path.Combine(game, "romfs");
if (OperatingSystem.IsWindows())
{
// (a junction: no rights needed, unlike a symbolic link)
var si = new System.Diagnostics.ProcessStartInfo("cmd.exe") { UseShellExecute = false, CreateNoWindow = true };
foreach (var a in new[] { "/c", "mklink", "/J", link, Path.Combine(parts[1], "romfs") }) si.ArgumentList.Add(a);
using var p = System.Diagnostics.Process.Start(si)!;
p.WaitForExit();
Check(Directory.Exists(link), "the junction to the real romfs");
}
else Directory.CreateSymbolicLink(link, Path.Combine(parts[1], "romfs"));
// (the link to the real romfs goes whatever happens: a folder cleaned later must never reach the game's files through it)
try
{
var ctx = Ctx(root, env: new() { ["TRIFORCE_OOTRR_EXE"] = parts[0] });
var r = new Randomizer(ctx, null, new ModManager(ctx) { GameRuns = _ => false });
var s = await r.SchemaAsync(CancellationToken.None);
Check(s.Settings.Count > 50 && s.Presets.Count > 0, "the real settings: " + s.Settings.Count);
// (every preset of OOTRR's, as the launcher applies it, makes a seed the build takes)
RandoMade? made = null;
JsonObject values = s.Defaults();
// (one the check refuses must fail the same way at Make, and leave nothing; one it passes must build)
foreach (var p in s.Presets)
{
var v = s.WithPreset(p.Id);
var gaps = s.Gaps(p.Settings);
var says = await r.CheckAsync(s, v, CancellationToken.None);
if (says != null)
{
await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, v, "triforce-e2e-" + p.Id, new RandoCosmetics(), null, CancellationToken.None), "Make refuses what the check refused");
Check(!r.Seeds(game).Any(x => x.Seed == "triforce-e2e-" + p.Id), "nothing left of it");
Console.WriteLine(" preset " + p.Id + ": refused by OOTRR " + Ootrr.Version + ": " + says);
continue;
}
values = v;
made = await r.MakeAsync(game, s, v, "triforce-e2e-" + p.Id, new RandoCosmetics(), null, CancellationToken.None);
Console.WriteLine(" preset " + p.Id + ": built" + (gaps.Count > 0 ? ", with the default for " + string.Join("; ", gaps) : ""));
}
Check(made != null, "a seed");
Equal(1, r.Seeds(game).Count(x => x.Mod.On), "one seed on");
var files = Directory.GetFiles(Path.Combine(made!.Seed.Mod.Path, "romfs"), "*", SearchOption.AllDirectories);
Check(files.Length > 50, "the seed's game files: " + files.Length);
Check(made.Seed.Settings.StartsWith(s.StringPrefix, StringComparison.Ordinal), "a real settings string: " + made.Seed.Settings);
Check(new FileInfo(made.Seed.Spoiler).Length > 1000, "a real spoiler");
var (decoded, _) = await r.DecodeAsync(s, made.Seed.Settings, CancellationToken.None);
Equal(s.ForOotrr(values).ToJsonString(), s.ForOotrr(decoded).ToJsonString(), "the seed's settings string reads back as the settings it was made with");
Console.WriteLine(" " + files.Length + " files, " + files.Sum(f => new FileInfo(f).Length) / (1 << 20) + " MB, settings " + made.Seed.Settings);
}
finally
{
try { if (Directory.Exists(link) && new DirectoryInfo(link).Attributes.HasFlag(FileAttributes.ReparsePoint)) Directory.Delete(link); }
catch (Exception e) { Console.WriteLine(" the link to the real romfs could not be removed: " + link + " (" + e.Message + ")"); }
}
}
}

View File

@@ -208,3 +208,47 @@ body.kb .cp-sv.held.kf { outline: 4px double var(--gold-hi) !important; box-shad
.ehpack .ehp-bar i { display: block; height: 100%; width: 0; background: linear-gradient(90deg, rgb(var(--gold-low-rgb)), rgb(var(--gold-hi-rgb))); box-shadow: 0 0 10px rgba(var(--gold-glow-rgb), .6); transition: width .4s; }
#s-home.nopic .ehpack { top: 192px; }
@media (prefers-reduced-motion: reduce) { .evilhd, .evilhd * { transition: none !important; } }
/* ((Triforce, 11-25) the Randomizer page (rando.js): the settings list on the left, the seed card on the right, the focused row's tip under the list */
#s-rando .settabs { flex-wrap: wrap; width: 800px; row-gap: 8px; }
#s-rando .rset { top: 246px !important; max-height: 520px !important; overflow-y: auto; padding-right: 12px; }
/* the right column: the seed card, then the focused setting's whole description under it (scrolling when long) */
.rside { position: absolute; right: 64px; top: 246px; bottom: 24px; width: 330px; display: flex; flex-direction: column; gap: 16px; }
/* (relative, not static: the box's inner line (.fbox::before) is drawn inside the card, not around the whole column) */
.rside .rcard { position: relative; top: auto; right: auto; flex: 0 0 auto; }
.rcard h3 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rcard .rseedt { color: var(--gold-hi); }
.rcard .rsmall { margin: 14px 0 0; font-size: 12.5px; color: var(--text3); }
.rcard .rline { margin: 10px 0 14px; font-size: 13px; color: var(--text2); min-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rbar { height: 6px; background: rgba(255, 255, 255, .06); outline: 1px solid rgba(var(--gold-rgb), .25); overflow: hidden; }
.rbar i { display: block; height: 100%; background: var(--gold); transition: width .3s; }
.rbar.busy i { width: 30%; animation: rbarrun 1.2s ease-in-out infinite; }
@keyframes rbarrun { 0% { transform: translateX(-100%); } 100% { transform: translateX(340%); } }
/* (the box stays put; its text scrolls inside it, the box's inner line with the box) */
.rtip { flex: 0 1 auto; min-height: 0; overflow: hidden; font-size: 13.5px; line-height: 1.5; color: var(--text2); display: none; }
.rtip.on { display: flex; flex-direction: column; }
.rtip .rtipin { overflow-y: auto; min-height: 0; padding: 16px 20px; }
.rtip b { display: block; font-size: 15px; color: var(--text); margin-bottom: 6px; }
.rtip p { margin: 0; white-space: pre-line; }
.rtipin::-webkit-scrollbar { width: 6px; } .rtipin::-webkit-scrollbar-thumb { background: rgba(var(--gold-rgb), .35); }
/* the randomizer's pickers: each option's description whole, wrapped; the list scrolls when long */
.sheet:has(.ropts) { width: 720px; }
.rintro { margin-top: 8px; font-size: 14px; line-height: 1.5; color: var(--text2); max-height: 140px; overflow-y: auto; padding-right: 8px; white-space: pre-line; }
.ropts { margin-top: 16px; max-height: 400px; overflow-y: auto; padding-right: 8px; }
.ropts .opt:first-of-type { margin-top: 0; }
.ropt { align-items: start; }
.ropt > div { white-space: normal !important; overflow: visible !important; text-overflow: clip !important; }
.ropt .rdesc { display: block; margin-top: 4px; font-size: 13.5px; line-height: 1.45; color: var(--text2); white-space: pre-line; }
.ropt em { font-style: normal; font-size: 12px; font-weight: 600; color: #ff8a92; margin-left: 10px; }
.ropt.dim b { opacity: .7; }
.ropts::-webkit-scrollbar, .rintro::-webkit-scrollbar { width: 6px; } .ropts::-webkit-scrollbar-thumb, .rintro::-webkit-scrollbar-thumb { background: rgba(var(--gold-rgb), .35); }
.rnote { margin-top: 14px !important; }
.rseeds .mod { grid-template-columns: 22px 1fr auto !important; }
.rseeds .rmi { width: 12px; height: 12px; transform: rotate(45deg); outline: 1px solid rgba(var(--gold-rgb), .5); background: transparent; margin-left: 4px; }
.rseeds .rmi.on { background: var(--emerald, #5fd38a); outline-color: transparent; }
.rin { position: static !important; width: 100% !important; margin-top: 16px; }
.rsacts { flex-wrap: wrap; row-gap: 12px; }
.rcard .rproblem { margin: 0 0 14px; font-size: 13px; line-height: 1.45; color: #ff8a92; max-height: 112px; overflow: auto; }
.rseeds .rsn { min-width: 0; } .rseeds .rsn b, .rseeds .rsn span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sheet h3 .mcount { font-family: inherit; font-size: 15px; font-weight: 600; color: var(--text3); }
.rbad { color: #ff8a92 !important; }

View File

@@ -3,7 +3,7 @@
page -> launcher {t:'ready'} {t:'win', a:'min'|'max'|'close'} {t:'pick', kind:'file'|'folder'} {t:'drop', files:[file:// on Linux]}
{t:'cmd', c:<name>, ...args} (build, stop, retry, play, update, playold, showgame, open, lang, folder, setting,
saves.import, saves.export, saves.open, mods.*, bench, benchstop, benchapply,
saves.import, saves.export, saves.open, mods.*, rando.* (rando.js), bench, benchstop, benchapply,
report, sound, color, workback, ...)
launcher -> page {t:'hello', chrome, os} {t:'state', ...parts} {t:'go', s} {t:'check', st, name, msg}
{t:'work', ...} {t:'log', lines} {t:'toast', html} {t:'sfx', id} {t:'bench', ...} {t:'max', on}
@@ -11,7 +11,8 @@
Without a launcher (a plain browser) demo.js answers instead, so the design can be looked at anywhere. */
'use strict';
const $ = (s, r = document) => r.querySelector(s), $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
// ((Triforce, 11-26) the single quote too: a value inside url('...') in a style attribute (a GameBanana picture) cannot end it)
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
/* ---------------- the window this page lives in ---------------- */
const HOST = window.chrome && window.chrome.webview ? 'win' : (window.external && typeof window.external.sendMessage === 'function' ? 'linux' : null);
@@ -234,9 +235,9 @@ document.addEventListener('pointerdown', e => {
});
/* ---------------- screens ---------------- */
const MAIN = ['home', 'mods', 'saves', 'settings'];
const MAIN = ['home', 'mods', 'rando', 'saves', 'settings'];
const FIRST_RUN = ['welcome', 'reveal', 'done'];
const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };
const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', rando: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };
let screen = null;
function go(name) {
if (name === screen || !$('#s-' + name)) return;
@@ -254,6 +255,7 @@ function go(name) {
setFocus($('#' + $('#s-' + name).dataset.first) || focusables()[0], false);
if (name === 'mods' && !S.mods.loaded) cmd('mods.list', { tab: S.mods.tab, q: '' });
if (name === 'saves') cmd('saves.list');
if (name === 'rando') cmd('rando.open');
cmd('screen', { s: name });
}
function afterOneShot(name) { if (name === 'itemget' && (MUSIC[screen] === 'fairy' || screen === 'done')) music('fairy'); }
@@ -277,6 +279,7 @@ function setFocus(el, sound) {
const letGo = focused && focused.id === 'cpSv' && focused.classList.contains('held'); // (the colour square lets go when focus leaves it)
if (letGo) focused.classList.remove('held');
focused = el; el.classList.add('kf');
if (typeof randoFocus === 'function') randoFocus(el); // (the Randomizer page's tip line: rando.js)
if (letGo || el.id === 'cpSv') colorMsg();
if (el.tagName === 'INPUT') el.focus(); else if (document.activeElement && document.activeElement.tagName === 'INPUT') document.activeElement.blur();
if (document.body.classList.contains('kb')) el.scrollIntoView({ block: 'nearest' });
@@ -343,7 +346,7 @@ function back() {
function tab(d) {
if (!MAIN.includes(screen) && screen !== 'bench') return;
const i = MAIN.indexOf(screen === 'bench' ? 'settings' : screen);
sfx(d < 0 ? 'tab_l' : 'tab_r'); go(MAIN[(i + d + 4) % 4]);
sfx(d < 0 ? 'tab_l' : 'tab_r'); go(MAIN[(i + d + MAIN.length) % MAIN.length]);
}
let toastT = 0;
function toast(html) {
@@ -371,6 +374,7 @@ const ACTIONS = {
evilhd: () => { const r = evilRow(); if (!r) return; r.v = +r.v === 1 ? 0 : 1; drawEvilHd(); cmd('gopt.value', { key: 'evil_hd', value: r.v }); },
bringin: () => openSaveFlow('import'),
copyout: () => openSaveFlow('export'),
benchstop: () => cmd('benchstop'), // ((Triforce, 11-26) the run screen's Esc / B: its data-back named this, which was no action)
opt: (a, el) => { $$('.opt', el.parentElement).forEach(o => o.classList.toggle('sel', o === el)); },
row: (id) => settingRow(id),
choose: (id) => cmd('choose', { id }),
@@ -386,6 +390,8 @@ function closeSheet(quiet) {
if (!$('#sheetBg').classList.contains('open')) return;
$('#sheetBg').classList.remove('open'); if (!quiet) sfx('close');
if (sheetReturn && document.contains(sheetReturn) && visible(sheetReturn)) { focused = null; setFocus(sheetReturn); }
// (the row it opened from is gone, drawn anew meanwhile: the screen's first place, never a button of the closed sheet)
else if (screen && $('#s-' + screen)) { focused = null; setFocus($('#' + $('#s-' + screen).dataset.first) || focusables()[0]); }
}
function openVol() { $('#vol').classList.add('open'); sfx('open'); setFocus($('[data-vol="music"]')); }
function closeVol(quiet) { if (!$('#vol').classList.contains('open')) return; $('#vol').classList.remove('open'); if (!quiet) sfx('close'); setFocus($('#spk')); }
@@ -513,7 +519,7 @@ function drawHome() {
$('#playBtn').classList.toggle('off', !!h.off);
$('#hLinks').innerHTML = (h.links || []).map(l => l.act ? `<span class="lnk" data-f data-act="${esc(l.act)}">${l.html}</span>` : `<span>${l.html}</span>`).join('');
const url = picUrl(f);
['#homeImg', '#homePic', '#savesImg', '#modsImg', '#setImg', '#playImg', '#benchImg'].forEach(s => $(s).style.backgroundImage = url);
['#homeImg', '#homePic', '#savesImg', '#modsImg', '#randoImg', '#setImg', '#playImg', '#benchImg'].forEach(s => $(s).style.backgroundImage = url);
$('#s-home').classList.toggle('nopic', !f);
$('#hCap').textContent = f ? `${f.label} · ${f.last ? 'your last save · ' : ''}picture from the game` : '';
$('#strip').innerHTML = files.map((x, i) => `<div class="f${i === S.cur ? ' on' : ''}" data-f data-act="file:${i}" id="f${i}"><img src="${esc(x.pic)}" alt=""><small>${esc(x.label)}</small></div>`).join('');
@@ -589,6 +595,10 @@ function gameRows(tab) {
}
function pct(r) { return r.hi > r.lo ? Math.round((r.v - r.lo) / (r.hi - r.lo) * 1000) / 10 : 0; }
function drawSettings() {
// ((Triforce, 11-26) a game-option slider being dragged, or whose value is on its way, is not drawn over: every state
// message drew the page anew, the dragged slider was gone from under the pointer, and the value at that moment was the one kept)
if (S.gDrag || S.gSend) { S.gPending = true; return; }
S.gPending = false;
const tabs = [{ id: 'launcher', name: 'Launcher' }].concat(S.gameopts && S.gameopts.tabs || []);
if (!tabs.some(t => t.id === S.settab)) S.settab = 'launcher';
const keep = focused && focused.id;
@@ -611,20 +621,36 @@ function gStep(el, v) {
v = Math.max(lo, Math.min(hi, lo + Math.round((v - lo) / st) * st));
el.dataset.v = v; const p = hi > lo ? (v - lo) / (hi - lo) * 100 : 0;
el.querySelector('i').style.width = p + '%'; el.querySelector('u').style.left = p + '%';
const lab = el.parentElement.querySelector('.gval'); if (lab) lab.textContent = String(v);
// (the randomizer's multiples show as 1.5x: rando.js rNum)
const lab = el.parentElement.querySelector('.gval'); if (lab) lab.textContent = el.dataset.times ? (v / +el.dataset.times).toFixed(2).replace(/\.?0+$/, '') + '\u00d7' : String(v);
return v;
}
let gSendT = 0;
function gSend(el) { clearTimeout(gSendT); gSendT = setTimeout(() => cmd('gopt.value', { key: el.dataset.gkey, value: +el.dataset.v }), 350); }
let gSendT = 0, gSendEl = null;
// (the randomizer's page waits while a value is on its way (S.rSend) or a slider is held (S.rDrag), then draws: rando.js drawRando.
// Another slider's value on its way goes at once, so none is lost)
const gKey = el => el.dataset.rkey ? 'r:' + el.dataset.rkey : 'g:' + el.dataset.gkey;
function gFire() {
const el = gSendEl; gSendEl = null; clearTimeout(gSendT); if (!el) return;
if (el.dataset.rkey) { S.rSend = false; cmd('rando.set', { id: el.dataset.rkey, value: +el.dataset.v }); } else { S.gSend = false; cmd('gopt.value', { key: el.dataset.gkey, value: +el.dataset.v }); }
}
function gSend(el) {
if (gSendEl && gKey(gSendEl) !== gKey(el)) gFire();
clearTimeout(gSendT); gSendEl = el;
if (el.dataset.rkey) S.rSend = true; else S.gSend = true;
gSendT = setTimeout(gFire, 350);
}
document.addEventListener('pointerdown', e => {
const s = e.target.closest('.slider[data-gkey]'); if (!s || s.closest('.off')) return;
const s = e.target.closest('.slider[data-gkey], .slider[data-rkey]'); if (!s || s.closest('.off')) return;
e.preventDefault(); setFocus(s, true);
const mv = ev => { const b = s.getBoundingClientRect(); gStep(s, +s.dataset.lo + (ev.clientX - b.left) / b.width * (+s.dataset.hi - +s.dataset.lo)); };
if (s.dataset.rkey) S.rDrag = true; else S.gDrag = true;
// (held by the slider, so letting go outside the window still ends the drag; a move with no button down ends it too)
try { s.setPointerCapture(e.pointerId); } catch (x) { }
const up = () => { removeEventListener('pointermove', mv); removeEventListener('pointerup', up); removeEventListener('pointercancel', up); S.rDrag = false; S.gDrag = false; sfx('cursor'); gSend(s); };
const mv = ev => { if (!ev.buttons) return up(); const b = s.getBoundingClientRect(); if (b.width > 0) gStep(s, +s.dataset.lo + (ev.clientX - b.left) / b.width * (+s.dataset.hi - +s.dataset.lo)); };
mv(e);
const up = () => { removeEventListener('pointermove', mv); removeEventListener('pointerup', up); sfx('cursor'); gSend(s); };
addEventListener('pointermove', mv); addEventListener('pointerup', up);
addEventListener('pointermove', mv); addEventListener('pointerup', up); addEventListener('pointercancel', up);
});
function gNudge(d) { if (!focused || !focused.dataset.gkey || focused.closest('.off')) return false; gStep(focused, +focused.dataset.v + d * (+focused.dataset.step || 1)); sfx('cursor'); gSend(focused); return true; }
function gNudge(d) { if (!focused || !(focused.dataset.gkey || focused.dataset.rkey) || focused.closest('.off')) return false; gStep(focused, +focused.dataset.v + d * (+focused.dataset.step || 1)); sfx('cursor'); gSend(focused); return true; }
function settingRow(id) { cmd('setting', { id }); }
// (the list is asked for each time the page opens, so it shows what is true now: Steam, shortcuts, the game folder)
new MutationObserver(() => { if ($('#s-settings').classList.contains('on')) cmd('settings.list'); }).observe($('#s-settings'), { attributes: true, attributeFilter: ['class'] });
@@ -855,6 +881,9 @@ onHost(m => {
if (!had.music && S.media.music && screen) { const want = MUSIC[screen]; curTrack = null; music(want === 'itemget' ? 'fairy' : want); }
}
drawPill(); drawHome(); drawReveal(); drawSaves(); drawSettings(); if (m.mods) drawMods(); nowPlaying();
if (m.rando && m.rando.schema) S.randoSchema = m.rando.schema; // (OOTRR's settings come once; the rows every time)
if (m.randoMade) S.rtab = 'seeds';
if ((m.rando || m.randoMade) && typeof drawRando === 'function') drawRando();
if (m.done) { $('#doneEb').textContent = S.done.eb || ''; $('#doneLead').textContent = S.done.lead || ''; }
break;
}
@@ -879,7 +908,7 @@ document.addEventListener('keydown', e => {
const ca = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] }[k];
if (ca && colorNudge(ca[0], ca[1])) { } // (the colour picker's square and hue take the arrows first)
else if (focused && focused.dataset.vol && (k === 'ArrowLeft' || k === 'ArrowRight')) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + (k === 'ArrowLeft' ? -.05 : .05)); sfx('cursor'); }
else if (focused && focused.dataset.gkey && (k === 'ArrowLeft' || k === 'ArrowRight')) gNudge(k === 'ArrowLeft' ? -1 : 1);
else if (focused && (focused.dataset.gkey || focused.dataset.rkey) && (k === 'ArrowLeft' || k === 'ArrowRight')) gNudge(k === 'ArrowLeft' ? -1 : 1);
else if (k === 'ArrowLeft') move(-1, 0); else if (k === 'ArrowRight') move(1, 0);
else if (k === 'ArrowUp') move(0, -1); else if (k === 'ArrowDown') move(0, 1);
else if (k === 'Enter' || k === ' ') activate(focused);

View File

@@ -107,8 +107,40 @@
}
}, 100);
}
// ((Triforce, 11-25) the Randomizer page: a few of OOTRR's settings, sample seeds, a pretend download and seed)
const RS = { have: false, frac: 0, busy: false, seeds: [{ id: 'Randomizer K7QW2MPA', seed: 'K7QW2MPA', on: true, sub: 'On · made 24 Nov 2026, 21:10 · OOTRR 0.8.2', settings: 'OOTRR1-AMAQAJQBAETQCAJ', spoiler: true, cos: '' }],
seed: 'R4TN8XQE', cos: { music: 'off', sfx: 'off', colors: 'off', title: true }, preset: 'default',
v: { open_forest: 'closed', zora_fountain: 'closed', shuffle_songs: 'off', shuffle_smallkeys: 'dungeon', bridge: 'vanilla', bridge_rewards: 9, skip_ganon_trials: false, trials: 6, starting_hearts: 3, starting_items: [], enemy_damage: 100, no_heart_drops: false } };
const RSCHEMA = { prefix: 'OOTRR1-', groups: [{ id: 'world', label: 'World', tip: 'How the world starts.' }, { id: 'shuffle', label: 'Shuffles', tip: '' }, { id: 'keys', label: 'Keys', tip: '' }, { id: 'goal', label: 'Goals', tip: '' }, { id: 'starting', label: 'Starting items', tip: '' }, { id: 'difficulty', label: 'Difficulty', tip: 'All off unless you turn them on.' }],
presets: [{ id: 'default', name: 'Default', tip: 'OOTRR\'s defaults.' }, { id: 'easy', name: 'Easy', tip: 'Keys are removed, the world is mostly open and the goals are short.' }, { id: 'keysanity', name: 'Keysanity', tip: 'Keys anywhere.' }],
settings: [
{ id: 'open_forest', label: 'Kokiri Forest', group: 'world', kind: 'choice', tip: 'Whether Mido lets you out of the forest from the start.', choices: [{ id: 'open', label: 'Open', tip: '' }, { id: 'closed', label: 'Closed', tip: '' }] },
{ id: 'zora_fountain', label: "Zora's Fountain", group: 'world', kind: 'choice', tip: 'Whether King Zora starts moved aside.', choices: [{ id: 'closed', label: 'Closed', tip: '' }, { id: 'adult', label: 'Open for adult', tip: '' }, { id: 'open', label: 'Open', tip: '' }] },
{ id: 'shuffle_songs', label: 'Songs', group: 'shuffle', kind: 'choice', tip: 'Where the songs are taught.', choices: [{ id: 'off', label: 'Vanilla', tip: '' }, { id: 'own', label: 'Among the song teachers', tip: '' }, { id: 'anywhere', label: 'Anywhere', tip: '' }] },
{ id: 'shuffle_smallkeys', label: 'Small keys', group: 'keys', kind: 'choice', tip: 'Where small keys can be.', choices: [{ id: 'remove', label: 'Removed', tip: '' }, { id: 'vanilla', label: 'Vanilla', tip: '' }, { id: 'dungeon', label: 'Own dungeon', tip: '' }, { id: 'keysanity', label: 'Anywhere', tip: '' }] },
{ id: 'bridge', label: 'Rainbow Bridge', group: 'goal', kind: 'choice', tip: 'What opens the bridge to Ganon\'s Castle.', choices: [{ id: 'open', label: 'Open', tip: '' }, { id: 'vanilla', label: 'Vanilla', tip: '' }, { id: 'dungeons', label: 'Dungeon rewards', tip: '' }] },
{ id: 'bridge_rewards', label: 'Rewards for the bridge', group: 'goal', kind: 'number', tip: 'How many Stones and Medallions open the bridge.', min: 0, max: 9, step: 1 },
{ id: 'skip_ganon_trials', label: "Skip Ganon's Trials", group: 'goal', kind: 'toggle', tip: 'The barrier is down from the start.' },
{ id: 'trials', label: 'Trials to clear', group: 'goal', kind: 'number', tip: 'How many of the six trials count.', min: 0, max: 6, step: 1 },
{ id: 'starting_hearts', label: 'Starting hearts', group: 'starting', kind: 'number', tip: 'Hearts at the start of a new game.', min: 1, max: 20, step: 1 },
{ id: 'starting_items', label: 'Starting items', group: 'starting', kind: 'multi', tip: 'Items you begin the game with.', choices: [{ id: 'ocarina', label: 'Ocarina', tip: '' }, { id: 'bow', label: 'Bow', tip: '' }, { id: 'hookshot', label: 'Hookshot', tip: '' }, { id: 'hover_boots', label: 'Hover Boots', tip: '' }] },
{ id: 'enemy_damage', label: 'Enemy damage', group: 'difficulty', kind: 'number', tip: 'How hard enemies hit, from 0.5x to 5x.', min: 50, max: 500, step: 25, times: 100 },
{ id: 'no_heart_drops', label: 'No heart drops', group: 'difficulty', kind: 'toggle', tip: 'Enemies and grass drop no hearts.' },
] };
function rshow(x, v) { return x.kind === 'toggle' ? (v ? 'On' : 'Off') : x.kind === 'choice' ? (x.choices.find(c => c.id === v) || {}).label : x.kind === 'multi' ? (v.length ? v.map(i => (x.choices.find(c => c.id === i) || {}).label).join(', ') : 'None') : String(v); }
function rando(withSchema) {
const rows = {};
for (const x of RSCHEMA.settings) {
const hide = (x.id === 'bridge_rewards' && RS.v.bridge !== 'dungeons') || (x.id === 'trials' && RS.v.skip_ganon_trials);
rows[x.id] = { st: hide ? 'hidden' : 'open', v: RS.v[x.id], show: rshow(x, RS.v[x.id]) };
}
const r = { tool: { have: RS.have, version: '0.8.2', size: '4.5 MB', busy: RS.busy && !RS.have, frac: RS.frac, line: RS.busy ? 'Downloading, ' + Math.round(RS.frac * 100) + ' %' : '' },
game: true, busy: RS.have && RS.busy, line: RS.line || '', seed: RS.seed, cos: RS.cos, preset: RS.preset, changed: RS.preset ? 0 : 3, rows, seeds: RS.seeds, note: '' };
if (withSchema) r.schema = RSCHEMA;
emit({ t: 'state', rando: r });
}
window.DEMO = {
jumps: [['welcome', 'First run: welcome'], ['reveal', 'First run: game found'], ['build', 'First run: building'], ['fail', 'Build failed'], ['done', 'First run: ready'], ['home', 'Home'], ['update', 'Home with an update ready'], ['saves', 'Saves'], ['mods', 'Mods'], ['settings', 'Settings'], ['bench', 'Benchmark']],
jumps: [['welcome', 'First run: welcome'], ['reveal', 'First run: game found'], ['build', 'First run: building'], ['fail', 'Build failed'], ['done', 'First run: ready'], ['home', 'Home'], ['update', 'Home with an update ready'], ['saves', 'Saves'], ['mods', 'Mods'], ['rando', 'Randomizer'], ['settings', 'Settings'], ['bench', 'Benchmark']],
jump(j, fn) {
out = fn; clearInterval(st.timer);
if (j === 'welcome') { emit({ t: 'state', media: { art: false, music: false, sfx: true } }); emit({ t: 'go', s: 'welcome' }); }
@@ -161,6 +193,36 @@
else if (c === 'texpackstop') { clearInterval(st.packTimer); st.pack.busy = false; st.pack.have = 'partial'; emit({ t: 'toast', html: 'Download stopped · it goes on where it stopped next time' }); emit(home()); }
else if (c === 'setting' && m.id === 'uninstall') emit({ t: 'ask', title: 'Uninstall Triforce?', html: '<p>Removes the launcher, its tools and the built game.</p><p>Your saves and mods stay in a backup folder.</p>', reply: 'uninstall', buttons: [{ id: 'no', label: 'Keep it' }, { id: 'yes', label: 'Uninstall', main: true }] });
else if (c === 'setting') emit({ t: 'toast', html: m.id + ' <span style="color:var(--text3)">· the launcher does this</span>' });
else if (c === 'rando.open') rando(true);
else if (c === 'rando.install' || c === 'rando.install.go') { RS.busy = true; clearInterval(st.packTimer); st.packTimer = setInterval(() => { RS.frac = Math.min(1, RS.frac + .1); if (RS.frac >= 1) { clearInterval(st.packTimer); RS.have = true; RS.busy = false; emit({ t: 'toast', html: '<b>&#9670;</b> The randomizer is ready · OOTRR 0.8.2', sfx: 'success' }); } rando(RS.have); }, 150); }
else if (c === 'rando.set') { RS.v[m.id] = m.value; RS.preset = null; rando(); }
else if (c === 'rando.pick') { RS.v[m.ctx] = m.id; RS.preset = null; rando(); }
else if (c === 'rando.preset.pick') { RS.preset = m.id; rando(); }
else if (c === 'rando.cos.pick') { RS.cos[m.ctx] = m.id; rando(); }
else if (c === 'rando.cos') { RS.cos.title = m.value === 'on'; rando(); }
else if (c === 'rando.seed') { RS.seed = m.text; rando(); }
else if (c === 'rando.reseed') { RS.seed = Math.random().toString(36).slice(2, 10).toUpperCase(); rando(); }
else if (c === 'rando.decode') { RS.preset = null; emit({ t: 'toast', html: 'Settings taken from the string', sfx: 'success' }); rando(); }
else if (c === 'rando.make') {
RS.busy = true; const lines = ['Placing the items', 'Writing the seed’s game files', 'Title logo: written', 'changed 156 of 236 placed chests']; let i = 0; clearInterval(st.packTimer);
st.packTimer = setInterval(() => {
RS.line = lines[i++];
if (i > lines.length) {
clearInterval(st.packTimer); RS.busy = false; RS.line = ''; RS.seeds.forEach(x => { x.on = false; x.sub = x.sub.replace(/^On/, 'Off'); });
RS.seeds.unshift({ id: 'Randomizer ' + RS.seed, seed: RS.seed, on: true, sub: 'On · made just now · OOTRR 0.8.2', settings: 'OOTRR1-AMAQ', spoiler: true, cos: '' });
emit({ t: 'toast', html: '<b>&#9670;</b> Seed <b>' + RS.seed + '</b> is on · start a <b>new game</b> in an empty file', sfx: 'success' });
RS.seed = Math.random().toString(36).slice(2, 10).toUpperCase(); emit({ t: 'state', randoMade: 1 });
}
rando();
}, 700);
rando();
}
else if (c === 'rando.stop') { clearInterval(st.packTimer); RS.busy = false; RS.line = ''; emit({ t: 'toast', html: 'Stopped · no seed was made' }); rando(); }
else if (c === 'rando.use') { RS.seeds.forEach(x => { x.on = x.id === m.id; x.sub = x.sub.replace(/^(On|Off)/, x.on ? 'On' : 'Off'); }); rando(); }
else if (c === 'rando.off') { RS.seeds.forEach(x => { x.on = false; x.sub = x.sub.replace(/^On/, 'Off'); }); rando(); }
else if (c === 'rando.remove') { RS.seeds = RS.seeds.filter(x => x.id !== m.id); rando(); }
else if (c === 'rando.spoiler') emit({ t: 'ask', title: 'Open the spoiler log?', html: '<p>It lists where every item of this seed is, and one way through the game. Open it only if you want to know.</p>', reply: 'rando.spoiler.go', buttons: [{ id: 'no', label: 'Keep it closed' }, { id: 'go', label: 'Open it', main: true }], ctx: m.id });
else if (c.startsWith('rando.')) emit({ t: 'toast', html: c + ' <span style="color:var(--text3)">· the launcher does this</span>' });
else if (c === 'bench') bench();
else if (c === 'benchstop') { clearInterval(st.timer); emit({ t: 'bench', phase: 'stopped' }); }
else if (c === 'benchapply') { emit({ t: 'go', s: 'settings' }); emit({ t: 'toast', html: '<b>&#9670;</b> Applied · they take effect the next time you play', sfx: 'success' }); }

View File

@@ -76,7 +76,7 @@
</section>
<!-- ============ SAVES ============ -->
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="2">
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="3">
<div class="scene"><div class="img" id="savesImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="savesEb"></div><h1 style="font-size:54px">Your files</h1></div></div>
<div class="sgrid" id="sgrid"></div>
@@ -96,8 +96,17 @@
<div class="modnote" id="modNote"></div>
</section>
<!-- ============ RANDOMIZER (rando.js; launcher/App/Backend.Randomizer.cs) ============ -->
<section class="screen" id="s-rando" data-first="rt-0" data-back="home" data-tab="2">
<div class="scene"><div class="img" id="randoImg" style="filter:blur(26px) saturate(1.1) brightness(.45)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="randoEb">Shuffle the items &#183; every seed can be finished</div><h1 style="font-size:54px">Randomizer</h1></div></div>
<div class="settabs" id="randoTabs"></div>
<div class="set rset" id="rando"></div>
<div class="rside"><div class="benchcard fbox rcard" id="randoCard"></div><div class="rtip fbox" id="randoTip"></div></div>
</section>
<!-- ============ SETTINGS ============ -->
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="3">
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="4">
<div class="scene"><div class="img" id="setImg" style="filter:blur(26px) saturate(1.1) brightness(.45)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="setEb">The launcher and your game</div><h1 style="font-size:54px">Settings</h1></div></div>
<div class="settabs" id="setTabs"></div>
@@ -116,7 +125,7 @@
</section>
<!-- ============ BENCHMARK RESULTS ============ -->
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="3">
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="4">
<div class="scene"><div class="img" id="benchImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="benchEb"></div><h1 style="font-size:54px">Your best settings</h1></div></div>
<div class="bench"><div><div class="places" id="places"></div>
@@ -129,7 +138,7 @@
<!-- ============ shared: the bar, the sound panel, the sheet ============ -->
<div class="bar" id="bar"><div class="brand flair"><div class="mark"></div><span>Triforce</span></div>
<div class="nav" id="nav"><a data-f data-go="home">Play</a><a data-f data-go="mods">Mods</a><a data-f data-go="saves">Saves</a><a data-f data-go="settings">Settings</a></div>
<div class="nav" id="nav"><a data-f data-go="home">Play</a><a data-f data-go="mods">Mods</a><a data-f data-go="rando">Randomizer</a><a data-f data-go="saves">Saves</a><a data-f data-go="settings">Settings</a></div>
<div class="grow"></div><div class="state" id="pill"></div>
<div class="spk on" id="spk" data-f data-act="vol"><svg viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M15.5 9a4.5 4.5 0 0 1 0 6M18 6.5a8 8 0 0 1 0 11"/></svg></div>
<div class="wc"><span data-act="win:min"><svg viewBox="0 0 12 12"><path d="M1 6.5h10"/></svg></span><span data-act="win:max"><svg viewBox="0 0 12 12"><rect x="1.5" y="1.5" width="9" height="9"/></svg></span><span data-act="win:close"><svg viewBox="0 0 12 12"><path d="M1.5 1.5l9 9M10.5 1.5l-9 9"/></svg></span></div></div>
@@ -148,4 +157,5 @@
<div id="jump"></div>
<script src="demo.js"></script>
<script src="app.js"></script>
<script src="rando.js"></script>
</body></html>

202
launcher/ui/rando.js Normal file
View File

@@ -0,0 +1,202 @@
/* ((Triforce, 11-25) The Randomizer page: OOTRR's seeds (launcher/App/Backend.Randomizer.cs). The launcher sends state.rando:
tool {have, version, size, busy, frac, line}, game, busy, line, seed, cos {music, sfx, colors, title}, preset, changed,
rows {<id>: {st: open|held|hidden, v, show, max?, why?}}, seeds [{id, seed, on, sub, settings, spoiler, cos}], note,
schema {prefix, groups [{id,label,tip}], presets [{id,name,tip}], settings [{id,label,group,kind,tip,tag,unsupported,choices?,min?,max?,step?}]}
(the schema once per OOTRR release; the rows each time). Tabs: New seed, OOTRR's own groups, Your seeds. Everything this page
changes goes back as rando.* commands; the launcher answers with the state again. Uses app.js's $, S, ACTIONS, cmd, sheets. */
'use strict';
S.rtab = 'new';
const RCOS = {
music: { label: 'Music', opts: [['off', 'Off', 'The game\'s own music where it always plays'], ['grouped', 'Shuffled within its kind', 'Area themes trade with area themes, fanfares with fanfares'], ['anywhere', 'Shuffled anywhere', 'Any track can play anywhere']] },
sfx: { label: 'Sound effects', opts: [['off', 'Off', 'Every sound as it comes'], ['grouped', 'Shuffled within its kind', 'Sounds trade with sounds of the same kind'], ['anywhere', 'Shuffled anywhere', 'Any sound can stand for any other']] },
colors: { label: 'Colors', opts: [['off', 'Off', 'Tunics and gear in their own colors'], ['random', 'Random', 'Tunics, gauntlets and trails in colors drawn from the seed']] },
};
function rSchema() { return S.randoSchema || null; }
/* a number as the row shows it: a multiple (OOTRR's "times") as 1.5x, else the number */
function rNum(x, v) { return x && x.times ? (v / x.times).toFixed(2).replace(/\.?0+$/, '') + '\u00d7' : String(v); }
function rSetting(id) { const s = rSchema(); return s ? s.settings.find(x => x.id === id) : null; }
/* a description as OOTRR wrote it, its paragraphs kept (shown with white-space: pre-line) */
function rTip(s) { return esc(String(s || '').replace(/\r/g, '').replace(/[ \t]+/g, ' ').replace(/ *\n */g, '\n').replace(/\n{3,}/g, '\n\n').trim()); }
function drawRandoTabs() {
const s = rSchema(), r = S.rando || {};
const tabs = [{ id: 'new', name: 'New seed' }].concat(r.tool && r.tool.have && s ? s.groups.map(g => ({ id: 'g:' + g.id, name: g.label })) : [])
.concat({ id: 'seeds', name: 'Your seeds' + (r.seeds && r.seeds.length ? ' · ' + r.seeds.length : '') });
if (!tabs.some(t => t.id === S.rtab)) S.rtab = 'new';
$('#randoTabs').innerHTML = tabs.map((t, i) => `<span data-f data-act="rtab:${esc(t.id)}" id="rt-${i}" class="${t.id === S.rtab ? 'on' : ''}">${esc(t.name)}</span>`).join('');
const on = tabs.findIndex(t => t.id === S.rtab);
$('#s-rando').dataset.first = 'rt-' + Math.max(0, on);
}
function rRow(id, label, value, act, em, tip, cls) {
return `<div class="row-set${cls ? ' ' + cls : ''}" data-f data-act="${esc(act)}" id="rr-${esc(id)}" data-tip="${tip || ''}"><b>${esc(label)}</b><span>${esc(value)}</span><em>${esc(em)}</em></div>`;
}
function drawRandoNew(r) {
const s = rSchema();
// (OOTRR is there but its settings could not be read: said, with a way to try again)
if (r.tool && r.tool.have && !s && r.schemaError) return `<p class="gnote rnote rbad">OOTRR's settings could not be read: ${esc(r.schemaError)}</p>` +
rRow('retry', 'Read them again', 'Ask OOTRR for its settings once more', 'rando.open', 'Try again', rTip('If it keeps failing, the launcher\'s log says more (Settings, Log folder).'));
if (r.tool && r.tool.have && !s) return '<p class="gnote">Reading OOTRR\'s settings…</p>';
if (!r.tool || !r.tool.have || !s) return `<p class="gnote">${r.tool && r.tool.busy ? 'Getting the randomizer…' : 'Get the randomizer to choose its settings. It is a download of ' + esc(r.tool ? r.tool.size : '5 MB') + ', once.'}</p>`;
const preset = s.presets.find(p => p.id === r.preset);
const cos = r.cos || {};
const cosShow = k => (RCOS[k].opts.find(o => o[0] === cos[k]) || RCOS[k].opts[0])[1];
return '<h4>Settings</h4>' +
rRow('preset', 'Preset', preset ? preset.name : 'Custom · ' + (r.changed || 0) + ' changed from OOTRR\'s defaults', 'rpreset', 'Change', rTip(preset ? preset.tip : 'Your own choice of settings: every tab above shows them.')) +
rRow('string', 'Settings string', 'Paste one to play the same settings as someone else', 'rpaste', 'Paste', rTip('A settings string (it starts with ' + (s.prefix || 'OOTRR1-') + ') sets every setting at once. Your seeds give theirs: Your seeds, then a seed, then Copy settings string.')) +
'<h4>Seed</h4>' +
rRow('seed', 'Seed', r.seed || '(a random one)', 'rseedtext', 'Change', rTip('The same seed with the same settings and OOTRR version makes the same game on every PC: share both for a race.')) +
rRow('reseed', 'New random seed', 'Draw another seed text', 'rando.reseed', 'Draw', rTip('Eight letters and digits, drawn at random.')) +
'<h4>Cosmetics</h4>' +
['music', 'sfx', 'colors'].map(k => rRow('cos-' + k, RCOS[k].label, cosShow(k), 'rcos:' + k, 'Change', rTip(RCOS[k].opts.map(o => o[1] + ': ' + o[2]).join('. ')))).join('') +
rRow('cos-title', 'Title screen', cos.title === false ? 'As it comes' : 'Says Randomizer under the logo', 'rcostitle', cos.title === false ? 'Turn on' : 'Turn off', rTip('OOTRR writes a Randomizer line under the game\'s logo, so a seed is easy to tell from the plain game.')) +
'<h4>About</h4>' +
rRow('about', 'OOTRR ' + r.tool.version, 'The Ocarina of Time Remake Randomizer, by its own team · free software (GPL-3.0)', 'rando.page', 'Its page', rTip('Triforce runs OOTRR\'s own program. Its logic comes from the OoT Randomizer for the N64 game. Report a seed that cannot be finished on its page.'));
}
function drawRandoGroup(r, group) {
const s = rSchema(); if (!s || !r.rows) return '';
const list = s.settings.filter(x => x.group === group && r.rows[x.id] && r.rows[x.id].st !== 'hidden');
if (!list.length) return '<p class="gnote">Nothing to set here with the settings as they are.</p>';
const g = s.groups.find(x => x.id === group);
return (g && g.tip ? `<p class="gnote">${esc(g.tip)}</p>` : '') + list.map(x => {
const row = r.rows[x.id], held = row.st === 'held', soon = !!x.unsupported;
const tip = rTip(x.tip + (held ? ' (' + row.why + ')' : '') + (soon ? ' (OOTRR\'s build does not apply this one yet.)' : ''));
const cls = held || soon || (x.noOn && !row.v) ? 'off' : '';
if (x.kind === 'number' && !held && !soon) {
const hi = row.max != null ? row.max : x.max, v = Math.min(+row.v, hi), p = hi > x.min ? (v - x.min) / (hi - x.min) * 100 : 0;
return `<div class="row-set gs" style="cursor:default" data-tip="${tip}"><b>${esc(x.label)}</b><div class="rng"><div class="slider" data-f data-rkey="${esc(x.id)}" data-lo="${x.min}" data-hi="${hi}" data-step="${x.step || 1}" data-v="${v}"${x.times ? ` data-times="${x.times}"` : ''} id="rr-${esc(x.id)}" data-tip="${tip}"><i style="width:${p}%"></i><u style="left:${p}%"></u></div><span class="gval">${esc(rNum(x, v))}</span></div><em></em></div>`;
}
const em = held ? 'Held' : soon ? 'Not yet' : x.kind === 'toggle' ? (row.v ? 'Turn off' : 'Turn on') : 'Change';
const act = held || soon || (x.noOn && !row.v) ? 'rnone' : x.kind === 'toggle' ? 'rtog:' + x.id : x.kind === 'multi' ? 'rmulti:' + x.id : 'rchoice:' + x.id;
return rRow(x.id, x.label, row.show, act, em, tip, cls);
}).join('');
}
function drawRandoSeeds(r) {
const seeds = r.seeds || [];
if (!seeds.length) return `<p class="gnote">${r.game ? 'No seeds yet. Make one on New seed: it goes into your mods folder, on.' : esc(r.note || '')}</p>`;
return '<div class="rseeds">' + seeds.map((x, i) => `<div class="mod" data-f data-act="rseed:${i}" id="rs${i}" data-tip="${rTip(x.cos ? 'Cosmetics: ' + x.cos : '')}"><div class="mi rmi${x.on ? ' on' : ''}"></div>` +
`<div class="rsn"><b>Seed ${esc(x.seed)}</b><span>${esc(x.sub)}</span></div>${x.on ? '<em class="inst">&#9670; On</em>' : '<em class="offm">Off</em>'}</div>`).join('') + '</div>';
}
function drawRandoCard(r) {
const t = r.tool || {}, card = $('#randoCard');
if (!t.have) {
const pct = Math.round((t.frac || 0) * 100);
card.innerHTML = '<h3>Get the randomizer</h3><p>OOTRR shuffles where the items are, and makes sure every seed can be finished. Triforce downloads its program once (' + esc(t.size || '') + ') and checks it before it runs.</p>' +
(t.busy ? `<div class="rbar"><i style="width:${pct}%"></i></div><p class="rline">${esc(t.line || 'Downloading')}</p>`
: `<div class="play sm" style="width:100%;font-size:23px;height:52px" data-f id="randoGet" data-act="rando.install">Download</div>`);
return;
}
const s = rSchema(), preset = s && s.presets.find(p => p.id === r.preset);
card.innerHTML = `<h3>Seed <span class="rseedt">${esc(r.seed || '')}</span></h3>` +
`<p>${esc(preset ? preset.name : 'Custom settings')} · ${r.changed || 0} changed from OOTRR's defaults</p>` +
(r.busy ? `<div class="rbar busy"><i></i></div><p class="rline">${esc(r.line || 'Working')}</p><div class="qbtn" style="width:100%" data-f id="randoStop" data-act="rando.stop">Stop</div>`
: (r.problem ? `<p class="rproblem">OOTRR cannot make these settings yet: ${esc(r.problem)}</p>` : '') +
`<div class="play sm${r.game && s && !r.problem ? '' : ' off'}" style="width:100%;font-size:23px;height:52px" data-f id="randoMake" data-act="rando.make" data-big>Make the seed</div>`) +
`<p class="rsmall">It goes into your mods folder, on, with your other seeds off. Start a new game in an empty file to play it.</p>` +
((r.seeds || []).some(x => x.on) ? `<p class="rsmall"><span class="lnk" data-f data-act="rando.off" id="randoOff">Turn every seed off</span> to play the game as it comes.</p>` : '');
}
function drawRando() {
const r = S.rando; if (!r) return;
// (a slider being dragged, or one whose value is on its way, is not drawn over: the launcher's answer draws the page then)
if (S.rDrag || S.rSend) { S.rPending = true; return; }
S.rPending = false;
drawRandoTabs();
const keep = focused && focused.id;
const body = S.rtab === 'new' ? drawRandoNew(r) : S.rtab === 'seeds' ? drawRandoSeeds(r) : drawRandoGroup(r, S.rtab.slice(2));
$('#rando').innerHTML = body + (r.note && S.rtab !== 'seeds' ? `<p class="gnote rnote">${esc(r.note)}</p>` : '');
drawRandoCard(r);
$('#randoEb').textContent = r.tool && r.tool.have ? 'OOTRR ' + r.tool.version + ' · every seed can be finished' : 'Shuffle the items · every seed can be finished';
if (keep && $('#' + keep) && screen === 'rando') { focused = null; setFocus($('#' + keep)); }
else if (screen === 'rando' && (!focused || !document.contains(focused))) { focused = null; setFocus($('#' + $('#s-rando').dataset.first)); }
}
/* the focused row's tip, under the list (mouse, keyboard and controller alike) */
function randoFocus(el) {
const box = $('#randoTip'); if (!box) return;
const tip = el && el.closest && el.closest('#s-rando') ? (el.dataset.tip || (el.closest('[data-tip]') || {}).dataset?.tip || '') : null;
if (tip == null) return;
// (data-tip comes back as plain text, the attribute's escaping undone: it is escaped again here, as OOTRR's words and a seed's
// file may hold anything)
const row = el.closest('.row-set, .mod'), name = row && row.querySelector('b') ? row.querySelector('b').textContent : '';
box.innerHTML = tip ? `<div class="rtipin">${name ? `<b>${esc(name)}</b>` : ''}<p>${esc(tip)}</p></div>` : '';
box.classList.toggle('on', !!tip);
}
/* ---------------- sheets ---------------- */
function openInput(title, text, value, reply, placeholder, max) {
openSheet(`<h3>${esc(title)}</h3><p>${text}</p><div class="search rin"><input data-f id="rIn" spellcheck="false" autocomplete="off" maxlength="${max || 4000}" placeholder="${esc(placeholder || '')}" value="${esc(value || '')}"></div>` +
`<div class="acts"><span class="qlink" data-f data-act="closesheet" data-back-sound>Cancel</span><div class="play sm" style="width:200px" data-f id="rInOk" data-act="rinok">OK</div></div>`, 'rIn');
S.rInReply = reply;
const inp = $('#rIn');
inp.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); ACTIONS.rinok(); }
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeSheet(); }
else if (e.key === 'ArrowDown') { e.preventDefault(); e.stopPropagation(); inp.blur(); setFocus($('#rInOk'), true); }
else e.stopPropagation();
});
setTimeout(() => { inp.focus(); inp.select(); }, 30);
}
ACTIONS.rinok = () => { const v = ($('#rIn') || {}).value || ''; const reply = S.rInReply; closeSheet(true); if (reply) cmd(reply, { text: v }); };
function rChoiceSheet(title, text, options, reply, ctx, ok) {
const at = Math.max(0, options.findIndex(o => o.sel));
const opts = options.map((o, i) => `<div class="opt ropt${o.sel ? ' sel' : ''}${o.dim ? ' dim' : ''}" data-f data-act="opt" data-id="${esc(o.id)}" id="op${i}">` +
`<div><b>${esc(o.name)}</b>${o.note ? `<em>${esc(o.note)}</em>` : ''}${o.sub ? `<span class="rdesc">${esc(o.sub)}</span>` : ''}</div><span></span></div>`).join('');
openSheet(`<h3>${esc(title)}</h3>${text ? `<div class="rintro">${text}</div>` : ''}<div class="ropts" id="rOpts">${opts}</div>` +
`<div class="acts"><span class="qlink" data-f data-act="closesheet" data-back-sound>Cancel</span><div class="play sm" style="width:220px" data-f data-act="rchoiceok" id="rChoiceOk">${esc(ok || 'Choose')}</div></div>`, 'op' + at);
S.rChoice = { reply, ctx };
const sel = $('#op' + at); if (sel) sel.scrollIntoView({ block: 'nearest' });
}
ACTIONS.rchoiceok = () => { const o = $('.opt.sel', $('#sheet')), c = S.rChoice; closeSheet(true); if (o && c) cmd(c.reply, { id: o.dataset.id, ctx: c.ctx }); };
function openMulti(x, row) {
const picked = new Set(Array.isArray(row.v) ? row.v : []);
const described = x.choices.some(c => c.tip);
const opts = x.choices.map((c, i) => `<div class="opt${described ? ' ropt' : ''}${picked.has(c.id) ? ' sel' : ''}" data-f data-act="mopt" data-id="${esc(c.id)}" id="mo${i}">` +
`<div><b>${esc(c.label)}</b>${described && c.tip ? `<span class="rdesc">${esc(c.tip)}</span>` : ''}</div><span></span></div>`).join('');
openSheet(`<h3>${esc(x.label)} <span class="mcount" id="mCount"></span></h3><div class="rintro">${rTip(x.tip)}</div><div class="${described ? 'ropts' : 'opts many'}">${opts}</div>` +
`<div class="acts"><span class="qlink" data-f data-act="mclear">None</span><span class="qlink" data-f data-act="closesheet" data-back-sound>Cancel</span><div class="play sm" style="width:200px" data-f data-act="mdone" id="mDone">Done</div></div>`, 'mo0');
S.rMulti = x.id;
mCount();
}
/* how many are ticked, beside the sheet's title */
function mCount() { const n = $$('#sheet .opt.sel').length, c = $('#mCount'); if (c) c.textContent = n ? '\u00b7 ' + n + ' chosen' : ''; }
ACTIONS.mopt = (a, el) => { el.classList.toggle('sel'); mCount(); };
ACTIONS.mclear = () => { $$('#sheet .opt').forEach(o => o.classList.remove('sel')); mCount(); };
ACTIONS.mdone = () => { const v = $$('#sheet .opt.sel').map(o => o.dataset.id); const id = S.rMulti; closeSheet(true); cmd('rando.set', { id, value: v }); };
function openSeedSheet(i) {
const x = ((S.rando || {}).seeds || [])[i]; if (!x) return;
openSheet(`<h3>Seed ${esc(x.seed)}</h3><p>${esc(x.sub)}${x.cos ? ' · ' + esc(x.cos) : ''}</p>` +
`<div class="asktext"><p>${x.on ? 'This seed is on: the game plays it from its next start. Saves you make now belong to it: play them only with it on.' : 'Turning it on turns your other seeds off. Start a new game in an empty file, or load a save you made with this seed.'}</p></div>` +
`<div class="acts rsacts"><span class="qlink" data-f data-act="closesheet">Close</span>` +
(x.spoiler ? `<span class="qlink" data-f data-act="rsgo:spoiler">Spoiler log</span>` : '') +
(x.settings ? `<span class="qlink" data-f data-act="rsgo:copy">Copy settings string</span>` : '') +
`<span class="qlink" data-f data-act="rsgo:folder">Its folder</span><span class="qlink" data-f data-act="rsgo:remove">Remove</span>` +
(x.on ? `<div class="play sm" style="width:200px" data-f data-act="rsoff" id="sh1">Turn off</div>` : `<div class="play sm" style="width:200px" data-f data-act="rsgo:use" id="sh1">Turn on</div>`) + '</div>', 'sh1');
// (the seed by its folder, not its place in the list: a seed made or removed while the sheet is open moves the others)
S.rSheetSeed = x.id;
}
/* ---------------- actions ---------------- */
ACTIONS.rtab = (t) => { S.rtab = t; drawRando(); $('#rando').scrollTop = 0; const i = $$('#randoTabs span').findIndex(s => s.dataset.act === 'rtab:' + t); setFocus($('#rt-' + Math.max(0, i))); };
ACTIONS.rnone = () => sfx('error');
ACTIONS.rtog = (id) => { const row = S.rando.rows[id]; if (row) cmd('rando.set', { id, value: !row.v }); };
ACTIONS.rchoice = (id) => {
const x = rSetting(id), row = S.rando.rows[id]; if (!x || !row) return;
// (an option OOTRR's build cannot apply yet is listed, marked, and refused by the launcher if chosen)
rChoiceSheet(x.label, rTip(x.tip), x.choices.map(c => ({ id: c.id, name: c.label, note: c.live === false ? 'Not in this OOTRR yet' : '', dim: c.live === false, sub: c.tip, sel: c.id === row.v })), 'rando.pick', id);
};
ACTIONS.rmulti = (id) => { const x = rSetting(id), row = S.rando.rows[id]; if (x && row) openMulti(x, row); };
ACTIONS.rpreset = () => {
const s = rSchema(); if (!s) return;
rChoiceSheet('Preset', 'OOTRR\'s own starting points. Every setting can still be changed after.', s.presets.map(p => ({ id: p.id, name: p.name, sub: p.tip, sel: p.id === S.rando.preset })), 'rando.preset.pick', '', 'Use it');
};
ACTIONS.rpaste = () => openInput('Paste a settings string', 'It sets every setting at once, as the seed it came from had them.', '', 'rando.decode', (rSchema() || {}).prefix ? rSchema().prefix + '…' : 'OOTRR1-…');
ACTIONS.rseedtext = () => openInput('Seed', 'Any text, up to ' + (S.rando.maxSeed || 200) + ' letters: the same text with the same settings and OOTRR makes the same seed. Leave it empty for a random one.', S.rando.seed || '', 'rando.seed', 'A word, a date, anything', S.rando.maxSeed || 200);
ACTIONS.rcos = (k) => { const c = RCOS[k]; if (!c) return; rChoiceSheet(c.label, 'Applied when the seed\'s files are written.', c.opts.map(o => ({ id: o[0], name: o[1], sub: o[2], sel: o[0] === (S.rando.cos || {})[k] })), 'rando.cos.pick', k); };
ACTIONS.rcostitle = () => cmd('rando.cos', { key: 'title', value: (S.rando.cos || {}).title === false ? 'on' : 'off' });
ACTIONS.rseed = (i) => openSeedSheet(+i);
ACTIONS.rsgo = (what) => { const id = S.rSheetSeed; closeSheet(true); if (id) cmd('rando.' + what, { id }); };
ACTIONS.rsoff = () => { closeSheet(true); cmd('rando.off'); };