using System.Buffers.Binary; using System.Globalization; using System.Numerics; using System.Text; using EvilEngine.Mounts; namespace EvilEngine.Adapters.Quake.Maps; public sealed class QuakeMapException(string file, string message) : Exception($"{file} {message}") { public string File { get; } = file; } public enum QuakeBspVersion { Bsp29, Bsp2 } public static class QuakeContents { public const int Empty = -1; public const int Solid = -2; public const int Water = -3; public const int Slime = -4; public const int Lava = -5; public const int Sky = -6; public const int Origin = -7; public const int Clip = -8; public const int CurrentLast = -14; } public readonly record struct QuakePlane(Vector3 Normal, float Distance); public readonly record struct QuakeNode(int Plane, int Front, int Back, int FirstFace, int FaceCount); public readonly record struct QuakeLeaf(int Contents, int FirstMark, int MarkCount); public readonly record struct QuakeTexInfo(Vector4 S, Vector4 T, int MipTex, int Flags) { public const int Special = 1; } public readonly record struct QuakeFace( int Plane, bool Back, int FirstEdge, int EdgeCount, int TexInfo, uint Styles, int LightOffset) { public const byte NoStyle = 255; public int StyleCount { get { var count = 0; while (count < 4 && Style(count) != NoStyle) count++; return count; } } public byte Style(int slot) { return (byte)(Styles >> (slot * 8)); } } public readonly record struct QuakeModel( Vector3 Min, Vector3 Max, Vector3 Origin, int HeadNode, int FirstFace, int FaceCount); public sealed record QuakeMipTex(string Name, int Width, int Height, IReadOnlyList>? Levels); public sealed class QuakeBsp { public const int MipLevels = 4; public const int LuxelSize = 16; private const int LumpCount = 15; private const int HeaderSize = 4 + LumpCount * 8; private const int Bsp2Magic = 0x32505342; private readonly Lazy> _edges; private readonly Lazy> _entities; private readonly Lazy> _extra; private readonly Lazy> _faces; private readonly Lazy> _leafs; private readonly Lazy> _lighting; private readonly (int Offset, int Length)[] _lumps; private readonly Lazy> _markSurfaces; private readonly Lazy> _mipTex; private readonly Lazy> _models; private readonly Lazy> _nodes; private readonly Lazy> _planes; private readonly Func> _read; private readonly Lazy> _surfEdges; private readonly Lazy> _texInfo; private readonly Lazy> _vertices; private QuakeBsp(string file, long length, Func> read) { File = file; _read = read; if (length < HeaderSize) throw new QuakeMapException(file, $"is {length} bytes, too short for a BSP header."); var header = read(0, HeaderSize).Span; var magic = BinaryPrimitives.ReadInt32LittleEndian(header); Version = magic switch { 29 => QuakeBspVersion.Bsp29, Bsp2Magic => QuakeBspVersion.Bsp2, _ => throw new QuakeMapException(file, $"is BSP version {Describe(header[..4])}, not 29 or BSP2.") }; _lumps = new (int, int)[LumpCount]; for (var i = 0; i < LumpCount; i++) { var offset = BinaryPrimitives.ReadInt32LittleEndian(header[(4 + i * 8)..]); var size = BinaryPrimitives.ReadInt32LittleEndian(header[(8 + i * 8)..]); if (offset < 0 || size < 0 || (long)offset + size > length) throw new QuakeMapException(file, $"puts lump {i} at {offset} for {size} bytes, past its {length}."); _lumps[i] = (offset, size); } var wide = Version == QuakeBspVersion.Bsp2; _planes = Lazy(() => Records(1, 20, span => new QuakePlane(Vector(span), Single(span, 12)))); _vertices = Lazy(() => Records(3, 12, Vector)); _nodes = Lazy(() => CheckNodes(wide ? Records(5, 44, span => new QuakeNode(Int(span, 0), Int(span, 4), Int(span, 8), Int(span, 36), Int(span, 40))) : Records(5, 24, span => new QuakeNode(Int(span, 0), Short(span, 4), Short(span, 6), UShort(span, 20), UShort(span, 22))))); _texInfo = Lazy(() => CheckTexInfo(Records(6, 40, span => new QuakeTexInfo( new Vector4(Single(span, 0), Single(span, 4), Single(span, 8), Single(span, 12)), new Vector4(Single(span, 16), Single(span, 20), Single(span, 24), Single(span, 28)), Int(span, 32), Int(span, 36))))); _faces = Lazy(() => CheckFaces(wide ? Records(7, 28, span => new QuakeFace(Int(span, 0), Int(span, 4) != 0, Int(span, 8), Int(span, 12), Int(span, 16), BinaryPrimitives.ReadUInt32LittleEndian(span[20..]), Int(span, 24))) : Records(7, 20, span => new QuakeFace(Short(span, 0), Short(span, 2) != 0, Int(span, 4), Short(span, 8), Short(span, 10), BinaryPrimitives.ReadUInt32LittleEndian(span[12..]), Int(span, 16))))); _lighting = new Lazy>(() => Lump(8)); _leafs = Lazy(() => wide ? Records(10, 44, span => new QuakeLeaf(Int(span, 0), Int(span, 32), Int(span, 36))) : Records(10, 28, span => new QuakeLeaf(Int(span, 0), UShort(span, 20), UShort(span, 22)))); _markSurfaces = Lazy(() => wide ? Records(11, 4, span => Int(span, 0)) : Records(11, 2, span => (int)UShort(span, 0))); _edges = Lazy(() => wide ? Records(12, 8, span => (Int(span, 0), Int(span, 4))) : Records(12, 4, span => ((int)UShort(span, 0), (int)UShort(span, 2)))); _surfEdges = Lazy(() => Records(13, 4, span => Int(span, 0))); _models = Lazy(() => CheckModels(Records(14, 64, span => new QuakeModel(Vector(span), Vector(span[12..]), Vector(span[24..]), Int(span, 36), Int(span, 56), Int(span, 60))))); _entities = Lazy(() => QuakeEntities.Read(Lump(0).Span, file).ToArray()); _mipTex = Lazy(() => ReadMipTex(Lump(2))); _extra = Lazy(() => ReadExtra(length)); } public string File { get; } public QuakeBspVersion Version { get; } public IReadOnlyList Planes => _planes.Value; public IReadOnlyList Vertices => _vertices.Value; public IReadOnlyList Nodes => _nodes.Value; public IReadOnlyList TexInfo => _texInfo.Value; public IReadOnlyList Faces => _faces.Value; public ReadOnlyMemory Lighting => _lighting.Value; public IReadOnlyList Leafs => _leafs.Value; public IReadOnlyList MarkSurfaces => _markSurfaces.Value; public IReadOnlyList<(int A, int B)> Edges => _edges.Value; public IReadOnlyList SurfEdges => _surfEdges.Value; public IReadOnlyList Models => _models.Value; public IReadOnlyList Entities => _entities.Value; public IReadOnlyList MipTex => _mipTex.Value; public IReadOnlyList Extra => _extra.Value; public static QuakeBsp Read(ReadOnlyMemory data, string file) { return new QuakeBsp(file, data.Length, (offset, length) => data.Slice((int)offset, length)); } public static QuakeBsp Open(IRandomAccess access, string file) { return new QuakeBsp(file, access.Length, (offset, length) => { var buffer = new byte[length]; access.ReadExactly(offset, buffer); return buffer; }); } public int FaceVertex(QuakeFace face, int corner) { var edge = SurfEdges[face.FirstEdge + corner]; return edge >= 0 ? Edges[edge].A : Edges[-edge].B; } public (int MinS, int MinT, int Width, int Height) Extents(QuakeFace face) { var info = TexInfo[face.TexInfo]; float minS = float.MaxValue, minT = float.MaxValue, maxS = float.MinValue, maxT = float.MinValue; for (var corner = 0; corner < face.EdgeCount; corner++) { var point = Vertices[FaceVertex(face, corner)]; var s = Texel(point, info.S); var t = Texel(point, info.T); (minS, maxS) = (Math.Min(minS, s), Math.Max(maxS, s)); (minT, maxT) = (Math.Min(minT, t), Math.Max(maxT, t)); } var lowS = (int)MathF.Floor(minS / LuxelSize); var lowT = (int)MathF.Floor(minT / LuxelSize); return (lowS * LuxelSize, lowT * LuxelSize, (int)MathF.Ceiling(maxS / LuxelSize) - lowS + 1, (int)MathF.Ceiling(maxT / LuxelSize) - lowT + 1); } public static float Texel(Vector3 point, Vector4 axis) { return (float)((double)point.X * axis.X + (double)point.Y * axis.Y + (double)point.Z * axis.Z + axis.W); } public static int Leaf(int child) { return -child - 1; } private QuakeFace[] CheckFaces(QuakeFace[] faces) { var planes = Planes.Count; var texInfo = TexInfo.Count; var surfEdges = SurfEdges; var edges = Edges; var vertices = Vertices.Count; foreach (var face in faces) { if (face.Plane < 0 || face.Plane >= planes || face.TexInfo < 0 || face.TexInfo >= texInfo || face.EdgeCount < 0 || face.FirstEdge < 0 || (long)face.FirstEdge + face.EdgeCount > surfEdges.Count) throw new QuakeMapException(File, "has a face whose plane, texinfo or edges are out of range."); for (var corner = 0; corner < face.EdgeCount; corner++) { var edge = surfEdges[face.FirstEdge + corner]; if (edge == int.MinValue || Math.Abs(edge) >= edges.Count) throw new QuakeMapException(File, $"has a face naming edge {edge} of {edges.Count}."); var (a, b) = edges[Math.Abs(edge)]; if (a < 0 || b < 0 || a >= vertices || b >= vertices) throw new QuakeMapException(File, $"has edge {Math.Abs(edge)} naming a vertex past its {vertices}."); } } return faces; } private QuakeNode[] CheckNodes(QuakeNode[] nodes) { var planes = Planes.Count; var leafs = Leafs.Count; foreach (var node in nodes) { if (node.Plane < 0 || node.Plane >= planes) throw new QuakeMapException(File, $"has a node on plane {node.Plane} of {planes}."); if (Bad(node.Front) || Bad(node.Back)) throw new QuakeMapException(File, "has a node whose child is out of range."); } return nodes; bool Bad(int child) { return child >= nodes.Length || (child < 0 && Leaf(child) >= leafs); } } private QuakeTexInfo[] CheckTexInfo(QuakeTexInfo[] texInfo) { var count = MipTex.Count; foreach (var info in texInfo) if (info.MipTex < 0 || info.MipTex >= count) throw new QuakeMapException(File, $"has a texinfo naming texture {info.MipTex} of {count}."); return texInfo; } private QuakeModel[] CheckModels(QuakeModel[] models) { if (models.Length == 0) throw new QuakeMapException(File, "has no models, so no world."); foreach (var model in models) if (model.HeadNode >= Nodes.Count || model.FirstFace < 0 || (long)model.FirstFace + model.FaceCount > Faces.Count) throw new QuakeMapException(File, "has a model whose head node or faces are out of range."); return models; } private QuakeMipTex?[] ReadMipTex(ReadOnlyMemory lump) { var span = lump.Span; if (span.Length == 0) return []; var count = Int(span, 0); if (count < 0 || 4L + count * 4L > span.Length) throw new QuakeMapException(File, $"says it holds {count} textures, more than its texture lump has room for."); var textures = new QuakeMipTex?[count]; for (var i = 0; i < count; i++) { var offset = Int(span, 4 + i * 4); if (offset < 0) continue; if ((long)offset + 40 > span.Length) throw new QuakeMapException(File, $"puts texture {i} at {offset}, past its texture lump."); var header = span[offset..]; var nameBytes = header[..16]; var end = nameBytes.IndexOf((byte)0); var name = Encoding.Latin1.GetString(end < 0 ? nameBytes : nameBytes[..end]); var width = Int(header, 16); var height = Int(header, 20); if (width >> (MipLevels - 1) <= 0 || height >> (MipLevels - 1) <= 0) throw new QuakeMapException(File, $"has texture '{name}' at {width}x{height}, too small for its {MipLevels} mip levels."); var levels = new ReadOnlyMemory[MipLevels]; var stored = true; for (var level = 0; level < MipLevels; level++) { var start = Int(header, 24 + level * 4); var size = (width >> level) * (height >> level); if (start == 0) { stored = false; break; } if (start < 0 || (long)offset + start + size > span.Length) throw new QuakeMapException(File, $"puts texture '{name}' level {level} past its texture lump."); levels[level] = lump.Slice(offset + start, size); } textures[i] = new QuakeMipTex(name, width, height, stored ? levels : null); } return textures; } private string[] ReadExtra(long length) { var end = _lumps.Max(lump => (long)lump.Offset + lump.Length); var start = (end + 3) & ~3L; if (start + 8 > length) return []; var header = _read(start, 8).Span; if (!header[..4].SequenceEqual("BSPX"u8)) return []; var count = Int(header, 4); if (count < 0 || start + 8 + count * 32L > length) throw new QuakeMapException(File, $"has a BSPX table of {count} lumps past its end."); var table = _read(start + 8, count * 32).Span; var names = new string[count]; for (var i = 0; i < count; i++) { var name = table.Slice(i * 32, 24); var zero = name.IndexOf((byte)0); names[i] = Encoding.ASCII.GetString(zero < 0 ? name : name[..zero]); } return names; } private ReadOnlyMemory Lump(int index) { var (offset, length) = _lumps[index]; return length == 0 ? ReadOnlyMemory.Empty : _read(offset, length); } private T[] Records(int index, int size, SpanReader read) { var length = _lumps[index].Length; if (length % size != 0) throw new QuakeMapException(File, $"has lump {index} of {length} bytes, not a whole number of {size}-byte records."); var span = Lump(index).Span; var records = new T[length / size]; for (var i = 0; i < records.Length; i++) records[i] = read(span.Slice(i * size, size)); return records; } private static Lazy> Lazy(Func read) { return new Lazy>(() => read()); } private static string Describe(ReadOnlySpan magic) { foreach (var b in magic) if (b is < 0x20 or >= 0x7F) return BinaryPrimitives.ReadInt32LittleEndian(magic).ToString(CultureInfo.InvariantCulture); return $"'{Encoding.ASCII.GetString(magic)}'"; } private static Vector3 Vector(ReadOnlySpan span) { return new Vector3(Single(span, 0), Single(span, 4), Single(span, 8)); } private static float Single(ReadOnlySpan span, int at) { return BinaryPrimitives.ReadSingleLittleEndian(span[at..]); } private static int Int(ReadOnlySpan span, int at) { return BinaryPrimitives.ReadInt32LittleEndian(span[at..]); } private static short Short(ReadOnlySpan span, int at) { return BinaryPrimitives.ReadInt16LittleEndian(span[at..]); } private static ushort UShort(ReadOnlySpan span, int at) { return BinaryPrimitives.ReadUInt16LittleEndian(span[at..]); } private delegate T SpanReader(ReadOnlySpan span); }