Files
GladiatorIdle/Mono/Gfx/Model3D.cs

1072 lines
58 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace GladiatorIdle.Gfx
{
/// Punkt mit Lage, Normale und Farbe (BasicEffect mit Licht und Punktfarben).
internal struct VertexPNC : IVertexType
{
public Vector3 Position, Normal;
public Color Color;
public static readonly VertexDeclaration Decl = new(
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
new VertexElement(24, VertexElementFormat.Color, VertexElementUsage.Color, 0));
VertexDeclaration IVertexType.VertexDeclaration => Decl;
}
/// Wie <see cref="VertexPNC"/>, dazu Texturkoordinaten (Figuren mit Textur, z. B. aus Meshy).
internal struct VertexPNCT : IVertexType
{
public Vector3 Position, Normal;
public Color Color;
public Vector2 Uv;
public static readonly VertexDeclaration Decl = new(
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
new VertexElement(24, VertexElementFormat.Color, VertexElementUsage.Color, 0),
new VertexElement(28, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0));
VertexDeclaration IVertexType.VertexDeclaration => Decl;
}
/// <summary>
/// 3D-Figur mit Skelett aus einer .gim-Datei (fbx2gim aus _Tools/ModelTools: Mixamo-Figur +
/// Bewegungen). Die Verformung rechnet der Prozessor (wenige zehntausend Punkte), Clips werden
/// beim Wechsel kurz überblendet. Teamfarbe: Magenta-Punkte wie bei den Sprites umgefärbt.
/// </summary>
internal sealed class Model3D
{
public sealed class Clip { public string Name = ""; public float Fps; public int Frames; public float[] Data = null!; public float Length => (Frames - 1) / Fps; }
readonly string[] _names;
readonly int[] _parent;
readonly float[] _rest; // 10 je Knochen
readonly Matrix[] _offset;
readonly Vector3[] _pos, _nrm;
readonly Color[] _baseCol;
readonly byte[] _bi;
readonly float[] _bw;
public readonly int[] Indices;
public readonly List<Clip> Clips = new();
public readonly VertexPNCT[] Vertices;
public BoundingBox Bounds { get; }
Texture2D? _texture;
Texture2D? _painted;
/// Maßstab: Modell-Einheiten je Zentimeter (Mixamo-Figuren gibt es in cm und in m).
public readonly float Unit;
readonly float[] _pose, _from; // aktuelle und überblendete Haltung (10 je Knochen)
readonly Matrix[] _global, _skin;
int _color = -1;
public int BoneCount => _names.Length;
public static Model3D? Load(string name) => Load(Assets.Device, name);
// Vorlagen je Datei: einmal gelesen, danach teilt jede Figur Gitter, Gewichte, Clips und Textur
// und hat nur eigene Haltung, eigene Puffer und eigene Waffen (Duellstart ohne Plattenzugriff).
static readonly Dictionary<string, Model3D?> _templates = new();
// im Hintergrund vorbereitete Vorlagen (Datei gelesen, Textur entpackt, Stufen gerechnet)
static readonly System.Collections.Concurrent.ConcurrentDictionary<string, Model3D> _parsed = new();
static string? PathOf(string name) => Assets.RootDir is string root ? Path.Combine(root, "Models", name + ".gim") : null;
/// Beim Start: alle Figuren im Hintergrund vorbereiten, damit später nichts ruckelt.
public static void PreloadAll()
{
if (Assets.RootDir is not string root || !Directory.Exists(Path.Combine(root, "Models"))) return;
var names = Directory.GetFiles(Path.Combine(root, "Models"), "*.gim").Select(f => Path.GetFileNameWithoutExtension(f)!).ToArray();
System.Threading.Tasks.Task.Run(() =>
{
foreach (var n in names)
{
if (_parsed.ContainsKey(n)) continue;
try { _parsed[n] = new Model3D(PathOf(n)!); } catch { /* beim Bedarf noch einmal auf dem Hauptthread */ }
}
});
}
public static Model3D? Load(GraphicsDevice gd, string name)
{
if (!_templates.TryGetValue(name, out var t))
{
var sw = System.Diagnostics.Stopwatch.StartNew();
string? path = PathOf(name);
bool pre = _parsed.TryRemove(name, out t);
if (!pre) t = path != null && File.Exists(path) ? new Model3D(path) : null;
t?.EnsureTexture();
_templates[name] = t;
if (DevShot.Active) DevShot.Log($"timing: model {name} {(pre ? "from preload" : "loaded")} in {sw.ElapsedMilliseconds} ms");
}
return t == null ? null : new Model3D(t);
}
Color[][]? _texLevels; int _texW, _texH;
Assets.PaintInfo? _texInfo;
// vorgerechnete Hauttöne (Stufen + Teamfarben-Daten), geteilt mit allen Figuren dieser Vorlage
Dictionary<float, (Color[][] Levels, Assets.PaintInfo Info)> _skinPre = new();
/// Textur aus den vorbereiteten Stufen hochladen (Hauptthread).
void EnsureTexture()
{
if (_texture != null || _texLevels == null) return;
_texture = Assets.Upload(_texLevels, _texW, _texH);
Assets.RegisterPixels(_texture, _texLevels[0]);
if (_texInfo != null) Assets.RegisterPaintInfo(_texture, _texInfo);
_texLevels = null;
}
/// Neue Figur auf den geteilten Daten einer Vorlage.
Model3D(Model3D src)
{
_names = src._names; _parent = src._parent; _rest = src._rest; _offset = src._offset;
_pos = src._pos; _nrm = src._nrm; _baseCol = src._baseCol; _bi = src._bi; _bw = src._bw;
Indices = src.Indices;
Clips = src.Clips;
Vertices = (VertexPNCT[])src.Vertices.Clone();
Bounds = src.Bounds;
_texture = src._texture;
_skinPre = src._skinPre;
Unit = src.Unit;
_pose = (float[])_rest.Clone(); _from = (float[])_rest.Clone();
_global = new Matrix[_names.Length]; _skin = new Matrix[_names.Length];
}
Model3D(string path)
{
using var r = new BinaryReader(File.OpenRead(path), Encoding.UTF8);
string magic = Encoding.ASCII.GetString(r.ReadBytes(4));
if (magic != "GIM1" && magic != "GIM2") throw new InvalidDataException(path);
bool v2 = magic == "GIM2";
var uv = new List<Vector2>();
int nb = r.ReadInt32();
_names = new string[nb]; _parent = new int[nb]; _rest = new float[nb * 10]; _offset = new Matrix[nb];
for (int b = 0; b < nb; b++)
{
_names[b] = r.ReadString(); _parent[b] = r.ReadInt32();
for (int k = 0; k < 10; k++) _rest[b * 10 + k] = r.ReadSingle();
r.ReadByte();
var m = new float[16];
for (int k = 0; k < 16; k++) m[k] = r.ReadSingle();
_offset[b] = new Matrix(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]);
}
int nv = r.ReadInt32();
_pos = new Vector3[nv]; _nrm = new Vector3[nv]; _baseCol = new Color[nv]; _bi = new byte[nv * 4]; _bw = new float[nv * 4];
for (int i = 0; i < nv; i++)
{
_pos[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
_nrm[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
uv.Add(v2 ? new Vector2(r.ReadSingle(), r.ReadSingle()) : Vector2.Zero);
var c = r.ReadBytes(4); _baseCol[i] = new Color(c[0], c[1], c[2], c[3]);
r.Read(_bi, i * 4, 4);
for (int k = 0; k < 4; k++) _bw[i * 4 + k] = r.ReadSingle();
}
Indices = new int[r.ReadInt32()];
for (int i = 0; i < Indices.Length; i++) Indices[i] = r.ReadInt32();
int nc = r.ReadInt32();
for (int c = 0; c < nc; c++)
{
var clip = new Clip { Name = r.ReadString(), Fps = r.ReadSingle(), Frames = r.ReadInt32() };
clip.Data = new float[clip.Frames * nb * 10];
for (int k = 0; k < clip.Data.Length; k++) clip.Data[k] = r.ReadSingle();
Clips.Add(clip);
}
NormalizeRoots(Path.GetFileNameWithoutExtension(path));
if (v2 && r.ReadInt32() is int texLen && texLen > 0)
{
// PNG ohne Grafikkarte entpacken (auch im Hintergrund), Stufen gegen Flimmern klein/weit weg
var img = StbImageSharp.ImageResult.FromMemory(r.ReadBytes(texLen), StbImageSharp.ColorComponents.RedGreenBlueAlpha);
var px = new Color[img.Width * img.Height];
for (int i = 0; i < px.Length; i++) px[i] = new Color(img.Data[i * 4], img.Data[i * 4 + 1], img.Data[i * 4 + 2], img.Data[i * 4 + 3]);
_texW = img.Width; _texH = img.Height;
_texLevels = Assets.MipLevels(px, _texW, _texH);
_texInfo = Assets.ComputePaintInfo(px);
// Vorlagen 2/3 der Gladiatoren nutzen diese Figur mit dunkler bzw. heller Haut: schon jetzt rechnen
if (Path.GetFileName(path).StartsWith("hero_"))
foreach (float dark in new[] { 1f, -1f })
{
var skin = SkinPixels(px, dark);
_skinPre[dark] = (Assets.MipLevels(skin, _texW, _texH), Assets.ComputePaintInfo(skin));
}
}
Vertices = new VertexPNCT[nv];
for (int i = 0; i < nv; i++) Vertices[i] = new VertexPNCT { Position = _pos[i], Normal = _nrm[i], Color = _baseCol[i], Uv = uv[i] };
Bounds = BoundingBox.CreateFromPoints(_pos);
_pose = (float[])_rest.Clone(); _from = (float[])_rest.Clone();
_global = new Matrix[nb]; _skin = new Matrix[nb];
// Kopf bis Knöchel etwa 150 cm bei einer 180-cm-Figur
int head = Bone("Head"), foot = Bone("LeftFoot");
Unit = head >= 0 && foot >= 0 ? Vector3.Distance(BindGlobal(head).Translation, BindGlobal(foot).Translation) / 150f : 1f;
}
public Clip? Find(string name) => Clips.Find(c => c.Name == name);
/// Bewegungen, die mit einer anderen Figur geladen wurden, haben die Hüfte (Wurzel-Knochen) in
/// anderer Höhe oder anderem Maßstab – die Figur schwebt oder versinkt. Je Clip die Wurzel-Bewegung
/// gemeinsam skalieren, sodass ihre Höhe zu den übrigen Clips der Figur passt.
void NormalizeRoots(string name)
{
int nb = _names.Length;
for (int bone = 0; bone < nb; bone++)
{
if (_parent[bone] >= 0 || Clips.Count < 3) continue;
// Bezug: Mittelwert der Hüfthöhe im ersten Bild über alle Clips (die meisten passen zusammen)
var ys = Clips.Select(c => MathF.Abs(c.Data[bone * 10 + 1])).Where(y => y > 1e-4f).OrderBy(y => y).ToArray();
if (ys.Length == 0) continue;
float median = ys[ys.Length / 2];
// Ausreißer (Faktor > 2): gemeinsamen Faktor nehmen, damit echte Unterschiede (Ducken) bleiben
var odd = Clips.Where(c => { float y = MathF.Abs(c.Data[bone * 10 + 1]); return y > 1e-4f && (y > median * 2 || y < median / 2); }).ToList();
if (odd.Count == 0) continue;
var ratios = odd.Select(c => median / MathF.Abs(c.Data[bone * 10 + 1])).OrderBy(k => k).ToArray();
float k = ratios[ratios.Length / 2];
foreach (var clip in odd)
{
for (int f = 0; f < clip.Frames; f++)
{
int o = (f * nb + bone) * 10;
clip.Data[o] *= k; clip.Data[o + 1] *= k; clip.Data[o + 2] *= k;
}
if (DevShot.Active) DevShot.Log($"root {name}/{clip.Name}: hips scaled x{k:0.###} (median {median:0.###})");
}
}
}
/// Teamfarbe (Index in Appearance.Colors), -1 = Originalfarben.
/// Hautton dunkler (0 = unverändert, 1 = dunkle Haut, −1 = helle, blasse Haut): für Aussehen-Vorlagen mit dunkler Haut, solange
/// sie das Modell einer anderen Vorlage nutzen. Haut erkannt an Farbton (Orange/Rosa), mittlerer
/// Sättigung und Helligkeit — Leder ist dunkler, Metall ungesättigt, Teamfarbe magenta.
public void SetSkin(float dark)
{
if (_texture == null || dark == 0) return;
if (_skins.TryGetValue((_texture, dark), out var done)) { _texture = done; _color = -2; return; }
if (_skinPre.TryGetValue(dark, out var pre))
{
var tex = Assets.Upload(pre.Levels, _texture.Width, _texture.Height);
Assets.RegisterPixels(tex, pre.Levels[0]);
Assets.RegisterPaintInfo(tex, pre.Info);
_skins[(_texture, dark)] = tex;
_texture = tex; _color = -2;
return;
}
var original = _texture; float key = dark;
var data = SkinPixels(Assets.KnownPixels(_texture) ?? GetPixels(_texture), dark);
_texture = Assets.MipTexture(data, _texture.Width, _texture.Height);
Assets.RegisterPixels(_texture, data);
_skins[(original, key)] = _texture;
_color = -2; // Teamfarbe neu auf die geänderte Textur
}
/// Hautton umrechnen (reine Pixel-Rechnung, auch im Hintergrund).
static Color[] SkinPixels(Color[] src, float dark)
{
bool pale = dark < 0; dark = MathF.Abs(dark); // negativ: hellere, blassere Haut
var data = (Color[])src.Clone();
System.Threading.Tasks.Parallel.For(0, (data.Length + 16383) / 16384, chunk =>
{
for (int i = chunk * 16384, end = Math.Min(data.Length, (chunk + 1) * 16384); i < end; i++)
{
var c = data[i];
float r = c.R / 255f, g = c.G / 255f, b = c.B / 255f;
float max = MathF.Max(r, MathF.Max(g, b)), min = MathF.Min(r, MathF.Min(g, b)), d = max - min;
if (max < 0.38f || d < 0.04f) continue;
float sat = d / max;
float h = max == r ? 60 * (((g - b) / d) % 6) : max == g ? 60 * ((b - r) / d + 2) : 60 * ((r - g) / d + 4);
if (h < 0) h += 360;
float wh = Band(h, 2, 10, 34, 46), ws = Band(sat, 0.12f, 0.2f, 0.62f, 0.75f), wv = Band(max, 0.38f, 0.48f, 1.1f, 1.2f);
float w = wh * ws * wv * dark;
if (w <= 0) continue;
// dunkle, warme Haut: Helligkeit stark senken, Sättigung leicht anheben
float nv = pale ? MathF.Min(1, max * (1 + 0.16f * w)) : max * (1 - 0.58f * w);
float ns = pale ? sat * (1 - 0.35f * w) : MathF.Min(1, sat * (1 + 0.25f * w));
float k = nv / max;
float nr = r * k, ng = g * k, nb = b * k;
float gray = (nr + ng + nb) / 3, boost = ns / MathF.Max(sat, 1e-3f);
nr = gray + (nr - gray) * boost; ng = gray + (ng - gray) * boost; nb = gray + (nb - gray) * boost;
data[i] = new Color(Math.Clamp(nr, 0, 1), Math.Clamp(ng, 0, 1), Math.Clamp(nb, 0, 1), c.A / 255f);
}
});
return data;
}
static readonly Dictionary<(Texture2D, float), Texture2D> _skins = new();
static Color[] GetPixels(Texture2D t) { var d = new Color[t.Width * t.Height]; t.GetData(d); return d; }
/// 0 unterhalb a, 1 zwischen b und c, 0 oberhalb d, linear dazwischen.
static float Band(float x, float a, float b, float c, float d) =>
x <= a || x >= d ? 0 : x < b ? (x - a) / (b - a) : x > c ? (d - x) / (d - c) : 1;
public void SetColor(int index)
{
if (index == _color) return;
_color = index;
var cols = (Color[])_baseCol.Clone();
if (index >= 0) Assets.PaintPixels(cols, index);
for (int i = 0; i < cols.Length; i++) Vertices[i].Color = cols[i];
_dirty = true;
if (_texture != null) _painted = index >= 0 ? Assets.Paint(_texture, index) : _texture;
foreach (var p in Props)
{
var pc = (Color[])p.Base.Clone();
if (index >= 0) Assets.PaintPixels(pc, index);
for (int i = 0; i < pc.Length; i++) p.V[i].Color = pc[i];
}
}
/// Überblendung beginnen: die jetzige Haltung wird zum Ausgangspunkt.
public void BeginBlend() { if (_posed) Array.Copy(_pose, _from, _pose.Length); }
bool _posed; // erst nach der ersten Haltung überblenden (die Ruhehaltung der Figurdatei kann andere Einheiten haben)
/// Haltung aus einem Clip zur Zeit t; blend 0..1 mischt von der gemerkten Haltung her.
/// inPlace hält die Hüfte waagerecht am Platz (Laufen auf der Stelle).
public void Pose(Clip clip, float t, bool loop, float blend = 1, bool inPlace = true, bool skin = true, float rootY = 1)
{
int nb = _names.Length;
if (!_posed) { blend = 1; _posed = true; }
float f = t * clip.Fps;
f = loop ? f % (clip.Frames - 1) : Math.Min(f, clip.Frames - 1);
if (f < 0) f += clip.Frames - 1;
int a = (int)f, b = Math.Min(a + 1, clip.Frames - 1);
float k = f - a;
for (int bone = 0; bone < nb; bone++)
{
int pa = (a * nb + bone) * 10, pb = (b * nb + bone) * 10, o = bone * 10;
var tr = Vector3.Lerp(V(clip.Data, pa), V(clip.Data, pb), k);
var q = Quaternion.Slerp(Q(clip.Data, pa), Q(clip.Data, pb), k);
if (inPlace && _parent[bone] < 0) { var r0 = V(clip.Data, bone * 10); tr.X = r0.X; tr.Z = r0.Z; tr.Y = r0.Y + (tr.Y - r0.Y) * rootY; } // rootY: Sprunghöhe
if (blend < 1)
{
tr = Vector3.Lerp(V(_from, o), tr, blend);
q = Quaternion.Slerp(Q(_from, o), q, blend);
}
_pose[o] = tr.X; _pose[o + 1] = tr.Y; _pose[o + 2] = tr.Z;
_pose[o + 3] = q.X; _pose[o + 4] = q.Y; _pose[o + 5] = q.Z; _pose[o + 6] = q.W;
_pose[o + 7] = clip.Data[pa + 7]; _pose[o + 8] = clip.Data[pa + 8]; _pose[o + 9] = clip.Data[pa + 9];
}
Bones();
if (skin) { SkinVertices(); _dirty = true; AvoidBody(); }
}
/// Trefferzeitpunkt eines Schlag-Clips: der Schwertarm am weitesten vorn (Blickrichtung +Z).
public float ImpactTime(Clip clip)
{
if (_impact.TryGetValue(clip, out float t)) return t;
var keep = (float[])_pose.Clone(); bool posed = _posed;
int hand = Bone("RightHand");
float best = float.MinValue; t = clip.Length * 0.5f;
// Zweihand-Waffe: Ausholen hinter dem Kopf, dann Schlag nach vorn – Treffer, wenn die Spitze
// am schnellsten nach vorn schnellt (die höchste Hand wäre mitten im Ausholen).
var weapon = _twoHand ? Props.Find(p => !p.Shield && !p.NoAvoid && p.Bone == hand) : null;
var dirZ = new List<float>();
for (int f = 0; f < clip.Frames && hand >= 0; f++)
{
_posed = true;
Pose(clip, f / clip.Fps, false, 1, true, skin: false);
if (weapon != null)
{
var m = weapon.Local * _global[hand];
dirZ.Add(Vector3.Normalize(new Vector3(m.M11, m.M12, m.M13)).Z);
continue;
}
float z = _global[hand].Translation.Z;
if (z > best) { best = z; t = f / clip.Fps; }
}
if (dirZ.Count > 0)
{
// tiefstes Ausholen (Spitze am weitesten nach hinten), danach erster Moment mit Spitze nach vorn
int end = Math.Max(1, (int)(dirZ.Count * 0.85f)); // Rückkehr in die Grundhaltung zählt nicht
int back = 0;
for (int f = 1; f < end; f++) if (dirZ[f] < dirZ[back]) back = f;
int hit = -1;
for (int f = back; f < end && hit < 0; f++) if (dirZ[f] > 0.6f) hit = f;
if (hit < 0) { hit = back; for (int f = back; f < end; f++) if (dirZ[f] > dirZ[hit]) hit = f; }
t = hit / clip.Fps;
}
Array.Copy(keep, _pose, keep.Length); _posed = posed; Bones();
return _impact[clip] = t;
}
readonly Dictionary<Clip, float> _impact = new();
bool _twoHand; // Waffe beidhändig (Großschwert-Bewegungen), siehe AimBlades
/// Figur auf 180 Einheiten Höhe, Füße auf y = 0, mittig (aus der jetzigen Haltung, robust gegen Ausreißer).
public Matrix FitNow()
{
// je Achse einmal sortieren (jeder 3. Punkt reicht für die Quantile)
float[] Sorted(Func<Vector3, float> axis)
{
var a = new float[(Vertices.Length + 2) / 3];
for (int i = 0; i < a.Length; i++) a[i] = axis(Vertices[i * 3].Position);
Array.Sort(a);
return a;
}
static float Q(float[] a, float q) => a[(int)(q * (a.Length - 1))];
var ys = Sorted(p => p.Y); var xs = Sorted(p => p.X); var zs = Sorted(p => p.Z);
float y0 = Q(ys, 0.002f), y1 = Q(ys, 0.998f);
float cx = (Q(xs, 0.01f) + Q(xs, 0.99f)) / 2, cz = (Q(zs, 0.01f) + Q(zs, 0.99f)) / 2;
return Matrix.CreateTranslation(-cx, -y0, -cz) * Matrix.CreateScale(180 / MathF.Max(1e-3f, y1 - y0));
}
static Vector3 V(float[] d, int o) => new(d[o], d[o + 1], d[o + 2]);
static Quaternion Q(float[] d, int o) => new(d[o + 3], d[o + 4], d[o + 5], d[o + 6]);
void Bones()
{
for (int b = 0; b < _names.Length; b++)
{
int o = b * 10;
var local = Matrix.CreateScale(_pose[o + 7], _pose[o + 8], _pose[o + 9]) * Matrix.CreateFromQuaternion(Q(_pose, o)) * Matrix.CreateTranslation(V(_pose, o));
_global[b] = _parent[b] >= 0 ? local * _global[_parent[b]] : local; // Eltern stehen vorher
_skin[b] = _offset[b] * _global[b];
}
}
void SkinVertices()
{
System.Threading.Tasks.Parallel.For(0, (_pos.Length + 4095) / 4096, chunk =>
{
for (int i = chunk * 4096, end = Math.Min(_pos.Length, i + 4096); i < end; i++)
{
Vector3 p = Vector3.Zero, n = Vector3.Zero;
for (int k = 0; k < 4; k++)
{
float w = _bw[i * 4 + k];
if (w <= 0) continue;
ref var m = ref _skin[_bi[i * 4 + k]];
p += Vector3.Transform(_pos[i], m) * w;
n += Vector3.TransformNormal(_nrm[i], m) * w;
}
Vertices[i].Position = p;
Vertices[i].Normal = n;
}
});
}
/// aura: nur Umriss in der Farbe des Effekts (additiv, ohne Tiefe), für Leuchten hinter der Figur.
IndexBuffer? _ib;
DynamicVertexBuffer? _vb;
bool _dirty;
/// Zeichnen; <paramref name="depth"/>/<paramref name="blend"/> überschreiben die Zustände (Schatten auf dem Boden).
public void Draw(GraphicsDevice gd, BasicEffect fx, bool aura = false, DepthStencilState? depth = null, BlendState? blend = null)
{
gd.DepthStencilState = depth ?? (aura ? DepthStencilState.None : DepthStencilState.Default);
gd.BlendState = blend ?? (aura ? BlendState.Additive : BlendState.Opaque);
gd.RasterizerState = RasterizerState.CullNone;
fx.TextureEnabled = _texture != null && !aura && blend == null;
fx.Texture = _painted ?? _texture;
// Indizes liegen einmal auf der Grafikkarte, Punkte nur nach einer neuen Haltung neu
if (_ib == null)
{
_ib = new IndexBuffer(gd, IndexElementSize.ThirtyTwoBits, Indices.Length, BufferUsage.WriteOnly);
_ib.SetData(Indices);
_vb = new DynamicVertexBuffer(gd, VertexPNCT.Decl, Vertices.Length, BufferUsage.WriteOnly);
_dirty = true;
}
if (_dirty || _vb!.IsContentLost) { _vb!.SetData(Vertices, 0, Vertices.Length, SetDataOptions.Discard); _dirty = false; }
gd.SetVertexBuffer(_vb);
gd.Indices = _ib;
foreach (var pass in fx.CurrentTechnique.Passes)
{
pass.Apply();
gd.SamplerStates[0] = SamplerState.AnisotropicClamp;
gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, Indices.Length / 3);
}
fx.TextureEnabled = false;
var world = fx.World;
foreach (var p in Props)
{
fx.World = p.World * p.Correction * world;
foreach (var pass in fx.CurrentTechnique.Passes)
{
pass.Apply();
gd.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, p.V, 0, p.V.Length, p.I, 0, p.I.Length / 3);
}
}
fx.World = world;
}
// ── Waffen: einfache Formen, an einem Handknochen befestigt ──────────
public sealed class Prop
{
public int Bone; public Matrix Local;
public bool Shield; public float Height, Width, Bend, Length; // Maße in cm (Schild: Höhe x, Breite y; Klinge: Länge entlang x)
public Matrix Correction = Matrix.Identity; // Ausweichen vor dem eigenen Körper (Modell-Raum)
public float Push, Angle; public Vector3 Axis = Vector3.Up;
public bool NoAvoid; // weicht nicht aus (Netz)
public bool Upright; // Schild aufrecht vor der Hand statt an der Handdrehung
public Matrix World = Matrix.Identity; // Lage im Modell-Raum (vor dem Ausweichen)
public VertexPNC[] V = Array.Empty<VertexPNC>(); public int[] I = Array.Empty<int>(); public Color[] Base = Array.Empty<Color>();
}
public readonly List<Prop> Props = new();
public int Bone(string name) => Array.FindIndex(_names, n => n == "mixamorig:" + name || n == name);
/// Lage eines Knochens in der Ruhehaltung (Netz-Raum).
Matrix BindGlobal(int b) => Matrix.Invert(_offset[b]);
Vector3 BindPos(string bone)
{
int b = Bone(bone);
if (b >= 0) return BindGlobal(b).Translation;
// Skelett ohne Finger (Mixamo mit kleinerer Skelettstufe): Fingerpunkte aus einem Rahmen, den das
// Skelett selbst liefert (Unterarm, oben = Hüfte zum Kopf, seitlich), mit Werten gemittelt aus vier
// vollständigen Figuren (Längen in cm bei 25 cm Unterarm). Unabhängig davon, wie die Figur im
// Raum liegt (Meshy-Figuren sind in der Grundhaltung z-oben).
string side = bone.StartsWith("Left") ? "Left" : "Right";
int hand = Bone(side + "Hand"), fore = Bone(side + "ForeArm"), hips = Bone("Hips"), head = Bone("Head");
if (hand < 0 || fore < 0 || hips < 0 || head < 0) return Vector3.Zero;
var h = BindGlobal(hand).Translation;
float cm = Vector3.Distance(h, BindGlobal(fore).Translation) / 25.25f;
var a = Vector3.Normalize(h - BindGlobal(fore).Translation);
var up = BindGlobal(head).Translation - BindGlobal(hips).Translation;
var u = Vector3.Normalize(up - a * Vector3.Dot(up, a));
var sd = Vector3.Cross(a, u);
float sg = side == "Right" ? -1 : 1;
Vector3 F(float x, float y, float z) => a * x + u * y + sd * (z * sg);
var across = Vector3.Normalize(F(0.2f, 0.57f, 0.77f));
var mid = h + F(13.8f, 1.4f, 0) * cm;
return bone[side.Length..] switch
{
"HandMiddle1" => mid,
"HandIndex1" => mid + across * 3.6f * cm,
"HandPinky1" => mid - across * 3.5f * cm,
"HandThumb1" => h + F(3.9f, -0.4f, 2.5f) * cm,
_ => h
};
}
/// Rahmen in der Ruhehaltung (Achsen x, y, z, Ursprung) → lokal zum Knochen.
Matrix Attach(int bone, Vector3 x, Vector3 y, Vector3 origin)
{
x.Normalize(); var z = Vector3.Normalize(Vector3.Cross(x, y)); y = Vector3.Cross(z, x);
var frame = new Matrix(x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X, z.Y, z.Z, 0, origin.X, origin.Y, origin.Z, 1);
return frame * _offset[bone]; // Rahmen · (Knochen in Ruhe)⁻¹
}
/// Ausrüstung nach Figur: Retiarius Dreizack und Netz, sonst Gladius und Scutum.
public void Arm(string art)
{
bool Is(params string[] keys) => keys.Any(k => art.Contains(k));
if (Is("retiarius")) { AddTrident(); AddNet(); }
else if (Is("thraex")) { AddSword(kind: "sica"); AddShield(kind: "parmula"); }
else if (Is("hoplomachus", "eques")) { AddSpear(); AddShield(kind: "round"); }
else if (Is("recruit")) { AddSword(kind: "rudis"); AddShield(); }
else if (Is("slave")) AddSword(kind: "club");
else if (Is("dimachaerus")) { AddSword(); AddSword("Left"); }
else if (Is("brawler")) { AddCestus(); AddCestus("Left"); } // Faustkämpfer
else if (Is("sagittarius", "essedarius", "laquearius", "doctore")) { AddSword(); AddShield(kind: "round"); }
else { AddSword(); AddShield(); } // Murmillo, Secutor, Provocator, Prätorianer, Crupellarius, Champions
AimBlades();
}
/// Klinge zum Gegner: im Treffermoment des Schlags soll die Waffe so zum Unterarm liegen wie bei den
/// Figuren mit sauberem Skelett. Bei manchen Skeletten ist die Hand nach dem Übertragen der
/// Bewegungen anders gedreht (Klinge nach hinten oder schräg) – dann wird die Waffe für diese Figur
/// einmal so gedreht, dass sie dort liegt, und bleibt in dieser Lage fest an der Hand.
void AimBlades()
{
var clip = Find("slash") ?? (Clips.Count > 0 ? Clips[0] : null);
if (clip == null) return;
var keep = (float[])_pose.Clone(); bool posed = _posed;
_posed = true;
// Zweihand-Bewegungen (Großschwert-Pack): in der Grundhaltung liegen beide Hände am Griff –
// dann zeigt die Waffe entlang der Linie linke → rechte Hand, gemessen in der Grundhaltung.
int rh = Bone("RightHand"), lh = Bone("LeftHand");
bool twoHand = false;
if (Find("idle") is { } idle && rh >= 0 && lh >= 0)
{
Pose(idle, 0, false, 1, true, skin: false);
var gap = _global[rh].Translation - _global[lh].Translation;
float fore = Vector3.Distance(_global[rh].Translation, _global[_parent[rh]].Translation);
twoHand = gap.Length() < fore * 0.8f;
}
_twoHand = twoHand;
float t = twoHand ? 0 : ImpactTime(clip);
if (twoHand) clip = Find("idle")!;
Pose(clip, t, false, 1, true, skin: false);
foreach (var p in Props)
{
if (p.Shield || p.NoAvoid) continue;
var m = p.Local * _global[p.Bone];
var dir = Vector3.Normalize(new Vector3(m.M11, m.M12, m.M13));
var (fa, fu, fs) = ArmFrame(p.Bone);
BladeLog = $"blade z {dir.Z:0.00} arm {Vector3.Dot(dir, fa):0.000} up {Vector3.Dot(dir, fu):0.000} side {Vector3.Dot(dir, fs):0.000} twohand {twoHand}"; // i18n-ok
// Ziel: Lage wie bei den Figuren mit sauberem Skelett (gemessen an vier Figuren)
float mirror = _names[p.Bone].Contains("Left") ? -1 : 1; // linke Hand: gespiegelt
var target = twoHand && p.Bone == rh
? Vector3.Normalize(_global[rh].Translation - _global[lh].Translation)
: Vector3.Normalize(fa * 0.31f + fu * 0.36f + fs * (0.88f * mirror));
float cos = MathHelper.Clamp(Vector3.Dot(dir, target), -1, 1);
if (cos < 0.97f)
{
var axis = Vector3.Cross(dir, target);
axis = axis.LengthSquared() > 1e-8f ? Vector3.Normalize(axis) : Vector3.Normalize(new Vector3(m.M21, m.M22, m.M23));
var grip = m.Translation;
var turn = Matrix.CreateTranslation(-grip) * Matrix.CreateFromAxisAngle(axis, MathF.Acos(cos)) * Matrix.CreateTranslation(grip);
p.Local = p.Local * _global[p.Bone] * turn * Matrix.Invert(_global[p.Bone]); // fest zur Hand
BladeLog += $" -> {MathHelper.ToDegrees(MathF.Acos(cos)):0} Grad gedreht"; // i18n-ok
}
}
Array.Copy(keep, _pose, keep.Length); _posed = posed; Bones();
}
/// Rahmen am Arm in der jetzigen Haltung: Unterarm-Richtung, oben (Körper), seitlich.
(Vector3 A, Vector3 U, Vector3 S) ArmFrame(int hand)
{
int fore = _parent[hand], hips = Bone("Hips"), head = Bone("Head");
var a = Vector3.Normalize(_global[hand].Translation - _global[fore].Translation);
var up = _global[head].Translation - _global[hips].Translation;
var u = Vector3.Normalize(up - a * Vector3.Dot(up, a));
return (a, u, Vector3.Cross(a, u));
}
/// Testläufe: wie die Klinge ausgerichtet wurde.
public string BladeLog = "";
/// Griff in der Faust: x vom kleinen Finger zum Zeigefinger (Waffe), y zur Handfläche, Ursprung im Griff.
Matrix Grip(string side)
{
var h = BindPos(side + "Hand"); var m = BindPos(side + "HandMiddle1");
var ix = BindPos(side + "HandIndex1"); var pk = BindPos(side + "HandPinky1"); var th = BindPos(side + "HandThumb1");
var finger = Vector3.Normalize(m - h);
var blade = Vector3.Normalize(ix - pk);
var palm = Vector3.Normalize(Vector3.Cross(finger, blade));
if (Vector3.Dot(palm, th - h) < 0) palm = -palm;
var grip = h + (m - h) * 0.75f + palm * 2.5f * Unit;
return Matrix.CreateScale(Unit) * Attach(Bone(side + "Hand"), blade, palm, grip);
}
/// Dreizack des Retiarius, in der Mitte gefasst: Schaft nach hinten, drei Zinken nach vorn.
public void AddTrident(string side = "Right")
{
var b = new MeshBuilder();
var wood = new Color(110, 74, 42); var bronze = new Color(184, 140, 70); var steel = new Color(200, 204, 210);
b.Box(new Vector3(15, 0, 0), new Vector3(150, 2.6f, 2.6f), wood); // Schaft (-60 … +90)
b.Box(new Vector3(-61, 0, 0), new Vector3(3, 3.6f, 3.6f), bronze); // Endkappe
b.Box(new Vector3(91, 0, 0), new Vector3(4, 4, 4), bronze); // Tülle
b.Box(new Vector3(95, 0, 0), new Vector3(3, 2, 22), bronze); // Querstück
foreach (float z in new[] { -10f, 0f, 10f })
{
float len = z == 0 ? 32 : 26;
b.Box(new Vector3(96 + len / 2, 0, z), new Vector3(len, 1.4f, 1.6f), steel); // Zinke
b.Box(new Vector3(96 + len - 2, 0, z + (z >= 0 ? 1.4f : -1.4f)), new Vector3(4, 1.2f, 1.6f), steel); // Widerhaken
}
var p = b.Build(Bone(side + "Hand"), Grip(side));
p.Length = 128;
Props.Add(p);
}
/// Wurfnetz des Retiarius: gerafft in der Faust, hängt als Maschenwerk mit Bleigewichten herab.
public void AddNet(string side = "Left")
{
var b = new MeshBuilder();
var rope = new Color(176, 152, 104); var lead = new Color(90, 92, 98);
const int COLS = 6, ROWS = 8;
const float W = 36, H = 58, CORD = 0.9f;
Vector3 P(float u, float v)
{
// vom Griff nach unten (Richtung kleiner Finger = -x), unten breiter, leicht gewellt
float spread = 0.35f + 0.65f * v;
return new Vector3(-4 - v * H, MathF.Sin(u * 9 + v * 5) * 2.5f * v, (u - 0.5f) * W * spread);
}
for (int c = 0; c <= COLS; c++) // senkrechte Schnüre
for (int r = 0; r < ROWS; r++)
{
var a = P(c / (float)COLS, r / (float)ROWS); var e = P(c / (float)COLS, (r + 1) / (float)ROWS);
b.Box((a + e) / 2, new Vector3(MathF.Abs(e.X - a.X) + CORD, CORD, CORD + MathF.Abs(e.Z - a.Z)), rope);
}
for (int r = 1; r <= ROWS; r++) // waagerechte Schnüre
for (int c = 0; c < COLS; c++)
{
var a = P(c / (float)COLS, r / (float)ROWS); var e = P((c + 1) / (float)COLS, r / (float)ROWS);
b.Box((a + e) / 2, new Vector3(CORD, CORD, MathF.Abs(e.Z - a.Z) + CORD), rope);
}
for (int c = 0; c <= COLS; c++) b.Box(P(c / (float)COLS, 1) + new Vector3(-1.5f, 0, 0), new Vector3(3, 2.2f, 2.2f), lead); // Bleigewichte
b.Box(new Vector3(-2, 0, 0), new Vector3(6, 5, 9), rope); // geraffter Teil in der Faust
var p = b.Build(Bone(side + "Hand"), Grip(side));
p.NoAvoid = true;
Props.Add(p);
}
/// Cestus: Lederriemen mit Bronzebeschlag um die Faust (Faustkämpfer).
public void AddCestus(string side = "Right")
{
var b = new MeshBuilder();
var leather = new Color(96, 62, 36); var bronze = new Color(176, 136, 62);
b.Box(new Vector3(0, 0, 0), new Vector3(9, 7, 9), leather); // Riemen um die Faust
b.Box(new Vector3(4, 0, 0), new Vector3(3, 7.6f, 9.6f), bronze); // Beschlag über den Knöcheln
b.Box(new Vector3(-9, 0, 0), new Vector3(10, 6, 6), leather); // Riemen am Handgelenk
var p = b.Build(Bone(side + "Hand"), Grip(side));
p.NoAvoid = true;
Props.Add(p);
}
/// Gladius in der Faust (Knochen-Präfix "Right"/"Left"). Klinge zeigt vom kleinen Finger zum Zeigefinger.
public void AddSword(string side = "Right", string kind = "gladius")
{
var b = new MeshBuilder();
var steel = new Color(196, 200, 206); var brass = new Color(176, 136, 62); var wood = new Color(92, 58, 34);
var lightWood = new Color(150, 112, 70);
float length = 63;
switch (kind)
{
case "rudis": // Holzschwert der Rekruten
b.Box(new Vector3(-3.5f, 0, 0), new Vector3(10, 3, 3), wood);
b.Box(new Vector3(2, 0, 0), new Vector3(2, 3.6f, 8), wood);
b.Box(new Vector3(28, 0, 0), new Vector3(50, 1.6f, 4.6f), lightWood);
b.Box(new Vector3(55, 0, 0), new Vector3(4, 1.4f, 3), lightWood);
length = 57; break;
case "sica": // gebogenes Kurzschwert der Thraker: Klinge biegt zur Schneide hin
{
b.Box(new Vector3(-9, 0, 0), new Vector3(1.5f, 3.6f, 3.6f), brass);
b.Box(new Vector3(-3.5f, 0, 0), new Vector3(10, 3, 3), wood);
b.Box(new Vector3(2, 0, 0), new Vector3(1.6f, 4, 8), brass);
var at = new Vector3(3, 0, 0); float angle = 0;
for (int i = 0; i < 5; i++)
{
float seg = i < 4 ? 11 : 9, width = i < 4 ? 4.6f : 3;
var dir = new Vector3(MathF.Cos(angle), 0, -MathF.Sin(angle));
b.Box(at + dir * seg / 2, new Vector3(seg + 0.6f, 0.8f, width), steel, Matrix.CreateRotationY(angle));
at += dir * seg;
angle += MathHelper.ToRadians(11);
}
length = 50; break;
}
case "club": // Knüppel: dicker werdendes Holz
b.Box(new Vector3(-3, 0, 0), new Vector3(12, 3.2f, 3.2f), wood);
for (int i = 0; i < 4; i++)
b.Box(new Vector3(8 + i * 11, 0, 0), new Vector3(11.5f, 4 + i * 1.3f, 4 + i * 1.3f), i % 2 == 0 ? wood : lightWood);
length = 50; break;
default: // Gladius
b.Box(new Vector3(-9, 0, 0), new Vector3(1.5f, 3.6f, 3.6f), brass);
b.Box(new Vector3(-3.5f, 0, 0), new Vector3(10, 3, 3), wood);
b.Box(new Vector3(2.2f, 0, 0), new Vector3(1.6f, 4, 11), brass);
b.Box(new Vector3(30, 0, 0), new Vector3(54, 0.8f, 5.2f), steel);
b.Box(new Vector3(60, 0, 0), new Vector3(6, 0.7f, 2.6f), steel);
break;
}
var sword = b.Build(Bone(side + "Hand"), Grip(side));
sword.Length = length;
Props.Add(sword);
}
/// Speer (Hasta) der Hoplomachi und Equites, in der Mitte gefasst: Blattspitze nach vorn.
public void AddSpear(string side = "Right")
{
var b = new MeshBuilder();
var wood = new Color(118, 82, 48); var bronze = new Color(184, 140, 70); var steel = new Color(200, 204, 210);
b.Box(new Vector3(25, 0, 0), new Vector3(170, 2.4f, 2.4f), wood); // Schaft (-60 … +110)
b.Box(new Vector3(-61, 0, 0), new Vector3(4, 3, 3), bronze); // Schuh
b.Box(new Vector3(111, 0, 0), new Vector3(5, 3.2f, 3.2f), bronze); // Tülle
// Blatt: zwei schräge Hälften bilden die Raute
b.Box(new Vector3(121, 0, 1.3f), new Vector3(16, 0.8f, 2.6f), steel, Matrix.CreateRotationY(MathHelper.ToRadians(-9)));
b.Box(new Vector3(121, 0, -1.3f), new Vector3(16, 0.8f, 2.6f), steel, Matrix.CreateRotationY(MathHelper.ToRadians(9)));
b.Box(new Vector3(131, 0, 0), new Vector3(7, 0.7f, 1.6f), steel);
var p = b.Build(Bone(side + "Hand"), Grip(side));
p.Length = 134;
Props.Add(p);
}
/// Gewölbter Schild (Scutum) am Unterarm, Bemalung in Magenta (Teamfarbe), Bronzerand und Buckel.
public void AddShield(string side = "Left", string kind = "scutum")
{
var fa = BindPos(side + "ForeArm"); var h = BindPos(side + "Hand");
var m = BindPos(side + "HandMiddle1"); var ix = BindPos(side + "HandIndex1"); var pk = BindPos(side + "HandPinky1"); var th = BindPos(side + "HandThumb1");
var arm = Vector3.Normalize(h - fa);
var across = Vector3.Normalize(ix - pk);
var palm = Vector3.Normalize(Vector3.Cross(Vector3.Normalize(m - h), across));
if (Vector3.Dot(palm, th - h) < 0) palm = -palm;
// Scutum mit Quergriff: die Faust hält den Griff (kleiner Finger → Zeigefinger), die Knöchel
// zeigen zum Schild; der Schild steht senkrecht zum Griff
var knuckles = Vector3.Normalize(m - h);
var centre = m + knuckles * 7 * Unit;
var b = new MeshBuilder();
var face = new Color(190, 30, 160); var rim = new Color(150, 112, 52); var boss = new Color(182, 150, 80);
float W = 50, H = 72, BEND = 0.011f;
if (kind == "round")
{
// Rundschild (Parma): flach gewölbte Scheibe mit Rand und Buckel
W = H = 60; BEND = 0.006f;
b.Disc(30, BEND, face, 1.2f);
b.Ring(30, BEND, rim);
b.Dome(new Vector3(0, 0, 1.5f), 8, 5, boss);
}
else
{
if (kind == "parmula") { W = 40; H = 48; BEND = 0.02f; } // kleiner Schild der Thraker
// x: Länge (entlang des Arms), y: Breite, z: nach außen (weg vom Arm), gewölbt um die Längsachse
b.Curved(W, H, BEND, face, 1.2f);
b.Rim(W, H, BEND, rim);
b.Dome(new Vector3(0, 0, 2.5f), kind == "parmula" ? 6 : 9, kind == "parmula" ? 4 : 5, boss);
}
// x (Höhe) = Griff (senkrecht gehalten, wie die Mixamo-Schildbewegungen es erwarten),
// y (Breite) = Knöchel × Griff, z (außen) = x × y = Knöchelrichtung
var shield = b.Build(Bone(side + "Hand"), Matrix.CreateScale(Unit) * Attach(Bone(side + "Hand"), across, Vector3.Cross(knuckles, across), centre));
shield.Shield = true; shield.Height = H; shield.Width = W; shield.Bend = BEND;
// Skelett ohne Finger: die Handdrehung passt nach der Übertragung der Bewegungen nicht zuverlässig
shield.Upright = Bone(side + "HandMiddle1") < 0;
Props.Add(shield);
}
// ── Waffen weichen dem eigenen Körper aus ───────────────────────────
// Die Mixamo-Bewegungen kennen Schwert und Schild nicht: in manchen Haltungen läge der Schild
// im Oberschenkel oder die Klinge im Rumpf. Der Körper wird grob als Kapseln (Strecke + Radius)
// aus den Knochen gebaut; der Schild wird nach außen geschoben, die Klinge um den Griff weggedreht.
// Beides federt nach, damit nichts springt oder zittert.
readonly List<(Vector3 A, Vector3 B, float R)> _body = new();
int[]? _bodyBones;
void BuildBody(out float cm)
{
_bodyBones ??= new[] { Bone("Hips"), Bone("Neck"), Bone("Head"), Bone("LeftUpLeg"), Bone("LeftLeg"), Bone("LeftFoot"),
Bone("RightUpLeg"), Bone("RightLeg"), Bone("RightFoot") };
_body.Clear();
var bb = _bodyBones;
Vector3 P(int i) => bb[i] >= 0 ? _global[bb[i]].Translation : Vector3.Zero;
// Maßstab: Oberschenkel etwa 45 cm
cm = bb[3] >= 0 && bb[4] >= 0 ? Vector3.Distance(P(3), P(4)) / 45f : 1;
if (bb[0] < 0 || bb[1] < 0) return;
_body.Add((P(0), P(1), 15 * cm)); // Rumpf
if (bb[3] >= 0 && bb[6] >= 0) _body.Add((P(3), P(6), 11 * cm)); // Becken
if (bb[2] >= 0) _body.Add((P(2), P(2) + (P(2) - P(1)) * 0.6f, 11 * cm)); // Kopf
if (bb[3] >= 0 && bb[4] >= 0 && bb[5] >= 0) { _body.Add((P(3), P(4), 9 * cm)); _body.Add((P(4), P(5), 6.5f * cm)); }
if (bb[6] >= 0 && bb[7] >= 0 && bb[8] >= 0) { _body.Add((P(6), P(7), 9 * cm)); _body.Add((P(7), P(8), 6.5f * cm)); }
}
static Vector3 Closest(Vector3 a, Vector3 b, Vector3 p)
{
var ab = b - a; float l = ab.LengthSquared();
return l < 1e-9f ? a : a + ab * MathHelper.Clamp(Vector3.Dot(p - a, ab) / l, 0, 1);
}
void AvoidBody()
{
if (Props.Count == 0) return;
BuildBody(out float cm);
foreach (var p in Props) p.World = p.Upright ? UprightShield(p, cm) : p.Local * _global[p.Bone];
if (_body.Count == 0) return;
Prop? shield = null;
foreach (var p in Props) if (p.Shield) shield = p;
if (shield != null) AvoidShield(shield, cm);
foreach (var p in Props) if (!p.Shield && !p.NoAvoid) AvoidBlade(p, shield, cm);
}
static Vector3 Axis(Matrix m, int row) => row switch
{
0 => new Vector3(m.M11, m.M12, m.M13), 1 => new Vector3(m.M21, m.M22, m.M23), _ => new Vector3(m.M31, m.M32, m.M33)
};
/// Schild aufrecht vor der Hand: Hochachse entlang des Oberkörpers, Vorderseite vom Körper zur Hand hin.
Matrix UprightShield(Prop s, float cm)
{
int hand = s.Bone, hips = Bone("Hips"), neck = Bone("Neck"), head = Bone("Head");
if (hips < 0 || neck < 0) return s.Local * _global[s.Bone];
var h = _global[hand].Translation;
var a = _global[hips].Translation; var n = _global[neck].Translation;
var up = Vector3.Normalize((head >= 0 ? _global[head].Translation : n) - a);
var outV = h - Closest(a, n, h);
outV -= up * Vector3.Dot(outV, up);
if (outV.LengthSquared() < 1e-6f) outV = Vector3.Cross(up, Vector3.UnitX);
outV.Normalize();
var y = Vector3.Cross(outV, up); // x (Höhe) = up, z (außen) = outV, z = x × y
var c = h + outV * 6 * cm;
var frame = new Matrix(up.X, up.Y, up.Z, 0, y.X, y.Y, y.Z, 0, outV.X, outV.Y, outV.Z, 0, c.X, c.Y, c.Z, 1);
return Matrix.CreateScale(cm) * frame;
}
/// Schild entlang seiner Außenseite verschieben, bis kein Körperteil von innen hineinragt.
void AvoidShield(Prop s, float cm)
{
var m = s.World;
var c = m.Translation;
float sc = Axis(m, 0).Length(); // Modell-Einheiten je Schild-cm
var ax = Vector3.Normalize(Axis(m, 0)); var ay = Vector3.Normalize(Axis(m, 1)); var az = Vector3.Normalize(Axis(m, 2));
float hh = s.Height / 2 * sc, hw = s.Width / 2 * sc, gap = 2 * cm, thick = 1.5f * sc;
float need = 0;
foreach (var (a, b, r) in _body)
for (int k = 0; k <= 8; k++)
{
var d = Vector3.Lerp(a, b, k / 8f) - c;
float u = Vector3.Dot(d, ax), v = Vector3.Dot(d, ay), w = Vector3.Dot(d, az);
if (MathF.Abs(u) > hh + r * 0.5f || MathF.Abs(v) > hw + r * 0.5f) continue; // neben dem Schild
float vc = MathHelper.Clamp(v, -hw, hw) / sc;
float surf = -s.Bend * vc * vc * sc - thick; // Innenseite (gewölbt)
if (w > surf + r) continue; // vor dem Schild: nicht durch Schieben lösbar
need = MathF.Max(need, w + r + gap - surf);
}
need = MathF.Min(need, 40 * cm);
s.Push += (need - s.Push) * (need > s.Push ? 0.55f : 0.12f); // schnell hinaus, langsam zurück
s.Correction = Matrix.CreateTranslation(az * s.Push);
}
/// Klinge um den Griff wegdrehen, wenn sie Körper oder eigenen Schild schneidet.
void AvoidBlade(Prop p, Prop? shield, float cm)
{
var m = p.World;
var grip = m.Translation;
float sc = Axis(m, 0).Length();
var dir = Vector3.Normalize(Axis(m, 0));
float len = p.Length * sc, half = 2.5f * cm;
var sm = shield != null ? shield.World * shield.Correction : Matrix.Identity;
float ss = Axis(sm, 0).Length();
var sx = Vector3.Normalize(Axis(sm, 0)); var sy = Vector3.Normalize(Axis(sm, 1)); var sz = Vector3.Normalize(Axis(sm, 2));
bool Hits(Vector3 d, out Vector3 away)
{
away = Vector3.Zero; bool hit = false;
for (int k = 2; k <= 10; k++)
{
var q = grip + d * (len * k / 10f);
foreach (var (a, b, r) in _body)
{
var cp = Closest(a, b, q);
if (Vector3.DistanceSquared(cp, q) < (r + half) * (r + half)) { away += q - cp; hit = true; }
}
if (shield != null)
{
var dq = q - sm.Translation;
float u = Vector3.Dot(dq, sx), v = Vector3.Dot(dq, sy), w = Vector3.Dot(dq, sz);
float vc = v / ss, surf = -shield.Bend * vc * vc * ss;
if (MathF.Abs(u) < shield.Height / 2 * ss && MathF.Abs(v) < shield.Width / 2 * ss && MathF.Abs(w - surf) < 2.5f * cm)
{ away += sz * (w >= surf ? 1 : -1); hit = true; }
}
}
return hit;
}
float target = 0;
if (Hits(dir, out var push) && push.LengthSquared() > 1e-9f)
{
var axis = Vector3.Cross(dir, Vector3.Normalize(push));
if (axis.LengthSquared() > 1e-9f)
{
axis.Normalize();
p.Axis = axis;
target = MathHelper.ToRadians(50);
for (int deg = 6; deg <= 50; deg += 6)
if (!Hits(Vector3.Transform(dir, Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(deg))), out _))
{ target = MathHelper.ToRadians(deg); break; }
}
}
p.Angle += (target - p.Angle) * (target > p.Angle ? 0.5f : 0.12f);
p.Correction = p.Angle < 1e-3f ? Matrix.Identity
: Matrix.CreateTranslation(-grip) * Matrix.CreateFromAxisAngle(p.Axis, p.Angle) * Matrix.CreateTranslation(grip);
}
sealed class MeshBuilder
{
readonly List<VertexPNC> _v = new(); readonly List<int> _i = new();
void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Color col)
{
var n = Vector3.Normalize(Vector3.Cross(b - a, c - a));
int o = _v.Count;
foreach (var p in new[] { a, b, c, d }) _v.Add(new VertexPNC { Position = p, Normal = n, Color = col });
_i.AddRange(new[] { o, o + 1, o + 2, o, o + 2, o + 3 });
}
public void Box(Vector3 c, Vector3 s, Color col, Matrix? rot = null)
{
var h = s / 2;
var r = rot ?? Matrix.Identity;
Vector3 P(float x, float y, float z) => c + Vector3.TransformNormal(new Vector3(x * h.X, y * h.Y, z * h.Z), r);
Quad(P(-1, -1, 1), P(1, -1, 1), P(1, 1, 1), P(-1, 1, 1), col);
Quad(P(1, -1, -1), P(-1, -1, -1), P(-1, 1, -1), P(1, 1, -1), col);
Quad(P(-1, 1, -1), P(-1, 1, 1), P(1, 1, 1), P(1, 1, -1), col);
Quad(P(-1, -1, 1), P(-1, -1, -1), P(1, -1, -1), P(1, -1, 1), col);
Quad(P(1, -1, 1), P(1, -1, -1), P(1, 1, -1), P(1, 1, 1), col);
Quad(P(-1, -1, -1), P(-1, -1, 1), P(-1, 1, 1), P(-1, 1, -1), col);
}
static Vector3 Surf(float x, float y, float bend, float off) => new(x, y, -bend * y * y + off);
public void Curved(float w, float h, float bend, Color col, float thick)
{
const int NX = 8, NY = 10;
for (int side = 0; side < 2; side++)
for (int i = 0; i < NX; i++)
for (int j = 0; j < NY; j++)
{
float x0 = -h / 2 + h * i / NX, x1 = -h / 2 + h * (i + 1) / NX;
float y0 = -w / 2 + w * j / NY, y1 = -w / 2 + w * (j + 1) / NY;
float off = side == 0 ? 0 : -thick;
var shade = side == 0 ? col : new Color(110, 78, 46); // Innenseite Holz
Quad(Surf(x0, y0, bend, off), Surf(x1, y0, bend, off), Surf(x1, y1, bend, off), Surf(x0, y1, bend, off), shade);
}
}
public void Rim(float w, float h, float bend, Color col)
{
const int N = 10;
for (int j = 0; j < N; j++)
{
float y0 = -w / 2 + w * j / N, y1 = -w / 2 + w * (j + 1) / N;
foreach (float x in new[] { -h / 2, h / 2 })
{
var a = Surf(x, y0, bend, 0.6f); var c = Surf(x, y1, bend, 0.6f);
Box((a + c) / 2, new Vector3(3, MathF.Abs(y1 - y0) + 0.2f, 3), col);
}
}
for (int i = 0; i < N; i++)
{
float x0 = -h / 2 + h * i / N, x1 = -h / 2 + h * (i + 1) / N;
foreach (float y in new[] { -w / 2, w / 2 })
Box(Surf((x0 + x1) / 2, y, bend, 0.6f), new Vector3(MathF.Abs(x1 - x0) + 0.2f, 3, 3), col);
}
}
public void Dome(Vector3 c, float r, float hgt, Color col)
{
const int SEG = 12, RING = 4;
for (int k = 0; k < RING; k++)
for (int s = 0; s < SEG; s++)
{
float a0 = MathF.PI / 2 * k / RING, a1 = MathF.PI / 2 * (k + 1) / RING;
float t0 = MathF.Tau * s / SEG, t1 = MathF.Tau * (s + 1) / SEG;
Vector3 P(float a, float t) => c + new Vector3(MathF.Cos(t) * MathF.Cos(a) * r, MathF.Sin(t) * MathF.Cos(a) * r, MathF.Sin(a) * hgt);
Quad(P(a0, t0), P(a0, t1), P(a1, t1), P(a1, t0), col);
}
}
/// Runde, leicht gewölbte Scheibe (Rundschild), Vorder- und Rückseite.
public void Disc(float r, float bend, Color col, float thick)
{
const int SEG = 28, RINGS = 4;
var back = new Color(110, 78, 46);
Vector3 S(float rad, float a, float off) => new(MathF.Cos(a) * rad, MathF.Sin(a) * rad, -bend * rad * rad + off);
for (int side = 0; side < 2; side++)
for (int k = 0; k < RINGS; k++)
for (int i = 0; i < SEG; i++)
{
float r0 = r * k / RINGS, r1 = r * (k + 1) / RINGS, a0 = MathF.Tau * i / SEG, a1 = MathF.Tau * (i + 1) / SEG;
float off = side == 0 ? 0 : -thick;
Quad(S(r0, a0, off), S(r1, a0, off), S(r1, a1, off), S(r0, a1, off), side == 0 ? col : back);
}
}
/// Rand eines Rundschilds aus kurzen, gedrehten Stücken.
public void Ring(float r, float bend, Color col)
{
const int SEG = 20;
for (int i = 0; i < SEG; i++)
{
float a = MathF.Tau * (i + 0.5f) / SEG;
var c = new Vector3(MathF.Cos(a) * r, MathF.Sin(a) * r, -bend * r * r + 0.6f);
Box(c, new Vector3(3, MathF.Tau * r / SEG + 0.4f, 3), col, Matrix.CreateRotationZ(a));
}
}
public Prop Build(int bone, Matrix local)
{
var v = _v.ToArray();
return new Prop { Bone = bone, Local = local, V = v, I = _i.ToArray(), Base = Array.ConvertAll(v, x => x.Color) };
}
}
}
}