mirror of
https://git.triforceproject.com/triforce/source
synced 2026-12-01 05:18:50 -04:00
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:
@@ -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;
|
||||
|
||||
1084
launcher/Core/GameFiles/AstcEncode.cs
Normal file
1084
launcher/Core/GameFiles/AstcEncode.cs
Normal file
File diff suppressed because it is too large
Load Diff
220
launcher/Core/GameFiles/Bc7.cs
Normal file
220
launcher/Core/GameFiles/Bc7.cs
Normal 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));
|
||||
}
|
||||
298
launcher/Core/GameFiles/Bfres.cs
Normal file
298
launcher/Core/GameFiles/Bfres.cs
Normal 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");
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"),
|
||||
};
|
||||
|
||||
107
launcher/Core/GameFiles/Fska.cs
Normal file
107
launcher/Core/GameFiles/Fska.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
418
launcher/Core/GameFiles/LinkScene.cs
Normal file
418
launcher/Core/GameFiles/LinkScene.cs
Normal 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/<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];
|
||||
}
|
||||
}
|
||||
36
launcher/Core/GameFiles/OverlaySource.cs
Normal file
36
launcher/Core/GameFiles/OverlaySource.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
357
launcher/Core/GameFiles/TextureRecolor.cs
Normal file
357
launcher/Core/GameFiles/TextureRecolor.cs
Normal 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 > 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 > c1; three plus transparent: c0 <= 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user