using System.Buffers.Binary; using System.Collections.Concurrent; using EvilEngine.Adapters.Gma; using EvilEngine.Adapters.Source.Textures; using EvilEngine.Adapters.Vpk; using EvilEngine.Formats.Textures; using EvilEngine.Mounts; namespace EvilEngine.Adapters.Tests; public sealed class GarrysModVtfTests(ITestOutputHelper output) { private static readonly int[][] Orders = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]; private static List<(string Name, Func Read)> EveryVtf() { var path = Environment.GetEnvironmentVariable("EVIL_GMOD"); Assert.SkipWhen(path is null, "Set EVIL_GMOD to a Garry's Mod install to convert its VTFs."); var install = new FolderSource(path!, CaseRule.Insensitive); var files = new List<(string, Func)>(); void Add(IFileSource source, string prefix, IEnumerable paths) { foreach (var file in paths.Where(file => file.Value.EndsWith(".vtf", StringComparison.OrdinalIgnoreCase))) files.Add(($"{prefix}{file}", () => { using var stream = source.Open(file); using var buffer = new MemoryStream(); stream.CopyTo(buffer); return buffer.ToArray(); })); } var vpks = new VpkContainer(); foreach (var directory in install.EnumerateAll().Select(entry => entry.Path) .Where(file => file.Name.EndsWith("_dir.vpk", StringComparison.OrdinalIgnoreCase)).Order()) { var vpk = (VpkSource)vpks.Open(install, directory); Add(vpk, $"{directory}:", vpk.Archive.Entries.Select(entry => entry.Path)); } Add(install, "", install.EnumerateAll().Select(entry => entry.Path)); var workshop = Path.GetFullPath(Path.Combine(path!, "../../workshop/content/4000")); if (Directory.Exists(workshop)) { var items = new FolderSource(workshop, CaseRule.Insensitive); var gmas = new GmaContainer(); foreach (var item in items.EnumerateAll().Select(entry => entry.Path) .Where(file => gmas.Recognises(items, file)).Order()) { var gma = (GmaSource)gmas.Open(items, item); Add(gma, $"{item}:", gma.EnumerateAll().Select(entry => entry.Path)); } } return files; } [Fact] public void ConvertsEveryVtfInARealInstall() { var files = EveryVtf(); var failures = new ConcurrentBag(); var warnings = new ConcurrentBag(); var tally = new ConcurrentDictionary(); var orderError = new ConcurrentDictionary(); void Count(string key) { tally.AddOrUpdate(key, 1, (_, count) => count + 1); } Parallel.ForEach(files, file => { try { var bytes = file.Read(); var vtf = VtfFile.Read(bytes, file.Name); var texture = VtfTexture.From(vtf, warnings.Add); var back = TextureFile.Read(TextureFile.Write(texture), file.Name); Assert.Equal(texture.Levels.Count, back.Levels.Count); for (var level = 0; level < texture.Levels.Count; level++) Assert.Equal(texture.Levels[level], back.Levels[level]); Count($"{VtfFormats.Name(vtf.Format)} as {texture.Format}"); if (texture.Cube) Count(vtf.HasSphereMap ? "cube maps whose sphere map was dropped" : "cube maps with six faces"); if (texture.Layers > 1) Count("animated"); if (texture.Sheet is not null) Count("sheets"); if (texture.Detail?.Largest is not null) Count("clamped at full detail"); if (Order(vtf, texture) is { } errors) orderError.AddOrUpdate(VtfFormats.Name(vtf.Format), errors, (_, sum) => sum.Zip(errors, (a, b) => a + b).ToArray()); } catch (Exception error) when (error is VtfFormatException or TextureFormatException or ArgumentException) { failures.Add(error is ArgumentException ? $"{file.Name}: {error.Message}" : error.Message); } }); foreach (var (key, count) in tally.OrderByDescending(pair => pair.Value)) output.WriteLine($"{count,6} × {key}"); foreach (var (format, errors) in orderError.OrderBy(pair => pair.Key)) output.WriteLine( $"{format} against its thumbnail: {string.Join(", ", Orders.Select((order, i) => $"{string.Concat(order.Select(c => "rgb"[c]))} {errors[i]:F0}"))}"); output.WriteLine($"{files.Count} VTFs, {failures.Count} failed, {warnings.Count} warned"); foreach (var warning in warnings.Order(StringComparer.Ordinal)) output.WriteLine(warning); foreach (var failure in failures.Order(StringComparer.Ordinal).Take(100)) output.WriteLine(failure); Assert.NotEmpty(files); Assert.Empty(failures); foreach (var (format, errors) in orderError) Assert.True(errors[0] <= errors.Skip(1).Min(), $"{format}'s channels sit closer to its thumbnail in another order: {string.Join(", ", errors)}"); } private static double[]? Order(VtfFile vtf, Texture texture) { if (vtf.LowResFormat != VtfFormat.Dxt1 || vtf.LowRes.IsEmpty || texture.Format is not (TextureFormat.R8G8B8Unorm or TextureFormat.R8G8B8A8Unorm) || texture.Swizzle != "rgba") return null; var thumbnail = Mean(Bc1(vtf.LowRes, vtf.LowResWidth, vtf.LowResHeight), 4); var stride = texture.Format == TextureFormat.R8G8B8Unorm ? 3 : 4; var image = Mean(texture.Image(0).ToArray(), stride); return Orders.Select(order => Enumerable.Range(0, 3).Sum(c => Math.Abs(image[order[c]] - thumbnail[c]))) .ToArray(); } private static double[] Mean(byte[] texels, int stride) { var sum = new double[3]; var count = texels.Length / stride; for (var i = 0; i < count; i++) for (var c = 0; c < 3; c++) sum[c] += texels[i * stride + c]; return sum.Select(value => value / count).ToArray(); } private static byte[] Bc1(ReadOnlyMemory blocks, int width, int height) { var texels = new byte[width * height * 4]; var span = blocks.Span; (int R, int G, int B) Color(ushort value) { return ((value >> 11) * 255 / 31, ((value >> 5) & 63) * 255 / 63, (value & 31) * 255 / 31); } for (int by = 0, block = 0; by < (height + 3) / 4; by++) for (var bx = 0; bx < (width + 3) / 4; bx++, block++) { var at = span[(block * 8)..]; var (c0, c1) = (BinaryPrimitives.ReadUInt16LittleEndian(at), BinaryPrimitives.ReadUInt16LittleEndian(at[2..])); var (a, b) = (Color(c0), Color(c1)); (int R, int G, int B)[] palette = c0 > c1 ? [ a, b, ((2 * a.R + b.R) / 3, (2 * a.G + b.G) / 3, (2 * a.B + b.B) / 3), ((a.R + 2 * b.R) / 3, (a.G + 2 * b.G) / 3, (a.B + 2 * b.B) / 3) ] : [a, b, ((a.R + b.R) / 2, (a.G + b.G) / 2, (a.B + b.B) / 2), (0, 0, 0)]; var indices = BinaryPrimitives.ReadUInt32LittleEndian(at[4..]); for (var i = 0; i < 16; i++) { var (x, y) = (bx * 4 + i % 4, by * 4 + i / 4); if (x >= width || y >= height) continue; var color = palette[(indices >> (i * 2)) & 3]; var texel = (y * width + x) * 4; (texels[texel], texels[texel + 1], texels[texel + 2], texels[texel + 3]) = ((byte)color.R, (byte)color.G, (byte)color.B, 255); } } return texels; } }