Files
_Tools/ModelTools/fbx2gim/Program.cs

361 lines
19 KiB
C#
Raw Normal View History

2026-11-13 00:38:47 +01:00
// fbx2gim – Mixamo-Figur (FBX mit Skelett) + Bewegungen (FBX ohne Skin) → .gim fürs Spiel.
//
// fbx2gim <figur.fbx> <bemalt.pcol|bemalt.glb|-> <ausgabe.gim> name=bewegung.fbx [name=bewegung.fbx ...]
// fbx2gim --info <datei> zeigt Netze, Knochen, Bewegungen
// fbx2gim --obj <figur.fbx> <aus.obj> [textur.png] Netz als OBJ für Mixamo (z. B. Meshy-FBX, die Mixamo ablehnt)
//
// Die Farbe: Mixamo gibt das Netz ohne Farbe zurück (und mit eigener Punktreihenfolge). Jeder Punkt
// holt sie sich vom nächstgelegenen Punkt des bemalten Modells (paint_mesh), nachdem beide auf
// dieselbe Größe gebracht sind. "-": keine Punktfarben – hat die Figur eine eingebettete Textur
// (z. B. Meshy), kommt die Farbe aus ihr (UVs + JPG/PNG werden mitgeschrieben), sonst grau.
//
// Format (.gim, little endian, Strings wie BinaryWriter):
// "GIM2"
// int boneCount; je Knochen: string name, int parent (-1 = Wurzel), 10 float Ruhe-Lokal (T xyz, R xyzw, S xyz),
// byte hasOffset, 16 float Offset (Netz → Knochen, Zeilenvektor-Konvention wie XNA)
// int vertexCount; je Punkt: 3 float Pos, 3 float Normale, 2 float UV, 4 byte RGBA, 4 byte Knochen, 4 float Gewichte
// int indexCount; int[] Indizes
// int clipCount; je Clip: string name, float fps, int frames, frames × boneCount × 10 float (T, R, S lokal)
// int textureBytes; Bilddatei (JPG/PNG) oder 0
using System.Numerics;
using System.Text;
using Assimp;
using AMatrix = Assimp.Matrix4x4;
using NMatrix = System.Numerics.Matrix4x4;
using NQuat = System.Numerics.Quaternion;
static class Fbx2Gim
{
const float FPS = 30;
static Scene Load(string path, bool pivots = false)
{
var ctx = new AssimpContext();
ctx.SetConfig(new Assimp.Configs.FBXPreservePivotsConfig(pivots));
return ctx.ImportFile(path, PostProcessSteps.Triangulate | PostProcessSteps.JoinIdenticalVertices | PostProcessSteps.LimitBoneWeights | PostProcessSteps.FlipUVs);
}
static NMatrix ToN(AMatrix a) => new(a.A1, a.B1, a.C1, a.D1, a.A2, a.B2, a.C2, a.D2, a.A3, a.B3, a.C3, a.D3, a.A4, a.B4, a.C4, a.D4);
static int Main(string[] args)
{
if (args.Length >= 2 && args[0] == "--info") { Info(Load(args[1])); return 0; }
if (args.Length >= 3 && args[0] == "--obj") return ToObj(args[1], args[2], args.Length > 3 ? args[3] : null);
// --tex=<bild>: Textur, falls die Figur keine eingebettete hat (z. B. Mixamo-FBX aus einer OBJ)
string? texFile = args.FirstOrDefault(x => x.StartsWith("--tex="))?[6..];
args = args.Where(x => !x.StartsWith("--tex=")).ToArray();
if (args.Length < 4) { Console.WriteLine("fbx2gim <figur.fbx> <bemalt.glb|-> <ausgabe.gim> name=bewegung.fbx ..."); return 1; }
var skin = Load(args[0]);
var mesh = skin.Meshes.OrderByDescending(m => m.VertexCount).First();
// ── Knochen: alle Knoten, die Knochen sind oder Knochen enthalten (Eltern vor Kindern)
var boneNames = new HashSet<string>(mesh.Bones.Select(b => b.Name));
var nodes = new List<Node>();
bool Needed(Node n) => boneNames.Contains(n.Name) || n.Children.Any(Needed);
void Walk(Node n) { if (n != skin.RootNode && Needed(n)) nodes.Add(n); foreach (var c in n.Children) Walk(c); }
Walk(skin.RootNode);
var index = nodes.Select((n, i) => (n.Name, i)).ToDictionary(p => p.Name, p => p.i);
var parent = nodes.Select(n => n.Parent != null && index.TryGetValue(n.Parent.Name, out int p) ? p : -1).ToArray();
var rest = nodes.Select(n => Trs(ToN(n.Transform))).ToArray();
var offsets = new NMatrix?[nodes.Count];
foreach (var b in mesh.Bones) offsets[index[b.Name]] = ToN(b.OffsetMatrix);
// ── Punkte, Gewichte (höchstens 4), Normalen
int vc = mesh.VertexCount;
var pos = mesh.Vertices.Select(v => new Vector3(v.X, v.Y, v.Z)).ToArray();
var bi = new byte[vc * 4];
var bw = new float[vc * 4];
var inf = new List<(int b, float w)>[vc];
for (int i = 0; i < vc; i++) inf[i] = new();
foreach (var b in mesh.Bones)
foreach (var w in b.VertexWeights) inf[w.VertexID].Add((index[b.Name], w.Weight));
for (int i = 0; i < vc; i++)
{
var top = inf[i].OrderByDescending(x => x.w).Take(4).ToList();
float sum = top.Sum(x => x.w);
for (int k = 0; k < top.Count; k++) { bi[i * 4 + k] = (byte)top[k].b; bw[i * 4 + k] = sum > 0 ? top[k].w / sum : 0; }
if (top.Count == 0) { bi[i * 4] = 0; bw[i * 4] = 1; }
}
var idx = mesh.GetIndices().ToArray();
var nrm = new Vector3[vc];
for (int t = 0; t < idx.Length; t += 3)
{
var a = pos[idx[t]]; var b2 = pos[idx[t + 1]]; var c = pos[idx[t + 2]];
var fn = Vector3.Cross(b2 - a, c - a);
nrm[idx[t]] += fn; nrm[idx[t + 1]] += fn; nrm[idx[t + 2]] += fn;
}
for (int i = 0; i < vc; i++) nrm[i] = nrm[i].LengthSquared() > 0 ? Vector3.Normalize(nrm[i]) : Vector3.UnitY;
if (mesh.HasNormals) // mitgelieferte Normalen (keine Kanten an UV-Nähten)
for (int i = 0; i < vc; i++) { var n = mesh.Normals[i]; var v = new Vector3(n.X, n.Y, n.Z); if (v.LengthSquared() > 0) nrm[i] = Vector3.Normalize(v); }
// ── Textur (eingebettet) und UVs
var uv = new Vector2[vc];
if (mesh.HasTextureCoords(0)) for (int i = 0; i < vc; i++) { var t = mesh.TextureCoordinateChannels[0][i]; uv[i] = new Vector2(t.X, t.Y); }
byte[] tex = Array.Empty<byte>();
if (mesh.HasTextureCoords(0) && skin.TextureCount > 0)
{
var mat = skin.Materials[mesh.MaterialIndex];
string want = mat.HasTextureDiffuse ? mat.TextureDiffuse.FilePath : "";
var et = want.StartsWith('*') && int.TryParse(want[1..], out int ti) && ti < skin.TextureCount ? skin.Textures[ti]
: skin.Textures.FirstOrDefault(t => t.Filename == want) ?? skin.Textures[0];
if (et.IsCompressed) tex = et.CompressedData;
Console.WriteLine($" Textur: {et.Filename} ({tex.Length / 1024} KB, {et.CompressedFormatHint})");
}
if (tex.Length == 0 && texFile != null && File.Exists(texFile) && mesh.HasTextureCoords(0))
{
tex = File.ReadAllBytes(texFile);
Console.WriteLine($" Textur aus Datei: {texFile} ({tex.Length / 1024} KB)");
}
byte grey = tex.Length > 0 ? (byte)255 : (byte)180;
var col = args[1] == "-" ? Enumerable.Repeat(new byte[] { grey, grey, grey, 255 }, vc).ToArray() : Colours(pos, args[1]);
// ── Bewegungen
var clips = new List<(string name, float[][] frames)>();
foreach (var spec in args.Skip(3))
{
int eq = spec.IndexOf('=');
string name = spec[..eq], file = spec[(eq + 1)..];
// Mit Hilfsknoten laden: FBX-Knochen haben Vor-Drehungen (PreRotation), die Spuren hängen an
// eigenen Knoten "<knochen>_$AssimpFbx$_Rotation". Der lokale Knochen ist das Produkt der
// ganzen Kette vom Knochen bis (ohne) zum Elternknochen.
var sc = Load(file, pivots: true);
if (sc.AnimationCount == 0) { Console.WriteLine($" {name}: keine Bewegung in {file}"); continue; }
var anim = sc.Animations[0];
double tps = anim.TicksPerSecond > 0 ? anim.TicksPerSecond : FPS;
// glTF: Assimp liefert die Zeiten in Millisekunden, meldet aber eine falsche Tick-Rate
if (file.EndsWith(".glb", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase)) tps = 1000;
int frames = Math.Max(1, (int)Math.Round(anim.DurationInTicks / tps * FPS) + 1);
var chan = anim.NodeAnimationChannels.ToDictionary(c => c.NodeName);
var byName = new Dictionary<string, Node>();
void W2(Node n) { byName[n.Name] = n; foreach (var c in n.Children) W2(c); }
W2(sc.RootNode);
var chains = new List<Node>?[nodes.Count];
int found = 0;
for (int b = 0; b < nodes.Count; b++)
{
if (!byName.TryGetValue(nodes[b].Name, out var n)) continue;
string? stop = parent[b] >= 0 ? nodes[parent[b]].Name : null;
var chain = new List<Node>();
for (var x = n; x != null && x.Name != stop && x != sc.RootNode; x = x.Parent) chain.Add(x);
chains[b] = chain; found++;
}
// Ruhelage der Kette in der Bewegungsdatei (ohne Spuren), für die Hüfte
var restChain = new float[nodes.Count][];
for (int b = 0; b < nodes.Count; b++)
if (chains[b] is { } ch0) { var m0 = NMatrix.Identity; foreach (var x in ch0) m0 *= ToN(x.Transform); restChain[b] = Trs(m0); }
var data = new float[frames][];
for (int f = 0; f < frames; f++)
{
double t = f / FPS * tps;
var fr = data[f] = new float[nodes.Count * 10];
for (int b = 0; b < nodes.Count; b++)
{
float[] trs = rest[b];
if (chains[b] is { } chain)
{
var m = NMatrix.Identity;
foreach (var x in chain) // Kind zuerst: Zeilenvektor-Konvention
m *= chan.TryGetValue(x.Name, out var ch) ? Mat(Sample(ch, t, Trs(ToN(x.Transform)))) : ToN(x.Transform);
var a = Trs(m);
// Übertragen auf diese Figur (die Bewegung darf von einer anderen Mixamo-Figur stammen):
// Drehung aus der Bewegung, Knochenlängen und Maßstab von der Figur, die Hüfte bewegt
// sich im Verhältnis der Hüfthöhen.
trs = (float[])rest[b].Clone();
trs[3] = a[3]; trs[4] = a[4]; trs[5] = a[5]; trs[6] = a[6];
if (parent[b] < 0)
{
var r0 = restChain[b];
float k = MathF.Abs(r0[1]) > 1e-6f ? rest[b][1] / r0[1] : 1;
for (int i = 0; i < 3; i++) trs[i] = rest[b][i] + (a[i] - r0[i]) * k;
}
}
Array.Copy(trs, 0, fr, b * 10, 10);
}
}
Console.WriteLine($" {name}: {frames} Bilder ({frames / FPS:0.00} s), {chan.Count} Spuren, {found}/{nodes.Count} Knochen gefunden");
clips.Add((name, data));
}
// ── schreiben
using (var w = new BinaryWriter(File.Create(args[2]), Encoding.UTF8))
{
w.Write(Encoding.ASCII.GetBytes("GIM2"));
w.Write(nodes.Count);
for (int b = 0; b < nodes.Count; b++)
{
w.Write(nodes[b].Name); w.Write(parent[b]);
foreach (var x in rest[b]) w.Write(x);
w.Write((byte)(offsets[b].HasValue ? 1 : 0));
var o = offsets[b] ?? NMatrix.Identity;
foreach (var x in new[] { o.M11, o.M12, o.M13, o.M14, o.M21, o.M22, o.M23, o.M24, o.M31, o.M32, o.M33, o.M34, o.M41, o.M42, o.M43, o.M44 }) w.Write(x);
}
w.Write(vc);
for (int i = 0; i < vc; i++)
{
w.Write(pos[i].X); w.Write(pos[i].Y); w.Write(pos[i].Z);
w.Write(nrm[i].X); w.Write(nrm[i].Y); w.Write(nrm[i].Z);
w.Write(uv[i].X); w.Write(uv[i].Y);
w.Write(col[i]);
w.Write(bi, i * 4, 4);
for (int k = 0; k < 4; k++) w.Write(bw[i * 4 + k]);
}
w.Write(idx.Length);
foreach (var i in idx) w.Write(i);
w.Write(clips.Count);
foreach (var (name, frames) in clips)
{
w.Write(name); w.Write(FPS); w.Write(frames.Length);
foreach (var fr in frames) foreach (var x in fr) w.Write(x);
}
w.Write(tex.Length); w.Write(tex);
}
var lo = pos.Aggregate(Vector3.Min); var hi = pos.Aggregate(Vector3.Max);
Console.WriteLine($"{args[2]}: {nodes.Count} Knochen, {vc} Punkte, {idx.Length / 3} Dreiecke, {clips.Count} Clips, Größe {lo} … {hi}, " +
$"{new FileInfo(args[2]).Length / 1024} KB");
return 0;
}
static NMatrix Mat(float[] t) =>
NMatrix.CreateScale(t[7], t[8], t[9]) * NMatrix.CreateFromQuaternion(new NQuat(t[3], t[4], t[5], t[6])) * NMatrix.CreateTranslation(t[0], t[1], t[2]);
static float[] Trs(NMatrix m)
{
NMatrix.Decompose(m, out var s, out var r, out var t);
return new[] { t.X, t.Y, t.Z, r.X, r.Y, r.Z, r.W, s.X, s.Y, s.Z };
}
static float[] Sample(NodeAnimationChannel ch, double t, float[] fallback)
{
var o = (float[])fallback.Clone();
if (ch.PositionKeyCount > 0)
{
var (a, b, f) = Find(ch.PositionKeys.Select(k => k.Time).ToList(), t);
var p = Vector3.Lerp(V(ch.PositionKeys[a].Value), V(ch.PositionKeys[b].Value), f);
o[0] = p.X; o[1] = p.Y; o[2] = p.Z;
}
if (ch.RotationKeyCount > 0)
{
var (a, b, f) = Find(ch.RotationKeys.Select(k => k.Time).ToList(), t);
var q = NQuat.Normalize(NQuat.Slerp(Q(ch.RotationKeys[a].Value), Q(ch.RotationKeys[b].Value), f));
o[3] = q.X; o[4] = q.Y; o[5] = q.Z; o[6] = q.W;
}
if (ch.ScalingKeyCount > 0)
{
var (a, b, f) = Find(ch.ScalingKeys.Select(k => k.Time).ToList(), t);
var s = Vector3.Lerp(V(ch.ScalingKeys[a].Value), V(ch.ScalingKeys[b].Value), f);
o[7] = s.X; o[8] = s.Y; o[9] = s.Z;
}
return o;
}
static (int, int, float) Find(List<double> times, double t)
{
if (times.Count == 1 || t <= times[0]) return (0, 0, 0);
for (int i = 1; i < times.Count; i++)
if (times[i] >= t) return (i - 1, i, (float)((t - times[i - 1]) / Math.Max(1e-9, times[i] - times[i - 1])));
return (times.Count - 1, times.Count - 1, 0);
}
static Vector3 V(Vector3D v) => new(v.X, v.Y, v.Z);
static NQuat Q(Assimp.Quaternion q) => new(q.X, q.Y, q.Z, q.W);
/// Farbe je Punkt vom nächstgelegenen Punkt des bemalten Modells (beide auf Füße/Mitte/Höhe normiert).
static byte[][] Colours(Vector3[] pos, string painted)
{
Vector3[] src; byte[][] cols;
if (painted.EndsWith(".pcol", StringComparison.OrdinalIgnoreCase))
{
// paint_mesh: int Anzahl, je Punkt 3 float + 4 byte RGBA
using var r = new BinaryReader(File.OpenRead(painted));
int n = r.ReadInt32();
src = new Vector3[n]; cols = new byte[n][];
for (int i = 0; i < n; i++) { src[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); cols[i] = r.ReadBytes(4); }
}
else
{
var m = Load(painted).Meshes.OrderByDescending(x => x.VertexCount).First();
src = m.Vertices.Select(v => new Vector3(v.X, v.Y, v.Z)).ToArray();
cols = m.VertexColorChannels[0].Select(c => new[] { B(c.R), B(c.G), B(c.B), (byte)255 }).ToArray();
}
var a = Normalize(pos); var b = Normalize(src);
// Gitter für die Suche
const float CELL = 0.03f;
var grid = new Dictionary<(int, int, int), List<int>>();
(int, int, int) Key(Vector3 p) => ((int)MathF.Floor(p.X / CELL), (int)MathF.Floor(p.Y / CELL), (int)MathF.Floor(p.Z / CELL));
for (int i = 0; i < b.Length; i++) { var k = Key(b[i]); if (!grid.TryGetValue(k, out var l)) grid[k] = l = new(); l.Add(i); }
var result = new byte[pos.Length][];
double far = 0;
Parallel.For(0, a.Length, i =>
{
var (x, y, z) = Key(a[i]);
int best = -1; float bd = float.MaxValue;
for (int r = 1; r <= 8 && best < 0; r++)
for (int dx = -r; dx <= r; dx++) for (int dy = -r; dy <= r; dy++) for (int dz = -r; dz <= r; dz++)
if (grid.TryGetValue((x + dx, y + dy, z + dz), out var l))
foreach (int j in l) { float d = Vector3.DistanceSquared(a[i], b[j]); if (d < bd) { bd = d; best = j; } }
result[i] = best >= 0 ? cols[best] : new byte[] { 128, 128, 128, 255 };
if (best >= 0) lock (result) far = Math.Max(far, Math.Sqrt(bd));
});
Console.WriteLine($" Farbe aus {painted}: {src.Length} Punkte, größter Abstand {far:0.000} (Höhe = 1)");
return result;
}
static byte B(float f) => (byte)Math.Clamp((int)MathF.Round(f * 255), 0, 255);
static Vector3[] Normalize(Vector3[] p)
{
var lo = p.Aggregate(Vector3.Min); var hi = p.Aggregate(Vector3.Max);
float h = hi.Y - lo.Y;
var c = new Vector3((lo.X + hi.X) / 2, lo.Y, (lo.Z + hi.Z) / 2);
return p.Select(v => (v - c) / h).ToArray();
}
/// Netz (mit UVs) als OBJ + MTL für Mixamo: ohne Skelett, Punkte verschweißt. Optional die Textur
/// (PNG/JPG) daneben; die MTL verweist auf sie.
static int ToObj(string input, string output, string? texture)
{
var ctx = new AssimpContext();
var s = ctx.ImportFile(input, PostProcessSteps.Triangulate | PostProcessSteps.JoinIdenticalVertices);
var inv = System.Globalization.CultureInfo.InvariantCulture;
string name = Path.GetFileNameWithoutExtension(output);
using (var w = new StreamWriter(output))
{
w.WriteLine($"mtllib {name}.mtl");
int baseV = 1;
foreach (var m in s.Meshes)
{
foreach (var v in m.Vertices) w.WriteLine(string.Format(inv, "v {0} {1} {2}", v.X, v.Y, v.Z));
bool uv = m.HasTextureCoords(0);
if (uv) foreach (var t in m.TextureCoordinateChannels[0]) w.WriteLine(string.Format(inv, "vt {0} {1}", t.X, t.Y));
w.WriteLine("usemtl skin");
foreach (var f in m.Faces)
{
if (f.IndexCount != 3) continue;
var ix = f.Indices;
w.WriteLine(uv ? $"f {ix[0] + baseV}/{ix[0] + baseV} {ix[1] + baseV}/{ix[1] + baseV} {ix[2] + baseV}/{ix[2] + baseV}"
: $"f {ix[0] + baseV} {ix[1] + baseV} {ix[2] + baseV}");
}
baseV += m.VertexCount;
}
}
using (var w = new StreamWriter(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(output))!, name + ".mtl")))
{
w.WriteLine("newmtl skin"); w.WriteLine("Kd 1 1 1");
if (texture != null) w.WriteLine("map_Kd " + Path.GetFileName(texture));
}
Console.WriteLine($"{output}: {s.Meshes.Sum(m => m.VertexCount)} Punkte, {s.Meshes.Sum(m => m.FaceCount)} Dreiecke");
return 0;
}
static void Info(Scene s)
{
Console.WriteLine($"meshes {s.MeshCount} anims {s.AnimationCount}");
foreach (var m in s.Meshes) Console.WriteLine($" mesh {m.Name} v{m.VertexCount} f{m.FaceCount} bones {m.BoneCount} colors {m.HasVertexColors(0)}");
foreach (var a in s.Animations) Console.WriteLine($" anim {a.Name} {a.DurationInTicks / a.TicksPerSecond:0.00}s ch {a.NodeAnimationChannelCount}: " + string.Join(", ", a.NodeAnimationChannels.Take(6).Select(c => $"{c.NodeName} p{c.PositionKeyCount} r{c.RotationKeyCount}")));
void P(Node n, int d) { Console.WriteLine(new string(' ', d) + n.Name); foreach (var c in n.Children) P(c, d + 1); }
P(s.RootNode, 0);
}
}