Skip to content
0.2.0-dev Download ZIP
212 lines ·10.1 KB Raw
1using System.Globalization;
2using System.Numerics;
3using System.Reflection;
4using EvilEngine.Conversion;
5using EvilEngine.Formats;
6using EvilEngine.Formats.Animations;
7using EvilEngine.Formats.Models;
8using EvilEngine.Mounts;
9
10namespace EvilEngine.Host.Tests;
11
12public sealed class GarrysModClipTests(ITestOutputHelper output)
13{
14 private const float Inch = 0.0254f;
15
16 private static readonly string Installed = typeof(GarrysModClipTests).Assembly
17 .GetCustomAttributes<AssemblyMetadataAttribute>()
18 .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!;
19
20 private static EngineHost Host(string gmod)
21 {
22 var host = new EngineHost();
23 host.Adapters.LoadAll([Installed]);
24 var off = (Environment.GetEnvironmentVariable("EVIL_GMOD_WORKSHOP_OFF") ?? "")
25 .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
26 .ToDictionary(id => $"workshop/{id}", _ => ExternalSetting.Disabled);
27 var mount = host.Mounts.Open(Assert.Single(host.Mounts.Probe(gmod)), off);
28 host.Conversion.AddNamespace(ContentNamespace.For(mount));
29 return host;
30 }
31
32 [Fact]
33 public void MatchesGarrysModsPosesInThePoseOracleDump()
34 {
35 var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD");
36 var dump = Environment.GetEnvironmentVariable("EVIL_GMOD_POSES");
37 Assert.SkipWhen(gmod is null || dump is null,
38 "Set EVIL_GMOD to a Garry's Mod install and EVIL_GMOD_POSES to zz_evil_pose_oracle.lua's dump folder.");
39 var host = Host(gmod!);
40 var worst = 0f;
41 var walks = new List<float>();
42 foreach (var file in Directory.EnumerateFiles(dump!, "*.txt")
43 .Where(path => int.TryParse(Path.GetFileNameWithoutExtension(path), out _))
44 .OrderBy(path => int.Parse(Path.GetFileNameWithoutExtension(path), CultureInfo.InvariantCulture)))
45 {
46 var lines = File.ReadAllLines(file).Select(line => line.Split('\t')).ToArray();
47 var head = lines[0];
48 if (head.Length < 9 || head[4] == "-1")
49 {
50 output.WriteLine($"{string.Join(' ', head)}: Garry's Mod has no such sequence");
51 continue;
52 }
53
54 var model = ContentId.Create("gmod", head[1][..^4]);
55 var cycle = float.Parse(head[3], CultureInfo.InvariantCulture);
56 var built = host.Conversion.Get(ContentKind.Model, model);
57 var converted = host.Conversion.Get(ContentKind.Animation,
58 ContentId.Create("gmod", $"{model.Name}/anim/{head[2]}"));
59 if (converted.Content is null || built.Content is null)
60 {
61 output.WriteLine($"{model} {head[2]}: {string.Join("; ", converted.Diagnostics)}");
62 continue;
63 }
64
65 var body = ModelFile.Read(built.Content.Data, model.ToString());
66 var clip = AnimationFile.Read(converted.Content.Data, head[2]);
67 var posed = Pose(body, clip, cycle * clip.Length);
68 var errors = new List<(string Bone, float Millimetres, float Degrees)>();
69 foreach (var row in lines.Where(row => row[0] == "bone" && row.Length >= 15))
70 {
71 if (!posed.TryGetValue(row[1], out var ours))
72 continue;
73 var m = row.Skip(3).Select(value => float.Parse(value, CultureInfo.InvariantCulture)).ToArray();
74 var theirs = new Vector3(m[3], m[7], m[11]);
75 var position = new Vector3(ours.Translation.Z, ours.Translation.X, ours.Translation.Y) / Inch;
76 var degrees = 0f;
77 for (var axis = 0; axis < 3; axis++)
78 {
79 var unit = axis switch { 0 => Vector3.UnitZ, 1 => Vector3.UnitX, _ => Vector3.UnitY };
80 var turned = Vector3.TransformNormal(unit, ours);
81 var mine = Vector3.Normalize(new Vector3(turned.Z, turned.X, turned.Y));
82 var column = Vector3.Normalize(new Vector3(m[axis], m[4 + axis], m[8 + axis]));
83 degrees = Math.Max(degrees,
84 MathF.Acos(Math.Clamp(Vector3.Dot(mine, column), -1, 1)) * 180 / MathF.PI);
85 }
86
87 errors.Add((row[1], Vector3.Distance(position, theirs) * Inch * 1000, degrees));
88 }
89
90 var far = errors.MaxBy(error => error.Millimetres);
91 var turnedMost = errors.MaxBy(error => error.Degrees);
92 output.WriteLine($"{model.Name} {head[2]} cycle {cycle}: {errors.Count} bones, " +
93 $"mean {errors.Average(error => error.Millimetres):F3} mm, " +
94 $"worst {far.Millimetres:F3} mm ({far.Bone}), {turnedMost.Degrees:F3}° ({turnedMost.Bone})");
95 foreach (var error in errors.Where(error => error.Millimetres > 0.1f || error.Degrees > 0.01f))
96 output.WriteLine($" {error.Bone}: {error.Millimetres:F3} mm {error.Degrees:F3}°");
97 worst = Math.Max(worst, far.Millimetres);
98 if (head[2] == "menu_walk")
99 walks.Add(errors.Average(error => error.Millimetres));
100 }
101
102 output.WriteLine($"worst {worst:F3} mm");
103 Assert.SkipWhen(walks.Count == 0,
104 "No menu_walk clip converted; turn off workshop items that stub m_anm with EVIL_GMOD_WORKSHOP_OFF.");
105 Assert.All(walks, mean => Assert.True(mean < 0.5f, $"menu_walk is {mean:F3} mm off on average"));
106 }
107
108 [Fact]
109 public void ConvertsKleinersRunAndWalkAsBlendsOverMoveXAndMoveY()
110 {
111 var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD");
112 Assert.SkipWhen(gmod is null, "Set EVIL_GMOD to a Garry's Mod install to convert Kleiner's blends.");
113 var host = Host(gmod!);
114 foreach (var sequence in new[] { "run_all_01", "walk_all" })
115 {
116 var id = ContentId.Create("gmod", $"models/player/kleiner/anim/{sequence}");
117 var result = host.Conversion.Get(ContentKind.Animation, id);
118 Assert.True(result.Content is not null, string.Join("; ", result.Diagnostics));
119 var blend = Assert.IsType<Blend>(AnimationFile.ReadAnimation(result.Content!.Data, id.ToString()));
120 var grid = Assert.IsType<BlendGrid>(blend.Grid);
121 output.WriteLine($"{sequence}: {string.Join(" by ", blend.Parameters)}, " +
122 string.Join("; ", grid.Axes.Select(axis => string.Join(" ", axis))) +
123 $", cells {string.Join(", ", blend.Cells.Select(cell => cell.Clip.Name).Distinct())}");
124 Assert.Equal(["move_x", "move_y"], blend.Parameters.Order());
125 Assert.All(blend.Cells, cell => Assert.True(cell.Clip.Loop));
126 }
127 }
128
129 [Fact]
130 public void ConvertsThePickersPreviewClipsForEveryPlayermodel()
131 {
132 var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD");
133 Assert.SkipWhen(gmod is null, "Set EVIL_GMOD to a Garry's Mod install to convert its playermodels' clips.");
134 var host = Host(gmod!);
135 var registry = LocalRegistry.Build(host.Mounts.Mounts.ToArray(), host.Conversion);
136 var people = registry.Playermodels().ToArray();
137 var failed = new List<string>();
138 var waiting = 0;
139 var converted = 0;
140 foreach (var person in people)
141 foreach (var sequence in new[] { "idle_all_01", "menu_walk" })
142 {
143 var id = ContentId.Create(person.Body.Model.Namespace, $"{person.Body.Model.Name}/anim/{sequence}");
144 var result = host.Conversion.Get(ContentKind.Animation, id);
145 if (result.Content is { } content && AnimationFile.Read(content.Data, id.ToString()).Tracks.Count > 0)
146 {
147 converted++;
148 }
149 else if (result.Diagnostics.Any(line =>
150 line.Contains("which isn't in its namespace", StringComparison.Ordinal)))
151 {
152 waiting++;
153 if (waiting <= 3)
154 output.WriteLine($"waiting {id}: {string.Join("; ", result.Diagnostics)}");
155 }
156 else
157 {
158 failed.Add($"{id}: {string.Join("; ", result.Diagnostics)}");
159 }
160 }
161
162 foreach (var line in failed)
163 output.WriteLine(line);
164 output.WriteLine($"{converted} clips for {people.Length} playermodels, {waiting} waiting on includes a Lua " +
165 $"addon writes at runtime, {failed.Count} failed");
166 Assert.Empty(failed);
167 }
168
169 private static Dictionary<string, Matrix4x4> Pose(Model body, Clip clip, float time)
170 {
171 var sampled = ClipSampler.Sample(clip, time);
172 var animated = new Dictionary<string, (bool Moves, bool Turns, ClipPose Pose)>(StringComparer.Ordinal);
173 foreach (var track in clip.Tracks)
174 {
175 var name = clip.Nodes[track.Node].Name;
176 var known = animated.GetValueOrDefault(name, (Moves: false, Turns: false, Pose: sampled[track.Node]));
177 animated[name] = track.Path switch
178 {
179 ModelChannelPath.Translation => known with { Moves = true },
180 ModelChannelPath.Rotation => known with { Turns = true },
181 _ => known
182 };
183 }
184
185 var world = new Dictionary<string, Matrix4x4>(StringComparer.Ordinal);
186
187 void Walk(int index, Matrix4x4 above)
188 {
189 var node = body.Nodes[index];
190 var translation = node.Translation;
191 var rotation = node.Rotation;
192 if (node.Name is { } name && animated.TryGetValue(name, out var pose))
193 {
194 if (pose.Moves)
195 translation = pose.Pose.Translation;
196 if (pose.Turns)
197 rotation = pose.Pose.Rotation;
198 }
199
200 var here = Matrix4x4.CreateScale(node.Scale) * Matrix4x4.CreateFromQuaternion(rotation) *
201 Matrix4x4.CreateTranslation(translation) * above;
202 if (node.Name is { } named)
203 world.TryAdd(named, here);
204 foreach (var child in node.Children)
205 Walk(child, here);
206 }
207
208 foreach (var root in body.Roots)
209 Walk(root, Matrix4x4.Identity);
210 return world;
211 }
212}