Skip to content
0.2.0-dev Download ZIP
256 lines ·10.3 KB Raw
1using System.Text.RegularExpressions;
2using EvilEngine.Adapters.Pc;
3using EvilEngine.Adapters.Source;
4using EvilEngine.Adapters.Steam;
5using EvilEngine.Formats.Records;
6using EvilEngine.Mounts;
7
8namespace EvilEngine.Adapters.Left4Dead2;
9
10public sealed partial class Left4Dead2Game : IGameAdapter
11{
12 public const string BaseFolder = "left4dead2";
13
14 public const string PlatformFolder = "platform";
15
16 public const string Vpk = "pak01_dir.vpk";
17
18 public const string GameInfoPath = "|gameinfo_path|";
19
20 public static readonly VirtualPath SteamInf = "left4dead2/steam.inf";
21
22 public static readonly VirtualPath GameInfo = "left4dead2/gameinfo.txt";
23
24 public static readonly VirtualPath Addons = "left4dead2/addons";
25
26 public static readonly VirtualPath AddonList = "left4dead2/addonlist.txt";
27
28 public static readonly IReadOnlyList<(VirtualPath Path, string Os)> Engines =
29 [("bin/engine.so", "linux"), ("bin/engine.dll", "windows"), ("bin/engine.dylib", "macos")];
30
31 public static readonly IReadOnlyList<string> ContentFolders =
32 [
33 "expressions", "maps", "materials", "media", "models", "particles", "resource", "scenes", "scripts", "sound",
34 "vgui"
35 ];
36
37 private static readonly Platform Pc = PcPlatform.Platform;
38
39 public string Game => Left4Dead2.Game;
40
41 public IReadOnlyList<Platform> Platforms { get; } = [Pc];
42
43 public MountProbe? Probe(IFileSource tree)
44 {
45 if (!tree.Exists(SteamInf) || !tree.Exists(GameInfo) || !tree.Exists($"{BaseFolder}/{Vpk}"))
46 return null;
47 var steam = SourceBuild.SteamInf(tree.ReadAllText(SteamInf));
48 if (steam.GetValueOrDefault("ProductName") != Left4Dead2.Game ||
49 steam.GetValueOrDefault("appID") != Left4Dead2.AppId)
50 return null;
51 var evidence = new List<string>
52 { $"{SteamInf} names ProductName={Left4Dead2.Game} and appID={Left4Dead2.AppId}" };
53 if (steam.GetValueOrDefault("PatchVersion") is { Length: > 0 } version)
54 evidence.Add($"its PatchVersion is {version}");
55 foreach (var (file, player) in new[]
56 { ("hl2_linux", "linux"), ("left4dead2.exe", "windows"), ("hl2_osx", "macos") })
57 if (tree.Exists(file))
58 evidence.Add($"{file} is the {player} player build");
59
60 DateTime? build = null;
61 foreach (var (engine, os) in Engines.Where(engine => tree.Exists(engine.Path)))
62 {
63 if (SourceBuild.Read(tree, engine) is not { } stamp)
64 {
65 evidence.Add($"{engine} has no build stamp");
66 continue;
67 }
68
69 evidence.Add($"{engine}, the {os} engine, was built at {stamp:yyyy-MM-dd HH:mm:ss}");
70 build ??= stamp;
71 }
72
73 if (build is not { } found)
74 {
75 evidence.Add("no engine binary with a build stamp was found, so the build is unknown");
76 return new MountProbe(new MountId(Game, Pc.Id, "unknown"), ProbeStatus.UnknownVariant, tree)
77 { Evidence = evidence, Externals = SteamClaims.Externals };
78 }
79
80 return new MountProbe(new MountId(Game, Pc.Id, SourceBuild.Id(found)), ProbeStatus.Known, tree)
81 { Evidence = evidence, Externals = SteamClaims.Externals };
82 }
83
84 public MountPlan Open(MountProbe probe, Externals externals)
85 {
86 var tree = probe.Tree;
87 var notes = new List<string>();
88 var claims = SteamClaims.For(tree, externals, Left4Dead2.AppId, notes)
89 .ToDictionary(pair => pair.Key.Value, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
90
91 var folders = Folders(tree, notes);
92 var addons = AddonVpks(tree, notes);
93
94 var layers = new List<LayerPlan>();
95 foreach (var (name, vpk) in addons)
96 layers.Add(new LayerPlan(vpk.Value, "addon", new LayerSource.Container(tree, vpk)));
97 foreach (var folder in folders)
98 if (tree.Exists(folder.Join(Vpk)))
99 layers.Add(new LayerPlan($"{folder}/pak01.vpk", "base",
100 new LayerSource.Container(tree, folder.Join(Vpk))));
101 foreach (var folder in folders)
102 layers.Add(new LayerPlan(folder.Value, "base", new LayerSource.Tree(new SubtreeSource(tree, folder))));
103 if (tree.DirectoryExists(PlatformFolder))
104 layers.Add(new LayerPlan(PlatformFolder, "platform",
105 new LayerSource.Tree(new SubtreeSource(tree, PlatformFolder))));
106
107 PartPlan Part(string name, IEnumerable<VirtualPath> files)
108 {
109 VirtualPath[] defining = [.. files.Distinct().Order()];
110 return new PartPlan(name, defining)
111 {
112 Sha1Claims = true,
113 Claims = defining.Where(path => claims.ContainsKey(path.Value))
114 .ToDictionary(path => path, path => claims[path.Value])
115 };
116 }
117
118 var parts = new List<PartPlan>
119 { Part("content", folders.Append(PlatformFolder).SelectMany(folder => Content(tree, folder))) };
120 parts.AddRange(addons.Select(addon => Part(addon.Name, [addon.Vpk])));
121
122 return new MountPlan(Pc.CaseRule)
123 {
124 Layers = layers,
125 Parts = parts,
126 BuildFiles =
127 [
128 SteamInf, GameInfo,
129 .. Engines.Select(engine => engine.Path).Where(engine => tree.Exists(engine)).Take(1),
130 .. folders.Select(folder => folder.Join(Vpk)).Where(path => tree.Exists(path))
131 ],
132 Records = [AlbumRecords.Set],
133 Notes = notes
134 };
135 }
136
137 public static IReadOnlyList<VirtualPath> Folders(IFileSource tree, List<string> notes)
138 {
139 if (Workshop.Read(tree, GameInfo, notes) is not { } info)
140 return [];
141 if (info["FileSystem"]?["SearchPaths"] is not { } paths)
142 {
143 notes.Add($"{GameInfo} has no FileSystem SearchPaths block, so nothing is searched.");
144 return [];
145 }
146
147 var folders = new List<VirtualPath>();
148 foreach (var path in paths.Children.Where(path => path.Value is not null))
149 {
150 if (!path.Key.Split('+').Contains("game", StringComparer.OrdinalIgnoreCase))
151 continue;
152 if (Resolve(path.Value!) is not { } folder)
153 {
154 notes.Add($"{GameInfo} names {path.Value}, which isn't a folder in the install, so it's skipped.");
155 continue;
156 }
157
158 if (folders.Any(known => known.Equals(folder, Pc.CaseRule)))
159 continue;
160 if (!tree.DirectoryExists(folder))
161 {
162 notes.Add($"{GameInfo} names {folder}, which isn't installed, so it's skipped.");
163 continue;
164 }
165
166 folders.Add(folder);
167 }
168
169 return folders;
170 }
171
172 public static VirtualPath? Resolve(string written)
173 {
174 var text = written.Replace('\\', VirtualPath.Separator);
175 if (text.StartsWith(GameInfoPath, StringComparison.OrdinalIgnoreCase))
176 text = $"{BaseFolder}/{text[GameInfoPath.Length..]}";
177 var parts = text.Split(VirtualPath.Separator, StringSplitOptions.RemoveEmptyEntries)
178 .Where(part => part != ".").ToArray();
179 if (parts.Length == 0 || parts.Contains("..") || parts[0].Contains(':'))
180 return null;
181 return VirtualPath.TryParse(string.Join(VirtualPath.Separator, parts), out var path)
182 ? path
183 : (VirtualPath?)null;
184 }
185
186 public static IReadOnlyList<(string Name, VirtualPath Vpk)> AddonVpks(IFileSource tree, List<string> notes)
187 {
188 var off = AddonsOff(tree, notes);
189 var found = new List<(string Name, VirtualPath Vpk)>();
190 var skipped = new List<string>();
191 foreach (var entry in tree.Enumerate(Addons, true))
192 {
193 if (!entry.Path.Extension.Equals("vpk", StringComparison.OrdinalIgnoreCase) ||
194 !entry.Path.TryRelativeTo(Addons, Pc.CaseRule, out var relative))
195 continue;
196 var stem = relative.Value[..^".vpk".Length];
197 string name;
198 if (WorkshopName().Match(relative.Value) is { Success: true } workshop)
199 {
200 name = $"workshop/{workshop.Groups[1].Value}";
201 }
202 else if (!stem.Contains(VirtualPath.Separator))
203 {
204 name = $"addons/{stem}";
205 }
206 else
207 {
208 notes.Add(
209 $"{entry.Path} isn't an add-on the game loads, which are VPKs in {Addons} and its workshop folder, so it's left out.");
210 continue;
211 }
212
213 if (off.Contains(relative.Value))
214 {
215 skipped.Add(relative.Value);
216 continue;
217 }
218
219 found.Add((name, entry.Path));
220 }
221
222 if (skipped.Count > 0)
223 notes.Add(
224 $"{AddonList} turns off {string.Join(", ", skipped.Order(StringComparer.OrdinalIgnoreCase))}, so " +
225 (skipped.Count == 1 ? "it isn't mounted." : "they aren't mounted."));
226 return [.. found.OrderBy(addon => addon.Vpk.Value, StringComparer.OrdinalIgnoreCase)];
227 }
228
229 public static IReadOnlySet<string> AddonsOff(IFileSource tree, List<string> notes)
230 {
231 var off = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
232 if (!tree.Exists(AddonList) || Workshop.Read(tree, AddonList, notes) is not { } list)
233 return off;
234 foreach (var addon in list.Children.Where(addon => addon.Value is not null))
235 if (addon.Value!.Trim() == "0")
236 off.Add(addon.Key.Replace('\\', VirtualPath.Separator));
237 return off;
238 }
239
240 public static IEnumerable<VirtualPath> Content(IFileSource tree, VirtualPath folder)
241 {
242 foreach (var entry in tree.Enumerate(folder, false))
243 if (VpkName().IsMatch(entry.Path.Name))
244 yield return entry.Path;
245 foreach (var name in ContentFolders)
246 foreach (var entry in tree.Enumerate(folder.Join(name), true))
247 if (!entry.Path.Extension.Equals("cache", StringComparison.OrdinalIgnoreCase))
248 yield return entry.Path;
249 }
250
251 [GeneratedRegex(@"^pak01_(dir|\d{3})\.vpk$", RegexOptions.IgnoreCase)]
252 private static partial Regex VpkName();
253
254 [GeneratedRegex(@"^workshop/(\d+)\.vpk$", RegexOptions.IgnoreCase)]
255 private static partial Regex WorkshopName();
256}