Skip to content
0.2.0-dev Download ZIP
84 lines ·2.4 KB Raw
1namespace EvilEngine.Formats.Animations;
2
3public sealed record BlendCell(IReadOnlyList<float> At, Clip Clip);
4
5public sealed record Blend(string? Name, IReadOnlyList<string> Parameters, IReadOnlyList<BlendCell> Cells)
6 : Animation(Name)
7{
8 public IReadOnlyList<ClipNode> Nodes => Cells[0].Clip.Nodes;
9
10 public ContentId? Model => Cells[0].Clip.Model;
11
12 public bool Loop => Cells[0].Clip.Loop;
13
14 public override float? FadeIn => Cells[0].Clip.FadeIn;
15
16 public override float? FadeOut => Cells[0].Clip.FadeOut;
17
18 public BlendGrid? Grid => BlendGrid.Of(this);
19
20 public int Parameter(string name)
21 {
22 for (var i = 0; i < Parameters.Count; i++)
23 if (Parameters[i] == name)
24 return i;
25 return -1;
26 }
27}
28
29public sealed class BlendGrid
30{
31 private readonly int[] _cells;
32
33 private BlendGrid(float[][] axes, int[] cells)
34 {
35 Axes = axes;
36 _cells = cells;
37 }
38
39 public IReadOnlyList<float[]> Axes { get; }
40
41 public int Width => Axes.Count > 0 ? Axes[0].Length : 1;
42
43 public int Height => Axes.Count > 1 ? Axes[1].Length : 1;
44
45 public int Cell(int x, int y)
46 {
47 return _cells[y * Width + x];
48 }
49
50 public static BlendGrid? Of(Blend blend)
51 {
52 if (blend.Parameters.Count is 0 or > 2)
53 return null;
54 var axes = Enumerable.Range(0, blend.Parameters.Count)
55 .Select(axis => blend.Cells.Select(cell => cell.At[axis]).Distinct().ToArray()).ToArray();
56 if (axes.Aggregate(1, (count, axis) => count * axis.Length) != blend.Cells.Count || !axes.All(Monotonic))
57 return null;
58 var width = axes[0].Length;
59 var cells = new int[blend.Cells.Count];
60 Array.Fill(cells, -1);
61 for (var i = 0; i < blend.Cells.Count; i++)
62 {
63 var at = blend.Cells[i].At;
64 var x = Array.IndexOf(axes[0], at[0]);
65 var y = axes.Length > 1 ? Array.IndexOf(axes[1], at[1]) : 0;
66 if (cells[y * width + x] >= 0)
67 return null;
68 cells[y * width + x] = i;
69 }
70
71 return new BlendGrid(axes, cells);
72 }
73
74 private static bool Monotonic(float[] keys)
75 {
76 if (keys.Length < 2)
77 return true;
78 var rising = keys[1] > keys[0];
79 for (var i = 1; i < keys.Length; i++)
80 if (rising ? !(keys[i] > keys[i - 1]) : !(keys[i] < keys[i - 1]))
81 return false;
82 return true;
83 }
84}