using System.Diagnostics.CodeAnalysis; using System.Text.Json.Nodes; using EvilEngine.Adapters.Zip; using EvilEngine.Mounts; namespace EvilEngine.Adapters.BeamNG; public enum Resolution { Found, Sealed, Missing } public sealed class GameFiles { public static readonly VirtualPath Content = "content"; public static readonly VirtualPath EngineArchive = "gameengine.zip"; private static readonly string[] Images = ["png", "jpg", "jpeg", "tga", "dds"]; private static readonly StringComparer Paths = StringComparer.OrdinalIgnoreCase; private readonly Dictionary _entries = new(Paths); private readonly Dictionary _links = new(Paths); public GameFiles(IFileSource install, ZipContainer zip, List notes) { Install = install; var archives = new List<(VirtualPath Path, ZipSource Source)>(); foreach (var path in ArchivePaths(install)) try { archives.Add((path, zip.Open(install, path, CaseRule.Insensitive))); } catch (MountException error) { notes.Add($"{path} can't be read as a ZIP, so it's left out: {error.Message}"); } Archives = archives; var collisions = 0; foreach (var (path, archive) in archives) foreach (var entry in archive.Directory.Entries) { if (!_entries.TryAdd(entry.Path.Value, (archive, entry))) { collisions++; continue; } if (entry.Encryption != ZipEncryption.None) Sealed[path] = Sealed.GetValueOrDefault(path) + 1; } if (collisions > 0) notes.Add( $"{collisions} paths are in more than one archive, and the first archive in ordinal order wins each."); View = new LayeredSource($"{install.Location} (game)", CaseRule.Insensitive, [ .. archives.Select(archive => new MountLayer(archive.Path.Value, "base", archive.Source)), new MountLayer("install", "base", install) ]); } public IFileSource Install { get; } public IReadOnlyList<(VirtualPath Path, ZipSource Source)> Archives { get; } public IFileSource View { get; } public Dictionary Sealed { get; } = []; public static IEnumerable ArchivePaths(IFileSource install) { var inContent = install.Enumerate(Content, true).Select(entry => entry.Path).Where(IsArchive); return inContent.Concat(install.Exists(EngineArchive) ? [EngineArchive] : []) .OrderBy(path => path.Value, StringComparer.Ordinal); } public bool TryEntry(VirtualPath path, [NotNullWhen(true)] out ZipEntry? entry) { entry = _entries.TryGetValue(path.Value, out var found) ? found.Entry : null; return entry is not null; } public bool IsSealed(VirtualPath path) { return _entries.TryGetValue(path.Value, out var found) && found.Entry.Encryption != ZipEncryption.None; } public bool Exists(VirtualPath path) { return _entries.ContainsKey(path.Value) || Install.Exists(path); } public IEnumerable EntriesOf(VirtualPath archive) { return Archives.Where(pair => pair.Path.Equals(archive, CaseRule.Insensitive)) .SelectMany(pair => pair.Source.Directory.Entries) .Where(entry => entry.Encryption == ZipEncryption.None) .Select(entry => entry.Path); } public IEnumerable Under(VirtualPath folder) { return View.Enumerate(folder, true).Select(entry => entry.Path).Where(path => !IsSealed(path)); } public Resolution Resolve(string written, out VirtualPath[] files) { files = []; var text = written.Replace('\\', '/').TrimStart('/'); if (!VirtualPath.TryParse(text, out var path) || path.IsRoot) return Resolution.Missing; var stem = path.WithoutExtension; var image = Images.Contains(path.Extension, Paths); VirtualPath[] candidates = image ? [path, Linked(path), Dds(stem), Linked(Dds(stem))] : [path, Linked(path)]; foreach (var candidate in candidates) { if (!Exists(candidate)) continue; if (IsSealed(candidate)) return Resolution.Sealed; if (!candidate.Extension.Equals("link", StringComparison.OrdinalIgnoreCase) || path.Extension.Equals("link", StringComparison.OrdinalIgnoreCase)) { files = [candidate]; return Resolution.Found; } files = [candidate, .. Follow(candidate)]; return files.Length > 1 ? Resolution.Found : Resolution.Missing; } return Resolution.Missing; } public byte[] Read(VirtualPath path) { return View.ReadAllBytes(path); } private VirtualPath[] Follow(VirtualPath link) { if (_links.TryGetValue(link.Value, out var known)) return known; VirtualPath[] result = []; try { if (LooseJson.Parse(Read(link)) is JsonObject json && json["path"]?.ToString() is { } target && VirtualPath.TryParse(target.Replace('\\', '/').TrimStart('/'), out var path) && !path.IsRoot) { if (Exists(path) && !IsSealed(path)) result = [path]; else if (Images.Contains(path.Extension, Paths) && Exists(Dds(path.WithoutExtension))) result = [Dds(path.WithoutExtension)]; } } catch (FormatException) { } _links[link.Value] = result; return result; } private static VirtualPath Linked(VirtualPath path) { return VirtualPath.Parse(path.Value + ".link"); } private static VirtualPath Dds(VirtualPath stem) { return VirtualPath.Parse(stem.Value + ".dds"); } private static bool IsArchive(VirtualPath path) { return path.Extension.Equals("zip", StringComparison.OrdinalIgnoreCase); } }