Skip to content
0.2.0-dev Download ZIP
313 lines ·15.3 KB Raw
1using System.Collections.Concurrent;
2using System.Globalization;
3using System.Reflection;
4using System.Text;
5using System.Text.RegularExpressions;
6using EvilEngine.Conversion;
7using EvilEngine.Formats;
8using EvilEngine.Formats.Materials;
9using EvilEngine.Mounts;
10
11namespace EvilEngine.Host.Tests;
12
13public sealed class GarrysModMaterialOracleTests(ITestOutputHelper output)
14{
15 private static readonly string Installed = typeof(GarrysModMaterialOracleTests).Assembly
16 .GetCustomAttributes<AssemblyMetadataAttribute>()
17 .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!;
18
19 private static readonly string[] Flags =
20 [
21 "debug", "no_debug_override", "no_draw", "use_in_fillrate_mode", "vertexcolor", "vertexalpha", "selfillum",
22 "additive",
23 "alphatest", "multipass", "znearer", "model", "flat", "nocull", "nofog", "ignorez", "decal", "envmapsphere",
24 "noalphamod",
25 "envmapcameraspace", "basealphaenvmapmask", "translucent", "normalmapalphaenvmapmask",
26 "needs_software_skinning",
27 "opaquetexture", "envmapmode", "suppress_decals", "halflambert", "wireframe", "allowalphatocoverage",
28 "ignore_alpha_modulation"
29 ];
30
31 private static readonly HashSet<string> Consumed = new(StringComparer.OrdinalIgnoreCase)
32 { "no_fullbright", "nodecal" };
33
34 private static string Show(MaterialValue value)
35 {
36 return value switch
37 {
38 MaterialValue.Boolean flag => flag.Value ? "true" : "false",
39 MaterialValue.Integer integer => integer.Value.ToString(CultureInfo.InvariantCulture),
40 MaterialValue.Number number => number.Value.ToString("R", CultureInfo.InvariantCulture),
41 MaterialValue.Vector vector =>
42 $"[{string.Join(" ", vector.Values.Select(component => component.ToString("R", CultureInfo.InvariantCulture)))}]",
43 MaterialValue.Text text => $"\"{text.Value}\"",
44 _ => value.GetType().Name
45 };
46 }
47
48 private static Dictionary<string, Dumped> ReadDump(string path)
49 {
50 static string Unescape(string text)
51 {
52 return Regex.Replace(text, @"\\(\d{3})", match => ((char)int.Parse(match.Groups[1].Value)).ToString());
53 }
54
55 var materials = new Dictionary<string, Dumped>(StringComparer.OrdinalIgnoreCase);
56 Dumped? current = null;
57 foreach (var line in File.ReadLines(path, Encoding.UTF8))
58 {
59 var parts = line.Split('\t');
60 if (line.StartsWith('@'))
61 {
62 current = new Dumped(Unescape(parts[1]), parts[2] == "true",
63 new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
64 materials[Unescape(parts[0][1..])] = current;
65 }
66 else if (current is not null && parts.Length == 2)
67 {
68 current.Variables[Unescape(parts[0])] = Unescape(parts[1]);
69 }
70 }
71
72 return materials;
73 }
74
75 private static double[] Numbers(string text)
76 {
77 return text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
78 .Select(word => double.Parse(word, CultureInfo.InvariantCulture)).ToArray();
79 }
80
81 private static bool Close(double a, double b)
82 {
83 return Math.Abs(a - b) <= 1e-5 * Math.Max(1, Math.Abs(b));
84 }
85
86 private static double Gamma(double value)
87 {
88 return value < 0 ? 0 :
89 value >= 0.95 ? 1 : Math.Pow(MathF.Round((float)value * 255f, MidpointRounding.ToEven) / 255.0, 2.2);
90 }
91
92 private static string? Disagreement(MaterialValue ours, string theirs)
93 {
94 var kind = theirs.Length > 1 ? theirs[..2] : theirs;
95 var value = theirs.Length > 2 ? theirs[2..] : "";
96 switch (ours)
97 {
98 case MaterialValue.Boolean flag when kind == "n:":
99 return Close(Numbers(value)[0], flag.Value ? 1 : 0) ? null : "bool";
100 case MaterialValue.Integer integer when kind == "n:":
101 return Close(Numbers(value)[0], integer.Value) ? null : "integer";
102 case MaterialValue.Number number when kind == "n:":
103 return Close(Numbers(value)[0], number.Value) ? null : "number";
104 case MaterialValue.Vector vector when kind == "v:":
105 var three = Numbers(value);
106 return vector.Values.Take(3).Select((component, i) => Math.Abs(three[i] - Gamma(component)) < 1e-4)
107 .All(same => same)
108 ? null
109 : "vector";
110 case MaterialValue.Vector vector when kind == "n:":
111 return Close(Numbers(value)[0], vector.Values[0]) ? null : "vector as number";
112 case MaterialValue.Boolean or MaterialValue.Integer or MaterialValue.Number when kind == "s:":
113 var expected = ours switch
114 {
115 MaterialValue.Boolean b => b.Value ? 1 : 0, MaterialValue.Integer i => i.Value,
116 MaterialValue.Number n => n.Value, _ => 0
117 };
118 return double.TryParse(value, CultureInfo.InvariantCulture, out var parsed) && Close(parsed, expected)
119 ? null
120 : "number held as text";
121 case MaterialValue.Text text when kind == "s:":
122 return text.Value == value ? null : "text";
123 case MaterialValue.Text when kind == "n:":
124 return "text a shader turns into a number";
125 case MaterialValue.Table:
126 return kind == "m:" ? null : "transform";
127 default:
128 return $"{ours.GetType().Name} against {kind}";
129 }
130 }
131
132 [Fact]
133 public void MatchesWhatGarrysModHoldsForEveryMaterial()
134 {
135 var gmod = Environment.GetEnvironmentVariable("EVIL_GMOD");
136 var dump = Environment.GetEnvironmentVariable("EVIL_GMOD_MATERIALS");
137 Assert.SkipWhen(gmod is null || dump is null,
138 "Set EVIL_GMOD to a Garry's Mod install and EVIL_GMOD_MATERIALS to its material dumps, split by the path separator.");
139 var dumped = new Dictionary<string, Dumped>(StringComparer.OrdinalIgnoreCase);
140 foreach (var part in dump!.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
141 foreach (var (name, material) in ReadDump(part))
142 dumped[name] = material;
143 var host = new EngineHost();
144 host.Adapters.LoadAll([Installed]);
145 var mount = host.Mounts.Open(Assert.Single(host.Mounts.Probe(gmod!)));
146 host.Conversion.AddNamespace(ContentNamespace.For(mount));
147
148 var compared = 0;
149 var kinds = new ConcurrentDictionary<string, int>();
150 var samples = new ConcurrentDictionary<string, ConcurrentBag<string>>();
151 var shaders = new ConcurrentDictionary<string, int>();
152 var every = new ConcurrentBag<string>();
153
154 void Note(string kind, string sample)
155 {
156 every.Add($"{kind}\t{sample}");
157 kinds.AddOrUpdate(kind, 1, (_, count) => count + 1);
158 var bag = samples.GetOrAdd(kind, _ => []);
159 if (bag.Count < 40)
160 bag.Add(sample);
161 }
162
163 var unmounted = mount.Layers
164 .Where(layer => layer.Name.StartsWith("workshop/", StringComparison.Ordinal))
165 .Where(layer => layer.Files.EnumerateAll().Any(entry =>
166 entry.Path.Value.StartsWith("materials/", StringComparison.OrdinalIgnoreCase)
167 && entry.Path.Value.EndsWith(".vmt", StringComparison.OrdinalIgnoreCase)
168 && !dumped.ContainsKey(entry.Path.Value["materials/".Length..^4])))
169 .Select(layer => layer.Name)
170 .ToHashSet();
171 output.WriteLine($"Workshop items with no materials in GMod's dump: {string.Join(", ", unmounted.Order())}");
172
173 Parallel.ForEach(dumped, pair =>
174 {
175 var (name, theirs) = pair;
176 if (mount.Origin(VirtualPath.Parse($"materials/{name}.vmt")) is { } origin &&
177 unmounted.Contains(origin.Layer.Name))
178 {
179 Note("from a workshop item missing from GMod's dump", name);
180 return;
181 }
182
183 var result = host.Conversion.Get(ContentKind.Material, ContentId.Create("gmod", $"materials/{name}"));
184 if (!result.Succeeded)
185 {
186 Note(
187 result.Diagnostics[^1].Contains("No converter") ? "not in this mount" :
188 theirs.Error ? "fails here, error in GMod" : "fails here, loads in GMod",
189 $"{name}: {result.Diagnostics[^1]}");
190 return;
191 }
192
193 var ours = MaterialText.Read(Encoding.UTF8.GetString(result.Content!.Data.Span), name);
194 if (theirs.Error)
195 {
196 Note(
197 name.Contains('.')
198 ? "a name with a dot, which GMod cuts at the dot and can't load"
199 : "GMod couldn't load it", name);
200 return;
201 }
202
203 if (ours.Shader.Name == "shaders/subrect")
204 {
205 Note("subrect, which GMod turns into the material it names", name);
206 return;
207 }
208
209 Interlocked.Increment(ref compared);
210 shaders.AddOrUpdate($"{ours.Shader.Name[8..]} → {theirs.Shader.ToLowerInvariant()}", 1,
211 (_, count) => count + 1);
212 var flags = theirs.Variables.TryGetValue("$flags", out var bits) && bits.StartsWith("n:")
213 ? (long)Numbers(bits[2..])[0]
214 : 0;
215 var defined = theirs.Variables.TryGetValue("$flags_defined", out var mask) && mask.StartsWith("n:")
216 ? (long)Numbers(mask[2..])[0]
217 : 0;
218 foreach (var (key, value) in ours.Parameters)
219 {
220 var bit = Array.IndexOf(Flags, key);
221 if (bit >= 0)
222 {
223 var set = ((flags >> bit) & 1) == 1;
224 if (value is MaterialValue.Boolean flag && flag.Value != set)
225 Note(
226 set ? "flag GMod's shader sets" :
227 ((defined >> bit) & 1) == 1 ? "flag GMod's shader clears" : "flag we set that GMod doesn't",
228 $"{name}: ${key} ours {Show(value)}, GMod $flags bit {(set ? 1 : 0)}, defined {(defined >> bit) & 1}");
229 continue;
230 }
231
232 if (!theirs.Variables.TryGetValue($"${key}", out var held))
233 Note(
234 Consumed.Contains(key)
235 ? "kept, though GMod's material system takes it into its own flags"
236 : "parameter GMod doesn't hold", $"{name}: ${key} = {Show(value)}");
237 else if (Disagreement(value, held) is { } kind)
238 Note(kind.StartsWith("text a shader") ? kind : $"{kind} differs",
239 $"{name}: ${key} ours {Show(value)}, GMod {held}, shader {theirs.Shader}");
240 }
241
242 foreach (var (key, id) in ours.Textures)
243 if (!theirs.Variables.TryGetValue($"${key}", out var held))
244 {
245 Note(
246 id == ContentId.Parse("evil:targets/probe")
247 ? "env_cubemap, which GMod binds as it draws"
248 : "texture GMod's shader leaves out", $"{name}: ${key} = {id}");
249 }
250 else if (!held.StartsWith("t:") && !held.StartsWith("s:"))
251 {
252 Note("texture GMod holds as something else", $"{name}: ${key} ours {id}, GMod {held}");
253 }
254 else
255 {
256 var texture = held[2..].Split('|')[0].Replace('\\', '/').ToLowerInvariant();
257 var expected = id.Namespace == "evil" ? null : id.Name["materials/".Length..];
258 if (texture == "error")
259 Note("GMod draws its error texture", $"{name}: ${key} ours {id}");
260 else if (expected is not null && texture != expected && texture != $"{expected}.hdr" &&
261 key == "startexture" && ours.Games.ContainsKey("gmod"))
262 Note("written by GMod's SkyPaint proxy as it draws", $"{name}: ${key} ours {id}, GMod {held}");
263 else if (expected is not null && texture != expected && texture != $"{expected}.hdr"
264 && mount.Origin(VirtualPath.Parse($"{id.Name}.vtf")) is { Layer.Name: var layer } &&
265 layer.StartsWith("workshop/", StringComparison.Ordinal))
266 Note("a texture only in a workshop GMA, which the oracle run unpacked no textures from",
267 $"{name}: ${key} ours {id}, GMod {held}");
268 else if (expected is not null &&
269 expected.StartsWith("engine/defaultcubemap", StringComparison.Ordinal) &&
270 texture != expected && texture != $"{expected}.hdr")
271 Note("a cube map in depot content this mount doesn't layer yet",
272 $"{name}: ${key} ours {id}, GMod {held}");
273 else if (expected is not null && texture != expected && texture != $"{expected}.hdr")
274 Note("texture differs", $"{name}: ${key} ours {id}, GMod {held}");
275 }
276
277 if (ours.Games.TryGetValue("gmod", out var block) &&
278 block.Entries.TryGetValue("unprefixed", out var extra) && extra is MaterialValue.Table unprefixed)
279 foreach (var (key, value) in unprefixed.Entries)
280 if (!theirs.Variables.TryGetValue(key, out var held))
281 Note("key without a $ GMod doesn't hold", $"{name}: {key} = {Show(value)}");
282 else if (Disagreement(value, held) is { } kind)
283 Note($"key without a $ differs ({kind})", $"{name}: {key} ours {Show(value)}, GMod {held}");
284 foreach (var (key, held) in theirs.Variables)
285 {
286 if (!key.StartsWith('$') || !held.StartsWith("t:") ||
287 key.Equals("$flashlighttexture", StringComparison.OrdinalIgnoreCase))
288 continue;
289 var bare = key[1..].ToLowerInvariant();
290 if (!ours.Textures.ContainsKey(bare) && !ours.Parameters.ContainsKey(bare))
291 Note("texture only GMod holds", $"{name}: {key} = {held}");
292 }
293 });
294
295 if (Environment.GetEnvironmentVariable("EVIL_GMOD_MATERIALS_REPORT") is { } report)
296 File.WriteAllLines(report, every.Order(StringComparer.Ordinal));
297 output.WriteLine($"{dumped.Count} materials in GMod's dump, {compared} compared");
298 foreach (var (kind, count) in kinds.OrderByDescending(pair => pair.Value))
299 {
300 output.WriteLine($"{count,6} × {kind}");
301 foreach (var sample in samples[kind].Order(StringComparer.Ordinal))
302 output.WriteLine($" {sample}");
303 }
304
305 foreach (var (pair, count) in shaders.OrderByDescending(pair => pair.Value))
306 output.WriteLine($"{count,6} × shader {pair}");
307 Assert.True(compared > 0);
308 Assert.DoesNotContain(kinds.Keys,
309 kind => kind.EndsWith("differs") || kind.StartsWith("fails here") || kind.StartsWith("flag we set"));
310 }
311
312 private sealed record Dumped(string Shader, bool Error, Dictionary<string, string> Variables);
313}