namespace EvilEngine.Formats.Animations; public sealed record BlendCell(IReadOnlyList At, Clip Clip); public sealed record Blend(string? Name, IReadOnlyList Parameters, IReadOnlyList Cells) : Animation(Name) { public IReadOnlyList Nodes => Cells[0].Clip.Nodes; public ContentId? Model => Cells[0].Clip.Model; public bool Loop => Cells[0].Clip.Loop; public override float? FadeIn => Cells[0].Clip.FadeIn; public override float? FadeOut => Cells[0].Clip.FadeOut; public BlendGrid? Grid => BlendGrid.Of(this); public int Parameter(string name) { for (var i = 0; i < Parameters.Count; i++) if (Parameters[i] == name) return i; return -1; } } public sealed class BlendGrid { private readonly int[] _cells; private BlendGrid(float[][] axes, int[] cells) { Axes = axes; _cells = cells; } public IReadOnlyList Axes { get; } public int Width => Axes.Count > 0 ? Axes[0].Length : 1; public int Height => Axes.Count > 1 ? Axes[1].Length : 1; public int Cell(int x, int y) { return _cells[y * Width + x]; } public static BlendGrid? Of(Blend blend) { if (blend.Parameters.Count is 0 or > 2) return null; var axes = Enumerable.Range(0, blend.Parameters.Count) .Select(axis => blend.Cells.Select(cell => cell.At[axis]).Distinct().ToArray()).ToArray(); if (axes.Aggregate(1, (count, axis) => count * axis.Length) != blend.Cells.Count || !axes.All(Monotonic)) return null; var width = axes[0].Length; var cells = new int[blend.Cells.Count]; Array.Fill(cells, -1); for (var i = 0; i < blend.Cells.Count; i++) { var at = blend.Cells[i].At; var x = Array.IndexOf(axes[0], at[0]); var y = axes.Length > 1 ? Array.IndexOf(axes[1], at[1]) : 0; if (cells[y * width + x] >= 0) return null; cells[y * width + x] = i; } return new BlendGrid(axes, cells); } private static bool Monotonic(float[] keys) { if (keys.Length < 2) return true; var rising = keys[1] > keys[0]; for (var i = 1; i < keys.Length; i++) if (rising ? !(keys[i] > keys[i - 1]) : !(keys[i] < keys[i - 1])) return false; return true; } }