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

@@ -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 + ")"); }
}
}
}