Skip to content
0.2.0-dev Download ZIP
213 lines ·10.8 KB Raw
1using EvilEngine.Formats.Models;
2
3namespace EvilEngine.Formats.Animations;
4
5public static class AnimationFile
6{
7 public static Clip Read(ReadOnlyMemory<byte> bytes, string file)
8 {
9 return ReadAnimation(bytes, file) switch
10 {
11 Clip clip => clip,
12 Blend blend => throw new ModelFormatException(file,
13 $"blends {blend.Cells.Count} animations over {string.Join(" and ", blend.Parameters)}, and a clip is one."),
14 _ => throw new ModelFormatException(file, "isn't a clip.")
15 };
16 }
17
18 public static Animation ReadAnimation(ReadOnlyMemory<byte> bytes, string file)
19 {
20 var model = ModelFile.Read(bytes, file);
21 if (model.Meshes.Count > 0 || model.Skins.Count > 0)
22 throw new ModelFormatException(file, "is animation, which holds no meshes or skins.");
23 if (model.Animations.Count == 0)
24 throw new ModelFormatException(file, "has no animations.");
25 var parents = new int[model.Nodes.Count];
26 Array.Fill(parents, -1);
27 for (var node = 0; node < model.Nodes.Count; node++)
28 foreach (var child in model.Nodes[node].Children)
29 parents[child] = node;
30 var names = new HashSet<string>(StringComparer.Ordinal);
31 var nodes = model.Nodes.Select((node, index) =>
32 {
33 if (node.Name is not { } name)
34 throw new ModelFormatException(file, $"has node {index} with no name, and a clip's tracks go by name.");
35 if (!names.Add(name))
36 throw new ModelFormatException(file, $"names two nodes '{name}', and a clip's tracks go by name.");
37 return new ClipNode(name, parents[index], node.Translation, node.Rotation, node.Scale);
38 }).ToArray();
39 var clips = model.Animations.Select(animation => Clip(animation, nodes, file)).ToArray();
40 if (model.Animations.Count == 1 && model.Animations[0].Info is not { Parameters.Count: > 0 })
41 return clips[0];
42 var parameters = model.Animations[0].Info?.Parameters ?? [];
43 if (parameters.Count == 0)
44 throw new ModelFormatException(file,
45 $"has {model.Animations.Count} animations and no parameters placing them, and a clip is one.");
46 if (model.Animations.Any(animation =>
47 animation.Info is not { } info || !info.Parameters.SequenceEqual(parameters)))
48 throw new ModelFormatException(file,
49 $"blends over {string.Join(" and ", parameters)}, and not every animation is placed on them.");
50 var blend = new Blend(model.Animations[0].Info?.Blend ?? model.Animations[0].Name, parameters,
51 clips.Select((clip, index) => new BlendCell(model.Animations[index].Info!.At, clip)).ToArray());
52 if (blend.Cells.Select(cell => string.Join(" ", cell.At)).Distinct().Count() != blend.Cells.Count)
53 throw new ModelFormatException(file, "places two animations at the same point.");
54 if (blend.Cells.Any(cell => cell.Clip.Loop != blend.Loop))
55 throw new ModelFormatException(file, "blends looping animations with ones that don't loop.");
56 if (blend.Cells.Any(cell => cell.Clip.Delta != blend.Delta || cell.Clip.Realtime != blend.Realtime))
57 throw new ModelFormatException(file,
58 "blends deltas with poses, or clocked animations with ones that aren't.");
59 return blend;
60 }
61
62 private static Clip Clip(ModelAnimation animation, ClipNode[] nodes, string file)
63 {
64 var tracks = animation.Channels.Select(channel =>
65 {
66 if (channel.Path == ModelChannelPath.Weights)
67 throw new ModelFormatException(file, "animates morph weights, which a clip can't hold yet.");
68 if (channel.Interpolation == ModelInterpolation.CubicSpline)
69 throw new ModelFormatException(file, "has a cubic spline track, which a clip can't hold yet.");
70 for (var key = 1; key < channel.Times.Length; key++)
71 if (!(channel.Times[key] > channel.Times[key - 1]))
72 throw new ModelFormatException(file, "has a track whose times don't rise.");
73 return new ClipTrack(channel.Node, channel.Path, channel.Times, channel.Values, channel.Interpolation);
74 }).ToArray();
75 var info = animation.Info;
76 if (info?.Weights is { } weights && weights.Count != nodes.Length)
77 throw new ModelFormatException(file, $"weighs {weights.Count} nodes, and it has {nodes.Length}.");
78 return new Clip(animation.Name, nodes, tracks, info?.Model, info?.Rate, info?.Loop ?? false)
79 {
80 Move = info?.Move, Fade = info?.Fade,
81 Overlay = info is null || (!info.Delta && !info.Realtime && info.Weights is null && info.Layers.Count == 0)
82 ? AnimationOverlay.None
83 : new AnimationOverlay(info.Delta, info.Realtime, info.Weights,
84 info.Layers.Select(layer => new AnimationLayer(layer.Animation, layer.Always)).ToArray())
85 };
86 }
87
88 public static byte[] Write(Animation animation)
89 {
90 return animation switch
91 {
92 Clip clip => Write(clip),
93 Blend blend => Write(blend),
94 _ => throw new ArgumentException($"{animation.GetType().Name} isn't animation the file holds.",
95 nameof(animation))
96 };
97 }
98
99 public static byte[] Write(Blend blend)
100 {
101 if (blend.Parameters.Count == 0 || blend.Cells.Count == 0)
102 throw new ArgumentException("A blend places at least one clip on at least one parameter.", nameof(blend));
103 var nodes = blend.Nodes;
104 foreach (var cell in blend.Cells)
105 {
106 if (cell.At.Count != blend.Parameters.Count)
107 throw new ArgumentException(
108 $"A cell sits at {cell.At.Count} values for {blend.Parameters.Count} parameters.", nameof(blend));
109 if (!cell.Clip.Nodes.Select(node => (node.Name, node.Parent))
110 .SequenceEqual(nodes.Select(node => (node.Name, node.Parent))))
111 throw new ArgumentException("A blend's clips share one tree of nodes.", nameof(blend));
112 if (cell.Clip.Rate is null)
113 throw new ArgumentException("A blend's clips need their rates.", nameof(blend));
114 if (cell.Clip.Weights is { } weights && weights.Count != nodes.Count)
115 throw new ArgumentException($"A cell weighs {weights.Count} nodes of {nodes.Count}.", nameof(blend));
116 }
117
118 var glb = Write(nodes, blend.Cells.Select(cell =>
119 {
120 var animation = Animation(cell.Clip, blend.Parameters, cell.At);
121 return animation with { Info = animation.Info! with { Blend = blend.Name } };
122 }).ToArray());
123 if (WrittenChecks.Enabled)
124 try
125 {
126 if (ReadAnimation(glb, "written blend") is not Blend)
127 throw new ModelFormatException("written blend", "reads back as a clip.");
128 }
129 catch (ModelFormatException error)
130 {
131 throw new ArgumentException($"The blend wouldn't read back: {error.Message}", error);
132 }
133
134 return glb;
135 }
136
137 public static byte[] Write(Clip clip)
138 {
139 if (clip.Weights is { } weights && weights.Count != clip.Nodes.Count)
140 throw new ArgumentException($"A clip weighs {weights.Count} nodes of {clip.Nodes.Count}.", nameof(clip));
141 var glb = Write(clip.Nodes, [Animation(clip, [], [])]);
142 if (WrittenChecks.Enabled)
143 try
144 {
145 Read(glb, "written clip");
146 }
147 catch (ModelFormatException error)
148 {
149 throw new ArgumentException($"The clip wouldn't read back: {error.Message}", error);
150 }
151
152 return glb;
153 }
154
155 private static ModelAnimation Animation(Clip clip, IReadOnlyList<string> parameters, IReadOnlyList<float> at)
156 {
157 var channels = clip.Tracks.Select(track =>
158 {
159 if (track.Node < 0 || track.Node >= clip.Nodes.Count)
160 throw new ArgumentException($"A track names node {track.Node}, and there are {clip.Nodes.Count}.",
161 nameof(clip));
162 if (track.Times.Length == 0 || track.Values.Length != track.Times.Length * track.Components)
163 throw new ArgumentException(
164 $"A track on '{clip.Nodes[track.Node].Name}' has {track.Times.Length} times and {track.Values.Length} values.",
165 nameof(clip));
166 return new ModelChannel(track.Node, track.Path, track.Interpolation, track.Times, track.Values);
167 }).ToArray();
168 return new ModelAnimation(clip.Name, channels)
169 {
170 Info = clip.Rate is { } rate
171 ? new ModelAnimationInfo(clip.Model, rate, clip.Loop)
172 {
173 Move = clip.Move, Fade = clip.Fade, Parameters = parameters, At = at, Delta = clip.Delta,
174 Realtime = clip.Realtime, Weights = clip.Weights,
175 Layers = clip.Layers.Select(layer => new ModelAnimationLayer(layer.Animation, layer.Always))
176 .ToArray()
177 }
178 : clip.Model is not null || clip.Loop || clip.Move is not null || clip.Fade is not null ||
179 parameters.Count > 0 || clip.Delta || clip.Realtime || clip.Weights is not null ||
180 clip.Layers.Count > 0
181 ? throw new ArgumentException(
182 "A clip naming its model, looping, moving, fading, layered, weighed or placed in a blend needs its rate.",
183 nameof(clip))
184 : null
185 };
186 }
187
188 private static byte[] Write(IReadOnlyList<ClipNode> clipNodes, IReadOnlyList<ModelAnimation> animations)
189 {
190 var names = new HashSet<string>(StringComparer.Ordinal);
191 var children = clipNodes.Select(_ => new List<int>()).ToArray();
192 var roots = new List<int>();
193 for (var i = 0; i < clipNodes.Count; i++)
194 {
195 var node = clipNodes[i];
196 if (!names.Add(node.Name))
197 throw new ArgumentException($"A clip names two nodes '{node.Name}'.", nameof(clipNodes));
198 var up = node.Parent;
199 for (var steps = 0; up >= 0; steps++, up = clipNodes[up].Parent)
200 if (up >= clipNodes.Count || up == i || steps > clipNodes.Count)
201 throw new ArgumentException($"Node '{node.Name}' isn't under a root of the clip's tree.",
202 nameof(clipNodes));
203 if (node.Parent < 0)
204 roots.Add(i);
205 else
206 children[node.Parent].Add(i);
207 }
208
209 var nodes = clipNodes.Select((node, index) =>
210 new ModelNode(node.Name, children[index], node.Translation, node.Rotation, node.Scale)).ToArray();
211 return ModelFile.Write(new Model(nodes, roots, [], [], [], [], [], animations, [], ModelExtras.Empty));
212 }
213}