mirror of
https://git.triforceproject.com/triforce/source
synced 2026-12-01 05:18:50 -04:00
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.
419 lines
23 KiB
C#
419 lines
23 KiB
C#
// (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/<name>.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];
|
|
}
|
|
}
|