Eigene Kampfstile je Gegner (Faustkampf, Axt-Champions), schnelleres Laden

Stand von main 975b62f0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 14:20:38 +01:00
parent e29db47b20
commit 35a5ac5032
10 changed files with 225 additions and 30 deletions

View File

@@ -28,7 +28,9 @@ namespace GladiatorIdle.Arena
void InitModel(int color)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
_model = Model3D.Load(_art);
double tLoad = sw.Elapsed.TotalMilliseconds;
bool own = _model != null;
foreach (var alt in Fallbacks(_art)) _model ??= Model3D.Load(alt);
_model ??= Model3D.Load(DefaultModel);
@@ -36,12 +38,18 @@ namespace GladiatorIdle.Arena
if (!own && _model != null && DarkSkin.Contains(_art)) _model.SetSkin(1);
else if (!own && _model != null && _art.StartsWith("hero_") && _art.EndsWith("_3")) _model.SetSkin(-1); // Vorlage 3: helle Haut
if (_model == null || _model.Clips.Count == 0) { _model = null; return; }
double tSkin = sw.Elapsed.TotalMilliseconds;
_model.Arm(_art);
double tArm = sw.Elapsed.TotalMilliseconds;
_model.SetColor(color);
var idle = Clip3("idle");
_model.Pose(idle, 0, true);
_fit = _model.FitNow();
double tColor = sw.Elapsed.TotalMilliseconds;
// Einpassen hängt nur von der Figur ab (sortiert alle Punkte): einmal je Bild-Name rechnen
if (!_fitCache.TryGetValue(_art, out _fit)) _fitCache[_art] = _fit = _model.FitNow();
double tFit = sw.Elapsed.TotalMilliseconds;
foreach (var c in new[] { "slash", "slash2", "slash3", "attack", "attack2" }) _model.ImpactTime(Clip3(c));
if (DevShot.Active) DevShot.Log($"timing: fighter {_art}: load {tLoad:0} skin {tSkin - tLoad:0} arm {tArm - tSkin:0} color {tColor - tArm:0} fit {tFit - tColor:0} impact {sw.Elapsed.TotalMilliseconds - tFit:0} ms");
_mfx = new BasicEffect(Assets.Device) { VertexColorEnabled = true, LightingEnabled = true, PreferPerPixelLighting = true };
// Kamera-Raum der Arena: x rechts, y nach unten, z zum Betrachter
_mfx.AmbientLightColor = new Vector3(0.45f, 0.40f, 0.37f);
@@ -71,12 +79,17 @@ namespace GladiatorIdle.Arena
case "foe_recruit": yield return "foe_slave"; break;
case "foe_provocator" or "foe_crupellarius" or "foe_praetorian" or "foe_eques":
yield return "foe_hoplomachus"; break;
case "foe_dimachaerus" or "foe_essedarius" or "foe_laquearius" or "foe_sagittarius":
yield return "foe_brawler"; break;
// der Raufbold kämpft mit Fäusten – Schwertkämpfer ohne eigene Figur nehmen Gladiatoren-Figuren
case "foe_dimachaerus" or "foe_essedarius":
yield return "hero_secutor_1"; break;
case "foe_laquearius" or "foe_sagittarius":
yield return "hero_thraex_1"; break;
}
yield return "foe_hoplomachus";
}
static readonly System.Collections.Generic.Dictionary<string, Matrix> _fitCache = new();
Model3D.Clip Clip3(string name) => _model!.Find(name) ?? _model!.Clips[0];
/// Clip und Zeit zum Zustand der Kampflogik.

View File

@@ -132,6 +132,7 @@ namespace GladiatorIdle
_sb = new SpriteBatch(GraphicsDevice);
_fx = new BasicEffect(GraphicsDevice) { TextureEnabled = true, VertexColorEnabled = true, LightingEnabled = false, World = Matrix.Identity };
Assets.Init(GraphicsDevice);
Gfx.Model3D.PreloadAll(); // alle Figuren im Hintergrund vorbereiten
_settings = new SettingsOverlay(ToggleFullscreen)
{
ApplyGraphics = () => ApplyFrameLimit(),
@@ -645,6 +646,8 @@ namespace GladiatorIdle
protected override void Draw(GameTime gameTime)
{
_drawWatch.Restart();
if (_frames == 0 && DevShot.Active)
DevShot.Log($"timing: first frame {(DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).TotalMilliseconds:0} ms after start");
bool capturing = _capture != null;
var gd = GraphicsDevice;
int w = gd.PresentationParameters.BackBufferWidth, h = gd.PresentationParameters.BackBufferHeight;

View File

@@ -116,28 +116,46 @@ namespace GladiatorIdle.Gfx
}
/// Textur aus Pixeln mit Mipmap-Stufen (2×2-Mittel je Stufe).
public static Texture2D MipTexture(Color[] data, int w, int h)
public static Texture2D MipTexture(Color[] data, int w, int h) => Upload(MipLevels(data, w, h), w, h);
/// Mipmap-Stufen nur aus Pixeln (ohne Grafikkarte, also auch im Hintergrund nutzbar).
public static Color[][] MipLevels(Color[] data, int w, int h)
{
var t = new Texture2D(_gd, w, h, true, SurfaceFormat.Color);
t.SetData(0, null, data, 0, data.Length);
var levels = new List<Color[]> { data };
var cur = data; int cw = w, ch = h;
for (int level = 1; level < t.LevelCount; level++)
while (cw > 1 || ch > 1)
{
int nw = Math.Max(1, cw / 2), nh = Math.Max(1, ch / 2);
var next = new Color[nw * nh];
for (int y = 0; y < nh; y++)
var src = cur; int sw = cw, sh = ch;
System.Threading.Tasks.Parallel.For(0, nh, y =>
{
for (int x = 0; x < nw; x++)
{
int x0 = Math.Min(cw - 1, x * 2), x1 = Math.Min(cw - 1, x * 2 + 1), y0 = Math.Min(ch - 1, y * 2), y1 = Math.Min(ch - 1, y * 2 + 1);
var a = cur[y0 * cw + x0]; var b = cur[y0 * cw + x1]; var c = cur[y1 * cw + x0]; var d = cur[y1 * cw + x1];
int x0 = Math.Min(sw - 1, x * 2), x1 = Math.Min(sw - 1, x * 2 + 1), y0 = Math.Min(sh - 1, y * 2), y1 = Math.Min(sh - 1, y * 2 + 1);
var a = src[y0 * sw + x0]; var b = src[y0 * sw + x1]; var c = src[y1 * sw + x0]; var d = src[y1 * sw + x1];
next[y * nw + x] = new Color((a.R + b.R + c.R + d.R + 2) / 4, (a.G + b.G + c.G + d.G + 2) / 4, (a.B + b.B + c.B + d.B + 2) / 4, (a.A + b.A + c.A + d.A + 2) / 4);
}
t.SetData(level, null, next, 0, next.Length);
});
levels.Add(next);
cur = next; cw = nw; ch = nh;
}
return levels.ToArray();
}
/// Fertige Stufen zur Grafikkarte (Hauptthread, schnell).
public static Texture2D Upload(Color[][] levels, int w, int h)
{
var t = new Texture2D(_gd, w, h, true, SurfaceFormat.Color);
for (int i = 0; i < Math.Min(levels.Length, t.LevelCount); i++) t.SetData(i, null, levels[i], 0, levels[i].Length);
return t;
}
/// Pixel einer Textur schon bekannt (Figuren): Einfärben braucht dann kein Zurücklesen von der Grafikkarte.
public static void RegisterPixels(Texture2D t, Color[] data) { lock (_known) _known[t] = data; }
public static Color[]? KnownPixels(Texture2D t) { lock (_known) return _known.TryGetValue(t, out var d) ? d : null; }
static readonly Dictionary<Texture2D, Color[]> _known = new();
/// Bild eines Video-Sprites: Farbe vor Schwarz (JPEG, also schon vormultipliziert)
/// plus Deckkraft (Graustufen-PNG) — zusammengesetzt zu einer Textur.
public static Texture2D? LoadFrame(string relBase)
@@ -194,15 +212,78 @@ namespace GladiatorIdle.Gfx
public static Texture2D Paint(Texture2D src, int colorIndex)
{
if (_painted.TryGetValue((src, colorIndex), out var t)) return t;
var data = new Color[src.Width * src.Height];
src.GetData(data);
PaintPixels(data, colorIndex);
var sw = System.Diagnostics.Stopwatch.StartNew();
var info = PaintInfoOf(src);
if (info.Index.Length == 0) return _painted[(src, colorIndex)] = src; // keine Teamfarben-Flächen
var data = (Color[])info.Data.Clone();
var c = Appearance.Colors[colorIndex];
System.Threading.Tasks.Parallel.For(0, (info.Index.Length + 8191) / 8192, chunk =>
{
int end = Math.Min(info.Index.Length, (chunk + 1) * 8192);
for (int k = chunk * 8192; k < end; k++)
{
int i = info.Index[k];
var px = data[i];
float a = px.A / 255f, r = px.R / 255f / a, g = px.G / 255f / a, b = px.B / 255f / a;
float max = info.Max[k], s = info.Sat[k], w = info.Weight[k];
var (nr, ng, nb) = Hsv(c.Hue, MathHelper.Clamp(s * c.Sat, 0, 1), MathHelper.Clamp(max * c.Val, 0, 1));
r += (nr - r) * w; g += (ng - g) * w; b += (nb - b) * w;
data[i] = new Color(r * a, g * a, b * a, a);
}
});
if (src.LevelCount > 1) t = MipTexture(data, src.Width, src.Height); // Figuren: Stufen behalten
else { t = new Texture2D(_gd, src.Width, src.Height); t.SetData(data); }
_painted[(src, colorIndex)] = t;
if (DevShot.Active && src.Width > 512) DevShot.Log($"timing: paint {src.Width}x{src.Height} color {colorIndex} in {sw.ElapsedMilliseconds} ms ({info.Index.Length} px)");
return t;
}
/// Je Quelle einmal: Pixel und welche davon Teamfarbe (Magenta) sind, mit Sättigung, Helligkeit, Gewicht.
public sealed record PaintInfo(Color[] Data, int[] Index, float[] Sat, float[] Max, float[] Weight);
/// Teamfarben-Daten vorab (auch im Hintergrund) und für eine Textur hinterlegen.
public static void RegisterPaintInfo(Texture2D t, PaintInfo info) { lock (_known) _paintInfo[t] = info; }
static readonly Dictionary<Texture2D, PaintInfo> _paintInfo = new();
static PaintInfo PaintInfoOf(Texture2D src)
{
lock (_known) if (_paintInfo.TryGetValue(src, out var info)) return info;
Color[]? known;
lock (_known) _known.TryGetValue(src, out known);
var data = known ?? new Color[src.Width * src.Height];
if (known == null) src.GetData(data);
var made = ComputePaintInfo(data);
lock (_known) _paintInfo[src] = made;
return made;
}
/// Welche Pixel Teamfarbe (Magenta) sind – reine Rechnung, auch im Hintergrund.
public static PaintInfo ComputePaintInfo(Color[] data)
{
// Gewicht je Pixel parallel, danach nur die Teamfarben-Pixel einsammeln
var wAll = new float[data.Length]; var sAll = new float[data.Length]; var mAll = new float[data.Length];
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 px = data[i];
if (px.A == 0) continue;
float a = px.A / 255f, r = px.R / 255f / a, g = px.G / 255f / a, b = px.B / 255f / a;
float max = MathF.Max(r, MathF.Max(g, b)), min = MathF.Min(r, MathF.Min(g, b)), d = max - min;
if (max <= 0.08f || d <= 0.001f) continue;
float s = 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 w = Smooth(48, 30, MathF.Abs(h - 312)) * Smooth(0.18f, 0.32f, s);
if (w > 0) { wAll[i] = w; sAll[i] = s; mAll[i] = max; }
}
});
var idx = new List<int>(); var sat = new List<float>(); var mx = new List<float>(); var wt = new List<float>();
for (int i = 0; i < data.Length; i++)
if (wAll[i] > 0) { idx.Add(i); sat.Add(sAll[i]); mx.Add(mAll[i]); wt.Add(wAll[i]); }
return new PaintInfo(data, idx.ToArray(), sat.ToArray(), mx.ToArray(), wt.ToArray());
}
/// Umfärben auf Pixeldaten (vormultipliziert) — auch im Hintergrund nutzbar.
public static void PaintPixels(Color[] data, int colorIndex)
{

View File

@@ -71,17 +71,56 @@ namespace GladiatorIdle.Gfx
// 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))
{
string? path = Assets.RootDir is string root ? Path.Combine(root, "Models", name + ".gim") : null;
_templates[name] = t = path != null && File.Exists(path) ? new Model3D(gd, path) : null;
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)
{
@@ -92,12 +131,13 @@ namespace GladiatorIdle.Gfx
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(GraphicsDevice gd, string path)
Model3D(string path)
{
using var r = new BinaryReader(File.OpenRead(path), Encoding.UTF8);
string magic = Encoding.ASCII.GetString(r.ReadBytes(4));
@@ -137,7 +177,22 @@ namespace GladiatorIdle.Gfx
Clips.Add(clip);
}
if (v2 && r.ReadInt32() is int texLen && texLen > 0)
using (var ms = new MemoryStream(r.ReadBytes(texLen))) _texture = Assets.Mipmapped(Texture2D.FromStream(gd, ms)); // Stufen: kein Flimmern klein/weit weg
{
// 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);
@@ -157,10 +212,32 @@ namespace GladiatorIdle.Gfx
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 = new Color[_texture.Width * _texture.Height];
_texture.GetData(data);
for (int i = 0; i < data.Length; i++)
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;
@@ -181,10 +258,13 @@ namespace GladiatorIdle.Gfx
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);
}
_texture = Assets.MipTexture(data, _texture.Width, _texture.Height);
_color = -2; // Teamfarbe neu auf die geänderte Textur
});
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;
@@ -284,14 +364,18 @@ namespace GladiatorIdle.Gfx
/// Figur auf 180 Einheiten Höhe, Füße auf y = 0, mittig (aus der jetzigen Haltung, robust gegen Ausreißer).
public Matrix FitNow()
{
float Q(Func<Vector3, float> axis, float q)
// je Achse einmal sortieren (jeder 3. Punkt reicht für die Quantile)
float[] Sorted(Func<Vector3, float> axis)
{
var a = Array.ConvertAll(Vertices, v => axis(v.Position));
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[(int)(q * (a.Length - 1))];
return a;
}
float y0 = Q(p => p.Y, 0.002f), y1 = Q(p => p.Y, 0.998f);
float cx = (Q(p => p.X, 0.01f) + Q(p => p.X, 0.99f)) / 2, cz = (Q(p => p.Z, 0.01f) + Q(p => p.Z, 0.99f)) / 2;
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));
}
@@ -442,7 +526,8 @@ namespace GladiatorIdle.Gfx
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", "sagittarius", "essedarius", "laquearius", "doctore")) { AddSword(); AddShield(kind: "round"); }
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();
}
@@ -576,6 +661,19 @@ namespace GladiatorIdle.Gfx
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")
{