Triforce v0.5.0

In-game mods (GameBanana browser, search and installs, with the Mask Salesman), code-patch and cheat mods, the devs' test18 to test45 work (full performance overlay, frame pacing on, steady frame rate, save export and import, bug capture, new options rows, Setup's Mods page and Add to Steam), occlusion queries and new defaults, Auto resolution that scales, replay helper threads and robust buffers off by default, the options in sections.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-17 22:40:50 -06:00
parent 93eeb714c2
commit 6f338c8f56
600 changed files with 116254 additions and 2522 deletions

View File

@@ -10,7 +10,21 @@ public partial class App : Application
// Why it stopped is one "error <text>" line on stdout (the stream a launcher reads) and again on stderr
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length > 0 && e.Args[0] == "--cli")
var cli = e.Args.Length > 0 && e.Args[0] == "--cli";
// ((Triforce) one builder at a time for its tools, Instance.cs: asked before any build or window)
if (Tools.Find() is { } tools && !Instance.Take(tools.Root))
{
if (cli)
{
var said = "error " + Instance.Refusal(tools.Root).Replace("\n\n", " ");
Console.Out.WriteLine(said);
Console.Error.WriteLine(said);
}
else MessageBox.Show(Instance.Refusal(tools.Root), "Hookshot Builder", MessageBoxButton.OK, MessageBoxImage.Information);
Environment.Exit(1);
return;
}
if (cli)
{
Environment.Exit(Cli(e.Args.Skip(1).ToList()));
return;

View File

@@ -0,0 +1,53 @@
using System;
using System.IO;
using System.Threading;
namespace HookshotBuilder;
/// (Triforce, handoff §5) One Hookshot Builder at a time for its build tools. Two of them on one tools folder ran make_game.py on
/// the same work folder, and make_game.py stops a build it finds running there: the first one's build ended without a reason.
/// The first builder holds a named mutex for as long as it runs (Windows lets go of it when the process ends, however it ends);
/// a second one for the same tools says so and ends. The name comes from the tools folder (Tools.Root), so builders of other
/// folders, Triforce Setup (its lock is named after its own folder) and the game (after its game folder) never meet it.
/// HOOKSHOT_SINGLE_INSTANCE=0: no lock (as before). Plain logic: tests/test_builder_instance.py compiles this file alone
static class Instance
{
static Mutex? held;
/// The lock's name for a tools folder: one for each spelling of it (case, '/' or '\', a separator at its end), a 64-bit FNV-1a
/// of that spelling. Local\: this user's session
public static string Name(string root)
{
try { root = Path.GetFullPath(root); } catch (Exception) { }
var text = root.Replace('/', '\\').TrimEnd('\\').ToUpperInvariant();
var h = 14695981039346656037UL; // (a name, not a secret)
foreach (var c in text) { h ^= c; h *= 1099511628211UL; }
return @"Local\HookshotBuilder-" + h.ToString("x16");
}
/// True when this process now holds the tools folder (or did already; it waited up to waitMs for a builder that was ending),
/// false when another builder does. Where no lock can be made at all nobody is refused
public static bool Take(string root, int waitMs = 5000)
{
if (held != null) return true;
if (Environment.GetEnvironmentVariable("HOOKSHOT_SINGLE_INSTANCE") == "0") return true;
Mutex m;
try { m = new Mutex(false, Name(root)); }
catch (UnauthorizedAccessException) { return false; } // (it is there, and belongs to a builder run as administrator)
catch (Exception) { return true; }
try
{
if (!m.WaitOne(waitMs)) { m.Dispose(); return false; }
}
catch (AbandonedMutexException) { } // (its holder ended without letting go: Windows hands it on, and it is ours)
catch (Exception) { m.Dispose(); return true; }
held = m;
return true;
}
/// What a second builder says
public static string Refusal(string root) =>
"Hookshot Builder is already running for these build tools:\n\n" + root +
"\n\nUse the window that is open, or close it and start the builder again. (Two builders on one tools folder would build " +
"into the same work folder and stop each other's build.)";
}

View File

@@ -0,0 +1,123 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
namespace HookshotBuilder;
/// (Triforce) What the setup (builder/setup/setup.c) lends from the installed version to the one it puts together, and the lock
/// every setup holds while it does. An update moves the folders of parts that did not change (Python, the compiler...) from
/// versions\<installed> into versions\<tag>.part and writes each down first in its reused.txt (the installed version's tag,
/// then a folder a line); a cut-off setup leaves them there. Free gives them back (UndoEveryReuse, setup.c undo_every_reuse,
/// the same rules) and never deletes a <tag>.part that still holds them (Lent): deleted, the installed version lost them for
/// good. Plain logic: tests/test_builder_setup_lock.py compiles this file alone
static class Reuse
{
public const string Note = "reused.txt";
/// True when folder is an unfinished version (a versions\*.part) that still holds folders of another version
public static bool Lent(string folder) =>
Path.GetFileName(folder.TrimEnd('\\', '/')).EndsWith(".part", StringComparison.OrdinalIgnoreCase) &&
File.Exists(Path.Combine(folder, Note));
/// The setup's lock for a setup folder (setup.c setup_lock_name and setup_parts.lock_name, the same): a 64-bit FNV-1a of the
/// folder's full path with '\' between its parts, none at its end, a to z in upper case. Local\: this user's session
public static string LockName(string setupBase)
{
try { setupBase = Path.GetFullPath(setupBase); } catch (Exception) { }
var text = setupBase.Replace('/', '\\').TrimEnd('\\');
var h = 14695981039346656037UL; // (a name, not a secret)
foreach (var c in text) { h ^= c >= 'a' && c <= 'z' ? (uint)(c - 32) : c; h *= 1099511628211UL; }
return @"Local\HookshotBuilder-Setup-" + h.ToString("x16");
}
/// The setup folder held by this thread until Dispose (one that holds nothing where no lock can be made at all), or null
/// when a setup held it for waitMs: one is installing now
public static Held? TakeLock(string setupBase, int waitMs = 0)
{
Mutex m;
try { m = new Mutex(false, LockName(setupBase)); }
catch (UnauthorizedAccessException) { return null; } // (it is there, and belongs to a setup run as administrator)
catch (Exception) { return new Held(null); }
try
{
if (!m.WaitOne(waitMs)) { m.Dispose(); return null; }
}
catch (AbandonedMutexException) { } // (its holder ended without letting go: Windows hands it on, and it is ours)
catch (Exception) { m.Dispose(); return new Held(null); }
return new Held(m);
}
public sealed class Held : IDisposable
{
Mutex? m;
internal Held(Mutex? m) => this.m = m;
public void Dispose()
{
if (m == null) return;
try { m.ReleaseMutex(); } catch (Exception) { }
m.Dispose();
m = null;
}
}
/// The folders a setup moved from the installed version into install (a <tag>.part), moved back: each only where that version
/// has none; the note goes once all went back. True: nothing is left to move back
public static bool Undo(string versions, string install)
{
var note = Path.Combine(install, Note);
string[] lines;
try { lines = File.ReadAllLines(note).Where(l => l.Trim().Length > 0).ToArray(); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return !File.Exists(note); }
if (lines.Length == 0 || !NameOk(lines[0], false)) // (no version named: nothing was moved yet)
{
try { File.Delete(note); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
return true;
}
var ok = true;
foreach (var rel in lines.Skip(1))
{
if (!NameOk(rel, true)) continue;
var from = Path.Combine(install, rel.Replace('/', '\\'));
var back = Path.Combine(versions, lines[0], rel.Replace('/', '\\'));
if (!(Directory.Exists(from) || File.Exists(from)) || Directory.Exists(back) || File.Exists(back)) continue;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(back)!);
if (Directory.Exists(from)) Directory.Move(from, back);
else File.Move(from, back);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { ok = false; }
}
if (ok)
try { File.Delete(note); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
return ok;
}
/// Undo for every versions\*.part with a note; the first whose folders could not all go back (each is tried), null when none
public static string? UndoEveryReuse(string versions)
{
string? left = null;
string[] dirs;
try { dirs = Directory.GetDirectories(versions); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; }
foreach (var d in dirs.OrderBy(d => d, StringComparer.Ordinal))
if (Lent(d) && !Undo(versions, d)) left ??= d;
return left;
}
/// A name from the note (setup.c list_name_ok, the same): letters, digits and . _ + - only (with path, '/' or '\' between
/// its parts), no "." or ".." part, no drive, no root
static bool NameOk(string s, bool path)
{
if (s.Length == 0 || s[0] == '/' || s[0] == '\\') return false;
foreach (var c in s)
if (!(c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' or '.' or '_' or '+' or '-' ||
(path && (c == '/' || c == '\\'))))
return false;
foreach (var part in path ? s.Split('/', '\\') : new[] { s })
if (part.Length == 0 || part == "." || part == "..") return false;
return true;
}
}

View File

@@ -75,17 +75,20 @@ static class Storage
/// What Free lets go. afterBuild: what goes once the game is ready, the compiled objects of the build (objcache, which make_game.py
/// prunes to them) and their system headers' stamp kept, so that the next update compiles only what changed (issue 1287: every
/// update compiled all ~600 files again, an hour and more). The Free up space button lets those go too
static IEnumerable<string> Freeable(bool afterBuild = false)
/// update compiled all ~600 files again, an hour and more). The Free up space button lets those go too. (Triforce) Never an
/// unfinished version that still holds folders of the installed one (Reuse.Lent): deleted, the installed version lost its
/// Python or its compiler for good. installing: a setup holds the folder now, and what it is putting together (downloads\,
/// versions\) stays. Nothing is changed here: Measure counts it
static IEnumerable<string> Freeable(bool afterBuild = false, bool installing = false)
{
foreach (var d in afterBuild ? new[] { "sa", "exefs", "probe" } : new[] { "objcache", "sa", "exefs", "probe" })
yield return Path.Combine(Work, d);
foreach (var d in new[] { "downloads", "update" })
foreach (var d in installing ? new[] { "update" } : new[] { "downloads", "update" })
yield return Path.Combine(Base, d);
var versions = Path.Combine(Base, "versions");
if (Directory.Exists(versions))
if (Directory.Exists(versions) && !installing)
foreach (var v in Directory.EnumerateDirectories(versions))
if (!Kept(v)) yield return v;
if (!Kept(v) && !Reuse.Lent(v)) yield return v;
}
/// Bytes in the builder's folder and the build files folder, and in what Free lets go (an object hard-linked in both sa\build and
@@ -103,12 +106,18 @@ static class Storage
/// Lets go of what Measure counts as freeable; returns the bytes it could not delete (a file in use)
public static long Free(bool afterBuild = false)
{
foreach (var d in Freeable(afterBuild)) Delete(d);
// ((Triforce) what a cut-off setup moved from the installed version goes back first (Reuse.UndoEveryReuse), and then its
// <tag>.part is freeable; one whose folders could not all go back stays. With the setup's folder held: a setup running now
// is not undone under it, and its folders are left alone)
using var setup = Reuse.TakeLock(Base);
var installing = setup == null;
if (!installing) Reuse.UndoEveryReuse(Path.Combine(Base, "versions"));
foreach (var d in Freeable(afterBuild, installing)) Delete(d);
if (!afterBuild) Delete(Path.Combine(Work, "system_headers.txt")); // (the stamp of the compiled objects' system headers goes with them)
if (!afterBuild) return Measure().freeable;
var seen = new HashSet<(uint, ulong)>(); // (what of the after-build set is still there: a file in use)
long left = 0;
foreach (var d in Freeable(afterBuild: true)) left += Size(d, seen);
foreach (var d in Freeable(afterBuild: true, installing)) left += Size(d, seen);
return left;
}

View File

@@ -302,27 +302,85 @@ static class Updater
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
if (!response.IsSuccessStatusCode) throw HttpFailure(response);
var total = response.Content.Headers.ContentLength ?? size;
await using var from = await response.Content.ReadAsStreamAsync(token);
await using var to = File.Create(path);
var buffer = new byte[1 << 20];
long have = 0;
var shown = DateTime.MinValue;
int n;
while (true)
// ((Triforce) the size the release lists, which the server must not contradict; the server's only where none is listed (the
// server's went first, and a short or other file passed as whole). Room for it asked before the first byte, and the bytes
// written to <file>.part, which becomes the file only once complete: a failure removes it)
var told = response.Content.Headers.ContentLength;
if (size > 0 && told is { } other && other != size)
throw new IOException($"The server offers {other} bytes as {Path.GetFileName(path)}, and the release lists {size}. Nothing was downloaded.");
var total = size > 0 ? size : told ?? 0;
if (total > 0 && NoRoom(path, total) is { } none) throw new IOException(none);
var part = path + ".part";
try
{
try { n = await from.ReadAsync(buffer, token); }
catch (IOException e) { throw new HttpRequestException("The download connection ended unexpectedly.", e); }
if (n == 0) break;
await to.WriteAsync(buffer.AsMemory(0, n), token);
have += n;
if (progress != null && total > 0 && DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(200))
await using (var from = await response.Content.ReadAsStreamAsync(token))
await using (var to = File.Create(part))
{
shown = DateTime.UtcNow;
progress(Math.Min(1.0, (double)have / total));
var buffer = new byte[1 << 20];
long have = 0;
var shown = DateTime.MinValue;
int n;
while (true)
{
try { n = await from.ReadAsync(buffer, token); }
catch (IOException e) { throw new HttpRequestException("The download connection ended unexpectedly.", e); }
if (n == 0) break;
await to.WriteAsync(buffer.AsMemory(0, n), token);
have += n;
if (total > 0 && have > total) throw new IOException($"The server sent more than the {total} bytes of {Path.GetFileName(path)}.");
if (progress != null && total > 0 && DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(200))
{
shown = DateTime.UtcNow;
progress(Math.Min(1.0, (double)have / total));
}
}
if (total > 0 && have != total) throw new HttpRequestException($"The download ended early ({have >> 20} of {total >> 20} MB).");
}
File.Move(part, path, true);
}
if (total > 0 && have != total) throw new HttpRequestException($"The download ended early ({have >> 20} of {total >> 20} MB).");
catch (Exception)
{
try { File.Delete(part); } catch (Exception) { }
throw;
}
}
/// ((Triforce) setup/Guard.cs Space, the same rule) Null when the disk of path has room for need bytes and 32 MB more (or
/// cannot be asked); else the sentence that says how much it takes and how much is free
static string? NoRoom(string path, long need)
{
long free;
try { free = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(path))!).AvailableFreeSpace; }
catch (Exception) { return null; }
need += 32L << 20;
return free >= need ? null
: $"There is no room for {Path.GetFileName(path)} on {Path.GetPathRoot(Path.GetFullPath(path))}: it takes {(need + (1 << 20) - 1) >> 20} MB there, and {free >> 20} MB are free. Make room and try again.";
}
static readonly HashSet<string> Devices = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" };
/// ((Triforce) setup/Mods.cs Unsafe, the same rules) Why a zip's member must not be unpacked under its name, null when it may:
/// a path from the disk's root or through "..", a colon (a drive's letter, a hidden stream), a name Windows keeps for a device
/// (with or without an extension), a name that ends in a dot or a space (Windows drops them), a character Windows refuses
internal static string? UnsafeName(string name)
{
var n = name.Replace('\\', '/');
if (n.Trim().Length == 0) return "a file without a name";
if (n[0] == '/') return "a path that starts at the disk's root";
if (n.IndexOf(':') >= 0) return "a name with a colon or a drive's letter";
foreach (var p in n.Split('/'))
{
if (p.Length == 0 || p == ".") continue;
if (p == "..") return "a path that leaves its own folder (..)";
if (p[p.Length - 1] == '.' || p[p.Length - 1] == ' ') return "a name that ends in a dot or a space, which Windows drops";
var dot = p.IndexOf('.');
var stem = (dot >= 0 ? p.Substring(0, dot) : p).TrimEnd(' ');
if (Devices.Contains(stem) || stem.Length == 4 && (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) &&
(stem[3] is >= '1' and <= '9' || stem[3] == (char)0xB9 || stem[3] == (char)0xB2 || stem[3] == (char)0xB3))
return "a name Windows keeps for a device (" + p + ")";
if (p.Any(c => c < 32 || "<>\"|?*".IndexOf(c) >= 0)) return "a name with a character Windows does not allow";
}
return null;
}
static HttpRequestException HttpFailure(HttpResponseMessage response) =>
@@ -335,14 +393,41 @@ static class Updater
error is HttpRequestException { StatusCode: { } status } ? $" (HTTP {(int)status})" : "";
/// The zip's HookshotBuilder folder, as target (an older one there replaced)
/// ((Triforce) every name checked first (UnsafeName: such a zip is refused whole), a failure removes the part, and an older
/// target is moved aside and back when the new one cannot take its place: before, it was deleted first, and a move that
/// failed then left neither)
static async Task<string> Unpack(string zip, string target)
{
var part = target + ".part";
if (Directory.Exists(part)) Directory.Delete(part, true);
await Task.Run(() => ZipFile.ExtractToDirectory(zip, part));
try
{
await Task.Run(() =>
{
using (var z = ZipFile.OpenRead(zip))
foreach (var e in z.Entries)
if (UnsafeName(e.FullName) is { } why)
throw new InvalidDataException($"The download holds {why} (\"{e.FullName}\"): it was not unpacked.");
ZipFile.ExtractToDirectory(zip, part);
});
}
catch (Exception)
{
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
throw;
}
var inner = Path.Combine(part, "HookshotBuilder");
if (Directory.Exists(target)) Directory.Delete(target, true);
Directory.Move(Directory.Exists(inner) ? inner : part, target);
var old = target + ".old";
if (Directory.Exists(old)) Directory.Delete(old, true);
if (Directory.Exists(target)) Directory.Move(target, old);
try { Directory.Move(Directory.Exists(inner) ? inner : part, target); }
catch (Exception)
{
try { if (!Directory.Exists(target) && Directory.Exists(old)) Directory.Move(old, target); } catch (Exception) { }
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
throw;
}
try { if (Directory.Exists(old)) Directory.Delete(old, true); } catch (Exception) { }
if (Directory.Exists(part)) Directory.Delete(part, true);
return target;
}

View File

@@ -11,6 +11,7 @@
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>