Triforce v0.9.0

Character tab, faster renderer defaults, HD rumble shipped, and the 11-30 bug pass: ending softlock below 60 fps, adult first-night lock, Intel Arc robust buffers, adult map, randomizer load order.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-30 20:55:14 -06:00
parent 8cb23131f9
commit 822ee913bc
86 changed files with 8128 additions and 438 deletions

View File

@@ -0,0 +1,427 @@
using System.Text.Json.Nodes;
using Triforce.Core.GameFiles;
using Triforce.Logic;
namespace Triforce.Launcher;
/// <summary>((Triforce, 11-29) The Character page (char.js, char3d.js): Link in 3D from the player's own game files
/// (Core LinkScene), young and adult, in his own colours (Logic LinkColors: OOTRR's recolouring, the randomizer's program).
/// The page is sent what it draws through Content's char/ route, made on a worker first (the route runs on the window's
/// thread and only hands over bytes that are ready):
/// char/scene/N.json, N.bin look N's parts and its posed mesh
/// char/tex/NAME.bin a texture (u32 width, u32 height, RGBA8)
/// char/mask/NAME.bin a colour map's calibration mask (where each of its parts lies)
/// char/exact/N/NAME.bin OOTRR's own recoloured colour map, from preview N
/// Picking a colour is live on the page (a tint over the mask) at once, and OOTRR's exact maps follow a moment later.
/// Apply writes the colours into the game as a mod (mods\~Link colors): every save shows them.</summary>
public sealed partial class Backend
{
LinkColors? linkColors;
LinkColors Colors => linkColors ??= new LinkColors(ctx, Rando.Tool, Rando.Manager);
LinkColors.Choice? charChoice;
LinkColors.Choice CharChoice => charChoice ??= Colors.LoadChoice();
readonly object charGate = new();
readonly Dictionary<string, byte[]> charFiles = new(StringComparer.Ordinal);
readonly Dictionary<string, (LinkScene Scene, string Game)> charScenes = new(StringComparer.Ordinal);
IReadOnlyList<LinkColors.CalMap>? charCal;
string? charCalGame, charCalError;
bool charCalBusy, charBusy;
string charLine = "";
int charN, charApplying;
readonly Dictionary<string, CancellationTokenSource> charPreviewCts = new();
CancellationTokenSource? charApplyCts;
void RegisterCharacter()
{
TextureRecolor.Astc = (texels, w, h) => AstcEncode.EncodeBlock(texels, w, h);
content.Character = CharContent;
OnAsync("char.open", _ => CharOpen());
OnAsync("char.look", m => CharLook((string?)m["look"] ?? "child", (m["have"] as JsonArray)?.Select(x => (string?)x).OfType<string>().ToHashSet() ?? new HashSet<string>()));
On("char.loaded", m => { var n = (int?)m["n"] ?? -1; lock (charGate) foreach (var k in charFiles.Keys.Where(k => k.StartsWith("tex/") || k.StartsWith("scene/" + n + ".")).ToList()) charFiles.Remove(k); });
On("char.set", m => CharSet((string?)m["age"], (string?)m["part"], (string?)m["hex"]));
On("char.many", m => CharMany((string?)m["age"], m["colors"] as JsonObject));
On("char.revert", _ => { charChoice = Colors.Applied(GameDir ?? "")?.Colors.Copy() ?? new LinkColors.Choice(); Colors.SaveChoice(CharChoice); CharPreviewSoon("child"); CharPreviewSoon("adult"); SendChar(); });
OnAsync("char.apply", _ => CharApply());
On("char.install", _ => CharInstallAsk());
On("char.hero", m => CharHero((string?)m["hero"]));
On("char.linkle", _ => CharLinkleAsk());
OnAsync("char.linkle.go", m => (string?)m["id"] == "go" ? CharLinkleGet() : Task.CompletedTask);
On("char.stop", _ => { try { charApplyCts?.Cancel(); } catch { } });
On("char.remove", _ =>
{
if (GameDir is not { } g || Colors.Applied(g) == null) return;
Ask("Back to the game's own colors?", "<p>Link's colors leave the game. Your picks stay here, so you can apply them again.</p>",
"char.remove.go", new[] { ("no", "Keep them", false), ("go", "Use the game's colors", true) });
});
On("char.remove.go", m =>
{
if ((string?)m["id"] != "go" || GameDir is not { } g) return;
try { Colors.Remove(g); Toast("Link wears the game's own colors again", "success"); }
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException) { Toast(H(e.Message), "error"); }
SendChar();
});
}
void CharInstallAsk()
{
if (Colors.Tool.Have || randoToolBusy) return;
Ask("Get the color tool",
"<p>Link's colors are dyed by <b>OOTRR</b>, the Ocarina of Time Remake Randomizer's own program (free software, GPL-3.0, as Triforce is), " +
"the one the Randomizer page uses. It recolors the game's own textures exactly, block by block, so nothing is redrawn or blurred.</p>" +
"<p><b>" + H(Colors.Tool.File.Name) + "</b>, " + Size(Colors.Tool.File.Size) + ", is downloaded once from its release on GitHub and checked " +
"against the fingerprint Triforce knows for it. It reads your game files on this PC only; nothing is uploaded.</p>",
"rando.install.go", new[] { ("no", "Not now", false), ("go", "Download", true) });
}
// ---------------- the page's files ----------------
(byte[], string)? CharContent(string path)
{
// (the name part is unescaped by Content already)
string key;
if (path.StartsWith("scene/", StringComparison.Ordinal) || path.StartsWith("tex/", StringComparison.Ordinal) || path.StartsWith("mask/", StringComparison.Ordinal)
|| path.StartsWith("exact/", StringComparison.Ordinal)) key = path;
else return null;
byte[]? data;
lock (charGate) charFiles.TryGetValue(key, out data);
if (data == null) return null;
return (data, key.EndsWith(".json", StringComparison.Ordinal) ? "application/json" : "application/octet-stream");
}
static byte[] TexFile(int w, int h, byte[] rgba)
{
var f = new byte[8 + rgba.Length];
BitConverter.GetBytes(w).CopyTo(f, 0);
BitConverter.GetBytes(h).CopyTo(f, 4);
rgba.CopyTo(f, 8);
return f;
}
// ---------------- state ----------------
async Task CharOpen()
{
var g = GameDir;
if (g != null) try { Colors.LeftOvers(g); } catch (Exception) { }
SendChar();
// (the exact previews first, then the calibration: once per game, in the background; the page tints live once it is there)
CharPreviewSoon("child", 0); CharPreviewSoon("adult", 0);
if (g != null && Colors.Tool.Have && charCal == null && !charCalBusy) { await Task.Delay(6000); if (charCal == null && !charCalBusy) await CharCalibrate(g); }
else if (charCal != null) SendCal();
}
JsonObject WithLinkleProgress(JsonObject o)
{
o["busy"] = charLinkleGetting == 1; o["frac"] = charLinkleFrac; o["line"] = charLinkleLine;
o["name"] = Linkle.Name; o["author"] = Linkle.Author; o["page"] = Linkle.Page;
return o;
}
void SendChar()
{
var g = GameDir;
var applied = g != null ? Colors.Applied(g) : null;
var choice = CharChoice;
// (who the game shows now: Linkle when her mod is on, whatever the colours' marker says)
var linkleOn = g != null && Linkle.Find(Rando.Manager, g) is { On: true };
var inGame = applied?.Colors.Copy() ?? new LinkColors.Choice();
inGame.Hero = linkleOn ? "linkle" : "link";
var tool = Colors.Tool;
var o = new JsonObject
{
["game"] = g != null,
["tool"] = new JsonObject { ["have"] = tool.Have, ["busy"] = randoToolBusy, ["frac"] = randoToolFrac, ["size"] = Size(tool.File.Size), ["version"] = Ootrr.Version },
["hero"] = choice.Hero,
["linkle"] = g == null ? null : WithLinkleProgress(Linkle.Find(Rando.Manager, g) is { } lm ? new JsonObject { ["have"] = true, ["on"] = lm.On } : new JsonObject { ["have"] = false }),
["parts"] = new JsonArray((choice.Hero == "linkle" ? Linkle.Parts : LinkColors.Parts).Select(p => (JsonNode?)new JsonObject
{
["id"] = p.Id, ["label"] = p.Label, ["group"] = p.Group, ["ages"] = p.Ages, ["tunic"] = p.Tunic, ["swatch"] = p.Swatch,
}).ToArray()),
["colors"] = choice.ToJson(),
["applied"] = applied?.Colors.ToJson(),
["appliedOn"] = applied?.On ?? false,
["same"] = inGame.Same(choice) || (applied == null && !linkleOn && choice.Empty),
["appliedHero"] = inGame.Hero,
["busy"] = charBusy, ["line"] = charLine,
["calBusy"] = charCalBusy, ["calError"] = charCalError,
["others"] = g != null ? new JsonArray(Colors.Others(g).Select(x => (JsonNode?)x).ToArray()) : new JsonArray(),
};
SendState(new JsonObject { ["char"] = o });
}
// ---------------- Link in 3D ----------------
async Task CharLook(string look, HashSet<string> have)
{
if (!LinkScene.Looks.Contains(look) || GameDir is not { } g) return;
var n = Interlocked.Increment(ref charN);
try
{
var data = await Task.Run(() =>
{
var romfs = Path.Combine(g, "romfs");
var hero = CharChoice.Hero;
var her = hero == "linkle" ? Linkle.Find(Rando.Manager, g) : null;
if (hero == "linkle" && her == null) throw new IOException("Linkle is not in the mods folder");
using IGameSource src = her != null ? Linkle.Source(her, g) : new FolderSource(romfs);
var zs = new Zs(src);
LinkScene scene;
lock (charGate)
{
var sk = hero + "/" + look;
if (!charScenes.TryGetValue(sk, out var c) || c.Game != g) charScenes[sk] = c = (LinkScene.Build(src, zs, look, hero, hero == "linkle" ? Linkle.SceneRenames : null), g);
scene = c.Scene;
}
var files = new Dictionary<string, byte[]>
{
["scene/" + n + ".json"] = System.Text.Encoding.UTF8.GetBytes(scene.Info.ToJsonString()),
["scene/" + n + ".bin"] = scene.Mesh,
};
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var p in (JsonArray)scene.Info["parts"]!)
foreach (var role in new[] { "alb", "nrm", "nrm2", "ao", "lut", "grey", "emc" })
if ((string?)p![role] is { } name && !have.Contains(name)) names.Add(name);
Parallel.ForEach(names, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(2, Environment.ProcessorCount / 2) }, name =>
{
try
{
var max = name.EndsWith("_Alb", StringComparison.Ordinal) || name.StartsWith("eye:", StringComparison.Ordinal) ? LinkScene.MaxTexture : LinkScene.MaxTexture / 2;
if (LinkScene.Texture(src, zs, hero == "linkle" ? Linkle.Original(name) : name, max) is { } t)
lock (files) files["tex/" + name + ".bin"] = TexFile(t.W, t.H, t.Rgba);
}
catch (Exception e) { Log.Write("character: texture " + name + ": " + e.Message); }
});
return files;
});
lock (charGate) foreach (var (k, v) in data) charFiles[k] = v;
Send(new JsonObject { ["t"] = "charLook", ["look"] = look, ["n"] = n, ["hero"] = CharChoice.Hero });
}
catch (Exception e) when (e is IOException || e is InvalidDataException || e is NotSupportedException || e is DirectoryNotFoundException)
{
Log.Write("character: " + look + ": " + e);
Send(new JsonObject { ["t"] = "charLook", ["look"] = look, ["n"] = n, ["error"] = "Link could not be read from your game: " + e.Message });
}
}
// ---------------- colours ----------------
void CharSet(string? age, string? part, string? hex)
{
var hero = CharChoice.Hero;
if (age == null || part == null || !LinkColors.Valid(hero, age, part)) return;
var clean = hex == null ? null : LinkColors.CleanHex(hex);
var ages = LinkColors.Shared.Contains(part) ? new[] { "child", "adult" } : new[] { age };
lock (charGate)
foreach (var a in ages)
if (clean == null) CharChoice.Age(LinkColors.Key(hero, a)).Remove(part); else CharChoice.Age(LinkColors.Key(hero, a))[part] = clean;
Colors.SaveChoice(CharChoice);
foreach (var a in ages) CharPreviewSoon(a);
SendChar();
}
/// <summary>Several parts at once (a preset, Randomize, Reset): colors {part: hex | null}; parts not named stay.</summary>
void CharMany(string? age, JsonObject? colors)
{
if (age is not ("child" or "adult") || colors == null) return;
lock (charGate)
foreach (var (part, v) in colors)
{
if (!LinkColors.Valid(CharChoice.Hero, age, part)) continue;
var hex = v is JsonValue jv && jv.TryGetValue<string>(out var s) ? LinkColors.CleanHex(s) : null;
foreach (var a in LinkColors.Shared.Contains(part) ? new[] { "child", "adult" } : new[] { age })
if (hex == null) CharChoice.Age(LinkColors.Key(CharChoice.Hero, a)).Remove(part); else CharChoice.Age(LinkColors.Key(CharChoice.Hero, a))[part] = hex;
}
Colors.SaveChoice(CharChoice);
CharPreviewSoon("child"); CharPreviewSoon("adult");
SendChar();
}
JsonArray? charCalMsg;
void SendCal() { if (charCalMsg != null) Send(new JsonObject { ["t"] = "charCal", ["maps"] = charCalMsg.DeepClone() }); }
async Task CharCalibrate(string g)
{
charCalBusy = true; charCalError = null; SendChar();
try
{
var stamp = GameStamp(g);
var cal = await Colors.CalibrateAsync(g, stamp, CancellationToken.None);
var arr = new JsonArray();
lock (charGate)
foreach (var m in cal)
{
charFiles["mask/" + m.Texture + ".bin"] = TexFile(m.Width, m.Height, m.Mask);
arr.Add(new JsonObject
{
["tex"] = LinkColors.ModelName(m.Texture), ["file"] = m.Texture,
["parts"] = new JsonArray(m.Parts.Select(p => (JsonNode?)p).ToArray()),
["ym"] = new JsonArray(m.Ym.Select(y => (JsonNode?)y).ToArray()), ["qm"] = new JsonArray(m.Qm.Select(y => (JsonNode?)y).ToArray()),
["ty"] = new JsonArray(m.Ty.Select(y => (JsonNode?)y).ToArray()),
["g"] = new JsonArray(m.G.Select(y => (JsonNode?)y).ToArray()),
});
}
charCal = cal; charCalGame = g; charCalMsg = arr;
SendCal();
}
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException || e is InvalidDataException || e is InvalidOperationException)
{
Log.Write("character: calibration: " + e);
charCalError = e.Message;
}
finally { charCalBusy = false; SendChar(); }
}
/// <summary>A name for this game's files (the folder and Link's model as they are): the calibration is kept under it.</summary>
static string GameStamp(string g)
{
var f = new FileInfo(Path.Combine(g, "romfs", "Model", "Player_Child.Player_Child.bfres.zs"));
var key = g.ToLowerInvariant() + "|" + (f.Exists ? f.Length + "-" + f.LastWriteTimeUtc.Ticks : "none") + "|" + Ootrr.Version;
return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(key)))[..16].ToLowerInvariant();
}
/// <summary>OOTRR's exact maps for one age, a moment after the last change (a newer change cancels a preview that runs).</summary>
void CharPreviewSoon(string age, int delayMs = 650)
{
if (GameDir is not { } g || (!Colors.Tool.Have && CharChoice.Hero != "linkle")) return;
CancellationTokenSource cts;
lock (charPreviewCts)
{
if (charPreviewCts.TryGetValue(age, out var old)) { try { old.Cancel(); } catch { } }
charPreviewCts[age] = cts = new CancellationTokenSource();
}
Dictionary<string, string> colors;
string hero;
lock (charGate) { hero = CharChoice.Hero; colors = new Dictionary<string, string>(CharChoice.Of(age)); }
var key = LinkColors.Key(hero, age);
_ = Task.Run(async () =>
{
try
{
await Task.Delay(delayMs, cts.Token);
var maps = hero == "linkle" ? await LinklePreview(g, age, colors, cts.Token) : await Colors.PreviewAsync(g, colors, cts.Token);
cts.Token.ThrowIfCancellationRequested();
var n = Interlocked.Increment(ref charN);
lock (charGate)
{
foreach (var k in charFiles.Keys.Where(k => k.StartsWith("exact/" + key + "/", StringComparison.Ordinal)).ToList()) charFiles.Remove(k);
foreach (var (tex, t) in maps) charFiles["exact/" + key + "/" + n + "/" + tex + ".bin"] = TexFile(t.W, t.H, t.Rgba);
}
Send(new JsonObject
{
["t"] = "charExact", ["age"] = age, ["hero"] = hero, ["key"] = key, ["n"] = n,
["colors"] = new JsonObject(colors.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)kv.Value))),
["tex"] = new JsonArray(maps.Keys.Select(k => (JsonNode?)k).ToArray()),
});
}
catch (OperationCanceledException) { }
catch (Exception e) when (e is OotrrException || e is IOException || e is InvalidDataException || e is NotSupportedException)
{
Log.Write("character: preview " + age + ": " + e.Message);
}
});
}
/// <summary>Linkle's dyed textures for one age (the launcher's own dye), and adult hair from the colour tool.</summary>
async Task<Dictionary<string, (int W, int H, byte[] Rgba)>> LinklePreview(string g, string age, Dictionary<string, string> colors, CancellationToken token)
{
var maps = new Dictionary<string, (int W, int H, byte[] Rgba)>(StringComparer.Ordinal);
if (colors.Count == 0) return maps;
var mod = Linkle.Find(Rando.Manager, g);
if (mod == null) return maps;
await Task.Run(() =>
{
using var her = Linkle.Source(mod, g);
var zs = new Zs(her);
foreach (var (tex, (_, _, prev)) in Linkle.Dye(her, zs, age, colors)) maps[tex] = prev;
}, token);
if (age == "adult" && colors.TryGetValue("hair", out var hair) && Colors.Tool.Have)
foreach (var (tex, m) in await Colors.PreviewAsync(g, new Dictionary<string, string> { ["hair"] = hair }, token))
if (tex == "Mt_Hairs_Player_Adult_Alb") maps[tex] = m;
return maps;
}
void CharHero(string? hero)
{
if (hero is not ("link" or "linkle") || hero == CharChoice.Hero) return;
lock (charGate) CharChoice.Hero = hero;
Colors.SaveChoice(CharChoice);
SendChar();
if (hero == "link" || (GameDir is { } g && Linkle.Find(Rando.Manager, g) != null)) { CharPreviewSoon("child", 0); CharPreviewSoon("adult", 0); }
}
int charLinkleGetting;
double charLinkleFrac;
string charLinkleLine = "";
void CharLinkleAsk()
{
Ask("Get Linkle",
"<p><b>" + H(Linkle.Name) + "</b> by <b>" + H(Linkle.Author) + "</b> replaces Link with Linkle from Hyrule Warriors, young and adult, " +
"with her own voice, gear and fairy, Liri.</p><p>It is downloaded from its page on GameBanana (about 320 MB) into your mods folder, " +
"as the Mods page does. It is the author's work: Triforce only installs it and switches it on and off.</p>",
"char.linkle.go", new[] { ("no", "Not now", false), ("go", "Download", true) });
}
async Task CharLinkleGet()
{
if (GameDir is not { } g || Interlocked.CompareExchange(ref charLinkleGetting, 1, 0) != 0) return;
charLinkleFrac = 0; charLinkleLine = "Asking GameBanana"; SendChar();
try
{
var d = await Gb.DetailsAsync(Linkle.GameBananaId, false);
if (d.Files.Count == 0) throw new ModsException("Its GameBanana page has no file to download.");
var file = d.Files[d.DefaultFile(false)];
var card = new GbMod(Linkle.GameBananaId, false, Linkle.Name, Linkle.Author, "", Linkle.Page, 0, 0, 0, null);
var last = DateTime.MinValue;
await new GameBananaInstaller(ctx).InstallAsync(gbHttp.Value, card, file, g, p =>
{
charLinkleFrac = p.Fraction; charLinkleLine = p.Fraction >= 1 ? "Unpacking" : "Downloading, " + (int)(p.Fraction * 100) + " %";
if ((DateTime.UtcNow - last).TotalMilliseconds < 500) return;
last = DateTime.UtcNow; SendChar();
}, CancellationToken.None);
Toast("<b>&#9670;</b> Linkle is in your mods folder", "success");
CharHero("linkle");
}
catch (Exception e) when (e is ModsException || e is HttpRequestException || e is IOException || e is UnauthorizedAccessException || e is TaskCanceledException || e is InvalidOperationException || e is System.Text.Json.JsonException)
{
Log.Write("character: linkle: " + e);
Toast("Linkle could not be downloaded: " + H(e.Message), "error");
}
finally { charLinkleLine = ""; Interlocked.Exchange(ref charLinkleGetting, 0); SendChar(); }
}
async Task CharApply()
{
if (GameDir is not { } g) return;
if (!Colors.Tool.Have) { CharInstallAsk(); return; }
if (Interlocked.CompareExchange(ref charApplying, 1, 0) != 0) return;
LinkColors.Choice choice;
lock (charGate) choice = CharChoice.Copy();
charBusy = true; charLine = "Getting ready"; SendChar();
var cts = charApplyCts = new CancellationTokenSource();
try
{
var dest = await Colors.ApplyAsync(g, choice, l => { charLine = l; SendChar(); }, cts.Token);
if (dest == null) Toast("Link wears the game's own colors again", "success");
else
{
var others = Colors.Others(g);
Toast("<b>&#9670;</b> Link's colors are in your game · every save, the next time you play" +
(others.Count > 0 ? " · they show over " + H(string.Join(", ", others)) : ""), "success");
Sfx("success");
}
}
catch (OperationCanceledException) { Toast("Stopped: your game keeps the colors it had"); }
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException || e is InvalidDataException || e is ModsException)
{
Log.Write("character: apply: " + e);
Toast("The colors could not be applied: " + H(e.Message), "error");
}
finally
{
charBusy = false; charLine = ""; charApplyCts = null;
Interlocked.Exchange(ref charApplying, 0);
SendChar();
}
}
}

View File

@@ -55,6 +55,13 @@ public sealed partial class Backend
OnAsync("retry", _ => retry != null ? retry() : Task.CompletedTask);
On("workback", _ => { StopWork(); Go(workKind == "update" ? "home" : "reveal"); });
On("play", _ => Play());
// ((Triforce, 11-30) Play's question when the mods' code patches wait for a build: PlayOne)
On("play.mods", m =>
{
var id = (string?)m["id"];
if (id == "build") StartRebuild();
else if (id == "anyway") { playModsAnyway = true; Play(); }
});
On("playold", _ => Play());
On("showgame", _ => ShowGame());
OnAsync("update", _ => UpdateNow(start.Args.UpdateFolder));
@@ -86,7 +93,7 @@ public sealed partial class Backend
// (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("screen", m => { pageScreen = (string?)m["s"]; });
On("open", m => OpenThing((string?)m["arg"] ?? ""));
On("report", _ => Copy(Report.ForBuild(ctx, lastResult, runner?.Details ?? "", new Tools(ctx).InstalledVersion, lastFailure)));
On("sound", m =>
@@ -636,6 +643,7 @@ public sealed partial class Backend
}
// ---------------- Play ----------------
bool playModsAnyway; // ((Triforce, 11-30) "Play anyway" once this session: Play does not ask about the mods' build again
void Play()
{
// ((Triforce, 11-26) one start at a time: two clicks on Play started two games before the first was seen running)
@@ -651,6 +659,18 @@ public sealed partial class Backend
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; }
// ((Triforce, 11-30) #bug-tracker: crashes at the start or the first load (guest 0x1, 0x10 writes) whose logs say "mods: N code
// patches wait for a build": a mod with code patches was added, removed or switched since the game was built, so its game files
// and the code built in no longer match. The Mods page said so; Play did not. Asked once a session: Build now, or Play anyway)
if (!playModsAnyway && SafeNeedsRebuild(g))
{
Ask("Your mods need a build",
"<p>A mod with code patches was added, removed or switched on or off since the game was built. Until the game is built " +
"again its code and that mod's files don't match, and the game can crash at the start or when a save loads.</p>" +
"<p>Building again takes <b>" + H(RebuildTime()) + "</b>. Your saves and mods stay.</p>",
"play.mods", new[] { ("anyway", "Play anyway", false), ("build", "Build now", true) });
return;
}
gameProc = game.Play(g);
if (gameProc == null) { Toast("The game would not start. Settings, Build the game again, repairs a broken game folder.", "error"); return; }
Log.Write("play " + g);
@@ -708,6 +728,7 @@ public sealed partial class Backend
{
"help" => BuildInfo.Home,
"changes" => release?.PageUrl ?? BuildInfo.Home,
"linkle" => Linkle.Page,
_ => what.StartsWith("https://", StringComparison.Ordinal) ? what : null,
};
// (through OpenLink: https only, whatever the release feed or the page says; a test run opens nothing)

View File

@@ -261,6 +261,7 @@ public sealed partial class Backend
if ((DateTime.UtcNow - last).TotalMilliseconds < 400) return;
last = DateTime.UtcNow;
SendRando();
if (pageScreen == "char") SendChar();
}, CancellationToken.None);
randoToolLine = "Reading its settings";
SendRando();
@@ -273,7 +274,12 @@ public sealed partial class Backend
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); }
finally
{
randoToolBusy = false; randoToolLine = ""; Interlocked.Exchange(ref randoInstalling, 0); SendRando(true);
// ((Triforce, 11-29) the Character page uses the same program for Link's colors)
if (pageScreen == "char") _ = CharOpen(); else SendChar();
}
}
// ---------------- the settings ----------------
@@ -427,7 +433,7 @@ public sealed partial class Backend
}, 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)";
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: the seed may not work (chests that stay shut) while " + (wins.Count == 1 ? "it is" : "they are") + " on (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)

View File

@@ -11,7 +11,8 @@ namespace Triforce.Launcher;
/// Backend.Saves.cs the Saves page (RegisterSaves)
/// Backend.Mods.cs the Mods page (RegisterMods)
/// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings)
/// Backend.Randomizer.cs the Randomizer page (OOTRR's seeds) (RegisterRandomizer)</summary>
/// Backend.Randomizer.cs the Randomizer page (OOTRR's seeds) (RegisterRandomizer)
/// Backend.Character.cs the Character page (Link in 3D, his colors) (RegisterCharacter)</summary>
public sealed partial class Backend
{
readonly IHost host;
@@ -20,13 +21,15 @@ public sealed partial class Backend
readonly TriforceContext ctx;
readonly StartupResult start;
readonly Dictionary<string, Action<JsonNode, string[]>> cmds = new();
/// <summary>The screen the page shows (its 'screen' message).</summary>
string? pageScreen;
public Backend(IHost host, Content content, TriforceContext ctx, StartupResult start, string dataDir)
{
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(); RegisterRandomizer();
RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack(); RegisterRandomizer(); RegisterCharacter();
}
partial void RegisterSaves();

View File

@@ -7,6 +7,7 @@ namespace Triforce.Launcher;
/// media/png/NAME a texture from the player's own game (Core/GameFiles), e.g. the title logo
/// media/wav/ID music or a sound from the player's own game
/// save/N.jpg the picture in save file N (the game's own caption.sav)
/// char/... the Character page's Link: his posed mesh, textures, masks and recoloured maps
/// Anything not there answers 404, and the page falls back (no game yet: no game art, no music).</summary>
public sealed class Content
{
@@ -16,6 +17,8 @@ public sealed class Content
readonly Dictionary<string, string> names;
public MediaSource? Media;
public Func<int, byte[]?>? SavePicture;
/// <summary>((Triforce, 11-29) char/...: the Character page's model, textures and colour maps (Backend.Character.cs).</summary>
public Func<string, (byte[] Data, string Mime)?>? Character;
public Content()
{
@@ -48,6 +51,8 @@ public sealed class Content
var data = Media(parts[1], name);
return data == null ? null : (data, parts[1] == "png" ? "image/png" : "audio/wav");
}
if (path.StartsWith("char/", StringComparison.Ordinal) && Character != null)
return Character(path["char/".Length..]);
if (path.StartsWith("save/", StringComparison.Ordinal) && SavePicture != null &&
int.TryParse(Path.GetFileNameWithoutExtension(path)[..Math.Min(2, Path.GetFileNameWithoutExtension(path).Length)], out var n))
{

View File

@@ -21,7 +21,7 @@ public static class Astc
// ---- bit streams ----
/// <summary>Reads bits from the low bit of the first byte upward; past the end it reads zeros.</summary>
ref struct InputBitStream
internal ref struct InputBitStream
{
readonly ReadOnlySpan<byte> data;
int bitsRead;
@@ -91,9 +91,9 @@ public static class Astc
// ---- bounded integer sequences ----
enum IntegerEncoding : byte { JustBits, Quint, Trit }
internal enum IntegerEncoding : byte { JustBits, Quint, Trit }
struct IntegerEncodedValue
internal struct IntegerEncodedValue
{
public IntegerEncoding Encoding;
public int NumBits;
@@ -143,7 +143,7 @@ public static class Astc
return new IntegerEncodedValue(IntegerEncoding.JustBits, 0);
}
static readonly IntegerEncodedValue[] Encodings = MakeEncodedValues();
internal static readonly IntegerEncodedValue[] Encodings = MakeEncodedValues();
static IntegerEncodedValue[] MakeEncodedValues()
{
@@ -155,7 +155,7 @@ public static class Astc
/// <summary>A fixed-capacity list of decoded values (boost::static_vector without throwing: values past the capacity
/// are dropped, as there).</summary>
sealed class EncodedVector
internal sealed class EncodedVector
{
public readonly IntegerEncodedValue[] Items = new IntegerEncodedValue[300];
public int Count;
@@ -167,7 +167,7 @@ public static class Astc
}
}
static void DecodeTritBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue)
internal static void DecodeTritBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue)
{
// (section C.2.12: read the trit-encoded block per table C.2.14)
Span<uint> m = stackalloc uint[5];
@@ -230,7 +230,7 @@ public static class Astc
}
}
static void DecodeQuintBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue)
internal static void DecodeQuintBlock(ref InputBitStream bits, EncodedVector result, int nBitsPerValue)
{
// (section C.2.12: read the quint-encoded block per table C.2.15)
Span<uint> m = stackalloc uint[3];
@@ -308,7 +308,7 @@ public static class Astc
// ---- block mode ----
struct TexelWeightParams
internal struct TexelWeightParams
{
public uint Width, Height;
public bool DualPlane;
@@ -332,7 +332,7 @@ public static class Astc
}
}
static TexelWeightParams DecodeBlockInfo(ref InputBitStream strm)
internal static TexelWeightParams DecodeBlockInfo(ref InputBitStream strm)
{
var p = new TexelWeightParams();
// (the whole block mode at once)
@@ -523,7 +523,7 @@ public static class Astc
// ---- color endpoints ----
static void DecodeColorValues(Span<uint> output, ReadOnlySpan<byte> data, ReadOnlySpan<uint> modes, int nPartitions,
internal static void DecodeColorValues(Span<uint> output, ReadOnlySpan<byte> data, ReadOnlySpan<uint> modes, int nPartitions,
int nBitsForColorData, EncodedVector decoded)
{
// (how many color values there are)
@@ -668,7 +668,7 @@ public static class Astc
}
}
static uint UnquantizeTexelWeight(IntegerEncodedValue val)
internal static uint UnquantizeTexelWeight(IntegerEncodedValue val)
{
var bitval = val.BitValue;
var bitlen = val.NumBits;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,220 @@
// (Triforce, 11-29) BC7 (BPTC unorm) decoding to RGBA8, for the Character page's textures (Link's face and adult hair are BC7).
// Written from the format's specification (the D3D11 functional spec / KHR_texture_compression_bptc): 8 modes, 1-3 subsets,
// partition tables, P-bits, index rotation and the separate alpha indexes of modes 4 and 5.
namespace Triforce.Core.GameFiles;
public static class Bc7
{
struct Mode
{
public int Subsets, PartBits, RotBits, IdxSelBits, ColorBits, AlphaBits, EndPBits, SharedPBits, IdxBits, Idx2Bits;
public Mode(int ns, int pb, int rb, int isb, int cb, int ab, int epb, int spb, int ib, int ib2)
{ Subsets = ns; PartBits = pb; RotBits = rb; IdxSelBits = isb; ColorBits = cb; AlphaBits = ab; EndPBits = epb; SharedPBits = spb; IdxBits = ib; Idx2Bits = ib2; }
}
static readonly Mode[] Modes =
{
new(3, 4, 0, 0, 4, 0, 1, 0, 3, 0),
new(2, 6, 0, 0, 6, 0, 0, 1, 3, 0),
new(3, 6, 0, 0, 5, 0, 0, 0, 2, 0),
new(2, 6, 0, 0, 7, 0, 1, 0, 2, 0),
new(1, 0, 2, 1, 5, 6, 0, 0, 2, 3),
new(1, 0, 2, 0, 7, 8, 0, 0, 2, 2),
new(1, 0, 0, 0, 7, 7, 1, 0, 4, 0),
new(2, 6, 0, 0, 5, 5, 1, 0, 2, 0),
};
static readonly byte[] W2 = { 0, 21, 43, 64 };
static readonly byte[] W3 = { 0, 9, 18, 27, 37, 46, 55, 64 };
static readonly byte[] W4 = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 };
static readonly uint[] P2 =
{
0xCCCC, 0x8888, 0xEEEE, 0xECC8, 0xC880, 0xFEEC, 0xFEC8, 0xEC80, 0xC800, 0xFFEC, 0xFE80, 0xE800, 0xFFE8, 0xFF00, 0xFFF0, 0xF000,
0xF710, 0x008E, 0x7100, 0x08CE, 0x008C, 0x7310, 0x3100, 0x8CCE, 0x088C, 0x3110, 0x6666, 0x366C, 0x17E8, 0x0FF0, 0x718E, 0x399C,
0xAAAA, 0xF0F0, 0x5A5A, 0x33CC, 0x3C3C, 0x55AA, 0x9696, 0xA55A, 0x73CE, 0x13C8, 0x324C, 0x3BDC, 0x6996, 0xC33C, 0x9966, 0x0660,
0x0272, 0x04E4, 0x4E40, 0x2720, 0xC936, 0x936C, 0x39C6, 0x639C, 0x9336, 0x9CC6, 0x817E, 0xE718, 0xCCF0, 0x0FCC, 0x7744, 0xEE22,
};
static readonly string P3 =
"0011001102212222" + "0001001122112221" + "0000200122112211" + "0222002200110111" + "0000000011221122" + "0011001100220022" + "0022002211111111" + "0011001122112211" +
"0000000011112222" + "0000111111112222" + "0000111122222222" + "0012001200120012" + "0112011201120112" + "0122012201220122" + "0011011211221222" + "0011200122002220" +
"0001001101121122" + "0111001120012200" + "0000112211221122" + "0022002200221111" + "0111011102220222" + "0001000122212221" + "0000001101220122" + "0000110022102210" +
"0122012200110000" + "0012001211222222" + "0110122112210110" + "0000011012211221" + "0022110211020022" + "0110011020022222" + "0011012201220011" + "0000200022112221" +
"0000000211221222" + "0222002200120011" + "0011001200220222" + "0120012001200120" + "0000111122220000" + "0120120120120120" + "0120201212010120" + "0011220011220011" +
"0011112222000011" + "0101010122222222" + "0000000021212121" + "0022112200221122" + "0022001100220011" + "0220122102201221" + "0101222222220101" + "0000212121212121" +
"0101010101012222" + "0222011102220111" + "0002111200021112" + "0000211221122112" + "0222011101110222" + "0002111211120002" + "0110011001102222" + "0000000021122112" +
"0110011022222222" + "0022001100110022" + "0022112211220022" + "0000000000002112" + "0002000100020001" + "0222122202221222" + "0101222222222222" + "0111201122012220";
static readonly byte[] A2 =
{
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2,
15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15,
};
static readonly byte[] A3a =
{
3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15,
8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3,
};
static readonly byte[] A3b =
{
15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8,
15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8,
};
ref struct Bits
{
readonly ReadOnlySpan<byte> b;
int pos;
public Bits(ReadOnlySpan<byte> block) { b = block; pos = 0; }
public int Read(int n)
{
var v = 0;
for (var i = 0; i < n; i++, pos++) v |= ((b[pos >> 3] >> (pos & 7)) & 1) << i;
return v;
}
}
/// <summary>BC7 blocks (16 bytes each, rows of blocks) decoded to RGBA8.</summary>
public static byte[] Decode(ReadOnlySpan<byte> blocks, int width, int height)
{
ImageLimits.Check(width, height);
int wb = (width + 3) / 4, hb = (height + 3) / 4;
var output = new byte[width * height * 4];
Span<byte> texels = stackalloc byte[64];
for (var by = 0; by < hb; by++)
for (var bx = 0; bx < wb; bx++)
{
DecodeBlock(blocks.Slice((by * wb + bx) * 16, 16), texels);
for (var y = 0; y < 4 && by * 4 + y < height; y++)
{
var count = Math.Min(4, width - bx * 4);
texels.Slice(y * 16, count * 4).CopyTo(output.AsSpan(((by * 4 + y) * width + bx * 4) * 4));
}
}
return output;
}
static int Subset(int subsets, int partition, int i) => subsets switch
{
2 => (int)((P2[partition] >> i) & 1),
3 => P3[partition * 16 + i] - '0',
_ => 0,
};
static bool IsAnchor(int subsets, int partition, int i) =>
i == 0 || (subsets == 2 && i == A2[partition]) || (subsets == 3 && (i == A3a[partition] || i == A3b[partition]));
static int Interp(int a, int b, int index, int bits)
{
var w = bits == 2 ? W2[index] : bits == 3 ? W3[index] : W4[index];
return ((64 - w) * a + w * b + 32) >> 6;
}
static void DecodeBlock(ReadOnlySpan<byte> block, Span<byte> texels)
{
var mode = 0;
while (mode < 8 && ((block[0] >> mode) & 1) == 0) mode++;
if (mode == 8) { texels.Clear(); return; }
var m = Modes[mode];
var bits = new Bits(block);
bits.Read(mode + 1);
var partition = bits.Read(m.PartBits);
var rotation = bits.Read(m.RotBits);
var idxSel = bits.Read(m.IdxSelBits);
// endpoints: [subset*2 + end][channel]
Span<int> ep = stackalloc int[6 * 4];
var ns = m.Subsets;
for (var c = 0; c < 3; c++)
for (var e = 0; e < ns * 2; e++)
ep[e * 4 + c] = bits.Read(m.ColorBits);
for (var e = 0; e < ns * 2; e++)
ep[e * 4 + 3] = m.AlphaBits > 0 ? bits.Read(m.AlphaBits) : 255;
var colorBits = m.ColorBits;
var alphaBits = m.AlphaBits;
if (m.EndPBits > 0)
{
for (var e = 0; e < ns * 2; e++)
{
var p = bits.Read(1);
for (var c = 0; c < 3; c++) ep[e * 4 + c] = (ep[e * 4 + c] << 1) | p;
if (alphaBits > 0) ep[e * 4 + 3] = (ep[e * 4 + 3] << 1) | p;
}
colorBits++;
if (alphaBits > 0) alphaBits++;
}
else if (m.SharedPBits > 0)
{
for (var s = 0; s < ns; s++)
{
var p = bits.Read(1);
for (var e = s * 2; e < s * 2 + 2; e++)
for (var c = 0; c < 3; c++) ep[e * 4 + c] = (ep[e * 4 + c] << 1) | p;
}
colorBits++;
}
// expand to 8 bits
for (var e = 0; e < ns * 2; e++)
{
for (var c = 0; c < 3; c++) ep[e * 4 + c] = Expand(ep[e * 4 + c], colorBits);
if (m.AlphaBits > 0) ep[e * 4 + 3] = Expand(ep[e * 4 + 3], alphaBits);
}
Span<int> idx1 = stackalloc int[16];
Span<int> idx2 = stackalloc int[16];
for (var i = 0; i < 16; i++)
{
var anchor = IsAnchor(ns, partition, i) && (ns == 1 ? i == 0 : true) && IsAnchorFor(ns, partition, i);
idx1[i] = bits.Read(anchor ? m.IdxBits - 1 : m.IdxBits);
}
if (m.Idx2Bits > 0)
for (var i = 0; i < 16; i++)
idx2[i] = bits.Read(i == 0 ? m.Idx2Bits - 1 : m.Idx2Bits);
for (var i = 0; i < 16; i++)
{
var s = Subset(ns, partition, i);
int e0 = s * 2 * 4, e1 = (s * 2 + 1) * 4;
int r, g, b, a;
if (m.Idx2Bits > 0)
{
int cIdx = idxSel == 0 ? idx1[i] : idx2[i], aIdx = idxSel == 0 ? idx2[i] : idx1[i];
int cBits = idxSel == 0 ? m.IdxBits : m.Idx2Bits, aBits = idxSel == 0 ? m.Idx2Bits : m.IdxBits;
r = Interp(ep[e0], ep[e1], cIdx, cBits);
g = Interp(ep[e0 + 1], ep[e1 + 1], cIdx, cBits);
b = Interp(ep[e0 + 2], ep[e1 + 2], cIdx, cBits);
a = Interp(ep[e0 + 3], ep[e1 + 3], aIdx, aBits);
}
else
{
r = Interp(ep[e0], ep[e1], idx1[i], m.IdxBits);
g = Interp(ep[e0 + 1], ep[e1 + 1], idx1[i], m.IdxBits);
b = Interp(ep[e0 + 2], ep[e1 + 2], idx1[i], m.IdxBits);
a = m.AlphaBits > 0 ? Interp(ep[e0 + 3], ep[e1 + 3], idx1[i], m.IdxBits) : 255;
}
switch (rotation)
{
case 1: (a, r) = (r, a); break;
case 2: (a, g) = (g, a); break;
case 3: (a, b) = (b, a); break;
}
texels[i * 4] = (byte)r;
texels[i * 4 + 1] = (byte)g;
texels[i * 4 + 2] = (byte)b;
texels[i * 4 + 3] = (byte)a;
}
}
/// <summary>Whether texel i is the anchor of its own subset (its index has one bit less).</summary>
static bool IsAnchorFor(int ns, int partition, int i)
{
if (i == 0) return true;
if (ns == 2) return i == A2[partition];
if (ns == 3) return i == A3a[partition] || i == A3b[partition];
return false;
}
static int Expand(int v, int bits) => bits >= 8 ? v : (v << (8 - bits)) | (v >> (2 * bits - 8));
}

View File

@@ -0,0 +1,298 @@
// (Triforce, 11-29) BFRES v10: the game's model files (romfs/Model/*.bfres.zs), read far enough to draw a character in the
// launcher's Character page: the first model's skeleton, its shapes' level-of-detail 0 vertices and triangles, and each
// material's name and texture names. Offsets as the lab's offline renders read them (export.py, 11-17), little-endian:
//
// FRES 0x28 u64 the model array (FMDL, the first one is used), 0x170 u64 where the vertex and index data starts
// FMDL 0x18 skeleton, 0x20 vertex buffers, 0x28 shapes (0x60 each), 0x38 materials (0xb0 each); 0x68/0x6a/0x6c counts
// FSKL 0x10 bones (0x58 each), 0x18 matrix-to-bone list (u16), 0x20 inverse bind matrices (3x4 f32);
// 0x38 bone count, 0x3a smooth matrices, 0x3c rigid matrices
// bone 0x00 name, 0x22 parent (s16), 0x2c flags (0x1000 = the rotation is Euler XYZ, else a quaternion),
// 0x30 scale (3 f32), 0x3c rotation (4 f32), 0x4c translation (3 f32)
// FVTX 0x08 attributes (0x10 each: name, 0x08 format, 0x0c offset, 0x0e buffer), 0x30 buffer sizes, 0x38 strides
// (0x10 each), 0x48 u32 the buffers' offset in the data, 0x4c attribute count, 0x4d buffer count, 0x50 vertex count,
// 0x54 skin count (0: rigid on the shape's bone, 1: rigid on one matrix with bone-local positions, 2+: smooth)
// FSHP 0x08 name, 0x10 vertex buffer, 0x18 meshes (the first is level of detail 0), 0x52 material, 0x58 bone
// mesh 0x20 index offset, 0x24 primitive (3 = triangles), 0x28 index format (0 u8, 1 u16, 2 u32), 0x2c count, 0x30 first
// FMAT 0x08 name, 0x20 texture names, 0xa3 texture count
// Names are inline (u16 length, then the text). Nothing is written back: the Character page only reads.
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
namespace Triforce.Core.GameFiles;
public sealed record BfresBone(string Name, int Parent, Vector3 Scale, Vector4 Rotation, bool Euler, Vector3 Translation);
public sealed record BfresMaterial(string Name, IReadOnlyList<string> Textures);
/// <summary>One shape at level of detail 0, in the model's bind pose: positions, normals, tangents (w = handedness), the
/// first UV set, its bone influences (skeleton bone indices) and triangles.</summary>
public sealed class BfresShape
{
public string Name = "";
public int Material;
public int SkinCount;
public Vector3[] Positions = Array.Empty<Vector3>();
public Vector3[] Normals = Array.Empty<Vector3>();
public Vector4[] Tangents = Array.Empty<Vector4>();
public Vector2[] Uvs = Array.Empty<Vector2>();
/// <summary>The second UV set (zero when the shape has none).</summary>
public Vector2[] Uvs1 = Array.Empty<Vector2>();
/// <summary>The vertex colour (_c0), white when the shape has none.</summary>
public Vector4[] Colors = Array.Empty<Vector4>();
/// <summary>Up to 8 influences a vertex: (bone, weight); a rigid vertex has one of weight 1.</summary>
public (int Bone, float Weight)[][] Influences = Array.Empty<(int, float)[]>();
public int[] Indices = Array.Empty<int>();
}
public sealed class Bfres
{
readonly byte[] b;
public IReadOnlyList<BfresBone> Bones { get; }
public IReadOnlyList<BfresMaterial> Materials { get; }
public IReadOnlyList<BfresShape> Shapes { get; }
/// <summary>Each bone's bind pose in model space (parents applied).</summary>
public Matrix4x4[] BindWorld { get; }
public Bfres(byte[] data)
{
b = data;
if (b.Length < 0x180 || Encoding.ASCII.GetString(b, 0, 4) != "FRES") throw new InvalidDataException("not a BFRES file");
var dataStart = (long)U64(0x170);
var fmdl = (long)U64(0x28);
Need(fmdl, 0x70);
if (Encoding.ASCII.GetString(b, (int)fmdl, 4) != "FMDL") throw new InvalidDataException("BFRES: no model");
long skl = (long)U64(fmdl + 0x18), shapesAt = (long)U64(fmdl + 0x28), matsAt = (long)U64(fmdl + 0x38);
int nShapes = U16(fmdl + 0x6a), nMats = U16(fmdl + 0x6c);
if (nShapes > 512 || nMats > 512) throw new InvalidDataException("BFRES: too many shapes or materials");
// skeleton
Need(skl, 0x40);
int nBones = U16(skl + 0x38), nSmooth = U16(skl + 0x3a), nRigid = U16(skl + 0x3c);
if (nBones > 4096 || nSmooth + nRigid > 8192) throw new InvalidDataException("BFRES: too many bones");
long bonesAt = (long)U64(skl + 0x10), m2bAt = (long)U64(skl + 0x18);
var bones = new List<BfresBone>();
for (var i = 0; i < nBones; i++)
{
var o = bonesAt + 0x58 * i;
Need(o, 0x58);
var flags = U32(o + 0x2c);
bones.Add(new BfresBone(Str((long)U64(o)), (short)U16(o + 0x22), V3(o + 0x30), new Vector4(F(o + 0x3c), F(o + 0x40), F(o + 0x44), F(o + 0x48)),
(flags & 0x1000) != 0, V3(o + 0x4c)));
}
Bones = bones;
BindWorld = new Matrix4x4[nBones];
for (var i = 0; i < nBones; i++)
{
var local = Local(bones[i]);
var p = bones[i].Parent;
BindWorld[i] = p >= 0 && p < i ? local * BindWorld[p] : local;
}
var m2b = new int[nSmooth + nRigid];
for (var i = 0; i < m2b.Length; i++) m2b[i] = Math.Min(U16(m2bAt + 2 * i), nBones - 1);
// materials
var mats = new List<BfresMaterial>();
for (var i = 0; i < nMats; i++)
{
var f = matsAt + 0xb0 * i;
Need(f, 0xb0);
var tp = (long)U64(f + 0x20);
var n = b[f + 0xa3];
var tex = new List<string>();
for (var k = 0; k < n; k++) tex.Add(Str((long)U64(tp + 8 * k)));
mats.Add(new BfresMaterial(Str((long)U64(f + 8)), tex));
}
Materials = mats;
// shapes
var shapes = new List<BfresShape>();
for (var i = 0; i < nShapes; i++)
{
var sh = shapesAt + 0x60 * i;
Need(sh, 0x60);
var vb = (long)U64(sh + 0x10);
Need(vb, 0x58);
int nAttr = b[vb + 0x4c], nBuf = b[vb + 0x4d], skin = b[vb + 0x54];
var vc = (int)U32(vb + 0x50);
if (vc > 2_000_000 || nBuf > 16) throw new InvalidDataException("BFRES: a shape too large");
var bufStart = new long[nBuf];
var strides = new int[nBuf];
var at = dataStart + U32(vb + 0x48);
for (var k = 0; k < nBuf; k++)
{
bufStart[k] = at;
var size = U32((long)U64(vb + 0x30) + 0x10 * k);
strides[k] = (int)U32((long)U64(vb + 0x38) + 0x10 * k);
at += (size + 7) & ~7u;
}
var attrs = new Dictionary<string, Vector4[]>();
for (var k = 0; k < nAttr; k++)
{
var a = (long)U64(vb + 8) + 0x10 * k;
var name = Str((long)U64(a));
var fmt = U32(a + 8);
int off = U16(a + 0xc), bi = U16(a + 0xe);
if (bi >= nBuf) continue;
Need(bufStart[bi], (long)vc * strides[bi]);
var vals = new Vector4[vc];
var ok = true;
for (var v = 0; v < vc && ok; v++) ok = Attr(fmt, bufStart[bi] + (long)v * strides[bi] + off, out vals[v]);
if (ok) attrs[name] = vals;
}
if (!attrs.TryGetValue("_p0", out var p0)) continue;
attrs.TryGetValue("_n0", out var n0);
attrs.TryGetValue("_t0", out var t0);
attrs.TryGetValue("_u0", out var u0);
attrs.TryGetValue("_u1", out var u1);
attrs.TryGetValue("_c0", out var c0);
attrs.TryGetValue("_i0", out var i0);
attrs.TryGetValue("_i1", out var i1);
attrs.TryGetValue("_w0", out var w0);
attrs.TryGetValue("_w1", out var w1);
int shapeBone = Math.Min(U16(sh + 0x58), nBones - 1);
var s = new BfresShape { Name = Str((long)U64(sh + 8)), Material = U16(sh + 0x52), SkinCount = skin };
s.Positions = new Vector3[vc]; s.Normals = new Vector3[vc]; s.Tangents = new Vector4[vc]; s.Uvs = new Vector2[vc];
s.Influences = new (int, float)[vc][];
s.Uvs1 = new Vector2[vc]; s.Colors = new Vector4[vc];
for (var v = 0; v < vc; v++)
{
var p = new Vector3(p0[v].X, p0[v].Y, p0[v].Z);
var n = n0 != null ? new Vector3(n0[v].X, n0[v].Y, n0[v].Z) : Vector3.UnitY;
var t = t0 != null ? new Vector3(t0[v].X, t0[v].Y, t0[v].Z) : Vector3.UnitX;
(int, float)[] inf;
if (skin <= 1)
{
// (rigid: skin 0 on the shape's own bone, skin 1 on one matrix; both store bone-local positions)
var bone = skin == 0 || i0 == null ? shapeBone : m2b[Math.Clamp((int)i0[v].X, 0, m2b.Length - 1)];
var w = BindWorld[bone];
p = Vector3.Transform(p, w); n = Vector3.TransformNormal(n, w); t = Vector3.TransformNormal(t, w);
inf = new[] { (bone, 1f) };
}
else
{
var l = new List<(int, float)>(8);
float[] ia = i0 != null ? new[] { i0[v].X, i0[v].Y, i0[v].Z, i0[v].W } : new float[4];
float[] wa = w0 != null ? new[] { w0[v].X, w0[v].Y, w0[v].Z, w0[v].W } : new[] { 1f, 0, 0, 0 };
for (var k = 0; k < Math.Min(4, skin); k++) l.Add((m2b[Math.Clamp((int)ia[k], 0, m2b.Length - 1)], wa[k]));
if (skin > 4 && i1 != null && w1 != null)
{
float[] ib = { i1[v].X, i1[v].Y, i1[v].Z, i1[v].W }, wb = { w1[v].X, w1[v].Y, w1[v].Z, w1[v].W };
for (var k = 0; k < Math.Min(4, skin - 4); k++) l.Add((m2b[Math.Clamp((int)ib[k], 0, m2b.Length - 1)], wb[k]));
}
inf = l.ToArray();
}
s.Positions[v] = p;
s.Normals[v] = n.LengthSquared() > 1e-12f ? Vector3.Normalize(n) : Vector3.UnitY;
s.Tangents[v] = new Vector4(t.LengthSquared() > 1e-12f ? Vector3.Normalize(t) : Vector3.UnitX, t0 != null && t0[v].W < 0 ? -1 : 1);
s.Uvs[v] = u0 != null ? new Vector2(u0[v].X, u0[v].Y) : Vector2.Zero;
s.Uvs1[v] = u1 != null ? new Vector2(u1[v].X, u1[v].Y) : Vector2.Zero;
s.Colors[v] = c0 != null ? c0[v] : Vector4.One;
s.Influences[v] = inf;
}
// level of detail 0
var mesh = (long)U64(sh + 0x18);
Need(mesh, 0x34);
long faceOff = U32(mesh + 0x20);
uint prim = U32(mesh + 0x24), ifmt = U32(mesh + 0x28);
var count = (int)U32(mesh + 0x2c);
var first = (int)U32(mesh + 0x30);
if (prim != 3 || ifmt > 2 || count > 12_000_000) continue;
var isz = ifmt == 0 ? 1 : ifmt == 1 ? 2 : 4;
Need(dataStart + faceOff, (long)count * isz);
var idx = new int[count];
for (var k = 0; k < count; k++)
{
var o = dataStart + faceOff + (long)k * isz;
var x = (ifmt == 0 ? b[o] : ifmt == 1 ? U16(o) : (int)U32(o)) + first;
idx[k] = x < vc ? x : 0;
}
s.Indices = idx;
shapes.Add(s);
}
Shapes = shapes;
}
/// <summary>A bone's local transform (scale, then rotation, then translation; row vectors as System.Numerics has them).</summary>
public static Matrix4x4 Local(BfresBone bone, Quaternion? rotation = null)
{
var q = rotation ?? Rotation(bone);
return Matrix4x4.CreateScale(bone.Scale) * Matrix4x4.CreateFromQuaternion(q) * Matrix4x4.CreateTranslation(bone.Translation);
}
/// <summary>A bone's rotation as a quaternion (Euler XYZ: X first, then Y, then Z).</summary>
public static Quaternion Rotation(BfresBone bone)
{
if (!bone.Euler) return Quaternion.Normalize(new Quaternion(bone.Rotation.X, bone.Rotation.Y, bone.Rotation.Z, bone.Rotation.W));
var r = bone.Rotation;
return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, r.Z) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, r.Y) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, r.X));
}
// ---------------- reading ----------------
void Need(long at, long n)
{
if (at < 0 || n < 0 || at + n > b.Length) throw new InvalidDataException("BFRES: a part lies outside the file");
}
ushort U16(long at) { Need(at, 2); return BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan((int)at)); }
uint U32(long at) { Need(at, 4); return BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan((int)at)); }
ulong U64(long at) { Need(at, 8); return BinaryPrimitives.ReadUInt64LittleEndian(b.AsSpan((int)at)); }
float F(long at) { Need(at, 4); return BinaryPrimitives.ReadSingleLittleEndian(b.AsSpan((int)at)); }
Vector3 V3(long at) => new(F(at), F(at + 4), F(at + 8));
string Str(long at)
{
if (at <= 0 || at + 2 > b.Length) return "";
var n = U16(at);
if (at + 2 + n > b.Length) return "";
return Encoding.UTF8.GetString(b, (int)at + 2, n);
}
/// <summary>One vertex attribute decoded to floats (unused components 0). False for a format this reader does not know.</summary>
bool Attr(uint fmt, long o, out Vector4 v)
{
v = default;
switch (fmt)
{
case 0x1805: v = new Vector4(F(o), F(o + 4), F(o + 8), 0); return true;
case 0x1905: v = new Vector4(F(o), F(o + 4), F(o + 8), F(o + 12)); return true;
case 0x1705: v = new Vector4(F(o), F(o + 4), 0, 0); return true;
case 0x1205: Need(o, 4); v = new Vector4((float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o)), (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 2)), 0, 0); return true;
case 0x1505:
Need(o, 8);
v = new Vector4((float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o)), (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 2)),
(float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 4)), (float)BinaryPrimitives.ReadHalfLittleEndian(b.AsSpan((int)o + 6)));
return true;
case 0x1202: v = new Vector4(Math.Max((short)U16(o) / 32767f, -1), Math.Max((short)U16(o + 2) / 32767f, -1), 0, 0); return true;
case 0x1201: v = new Vector4(U16(o) / 65535f, U16(o + 2) / 65535f, 0, 0); return true;
case 0x0e02:
{
var x = U32(o);
float C(int c) { var q = (int)((x >> (10 * c)) & 0x3ff); if (q >= 512) q -= 1024; return Math.Max(q / 511f, -1); }
var w = (int)((x >> 30) & 3); if (w >= 2) w -= 4;
v = new Vector4(C(0), C(1), C(2), w);
return true;
}
case 0x0201: Need(o, 1); v = new Vector4(b[o] / 255f, 0, 0, 0); return true;
case 0x0203: Need(o, 1); v = new Vector4(b[o], 0, 0, 0); return true;
case 0x0901: Need(o, 2); v = new Vector4(b[o] / 255f, b[o + 1] / 255f, 0, 0); return true;
case 0x0903: Need(o, 2); v = new Vector4(b[o], b[o + 1], 0, 0); return true;
case 0x0b01: Need(o, 4); v = new Vector4(b[o] / 255f, b[o + 1] / 255f, b[o + 2] / 255f, b[o + 3] / 255f); return true;
case 0x0b03: Need(o, 4); v = new Vector4(b[o], b[o + 1], b[o + 2], b[o + 3]); return true;
case 0x0a01: v = new Vector4(U16(o) / 65535f, 0, 0, 0); return true;
case 0x0a03: v = new Vector4(U16(o), 0, 0, 0); return true;
case 0x1001: v = new Vector4(U16(o) / 65535f, U16(o + 2) / 65535f, 0, 0); return true;
case 0x1003: v = new Vector4(U16(o), U16(o + 2), 0, 0); return true;
case 0x1501 or 0x1503:
{
var k = fmt == 0x1501 ? 1 / 65535f : 1f;
v = new Vector4(U16(o) * k, U16(o + 2) * k, U16(o + 4) * k, U16(o + 6) * k);
return true;
}
default: return false;
}
}
/// <summary>The attribute formats a file uses that this reader skips (for diagnostics).</summary>
public static string FormatName(uint fmt) => "0x" + fmt.ToString("x4");
}

View File

@@ -69,4 +69,41 @@ public static class BlockLinear
}
return output;
}
/// <summary>((Triforce, 11-29) The other way: a linear image written into block-linear order, into output (at least
/// Size bytes; bytes the image does not cover are left as they are). For the Character page's recoloured textures.</summary>
public static void Swizzle(ReadOnlySpan<byte> linear, Span<byte> output, int width, int height, int bytesPerElement, int blockHeightLog2)
{
if (bytesPerElement is not (1 or 2 or 4 or 8 or 16))
throw new NotSupportedException(bytesPerElement + " bytes per element");
if (Size(width, height, bytesPerElement, blockHeightLog2) > output.Length)
throw new InvalidDataException("the texture's data is shorter than its size calls for");
var pitch = width * bytesPerElement;
var gobsInX = (pitch + 63) >> GobSizeXShift;
var blockSize = gobsInX << (GobSizeShift + blockHeightLog2);
var blockHeightMask = (1 << blockHeightLog2) - 1;
var xShift = GobSizeShift + blockHeightLog2;
for (var y = 0; y < height; y++)
{
var swizzledY = SwizzleY(y);
var blockY = y >> GobSizeYShift;
var offsetY = (blockY >> blockHeightLog2) * blockSize + ((blockY & blockHeightMask) << GobSizeShift);
var row = linear.Slice(y * pitch, pitch);
for (var x = 0; x < pitch; x += bytesPerElement)
{
var offsetX = (x >> GobSizeXShift) << xShift;
var at = offsetY + offsetX + (SwizzleX(x & 63) | swizzledY);
row.Slice(x, bytesPerElement).CopyTo(output.Slice(at, bytesPerElement));
}
}
}
/// <summary>The block height (log2, in GOBs) a smaller mip level uses: the texture's, halved while half of it still
/// covers the level's height (the GPU's rule).</summary>
public static int MipBlockHeight(int heightInElements, int blockHeightLog2)
{
var bh = blockHeightLog2;
while (bh > 0 && (8 << (bh - 1)) >= heightInElements) bh--;
return bh;
}
}

View File

@@ -18,6 +18,9 @@ namespace Triforce.Core.GameFiles;
public sealed record BntxTexture(string Name, int Width, int Height, uint Format, int MipCount, int TileMode,
int BlockHeightLog2, long DataOffset, long ImageSize, byte[] ChannelSources)
{
/// <summary>((Triforce, 11-29) Where each mip level's data starts in the file (level 0 is DataOffset).</summary>
public long[] MipOffsets { get; init; } = Array.Empty<long>();
/// <summary>The format's kind (high byte), e.g. 0x2d for ASTC 4x4.</summary>
public int Kind => (int)(Format >> 8);
@@ -58,8 +61,11 @@ public sealed class Bntx
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);
int mipCount = Math.Clamp((int)U16(p + 0x16), 1, 16);
var offs = new long[mipCount];
for (var k = 0; k < mipCount; k++) offs[k] = mips + 8L * k + 8 <= data.Length ? (long)U64(mips + 8L * k) : 0;
var tex = new BntxTexture(name, (int)U32(p + 0x24), (int)U32(p + 0x28), U32(p + 0x1C), U16(p + 0x16), U16(p + 0x12),
(int)(U32(p + 0x34) & 7), (long)U64(mips), U32(p + 0x50), data[(int)(p + 0x58)..(int)(p + 0x5C)]);
(int)(U32(p + 0x34) & 7), (long)U64(mips), U32(p + 0x50), data[(int)(p + 0x58)..(int)(p + 0x5C)]) { MipOffsets = offs };
list.Add(tex);
byName.TryAdd(name, tex);
}
@@ -96,6 +102,7 @@ public sealed class Bntx
0x1c => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC3),
0x1d => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC4),
0x1e => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC5),
0x20 => Bc7.Decode(linear, t.Width, t.Height),
0x0b => linear,
0x0c => Swap(linear, 2, 1, 0, 3),
0x02 => Expand(linear, 1),
@@ -108,13 +115,13 @@ public sealed class Bntx
}
/// <summary>The block size and bytes per block of a format (1x1 for an uncompressed one).</summary>
static (int W, int H, int Bytes) BlockInfo(uint format) => (format >> 8) switch
public static (int W, int H, int Bytes) BlockInfo(uint format) => (format >> 8) switch
{
0x02 => (1, 1, 1),
0x09 => (1, 1, 2),
0x0b or 0x0c => (1, 1, 4),
0x1a or 0x1d => (4, 4, 8),
0x1b or 0x1c or 0x1e => (4, 4, 16),
0x1b or 0x1c or 0x1e or 0x20 => (4, 4, 16),
var k and >= 0x2d and <= 0x3a => (AstcBlocks[k - 0x2d].W, AstcBlocks[k - 0x2d].H, 16),
_ => throw new NotSupportedException("texture format " + FormatName(format) + " is not supported"),
};

View File

@@ -0,0 +1,107 @@
// (Triforce, 11-29) FSKA, a skeletal animation inside a BFRES v10 animation file (romfs/Model/*_Animation.anim.bfres.zs),
// read far enough to pose a model at one frame: each bone track's base values (frame 0) and its curves sampled at the frame.
// Layout as the lab's offline renders read it (export.py anim_base, 11-17), little-endian:
// FSKA 0x04 flags (0x1000: rotations are Euler XYZ), 0x08 name, 0x28 bone tracks (0x38 each), 0x4c track count
// track 0x00 bone name, 0x08 curves (0x30 each), 0x10 base data, 0x28 flags (0x08 scale, 0x10 rotation, 0x20 translation
// in the base data), 0x2e curve count
// base scale (3 f32), rotation (4 f32: Euler XYZ and a pad, or a quaternion), translation (3 f32), each when flagged
// curve 0x00 frames, 0x08 keys, 0x10 flags (bits 0-1 frame type: 0 f32, 1 s16/32, 2 u8; bits 2-3 key type: 0 f32,
// 1 u16, 2 u8), 0x12 key count, 0x14 target offset (0x04.. scale, 0x10.. translation, 0x20.. rotation),
// 0x18 start, 0x1c end, 0x24 scale, 0x28 offset (a key is offset + value * scale); keys are sampled with a
// Catmull-Rom spline through them
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
namespace Triforce.Core.GameFiles;
public sealed record FskaPose(Vector3? Scale, Vector4? Rotation, Vector3? Translation, bool Euler);
public static class Fska
{
/// <summary>The bone poses of animation <paramref name="name"/> in this file at <paramref name="frame"/> (null when the file
/// has no such animation).</summary>
public static Dictionary<string, FskaPose>? Pose(byte[] a, string name, float frame)
{
ushort U16(long o) => o >= 0 && o + 2 <= a.Length ? BinaryPrimitives.ReadUInt16LittleEndian(a.AsSpan((int)o)) : (ushort)0;
uint U32(long o) => o >= 0 && o + 4 <= a.Length ? BinaryPrimitives.ReadUInt32LittleEndian(a.AsSpan((int)o)) : 0;
long U64(long o) => o >= 0 && o + 8 <= a.Length ? (long)BinaryPrimitives.ReadUInt64LittleEndian(a.AsSpan((int)o)) : -1;
float F(long o) => o >= 0 && o + 4 <= a.Length ? BinaryPrimitives.ReadSingleLittleEndian(a.AsSpan((int)o)) : 0;
string S(long o)
{
if (o <= 0 || o + 2 > a.Length) return "";
var n = U16(o);
return o + 2 + n <= a.Length ? Encoding.UTF8.GetString(a, (int)o + 2, n) : "";
}
var magic = "FSKA"u8;
for (var f = a.AsSpan().IndexOf(magic); f >= 0;)
{
if (S(U64(f + 8)) == name)
{
var euler = (U32(f + 4) & 0x1000) != 0;
long tracks = U64(f + 0x28);
int n = U16(f + 0x4c);
var poses = new Dictionary<string, FskaPose>(StringComparer.Ordinal);
for (var i = 0; i < n && i < 4096; i++)
{
var o = tracks + 0x38L * i;
var bone = S(U64(o));
long k = U64(o + 0x10);
var fl = U32(o + 0x28);
float[]? sc = null, rot = null, tr = null;
if ((fl & 0x08) != 0) { sc = new[] { F(k), F(k + 4), F(k + 8) }; k += 12; }
if ((fl & 0x10) != 0) { rot = new[] { F(k), F(k + 4), F(k + 8), F(k + 12) }; k += 16; }
// (a file may mix them: an Euler track keeps 1 in its fourth value, a quaternion track does not unless it is
// the identity, which reads the same either way)
var trackEuler = rot == null ? euler : euler || MathF.Abs(rot[3] - 1) < 1e-6f;
if ((fl & 0x20) != 0) { tr = new[] { F(k), F(k + 4), F(k + 8) }; k += 12; }
int nc = o + 0x2e < a.Length ? a[o + 0x2e] : 0;
long cv = U64(o + 8);
for (var c = 0; c < nc; c++)
{
var co = cv + 0x30L * c;
long frames = U64(co), keys = U64(co + 8);
int cfl = U16(co + 0x10), nk = U16(co + 0x12);
var target = U32(co + 0x14);
float scale = F(co + 0x24), offset = F(co + 0x28);
if (nk <= 0 || nk > 100000) continue;
int ft = cfl & 3, kt = (cfl >> 2) & 3;
var fr = new float[nk];
var val = new float[nk];
for (var j = 0; j < nk; j++)
{
fr[j] = ft == 2 ? (frames + j < a.Length ? a[frames + j] : 0) : ft == 1 ? (short)U16(frames + 2 * j) / 32f : F(frames + 4 * j);
var kp = keys + 8;
val[j] = kt == 2 ? offset + (kp + 2 * j < a.Length ? a[kp + 2 * j] : 0) * scale
: kt == 1 ? offset + U16(kp + 4 * j) * scale
: F(kp + 8 * j);
}
var v = Sample(fr, val, frame);
if (target >= 0x04 && target <= 0x0c && sc != null) sc[(target - 0x04) / 4] = v;
else if (target >= 0x10 && target <= 0x18 && tr != null) tr[(target - 0x10) / 4] = v;
else if (target >= 0x20 && target <= 0x2c && rot != null) rot[(target - 0x20) / 4] = v;
}
poses[bone] = new FskaPose(sc == null ? null : new Vector3(sc[0], sc[1], sc[2]),
rot == null ? null : new Vector4(rot[0], rot[1], rot[2], rot[3]), tr == null ? null : new Vector3(tr[0], tr[1], tr[2]), trackEuler);
}
return poses;
}
var next = a.AsSpan(f + 4).IndexOf(magic);
f = next < 0 ? -1 : f + 4 + next;
}
return null;
}
/// <summary>A Catmull-Rom spline through the keys, at frame t (held at the ends).</summary>
static float Sample(float[] fr, float[] v, float t)
{
var n = fr.Length;
if (n == 1) return v[0];
t = Math.Clamp(t, fr[0], fr[n - 1]);
var i = 0;
while (i < n - 2 && fr[i + 1] < t) i++;
float f0 = fr[i], f1 = fr[i + 1], u = f1 == f0 ? 0 : (t - f0) / (f1 - f0);
float p0 = i > 0 ? v[i - 1] : v[i], p1 = v[i], p2 = v[i + 1], p3 = i + 2 < n ? v[i + 2] : v[i + 1];
return 0.5f * (2 * p1 + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u * u + (-p0 + 3 * p1 - 3 * p2 + p3) * u * u * u);
}
}

View File

@@ -0,0 +1,418 @@
// (Triforce, 11-29) Link as the launcher's Character page draws him, from the player's own game files: young Link
// (Player_Child) or adult Link (Player_Adult) in the Kokiri, Goron or Zora tunic (Armor_Adult_Goron / _Zora drawn over
// Player_Adult with the shapes they replace hidden), posed from the models' A-pose to a relaxed stand (arms lowered) by
// skinning on the CPU. The result is one binary of interleaved vertices and triangles plus a JSON description of each part
// (its material, its textures and how it is drawn). Textures are decoded here too (Texture), at most MaxTexture wide.
// Nothing of the game is kept by the launcher beyond its own cache; nothing is written into the game.
using System.Buffers.Binary;
using System.Numerics;
using System.Text.Json.Nodes;
namespace Triforce.Core.GameFiles;
public sealed class LinkScene
{
/// <summary>The looks the page offers: young Link and adult Link in each tunic.</summary>
public static readonly string[] Looks = { "child", "adult", "adult-goron", "adult-zora" };
/// <summary>The widest a texture is sent to the page: the preview is never larger on screen.</summary>
public const int MaxTexture = 2048;
public byte[] Mesh { get; private init; } = Array.Empty<byte>();
public JsonObject Info { get; private init; } = new();
/// <summary>Materials whose shapes an armour model replaces on Player_Adult (the armour brings its own).</summary>
static readonly HashSet<string> ArmourHides = new(StringComparer.Ordinal)
{
"Mt_Angin", "Mt_Angin_Acs", "Mt_Angin_Acs_AlphaMask", "Mt_Vest", "Mt_Inner", "Mt_Leater_Upper", "Mt_Leather_Upper_Metal",
};
/// <summary>The relaxed stand: (bone, axis in model space, degrees), applied from the root out. The models' A-pose holds the
/// arms 45 degrees out; these bring them down beside the body with a slight bend at the elbow.</summary>
static readonly (string Bone, Vector3 Axis, float Deg)[] Stand =
{
("Arm_1_L", Vector3.UnitZ, -36), ("Arm_1_R", Vector3.UnitZ, 36),
("Arm_1_L", Vector3.UnitX, -8), ("Arm_1_R", Vector3.UnitX, -8),
("Arm_2_L", Vector3.UnitX, -14), ("Arm_2_R", Vector3.UnitX, -14),
("Arm_2_L", Vector3.UnitY, 10), ("Arm_2_R", Vector3.UnitY, -10),
("Wrist_L", Vector3.UnitZ, 10), ("Wrist_R", Vector3.UnitZ, -10),
};
/// <summary>Linkle (the Playable Linkle mod, read through an OverlaySource of its romfs over the game's): her models, by
/// the names the mod's packs give them. Her Goron and Zora outfits are whole bodies of their own.</summary>
public const string LinkleChild = "Model/Npc_Kokiri_WC_002.Player_Linkle_Child.bfres.zs";
const string LinkleChildAnim = "Model/Linkl__Child_04_Animation.anim.bfres.zs";
const string LinkleZora = "Model/Npc_Hylia_WU_Zelda_Adult.Player_Zelda_Adult_Zora.bfres.zs";
const string LinkleFairy = "Model/Npc_Navi.Dm_Npc_Liri.bfres.zs";
/// <param name="renames">Per model file, texture names to show under another name (Linkle's copies: her model will point
/// at them once dyed, so the preview's dyed maps reach only the outfit that wears them).</param>
public static LinkScene Build(IGameSource src, Zs zs, string look, string hero = "link", IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>>? renames = null)
{
Renames = renames;
if (!Looks.Contains(look)) throw new ArgumentException("no such look: " + look);
if (hero == "linkle") return BuildLinkle(src, zs, look);
return Build2(src, zs, look, "link", look == "child" ? "Model/Player_Child.Player_Child.bfres.zs" : "Model/Player_Adult.Player_Adult.bfres.zs",
look == "child" ? "Model/Player_Child_04_Animation.anim.bfres.zs" : "Model/Player_Adult_04_Animation.anim.bfres.zs");
}
static LinkScene Build2(IGameSource src, Zs zs, string look, string hero, string bodyFile, string animFile)
{
var child = look == "child";
var body = new Bfres(zs.Unpack(bodyFile));
IReadOnlyDictionary<string, string>? rename = null;
Renames?.TryGetValue(bodyFile, out rename);
Bfres? armour = hero == "linkle" ? null : look switch
{
"adult-goron" => new Bfres(zs.Unpack("Model/Armor_Adult_Goron.Armor_Adult_Goron.bfres.zs")),
"adult-zora" => new Bfres(zs.Unpack("Model/Armor_Adult_Zora.Armor_Adult_Zora.bfres.zs")),
_ => null,
};
// the pose: the game's own standing animation ("Wait") at its first frame, on the body's skeleton; an armour's bones
// follow the body's bone of the same name. A game without it: the bind pose with the arms lowered by hand
Dictionary<string, FskaPose>? wait = null;
try { if (src.Exists(animFile)) wait = Fska.Pose(zs.Unpack(animFile), "Wait", 0); }
catch (Exception e) when (e is IOException || e is InvalidDataException || e is FileNotFoundException) { }
var posed = Pose(body, wait);
var byName = new Dictionary<string, int>(StringComparer.Ordinal);
for (var i = 0; i < body.Bones.Count; i++) byName.TryAdd(body.Bones[i].Name, i);
Matrix4x4[] SkinOf(Bfres m, Matrix4x4[]? own)
{
var s = new Matrix4x4[m.Bones.Count];
for (var i = 0; i < s.Length; i++)
{
Matrix4x4.Invert(m.BindWorld[i], out var inv);
if (own != null) s[i] = inv * own[i];
else if (byName.TryGetValue(m.Bones[i].Name, out var j))
{
// (the armour's bind may differ from the body's by a little: carry its bone as the body's moves)
Matrix4x4.Invert(body.BindWorld[j], out var invBody);
s[i] = invBody * posed[j];
}
else s[i] = Matrix4x4.Identity;
}
return s;
}
var bodySkin = SkinOf(body, posed);
var parts = new JsonArray();
using var bin = new MemoryStream();
var min = new Vector3(float.MaxValue);
var max = new Vector3(float.MinValue);
var vbuf = new byte[64];
var ibuf = new byte[4];
void Add(Bfres m, Matrix4x4[] skin, string source, Func<BfresShape, bool> keep)
{
foreach (var s in m.Shapes)
{
if (!keep(s)) continue;
var mat = m.Materials[Math.Clamp(s.Material, 0, m.Materials.Count - 1)];
var kind = Kind(mat.Name, s.Name);
if (kind == "skip") continue;
if (source == "navi" && kind is "cloth" or "hair" or "skin") kind = "fairy"; // (Linkle's Liri: a little lit figure)
var n = s.Positions.Length;
var voff = bin.Position;
var v = vbuf;
for (var i = 0; i < n; i++)
{
var p = Vector3.Zero; var nr = Vector3.Zero; var t = Vector3.Zero;
var total = 0f;
foreach (var (bone, w) in s.Influences[i])
{
if (w <= 0) continue;
var k = skin[Math.Clamp(bone, 0, skin.Length - 1)];
p += w * Vector3.Transform(s.Positions[i], k);
nr += w * Vector3.TransformNormal(s.Normals[i], k);
t += w * Vector3.TransformNormal(new Vector3(s.Tangents[i].X, s.Tangents[i].Y, s.Tangents[i].Z), k);
total += w;
}
if (total <= 0) { p = s.Positions[i]; nr = s.Normals[i]; t = new Vector3(s.Tangents[i].X, s.Tangents[i].Y, s.Tangents[i].Z); }
else if (MathF.Abs(total - 1) > 1e-3f) p /= total;
nr = nr.LengthSquared() > 1e-12f ? Vector3.Normalize(nr) : Vector3.UnitY;
t = t.LengthSquared() > 1e-12f ? Vector3.Normalize(t) : Vector3.UnitX;
min = Vector3.Min(min, p); max = Vector3.Max(max, p);
W(v, 0, p.X); W(v, 4, p.Y); W(v, 8, p.Z);
W(v, 12, nr.X); W(v, 16, nr.Y); W(v, 20, nr.Z);
W(v, 24, t.X); W(v, 28, t.Y); W(v, 32, t.Z); W(v, 36, s.Tangents[i].W);
W(v, 40, s.Uvs[i].X); W(v, 44, s.Uvs[i].Y);
var c = s.Colors.Length > i ? s.Colors[i] : Vector4.One;
W(v, 48, c.X); W(v, 52, c.Y); W(v, 56, c.Z); W(v, 60, c.W);
bin.Write(v);
}
var ioff = bin.Position;
var ix = ibuf;
foreach (var x in s.Indices) { BinaryPrimitives.WriteInt32LittleEndian(ix, x); bin.Write(ix); }
var tex = Textures(mat, kind, name => src.Exists("Tex/" + name + ".bntx.zs"));
if (source == "body" && rename != null)
foreach (var k in tex.Keys.ToList())
if ((string?)tex[k] is { } nm && rename.TryGetValue(nm, out var to)) tex[k] = to;
var part = new JsonObject
{
["name"] = s.Name, ["mat"] = mat.Name, ["src"] = source, ["kind"] = kind,
["voff"] = voff, ["vcount"] = n, ["ioff"] = ioff, ["icount"] = s.Indices.Length,
};
foreach (var kv in tex) part[kv.Key] = kv.Value;
parts.Add(part);
}
}
Add(body, bodySkin, "body", s =>
{
if (armour == null) return true;
var mat = body.Materials[Math.Clamp(s.Material, 0, body.Materials.Count - 1)].Name;
if (ArmourHides.Contains(mat)) return false;
// (the Zora tunic brings its own feather)
return !(look == "adult-zora" && mat == "Mt_Feather");
});
if (armour != null) Add(armour, SkinOf(armour, null), look[6..], _ => true);
// Navi, at his shoulder (her own bind pose, a little larger than life so she reads beside him)
JsonArray? naviAt = null;
var fairyFile = FairyOf(src, hero);
if (fairyFile != null)
{
try
{
var navi = new Bfres(zs.Unpack(fairyFile));
var h = max.Y - min.Y;
var at = new Vector3((min.X + max.X) / 2 + h * 0.3f, min.Y + h * 0.86f, (min.Z + max.Z) / 2 + h * 0.1f);
var place = Matrix4x4.CreateScale(1.5f) * Matrix4x4.CreateRotationY(-0.5f) * Matrix4x4.CreateTranslation(at);
var ns = new Matrix4x4[navi.Bones.Count];
for (var i = 0; i < ns.Length; i++) { Matrix4x4.Invert(navi.BindWorld[i], out var inv); ns[i] = inv * navi.BindWorld[i] * place; }
var mn = min; var mx = max;
Add(navi, ns, "navi", _ => true);
min = mn; max = mx; // (Link's bounds frame the view, not hers)
naviAt = new JsonArray(at.X, at.Y, at.Z);
}
catch (Exception e) when (e is IOException || e is InvalidDataException) { }
}
// (the animation may stand him a little off the origin: his feet on the floor, centred on it)
var mesh = bin.ToArray();
var shift = new Vector3(-(min.X + max.X) / 2, -min.Y, -(min.Z + max.Z) / 2);
foreach (var p in parts)
{
long vo = (long)p!["voff"]!; int vc = (int)p["vcount"]!;
for (var i = 0; i < vc; i++)
{
var at = (int)(vo + 64L * i);
for (var c = 0; c < 3; c++)
{
var s = mesh.AsSpan(at + 4 * c);
BinaryPrimitives.WriteSingleLittleEndian(s, BinaryPrimitives.ReadSingleLittleEndian(s) + (c == 0 ? shift.X : c == 1 ? shift.Y : shift.Z));
}
}
}
min += shift; max += shift;
if (naviAt != null) naviAt = new JsonArray((float)naviAt[0]! + shift.X, (float)naviAt[1]! + shift.Y, (float)naviAt[2]! + shift.Z);
return new LinkScene
{
Mesh = mesh,
Info = new JsonObject
{
["look"] = look, ["parts"] = parts, ["stride"] = 64,
["min"] = new JsonArray(min.X, min.Y, min.Z), ["max"] = new JsonArray(max.X, max.Y, max.Z), ["navi"] = naviAt,
},
};
}
[ThreadStatic] static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>>? Renames;
static string? FairyOf(IGameSource src, string hero) =>
hero == "linkle" && src.Exists(LinkleFairy) ? LinkleFairy : src.Exists("Model/Npc_Navi.Npc_Navi.bfres.zs") ? "Model/Npc_Navi.Npc_Navi.bfres.zs" : null;
/// <summary>Linkle: young (her own model, posed by her own Wait), adult (the mod's Player_Adult), or her Goron / Zora
/// outfit (whole bodies, posed by adult Link's Wait where their bones carry his names).</summary>
static LinkScene BuildLinkle(IGameSource src, Zs zs, string look) => Build2(src, zs, look, "linkle",
look switch
{
"child" => LinkleChild,
"adult-goron" => "Model/Armor_Adult_Goron.Armor_Adult_Goron.bfres.zs",
"adult-zora" => LinkleZora,
_ => "Model/Player_Adult.Player_Adult.bfres.zs",
},
look == "child" ? LinkleChildAnim : "Model/Player_Adult_04_Animation.anim.bfres.zs");
static void W(Span<byte> v, int at, float f) => BinaryPrimitives.WriteSingleLittleEndian(v[at..], f);
/// <summary>The posed model-space matrix of each bone: the bind pose with Stand's rotations about the joints.</summary>
static Matrix4x4[] Pose(Bfres m, Dictionary<string, FskaPose>? anim)
{
var n = m.Bones.Count;
var posed = new Matrix4x4[n];
for (var i = 0; i < n; i++)
{
var parent = m.Bones[i].Parent;
var b = m.Bones[i];
Matrix4x4 local;
if (anim != null && anim.TryGetValue(b.Name, out var a))
{
var r = a.Rotation is { } q
? (a.Euler ? Quaternion.Normalize(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, q.Z) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, q.Y) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, q.X))
: Quaternion.Normalize(new Quaternion(q.X, q.Y, q.Z, q.W)))
: Bfres.Rotation(b);
local = Matrix4x4.CreateScale(a.Scale ?? b.Scale) * Matrix4x4.CreateFromQuaternion(r) * Matrix4x4.CreateTranslation(a.Translation ?? b.Translation);
}
else if (parent >= 0 && parent < i)
{
Matrix4x4.Invert(m.BindWorld[parent], out var invParent);
local = m.BindWorld[i] * invParent;
}
else local = m.BindWorld[i];
posed[i] = parent >= 0 && parent < i ? local * posed[parent] : local;
if (anim != null) continue;
foreach (var (bone, axis, deg) in Stand)
{
if (m.Bones[i].Name != bone) continue;
var o = posed[i].Translation;
posed[i] = posed[i] * Matrix4x4.CreateTranslation(-o) * Matrix4x4.CreateFromAxisAngle(axis, deg * MathF.PI / 180) * Matrix4x4.CreateTranslation(o);
}
}
return posed;
}
/// <summary>How a material is drawn: cloth (the default), skin, hair, eye, metal, lash (soft-edged cards), fur, or skip.</summary>
static string Kind(string mat, string shape)
{
if (mat == "Mt_Wings") return "wing";
if (mat.StartsWith("Mt_Body", StringComparison.Ordinal) && shape.Contains("Fur", StringComparison.Ordinal)) return "navifur";
if (mat == "Mt_Body") return "navi";
if (mat.Contains("Eye_Outer", StringComparison.Ordinal)) return "glint"; // (the wet film over the eye: its highlights)
if (mat.Contains("Eye_Inner", StringComparison.Ordinal)) return "eye";
if (mat.Contains("EyeShadow", StringComparison.OrdinalIgnoreCase)) return "shade"; // (a soft shadow over the eye: its map is a mask)
if (mat.Contains("Eyelash", StringComparison.Ordinal) || mat.Contains("Eyebrow", StringComparison.Ordinal)) return "lash";
if (mat.Contains("Hair", StringComparison.Ordinal)) return "hair";
if (mat is "Mt_Skin" or "Mt_Face" or "Mt_Hand" or "Mt_Face_Eyelid" or "Mt_Face_SoftEdge" || mat.StartsWith("Mt_Skin", StringComparison.Ordinal)) return "skin";
if (mat.Contains("Teeth", StringComparison.Ordinal)) return "skin";
if (mat.Contains("Fur", StringComparison.Ordinal) || mat.Contains("Far", StringComparison.Ordinal)) return "fur";
if (mat.Contains("Metal", StringComparison.Ordinal)) return "metal";
return "cloth";
}
/// <summary>A part's textures by role: alb (colour), nrm (normal map), ao, mask (alpha cut), lut (a colour ramp read
/// by a grey map: young Link's hair has no colour map of its own), eye (iris|sclera|mask composited here).</summary>
const string AdultHair = "Mt_Hairs_Player_Adult";
static Dictionary<string, JsonNode?> Textures(BfresMaterial mat, string kind, Func<string, bool> exists)
{
var t = mat.Textures.Where(exists).ToList();
// (a name may carry a variant number after its kind: "..._Alb.01")
static bool Is(string x, string suffix) => x.EndsWith(suffix, StringComparison.Ordinal)
|| (x.Length > suffix.Length + 3 && x[^3] == '.' && char.IsAsciiDigit(x[^2]) && char.IsAsciiDigit(x[^1]) && x[..^3].EndsWith(suffix, StringComparison.Ordinal));
string? First(string suffix, Func<string, bool>? not = null) => t.FirstOrDefault(x => Is(x, suffix) && (not == null || !not(x)));
var o = new Dictionary<string, JsonNode?>();
if (kind == "eye")
{
var iris = t.FirstOrDefault(x => x.Contains("Iris", StringComparison.Ordinal) && x.EndsWith("_Alb", StringComparison.Ordinal));
var sclera = t.FirstOrDefault(x => x.Contains("Sclera", StringComparison.Ordinal) && x.EndsWith("_Alb", StringComparison.Ordinal));
var mask = t.FirstOrDefault(x => x.Contains("Mask", StringComparison.Ordinal) && x.EndsWith("_Gn3", StringComparison.Ordinal));
if (iris != null && sclera != null && mask != null) o["alb"] = "eye:" + iris + "|" + sclera + "|" + mask;
else if (t.FirstOrDefault(x => x.Contains("_Alb", StringComparison.Ordinal)) is { } own) o["alb"] = own; // (Linkle's eyes: a picture of their own)
return o;
}
if (kind == "glint") { if (First("_Emc") is { } emc) o["alb"] = emc; return o; }
if (kind is "navi" or "navifur" or "wing")
{
if (t.FirstOrDefault(x => x.Contains("_Alb", StringComparison.Ordinal)) is { } na) o["alb"] = na;
if (t.FirstOrDefault(x => x.Contains("_Emc", StringComparison.Ordinal)) is { } ne) o["emc"] = ne;
if (First("_Nrm") is { } nn) o["nrm"] = nn;
return o;
}
var alb = First("_Alb");
if (alb == null && kind == "hair" && exists(AdultHair + "_Alb"))
{
// (young Link's hair maps are not in the game: his hair cards are laid out on the same strand sheet as adult
// Link's, whose maps give them their strands)
o["alb"] = AdultHair + "_Alb";
if (exists(AdultHair + "_Nrm")) o["nrm"] = AdultHair + "_Nrm";
if (exists(AdultHair + "_AO")) o["ao"] = AdultHair + "_AO";
return o;
}
if (alb != null) o["alb"] = alb;
else if (kind == "hair" && First("_Gn0") is { } lut && First("_Gn3") is { } grey) { o["lut"] = lut; o["grey"] = grey; }
else if (kind == "shade" && First("_Gn3") is { } g3) o["alb"] = g3;
var nrm = First("_Nrm", x => x.StartsWith("Skin_Detail", StringComparison.Ordinal) || x.Contains("Flatten", StringComparison.Ordinal));
if (nrm != null) o["nrm"] = nrm;
// (Mt_Cloth's tile normal is the first; the garment's own shape normal is the second _Nrm)
var nrms = t.Where(x => x.EndsWith("_Nrm", StringComparison.Ordinal) && !x.StartsWith("Skin_Detail", StringComparison.Ordinal)).ToList();
if (nrms.Count > 1 && nrms[0].StartsWith("Angin_Tile", StringComparison.Ordinal)) { o["nrm"] = nrms[1]; o["nrm2"] = nrms[0]; }
var aos = t.Where(x => x.EndsWith("_AO", StringComparison.Ordinal)).ToList();
if (aos.Count > 0) o["ao"] = aos[^1];
return o;
}
// ---------------- textures ----------------
/// <summary>A texture for the page: (width, height, RGBA8), its channel sources applied, box-shrunk to at most max wide.
/// "eye:iris|sclera|mask" composites an eye; any other name is Tex/&lt;name&gt;.bntx.zs. Null when the game has no such file.</summary>
public static (int W, int H, byte[] Rgba)? Texture(IGameSource src, Zs zs, string name, int max = MaxTexture)
{
if (name.StartsWith("eye:", StringComparison.Ordinal))
{
var p = name[4..].Split('|');
if (p.Length != 3) return null;
var iris = Texture(src, zs, p[0], 512); var sclera = Texture(src, zs, p[1], 512); var mask = Texture(src, zs, p[2], 512);
if (iris == null || sclera == null || mask == null) return null;
return Eye(iris.Value, sclera.Value, mask.Value);
}
var path = "Tex/" + name + ".bntx.zs";
if (!src.Exists(path)) return null;
var b = new Bntx(zs.Unpack(path));
var t = b.Find(name) ?? b.Textures.FirstOrDefault();
if (t == null) return null;
var rgba = b.DecodeRgba(t, true);
int w = t.Width, h = t.Height;
while (w > max || h > max)
{
(rgba, w, h) = Half(rgba, w, h);
}
return (w, h, rgba);
}
/// <summary>An image at half the size (2x2 boxes).</summary>
public static (byte[] Rgba, int W, int H) Half(byte[] src, int w, int h)
{
int nw = Math.Max(1, w / 2), nh = Math.Max(1, h / 2);
var o = new byte[nw * nh * 4];
for (var y = 0; y < nh; y++)
for (var x = 0; x < nw; x++)
for (var c = 0; c < 4; c++)
{
int x0 = Math.Min(2 * x, w - 1), x1 = Math.Min(2 * x + 1, w - 1), y0 = Math.Min(2 * y, h - 1), y1 = Math.Min(2 * y + 1, h - 1);
o[(y * nw + x) * 4 + c] = (byte)((src[(y0 * w + x0) * 4 + c] + src[(y0 * w + x1) * 4 + c] + src[(y1 * w + x0) * 4 + c] + src[(y1 * w + x1) * 4 + c] + 2) >> 2);
}
return (o, nw, nh);
}
/// <summary>The eye as one picture: the sclera, with the iris inside the mask's circle (the iris map spans the circle at
/// IrisScale of its own width).</summary>
static (int, int, byte[]) Eye((int W, int H, byte[] Rgba) iris, (int W, int H, byte[] Rgba) sclera, (int W, int H, byte[] Rgba) mask)
{
const float IrisScale = 2.85f;
int w = sclera.W, h = sclera.H;
var o = new byte[w * h * 4];
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
{
float u = (x + .5f) / w, v = (y + .5f) / h;
var m = Sample(mask, u, v, 0) / 255f;
float iu = .5f + (u - .5f) * IrisScale, iv = .5f + (v - .5f) * IrisScale;
for (var c = 0; c < 3; c++)
{
var s = Sample(sclera, u, v, c);
var i = Sample(iris, iu, iv, c);
o[(y * w + x) * 4 + c] = (byte)Math.Clamp(s + (i - s) * m + .5f, 0, 255);
}
o[(y * w + x) * 4 + 3] = 255;
}
return (w, h, o);
}
static float Sample((int W, int H, byte[] Rgba) t, float u, float v, int c)
{
var x = Math.Clamp((int)(u * t.W), 0, t.W - 1);
var y = Math.Clamp((int)(v * t.H), 0, t.H - 1);
return t.Rgba[(y * t.W + x) * 4 + c];
}
}

View File

@@ -0,0 +1,36 @@
// (Triforce, 11-29) A mod's romfs over the game's, as the game sees them both (host/mods.c: a mod's file wins over the game's):
// the Character page reads Linkle (a mod: Model/, Tex/, Pack/ ...) this way, so her models and textures come from the mod and
// everything she shares with the game from the game. Read-only, like every source.
namespace Triforce.Core.GameFiles;
public sealed class OverlaySource : IGameSource
{
readonly IGameSource top, bottom;
readonly bool ownsTop;
/// <param name="top">The mod's romfs (its files win).</param>
/// <param name="bottom">The game's romfs.</param>
/// <param name="ownsTop">Dispose top with this source (bottom is the caller's).</param>
public OverlaySource(IGameSource top, IGameSource bottom, bool ownsTop = true)
{
this.top = top; this.bottom = bottom; this.ownsTop = ownsTop;
}
public string Describe => top.Describe + " over " + bottom.Describe;
/// <summary>Whether the mod (not the game) has this file.</summary>
public bool InTop(string romfsPath) => top.Exists(romfsPath);
public bool Exists(string romfsPath) => top.Exists(romfsPath) || bottom.Exists(romfsPath);
public byte[] Read(string romfsPath) => top.Exists(romfsPath) ? top.Read(romfsPath) : bottom.Read(romfsPath);
public IEnumerable<string> List(string dir) => top.List(dir).Union(bottom.List(dir), StringComparer.Ordinal);
public string? Stamp(string romfsPath) => top.Exists(romfsPath) ? "mod:" + top.Stamp(romfsPath) : bottom.Stamp(romfsPath);
public void Dispose()
{
if (ownsTop) top.Dispose();
}
}

View File

@@ -0,0 +1,357 @@
// (Triforce, 11-29) Recolouring a texture of a BNTX file in place, for the Character page's Linkle: her outfit textures are ones
// the randomizer's colour tool cannot read (uncompressed, or BC1 / BC3 it does not edit), so the launcher dyes them itself, the
// way that tool does: the texels of a part are found by their colour band (a hue range, enough saturation), keep their shading
// (luminance relative to the band's median, brightness compressed toward the new colour as the tool's dye comes out), and
// take the new colour. Every mip level is dyed from its own texels with the same rule; a block none of whose texels changed
// keeps its bytes; the others are encoded again in the texture's own format (RGBA8, BC1, BC3's colour half, ASTC), so the file
// keeps its size and layout and only its pixels change. BC7 is refused (the caller leaves such a texture as it is).
// A texture may also be given a new name of the same length (a copy only one model points at).
using System.Buffers.Binary;
using System.Text;
namespace Triforce.Core.GameFiles;
/// <summary>A part's colour band: hues from HueLo to HueHi degrees (wrapping past 360 when HueLo &gt; HueHi), saturation
/// from MinSat and value from MinVal (all 0-1), feathered at the edges so the dye has no hard border.</summary>
public sealed record ColorBand(float HueLo, float HueHi, float MinSat = 0.12f, float MinVal = 0.04f, float MaxVal = 1.01f)
{
/// <summary>Where on the texture the part lies (rectangles in 0-1 texture space: x0, y0, x1, y1), when the texture is a
/// sheet of several things that share colours (a face and a red tunic): null is anywhere.</summary>
public float[][]? Rects { get; init; }
/// <summary>Any colour at all (a texture that is all one part).</summary>
public static readonly ColorBand All = new(0, 360, 0, 0);
}
public static class TextureRecolor
{
/// <summary>Encodes one ASTC block (texels RGBA8, block width, height) to 16 bytes: AstcEncode.EncodeBlock, set by the
/// caller. Without it an ASTC texture is refused.</summary>
public delegate byte[] BlockEncoder(ReadOnlySpan<byte> texels, int blockWidth, int blockHeight);
public static BlockEncoder? Astc;
/// <summary>The texture recoloured: (the new BNTX bytes, the recoloured level 0 as RGBA8 for a preview, how many level-0
/// texels changed). parts: each band and its colour (#rrggbb); a texel in two bands takes the first. newName: a name of the
/// same length for a copy (null keeps the name).</summary>
public static (byte[] Bntx, (int W, int H, byte[] Rgba) Preview, int Changed) Recolor(byte[] bntx, string texName,
IReadOnlyList<(ColorBand Band, string Hex)> parts, string? newName = null)
{
var b = new Bntx(bntx);
var t = b.Find(texName) ?? b.Textures[0];
if (t.TileMode != 0) throw new NotSupportedException(texName + ": a linear texture");
var kind = t.Format >> 8;
if (!(kind is 0x0b or 0x1a or 0x1c || (kind is >= 0x2d and <= 0x3a && Astc != null)))
throw new NotSupportedException(texName + ": " + Bntx.FormatName(t.Format) + " cannot be dyed here");
var (bw, bh, bpb) = Bntx.BlockInfo(t.Format);
var output = (byte[])bntx.Clone();
// the band's reference brightness, from level 0
var level0 = DecodeLevel(bntx, t, 0, out _);
var targets = parts.Select(p => (p.Band, Lin: Lin3(p.Hex))).ToArray();
var ym = new float[targets.Length];
for (var k = 0; k < targets.Length; k++)
{
var ys = new List<float>();
for (var i = 0; i < level0.Rgba.Length; i += 4)
if (Weight(targets[k].Band, level0.Rgba, i, level0.W, level0.H) > 0.5f) ys.Add(Y(level0.Rgba, i));
ys.Sort();
ym[k] = ys.Count > 0 ? Math.Max(ys[ys.Count / 2], 1e-4f) : 0.1f;
}
(int, int, byte[]) preview = default;
var changedTexels = 0;
for (var level = 0; level < t.MipOffsets.Length; level++)
{
int w = Math.Max(1, t.Width >> level), h = Math.Max(1, t.Height >> level);
var orig = level == 0 ? level0 : DecodeLevel(bntx, t, level, out _);
var dyed = (byte[])orig.Rgba.Clone();
var changed = new bool[w * h];
for (var p = 0; p < w * h; p++)
{
var i = p * 4;
for (var k = 0; k < targets.Length; k++)
{
var wt = Weight(targets[k].Band, orig.Rgba, i, w, h);
if (wt <= 0) continue;
Dye(orig.Rgba, dyed, i, targets[k].Lin, ym[k], wt);
changed[p] = dyed[i] != orig.Rgba[i] || dyed[i + 1] != orig.Rgba[i + 1] || dyed[i + 2] != orig.Rgba[i + 2];
break;
}
}
if (level == 0) { preview = (w, h, dyed); changedTexels = changed.Count(c => c); }
if (!changed.Any(c => c)) continue;
// encode the changed blocks, keep the others' bytes
int wB = (w + bw - 1) / bw, hB = (h + bh - 1) / bh;
var bhl = BlockLinear.MipBlockHeight(hB, t.BlockHeightLog2);
var at = (int)t.MipOffsets[level];
var size = (int)BlockLinear.Size(wB, hB, bpb, bhl);
if (at <= 0 || at + size > output.Length) throw new InvalidDataException(texName + ": mip " + level + " lies outside the file");
var linear = BlockLinear.Deswizzle(output.AsSpan(at, size), wB, hB, bpb, bhl);
Parallel.For(0, hB, by =>
{
Span<byte> block = stackalloc byte[12 * 12 * 4];
for (var bx = 0; bx < wB; bx++)
{
var any = false;
for (var y = 0; y < bh && !any; y++)
for (var x = 0; x < bw && !any; x++)
{
int px = Math.Min(bx * bw + x, w - 1), py = Math.Min(by * bh + y, h - 1);
any = changed[py * w + px];
}
if (!any) continue;
for (var y = 0; y < bh; y++)
for (var x = 0; x < bw; x++)
{
int px = Math.Min(bx * bw + x, w - 1), py = Math.Min(by * bh + y, h - 1);
dyed.AsSpan((py * w + px) * 4, 4).CopyTo(block.Slice((y * bw + x) * 4, 4));
}
var dst = linear.AsSpan((by * wB + bx) * bpb, bpb);
var px16 = block[..(bw * bh * 4)];
switch (kind)
{
case 0x0b: px16[..4].CopyTo(dst); break;
case 0x1a: Bc1(px16, dst, true); break;
case 0x1c: Bc1(px16, dst[8..], false); break; // (BC3: the alpha half stays: the dye leaves alpha alone)
default: Astc!(px16, bw, bh).CopyTo(dst); break;
}
}
});
BlockLinear.Swizzle(linear, output.AsSpan(at, size), wB, hB, bpb, bhl);
}
if (newName != null && newName != t.Name)
{
if (newName.Length != t.Name.Length) throw new ArgumentException("a new name must keep the length");
ReplaceAll(output, t.Name, newName);
}
return (output, preview, changedTexels);
}
/// <summary>Every place a name is written, changed to another of the same length.</summary>
public static int ReplaceAll(byte[] data, string from, string to)
{
byte[] f = Encoding.ASCII.GetBytes(from), n = Encoding.ASCII.GetBytes(to);
var count = 0;
for (var i = data.AsSpan().IndexOf(f); i >= 0;)
{
n.CopyTo(data, i); count++;
var next = data.AsSpan(i + f.Length).IndexOf(f);
i = next < 0 ? -1 : i + f.Length + next;
}
return count;
}
/// <summary>One mip level decoded to RGBA8 (as stored: no channel sources applied).</summary>
public static (int W, int H, byte[] Rgba) DecodeLevel(byte[] bntx, BntxTexture t, int level, out byte[] linearBlocks)
{
var (bw, bh, bpb) = Bntx.BlockInfo(t.Format);
int w = Math.Max(1, t.Width >> level), h = Math.Max(1, t.Height >> level);
int wB = (w + bw - 1) / bw, hB = (h + bh - 1) / bh;
var bhl = BlockLinear.MipBlockHeight(hB, t.BlockHeightLog2);
var at = (int)t.MipOffsets[level];
var size = (int)BlockLinear.Size(wB, hB, bpb, bhl);
if (at <= 0 || at + size > bntx.Length) throw new InvalidDataException(t.Name + ": mip " + level + " lies outside the file");
linearBlocks = BlockLinear.Deswizzle(bntx.AsSpan(at, size), wB, hB, bpb, bhl);
var rgba = (t.Format >> 8) switch
{
>= 0x2d and <= 0x3a => GameFiles.Astc.Decompress(linearBlocks, w, h, bw, bh),
0x1a => BlockCompression.Decode(linearBlocks, w, h, BlockCompression.Kind.BC1),
0x1c => BlockCompression.Decode(linearBlocks, w, h, BlockCompression.Kind.BC3),
0x0b => linearBlocks,
_ => throw new NotSupportedException(t.Name + ": " + Bntx.FormatName(t.Format)),
};
return (w, h, rgba);
}
// ---------------- the dye ----------------
static readonly float[] ToLin = Enumerable.Range(0, 256).Select(i => { var x = i / 255f; return x <= 0.04045f ? x / 12.92f : MathF.Pow((x + 0.055f) / 1.055f, 2.4f); }).ToArray();
static byte ToSrgb(float x)
{
x = Math.Clamp(x, 0, 1);
var s = x <= 0.0031308f ? x * 12.92f : 1.055f * MathF.Pow(x, 1 / 2.4f) - 0.055f;
return (byte)Math.Clamp((int)(s * 255 + 0.5f), 0, 255);
}
static float Y(byte[] p, int i) => 0.2126f * ToLin[p[i]] + 0.7152f * ToLin[p[i + 1]] + 0.0722f * ToLin[p[i + 2]];
static float[] Lin3(string hex)
{
var c = Convert.FromHexString(hex.TrimStart('#'));
return new[] { ToLin[c[0]], ToLin[c[1]], ToLin[c[2]] };
}
/// <summary>How much a texel belongs to a band (0-1).</summary>
static float Weight(ColorBand band, byte[] p, int i, int texW, int texH)
{
if (band.Rects is { } rects)
{
var px = i / 4;
float u = (px % texW + 0.5f) / texW, v = (px / texW + 0.5f) / texH;
if (!rects.Any(r => u >= r[0] && u < r[2] && v >= r[1] && v < r[3])) return 0;
}
if (band.HueLo == 0 && band.HueHi >= 360 && band.MinSat <= 0 && band.MinVal <= 0) return 1;
float r = p[i] / 255f, g = p[i + 1] / 255f, bl = p[i + 2] / 255f;
float mx = Math.Max(r, Math.Max(g, bl)), mn = Math.Min(r, Math.Min(g, bl)), d = mx - mn;
if (mx <= 0) return 0;
float s = d / mx;
float h = d <= 0 ? 0 : mx == r ? 60 * (((g - bl) / d + 6) % 6) : mx == g ? 60 * ((bl - r) / d + 2) : 60 * ((r - g) / d + 4);
// hue inside the range, feathered 10 degrees outside it
float lo = band.HueLo, hi = band.HueHi;
float inside;
if (hi - lo >= 360) inside = 1;
else
{
float span = (hi - lo + 360) % 360, off = (h - lo + 360) % 360;
float dist = off <= span ? 0 : Math.Min(off - span, 360 - off);
inside = Math.Clamp(1 - dist / 10f, 0, 1);
}
float sat = band.MinSat <= 0 ? 1 : Math.Clamp((s - band.MinSat) / 0.06f + 0.5f, 0, 1); // (no saturation floor: whites too)
float val = Math.Clamp((mx - band.MinVal) / 0.04f + 0.5f, 0, 1) * Math.Clamp((band.MaxVal - mx) / 0.04f + 0.5f, 0, 1);
return inside * sat * val;
}
/// <summary>A texel dyed: its luminance relative to the band's median (the shading) carried onto the colour, whose median
/// brightness lands between the band's and the colour's (Ym^0.38 * Ty^0.62, as the colour tool's dye comes out).</summary>
static void Dye(byte[] src, byte[] dst, int i, float[] target, float ym, float wt)
{
float ty = Math.Max(0.2126f * target[0] + 0.7152f * target[1] + 0.0722f * target[2], 1e-4f);
float y = Y(src, i);
float q = ym * MathF.Pow(ty / ym, 0.62f);
float k = q / ty * (y / ym);
for (var c = 0; c < 3; c++)
{
var o = ToLin[src[i + c]];
dst[i + c] = ToSrgb(o + (target[c] * k - o) * wt);
}
}
// ---------------- BC1 ----------------
/// <summary>A BC1 colour block for 16 texels (RGBA8): endpoints along the colours' principal axis, refined once by least
/// squares. punchThrough: texels with alpha under 128 take the transparent index (BC1's three-colour mode).</summary>
static void Bc1(ReadOnlySpan<byte> px, Span<byte> dst, bool punchThrough)
{
Span<float> c = stackalloc float[48];
Span<bool> clear = stackalloc bool[16];
var anyClear = false;
var n = 0;
var mean = new float[3];
for (var i = 0; i < 16; i++)
{
clear[i] = punchThrough && px[i * 4 + 3] < 128;
anyClear |= clear[i];
for (var k = 0; k < 3; k++) c[i * 3 + k] = px[i * 4 + k];
if (clear[i]) continue;
for (var k = 0; k < 3; k++) mean[k] += c[i * 3 + k];
n++;
}
if (n == 0) { dst.Clear(); BinaryPrimitives.WriteUInt32LittleEndian(dst[4..], 0xFFFFFFFF); return; }
for (var k = 0; k < 3; k++) mean[k] /= n;
// principal axis (power iteration on the covariance)
float cxx = 0, cxy = 0, cxz = 0, cyy = 0, cyz = 0, czz = 0;
for (var i = 0; i < 16; i++)
{
if (clear[i]) continue;
float x = c[i * 3] - mean[0], y = c[i * 3 + 1] - mean[1], z = c[i * 3 + 2] - mean[2];
cxx += x * x; cxy += x * y; cxz += x * z; cyy += y * y; cyz += y * z; czz += z * z;
}
float ax = 1, ay = 1, az = 1;
for (var it = 0; it < 8; it++)
{
float nx = cxx * ax + cxy * ay + cxz * az, ny = cxy * ax + cyy * ay + cyz * az, nz = cxz * ax + cyz * ay + czz * az;
var len = MathF.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-6f) { ax = 0.577f; ay = 0.577f; az = 0.577f; break; }
ax = nx / len; ay = ny / len; az = nz / len;
}
float lo = float.MaxValue, hi = float.MinValue;
for (var i = 0; i < 16; i++)
{
if (clear[i]) continue;
var d = (c[i * 3] - mean[0]) * ax + (c[i * 3 + 1] - mean[1]) * ay + (c[i * 3 + 2] - mean[2]) * az;
lo = Math.Min(lo, d); hi = Math.Max(hi, d);
}
Span<float> e0 = stackalloc float[3], e1 = stackalloc float[3];
for (var k = 0; k < 3; k++) { var a = k == 0 ? ax : k == 1 ? ay : az; e0[k] = mean[k] + a * hi; e1[k] = mean[k] + a * lo; }
var three = anyClear;
Span<int> idx = stackalloc int[16];
for (var pass = 0; pass < 2; pass++)
{
// (keep e0 the one that quantises larger, so the indices below refer to e0 / e1 as Encode orders them)
if (!three && To565(e0) < To565(e1)) for (var k = 0; k < 3; k++) (e0[k], e1[k]) = (e1[k], e0[k]);
Encode(e0, e1, three, c, clear, idx, out var q0, out var q1);
if (pass == 1 || three) { Write(dst, q0, q1, idx); return; }
// least squares refit of the endpoints for these indices (four-colour mode: weights 0, 1/3, 2/3, 1)
float aa = 0, ab = 0, bb = 0;
Span<float> ax2 = stackalloc float[3], bx2 = stackalloc float[3];
ax2.Clear(); bx2.Clear();
for (var i = 0; i < 16; i++)
{
var wgt = idx[i] switch { 0 => 0f, 1 => 1f, 2 => 1 / 3f, _ => 2 / 3f }; // (index 1 = e1, 2 = 2/3 e0 + 1/3 e1, 3 = 1/3 e0 + 2/3 e1)
float a = 1 - wgt, bq = wgt;
aa += a * a; ab += a * bq; bb += bq * bq;
for (var k = 0; k < 3; k++) { ax2[k] += a * c[i * 3 + k]; bx2[k] += bq * c[i * 3 + k]; }
}
var det = aa * bb - ab * ab;
if (MathF.Abs(det) < 1e-6f) { Write(dst, q0, q1, idx); return; }
for (var k = 0; k < 3; k++)
{
e0[k] = Math.Clamp((bb * ax2[k] - ab * bx2[k]) / det, 0, 255);
e1[k] = Math.Clamp((aa * bx2[k] - ab * ax2[k]) / det, 0, 255);
}
}
}
static ushort To565(ReadOnlySpan<float> c) =>
(ushort)((Math.Clamp((int)(c[0] * 31 / 255 + 0.5f), 0, 31) << 11) | (Math.Clamp((int)(c[1] * 63 / 255 + 0.5f), 0, 63) << 5) | Math.Clamp((int)(c[2] * 31 / 255 + 0.5f), 0, 31));
static void From565(ushort v, Span<int> o)
{
int r = (v >> 11) & 31, g = (v >> 5) & 63, b = v & 31;
o[0] = (r << 3) | (r >> 2); o[1] = (g << 2) | (g >> 4); o[2] = (b << 3) | (b >> 2);
}
/// <summary>Endpoints quantised and ordered for the mode (four colours: c0 &gt; c1; three plus transparent: c0 &lt;= c1),
/// and each texel's nearest palette entry.</summary>
static void Encode(ReadOnlySpan<float> e0, ReadOnlySpan<float> e1, bool three, ReadOnlySpan<float> c, ReadOnlySpan<bool> clear, Span<int> idx, out ushort q0, out ushort q1)
{
q0 = To565(e0); q1 = To565(e1);
if (!three && q0 < q1) (q0, q1) = (q1, q0);
if (three && q0 > q1) (q0, q1) = (q1, q0);
if (!three && q0 == q1)
{
// (one colour: four-colour mode needs c0 > c1)
if (q0 > 0) q1 = (ushort)(q0 - 1); else q0 = 1;
}
Span<int> a = stackalloc int[3], b = stackalloc int[3];
From565(q0, a); From565(q1, b);
Span<int> pal = stackalloc int[12];
for (var k = 0; k < 3; k++)
{
pal[k] = a[k]; pal[3 + k] = b[k];
if (three) { pal[6 + k] = (a[k] + b[k] + 1) / 2; pal[9 + k] = 0; }
else { pal[6 + k] = (2 * a[k] + b[k] + 1) / 3; pal[9 + k] = (a[k] + 2 * b[k] + 1) / 3; }
}
var count = three ? 3 : 4;
for (var i = 0; i < 16; i++)
{
if (clear[i]) { idx[i] = 3; continue; }
var best = 0; var bd = int.MaxValue;
for (var j = 0; j < count; j++)
{
int dr = pal[j * 3] - (int)c[i * 3], dg = pal[j * 3 + 1] - (int)c[i * 3 + 1], db = pal[j * 3 + 2] - (int)c[i * 3 + 2];
var dd = dr * dr * 3 + dg * dg * 4 + db * db * 2;
if (dd < bd) { bd = dd; best = j; }
}
idx[i] = best;
}
}
static void Write(Span<byte> dst, ushort q0, ushort q1, ReadOnlySpan<int> idx)
{
BinaryPrimitives.WriteUInt16LittleEndian(dst, q0);
BinaryPrimitives.WriteUInt16LittleEndian(dst[2..], q1);
uint bits = 0;
for (var i = 0; i < 16; i++) bits |= (uint)(idx[i] & 3) << (2 * i);
BinaryPrimitives.WriteUInt32LittleEndian(dst[4..], bits);
}
}

View File

@@ -0,0 +1,652 @@
// (Triforce, 11-29) The Character page's colours: young Link's and adult Link's tunics, gear and hair, each in its own colours.
// The recolouring is OOTRR's (the randomizer's program, already used by the Randomizer page: Ootrr.cs): its colors-preview
// gives the recoloured colour maps as pictures in seconds (the page's exact preview), and its build writes the game files
// (block-exact edits of the compressed textures, so nothing is re-encoded). A build recolours a part for every age at once,
// so young and adult Link each get a build of their own and the files are taken from each: young Link's from the first,
// adult Link's from the second. The one texture both ages share (OOTRR's own copy of the cloth tile, Angin_Tile_L_Alb) is
// renamed once more for young Link (Angin_Tile_Y_Alb, the same length) and his models point at it: the same one-letter edit
// OOTRR makes to point Link away from the tile the Kokiri share.
//
// The result is a mod of its own, <game>\mods\~Link colors (its name sorts after every other mod's, so its files win over a
// randomizer seed's colours), with triforce_mod.json (its name on the Mods page) and link_colors.json (the colours, which the
// page reads back). It changes the game's files, not a save: every save, old or new, shows the colours.
//
// <home>\character\choices.json the colours being picked (not applied yet)
// <home>\character\<game stamp>\cal\ the calibration: where each part lies on each colour map (masks) and its brightness
// <home>\character\work\<id>\ a build or preview while it runs (taken away after)
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Triforce.Core.GameFiles;
using ZstdSharp;
namespace Triforce.Logic;
/// <summary>A part of Link the page can colour: OOTRR's id, its name on the page, its group, the ages and tunics it shows on,
/// and roughly the game's own colour (for the swatch while it is unchanged).</summary>
public sealed record LinkPart(string Id, string Label, string Group, string Ages, string Tunic, string Swatch);
public sealed class LinkColors
{
public const string ModFolder = "~Link colors";
public const string Marker = "link_colors.json";
public const string WorkFolder = "character";
/// <summary>Ages: "child" (young Link) and "adult". Tunic: "" any, else kokiri / goron / zora (the adult's tunic it shows on).</summary>
public static readonly LinkPart[] Parts =
{
new("kokiri", "Tunic and cap", "Tunic", "child,adult", "kokiri", "#2f8f3a"),
new("kokiri_pants", "Leggings", "Tunic", "child", "", "#3d7a33"),
new("kokiri_shirt", "Undershirt and leggings", "Tunic", "adult", "kokiri", "#d8d1bd"),
new("feathers", "Cap feather", "Tunic", "child,adult", "kokiri", "#e6dfcf"),
new("goron", "Goron Tunic", "Tunic", "adult", "goron", "#b3262c"),
new("goron_trim", "Goron trim", "Tunic", "adult", "goron", "#d4a634"),
new("goron_belt", "Goron belt", "Tunic", "adult", "goron", "#6b4a2b"),
new("goron_beads", "Goron beads", "Tunic", "adult", "goron", "#c9b07a"),
new("zora", "Zora Tunic", "Tunic", "adult", "zora", "#2a4fb0"),
new("zora_shirt", "Zora undershirt", "Tunic", "adult", "zora", "#d4d8de"),
new("zora_belt", "Zora belt", "Tunic", "adult", "zora", "#8a3c8e"),
new("zora_scales", "Zora scales", "Tunic", "adult", "zora", "#3d8fb8"),
new("kokiri_belt", "Belts and straps", "Leather", "child,adult", "kokiri", "#6b4a2b"),
new("leather_trim", "Leather trim", "Leather", "child,adult", "", "#9c2f25"),
new("boots", "Boots", "Leather", "adult", "", "#5b3f26"),
new("gloves", "Gloves", "Leather", "adult", "", "#7a5534"),
new("hair", "Hair", "Hair", "child,adult", "", "#e0b84a"),
new("navi", "Navi", "Navi", "child,adult", "", "#dff3ff"),
};
public static IEnumerable<LinkPart> PartsOf(string age) => Parts.Where(p => p.Ages.Split(',').Contains(age));
public static bool Valid(string age, string part) => PartsOf(age).Any(p => p.Id == part);
/// <summary>(11-29) The heroes: Link, and Linkle (a mod: Linkle.cs). A colour key is the age, "linkle:" in front for her.</summary>
public static readonly string[] Heroes = { "link", "linkle" };
public static string Key(string hero, string age) => hero == "linkle" ? "linkle:" + age : age;
public static (string Hero, string Age) FromKey(string key) => key.StartsWith("linkle:", StringComparison.Ordinal) ? ("linkle", key[7..]) : ("link", key);
public static IEnumerable<LinkPart> PartsOf(string hero, string age) => (hero == "linkle" ? Linkle.Parts : Parts).Where(p => p.Ages.Split(',').Contains(age));
public static bool Valid(string hero, string age, string part) => PartsOf(hero, age).Any(p => p.Id == part);
static readonly string[] Keys = { "child", "adult", "linkle:child", "linkle:adult" };
/// <summary>Parts the game has once for both ages (Navi is one fairy): set for one age, set for both.</summary>
public static readonly string[] Shared = { "navi" };
static readonly Regex Hex = new("^#[0-9a-f]{6}$", RegexOptions.CultureInvariant);
public static string? CleanHex(string? hex)
{
hex = (hex ?? "").Trim().ToLowerInvariant();
if (hex.Length == 6) hex = "#" + hex;
return Hex.IsMatch(hex) ? hex : null;
}
readonly TriforceContext ctx;
public Ootrr Tool { get; }
public ModManager Mods { get; }
public LinkColors(TriforceContext ctx, Ootrr tool, ModManager mods) { this.ctx = ctx; Tool = tool; Mods = mods; }
string Home => Path.Combine(ctx.Home, WorkFolder);
// ---------------- the colours being picked ----------------
/// <summary>age -> part -> #rrggbb. A part not in it keeps the game's colour.</summary>
public sealed class Choice
{
public Dictionary<string, Dictionary<string, string>> Colors { get; } = new() { ["child"] = new(), ["adult"] = new() };
/// <summary>Who the player plays: "link" or "linkle".</summary>
public string Hero { get; set; } = "link";
/// <summary>The colours of the hero being played, by age.</summary>
public Dictionary<string, string> Of(string age) => Age(Key(Hero, age));
public Dictionary<string, string> Age(string age) => Colors.TryGetValue(age, out var d) ? d : Colors[age] = new();
public Choice Copy()
{
var c = new Choice { Hero = Hero };
foreach (var (age, d) in Colors) c.Colors[age] = new Dictionary<string, string>(d);
return c;
}
/// <summary>The same hero, and the same colours for that hero (the other hero's picks are not in the game).</summary>
public bool Same(Choice o) => Hero == o.Hero && new[] { Key(Hero, "child"), Key(Hero, "adult") }.All(a =>
{
var x = Colors.TryGetValue(a, out var p) ? p : new(); var y = o.Colors.TryGetValue(a, out var q) ? q : new();
return x.Count == y.Count && x.All(kv => y.TryGetValue(kv.Key, out var v) && v == kv.Value);
});
/// <summary>Nothing to write: Link in the game's own colours.</summary>
public bool Empty => Hero == "link" && Of("child").Count == 0 && Of("adult").Count == 0;
public JsonObject ToJson()
{
var o = new JsonObject(Colors.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)new JsonObject(kv.Value.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value))))));
o["hero"] = Hero;
return o;
}
public static Choice FromJson(JsonNode? n)
{
var c = new Choice();
if (n is not JsonObject o) return c;
if (o["hero"] is JsonValue h && h.TryGetValue<string>(out var hero) && Heroes.Contains(hero)) c.Hero = hero;
foreach (var key in Keys)
{
var (kh, age) = FromKey(key);
if (o[key] is JsonObject a)
foreach (var (part, v) in a)
if (Valid(kh, age, part) && CleanHex(v is JsonValue jv && jv.TryGetValue<string>(out var s) ? s : null) is { } hex) c.Age(key)[part] = hex;
}
return c;
}
}
string ChoicesFile => Path.Combine(Home, "choices.json");
public Choice LoadChoice()
{
try { return File.Exists(ChoicesFile) ? Choice.FromJson(JsonNode.Parse(File.ReadAllText(ChoicesFile))) : new Choice(); }
catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException) { return new Choice(); }
}
public void SaveChoice(Choice c)
{
if (!ctx.Allowed(Home)) return;
try
{
Directory.CreateDirectory(Home);
var tmp = ChoicesFile + ".tmp";
File.WriteAllText(tmp, new JsonObject { ["colors"] = c.ToJson() }["colors"]!.ToJsonString());
File.Move(tmp, ChoicesFile, true);
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { ctx.Log.Write("character: colours not kept: " + e.Message); }
}
// ---------------- what the game has now ----------------
public static string ModPath(string game) => Path.Combine(Triforce.Logic.Mods.FolderOf(game), ModFolder);
/// <summary>The colours the game has now (the mod's marker), or null when the mod is not there. On is false when the
/// player switched it off on the Mods page.</summary>
public (Choice Colors, bool On, string Path)? Applied(string game)
{
var mods = Triforce.Logic.Mods.FolderOf(game);
foreach (var path in new[] { Path.Combine(mods, ModFolder), Path.Combine(mods, "-" + ModFolder), Path.Combine(mods, "_" + ModFolder) })
{
var marker = Path.Combine(path, Marker);
if (!File.Exists(marker)) continue;
try { return (Choice.FromJson(JsonNode.Parse(File.ReadAllText(marker))?["colors"]), !System.IO.Path.GetFileName(path).StartsWith('-') && !System.IO.Path.GetFileName(path).StartsWith('_'), path); }
catch (Exception e) when (e is IOException || e is JsonException) { return (new Choice(), true, path); }
}
return null;
}
/// <summary>Other mods that are on and carry Link's model or one of the colour maps: the page says which wins.</summary>
public IReadOnlyList<string> Others(string game)
{
try
{
return Mods.ListGame(game, false).Where(m => m.On && !m.Path.EndsWith(ModFolder, StringComparison.OrdinalIgnoreCase)
&& m.Files.Any(f => f.StartsWith("model/player_child", StringComparison.Ordinal) || f.StartsWith("model/player_adult", StringComparison.Ordinal)))
.Select(m => m.Info?.Name is { Length: > 0 } n ? n : m.Name).ToList();
}
catch (Exception) { return Array.Empty<string>(); }
}
// ---------------- calibration: where each part lies on each colour map ----------------
/// <summary>One colour map's parts: up to two (slot 0 in the mask's red, slot 1 in its green), each with the median
/// linear luminance of its texels before (Ym) and after (Qm) the calibration colour of luminance Ty. OOTRR keeps the
/// shading and compresses brightness: a colour of luminance Y comes out near Qm * (Y / Ty)^0.62 at the median texel.</summary>
/// ((11-30) G: the contrast OOTRR gives its texels, after_Y ~ before_Y^G over the part's texels (0.98 to 1.6 on Link's maps:
/// the live tint follows it, or the tint and OOTRR's exact map differed enough that a pick seemed to "switch back")
public sealed record CalMap(string Texture, string[] Parts, float[] Ym, float[] Qm, float[] Ty, float[] G, int Width, int Height, byte[] Mask);
static readonly string[] Trims = { "leather_trim", "goron_trim" };
const string Primary = "#ff00ff", Trim = "#00ffff";
public string CalFolder(string stamp) => Path.Combine(Home, stamp, "cal5"); // ((11-30) cal5: with G and the mask by strength, made again once
static JsonArray Floats(float[] v) => new(v.Select(x => (JsonNode?)x).ToArray());
/// <summary>The calibration, read from the cache or made (one colors-preview of every part: about 15 s, once per game).</summary>
public async Task<IReadOnlyList<CalMap>> CalibrateAsync(string game, string stamp, CancellationToken token)
{
var dir = CalFolder(stamp);
var index = Path.Combine(dir, "cal.json");
if (File.Exists(index))
try { return ReadCal(dir, index); } catch (Exception e) when (e is IOException || e is JsonException || e is InvalidDataException) { ctx.Log.Write("character: calibration unreadable, made again: " + e.Message); }
ctx.Require(Home);
var work = Path.Combine(Home, "work", "cal-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(work);
try
{
var args = new List<string> { "colors-preview", Romfs(game), work, "custom", "triforce" };
args.AddRange(Parts.Select(p => p.Id + "=" + (Trims.Contains(p.Id) ? Trim : Primary)));
var run = await Tool.RunAsync(args, null, token).ConfigureAwait(false);
var maps = new List<CalMap>();
foreach (var (tex, parts) in PreviewLines(run.Out))
{
var before = Path.Combine(work, tex + "_before.png");
var after = Path.Combine(work, tex + "_after.png");
if (!File.Exists(before) || !File.Exists(after) || parts.Count == 0) continue;
var (w, h, b) = Png.Decode(File.ReadAllBytes(before));
var (w2, h2, a) = Png.Decode(File.ReadAllBytes(after));
if (w != w2 || h != h2) continue;
var slots = parts.Take(2).ToArray();
var mask = new byte[w * h * 4];
var yb = slots.Select(_ => new List<float>()).ToArray();
var ya = slots.Select(_ => new List<float>()).ToArray();
for (var i = 0; i < w * h; i++)
{
int dr = a[4 * i] - b[4 * i], dg = a[4 * i + 1] - b[4 * i + 1], db = a[4 * i + 2] - b[4 * i + 2];
// ((11-30) by how far OOTRR moved it: the leather 100 and more (of 765), metal, buckles and charms under 60
// and nearly grey; the tint fades in from 20 to 100, so it no longer paints the buckle and ring)
var moved = Math.Abs(dr) + Math.Abs(dg) + Math.Abs(db);
if (moved < 20) continue;
// (which part moved it: the trim parts were set to cyan, the others to magenta)
var slot = 0;
if (slots.Length > 1)
{
var cyan = a[4 * i + 1] - a[4 * i]; // (cyan: green over red; magenta: red over green)
var trimSlot = Array.FindIndex(slots, s => Trims.Contains(s));
slot = trimSlot >= 0 ? (cyan > 0 ? trimSlot : 1 - trimSlot) : 0;
}
mask[4 * i + slot] = (byte)Math.Clamp((moved - 20) * 255 / 80, 0, 255);
mask[4 * i + 3] = 255;
if (moved < 60) continue; // (the part's own texels alone in its medians and contrast)
yb[slot].Add(Lum(b, 4 * i));
ya[slot].Add(Lum(a, 4 * i));
}
var ym = new float[slots.Length]; var qm = new float[slots.Length]; var ty = new float[slots.Length]; var g = new float[slots.Length];
for (var s = 0; s < slots.Length; s++)
{
ty[s] = LumOf(Trims.Contains(slots[s]) ? Trim : Primary);
g[s] = Contrast(yb[s], ya[s]);
ym[s] = yb[s].Count > 0 ? Math.Max(Median(yb[s]), 1e-4f) : 0.05f;
qm[s] = ya[s].Count > 0 ? Math.Max(Median(ya[s]), 1e-4f) : 0.1f;
}
maps.Add(new CalMap(tex, slots, ym, qm, ty, g, w, h, Blur(mask, w, h)));
}
Directory.CreateDirectory(dir);
var j = new JsonArray();
foreach (var m in maps)
{
await File.WriteAllBytesAsync(Path.Combine(dir, m.Texture + ".mask"), m.Mask, token).ConfigureAwait(false);
j.Add(new JsonObject
{
["tex"] = m.Texture, ["parts"] = new JsonArray(m.Parts.Select(p => (JsonNode?)p).ToArray()), ["w"] = m.Width, ["h"] = m.Height,
["ym"] = Floats(m.Ym), ["qm"] = Floats(m.Qm), ["ty"] = Floats(m.Ty), ["g"] = Floats(m.G),
});
}
await File.WriteAllTextAsync(index, j.ToJsonString(), token).ConfigureAwait(false);
ctx.Log.Write("character: calibration made, " + maps.Count + " colour maps");
return maps;
}
finally { try { Directory.Delete(work, true); } catch (Exception) { } }
}
static IReadOnlyList<CalMap> ReadCal(string dir, string index)
{
var list = new List<CalMap>();
foreach (var n in JsonNode.Parse(File.ReadAllText(index)) as JsonArray ?? new JsonArray())
{
var tex = (string)n!["tex"]!;
if (tex.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) continue;
int w = (int)n["w"]!, h = (int)n["h"]!;
var mask = File.ReadAllBytes(Path.Combine(dir, tex + ".mask"));
if (mask.Length != w * h * 4) throw new InvalidDataException("a mask of the wrong size");
float[] F(string k) => ((JsonArray)n[k]!).Select(x => (float)x!).ToArray();
if (n["g"] is not JsonArray) throw new InvalidDataException("a calibration without the contrast (g)");
list.Add(new CalMap(tex, ((JsonArray)n["parts"]!).Select(x => (string)x!).ToArray(), F("ym"), F("qm"), F("ty"), F("g"), w, h, mask));
}
return list;
}
/// <summary>A mask softened by one texel, so the live tint has no hard stairs at its edges.</summary>
static byte[] Blur(byte[] m, int w, int h)
{
var o = new byte[m.Length];
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
for (var c = 0; c < 4; c++)
{
int s = 0, n = 0;
for (var dy = -1; dy <= 1; dy++)
for (var dx = -1; dx <= 1; dx++)
{
int xx = x + dx, yy = y + dy;
if (xx < 0 || yy < 0 || xx >= w || yy >= h) continue;
s += m[(yy * w + xx) * 4 + c]; n++;
}
o[(y * w + x) * 4 + c] = (byte)(s / n);
}
return o;
}
static float Lin(byte v) { var x = v / 255f; return x <= 0.04045f ? x / 12.92f : MathF.Pow((x + 0.055f) / 1.055f, 2.4f); }
static float Lum(byte[] p, int i) => 0.2126f * Lin(p[i]) + 0.7152f * Lin(p[i + 1]) + 0.0722f * Lin(p[i + 2]);
public static float LumOf(string hex)
{
var c = Convert.FromHexString(hex[1..]);
return 0.2126f * Lin(c[0]) + 0.7152f * Lin(c[1]) + 0.0722f * Lin(c[2]);
}
static float Median(List<float> v) { v.Sort(); return v[v.Count / 2]; }
/// <summary>((11-30)) The slope of log(after) on log(before) over a part's texels (least squares), in [0.7, 1.8]; 1 when too few
/// texels or no spread. Measured on young Link's belt: 1.15 for red, 0.98 for blue; his vest: 1.6.</summary>
internal static float Contrast(List<float> before, List<float> after)
{
double sx = 0, sy = 0, sxx = 0, sxy = 0; var n = 0;
for (var i = 0; i < before.Count && i < after.Count; i++)
{
if (before[i] < 1e-4f || after[i] < 1e-4f) continue;
double x = Math.Log(before[i]), y = Math.Log(after[i]);
sx += x; sy += y; sxx += x * x; sxy += x * y; n++;
}
if (n < 64) return 1f;
var vx = sxx - sx * sx / n;
if (vx < 1e-6) return 1f;
return (float)Math.Clamp((sxy - sx * sy / n) / vx, 0.7, 1.8);
}
/// <summary>colors-preview's lines: "Tex_Name: part #RRGGBB, part2 #RRGGBB, n of m blocks changed ...".</summary>
static IEnumerable<(string Tex, List<string> Parts)> PreviewLines(string output)
{
foreach (var raw in output.Split('\n'))
{
var l = raw.Trim();
var colon = l.IndexOf(": ", StringComparison.Ordinal);
if (colon <= 0) continue;
var tex = l[..colon];
if (tex.Contains(' ') || tex.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) continue;
var parts = Regex.Matches(l[(colon + 2)..], @"([a-z_]+) #[0-9A-Fa-f]{6}").Select(m => m.Groups[1].Value).Where(p => Parts.Any(x => x.Id == p)).ToList();
if (parts.Count > 0) yield return (tex, parts);
}
}
// ---------------- the exact preview ----------------
/// <summary>OOTRR's own recoloured colour maps for one age's colours (pictures of the colour maps it would write, at the
/// size colors-preview gives them). Keys are the texture names as the model names them (OOTRR's renamed copy of the cloth
/// tile is given under the tile's own name).</summary>
public async Task<Dictionary<string, (int W, int H, byte[] Rgba)>> PreviewAsync(string game, IReadOnlyDictionary<string, string> colors, CancellationToken token)
{
var maps = new Dictionary<string, (int, int, byte[])>(StringComparer.Ordinal);
if (colors.Count == 0) return maps;
ctx.Require(Home);
var work = Path.Combine(Home, "work", "pv-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(work);
try
{
var args = new List<string> { "colors-preview", Romfs(game), work, "custom", "triforce" };
args.AddRange(colors.Select(kv => kv.Key + "=" + kv.Value));
var run = await Tool.RunAsync(args, null, token).ConfigureAwait(false);
using var src = new FolderSource(Romfs(game));
var zs = new Zs(src);
foreach (var (tex, _) in PreviewLines(run.Out))
{
var after = Path.Combine(work, tex + "_after.png");
var before = Path.Combine(work, tex + "_before.png");
if (!File.Exists(after) || !File.Exists(before)) continue;
var a = Png.Decode(await File.ReadAllBytesAsync(after, token).ConfigureAwait(false));
var b = Png.Decode(await File.ReadAllBytesAsync(before, token).ConfigureAwait(false));
var name = ModelName(tex);
// (colors-preview's pictures are small: the change they show is carried onto the game's own full-size map)
var full = LinkScene.Texture(src, zs, name);
maps[name] = full is { } f && a.Width == b.Width && a.Height == b.Height ? Carry(f, b, a) : a;
token.ThrowIfCancellationRequested();
}
return maps;
}
finally { try { Directory.Delete(work, true); } catch (Exception) { } }
}
static readonly float[] ToLin = Enumerable.Range(0, 256).Select(i => Lin((byte)i)).ToArray();
static readonly byte[] ToSrgb = Enumerable.Range(0, 4096).Select(i =>
{
var x = i / 4095f;
var s = x <= 0.0031308f ? x * 12.92f : 1.055f * MathF.Pow(x, 1 / 2.4f) - 0.055f;
return (byte)Math.Clamp(MathF.Round(s * 255), 0, 255);
}).ToArray();
/// <summary>The full-size map with the change from before to after (two small pictures of it) carried over: each texel is
/// scaled, channel by channel in linear light, as the small pictures change at its place.</summary>
static (int, int, byte[]) Carry((int W, int H, byte[] Rgba) full, (int Width, int Height, byte[] Rgba) before, (int Width, int Height, byte[] Rgba) after)
{
// ((11-30) E 0.012 -> 0.002: measured on young Link's belt at #FF0000, 0.012 made the red 11% darker than OOTRR's own
// picture (0.220 against 0.246 linear at the median), 0.002 within 1%; the factor is held to 16 where a texel was near black)
const float E = 0.002f, MaxGain = 16f;
int w = full.W, h = full.H, sw = before.Width, sh = before.Height;
var o = new byte[w * h * 4];
Parallel.For(0, h, y =>
{
var fy = Math.Clamp((y + .5f) * sh / h - .5f, 0, sh - 1);
int y0 = (int)fy, y1 = Math.Min(y0 + 1, sh - 1); var ty = fy - y0;
for (var x = 0; x < w; x++)
{
var fx = Math.Clamp((x + .5f) * sw / w - .5f, 0, sw - 1);
int x0 = (int)fx, x1 = Math.Min(x0 + 1, sw - 1); var tx = fx - x0;
var i = (y * w + x) * 4;
for (var c = 0; c < 3; c++)
{
float S(byte[] p, int xx, int yy) => ToLin[p[(yy * sw + xx) * 4 + c]];
float Bi(byte[] p) => (S(p, x0, y0) * (1 - tx) + S(p, x1, y0) * tx) * (1 - ty) + (S(p, x0, y1) * (1 - tx) + S(p, x1, y1) * tx) * ty;
var v = ToLin[full.Rgba[i + c]] * Math.Min((Bi(after.Rgba) + E) / (Bi(before.Rgba) + E), MaxGain);
o[i + c] = ToSrgb[Math.Clamp((int)(v * 4095 + .5f), 0, 4095)];
}
o[i + 3] = full.Rgba[i + 3];
}
});
return (w, h, o);
}
/// <summary>OOTRR's renamed copies under the name the game's models give them.</summary>
public static string ModelName(string tex) => tex switch
{
"Angin_Tile_L_Alb" => "Angin_Tile_A_Alb",
_ => tex,
};
// ---------------- apply: the mod ----------------
static readonly string[] RomfsNeeds = { "Model", "Tex", "Pack" };
static string Romfs(string game)
{
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. Build the game again first.");
return romfs;
}
/// <summary>The seed every colour build uses: the randomizer's defaults, made once (only the colours are taken from the
/// build; the seed's own files are thrown away).</summary>
async Task<string> SeedAsync(CancellationToken token)
{
var seed = Path.Combine(Home, "colors-" + Ootrr.Version + ".ootrr");
if (File.Exists(seed)) return seed;
var settings = Path.Combine(Home, "colors-settings.json");
await File.WriteAllTextAsync(settings, "{}", token).ConfigureAwait(false);
await Tool.RunAsync(new[] { "generate", settings, "TRIFORCECOLORS", seed }, null, token).ConfigureAwait(false);
if (!File.Exists(seed)) throw new OotrrException("The randomizer made no seed for the colours.");
return seed;
}
const string ChildTile = "Angin_Tile_L_Alb", ChildTileMine = "Angin_Tile_Y_Alb";
/// <summary>Writes the mod for these colours (or takes it away when there are none) and returns the folder. progress: a
/// line for the page.</summary>
public async Task<string?> ApplyAsync(string game, Choice choice, Action<string>? progress, CancellationToken token)
{
var mods = Triforce.Logic.Mods.FolderOf(game);
ctx.Require(mods);
if (Mods.GameRuns(game)) throw new OotrrException("Close the game first: it reads its files when it starts.");
var linkleMod = Linkle.Find(Mods, game);
var linkle = choice.Hero == "linkle";
if (linkle && linkleMod == null) throw new OotrrException("Get Linkle first: she is a mod from GameBanana, downloaded on the Character page.");
if (choice.Empty) { Remove(game); SetLinkle(game, linkleMod, false); return null; }
// (what the colour tool dyes: all of Link's colours; for Linkle only adult hair, the game's own texture she wears)
var ootrr = new[] { "child", "adult" }.ToDictionary(a => a, a => linkle
? (a == "adult" && choice.Of(a).TryGetValue("hair", out var hh) ? new Dictionary<string, string> { ["hair"] = hh } : new Dictionary<string, string>())
: new Dictionary<string, string>(choice.Of(a)));
if (ootrr.Values.Any(d => d.Count > 0) && !Tool.Have) throw new OotrrException("The colour tool is not installed yet.");
var romfs = Romfs(game);
Directory.CreateDirectory(Home);
var seed = ootrr.Values.Any(d => d.Count > 0) ? await SeedAsync(token).ConfigureAwait(false) : "";
var work = Path.Combine(Home, "work", "apply-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(work);
var staging = Path.Combine(mods, ".colors-" + Guid.NewGuid().ToString("N")[..8]);
try
{
progress?.Invoke("Dyeing the cloth");
var ages = new[] { "child", "adult" }.Where(a => ootrr[a].Count > 0).ToList();
await Task.WhenAll(ages.Select(age =>
{
var args = new List<string> { "build", seed, romfs, work, age, "--host", "nx2navi", "--colors", "custom", "--no-title-logo" };
foreach (var (part, hex) in ootrr[age]) { args.Add("--color-part"); args.Add(part + "=" + hex); }
return Tool.RunAsync(args, null, token);
})).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
progress?.Invoke("Putting the colours in place");
var into = Path.Combine(staging, "romfs");
Directory.CreateDirectory(Path.Combine(into, "Model"));
Directory.CreateDirectory(Path.Combine(into, "Tex"));
var src = new FolderSource(romfs);
var zs = new Zs(src);
foreach (var age in ages)
{
var built = Path.Combine(work, age, "romfs");
var child = age == "child";
foreach (var f in Directory.EnumerateFiles(Path.Combine(built, "Tex"), "*.bntx.zs"))
{
var name = Path.GetFileName(f)[..^".bntx.zs".Length];
if (linkle) { if (name == "Mt_Hairs_Player_Adult_Alb") File.Copy(f, Path.Combine(into, "Tex", Path.GetFileName(f)), true); continue; }
var mine = name.Contains("_Adult", StringComparison.Ordinal) ? !child : name.Contains("_Child", StringComparison.Ordinal) ? child
: (child ? !src.Exists("Tex/" + name + ".bntx.zs") || name.Contains("_Dark_", StringComparison.Ordinal) || name.StartsWith("Npc_Navi", StringComparison.Ordinal) : true);
if (!mine) continue;
if (child && name == ChildTile)
{
// (young Link's own copy of the tile, under a name adult Link's models do not use)
var data = Rename(zs, "Tex/" + name + ".bntx.zs", await File.ReadAllBytesAsync(f, token).ConfigureAwait(false), ChildTile, ChildTileMine);
await File.WriteAllBytesAsync(Path.Combine(into, "Tex", ChildTileMine + ".bntx.zs"), data, token).ConfigureAwait(false);
continue;
}
var to = Path.Combine(into, "Tex", Path.GetFileName(f));
if (child && File.Exists(to)) continue; // (a map both ages write in place: adult Link's wins)
File.Copy(f, to, true);
}
var modelDir = Path.Combine(built, "Model");
if (linkle || !Directory.Exists(modelDir)) continue;
foreach (var f in Directory.EnumerateFiles(modelDir, "*.bfres.zs"))
{
var name = Path.GetFileName(f);
var isChild = name.Contains("_Child", StringComparison.Ordinal);
var both = name.StartsWith("Npc_Navi", StringComparison.Ordinal); // (Navi: either build's, adult Link's last)
if (isChild != child && !both) continue;
var data = await File.ReadAllBytesAsync(f, token).ConfigureAwait(false);
if (child) data = Rename(zs, "Model/" + name, data, ChildTile, ChildTileMine);
await File.WriteAllBytesAsync(Path.Combine(into, "Model", name), data, token).ConfigureAwait(false);
}
}
if (linkle)
{
progress?.Invoke("Dyeing Linkle's clothes");
using var her = Linkle.Source(linkleMod!, game);
var hzs = new Zs(her);
var written = new List<LinklePiece>();
foreach (var age in new[] { "child", "adult" })
{
var dyed = Linkle.Dye(her, hzs, age, choice.Of(age));
foreach (var (tex, (writeName, bntx, _)) in dyed)
{
await File.WriteAllBytesAsync(Path.Combine(into, "Tex", writeName + ".bntx.zs"), Linkle.Pack(hzs, "Tex/" + writeName + ".bntx.zs", bntx), token).ConfigureAwait(false);
written.AddRange(Linkle.Pieces.Where(kv => kv.Key.Age == age).SelectMany(kv => kv.Value).Where(p => (p.Copy ?? p.Texture) == tex));
}
token.ThrowIfCancellationRequested();
}
foreach (var (model, data) in Linkle.PatchModels(her, hzs, written))
await File.WriteAllBytesAsync(Path.Combine(into, model.Replace('/', Path.DirectorySeparatorChar)), data, token).ConfigureAwait(false);
}
if (!Directory.EnumerateFiles(into, "*", SearchOption.AllDirectories).Any())
{
// (Linkle in her own colours: nothing to write, she only goes on)
Remove(game);
SetLinkle(game, linkleMod, linkle);
return null;
}
var opts = new JsonSerializerOptions { WriteIndented = true };
await File.WriteAllTextAsync(Path.Combine(staging, "triforce_mod.json"), new JsonObject
{
["name"] = "Link's colors", ["author"] = "Triforce · Character page",
}.ToJsonString(opts), token).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(staging, Marker), new JsonObject
{
["colors"] = choice.ToJson(), ["ootrr"] = Ootrr.Version, ["made"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
}.ToJsonString(opts), token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
// (in place: the old one goes aside first, the new one moves in, the old one goes; a switched-off one stays off)
var old = Applied(game);
var dest = old is { On: false } o ? o.Path : Path.Combine(mods, ModFolder);
string? aside = null;
if (old != null)
{
aside = Path.Combine(mods, ".colors-old-" + Guid.NewGuid().ToString("N")[..8]);
Directory.Move(old.Value.Path, aside);
}
try { Directory.Move(staging, dest); }
catch
{
if (aside != null) try { Directory.Move(aside, old!.Value.Path); aside = null; } catch (Exception) { }
throw;
}
if (aside != null) try { Directory.Delete(aside, true); } catch (Exception e) { ctx.Log.Write("character: the old colours' folder stays: " + e.Message); }
ctx.Log.Write("character: colours applied in " + dest);
SetLinkle(game, linkleMod, linkle);
return dest;
}
finally
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch (Exception) { }
try { Directory.Delete(work, true); } catch (Exception) { }
}
}
/// <summary>Linkle's mod on (she is played) or off (Link is).</summary>
void SetLinkle(string game, Mod? mod, bool on)
{
if (mod == null || mod.On == on) return;
Mods.SetOn(Triforce.Logic.Mods.FolderOf(game), mod, on);
ctx.Log.Write("character: Linkle " + (on ? "on" : "off"));
}
/// <summary>Takes the colours' mod away: the game has its own colours again.</summary>
public void Remove(string game)
{
if (Mods.GameRuns(game)) throw new OotrrException("Close the game first: it reads its files when it starts.");
var old = Applied(game);
if (old == null) return;
ctx.Require(old.Value.Path);
Directory.Delete(old.Value.Path, true);
ctx.Log.Write("character: colours taken away (" + old.Value.Path + ")");
}
/// <summary>Takes away what a stopped apply left in the mods folder (.colors-*: never a folder the game reads).</summary>
public void LeftOvers(string game)
{
var mods = Triforce.Logic.Mods.FolderOf(game);
if (!ctx.Allowed(mods) || !Directory.Exists(mods)) return;
foreach (var d in Directory.GetDirectories(mods, ".colors-*"))
try { Directory.Delete(d, true); } catch (Exception) { }
}
/// <summary>A .zs file with one name changed to another of the same length (every place it is written), packed again with
/// the game's dictionary for that file.</summary>
static byte[] Rename(Zs zs, string romfsPath, byte[] packed, string from, string to)
{
if (from.Length != to.Length) throw new ArgumentException("names of different lengths");
var data = zs.Unpack(romfsPath, packed);
byte[] f = Encoding.ASCII.GetBytes(from), t = Encoding.ASCII.GetBytes(to);
var n = 0;
for (var i = data.AsSpan().IndexOf(f); i >= 0;)
{
t.CopyTo(data, i); n++;
var next = data.AsSpan(i + f.Length).IndexOf(f);
i = next < 0 ? -1 : i + f.Length + next;
}
if (n == 0) return packed;
zs.Dictionaries.TryGetValue(Zs.DictionaryFor(romfsPath), out var dict);
using var c = new Compressor(9);
if (dict != null) c.LoadDictionary(dict);
return c.Wrap(data).ToArray();
}
}

View File

@@ -0,0 +1,167 @@
// (Triforce, 11-29) Linkle on the Character page: "Playable Linkle - Total Conversion" by ThatGuyOnCops
// (https://gamebanana.com/mods/746375), a mod the launcher downloads from its GameBanana page on the player's word and
// installs into the mods folder like any other (its license allows downloading and installing it; nothing of it ships with
// Triforce). Choosing Link or Linkle switches that mod off or on.
//
// Her colours: the randomizer's colour tool cannot read her textures (some are uncompressed, the rest it does not edit), so
// the launcher dyes them itself (Core TextureRecolor: the same colour-band rule). Each part names the textures it dyes and the
// band of each; a texture she shares with the game's other characters is dyed as a copy of her own (a name of the same length,
// her model pointed at it). Adult hair is the game's own BC7 texture, which the colour tool does dye (LinkColors).
using System.Text;
using Triforce.Core.GameFiles;
using ZstdSharp;
namespace Triforce.Logic;
/// <summary>A texture a part dyes: its name, the band of the part on it, and the name of her own copy when the texture is shared
/// (the copy is written under that name and Model is pointed at it).</summary>
public sealed record LinklePiece(string Texture, ColorBand Band, string? Copy = null, string? Model = null);
public static class Linkle
{
public const int GameBananaId = 746375;
public const string Name = "Playable Linkle - Total Conversion";
public const string Author = "ThatGuyOnCops";
public const string Page = "https://gamebanana.com/mods/746375";
/// <summary>A file only this mod has (young Linkle's model), as the Mods list keeps file names.</summary>
public const string Signature = "model/npc_kokiri_wc_002.player_linkle_child.bfres.zs";
const string ChildModel = "Model/Npc_Kokiri_WC_002.Player_Linkle_Child.bfres.zs";
const string AdultModel = "Model/Player_Adult.Player_Adult.bfres.zs";
/// <summary>Her parts (ids as Link's where they mean the same, so a look can dress either).</summary>
public static readonly LinkPart[] Parts =
{
new("kokiri", "Outfit", "Outfit", "child", "", "#4f7d2f"),
new("kokiri", "Tunic and hood", "Outfit", "adult", "kokiri", "#3f8a2c"),
new("skirt", "Skirt (every outfit)", "Outfit", "adult", "", "#c8641e"),
new("kokiri_shirt", "Shirt and sleeves", "Outfit", "adult", "kokiri", "#d8d1bd"),
new("goron", "Goron Tunic", "Outfit", "adult", "goron", "#b3262c"),
new("zora", "Zora Tunic", "Outfit", "adult", "zora", "#2a4fb0"),
new("flowers", "Flowers", "Outfit", "child", "", "#e0b84a"),
new("shoes", "Shoes", "Leather", "child", "", "#8a7a3a"),
new("kokiri_belt", "Belts and straps", "Leather", "adult", "", "#5b3f26"),
new("boots", "Boots", "Leather", "adult", "", "#5b3f26"),
new("gloves", "Gloves", "Leather", "adult", "", "#7a5534"),
new("hair", "Hair", "Hair", "child,adult", "", "#e0b84a"),
new("navi", "Liri", "Navi", "child,adult", "", "#d8e070"),
};
static readonly ColorBand Green = new(70, 130, 0.15f);
/// <summary>Her adult outfit sheets (Kokiri, Goron and Zora tunics share one layout): face and hair at the top left, the
/// cape at the top right, the vest in the middle left, the shirt in the middle, the hood at the bottom left, the skirt panel
/// below the shirt. The tunic is the vest, cape and hood; the skirt its panel.</summary>
static readonly float[][] TunicRects = { new[] { 0f, .24f, .47f, .55f }, new[] { .62f, 0f, .97f, .25f }, new[] { 0f, .55f, .29f, .88f }, new[] { .29f, .55f, .50f, .80f } };
static readonly float[][] SkirtRects = { new[] { .48f, .55f, .85f, .68f } };
static readonly float[][] ShirtRects = { new[] { .46f, .25f, .68f, .55f }, new[] { .68f, .35f, .85f, .55f } };
static readonly ColorBand Brown = new(8, 42, 0.18f, 0.04f, 0.6f);
/// <summary>(age, part) to the textures it dyes.</summary>
public static readonly Dictionary<(string Age, string Part), LinklePiece[]> Pieces = new()
{
[("child", "kokiri")] = new[] { new LinklePiece("CmnTex_Chara_Mt_Cloth_Npc_Kokiri_WC_001_Alb.01", Green, "CmnTex_Chara_Mt_Cloth_Npc_Kokiri_WC_001_Alb.09", ChildModel) },
[("child", "flowers")] = new[] { new LinklePiece("Mt_PantsParts_Player_Child_Alb", new ColorBand(28, 62, 0.25f)) },
[("child", "shoes")] = new[] { new LinklePiece("CmnTex_Chara_Mt_Shoes_Npc_Kokiri_WC_001_Alb.03", ColorBand.All, "CmnTex_Chara_Mt_Shoes_Npc_Kokiri_WC_001_Alb.08", ChildModel) },
[("child", "hair")] = new[] { new LinklePiece("Mt_Cloth_Parts_Player_Child_Alb", new ColorBand(30, 62, 0.15f)) },
[("adult", "kokiri")] = new[]
{
new LinklePiece("Mt_Vest_Player_Adult_Alb", Green with { Rects = TunicRects }),
new LinklePiece("Angin_Tile_A_Alb", ColorBand.All, "Angin_Tile_K_Alb", AdultModel),
},
// (the skirt panel in every outfit's sheet: she wears it with each tunic)
[("adult", "skirt")] = new[]
{
new LinklePiece("Mt_Vest_Player_Adult_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }),
new LinklePiece("Mt_Vest_Armor_Adult_Goron_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }),
new LinklePiece("Mt_Angin_Armor_Adult_Zora_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }),
},
// (her shirt and sleeves: the white panel of the Kokiri outfit's own sheet; the game's Mt_Inner she wears is not it)
[("adult", "kokiri_shirt")] = new[] { new LinklePiece("Mt_Vest_Player_Adult_Alb", new ColorBand(0, 360, 0, 0.1f) { Rects = ShirtRects }) },
[("adult", "goron")] = new[] { new LinklePiece("Mt_Vest_Armor_Adult_Goron_Alb", new ColorBand(335, 22, 0.3f) { Rects = TunicRects }) },
[("adult", "zora")] = new[] { new LinklePiece("Mt_Angin_Armor_Adult_Zora_Alb", new ColorBand(185, 250, 0.15f) { Rects = TunicRects }) },
[("adult", "kokiri_belt")] = new[] { new LinklePiece("Mt_Leater_Upper_Player_Adult_Alb", new ColorBand(20, 50, 0.2f, 0.04f, 0.45f)) },
[("adult", "boots")] = new[] { new LinklePiece("Mt_Boots_Player_Adult_Alb", Brown) },
[("adult", "gloves")] = new[] { new LinklePiece("Mt_Glove_Player_Adult_Alb", Brown) },
[("child", "navi")] = new[] { new LinklePiece("Npc_Liri_Wings_Alb.00", new ColorBand(48, 88, 0.12f)) },
[("adult", "navi")] = new[] { new LinklePiece("Npc_Liri_Wings_Alb.00", new ColorBand(48, 88, 0.12f)) },
// (adult hair: the game's own Mt_Hairs_Player_Adult_Alb, dyed by the colour tool: LinkColors)
};
/// <summary>Her copies: the copy's name to (the model that points at it, the texture it is a copy of).</summary>
public static readonly Dictionary<string, (string Model, string Original)> Copies = Pieces.Values.SelectMany(v => v)
.Where(p => p.Copy != null && p.Model != null).DistinctBy(p => p.Copy).ToDictionary(p => p.Copy!, p => (p.Model!, p.Texture), StringComparer.Ordinal);
/// <summary>For the preview's scene: per model, the texture names her models will point at once dyed (original to copy).</summary>
public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> SceneRenames { get; } = Copies
.GroupBy(kv => kv.Value.Model).ToDictionary(g => g.Key, g => (IReadOnlyDictionary<string, string>)g.ToDictionary(kv => kv.Value.Original, kv => kv.Key, StringComparer.Ordinal), StringComparer.Ordinal);
/// <summary>The texture to read for a name (a copy reads its original).</summary>
public static string Original(string name) => Copies.TryGetValue(name, out var c) ? c.Original : name;
/// <summary>The Linkle mod in this game's mods folder (on or off), or null.</summary>
public static Mod? Find(ModManager mods, string game)
{
try
{
return mods.ListGame(game, true).FirstOrDefault(m => m.Info?.GameBananaId == GameBananaId || m.Files.Contains(Signature));
}
catch (Exception) { return null; }
}
/// <summary>Her files over the game's: what the game shows when the mod is on.</summary>
public static OverlaySource Source(Mod mod, string game) =>
new(new FolderSource(Path.Combine(mod.Path, "romfs")), new FolderSource(Path.Combine(game, "romfs")));
/// <summary>Her textures dyed for one age's colours: texture name (as her models name it) to (the name it is written under,
/// the dyed BNTX, its level 0 for the preview). A texture none of the colours touch is left out.</summary>
public static Dictionary<string, (string WriteName, byte[] Bntx, (int W, int H, byte[] Rgba) Preview)> Dye(IGameSource src, Zs zs, string age, IReadOnlyDictionary<string, string> colors)
{
var byTex = new Dictionary<string, (LinklePiece Piece, List<(ColorBand, string)> Bands)>(StringComparer.Ordinal);
foreach (var (part, hex) in colors)
{
if (!Pieces.TryGetValue((age, part), out var pieces)) continue;
foreach (var p in pieces)
{
if (!byTex.TryGetValue(p.Texture, out var e)) byTex[p.Texture] = e = (p, new List<(ColorBand, string)>());
e.Bands.Add((p.Band, hex));
}
}
var outp = new Dictionary<string, (string, byte[], (int, int, byte[]))>(StringComparer.Ordinal);
foreach (var (tex, (piece, bands)) in byTex)
{
var path = "Tex/" + tex + ".bntx.zs";
if (!src.Exists(path)) continue;
try
{
var (bntx, prev, _) = TextureRecolor.Recolor(zs.Unpack(path), tex, bands, piece.Copy);
outp[piece.Copy ?? tex] = (piece.Copy ?? tex, bntx, prev);
}
catch (NotSupportedException) { }
}
return outp;
}
/// <summary>Her models pointed at her copies (only for the copies written): model path to its new packed bytes.</summary>
public static Dictionary<string, byte[]> PatchModels(IGameSource src, Zs zs, IEnumerable<LinklePiece> written)
{
var outp = new Dictionary<string, byte[]>(StringComparer.Ordinal);
foreach (var g in written.Where(p => p.Copy != null && p.Model != null).GroupBy(p => p.Model!))
{
if (!src.Exists(g.Key)) continue;
var data = zs.Unpack(g.Key);
var n = 0;
foreach (var p in g.DistinctBy(p => p.Texture)) n += TextureRecolor.ReplaceAll(data, p.Texture, p.Copy!);
if (n > 0) outp[g.Key] = Pack(zs, g.Key, data);
}
return outp;
}
/// <summary>A romfs file packed again with the game's dictionary for it.</summary>
public static byte[] Pack(Zs zs, string romfsPath, byte[] data)
{
zs.Dictionaries.TryGetValue(Zs.DictionaryFor(romfsPath), out var dict);
using var c = new Compressor(9);
if (dict != null) c.LoadDictionary(dict);
return c.Wrap(data).ToArray();
}
}

View File

@@ -776,6 +776,8 @@ public static class GameOptionsSchema
PadSound("Fishing"), PadSound("Bottles"),
Row(GameOptionTab.System, "Saves & reports", "Autosave", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true,
"Whether the game saves by itself as you go from one area to another. Off skips those saves; saving from the pause menu still works."),
Row(GameOptionTab.System, "NFC", "Unlimited amiibo uses", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,
"Off: each figure gives its reward once a day, as in the game. On: a figure can be scanned again at once, any number of times, and gives its reward each time (choose it again under NFC tag for each scan). Your dumps are not changed."),
Row(GameOptionTab.System, "Online", "Discord status", 0, 1, 1, 1, GameOptionKind.Choice, TxOnoff, false, true,
"Shows \"Playing Triforce\" and the time played in your Discord status, while Discord runs on this PC."),
Row(GameOptionTab.Controls, "Controller", "Controller in background", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, false,

View File

@@ -229,8 +229,10 @@ public sealed class ModManager
// ---- on and off ----
/// <summary>Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns its folder now.</summary>
public string SetOn(string mods, Mod mod, bool on)
/// <summary>Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns its folder now.
/// onName: switched on, the folder takes this name in place of its own without the switch (the Randomizer's seeds, which
/// must sort after the other mods: Randomizer.OnName).</summary>
public string SetOn(string mods, Mod mod, bool on, string? onName = null)
{
Refuse(mods);
if (!Directory.Exists(mod.Path)) throw new ModsException(mod.Name + " is no longer in the mods folder.");
@@ -238,7 +240,9 @@ public sealed class ModManager
if (on && mod.OffAbove != null)
throw new ModsException(mod.Name + " is inside the folder " + mod.OffAbove + ", whose name switches off everything in it. Take the - or _ off that folder's name.");
if (on == !off) return mod.Path;
var name = on ? mod.Folder.TrimStart('-', '_') : "-" + mod.Folder;
// (an onName that would be off, or is no plain folder name, is not taken)
var own = onName is { Length: > 0 } n && n[0] != '-' && n[0] != '_' && n.IndexOfAny(new[] { '/', '\\' }) < 0 ? n : null;
var name = on ? own ?? mod.Folder.TrimStart('-', '_') : "-" + mod.Folder;
if (name.Length == 0 || name[0] == '.') throw new ModsException("Without the " + mod.Folder[0] + " in front, the folder " + mod.Folder + " has no name the game looks at. Rename it by hand.");
var target = Path.Combine(Path.GetDirectoryName(mod.Path)!, name);
if (Directory.Exists(target) || File.Exists(target))

View File

@@ -4,6 +4,11 @@
// <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
// ((Triforce, 11-30) The folder is "~Randomizer <seed>": the ~ sorts the seed after every other mod (host/mods.c: of two mods
// that carry a file, the one whose name sorts last wins it). A seed's event tables (RSDB EventSetting, GameAnalyzedEventInfo)
// register the events its chests, boss keys and Epona run; a mod that carried its own copies and sorted after "Randomizer" took
// them over, and the seed's chests did not open and its boss warp did nothing (ticket 1576351134820470917, "Song of Time Age
// Swap"). A seed made before is "Randomizer <seed>": Use gives it the ~ when it switches it on.)
// 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;
@@ -45,6 +50,9 @@ public sealed class Randomizer
public const string Marker = "triforce_rando.json";
public const string FilesFolder = "ootrr";
public const string Prefix = "Randomizer ";
/// <summary>In front of a seed's folder: it sorts after every other mod's (~ comes after the letters and digits, as the game
/// compares names).</summary>
public const string Last = "~";
readonly TriforceContext ctx;
public Ootrr Tool { get; }
@@ -189,10 +197,19 @@ public sealed class Randomizer
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;
var name = Last + Prefix + clean;
return name.Length <= 60 ? name : name.Substring(0, 60).TrimEnd(' ', '-');
}
/// <summary>The name a seed's folder takes when it is switched on: a seed made before 11-30 ("Randomizer &lt;seed&gt;", which
/// another mod could sort after) gets the ~ in front; null for one that keeps its name (one that has it, or one numbered on
/// the Mods page: that order is the player's).</summary>
public static string? OnName(string folder)
{
var (_, number, name) = Mods.Parse(folder);
return number == null && name.StartsWith(Prefix, StringComparison.Ordinal) ? Last + name : null;
}
/// <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)
{
@@ -367,7 +384,7 @@ public sealed class Randomizer
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);
return now.Mod.On ? now.Mod.Path : Manager.SetOn(mods, now.Mod, true, OnName(now.Mod.Folder));
}
/// <summary>Switches every seed off: the game is the plain game again.</summary>

View File

@@ -21,6 +21,11 @@
<InternalsVisibleTo Include="Triforce.LogicTests" />
</ItemGroup>
<!-- (11-29) the game's files (Core): the Character page's colours read and repack a few of them -->
<ItemGroup>
<ProjectReference Include="..\Core\Triforce.Core.csproj" />
</ItemGroup>
<!-- BuildInfo.Version as a const, written from TriforceVersion before each compile -->
<Target Name="TriforceVersionFile" BeforeTargets="CoreCompile">
<PropertyGroup>

View File

@@ -256,7 +256,8 @@ static partial class Tests
Equal("Evil HD,This PC,Upscaling,Anti-aliasing,N64 Classic,Frame generation,Frame rate & latency,Textures,Post-processing,Detail,Advanced", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Graphics)), "Graphics' sections");
Equal("Controller,Mouse & keyboard,Rumble,Gameplay,Motion,Hold to toggle,Controls", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Controls)), "Controls' sections");
Equal("Sound,Microphone,Controller speaker", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Audio)), "Audio's sections");
Equal("Achievements,Game,Saves & reports,Online", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.System)), "System's sections (with rows)");
// ((Triforce) NFC: its Unlimited amiibo uses row; the NFC tag row before it opens a page, not a value)
Equal("Achievements,Game,Saves & reports,NFC,Online", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.System)), "System's sections (with rows)");
string L(string key, int v) => GameOptionsSchema.Get(key).Label(v);
string Cs(string key) => string.Join("|", GameOptionsSchema.Get(key).Choices.Select(c => c.Value + "=" + c.Label));

View File

@@ -195,10 +195,10 @@ static partial class Tests
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");
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");
@@ -310,7 +310,7 @@ static partial class Tests
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!");
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");
@@ -333,27 +333,56 @@ static partial class Tests
// (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");
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");
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");
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"));
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)
// (another mod that is on and carries one of the seed's files: the seed sorts after it and wins, unnumbered names after
// "Randomizer" included (11-30, ticket 1576351134820470917: "Song of Time Age Swap" took the seed's event tables, its
// chests stayed shut)
r.Use(game, r.Seeds(game).Single());
var other = Path.Combine(game, "mods", "Tall grass", "romfs", "Event", "EventFlow");
var other = Path.Combine(game, "mods", "Song of Time Age Swap", "romfs", "RSDB");
Directory.CreateDirectory(other);
File.WriteAllText(Path.Combine(other, "Dm_Kokiri_0000.bfevfl.zs"), "other");
File.WriteAllText(Path.Combine(other, "EventSetting.Product.111.rstbl.byml.zs"), "other");
var seedRsdb = Path.Combine(r.Seeds(game).Single().Mod.Path, "romfs", "RSDB");
Directory.CreateDirectory(seedRsdb);
File.WriteAllText(Path.Combine(seedRsdb, "EventSetting.Product.111.rstbl.byml.zs"), "seed's");
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");
Check(shared.Count == 1 && shared[0].Name == "Song of Time Age Swap" && !shared[0].Wins, "the seed wins its event table: " + string.Join(";", shared));
Equal("seed's", File.ReadAllText(r.Manager.RomfsFile(game, "RSDB/EventSetting.Product.111.rstbl.byml.zs")!), "the file the game takes is the seed's");
// (a mod whose name sorts after ~ still can: that is said)
var after = Path.Combine(game, "mods", "Über grass", "romfs", "Event", "EventFlow");
Directory.CreateDirectory(after);
File.WriteAllText(Path.Combine(after, "Dm_Kokiri_0000.bfevfl.zs"), "other");
shared = r.Shared(game, r.Seeds(game).Single().Mod.Rel);
Check(shared.Any(x => x.Name == "Über grass" && x.Wins), "the other mod that wins a file");
Directory.Delete(Path.Combine(game, "mods", "Über grass"), true);
Directory.Delete(Path.Combine(game, "mods", "Song of Time Age Swap"), true);
// (a seed made before 11-30, "Randomizer <seed>": switched on, it gets the ~; one numbered on the Mods page keeps its place)
Equal("~Randomizer Old", Randomizer.OnName("-Randomizer Old"), "an old seed's folder");
Equal(null, Randomizer.OnName("-~Randomizer New"), "a new one keeps its name");
Equal(null, Randomizer.OnName("-04-Randomizer Ordered"), "a numbered one keeps its name");
Equal(null, Randomizer.OnName("-Tall grass"), "not a seed's name");
var oldSeed = Path.Combine(game, "mods", "-Randomizer Old");
Directory.CreateDirectory(Path.Combine(oldSeed, "romfs", "Event"));
File.WriteAllText(Path.Combine(oldSeed, "romfs", "Event", "x.zs"), "old");
File.WriteAllText(Path.Combine(oldSeed, Randomizer.Marker), "{\"seed\":\"Old\"}");
var onOld = r.Use(game, r.Seeds(game).Single(x => x.Seed == "Old"));
Equal(Path.Combine(game, "mods", "~Randomizer Old"), onOld, "the old seed switched on under the ~ name");
Check(r.Seeds(game).Single(x => x.Mod.On).Seed == "Old", "and it is the one on");
r.Use(game, r.Seeds(game).Single(x => x.Seed != "Old"));
r.Remove(game, r.Seeds(game).Single(x => x.Seed == "Old"));
// (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);
@@ -361,7 +390,7 @@ static partial class Tests
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");
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");
@@ -399,12 +428,12 @@ static partial class Tests
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");
Check(!Directory.Exists(Path.Combine(game, "mods", Randomizer.FolderName("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.Exists(Path.Combine(game, "mods", Randomizer.FolderName("slow"))) && !Directory.Exists(Path.Combine(game, "mods", "-" + Randomizer.FolderName("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");
@@ -412,7 +441,7 @@ static partial class Tests
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);
Check(room.Message.Length > 0 && !Directory.Exists(Path.Combine(game, "mods", Randomizer.FolderName("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();

View File

@@ -235,9 +235,9 @@ document.addEventListener('pointerdown', e => {
});
/* ---------------- screens ---------------- */
const MAIN = ['home', 'mods', 'rando', 'saves', 'settings'];
const MAIN = ['home', 'mods', 'rando', 'char', 'saves', 'settings'];
const FIRST_RUN = ['welcome', 'reveal', 'done'];
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 };
const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', rando: 'fairy', char: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };
let screen = null;
function go(name) {
if (name === screen || !$('#s-' + name)) return;
@@ -256,6 +256,7 @@ function go(name) {
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');
if (typeof charShown === 'function') charShown(name); // (the Character page: char.js)
cmd('screen', { s: name });
}
function afterOneShot(name) { if (name === 'itemget' && (MUSIC[screen] === 'fairy' || screen === 'done')) music('fairy'); }
@@ -884,6 +885,7 @@ onHost(m => {
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.char && typeof drawChar === 'function') drawChar();
if (m.done) { $('#doneEb').textContent = S.done.eb || ''; $('#doneLead').textContent = S.done.lead || ''; }
break;
}
@@ -896,6 +898,7 @@ onHost(m => {
case 'choice': openChoice(m); break;
case 'ask': openAsk(m); break;
case 'bench': onBench(m); break;
case 'charLook': case 'charExact': case 'charCal': if (typeof charMessage === 'function') charMessage(m); break;
case 'copy': navigator.clipboard && navigator.clipboard.writeText(m.text).then(() => toast('Copied'), () => toast('Could not copy')); break;
}
});
@@ -906,7 +909,7 @@ document.addEventListener('keydown', e => {
if (document.activeElement && document.activeElement.tagName === 'INPUT' && !['Escape', 'Enter', 'ArrowDown', 'ArrowUp', 'Tab'].includes(e.key)) return;
const k = e.key; let used = true;
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)
if (ca && (colorNudge(ca[0], ca[1]) || (typeof charNudge === 'function' && charNudge(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 || 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);
@@ -927,10 +930,11 @@ function pad(t) {
const gp = [...(navigator.getGamepads ? navigator.getGamepads() : [])].find(g => g && g.connected); if (!gp) return;
const B = i => gp.buttons[i] && gp.buttons[i].pressed;
const edge = (i, fn) => { const p = B(i); if (p && !held[i]) { document.body.classList.add('kb'); unlocked = true; fn(); } held[i] = p; };
const slide = d => { if (colorNudge(d, 0)) return true; if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); };
const slide = d => { if (colorNudge(d, 0) || (typeof charNudge === 'function' && charNudge(d, 0))) return true; if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); };
edge(0, () => activate(focused)); edge(1, back); edge(4, () => tab(-1)); edge(5, () => tab(1));
edge(3, toggleMute); edge(9, () => { if (MAIN.includes(screen)) go('settings'); });
edge(12, () => colorNudge(0, 1) || move(0, -1)); edge(13, () => colorNudge(0, -1) || move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0));
const cn = (dx, dy) => colorNudge(dx, dy) || (typeof charNudge === 'function' && charNudge(dx, dy));
edge(12, () => cn(0, 1) || move(0, -1)); edge(13, () => cn(0, -1) || move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0));
const x = gp.axes[0] || 0, y = gp.axes[1] || 0, dir = Math.abs(x) > .55 ? (x > 0 ? 'r' : 'l') : Math.abs(y) > .55 ? (y > 0 ? 'd' : 'u') : '';
if (dir && (dir !== stickDir || t - stickAt > 220)) {
document.body.classList.add('kb'); stickAt = t + (dir !== stickDir ? 160 : 0);

101
launcher/ui/char.css Normal file
View File

@@ -0,0 +1,101 @@
/* ((Triforce, 11-29) The Character page: Link on a lit stage at the left, his colors in a panel at the right. On top of
ui.css, theme.css, v3.css, proto.css and app.css (the picker reuses app.css's .cp-sv / .cp-hue / .cp-f). */
#s-char { background:
radial-gradient(520px 600px at 360px 520px, rgba(var(--gold-warm-rgb), .16) 0%, rgba(var(--gold-warm-rgb), .05) 38%, rgba(0, 0, 0, 0) 70%),
radial-gradient(900px 760px at 360px 420px, #1d1710 0%, #110e0a 52%, var(--ink) 82%); }
/* the stage: Link's canvas, under the title; a soft light from above behind him */
.chstage { position: absolute; left: 170px; top: 44px; width: 590px; height: 756px; }
.chstage canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none;
-webkit-mask: linear-gradient(90deg, transparent 0, #000 9%, #000 91%, transparent 100%); mask: linear-gradient(90deg, transparent 0, #000 9%, #000 91%, transparent 100%); }
.chstage canvas.grab { cursor: grabbing; }
.chglow { position: absolute; left: 125px; top: 0; width: 340px; height: 520px; pointer-events: none;
background: radial-gradient(closest-side, rgba(var(--gold-lit-rgb), .07), rgba(var(--gold-lit-rgb), 0)); mix-blend-mode: screen; }
.chhead { position: absolute; left: 64px; top: 96px; z-index: 2; pointer-events: none; }
.chhead > * { pointer-events: auto; }
.chhead .cont h1 { text-shadow: 0 2px 18px rgba(0, 0, 0, .75); }
/* young / adult: two halves of one gold-edged bar */
.chseg { display: inline-flex; margin-top: 18px; border: 1px solid rgba(var(--gold-rgb), .45); background: rgba(10, 9, 8, .55); }
.chseg span { padding: 9px 20px; font-size: 15px; font-weight: 600; color: var(--text2); cursor: pointer; transition: background .15s, color .15s; }
.chseg span + span { border-left: 1px solid rgba(var(--gold-rgb), .3); }
.chseg span.on { color: var(--gold-ink2); background: linear-gradient(180deg, rgb(var(--gold-bar-hi-rgb)), rgb(var(--gold-bar-rgb)) 55%, rgb(var(--gold-bar-low-rgb))); }
.chseg span:not(.on):hover { color: var(--gold-hi); }
/* the adult's tunic: three small diamonds-and-words under it */
.chtunic { display: flex; gap: 20px; margin-top: 14px; font-size: 14px; color: var(--text3); }
.chtunic span { position: relative; padding: 4px 0 6px 18px; cursor: pointer; }
.chtunic span::before { content: ''; position: absolute; left: 1px; top: 10px; width: 8px; height: 8px; transform: rotate(45deg); border: 1px solid rgba(var(--gold-rgb), .55); }
.chtunic span:nth-child(1)::before { background: #2f8f3a; } .chtunic span:nth-child(2)::before { background: #b3262c; } .chtunic span:nth-child(3)::before { background: #2a4fb0; }
.chtunic span.on { color: var(--gold-hi); font-weight: 600; box-shadow: inset 0 -2px 0 var(--gold); }
.chtunic span:not(.on):hover { color: var(--text); }
/* under the stage: turn him, look at his face */
.chview { position: absolute; left: 64px; bottom: 30px; display: flex; align-items: center; gap: 18px; font-size: 14px; z-index: 2; }
.chview .lnk { color: var(--gold); font-weight: 600; cursor: pointer; padding: 4px 2px; }
.chview #chTurnL, .chview #chTurnR { font-size: 12px; }
.chview em { font-style: normal; color: var(--text3); font-size: 13px; margin-left: 6px; }
.chwait { position: absolute; left: 170px; top: 330px; width: 590px; display: none; flex-direction: column; align-items: center; gap: 16px; color: var(--text2); font-size: 15px; pointer-events: none; }
.chwait.on { display: flex; }
.chwait.err .chspin { display: none; }
.chwait.err span { max-width: 420px; text-align: center; color: var(--text3); }
.chspin { width: 30px; height: 30px; transform: rotate(45deg); border: 2px solid rgba(var(--gold-rgb), .25); border-top-color: var(--gold-hi); animation: chspin 1.1s linear infinite; }
.chspin.sm { display: inline-block; width: 11px; height: 11px; margin: 0 10px -1px 0; border-width: 1.5px; vertical-align: 0; }
@keyframes chspin { to { transform: rotate(405deg); } }
/* the panel */
.chpanel { position: absolute; right: 48px; top: 96px; bottom: 26px; width: 468px; display: flex; flex-direction: column; padding: 22px 26px 20px; }
.chtop { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
.chtop h3 { font-family: 'Cormorant Garamond', Georgia, serif; font-weight: 700; font-size: 27px; color: var(--text); }
.chstate { font-size: 13px; color: var(--text3); white-space: nowrap; }
.chlooks { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0 6px; }
.chlooks span { padding: 5px 12px; font-size: 13px; font-weight: 600; color: var(--text2); border: 1px solid rgba(var(--gold-rgb), .28); background: rgba(243, 234, 213, .04); cursor: pointer; transition: border-color .15s, color .15s; }
.chlooks span:hover { border-color: rgba(var(--gold-rgb), .7); color: var(--text); }
.chlooks span.on { border-color: var(--gold-hi); color: var(--gold-hi); background: rgba(var(--gold-rgb), .1); }
.chlist { flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; margin: 6px -12px 0 0; padding: 0 12px 8px 0; scrollbar-width: thin; scrollbar-color: rgba(var(--gold-rgb), .45) transparent; }
.chlist::-webkit-scrollbar { width: 6px; } .chlist::-webkit-scrollbar-track { background: transparent; }
.chlist::-webkit-scrollbar-thumb { background: rgba(var(--gold-rgb), .38); } .chlist::-webkit-scrollbar-thumb:hover { background: rgba(var(--gold-rgb), .6); }
.chlist h4 { margin: 14px 0 2px; font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-weight: 600; font-size: 17px; color: var(--gold-hi); }
.chrow { display: grid; grid-template-columns: 30px 1fr auto 56px; align-items: center; gap: 12px; padding: 11px 2px; border-bottom: 1px solid var(--line-soft); font-size: 15px; cursor: pointer; }
.chrow b { font-weight: 600; } .chrow > span { color: var(--text2); font-size: 13.5px; font-variant-numeric: tabular-nums; letter-spacing: .02em; }
.chrow > span u { display: inline-block; width: 6px; height: 6px; margin-left: 8px; transform: rotate(45deg) translateY(-2px); background: var(--gold-hi); text-decoration: none; }
.chrow em { font-style: normal; color: var(--gold); font-weight: 600; font-size: 14px; text-align: right; }
.chrow.open { border-bottom-color: transparent; } .chrow.open em { color: var(--gold-hi); }
.chrow:hover b { color: var(--gold-hi); }
.chsw { width: 18px; height: 18px; margin-left: 5px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 1px rgba(243, 234, 213, .35), 0 0 0 3px rgba(10, 9, 8, .9); }
.chsw.orig { box-shadow: 0 0 0 1px rgba(243, 234, 213, .18), 0 0 0 3px rgba(10, 9, 8, .9); opacity: .78; }
.chnote { margin-top: 14px !important; }
/* the picker under the open row */
.chpick { display: grid; grid-template-columns: 188px 1fr; gap: 22px; min-width: 0; padding: 8px 2px 18px; border-bottom: 1px solid var(--line-soft); animation: chopen .2s ease; }
@keyframes chopen { from { opacity: 0; transform: translateY(-4px); } }
.chsv { height: 118px; }
.chhue { margin-top: 24px; }
.chpk-r { min-width: 0; }
.chpick label { display: block; font-family: Commissioner, sans-serif; font-style: normal; font-weight: 600; font-size: 13px; color: var(--text3); }
.chpk-r .cp-f input#chHex { width: 112px; font-family: Commissioner, sans-serif; font-style: normal; letter-spacing: .03em; text-transform: uppercase; display: block; height: 36px; margin-top: 5px; padding: 0 12px; font: inherit; font-size: 14.5px; color: var(--text);
background: rgba(243, 234, 213, .05); border: 1px solid rgba(var(--gold-rgb), .35); outline: none; }
.chpk-r .cp-f input#chHex:focus { border-color: var(--gold-hi); } .chpk-r .cp-f input#chHex.bad { border-color: #ff8a92; color: #ffd6d9; }
.chpre { display: grid; grid-template-columns: repeat(8, 14px); gap: 12px 10px; margin: 16px 0 0 4px; }
.chpre span { width: 13px; height: 13px; transform: rotate(45deg); background: var(--c); box-shadow: 0 0 0 1px rgba(243, 234, 213, .25), 0 0 0 3px rgba(10, 9, 8, .9); cursor: pointer; }
.chpre span.on { box-shadow: 0 0 0 2px var(--text), 0 0 0 4px rgba(10, 9, 8, .9); }
.chpk-r .cp-foot { margin-top: 14px; gap: 10px; } .chpk-r .cp-foot .lnk { white-space: nowrap; }
/* the foot: where the picks stand, and Apply */
.chfoot { padding-top: 14px; border-top: 1px solid rgba(var(--gold-rgb), .25); }
.chmsg { font-size: 13.5px; color: var(--text2); line-height: 1.45; }
.chmsg.pend { color: var(--gold-hi); }
.chmsg.warn { color: var(--text3); font-size: 12.5px; margin-top: 4px; }
.chbtns { display: flex; align-items: center; justify-content: flex-end; gap: 22px; margin-top: 12px; }
.chbtns .lnk { color: var(--gold); font-weight: 600; font-size: 14px; cursor: pointer; }
.chbtns .play.sm { width: 230px; height: 50px; font-size: 21px; margin: 0; }
.chbtns .play.off { filter: saturate(.25) brightness(.6); cursor: default; }
.chbar { height: 3px; margin-top: 10px; background: rgba(var(--gold-rgb), .15); } .chbar i { display: block; height: 100%; background: var(--gold-hi); }
.chdye { display: none; color: var(--gold-hi); font-size: 13px; font-weight: 600; margin-left: 8px; } .chdye.on { display: inline-flex; align-items: center; }
/* Link or Linkle: above the ages, the same bar a little smaller */
.chhero { display: flex; width: max-content; margin-top: 16px; } .chhero span { padding: 7px 18px; font-size: 14px; }
.chhero + .chseg { margin-top: 10px; }
/* Linkle not downloaded yet: her card on the stage */
.chget { position: absolute; left: 230px; top: 300px; width: 470px; padding: 24px 28px; display: none; z-index: 3; }
.chget.on { display: block; }
.chget h3 { font-family: 'Cormorant Garamond', Georgia, serif; font-weight: 700; font-size: 27px; }
.chget p { margin-top: 8px; font-size: 14px; line-height: 1.5; color: var(--text2); }
.chget .chbtns { margin-top: 16px; }

353
launcher/ui/char.js Normal file
View File

@@ -0,0 +1,353 @@
/* ((Triforce, 11-29) The Character page: Link in 3D (char3d.js) from the player's own game, young or adult (Kokiri, Goron or
Zora tunic), and his colors (launcher/App/Backend.Character.cs, launcher/Logic/Character/LinkColors.cs). The launcher sends
state.char: game, tool {have, busy, frac, size}, parts [{id, label, group, ages, tunic, swatch}], colors {child, adult}
(the picks), applied {child, adult} | null (what the game has), appliedOn, same, busy, line, calBusy, others; and the
messages charLook {look, n, error?} (the look's files are ready), charCal {maps [{tex, file, parts, yref}]} (where each
part lies on each colour map) and charExact {age, n, colors, tex} (OOTRR's own recoloured maps for those colours).
A pick shows at once as a tint over the calibration mask, then OOTRR's exact map takes its place. Uses app.js's $, $$, S,
ACTIONS, cmd, sfx, esc, toast and its colour helpers. */
'use strict';
const CH = {
age: 'child', tunic: 'kokiri', open: null, h: 0, s: 0, v: 0,
viewer: null, look: null, want: null, n: 0, have: new Set(), sceneTex: new Set(), loading: false, error: '',
cal: null, masks: new Set(), exact: { child: null, adult: null }, cmKey: new Map(),
colors: { child: {}, adult: {}, 'linkle:child': {}, 'linkle:adult': {} }, touchedAt: 0, sendT: 0, face: false, hero: 'link',
};
/* swatches in the picker: the game's tunics first, then a spread */
const CH_SWATCH = [['#2f8f3a', 'Kokiri green'], ['#b3262c', 'Goron red'], ['#2a4fb0', 'Zora blue'], ['#1f5e2e', 'Deep forest'], ['#7d1622', 'Crimson'],
['#1c2a52', 'Midnight'], ['#4b2a84', 'Royal purple'], ['#2a8f8a', 'Lake teal'], ['#d4a634', 'Triforce gold'], ['#c8641e', 'Ember'],
['#d86a9a', 'Fairy pink'], ['#ebe7de', 'Snow'], ['#a7abb3', 'Silver'], ['#6b4a2b', 'Leather'], ['#2b2b2e', 'Charcoal'], ['#121214', 'Shadow']];
/* whole looks: each names what it changes; Original takes every part back to the game's colour */
const CH_LOOKS = [
{ id: 'original', name: 'Original', c: {} },
{ id: 'midnight', name: 'Midnight', c: { kokiri: '#1f2b4d', kokiri_pants: '#2b3352', kokiri_shirt: '#cfc8b8', kokiri_belt: '#3b2a1f', leather_trim: '#8a1f2b', boots: '#2a1d15', gloves: '#2a1d15', feathers: '#e9e5dc', goron: '#33204a', goron_trim: '#c9a24a', zora: '#1c2448', zora_shirt: '#cfd3da' } },
{ id: 'crimson', name: 'Crimson', c: { kokiri: '#8e1b22', kokiri_pants: '#5a1a1a', kokiri_shirt: '#e6dcc8', kokiri_belt: '#3b2416', leather_trim: '#d4a634', boots: '#3b2416', gloves: '#3b2416', feathers: '#f2ead8', zora: '#7a1a2a' } },
{ id: 'royal', name: 'Royal', c: { kokiri: '#3b2a7a', kokiri_pants: '#2e2458', kokiri_shirt: '#ece3cf', kokiri_belt: '#4a2f1d', leather_trim: '#d4a634', feathers: '#f5e6b0', goron: '#4b2a84', goron_trim: '#e0b84a', zora: '#3b2a7a' } },
{ id: 'snow', name: 'Snow', c: { kokiri: '#e8e6df', kokiri_pants: '#cfcac0', kokiri_shirt: '#f4f1ea', kokiri_belt: '#8a6a4a', leather_trim: '#b8963e', boots: '#e0dbd0', gloves: '#e0dbd0', feathers: '#ffffff', goron: '#e8e6df', zora: '#e8eef4' } },
{ id: 'shadow', name: 'Shadow', c: { kokiri: '#1b1b1e', kokiri_pants: '#222226', kokiri_shirt: '#3a3a3e', kokiri_belt: '#141414', leather_trim: '#6a0f18', boots: '#111113', gloves: '#111113', feathers: '#2a2a2e', hair: '#e8e8ea', goron: '#1b1b1e', zora: '#1b1b1e' } },
{ id: 'random', name: 'Random', c: null },
];
function chS() { return S.char || {}; }
function chLook() { return CH.age === 'child' ? 'child' : CH.tunic === 'kokiri' ? 'adult' : 'adult-' + CH.tunic; }
/* a colour set's key: the age, "linkle:" in front for her */
function chKey(age) { return (CH.hero === 'linkle' ? 'linkle:' : '') + (age || CH.age); }
function chCur() { return CH.colors[chKey()] || (CH.colors[chKey()] = {}); }
function chLinkle() { return chS().linkle || {}; }
function chHeroName() { return CH.hero === 'linkle' ? 'Linkle' : 'Link'; }
function chParts() {
return (chS().parts || []).filter(p => p.ages.split(',').includes(CH.age) && (CH.age === 'child' || !p.tunic || p.tunic === CH.tunic));
}
function chLin(hex) { return hexRgb(hex).map(x => { x /= 255; return x <= .04045 ? x / 12.92 : ((x + .055) / 1.055) ** 2.4; }); }
/* ---------------- the stage ---------------- */
function chViewer() {
if (CH.viewer) return CH.viewer;
const c = $('#chCanvas');
try { CH.viewer = window.Char3D && Char3D.create(c); } catch (e) { CH.viewer = null; console.error(e); }
if (!CH.viewer) { CH.error = 'This PC\'s browser engine has no WebGL 2, so Link cannot be drawn here. Colors still apply.'; drawChar(); }
new ResizeObserver(() => CH.viewer && CH.viewer.resize()).observe(c);
return CH.viewer;
}
function chLoad() {
const look = CH.hero + '/' + chLook();
if (CH.look === look || CH.want === look || !chS().game || !chViewer()) return;
if (CH.hero === 'linkle' && !chLinkle().have) return;
CH.want = look; CH.loading = true; CH.error = ''; drawChar();
cmd('char.look', { look: chLook(), have: [...CH.have] });
}
async function chFetchTex(name) {
const r = await fetch('/char/tex/' + encodeURIComponent(name) + '.bin');
if (!r.ok) return null;
const b = await r.arrayBuffer(), d = new DataView(b);
CH.have.add(name);
return { w: d.getUint32(0, true), h: d.getUint32(4, true), data: new Uint8Array(b, 8) };
}
async function chFetchBin(url) {
const r = await fetch(url); if (!r.ok) return null;
const b = await r.arrayBuffer(), d = new DataView(b);
return { w: d.getUint32(0, true), h: d.getUint32(4, true), data: new Uint8Array(b, 8) };
}
async function chOnLook(m) {
const want = (m.hero || 'link') + '/' + m.look;
if (want !== CH.want) return;
if (m.error) { CH.want = null; CH.loading = false; CH.error = m.error; drawChar(); return; }
try {
const info = await (await fetch('/char/scene/' + m.n + '.json')).json();
const mesh = await (await fetch('/char/scene/' + m.n + '.bin')).arrayBuffer();
if (want !== CH.want) return;
await CH.viewer.load(info, mesh, chFetchTex);
cmd('char.loaded', { n: m.n });
CH.look = want; CH.want = null; CH.loading = false;
CH.sceneTex = new Set(info.parts.map(p => p.alb).filter(Boolean));
CH.cmKey.clear(); CH.viewer.clearColorMaps();
chTint();
} catch (e) { CH.want = null; CH.loading = false; CH.error = 'Link could not be drawn: ' + e.message; }
drawChar();
}
/* ---------------- colours on the model: OOTRR's exact map when it matches the picks, else the live tint ---------------- */
function chTint() {
const v = CH.viewer; if (!v || !CH.look) return;
const cur = chCur(), ex = CH.exact[chKey()];
v.setNaviColor(cur.navi || (CH.hero === 'linkle' ? '#e8f070' : null));
const same = (parts, colors) => parts.every(p => (cur[p] || null) === ((colors || {})[p] || null));
const done = new Set();
for (const [tex, c] of (CH.hero === 'link' && CH.cal || new Map())) {
if (!CH.sceneTex.has(tex)) continue;
done.add(tex);
if (ex && same(c.parts, ex.colors)) { v.setTint(tex, null); chUseExact(tex, ex); continue; }
chUseExact(tex, null);
const slots = c.parts.map((p, i) => cur[p] ? chTintSlot(cur[p], c.ym[i], c.qm[i], c.ty[i], c.g ? c.g[i] : 1) : null);
if (slots.some(Boolean) && chMask(tex, c.file)) v.setTint(tex, slots); else v.setTint(tex, null);
}
/* (no calibration yet: the exact maps alone, when they match every pick of this age) */
if (ex) for (const tex of ex.tex) if (!done.has(tex) && CH.sceneTex.has(tex)) chUseExact(tex, Object.keys(cur).length === Object.keys(ex.colors).length && Object.keys(cur).every(k => cur[k] === ex.colors[k]) ? ex : null);
}
/* a part's live tint, as OOTRR's dye comes out: [r, g, b] the colour at the part's median texel (linear), ym that texel's
luminance, and the contrast g. OOTRR compresses brightness, so the median texel comes out near qm * (Y / ty)^0.62, mixes
the colour toward its own grey (measured 11-30 at the median texel, linear: 26% for #FF0000, 36% for #2050C0 on young
Link's belt; 30% here), and scales the shading by (y / ym)^g, flattened at the top (char3d.js). 11-30: the tint was
brighter than OOTRR's map, and painted the buckle and ring, so a pick seemed to switch when the exact map came */
function chTintSlot(hex, ym, qm, ty, g) {
const c = chLin(hex), y = Math.max(1e-4, .2126 * c[0] + .7152 * c[1] + .0722 * c[2]);
const out = qm * Math.pow(y / ty, .62), k = out / y;
return c.map(x => (x * .7 + y * .3) * k).concat(Math.max(1e-4, ym), g || 1);
}
function chUseExact(tex, ex) {
const key = ex && ex.tex.includes(tex) ? chKey() + '/' + ex.n : '';
if ((CH.cmKey.get(tex) || '') === key) return;
CH.cmKey.set(tex, key);
if (!key) { CH.viewer.setColorMap(tex, null); return; }
chFetchBin('/char/exact/' + chKey() + '/' + ex.n + '/' + encodeURIComponent(tex) + '.bin').then(t => {
if (CH.cmKey.get(tex) === key && t) CH.viewer.setColorMap(tex, t);
});
}
function chMask(tex, file) {
if (CH.masks.has(tex)) return true;
CH.masks.add(tex);
chFetchBin('/char/mask/' + encodeURIComponent(file) + '.bin').then(t => { if (t) { CH.viewer.setMask(tex, t); chTint(); } else CH.masks.delete(tex); });
return false;
}
/* ---------------- picks ---------------- */
function chNaviBoth() { const h = chCur().navi, o = CH.colors[chKey(CH.age === 'child' ? 'adult' : 'child')] || (CH.colors[chKey(CH.age === 'child' ? 'adult' : 'child')] = {}); if (h) o.navi = h; else delete o.navi; }
function chSet(part, hex, final) {
const c = chCur();
if (hex) c[part] = hex; else delete c[part];
if (part === 'navi') chNaviBoth();
CH.touchedAt = performance.now();
chTint();
if (final) drawChar(); else chPatchRow(part);
chDyeing();
clearTimeout(CH.sendT);
const go = () => cmd('char.set', { age: CH.age, part, hex: hex || null });
if (final) go(); else CH.sendT = setTimeout(go, 220);
}
function chMany(colors) {
const c = chCur();
for (const k in colors) { if (colors[k]) c[k] = colors[k]; else delete c[k]; }
if ('navi' in colors) chNaviBoth();
CH.touchedAt = performance.now();
chTint(); drawChar();
cmd('char.many', { age: CH.age, colors });
}
function chRandom() {
const out = {}, base = Math.random() * 360;
chParts().forEach((p, i) => {
const h = (base + (p.group === 'Tunic' ? 0 : p.group === 'Leather' ? 25 + Math.random() * 30 : Math.random() * 360) + (i % 3) * 8) % 360;
const s = p.group === 'Leather' ? .35 + Math.random() * .3 : .45 + Math.random() * .45;
const v = p.group === 'Leather' ? .22 + Math.random() * .25 : .35 + Math.random() * .5;
out[p.id] = rgbHex(hsvRgb(h, s, v));
});
return out;
}
/* ---------------- drawing the page ---------------- */
function drawChar() {
if (!$('#s-char')) return;
const st = chS();
// (the launcher's picks are taken unless one was made here a moment ago and is still on its way)
if (st.colors && performance.now() - CH.touchedAt > 1500) {
CH.colors = {};
for (const k of ['child', 'adult', 'linkle:child', 'linkle:adult']) CH.colors[k] = Object.assign({}, st.colors[k] || {});
}
if (st.hero && st.hero !== CH.hero) chHeroSwitch(st.hero);
$$('#chHeroes span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chhero:' + CH.hero));
$$('#chAges span').forEach(s => { s.textContent = (s.dataset.act === 'chage:child' ? 'Young ' : 'Adult ') + chHeroName(); });
$$('#chAges span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chage:' + CH.age));
$('#chTunics').style.visibility = CH.age === 'adult' ? 'visible' : 'hidden';
$$('#chTunics span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chtunic:' + CH.tunic));
$('#chTitle').textContent = (CH.age === 'child' ? 'Young ' : 'Adult ') + chHeroName() + '’s colors';
$('#chFace').textContent = CH.face ? 'Full body' : 'Face';
const wait = $('#chWait');
const lk = chLinkle();
const noLinkle = CH.hero === 'linkle' && st.game && !lk.have;
const waitText = !st.game ? 'Build the game first: Link is read from it' : noLinkle ? '' : CH.error || (CH.loading ? 'Reading ' + chHeroName() + ' from your files' : '');
wait.classList.toggle('on', !!waitText); wait.classList.toggle('err', !!(CH.error || !st.game));
$('#chWaitT').textContent = waitText;
const get = $('#chGet');
get.classList.toggle('on', !!noLinkle);
if (noLinkle) get.innerHTML = `<h3>Play as Linkle</h3><p><b>${esc(lk.name || 'Playable Linkle')}</b> by <b>${esc(lk.author || '')}</b>: Linkle from Hyrule Warriors, young and adult, with her own voice, gear and fairy, Liri. A mod from GameBanana, about 320 MB.</p>` +
(lk.busy ? `<p class="chmsg">${esc(lk.line || 'Downloading')}</p><div class="chbar"><i style="width:${(lk.frac || 0) * 100}%"></i></div>`
: `<div class="chbtns" style="justify-content:flex-start"><div class="play sm" data-f id="chGetBtn" data-act="chlinkle">Get Linkle</div><span class="lnk" data-f data-act="chpage">Her page</span></div>`);
if (CH.viewer) { if (noLinkle) CH.viewer.stop(); else if (screen === 'char') CH.viewer.start(); }
$('#chCanvas').style.visibility = noLinkle ? 'hidden' : '';
const changed = Object.keys(chCur()).length;
chDyeing();
$('#chState').textContent = changed ? changed + (changed === 1 ? ' part changed' : ' parts changed') : 'The game’s own colors';
$('#chLooks').innerHTML = CH_LOOKS.map((l, i) => `<span data-f data-act="chlook:${l.id}" id="chl${i}" class="${chLookOn(l) ? 'on' : ''}">${esc(l.name)}</span>`).join('');
chDrawRows();
chDrawFoot();
if (screen === 'char') chLoad();
}
/* "Dyeing" under the stage while OOTRR's exact maps for the picks are on their way and no live tint stands in for them */
function chDyeing() {
const cur = chCur(), ex = CH.exact[chKey()];
const match = ex && Object.keys(cur).length === Object.keys(ex.colors).length && Object.keys(cur).every(k => cur[k] === ex.colors[k]);
const el = $('#chDye'); if (el) el.classList.toggle('on', (CH.hero === 'linkle' || !!(chS().tool || {}).have) && !match && (CH.hero === 'linkle' || !CH.cal) && !!CH.look);
}
function chLookOn(l) {
if (!l.c) return false;
const cur = chCur() || {}, ids = chParts().map(p => p.id);
return ids.every(id => (cur[id] || null) === (l.c[id] || null)) && (l.id === 'original' || ids.some(id => l.c[id]));
}
function chDrawRows() {
const list = $('#chList'); if (!list) return;
const parts = chParts(), cur = chCur() || {}, applied = (chS().applied || {})[chKey()] || {};
const keep = focused && list.contains(focused) ? focused.id : null;
let html = '', group = '';
for (const p of parts) {
if (p.group !== group) { group = p.group; html += `<h4>${esc(group === 'Leather' ? 'Leather and gear' : group === 'Navi' ? 'Your fairy' : group)}</h4>`; }
const hex = cur[p.id], shown = hex || p.swatch, open = CH.open === p.id, pend = (hex || null) !== (applied[p.id] || null);
html += `<div class="chrow${open ? ' open' : ''}" data-f data-act="chpick:${p.id}" id="chp-${p.id}"><i class="chsw${hex ? '' : ' orig'}" style="--c:${shown}"></i>` +
`<b>${esc(p.label)}</b><span>${hex ? hex.toUpperCase() : 'Game’s color'}${pend ? '<u title="Not in your game yet"></u>' : ''}</span><em>${open ? 'Done' : 'Change'}</em></div>`;
if (open) html += chPicker(p, shown, !!hex);
}
html += CH.hero === 'linkle' ? `<p class="gnote chnote">Liri is one fairy for both ages. Linkle is <span class="lnk" data-act="chpage">${esc(chLinkle().name || 'a mod')}</span> by ${esc(chLinkle().author || '')}.</p>`
: '<p class="gnote chnote">Navi is one fairy for both ages: her color goes with young and adult Link.</p>';
// (the list is drawn again only when what it shows changed: a pick while dragging moves the marks, not the whole list)
if (list.dataset.html !== html) {
const top = list.scrollTop; list.innerHTML = html; list.dataset.html = html; list.scrollTop = top;
if (keep && $('#' + keep)) { focused = null; setFocus($('#' + keep)); }
}
chDrawPicker();
}
function chPicker(p, hex, set) {
return `<div class="chpick" id="chPick"><div class="chpk-l"><div class="cp-sv chsv" data-f id="chSv"><u></u></div><div class="slider cp-hue chhue" data-f id="chHue"><u></u></div></div>` +
`<div class="chpk-r"><div class="cp-f"><label>Hex<input data-f id="chHex" value="${hex.toUpperCase()}" maxlength="7" spellcheck="false" autocomplete="off"></label></div>` +
`<div class="chpre">${CH_SWATCH.map(([c, n], i) => `<span data-f data-act="chsw:${c}" id="chs${i}" title="${esc(n)}" style="--c:${c}"></span>`).join('')}</div>` +
`<div class="cp-foot"><em id="chSwName"></em>${set ? `<span class="lnk" data-f data-act="chorig:${p.id}" id="chOrig">Game’s color</span>` : ''}</div></div></div>`;
}
/* while a colour is dragged: only the row's mark and value move (the list is not drawn again under the pointer) */
function chPatchRow(part) {
const row = $('#chp-' + part); if (!row) return;
const hex = chCur()[part], p = chParts().find(x => x.id === part) || {};
const sw = row.querySelector('.chsw'); sw.style.setProperty('--c', hex || p.swatch); sw.classList.toggle('orig', !hex);
row.querySelector('span').firstChild.textContent = hex ? hex.toUpperCase() : 'Game’s color';
}
function chDrawPicker() {
const sv = $('#chSv'), hu = $('#chHue'); if (!sv || !CH.open) return;
const hex = chCur()[CH.open] || (chParts().find(p => p.id === CH.open) || {}).swatch || '#808080';
if (rgbHex(hsvRgb(CH.h, CH.s, CH.v)) !== hex) { const [r, g, b] = hexRgb(hex), mx = Math.max(r, g, b), d = mx - Math.min(r, g, b); CH.s = mx ? d / mx : 0; CH.v = mx / 255; if (d) CH.h = rgbHsl([r, g, b])[0]; }
sv.style.setProperty('--cp-h', CH.h); sv.style.setProperty('--cp-c', hex);
sv.querySelector('u').style.left = CH.s * 100 + '%'; sv.querySelector('u').style.top = (1 - CH.v) * 100 + '%';
hu.style.setProperty('--cp-c', `hsl(${CH.h}, 100%, 50%)`); hu.querySelector('u').style.left = CH.h / 360 * 100 + '%';
const f = $('#chHex'); if (f && document.activeElement !== f) { f.value = hex.toUpperCase(); f.classList.remove('bad'); }
const n = CH_SWATCH.find(x => x[0] === hex); $('#chSwName').textContent = n ? n[1] : '';
$$('.chpre span').forEach(s => s.classList.toggle('on', s.dataset.act === 'chsw:' + hex));
}
function chDrawFoot() {
const st = chS(), t = st.tool || {}, f = $('#chFoot');
const changed = !st.same, hasApplied = !!st.applied;
let html;
if (!st.game) html = '<p class="chmsg">Build the game first: the colors go into its files.</p>';
else if (!t.have) html = t.busy ? `<p class="chmsg">Getting the color tool… ${Math.round((t.frac || 0) * 100)} %</p><div class="chbar"><i style="width:${(t.frac || 0) * 100}%"></i></div>`
: `<p class="chmsg">Picks show here now. To put them in your game, Triforce uses the randomizer’s color tool (OOTRR, ${esc(t.size || '5 MB')}, once).</p><div class="chbtns"><div class="play sm" data-f id="chGo" data-act="chinstall">Get the color tool</div></div>`;
else if (st.busy) html = `<p class="chmsg"><span class="chspin sm"></span>${esc(st.line || 'Working')}… about half a minute</p><div class="chbtns"><span class="lnk" data-f id="chStop" data-act="chstop">Stop</span></div>`;
else {
const msg = changed ? (hasApplied ? 'Changed since you applied: not in your game yet' : 'Not in your game yet')
: hasApplied ? (st.appliedOn ? '◆ In your game · every save, new or old' : 'In your game, but switched off on the Mods page') : 'Your game has its own colors';
const others = (st.others || []).length ? `<p class="chmsg warn">Over ${esc(st.others.join(', '))}, which changes Link too.</p>` : '';
html = `<p class="chmsg${changed ? ' pend' : ''}">${msg}</p>${others}<div class="chbtns">` +
(changed && st.appliedHero && st.appliedHero !== CH.hero ? `<span class="chmsg" style="margin-right:auto">Your game plays ${st.appliedHero === 'linkle' ? 'Linkle' : 'Link'} now</span>` : '') +
(changed && hasApplied ? '<span class="lnk" data-f id="chUndo" data-act="chrevert">Undo changes</span>' : '') +
(!changed && hasApplied ? '<span class="lnk" data-f id="chRemove" data-act="chremove">Use the game’s colors</span>' : '') +
`<div class="play sm${changed ? '' : ' off'}" data-f id="chGo" data-act="chapply">${changed && !Object.values(CH.colors).some(c => Object.keys(c).length) ? 'Apply the game’s colors' : 'Apply to my game'}</div></div>`;
}
if (f.dataset.html !== html) { const keep = focused && f.contains(focused) ? focused.id : null; f.innerHTML = html; f.dataset.html = html; if (keep && $('#' + keep)) { focused = null; setFocus($('#' + keep)); } }
}
/* ---------------- actions ---------------- */
function chHeroSwitch(hero) {
if (hero === CH.hero) return;
CH.hero = hero; CH.open = null; CH.look = null; CH.want = null; CH.have.clear(); CH.cmKey.clear(); CH.masks.clear();
if (CH.viewer) CH.viewer.clearTextures();
if (hero === 'linkle' && CH.tunic !== 'kokiri' && false) CH.tunic = 'kokiri';
}
ACTIONS.chhero = (h) => { if (h === CH.hero) return; chHeroSwitch(h); cmd('char.hero', { hero: h }); drawChar(); chLoad(); };
ACTIONS.chlinkle = () => cmd('char.linkle');
ACTIONS.chpage = () => cmd('open', { arg: 'linkle' });
ACTIONS.chage = (a) => { if (CH.age === a) return; CH.age = a; CH.open = null; drawChar(); chLoad(); };
ACTIONS.chtunic = (t) => { if (CH.tunic === t) return; CH.tunic = t; CH.open = null; drawChar(); chLoad(); };
ACTIONS.chturn = (d) => CH.viewer && CH.viewer.turn(+d * 0.7);
ACTIONS.chface = () => { CH.face = !CH.face; if (CH.viewer) CH.viewer.look(CH.face ? 'face' : 'body'); drawChar(); };
ACTIONS.chpick = (id) => { CH.open = CH.open === id ? null : id; chDrawRows(); if (CH.open) setTimeout(() => { const p = $('#chPick'), l = $('#chList'); if (p && l) { const over = p.offsetTop + p.offsetHeight - l.scrollTop - l.clientHeight; if (over > 0) l.scrollTop += over + 8; } }, 30); };
ACTIONS.chsw = (hex) => { chSet(CH.open, hex, true); chDrawPicker(); };
ACTIONS.chorig = (id) => { chSet(id, null, true); CH.open = null; chDrawRows(); };
ACTIONS.chlook = (id) => {
const l = CH_LOOKS.find(x => x.id === id); if (!l) return;
const src = l.c || chRandom(), out = {};
for (const p of chParts()) out[p.id] = src[p.id] || null;
chMany(out);
};
ACTIONS.chapply = () => cmd('char.apply');
ACTIONS.chinstall = () => cmd('char.install');
ACTIONS.chstop = () => cmd('char.stop');
ACTIONS.chrevert = () => { CH.touchedAt = 0; cmd('char.revert'); };
ACTIONS.chremove = () => cmd('char.remove');
/* the picker: drag in the square / on the hue, or type the hex */
document.addEventListener('pointerdown', e => {
const el = e.target.closest('#chSv, #chHue'); if (!el || !CH.open) return;
e.preventDefault(); setFocus(el, true);
const id = el.id;
const mv = ev => {
const n = $('#' + id); if (!n) return;
const b = n.getBoundingClientRect(), x = clamp01((ev.clientX - b.left) / b.width), y = clamp01((ev.clientY - b.top) / b.height);
if (id === 'chHue') CH.h = Math.round(x * 359); else { CH.s = x; CH.v = 1 - y; }
chSet(CH.open, rgbHex(hsvRgb(CH.h, CH.s, CH.v)), false); chDrawPicker();
};
mv(e);
const up = () => { removeEventListener('pointermove', mv); removeEventListener('pointerup', up); clearTimeout(CH.sendT); if (CH.open) chSet(CH.open, chCur()[CH.open] || null, true); sfx('cursor'); };
addEventListener('pointermove', mv); addEventListener('pointerup', up);
});
document.addEventListener('input', e => {
if (e.target.id !== 'chHex') return;
const v = e.target.value.trim().replace(/^#/, '');
e.target.classList.toggle('bad', /[^0-9a-f]/i.test(v) || v.length > 6);
if (/^[0-9a-f]{6}$/i.test(v) && CH.open) { chSet(CH.open, '#' + v.toLowerCase(), true); chDrawPicker(); }
});
/* arrows on the square and the hue (app.js asks this first) */
function charNudge(dx, dy) {
if (!focused || !CH.open) return false;
if (focused.id === 'chHue' && dx) CH.h = Math.max(0, Math.min(359, CH.h + dx * 5));
else if (focused.id === 'chSv' && (dx || dy)) { CH.s = clamp01(CH.s + dx * .04); CH.v = clamp01(CH.v + dy * .04); }
else return false;
chSet(CH.open, rgbHex(hsvRgb(CH.h, CH.s, CH.v)), false); chDrawPicker(); sfx('cursor');
return true;
}
/* ---------------- from the launcher ---------------- */
function charMessage(m) {
if (m.t === 'charLook') chOnLook(m);
else if (m.t === 'charCal') { CH.cal = new Map(m.maps.map(x => [x.tex, x])); chTint(); }
else if (m.t === 'charExact') { const k = m.key || m.age; CH.exact[k] = { n: m.n, colors: m.colors || {}, tex: m.tex || [] }; if (k === chKey()) chTint(); chDyeing(); }
}
function charShown(name) {
if (name !== 'char') { if (CH.viewer) CH.viewer.stop(); return; }
cmd('char.open');
const v = chViewer();
if (v) { v.start(); v.resize(); }
drawChar(); chLoad();
}

441
launcher/ui/char3d.js Normal file
View File

@@ -0,0 +1,441 @@
/* ((Triforce, 11-29) The Character page's stage: Link in 3D, drawn with WebGL2 from the player's own game files (the launcher
sends the posed mesh and the textures: launcher/Core/GameFiles/LinkScene.cs). Studio light: a warm key with a soft shadow
map, a cool fill, a gold rim and a sky/ground ambient; normal maps and AO; ACES tone mapping. The model turns, the lights
stay. Drag turns him, the wheel zooms, a double click looks at the face and back.
Colours: each colour map can carry a "tint" (a mask of where a part is, two parts a map at most, and the part's colour):
that is the live preview while a colour is picked; the launcher then sends OOTRR's own recoloured map (exact) in its place.
Char3D.create(canvas) -> { load(info, meshBuffer, fetchTex), setTint(texName, slots), setColorMap(texName, tex), clearColorMaps(),
look(where), resize(), stop() } with tex = {w, h, data: Uint8Array RGBA}. */
'use strict';
(function () {
const VS = `#version 300 es
layout(location=0) in vec3 aPos; layout(location=1) in vec3 aNrm; layout(location=2) in vec4 aTan; layout(location=3) in vec2 aUv; layout(location=4) in vec4 aCol;
uniform mat4 uModel, uVP, uLightVP;
out vec3 vPos; out vec3 vNrm; out vec4 vTan; out vec2 vUv; out vec4 vLight; out vec4 vCol;
void main() {
vec4 w = uModel * vec4(aPos, 1.0);
vPos = w.xyz; vNrm = mat3(uModel) * aNrm; vTan = vec4(mat3(uModel) * aTan.xyz, aTan.w); vUv = aUv;
vLight = uLightVP * w; vCol = aCol;
gl_Position = uVP * w;
}`;
const FS = `#version 300 es
precision highp float;
in vec3 vPos; in vec3 vNrm; in vec4 vTan; in vec2 vUv; in vec4 vLight; in vec4 vCol;
uniform int uDebug, uStrands;
uniform sampler2D uAlb, uNrm, uAo, uLut, uGrey, uMask, uShadow, uNrm2, uEmc;
uniform int uHasEmc;
uniform int uHasAlb, uHasNrm, uHasAo, uHasLut, uHasNrm2, uKind, uAlphaMode, uTint;
uniform vec4 uTintA, uTintB; /* rgb: the part's colour at its median texel (linear), a: that texel's luminance (0: not tinted) */
uniform vec2 uTintG; /* (11-30) each part's contrast: its texels scale as (y / a)^g, at most 3.6x the median (OOTRR flattens its top: 99% ~3.8x) */
uniform vec3 uEye; uniform float uExposure, uTile;
out vec4 frag;
float lum(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
vec3 aces(vec3 x) { const float a = 2.51, b = 0.03, c = 2.43, d = 0.59, e = 0.14; return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0); }
float shadowAt(vec3 n, vec3 l) {
vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5;
if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z > 1.0) return 1.0;
float bias = 0.0012 + 0.0025 * (1.0 - max(dot(n, l), 0.0));
vec2 texel = 1.0 / vec2(textureSize(uShadow, 0));
float s = 0.0;
for (int y = -2; y <= 2; y++) for (int x = -2; x <= 2; x++)
s += (p.z - bias <= texture(uShadow, p.xy + vec2(x, y) * texel * 1.2).r) ? 1.0 : 0.0;
return s / 25.0;
}
void main() {
vec4 alb = uHasAlb == 1 ? texture(uAlb, vUv) : vec4(0.6, 0.6, 0.6, 1.0);
if (uHasLut == 1) {
/* young Link's hair has no colour map: the game's own hair ramp (its warm half), varied a strand at a time by the
vertex colour, darker where the strand mask says the strand turns under */
float g = texture(uGrey, vUv).r;
vec3 c = texture(uLut, vec2(0.58 + 0.38 * clamp(vCol.r, 0.0, 1.0), 0.5)).rgb;
c = mix(vec3(lum(c)), c, 0.78) * (0.72 + 0.28 * g) * mix(0.82, 1.0, clamp(vCol.g, 0.0, 1.0));
/* strands: fine stripes across the card (its u), each strand its own shade */
float su = vUv.x * float(uStrands);
float id = floor(su), fr = fract(su);
float h1 = fract(sin(id * 12.9898 + floor(vUv.y * 3.0) * 4.1) * 43758.5);
float edge = smoothstep(0.0, 0.25, fr) * smoothstep(1.0, 0.75, fr);
c *= mix(0.62, 1.08, h1) * mix(0.78, 1.0, edge);
alb = vec4(c, 1.0);
}
if (uAlphaMode == 1 && alb.a < 0.45) discard;
if (uAlphaMode == 3) { frag = vec4(0.06, 0.025, 0.02, alb.r * 0.5); return; }
if (uKind == 5) { /* Navi's body: her light */
vec3 c = alb.rgb; float f = pow(1.0 - abs(dot(normalize(vNrm), normalize(uEye - vPos))), 2.0);
frag = vec4(pow(aces(c * (1.6 + 2.2 * f)), vec3(1.0 / 2.2)), 1.0); return;
}
if (uKind == 6) { /* her wings: thin and lit, their own glow added */
vec3 e = uHasEmc == 1 ? texture(uEmc, vUv).rgb : vec3(0.0);
vec3 c = alb.rgb * 0.55 + e * 1.8;
frag = vec4(pow(aces(c), vec3(1.0 / 2.2)), clamp(alb.a * 0.7 + lum(e), 0.0, 1.0)); return;
}
if (uKind == 8) { vec3 c = alb.rgb; if (uAlphaMode == 1 && alb.a < 0.45) discard; frag = vec4(pow(aces(c * 1.4 + c * c * 0.8), vec3(1.0 / 2.2)), 1.0); return; }
if (uKind == 7) { if (alb.a < 0.3) discard; frag = vec4(pow(aces(alb.rgb * 2.0), vec3(1.0 / 2.2)), 0.55); return; }
if (uAlphaMode == 4) { frag = vec4(pow(clamp(alb.rgb * 1.4, 0.0, 1.0), vec3(1.0 / 2.2)), 0.0); return; } /* the eye's highlights: added */
vec3 base = alb.rgb;
if (uTint == 1) {
vec2 m = texture(uMask, vUv).rg;
float y = lum(base);
if (uTintA.a > 0.0 && m.r > 0.0) base = mix(base, uTintA.rgb * min(pow(clamp(y / uTintA.a, 0.0, 4.0), uTintG.x), 3.6), m.r);
if (uTintB.a > 0.0 && m.g > 0.0) base = mix(base, uTintB.rgb * min(pow(clamp(y / uTintB.a, 0.0, 4.0), uTintG.y), 3.6), m.g);
}
if (uKind == 1) base *= vec3(1.0, 0.9, 0.82); /* skin: the game's skin shading warms it */
if (uKind == 3) base = mix(base, base * 1.35, 0.6); /* eyes: the game lights them from inside */
vec3 n = normalize(vNrm);
if (!gl_FrontFacing) n = -n;
if (uHasNrm == 1) {
vec3 t = normalize(vTan.xyz - n * dot(n, vTan.xyz));
vec3 b = cross(n, t) * (vTan.w < 0.0 ? -1.0 : 1.0);
vec2 xy = texture(uNrm, vUv).rg * 2.0 - 1.0;
if (uHasNrm2 == 1) xy += (texture(uNrm2, vUv * uTile).rg * 2.0 - 1.0) * 0.6;
vec3 tn = vec3(xy, sqrt(max(1.0 - dot(xy, xy), 0.0)));
n = normalize(mat3(t, b, n) * tn);
}
float ao = uHasAo == 1 ? mix(1.0, texture(uAo, vUv).r, 0.85) : 1.0;
vec3 v = normalize(uEye - vPos);
/* lights: key (warm, upper left front, shadowed), fill (cool, right), rim (gold, behind) */
vec3 lk = normalize(vec3(-0.55, 0.72, 0.62)), lf = normalize(vec3(0.85, 0.25, 0.45)), lr = normalize(vec3(0.35, 0.55, -0.9));
vec3 ck = vec3(1.0, 0.9, 0.76) * 3.1, cf = vec3(0.46, 0.56, 0.8) * 0.8, cr = vec3(1.0, 0.78, 0.42) * 2.4;
float rough = uKind == 1 ? 0.5 : uKind == 2 ? 0.42 : uKind == 3 ? 0.12 : uKind == 4 ? 0.3 : 0.82;
float spec = uKind == 1 ? 0.35 : uKind == 2 ? 0.5 : uKind == 3 ? 1.0 : uKind == 4 ? 0.9 : 0.18;
float sh = shadowAt(n, lk);
float wrap = uKind == 1 ? 0.35 : 0.08;
float dk = max((dot(n, lk) + wrap) / (1.0 + wrap), 0.0) * sh;
float df = max((dot(n, lf) + wrap) / (1.0 + wrap), 0.0);
float fres = pow(1.0 - max(dot(n, v), 0.0), 3.0);
float dr = max(dot(n, lr), 0.0) * (0.35 + 0.65 * fres);
float sp = pow(2.0, 12.0 * (1.0 - rough));
vec3 hk = normalize(lk + v), hr = normalize(lr + v);
float sk = pow(max(dot(n, hk), 0.0), sp) * (sp + 8.0) / 25.0 * sh;
float sr = pow(max(dot(n, hr), 0.0), sp) * (sp + 8.0) / 25.0;
vec3 specCol = uKind == 4 ? base * 1.6 + 0.04 : vec3(0.04 + 0.08 * fres);
vec3 sky = vec3(0.34, 0.36, 0.42), ground = vec3(0.22, 0.16, 0.1);
vec3 amb = mix(ground, sky, n.y * 0.5 + 0.5) * 0.55;
vec3 col = base * (amb * ao + ck * dk * ao + cf * df * ao + cr * dr * 0.55)
+ specCol * spec * (ck * sk + cr * sr * 0.6) * ao;
if (uKind == 1) col += base * vec3(0.9, 0.25, 0.15) * 0.09 * (1.0 - dk);
if (uKind == 3) col += base * 0.55; /* eyes: lit from within, never black in shadow */
if (uKind == 2) {
vec3 tt = normalize(vTan.xyz);
float th = dot(tt, hk), kk = sqrt(max(1.0 - th * th, 0.0));
float s1 = pow(kk, 90.0), s2 = pow(sqrt(max(1.0 - pow(dot(tt, normalize(hk + n * 0.12)), 2.0), 0.0)), 24.0);
col += (ck * 0.05 * s1 + base * ck * 0.06 * s2) * sh * ao;
} /* skin: a little warmth where the light turns */
col = aces(col * uExposure);
frag = vec4(pow(col, vec3(1.0 / 2.2)), uAlphaMode == 2 ? alb.a : 1.0);
}`;
const SVS = `#version 300 es
layout(location=0) in vec3 aPos; layout(location=3) in vec2 aUv;
uniform mat4 uModel, uLightVP; out vec2 vUv;
void main() { vUv = aUv; gl_Position = uLightVP * uModel * vec4(aPos, 1.0); }`;
const SFS = `#version 300 es
precision mediump float; in vec2 vUv; uniform sampler2D uAlb; uniform int uCut; out vec4 o;
void main() { if (uCut == 1 && texture(uAlb, vUv).a < 0.45) discard; o = vec4(1.0); }`;
/* the floor: a dark disc lit from above, with his shadow and a gold ring at its edge */
const GVS = `#version 300 es
layout(location=0) in vec2 aXZ; uniform mat4 uVP, uLightVP; uniform float uR; out vec2 vXZ; out vec4 vLight;
void main() { vXZ = aXZ; vec4 w = vec4(aXZ.x * uR, 0.0, aXZ.y * uR, 1.0); vLight = uLightVP * w; gl_Position = uVP * w; }`;
const GFS = `#version 300 es
precision highp float; in vec2 vXZ; in vec4 vLight; uniform sampler2D uShadow; out vec4 o;
void main() {
float r = length(vXZ);
if (r > 1.0) discard;
vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5; float s = 0.0;
vec2 texel = 1.0 / vec2(textureSize(uShadow, 0));
for (int y = -3; y <= 3; y++) for (int x = -3; x <= 3; x++) s += (p.z - 0.003 <= texture(uShadow, p.xy + vec2(x, y) * texel * 2.0).r) ? 1.0 : 0.0;
s /= 49.0;
float pool = smoothstep(1.0, 0.0, r);
vec3 c = mix(vec3(0.02, 0.018, 0.014), vec3(0.2, 0.15, 0.08), pool * pool) * (0.35 + 0.65 * s);
float ring = smoothstep(0.03, 0.0, abs(r - 0.93)) * 0.9 + smoothstep(0.012, 0.0, abs(r - 0.86)) * 0.4;
c += vec3(0.88, 0.66, 0.24) * ring * 0.45;
float a = smoothstep(1.0, 0.82, r) * (0.75 + 0.25 * pool);
o = vec4(pow(c, vec3(1.0 / 2.2)) * a, a);
}`;
/* Navi's glow: a soft disc that faces the camera, added over everything */
const HVS = `#version 300 es
layout(location=0) in vec2 aXZ; uniform mat4 uVP; uniform vec3 uAt, uRight, uUp; uniform float uR; out vec2 vQ;
void main() { vQ = aXZ; gl_Position = uVP * vec4(uAt + (uRight * aXZ.x + uUp * aXZ.y) * uR, 1.0); }`;
const HFS = `#version 300 es
precision mediump float; in vec2 vQ; uniform vec3 uCol; out vec4 o;
void main() { float r = length(vQ); if (r > 1.0) discard; float a = exp(-r * r * 5.0) * 0.85 + exp(-r * r * 40.0) * 0.6; o = vec4(uCol * a, 0.0); }`;
const KIND = { cloth: 0, skin: 1, hair: 2, eye: 3, metal: 4, lash: 0, fur: 0, shade: 0, glint: 0, navi: 5, wing: 6, navifur: 7, fairy: 8 };
const SOFT = { lash: 1, shade: 1, glint: 1, wing: 1, navifur: 1 };
function compile(gl, vs, fs) {
const p = gl.createProgram();
for (const [t, s] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
const sh = gl.createShader(t); gl.shaderSource(sh, s); gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh));
gl.attachShader(p, sh);
}
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
const u = {}; const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < n; i++) { const a = gl.getActiveUniform(p, i); u[a.name] = gl.getUniformLocation(p, a.name); }
return { p, u };
}
/* column-major 4x4 helpers */
function mul(a, b) { const o = new Float32Array(16); for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) { let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k]; o[c * 4 + r] = s; } return o; }
function persp(fov, asp, n, f) { const t = 1 / Math.tan(fov / 2), o = new Float32Array(16); o[0] = t / asp; o[5] = t; o[10] = (f + n) / (n - f); o[11] = -1; o[14] = 2 * f * n / (n - f); return o; }
function ortho(l, r, b, t, n, f) { const o = new Float32Array(16); o[0] = 2 / (r - l); o[5] = 2 / (t - b); o[10] = -2 / (f - n); o[12] = -(r + l) / (r - l); o[13] = -(t + b) / (t - b); o[14] = -(f + n) / (f - n); o[15] = 1; return o; }
function lookAt(e, c, up) {
const z = norm([e[0] - c[0], e[1] - c[1], e[2] - c[2]]), x = norm(cross(up, z)), y = cross(z, x);
return new Float32Array([x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, e), -dot(y, e), -dot(z, e), 1]);
}
function rotY(a) { const c = Math.cos(a), s = Math.sin(a); return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); }
function norm(v) { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; }
function cross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; }
function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
function create(canvas) {
const gl = canvas.getContext('webgl2', { antialias: true, alpha: true, premultipliedAlpha: true, preserveDrawingBuffer: false });
if (!gl) return null;
const aniso = gl.getExtension('EXT_texture_filter_anisotropic');
const main = compile(gl, VS, FS), shadow = compile(gl, SVS, SFS), floor = compile(gl, GVS, GFS), halo = compile(gl, HVS, HFS);
const SHADOW = 2048;
const shadowTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, shadowTex);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.DEPTH_COMPONENT24, SHADOW, SHADOW);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
const shadowFb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowTex, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const floorBuf = gl.createBuffer(), floorVao = gl.createVertexArray();
gl.bindVertexArray(floorVao); gl.bindBuffer(gl.ARRAY_BUFFER, floorBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
const white = tex1([255, 255, 255, 255]), flat = tex1([128, 128, 255, 255]);
function tex1(c) { const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(c)); return t; }
const S = { parts: [], vao: null, buf: [], tex: new Map(), color: new Map(), tints: new Map(), masks: new Map(), info: null,
yaw: 0.35, yawTo: 0.35, pitch: 0.04, pitchTo: 0.04, dist: 0, distTo: 0, tgt: [0, 1, 0], tgtTo: [0, 1, 0], face: false,
spin: false, idleAt: 0, dirty: true, raf: 0, gen: 0, ready: false, naviCol: [0.75, 0.88, 1.0] }; // ((11-30, the owner) no idle turn: Link turns only when dragged or with the arrows
function upload(t, srgb, clamp) {
const g = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, g);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(gl.TEXTURE_2D, 0, srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8, t.w, t.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, t.data);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
const wrap = clamp ? gl.CLAMP_TO_EDGE : gl.REPEAT;
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
if (aniso) gl.texParameterf(gl.TEXTURE_2D, aniso.TEXTURE_MAX_ANISOTROPY_EXT, 8);
return g;
}
/* info: LinkScene's JSON; mesh: ArrayBuffer; fetchTex(name) -> Promise<{w,h,data}|null>. Resolves once every texture is in. */
async function load(info, mesh, fetchTex) {
const gen = ++S.gen;
S.ready = false;
const vao = gl.createVertexArray(), vb = gl.createBuffer(), ib = gl.createBuffer();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, vb); gl.bufferData(gl.ARRAY_BUFFER, mesh, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh, gl.STATIC_DRAW);
gl.bindVertexArray(null);
const want = new Set();
for (const p of info.parts) for (const k of ['alb', 'nrm', 'nrm2', 'ao', 'lut', 'grey', 'emc']) if (p[k] && !S.tex.has(p[k])) want.add(p[k]);
await Promise.all([...want].map(async n => {
const t = await fetchTex(n).catch(() => null);
if (gen !== S.gen) return;
const srgb = info.parts.some(p => p.alb === n || p.lut === n || p.emc === n);
S.tex.set(n, t ? upload(t, srgb, n.startsWith('eye:') || info.parts.some(p => p.lut === n)) : null);
}));
if (gen !== S.gen) { gl.deleteVertexArray(vao); gl.deleteBuffer(vb); gl.deleteBuffer(ib); return; }
if (S.vao) { gl.deleteVertexArray(S.vao); S.buf.forEach(b => gl.deleteBuffer(b)); }
S.vao = vao; S.buf = [vb, ib]; S.info = info;
S.parts = info.parts.filter(p => !(SOFT[p.kind] && !p.alb) && !(p.alb && !S.tex.get(p.alb) && !p.lut));
const h = info.max[1] - info.min[1];
S.height = h;
const fit = body();
S.tgtTo = fit.tgt.slice(); S.distTo = fit.dist;
if (!S.dist) { S.tgt = fit.tgt.slice(); S.dist = fit.dist * 1.25; }
S.face = false;
S.ready = true; S.dirty = true;
if (!S.raf) S.raf = requestAnimationFrame(frame);
}
function body() { const h = S.height || 1.2; return { tgt: [0, h * 0.47, 0], dist: h * 2.75 }; }
function headView() { const h = S.height || 1.2; return { tgt: [0, h * 0.84, 0], dist: h * 1.2 }; }
function look(where) {
const v = where === 'face' ? headView() : body();
S.face = where === 'face'; S.tgtTo = v.tgt; S.distTo = v.dist; S.dirty = true;
if (S.face) { S.yawTo = Math.round(S.yawTo / (2 * Math.PI)) * 2 * Math.PI + 0.25; S.pitchTo = 0.02; }
}
function draw(proj, view, eye, light) {
const W = canvas.width, H = canvas.height;
const model = rotY(S.yaw);
/* shadow pass */
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb);
gl.viewport(0, 0, SHADOW, SHADOW);
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); gl.colorMask(false, false, false, false);
gl.useProgram(shadow.p);
gl.uniformMatrix4fv(shadow.u.uModel, false, model); gl.uniformMatrix4fv(shadow.u.uLightVP, false, light);
gl.bindVertexArray(S.vao);
bindAttrs();
gl.activeTexture(gl.TEXTURE0); gl.uniform1i(shadow.u.uAlb, 0);
for (const p of S.parts) {
if (SOFT[p.kind] || p.kind === 'eye' || p.kind === 'navi') continue;
const cut = cutOf(p);
gl.uniform1i(shadow.u.uCut, cut === 1 ? 1 : 0);
ptrs(p);
gl.bindTexture(gl.TEXTURE_2D, (p.alb && S.tex.get(p.alb)) || white);
gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff);
}
gl.colorMask(true, true, true, true);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, W, H);
gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const vp = mul(proj, view);
/* floor */
gl.useProgram(floor.p);
gl.uniformMatrix4fv(floor.u.uVP, false, vp); gl.uniformMatrix4fv(floor.u.uLightVP, false, light); gl.uniform1f(floor.u.uR, S.height * 0.46);
gl.activeTexture(gl.TEXTURE7); gl.bindTexture(gl.TEXTURE_2D, shadowTex); gl.uniform1i(floor.u.uShadow, 7);
gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.depthMask(true); gl.disable(gl.BLEND);
/* Link */
gl.useProgram(main.p);
gl.uniformMatrix4fv(main.u.uModel, false, model); gl.uniformMatrix4fv(main.u.uVP, false, vp); gl.uniformMatrix4fv(main.u.uLightVP, false, light);
gl.uniform3fv(main.u.uEye, eye); gl.uniform1f(main.u.uExposure, 0.86);
gl.uniform1i(main.u.uAlb, 0); gl.uniform1i(main.u.uNrm, 1); gl.uniform1i(main.u.uAo, 2); gl.uniform1i(main.u.uLut, 3); gl.uniform1i(main.u.uGrey, 4);
gl.uniform1i(main.u.uMask, 5); gl.uniform1i(main.u.uNrm2, 6); gl.uniform1i(main.u.uShadow, 7); gl.uniform1i(main.u.uEmc, 8);
gl.bindVertexArray(S.vao);
const opaque = S.parts.filter(p => !SOFT[p.kind]), soft = S.parts.filter(p => SOFT[p.kind]);
for (const p of opaque) drawPart(p);
gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
for (const p of soft) {
if (p.kind === 'glint') gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ZERO, gl.ONE);
drawPart(p);
if (p.kind === 'glint') gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
}
gl.depthMask(true); gl.disable(gl.BLEND);
/* Navi's glow */
const at = S.info && S.info.navi;
if (at) {
const c = Math.cos(S.yaw), s = Math.sin(S.yaw);
const w = [c * at[0] + s * at[2], at[1], -s * at[0] + c * at[2]];
const right = [view[0], view[4], view[8]], upv = [view[1], view[5], view[9]];
gl.useProgram(halo.p);
gl.uniformMatrix4fv(halo.u.uVP, false, vp); gl.uniform3fv(halo.u.uAt, w); gl.uniform3fv(halo.u.uRight, right); gl.uniform3fv(halo.u.uUp, upv);
gl.uniform1f(halo.u.uR, S.height * 0.16); gl.uniform3fv(halo.u.uCol, S.naviCol);
/* (depth-tested: when she flies behind him, his head hides her glow) */
gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); gl.depthMask(false);
gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.depthMask(true); gl.disable(gl.BLEND);
}
}
function cutOf(p) { return p.kind === 'fairy' ? 1 : p.kind === 'glint' ? 4 : p.kind === 'shade' ? 3 : p.kind === 'lash' ? 2 : (p.kind === 'hair' || p.kind === 'fur' || /Alpha|Mask|Feather|Band/.test(p.mat)) ? 1 : 0; }
function bindAttrs() {
gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]);
for (let i = 0; i < 5; i++) gl.enableVertexAttribArray(i);
}
function ptrs(p) {
const stride = 64;
gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, p.voff);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, p.voff + 12);
gl.vertexAttribPointer(2, 4, gl.FLOAT, false, stride, p.voff + 24);
gl.vertexAttribPointer(3, 2, gl.FLOAT, false, stride, p.voff + 40);
gl.vertexAttribPointer(4, 4, gl.FLOAT, false, stride, p.voff + 48);
}
function drawPart(p) {
ptrs(p);
const albName = p.alb;
const colorMap = albName && S.color.get(albName);
const t = (n) => (n && S.tex.get(n)) || null;
const alb = colorMap || t(albName);
bindTex(0, alb || white); gl.uniform1i(main.u.uHasAlb, alb ? 1 : 0);
bindTex(1, t(p.nrm) || flat); gl.uniform1i(main.u.uHasNrm, t(p.nrm) ? 1 : 0);
bindTex(2, t(p.ao) || white); gl.uniform1i(main.u.uHasAo, t(p.ao) ? 1 : 0);
const lut = !alb && t(p.lut) && t(p.grey);
bindTex(3, lut ? t(p.lut) : white); bindTex(4, lut ? t(p.grey) : white); gl.uniform1i(main.u.uHasLut, lut ? 1 : 0);
bindTex(8, t(p.emc) || white); gl.uniform1i(main.u.uHasEmc, t(p.emc) ? 1 : 0);
bindTex(6, t(p.nrm2) || flat); gl.uniform1i(main.u.uHasNrm2, t(p.nrm2) ? 1 : 0); gl.uniform1f(main.u.uTile, 1.0);
const tint = albName && S.tints.get(albName);
if (tint && S.masks.get(albName)) {
bindTex(5, S.masks.get(albName));
gl.uniform1i(main.u.uTint, 1);
gl.uniform4fv(main.u.uTintA, tint[0] ? tint[0].slice(0, 4) : [0, 0, 0, 0]); gl.uniform4fv(main.u.uTintB, tint[1] ? tint[1].slice(0, 4) : [0, 0, 0, 0]);
gl.uniform2f(main.u.uTintG, tint[0] && tint[0][4] || 1, tint[1] && tint[1][4] || 1); // ((11-30) each slot's contrast
} else { bindTex(5, white); gl.uniform1i(main.u.uTint, 0); }
gl.uniform1i(main.u.uKind, KIND[p.kind] || 0); gl.uniform1i(main.u.uDebug, window.charDebug || 0); gl.uniform1i(main.u.uStrands, window.charStrands || 80);
gl.uniform1i(main.u.uAlphaMode, cutOf(p));
if (p.kind === 'hair') gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff);
if (p.kind === 'hair') gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
}
function bindTex(unit, t) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, t); }
let last = 0;
function frame(now) {
S.raf = requestAnimationFrame(frame);
const dt = Math.min(0.05, (now - (last || now)) / 1000); last = now;
if (!S.ready) return;
if (S.spin && !S.drag && !S.face && now - S.idleAt > 2500) { S.yawTo += dt * 0.32; }
const k = 1 - Math.pow(0.0008, dt);
const moved = Math.abs(S.yawTo - S.yaw) + Math.abs(S.pitchTo - S.pitch) + Math.abs(S.distTo - S.dist) + Math.abs(S.tgtTo[1] - S.tgt[1]);
if (moved < 1e-5 && !S.dirty) return;
S.yaw += (S.yawTo - S.yaw) * k; S.pitch += (S.pitchTo - S.pitch) * k; S.dist += (S.distTo - S.dist) * k;
for (let i = 0; i < 3; i++) S.tgt[i] += (S.tgtTo[i] - S.tgt[i]) * k;
S.dirty = false;
const W = canvas.width, H = canvas.height;
const eye = [S.tgt[0], S.tgt[1] + Math.sin(S.pitch) * S.dist, S.tgt[2] + Math.cos(S.pitch) * S.dist];
const proj = persp(26 * Math.PI / 180, W / H, 0.05, 20);
const view = lookAt(eye, S.tgt, [0, 1, 0]);
const h = S.height;
const lightDir = norm([-0.55, 0.72, 0.62]);
const lc = [lightDir[0] * 4, h * 0.5 + lightDir[1] * 4, lightDir[2] * 4];
const light = mul(ortho(-h * 0.75, h * 0.75, -h * 0.75, h * 0.75, 0.5, 9), lookAt(lc, [0, h * 0.5, 0], [0, 1, 0]));
draw(proj, view, eye, light);
}
/* input: drag turns him (and tilts the view a little), the wheel zooms, a double click looks at his face and back */
canvas.addEventListener('pointerdown', e => { S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); canvas.setPointerCapture(e.pointerId); canvas.classList.add('grab'); });
canvas.addEventListener('pointermove', e => {
if (!S.drag) return;
S.yawTo += (e.clientX - S.drag.x) * 0.011; S.pitchTo = Math.max(-0.25, Math.min(0.55, S.pitchTo + (e.clientY - S.drag.y) * 0.004));
S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); S.dirty = true;
});
const up = () => { S.drag = null; S.idleAt = performance.now(); canvas.classList.remove('grab'); };
canvas.addEventListener('pointerup', up); canvas.addEventListener('pointercancel', up);
canvas.addEventListener('wheel', e => {
e.preventDefault();
const b = body(), f = headView();
S.distTo = Math.max(f.dist * 0.8, Math.min(b.dist * 1.3, S.distTo * (e.deltaY > 0 ? 1.12 : 0.89)));
/* (closer: the view slides up toward the face) */
const t = Math.max(0, Math.min(1, (b.dist - S.distTo) / (b.dist - f.dist)));
S.tgtTo = [0, b.tgt[1] + (f.tgt[1] - b.tgt[1]) * t, 0]; S.face = t > 0.6; S.idleAt = performance.now(); S.dirty = true;
}, { passive: false });
canvas.addEventListener('dblclick', () => look(S.face ? 'body' : 'face'));
function resize() {
const r = canvas.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1);
const w = Math.max(1, Math.round(r.width * d)), h = Math.max(1, Math.round(r.height * d));
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; S.dirty = true; }
}
resize();
return {
load, look, resize,
turn(by) { S.yawTo += by; S.idleAt = performance.now(); S.dirty = true; },
spin(on) { S.spin = on; },
/* a part's live colour: slots [[r,g,b,yref,contrast] | null, ...] in linear light, or null to stop */
/* Navi's glow colour (#rrggbb), null for her own */
setNaviColor(hex) { const c = hex ? [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255) : [0.75, 0.88, 1.0]; S.naviCol = c.map(x => Math.max(0.12, x)); S.dirty = true; },
setTint(name, slots) { if (slots) S.tints.set(name, slots); else S.tints.delete(name); S.dirty = true; },
setMask(name, t) { const old = S.masks.get(name); if (old) gl.deleteTexture(old); if (t) S.masks.set(name, upload(t, false, false)); else S.masks.delete(name); S.dirty = true; },
setColorMap(name, t) { const old = S.color.get(name); if (old) gl.deleteTexture(old); if (t) S.color.set(name, upload(t, true, false)); else S.color.delete(name); S.dirty = true; },
/* every texture let go (another hero's files carry the same names) */
clearTextures() { for (const g of S.tex.values()) if (g) gl.deleteTexture(g); S.tex.clear(); for (const g of S.color.values()) gl.deleteTexture(g); S.color.clear(); for (const g of S.masks.values()) gl.deleteTexture(g); S.masks.clear(); S.tints.clear(); S.ready = false; S.dirty = true; },
clearColorMaps() { for (const t of S.color.values()) gl.deleteTexture(t); S.color.clear(); S.tints.clear(); S.dirty = true; },
get ready() { return S.ready; },
stop() { cancelAnimationFrame(S.raf); S.raf = 0; },
start() { if (!S.raf) { S.dirty = true; S.raf = requestAnimationFrame(frame); } },
};
}
window.Char3D = { create };
})();

View File

@@ -1,6 +1,6 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Triforce</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="ui.css"><link rel="stylesheet" href="theme.css"><link rel="stylesheet" href="v3.css"><link rel="stylesheet" href="proto.css"><link rel="stylesheet" href="app.css"></head>
<link rel="stylesheet" href="ui.css"><link rel="stylesheet" href="theme.css"><link rel="stylesheet" href="v3.css"><link rel="stylesheet" href="proto.css"><link rel="stylesheet" href="app.css"><link rel="stylesheet" href="char.css"></head>
<body>
<div id="fit"><div class="win" id="win">
@@ -76,7 +76,7 @@
</section>
<!-- ============ SAVES ============ -->
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="3">
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="4">
<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>
@@ -105,8 +105,24 @@
<div class="rside"><div class="benchcard fbox rcard" id="randoCard"></div><div class="rtip fbox" id="randoTip"></div></div>
</section>
<!-- ============ CHARACTER (char.js + char3d.js; launcher/App/Backend.Character.cs) ============ -->
<section class="screen" id="s-char" data-first="chHero0" data-back="home" data-tab="3">
<div class="chstage"><canvas id="chCanvas"></canvas><div class="chglow"></div></div>
<div class="chhead"><div class="cont" style="position:static;width:auto"><div class="eb" id="chEb">Your hero, in your colors</div><h1 style="font-size:54px">Character</h1></div>
<div class="chseg chhero" id="chHeroes"><span data-f id="chHero0" data-act="chhero:link">Link</span><span data-f id="chHero1" data-act="chhero:linkle">Linkle</span></div>
<div class="chseg" id="chAges"><span data-f id="chAge0" data-act="chage:child">Young Link</span><span data-f id="chAge1" data-act="chage:adult">Adult Link</span></div>
<div class="chtunic" id="chTunics"><span data-f id="chTu0" data-act="chtunic:kokiri">Kokiri Tunic</span><span data-f id="chTu1" data-act="chtunic:goron">Goron Tunic</span><span data-f id="chTu2" data-act="chtunic:zora">Zora Tunic</span></div></div>
<div class="chview"><span class="lnk" data-f id="chTurnL" data-act="chturn:-1" title="Turn left">&#9664;</span><span class="lnk" data-f id="chFace" data-act="chface">Face</span><span class="lnk" data-f id="chTurnR" data-act="chturn:1" title="Turn right">&#9654;</span><em>Drag to turn &#183; scroll to zoom</em><span class="chdye" id="chDye"><i class="chspin sm"></i>Dyeing</span></div>
<div class="chget fbox" id="chGet"></div>
<div class="chwait" id="chWait"><div class="chspin"></div><span id="chWaitT">Reading Link from your game</span></div>
<div class="chpanel fbox" id="chPanel"><div class="chtop"><h3 id="chTitle">Young Link's colors</h3><span class="chstate" id="chState"></span></div>
<div class="chlooks" id="chLooks"></div>
<div class="chlist" id="chList"></div>
<div class="chfoot" id="chFoot"></div></div>
</section>
<!-- ============ SETTINGS ============ -->
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="4">
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="5">
<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>
@@ -125,7 +141,7 @@
</section>
<!-- ============ BENCHMARK RESULTS ============ -->
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="4">
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="5">
<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>
@@ -138,7 +154,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="rando">Randomizer</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="char">Character</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>
@@ -158,4 +174,6 @@
<script src="demo.js"></script>
<script src="app.js"></script>
<script src="rando.js"></script>
<script src="char3d.js"></script>
<script src="char.js"></script>
</body></html>