using EvilEngine.Formats.Models; namespace EvilEngine.Formats.Animations; public static class AnimationFile { public static Clip Read(ReadOnlyMemory bytes, string file) { return ReadAnimation(bytes, file) switch { Clip clip => clip, Blend blend => throw new ModelFormatException(file, $"blends {blend.Cells.Count} animations over {string.Join(" and ", blend.Parameters)}, and a clip is one."), _ => throw new ModelFormatException(file, "isn't a clip.") }; } public static Animation ReadAnimation(ReadOnlyMemory bytes, string file) { var model = ModelFile.Read(bytes, file); if (model.Meshes.Count > 0 || model.Skins.Count > 0) throw new ModelFormatException(file, "is animation, which holds no meshes or skins."); if (model.Animations.Count == 0) throw new ModelFormatException(file, "has no animations."); var parents = new int[model.Nodes.Count]; Array.Fill(parents, -1); for (var node = 0; node < model.Nodes.Count; node++) foreach (var child in model.Nodes[node].Children) parents[child] = node; var names = new HashSet(StringComparer.Ordinal); var nodes = model.Nodes.Select((node, index) => { if (node.Name is not { } name) throw new ModelFormatException(file, $"has node {index} with no name, and a clip's tracks go by name."); if (!names.Add(name)) throw new ModelFormatException(file, $"names two nodes '{name}', and a clip's tracks go by name."); return new ClipNode(name, parents[index], node.Translation, node.Rotation, node.Scale); }).ToArray(); var clips = model.Animations.Select(animation => Clip(animation, nodes, file)).ToArray(); if (model.Animations.Count == 1 && model.Animations[0].Info is not { Parameters.Count: > 0 }) return clips[0]; var parameters = model.Animations[0].Info?.Parameters ?? []; if (parameters.Count == 0) throw new ModelFormatException(file, $"has {model.Animations.Count} animations and no parameters placing them, and a clip is one."); if (model.Animations.Any(animation => animation.Info is not { } info || !info.Parameters.SequenceEqual(parameters))) throw new ModelFormatException(file, $"blends over {string.Join(" and ", parameters)}, and not every animation is placed on them."); var blend = new Blend(model.Animations[0].Info?.Blend ?? model.Animations[0].Name, parameters, clips.Select((clip, index) => new BlendCell(model.Animations[index].Info!.At, clip)).ToArray()); if (blend.Cells.Select(cell => string.Join(" ", cell.At)).Distinct().Count() != blend.Cells.Count) throw new ModelFormatException(file, "places two animations at the same point."); if (blend.Cells.Any(cell => cell.Clip.Loop != blend.Loop)) throw new ModelFormatException(file, "blends looping animations with ones that don't loop."); if (blend.Cells.Any(cell => cell.Clip.Delta != blend.Delta || cell.Clip.Realtime != blend.Realtime)) throw new ModelFormatException(file, "blends deltas with poses, or clocked animations with ones that aren't."); return blend; } private static Clip Clip(ModelAnimation animation, ClipNode[] nodes, string file) { var tracks = animation.Channels.Select(channel => { if (channel.Path == ModelChannelPath.Weights) throw new ModelFormatException(file, "animates morph weights, which a clip can't hold yet."); if (channel.Interpolation == ModelInterpolation.CubicSpline) throw new ModelFormatException(file, "has a cubic spline track, which a clip can't hold yet."); for (var key = 1; key < channel.Times.Length; key++) if (!(channel.Times[key] > channel.Times[key - 1])) throw new ModelFormatException(file, "has a track whose times don't rise."); return new ClipTrack(channel.Node, channel.Path, channel.Times, channel.Values, channel.Interpolation); }).ToArray(); var info = animation.Info; if (info?.Weights is { } weights && weights.Count != nodes.Length) throw new ModelFormatException(file, $"weighs {weights.Count} nodes, and it has {nodes.Length}."); return new Clip(animation.Name, nodes, tracks, info?.Model, info?.Rate, info?.Loop ?? false) { Move = info?.Move, Fade = info?.Fade, Overlay = info is null || (!info.Delta && !info.Realtime && info.Weights is null && info.Layers.Count == 0) ? AnimationOverlay.None : new AnimationOverlay(info.Delta, info.Realtime, info.Weights, info.Layers.Select(layer => new AnimationLayer(layer.Animation, layer.Always)).ToArray()) }; } public static byte[] Write(Animation animation) { return animation switch { Clip clip => Write(clip), Blend blend => Write(blend), _ => throw new ArgumentException($"{animation.GetType().Name} isn't animation the file holds.", nameof(animation)) }; } public static byte[] Write(Blend blend) { if (blend.Parameters.Count == 0 || blend.Cells.Count == 0) throw new ArgumentException("A blend places at least one clip on at least one parameter.", nameof(blend)); var nodes = blend.Nodes; foreach (var cell in blend.Cells) { if (cell.At.Count != blend.Parameters.Count) throw new ArgumentException( $"A cell sits at {cell.At.Count} values for {blend.Parameters.Count} parameters.", nameof(blend)); if (!cell.Clip.Nodes.Select(node => (node.Name, node.Parent)) .SequenceEqual(nodes.Select(node => (node.Name, node.Parent)))) throw new ArgumentException("A blend's clips share one tree of nodes.", nameof(blend)); if (cell.Clip.Rate is null) throw new ArgumentException("A blend's clips need their rates.", nameof(blend)); if (cell.Clip.Weights is { } weights && weights.Count != nodes.Count) throw new ArgumentException($"A cell weighs {weights.Count} nodes of {nodes.Count}.", nameof(blend)); } var glb = Write(nodes, blend.Cells.Select(cell => { var animation = Animation(cell.Clip, blend.Parameters, cell.At); return animation with { Info = animation.Info! with { Blend = blend.Name } }; }).ToArray()); if (WrittenChecks.Enabled) try { if (ReadAnimation(glb, "written blend") is not Blend) throw new ModelFormatException("written blend", "reads back as a clip."); } catch (ModelFormatException error) { throw new ArgumentException($"The blend wouldn't read back: {error.Message}", error); } return glb; } public static byte[] Write(Clip clip) { if (clip.Weights is { } weights && weights.Count != clip.Nodes.Count) throw new ArgumentException($"A clip weighs {weights.Count} nodes of {clip.Nodes.Count}.", nameof(clip)); var glb = Write(clip.Nodes, [Animation(clip, [], [])]); if (WrittenChecks.Enabled) try { Read(glb, "written clip"); } catch (ModelFormatException error) { throw new ArgumentException($"The clip wouldn't read back: {error.Message}", error); } return glb; } private static ModelAnimation Animation(Clip clip, IReadOnlyList parameters, IReadOnlyList at) { var channels = clip.Tracks.Select(track => { if (track.Node < 0 || track.Node >= clip.Nodes.Count) throw new ArgumentException($"A track names node {track.Node}, and there are {clip.Nodes.Count}.", nameof(clip)); if (track.Times.Length == 0 || track.Values.Length != track.Times.Length * track.Components) throw new ArgumentException( $"A track on '{clip.Nodes[track.Node].Name}' has {track.Times.Length} times and {track.Values.Length} values.", nameof(clip)); return new ModelChannel(track.Node, track.Path, track.Interpolation, track.Times, track.Values); }).ToArray(); return new ModelAnimation(clip.Name, channels) { Info = clip.Rate is { } rate ? new ModelAnimationInfo(clip.Model, rate, clip.Loop) { Move = clip.Move, Fade = clip.Fade, Parameters = parameters, At = at, Delta = clip.Delta, Realtime = clip.Realtime, Weights = clip.Weights, Layers = clip.Layers.Select(layer => new ModelAnimationLayer(layer.Animation, layer.Always)) .ToArray() } : clip.Model is not null || clip.Loop || clip.Move is not null || clip.Fade is not null || parameters.Count > 0 || clip.Delta || clip.Realtime || clip.Weights is not null || clip.Layers.Count > 0 ? throw new ArgumentException( "A clip naming its model, looping, moving, fading, layered, weighed or placed in a blend needs its rate.", nameof(clip)) : null }; } private static byte[] Write(IReadOnlyList clipNodes, IReadOnlyList animations) { var names = new HashSet(StringComparer.Ordinal); var children = clipNodes.Select(_ => new List()).ToArray(); var roots = new List(); for (var i = 0; i < clipNodes.Count; i++) { var node = clipNodes[i]; if (!names.Add(node.Name)) throw new ArgumentException($"A clip names two nodes '{node.Name}'.", nameof(clipNodes)); var up = node.Parent; for (var steps = 0; up >= 0; steps++, up = clipNodes[up].Parent) if (up >= clipNodes.Count || up == i || steps > clipNodes.Count) throw new ArgumentException($"Node '{node.Name}' isn't under a root of the clip's tree.", nameof(clipNodes)); if (node.Parent < 0) roots.Add(i); else children[node.Parent].Add(i); } var nodes = clipNodes.Select((node, index) => new ModelNode(node.Name, children[index], node.Translation, node.Rotation, node.Scale)).ToArray(); return ModelFile.Write(new Model(nodes, roots, [], [], [], [], [], animations, [], ModelExtras.Empty)); } }