using System.Globalization; using System.Numerics; using System.Reflection; using EvilEngine.Conversion; using EvilEngine.Formats; using EvilEngine.Formats.Animations; using EvilEngine.Formats.Models; using EvilEngine.Mounts; namespace EvilEngine.Host.Tests; public sealed class GarrysModClipTests(ITestOutputHelper output) { private const float Inch = 0.0254f; private static readonly string Installed = typeof(GarrysModClipTests).Assembly .GetCustomAttributes() .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!; private static EngineHost Host(string gmod) { var host = new EngineHost(); host.Adapters.LoadAll([Installed]); var off = (Environment.GetEnvironmentVariable("EVIL_GMOD_WORKSHOP_OFF") ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .ToDictionary(id => $"workshop/{id}", _ => ExternalSetting.Disabled); var mount = host.Mounts.Open(Assert.Single(host.Mounts.Probe(gmod)), off); host.Conversion.AddNamespace(ContentNamespace.For(mount)); return host; } [Fact] public void MatchesGarrysModsPosesInThePoseOracleDump() { var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD"); var dump = Environment.GetEnvironmentVariable("EVIL_GMOD_POSES"); Assert.SkipWhen(gmod is null || dump is null, "Set EVIL_GMOD to a Garry's Mod install and EVIL_GMOD_POSES to zz_evil_pose_oracle.lua's dump folder."); var host = Host(gmod!); var worst = 0f; var walks = new List(); foreach (var file in Directory.EnumerateFiles(dump!, "*.txt") .Where(path => int.TryParse(Path.GetFileNameWithoutExtension(path), out _)) .OrderBy(path => int.Parse(Path.GetFileNameWithoutExtension(path), CultureInfo.InvariantCulture))) { var lines = File.ReadAllLines(file).Select(line => line.Split('\t')).ToArray(); var head = lines[0]; if (head.Length < 9 || head[4] == "-1") { output.WriteLine($"{string.Join(' ', head)}: Garry's Mod has no such sequence"); continue; } var model = ContentId.Create("gmod", head[1][..^4]); var cycle = float.Parse(head[3], CultureInfo.InvariantCulture); var built = host.Conversion.Get(ContentKind.Model, model); var converted = host.Conversion.Get(ContentKind.Animation, ContentId.Create("gmod", $"{model.Name}/anim/{head[2]}")); if (converted.Content is null || built.Content is null) { output.WriteLine($"{model} {head[2]}: {string.Join("; ", converted.Diagnostics)}"); continue; } var body = ModelFile.Read(built.Content.Data, model.ToString()); var clip = AnimationFile.Read(converted.Content.Data, head[2]); var posed = Pose(body, clip, cycle * clip.Length); var errors = new List<(string Bone, float Millimetres, float Degrees)>(); foreach (var row in lines.Where(row => row[0] == "bone" && row.Length >= 15)) { if (!posed.TryGetValue(row[1], out var ours)) continue; var m = row.Skip(3).Select(value => float.Parse(value, CultureInfo.InvariantCulture)).ToArray(); var theirs = new Vector3(m[3], m[7], m[11]); var position = new Vector3(ours.Translation.Z, ours.Translation.X, ours.Translation.Y) / Inch; var degrees = 0f; for (var axis = 0; axis < 3; axis++) { var unit = axis switch { 0 => Vector3.UnitZ, 1 => Vector3.UnitX, _ => Vector3.UnitY }; var turned = Vector3.TransformNormal(unit, ours); var mine = Vector3.Normalize(new Vector3(turned.Z, turned.X, turned.Y)); var column = Vector3.Normalize(new Vector3(m[axis], m[4 + axis], m[8 + axis])); degrees = Math.Max(degrees, MathF.Acos(Math.Clamp(Vector3.Dot(mine, column), -1, 1)) * 180 / MathF.PI); } errors.Add((row[1], Vector3.Distance(position, theirs) * Inch * 1000, degrees)); } var far = errors.MaxBy(error => error.Millimetres); var turnedMost = errors.MaxBy(error => error.Degrees); output.WriteLine($"{model.Name} {head[2]} cycle {cycle}: {errors.Count} bones, " + $"mean {errors.Average(error => error.Millimetres):F3} mm, " + $"worst {far.Millimetres:F3} mm ({far.Bone}), {turnedMost.Degrees:F3}° ({turnedMost.Bone})"); foreach (var error in errors.Where(error => error.Millimetres > 0.1f || error.Degrees > 0.01f)) output.WriteLine($" {error.Bone}: {error.Millimetres:F3} mm {error.Degrees:F3}°"); worst = Math.Max(worst, far.Millimetres); if (head[2] == "menu_walk") walks.Add(errors.Average(error => error.Millimetres)); } output.WriteLine($"worst {worst:F3} mm"); Assert.SkipWhen(walks.Count == 0, "No menu_walk clip converted; turn off workshop items that stub m_anm with EVIL_GMOD_WORKSHOP_OFF."); Assert.All(walks, mean => Assert.True(mean < 0.5f, $"menu_walk is {mean:F3} mm off on average")); } [Fact] public void ConvertsKleinersRunAndWalkAsBlendsOverMoveXAndMoveY() { var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD"); Assert.SkipWhen(gmod is null, "Set EVIL_GMOD to a Garry's Mod install to convert Kleiner's blends."); var host = Host(gmod!); foreach (var sequence in new[] { "run_all_01", "walk_all" }) { var id = ContentId.Create("gmod", $"models/player/kleiner/anim/{sequence}"); var result = host.Conversion.Get(ContentKind.Animation, id); Assert.True(result.Content is not null, string.Join("; ", result.Diagnostics)); var blend = Assert.IsType(AnimationFile.ReadAnimation(result.Content!.Data, id.ToString())); var grid = Assert.IsType(blend.Grid); output.WriteLine($"{sequence}: {string.Join(" by ", blend.Parameters)}, " + string.Join("; ", grid.Axes.Select(axis => string.Join(" ", axis))) + $", cells {string.Join(", ", blend.Cells.Select(cell => cell.Clip.Name).Distinct())}"); Assert.Equal(["move_x", "move_y"], blend.Parameters.Order()); Assert.All(blend.Cells, cell => Assert.True(cell.Clip.Loop)); } } [Fact] public void ConvertsThePickersPreviewClipsForEveryPlayermodel() { var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD"); Assert.SkipWhen(gmod is null, "Set EVIL_GMOD to a Garry's Mod install to convert its playermodels' clips."); var host = Host(gmod!); var registry = LocalRegistry.Build(host.Mounts.Mounts.ToArray(), host.Conversion); var people = registry.Playermodels().ToArray(); var failed = new List(); var waiting = 0; var converted = 0; foreach (var person in people) foreach (var sequence in new[] { "idle_all_01", "menu_walk" }) { var id = ContentId.Create(person.Body.Model.Namespace, $"{person.Body.Model.Name}/anim/{sequence}"); var result = host.Conversion.Get(ContentKind.Animation, id); if (result.Content is { } content && AnimationFile.Read(content.Data, id.ToString()).Tracks.Count > 0) { converted++; } else if (result.Diagnostics.Any(line => line.Contains("which isn't in its namespace", StringComparison.Ordinal))) { waiting++; if (waiting <= 3) output.WriteLine($"waiting {id}: {string.Join("; ", result.Diagnostics)}"); } else { failed.Add($"{id}: {string.Join("; ", result.Diagnostics)}"); } } foreach (var line in failed) output.WriteLine(line); output.WriteLine($"{converted} clips for {people.Length} playermodels, {waiting} waiting on includes a Lua " + $"addon writes at runtime, {failed.Count} failed"); Assert.Empty(failed); } private static Dictionary Pose(Model body, Clip clip, float time) { var sampled = ClipSampler.Sample(clip, time); var animated = new Dictionary(StringComparer.Ordinal); foreach (var track in clip.Tracks) { var name = clip.Nodes[track.Node].Name; var known = animated.GetValueOrDefault(name, (Moves: false, Turns: false, Pose: sampled[track.Node])); animated[name] = track.Path switch { ModelChannelPath.Translation => known with { Moves = true }, ModelChannelPath.Rotation => known with { Turns = true }, _ => known }; } var world = new Dictionary(StringComparer.Ordinal); void Walk(int index, Matrix4x4 above) { var node = body.Nodes[index]; var translation = node.Translation; var rotation = node.Rotation; if (node.Name is { } name && animated.TryGetValue(name, out var pose)) { if (pose.Moves) translation = pose.Pose.Translation; if (pose.Turns) rotation = pose.Pose.Rotation; } var here = Matrix4x4.CreateScale(node.Scale) * Matrix4x4.CreateFromQuaternion(rotation) * Matrix4x4.CreateTranslation(translation) * above; if (node.Name is { } named) world.TryAdd(named, here); foreach (var child in node.Children) Walk(child, here); } foreach (var root in body.Roots) Walk(root, Matrix4x4.Identity); return world; } }