diff --git a/src/OrthoStreamXP/Gui/Airports/AirportRow.cs b/src/OrthoStreamXP/Gui/Airports/AirportRow.cs
index daa061c..748acde 100644
--- a/src/OrthoStreamXP/Gui/Airports/AirportRow.cs
+++ b/src/OrthoStreamXP/Gui/Airports/AirportRow.cs
@@ -44,7 +44,7 @@ public string Details
public string? StateText => Airport.State switch
{
FlattenState.FlattenedByScenery => "Already flattened by its own scenery",
- FlattenState.Outdated => "Flattened, but its scenery changed since: flatten it again to take the new layout",
+ FlattenState.Outdated => "Flattened, but the copy is out of date (its scenery changed, or it was made without the buildings): flatten it again",
FlattenState.Flattened when !Airport.InEffect =>
$"Flattened, but X-Plane uses {Airport.Source?.Source.Name}'s copy: it is higher in the scenery list, or {FlattenedAirports.PackageName} is switched off. Flatten it again to fix that",
FlattenState.Flattened => "Flattened by OrthoStreamXP",
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs b/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs
index 6c3368d..569ecfb 100644
--- a/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs
+++ b/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs
@@ -50,6 +50,42 @@ public AirportBlock Flattened()
return new AirportBlock([.. lines], Ident, Name);
}
+ ///
+ /// The area its runways, helipads, pavement, start positions, signs and datum span, in degrees (south, west, north, east);
+ /// null when no line places it.
+ ///
+ public (double South, double West, double North, double East)? Area()
+ {
+ double south = double.MaxValue, west = double.MaxValue, north = double.MinValue, east = double.MinValue;
+ void Add(string lat, string lon)
+ {
+ if (!double.TryParse(lat, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double y)
+ || !double.TryParse(lon, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double x)
+ || Math.Abs(y) > 90 || Math.Abs(x) > 180) return;
+ (south, north, west, east) = (Math.Min(south, y), Math.Max(north, y), Math.Min(west, x), Math.Max(east, x));
+ }
+
+ string? datumLat = null, datumLon = null;
+ foreach (string line in _lines)
+ {
+ string[] p = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
+ if (p.Length == 0) continue;
+ switch (p[0])
+ {
+ case "100" when p.Length > 19: Add(p[9], p[10]); Add(p[18], p[19]); break; // runway ends
+ case "101" when p.Length > 8: Add(p[4], p[5]); Add(p[7], p[8]); break; // water runway ends
+ case "102" when p.Length > 3: Add(p[2], p[3]); break; // helipad
+ case "14" or "15" or "19" or "20" or "1300" or "111" or "112" or "113" or "114" or "115" or "116" when p.Length > 2:
+ Add(p[1], p[2]); break; // viewpoint, start, windsock, sign, start location, pavement nodes
+ case "21" when p.Length > 3: Add(p[2], p[3]); break; // lighting
+ case "1302" when p.Length > 2 && p[1] == "datum_lat": datumLat = p[2]; break;
+ case "1302" when p.Length > 2 && p[1] == "datum_lon": datumLon = p[2]; break;
+ }
+ }
+ if (datumLat is not null && datumLon is not null) Add(datumLat, datumLon);
+ return south <= north ? (south, west, north, east) : null;
+ }
+
/// Whether both hold the same lines.
public bool SameAs(AirportBlock other) => _lines.SequenceEqual(other._lines, StringComparer.Ordinal);
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportDsfFinder.cs b/src/OrthoStreamXP/Setup/Airports/AirportDsfFinder.cs
new file mode 100644
index 0000000..ab79459
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportDsfFinder.cs
@@ -0,0 +1,49 @@
+using System.Globalization;
+
+namespace OrthoStreamXP.Setup;
+
+///
+/// Finds the DSF tiles of a package that hold an airport's 3D in a filter of its own (see ): the
+/// tiles under the airport and a few kilometres around it, in the package's Earth nav data folder.
+///
+internal static class AirportDsfFinder
+{
+ /// How far past its pavement an airport's buildings are looked for, in degrees.
+ private const double Margin = 0.05;
+
+ /// The DSF files in with a filter for .
+ public static IReadOnlyList Find(string earthNavData, AirportBlock airport)
+ {
+ if (airport.Area() is not var (south, west, north, east)) return [];
+ var found = new List();
+ for (int lat = Floor(south - Margin); lat <= Floor(north + Margin); lat++)
+ for (int lon = Math.Max(-180, Floor(west - Margin)); lon <= Math.Min(179, Floor(east + Margin)); lon++)
+ {
+ string path = Path.Join(earthNavData, TilePath(lat, lon));
+ if (File.Exists(path) && HasFilter(path, airport.Ident)) found.Add(path);
+ }
+ return found;
+ }
+
+ /// "+40-010\+44-001.dsf": the ten-degree folder and the one-degree tile.
+ public static string TilePath(int lat, int lon) =>
+ Path.Join(Name(Floor(lat / 10.0) * 10, Floor(lon / 10.0) * 10), Name(lat, lon) + ".dsf");
+
+ private static string Name(int lat, int lon) =>
+ lat.ToString("+00;-00", CultureInfo.InvariantCulture) + lon.ToString("+000;-000", CultureInfo.InvariantCulture);
+
+ private static int Floor(double degrees) => (int)Math.Floor(degrees);
+
+ private static bool HasFilter(string path, string ident)
+ {
+ try
+ {
+ return DsfFile.ReadProperties(path).Any(p => p.Key == AirportDsfMerger.FilterProperty && p.Value.Equals(ident, StringComparison.OrdinalIgnoreCase));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ Log.Warning($"Could not look for {ident}'s buildings in {path}: {ex.Message}");
+ return false;
+ }
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportDsfMerger.cs b/src/OrthoStreamXP/Setup/Airports/AirportDsfMerger.cs
new file mode 100644
index 0000000..1c30cf9
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportDsfMerger.cs
@@ -0,0 +1,256 @@
+using System.Buffers.Binary;
+
+namespace OrthoStreamXP.Setup;
+
+///
+/// Copies chosen airports' 3D out of overlay DSFs into one new DSF. X-Plane's gateway airports keep their buildings, ground
+/// polygons and roads in "filters": a sim/filter/aptid property names the airport, and a comment command (type 1, then the
+/// filter's number in the order of those properties) starts its commands. X-Plane draws a filter only when the airport it names
+/// comes from the same package, so an airport taken over by another package's apt.dat needs its filters copied there too.
+/// The new file keeps each source's point pools whole and re-numbers pools, definitions and filters as it merges; everything
+/// outside the chosen filters is left out.
+///
+internal sealed class AirportDsfMerger
+{
+ public const string FilterProperty = "sim/filter/aptid";
+
+ private const ushort FilterComment = 1;
+
+ private readonly List> _global = [], _filters = [];
+ private readonly Dictionary> _definitions = DsfFile.DefinitionTables.ToDictionary(id => id, _ => new List());
+ private readonly List _geodesy = [];
+ private readonly List _commands = [];
+ private int _filterCount;
+
+ // What the new command stream has set so far (-1: nothing yet).
+ private long _pool = -1, _definition = -1, _subtype = -1, _junction = -1, _filter = -1;
+ private readonly Dictionary _markers = [];
+
+ /// Whether any airport was copied.
+ public bool IsEmpty => _filterCount == 0;
+
+ /// Copies the filters of from ; false when it has none of them.
+ /// The source is not an overlay, or its commands are damaged or draw terrain in a chosen filter.
+ public bool Add(DsfFile source, IReadOnlySet idents)
+ {
+ if (!source.Values("sim/overlay").Contains("1")) throw new InvalidDataException("the DSF is not an overlay");
+ Dictionary filters = TakeProperties(source, idents);
+ if (filters.Count == 0) return false;
+
+ var definitions = DsfFile.DefinitionTables.ToDictionary(id => id, id => Merge(id, source.Definitions.GetValueOrDefault(id) ?? []));
+ var poolOffset = new Dictionary { [DsfFile.Pool16] = Count(DsfFile.Pool16), [DsfFile.Pool32] = Count(DsfFile.Pool32) };
+ _geodesy.AddRange(source.Geodesy);
+ try
+ {
+ new Copier(this, filters, definitions, poolOffset).Run(source.Commands);
+ }
+ catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException)
+ {
+ throw new InvalidDataException("the DSF commands are cut short or damaged", ex);
+ }
+ return true;
+ }
+
+ /// The new DSF: the sources' general properties, then each copied filter with its own (exclusions and the like).
+ public DsfFile Build() => new(
+ [.. _global, .. _filters],
+ DsfFile.DefinitionTables.ToDictionary(id => id, id => (IReadOnlyList)_definitions[id]),
+ _geodesy,
+ [.. _commands]);
+
+ ///
+ /// Takes the source's general properties (those before its first filter) and the properties of the chosen filters. Returns
+ /// the chosen filters' numbers in the source and in the new file.
+ ///
+ private Dictionary TakeProperties(DsfFile source, IReadOnlySet idents)
+ {
+ var filters = new Dictionary();
+ int filter = -1;
+ bool chosen = false;
+ foreach (KeyValuePair property in source.Properties)
+ {
+ if (property.Key == FilterProperty)
+ {
+ filter++;
+ chosen = idents.Contains(property.Value);
+ if (chosen) filters[filter] = _filterCount++;
+ }
+ if (filter < 0)
+ {
+ if (property.Key != "sim/creation_agent" && !_global.Contains(property)) _global.Add(property);
+ }
+ else if (chosen)
+ {
+ _filters.Add(property);
+ }
+ }
+ if (!_global.Any(p => p.Key == "sim/creation_agent")) _global.Add(new("sim/creation_agent", "OrthoStreamXP"));
+ return filters;
+ }
+
+ /// Adds a source's definition table to the new one (an entry already there is shared); its entries' new numbers.
+ private int[] Merge(uint table, IReadOnlyList entries)
+ {
+ List merged = _definitions[table];
+ var numbers = new int[entries.Count];
+ for (int i = 0; i < entries.Count; i++)
+ {
+ int at = merged.IndexOf(entries[i]);
+ if (at < 0)
+ {
+ at = merged.Count;
+ merged.Add(entries[i]);
+ }
+ numbers[i] = at;
+ }
+ return numbers;
+ }
+
+ private int Count(uint pool) => _geodesy.Count(a => a.Id == pool);
+
+ private enum Kind
+ {
+ Object,
+ Network,
+ Polygon,
+ }
+
+ /// Walks one source's command stream, writing the chosen filters' commands with the state they need.
+ private sealed class Copier(AirportDsfMerger target, Dictionary filters, Dictionary definitions, Dictionary poolOffset)
+ {
+ private int _pool, _filter = -1, _subtype;
+ private uint _definition, _junction;
+ private readonly Dictionary _markers = [];
+
+ public void Run(byte[] commands)
+ {
+ int at = 0;
+ while (at < commands.Length)
+ {
+ byte command = commands[at];
+ int length = 1 + PayloadLength(commands, at + 1, command);
+ if (at + length > commands.Length) throw new InvalidDataException("the DSF commands are cut short");
+ ReadOnlySpan payload = commands.AsSpan(at + 1, length - 1);
+ switch (command)
+ {
+ case 1: _pool = BinaryPrimitives.ReadUInt16LittleEndian(payload); break;
+ case 2: _junction = BinaryPrimitives.ReadUInt32LittleEndian(payload); break;
+ case 3: _definition = payload[0]; break;
+ case 4: _definition = BinaryPrimitives.ReadUInt16LittleEndian(payload); break;
+ case 5: _definition = BinaryPrimitives.ReadUInt32LittleEndian(payload); break;
+ case 6: _subtype = payload[0]; break;
+ case 7 or 8: Copy(Kind.Object, commands.AsSpan(at, length), usesJunction: false); break;
+ case 9 or 10: Copy(Kind.Network, commands.AsSpan(at, length), usesJunction: true); break;
+ case 11: Copy(Kind.Network, commands.AsSpan(at, length), usesJunction: false); break;
+ case >= 12 and <= 15: Copy(Kind.Polygon, commands.AsSpan(at, length), usesJunction: false); break;
+ case 32: Comment(payload[1..]); break;
+ case (>= 16 and <= 18) or (>= 23 and <= 31):
+ if (filters.ContainsKey(_filter)) throw new InvalidDataException("an airport's filter draws terrain");
+ break;
+ }
+ at += length;
+ }
+ }
+
+ /// A comment either starts a filter (type 1) or marks the commands after it: kept to be written before them.
+ private void Comment(ReadOnlySpan text)
+ {
+ if (text.Length < 2) return;
+ ushort type = BinaryPrimitives.ReadUInt16LittleEndian(text);
+ if (type == FilterComment) _filter = text.Length >= 6 ? BinaryPrimitives.ReadInt32LittleEndian(text[2..]) : -1;
+ else _markers[type] = text.ToArray();
+ }
+
+ private void Copy(Kind kind, ReadOnlySpan command, bool usesJunction)
+ {
+ if (!filters.TryGetValue(_filter, out int filter)) return;
+ if (filter != target._filter)
+ {
+ Span text = stackalloc byte[6];
+ BinaryPrimitives.WriteUInt16LittleEndian(text, FilterComment);
+ BinaryPrimitives.WriteInt32LittleEndian(text[2..], filter);
+ WriteComment(text);
+ target._filter = filter;
+ }
+ foreach (var (type, text) in _markers)
+ {
+ if (target._markers.TryGetValue(type, out byte[]? written) && written.AsSpan().SequenceEqual(text)) continue;
+ WriteComment(text);
+ target._markers[type] = text;
+ }
+
+ int pool = checked(_pool + poolOffset[kind == Kind.Network ? DsfFile.Pool32 : DsfFile.Pool16]);
+ if (pool > ushort.MaxValue) throw new InvalidDataException("too many point pools to merge");
+ if (pool != target._pool)
+ {
+ Write(1, BitConverter.GetBytes((ushort)pool));
+ target._pool = pool;
+ }
+ int[] numbers = definitions[kind switch { Kind.Object => DsfFile.Objects, Kind.Network => DsfFile.Networks, _ => DsfFile.Polygons }];
+ if (_definition >= numbers.Length) throw new InvalidDataException("a DSF command uses a definition the file does not have");
+ int definition = numbers[_definition];
+ if (definition != target._definition)
+ {
+ Write(5, BitConverter.GetBytes((uint)definition));
+ target._definition = definition;
+ }
+ if (kind == Kind.Network && _subtype != target._subtype)
+ {
+ Write(6, [(byte)_subtype]);
+ target._subtype = _subtype;
+ }
+ if (usesJunction && _junction != target._junction)
+ {
+ Write(2, BitConverter.GetBytes(_junction));
+ target._junction = _junction;
+ }
+ foreach (byte b in command) target._commands.Add(b);
+ }
+
+ private void WriteComment(ReadOnlySpan text) => Write(32, [(byte)text.Length, .. text]);
+
+ private void Write(byte command, ReadOnlySpan payload)
+ {
+ target._commands.Add(command);
+ foreach (byte b in payload) target._commands.Add(b);
+ }
+
+ /// How many bytes follow the command byte, from the DSF specification.
+ private static int PayloadLength(byte[] c, int at, byte command) => command switch
+ {
+ 1 => 2,
+ 2 => 4,
+ 3 => 1,
+ 4 => 2,
+ 5 => 4,
+ 6 => 1,
+ 7 => 2,
+ 8 => 4,
+ 9 => 1 + 2 * c[at],
+ 10 => 4,
+ 11 => 1 + 4 * c[at],
+ 12 => 3 + 2 * c[at + 2],
+ 13 => 6,
+ 14 => NestedPolygonLength(c, at),
+ 15 => 3 + 2 * (c[at + 2] + 1),
+ 16 => 0,
+ 17 => 1,
+ 18 => 9,
+ 23 or 26 or 29 => 1 + 2 * c[at],
+ 24 or 27 or 30 => 1 + 4 * c[at],
+ 25 or 28 or 31 => 4,
+ 32 => 1 + c[at],
+ 33 => 2 + BinaryPrimitives.ReadUInt16LittleEndian(c.AsSpan(at)),
+ 34 => checked(4 + (int)BinaryPrimitives.ReadUInt32LittleEndian(c.AsSpan(at))),
+ _ => throw new InvalidDataException($"unknown DSF command {command}"),
+ };
+
+ /// A nested polygon: parameter, number of windings, and each winding's count and 16-bit indices.
+ private static int NestedPolygonLength(byte[] c, int at)
+ {
+ int length = 3, windings = c[at + 2];
+ for (int w = 0; w < windings; w++) length += 1 + 2 * c[at + length];
+ return length;
+ }
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs b/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs
index e000fc8..a31cb4d 100644
--- a/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs
+++ b/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs
@@ -9,7 +9,10 @@ internal enum FlattenState
FlattenedByScenery,
/// Flattened by OrthoStreamXP; can be undone.
Flattened,
- /// Flattened by OrthoStreamXP, but its scenery changed since: the copy holds the old layout.
+ ///
+ /// Flattened by OrthoStreamXP, but its scenery changed since (the copy holds the old layout), or the copy was made without the
+ /// airport's buildings (before OrthoStreamXP copied them).
+ ///
Outdated,
}
@@ -54,8 +57,10 @@ public FlattenableAirport Flatten(FlattenableAirport airport)
{
if (airport.Source is not { } source) throw new InvalidOperationException($"{airport.Ident} has no scenery to take it from.");
AirportBlock block = AptDatReader.ReadBlock(source.Source.AptDat, source.Record);
- _package.Add(block.Flattened(), source.Source.EntryPath);
- Log.Info($"Flattened {airport.Ident} ({airport.Name}), from {source.Source.Name}, in {FlattenedAirports.PackageName}");
+ IReadOnlyList buildings = AirportDsfFinder.Find(Path.GetDirectoryName(source.Source.AptDat)!, block);
+ _package.Add(block.Flattened(), source.Source.EntryPath, buildings);
+ Log.Info($"Flattened {airport.Ident} ({airport.Name}), from {source.Source.Name}, in {FlattenedAirports.PackageName}"
+ + (buildings.Count > 0 ? $", with its buildings from {string.Join(", ", buildings.Select(Path.GetFileName))}" : ""));
return airport with { State = FlattenState.Flattened, InEffect = _package.IsAbove(source.Source.EntryPath) };
}
@@ -76,7 +81,8 @@ private FlattenableAirport Describe(SourcedAirport airport, AirportBlock? copy)
FlattenState state;
try
{
- state = AptDatReader.ReadBlock(airport.Source.AptDat, record).Flattened().SameAs(copy) ? FlattenState.Flattened : FlattenState.Outdated;
+ state = AptDatReader.ReadBlock(airport.Source.AptDat, record).Flattened().SameAs(copy) && _package.Buildings.Knows(record.Ident)
+ ? FlattenState.Flattened : FlattenState.Outdated;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or FormatException)
{
diff --git a/src/OrthoStreamXP/Setup/Airports/DsfFile.cs b/src/OrthoStreamXP/Setup/Airports/DsfFile.cs
new file mode 100644
index 0000000..e2d1ac4
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/DsfFile.cs
@@ -0,0 +1,154 @@
+using System.Buffers.Binary;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace OrthoStreamXP.Setup;
+
+/// A DSF atom: its four-character id (as stored, a little-endian integer) and contents.
+internal sealed record DsfAtom(uint Id, byte[] Body);
+
+///
+/// An uncompressed DSF (X-Plane's scenery tile format) as atoms: its properties (HEAD/PROP), definition tables (DEFN), point pools
+/// and their scales (GEOD, kept as they are) and command stream (CMDS). Raster layers (DEMS) are not kept. Strings are Latin-1, so
+/// they come back byte for byte.
+///
+internal sealed record DsfFile(
+ IReadOnlyList> Properties,
+ IReadOnlyDictionary> Definitions,
+ IReadOnlyList Geodesy,
+ byte[] Commands)
+{
+ // Atom ids are four characters stored as a little-endian integer.
+ public const uint Head = 0x48454144, Prop = 0x50524F50, Defn = 0x4445464E, Geod = 0x47454F44, Cmds = 0x434D4453;
+ public const uint Terrains = 0x54455254, Objects = 0x4F424A54, Polygons = 0x504F4C59, Networks = 0x4E455457, Rasters = 0x44454D4E;
+ public const uint Pool16 = 0x504F4F4C, Pool32 = 0x504F3332;
+
+ /// The definition tables in the order X-Plane writes them.
+ public static readonly uint[] DefinitionTables = [Terrains, Objects, Polygons, Networks, Rasters];
+
+ private const int HeaderSize = 12, FooterSize = 16; // "XPLNEDSF", version; the MD5 at the end
+
+ /// The values of every property named , in order.
+ public IEnumerable Values(string key) => Properties.Where(p => p.Key == key).Select(p => p.Value);
+
+ /// Not an uncompressed DSF, or damaged.
+ public static DsfFile Parse(byte[] file)
+ {
+ CheckHeader(file);
+ try
+ {
+ IReadOnlyList> properties = [];
+ var definitions = new Dictionary>();
+ List geodesy = [];
+ byte[] commands = [];
+ foreach (DsfAtom atom in Atoms(file.AsSpan(HeaderSize, file.Length - HeaderSize - FooterSize)))
+ {
+ switch (atom.Id)
+ {
+ case Head: properties = Pairs(Atoms(atom.Body).FirstOrDefault(a => a.Id == Prop)?.Body ?? []); break;
+ case Defn:
+ foreach (DsfAtom table in Atoms(atom.Body)) definitions[table.Id] = Strings(table.Body);
+ break;
+ case Geod: geodesy = Atoms(atom.Body); break;
+ case Cmds: commands = atom.Body; break;
+ }
+ }
+ return new DsfFile(properties, definitions, geodesy, commands);
+ }
+ catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException)
+ {
+ throw new InvalidDataException("the DSF is cut short or damaged", ex);
+ }
+ }
+
+ /// Only the properties of the DSF at , read from the start of the file.
+ /// Not an uncompressed DSF, or damaged.
+ public static IReadOnlyList> ReadProperties(string path)
+ {
+ using FileStream stream = File.OpenRead(path);
+ byte[] start = new byte[HeaderSize + 8];
+ stream.ReadExactly(start);
+ CheckHeader(start);
+ if (BinaryPrimitives.ReadUInt32LittleEndian(start.AsSpan(HeaderSize)) != Head) throw new InvalidDataException("the DSF does not start with its properties");
+ int length = BinaryPrimitives.ReadInt32LittleEndian(start.AsSpan(HeaderSize + 4));
+ if (length < 8 || length > stream.Length - HeaderSize) throw new InvalidDataException("the DSF's properties run past its end");
+ byte[] head = new byte[length - 8];
+ stream.ReadExactly(head);
+ return Pairs(Atoms(head).FirstOrDefault(a => a.Id == Prop)?.Body ?? []);
+ }
+
+ /// The file X-Plane reads: header, atoms, and the MD5 of all of it.
+ public byte[] ToBytes()
+ {
+ using var file = new MemoryStream();
+ file.Write("XPLNEDSF"u8);
+ WriteInt(file, 1);
+ WriteAtom(file, Head, Atom(Prop, Latin1(Properties.SelectMany(p => new[] { p.Key, p.Value }))));
+ WriteAtom(file, Defn, Concat(DefinitionTables.Select(id => Atom(id, Latin1(Definitions.GetValueOrDefault(id) ?? [])))));
+ WriteAtom(file, Geod, Concat(Geodesy.Select(a => Atom(a.Id, a.Body))));
+ WriteAtom(file, Cmds, Commands);
+#pragma warning disable CA5351 // the DSF format ends with an MD5 checksum of the file; it is not used for security
+ file.Write(MD5.HashData(file.GetBuffer().AsSpan(0, (int)file.Length)));
+#pragma warning restore CA5351
+ return file.ToArray();
+ }
+
+ private static void CheckHeader(ReadOnlySpan file)
+ {
+ if (file.Length >= 6 && file[..6].SequenceEqual((ReadOnlySpan)[0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C]))
+ throw new InvalidDataException("the DSF is compressed (7-Zip)");
+ if (file.Length < HeaderSize + 8 || !file[..8].SequenceEqual("XPLNEDSF"u8)) throw new InvalidDataException("not a DSF file");
+ }
+
+ private static List Atoms(ReadOnlySpan data)
+ {
+ var atoms = new List();
+ int at = 0;
+ while (at + 8 <= data.Length)
+ {
+ uint id = BinaryPrimitives.ReadUInt32LittleEndian(data[at..]);
+ int length = BinaryPrimitives.ReadInt32LittleEndian(data[(at + 4)..]);
+ if (length < 8 || length > data.Length - at) throw new InvalidDataException("a DSF atom runs past its parent");
+ atoms.Add(new DsfAtom(id, data[(at + 8)..(at + length)].ToArray()));
+ at += length;
+ }
+ return atoms;
+ }
+
+ private static List Strings(byte[] table)
+ {
+ List strings = [.. Encoding.Latin1.GetString(table).Split('\0')];
+ if (strings.Count > 0 && strings[^1].Length == 0) strings.RemoveAt(strings.Count - 1); // after the last terminator
+ return strings;
+ }
+
+ private static List> Pairs(byte[] table)
+ {
+ List strings = Strings(table);
+ var pairs = new List>(strings.Count / 2);
+ for (int i = 0; i + 1 < strings.Count; i += 2) pairs.Add(new(strings[i], strings[i + 1]));
+ return pairs;
+ }
+
+ private static byte[] Latin1(IEnumerable strings) => Encoding.Latin1.GetBytes(string.Concat(strings.Select(s => s + "\0")));
+
+ private static byte[] Atom(uint id, byte[] body)
+ {
+ byte[] atom = new byte[8 + body.Length];
+ BinaryPrimitives.WriteUInt32LittleEndian(atom, id);
+ BinaryPrimitives.WriteInt32LittleEndian(atom.AsSpan(4), atom.Length);
+ body.CopyTo(atom, 8);
+ return atom;
+ }
+
+ private static byte[] Concat(IEnumerable parts) => [.. parts.SelectMany(p => p)];
+
+ private static void WriteAtom(Stream file, uint id, byte[] body) => file.Write(Atom(id, body));
+
+ private static void WriteInt(Stream file, int value)
+ {
+ Span bytes = stackalloc byte[4];
+ BinaryPrimitives.WriteInt32LittleEndian(bytes, value);
+ file.Write(bytes);
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs b/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs
index f7071eb..fc8067e 100644
--- a/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs
+++ b/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs
@@ -7,7 +7,8 @@ namespace OrthoStreamXP.Setup;
/// The scenery package OrthoStreamXP keeps its flattened airports in: Custom Scenery\OrthoStreamXP Flattened Airports, with an
/// apt.dat holding a copy of each airport plus "1302 flatten 1". X-Plane uses an airport's definition from the highest package
/// that lists it, so the package is kept above the airports' own ones in scenery_packs.ini (a new entry goes just above the first
-/// airport's package, not above unrelated ones); their files are never changed.
+/// airport's package, not above unrelated ones); their files are never changed. The airports' 3D comes along (see
+/// ): X-Plane would hide it otherwise.
/// Undoing takes the airport out again, and the package goes when its last airport does.
///
internal sealed class FlattenedAirports(string xplane)
@@ -21,16 +22,21 @@ internal sealed class FlattenedAirports(string xplane)
private string AptDat => Path.Join(NavData, "apt.dat");
private SceneryPackList List => new(CustomScenery);
+ /// The flattened airports' buildings.
+ public FlattenedBuildings Buildings => new(Folder);
+
/// The airports flattened so far.
public IReadOnlyList Read() => File.Exists(AptDat) ? AirportBlock.Split(File.ReadAllText(AptDat)) : [];
///
- /// Adds (or replaces) , and makes sure the package is listed, enabled, above
- /// (the scenery_packs.ini entry of the package the airport comes from).
+ /// Adds (or replaces) with its 3D from (its package's DSF files that
+ /// have it), and makes sure the package is listed, enabled, above (the scenery_packs.ini entry
+ /// of the package the airport comes from).
///
- public void Add(AirportBlock airport, string sourceEntry)
+ public void Add(AirportBlock airport, string sourceEntry, IReadOnlyList buildings)
{
Write([.. Read().Where(b => !b.Ident.Equals(airport.Ident, StringComparison.OrdinalIgnoreCase)), airport]);
+ Buildings.Set(airport.Ident, buildings);
PlaceAbove(sourceEntry);
}
@@ -40,7 +46,11 @@ public bool Remove(string ident)
IReadOnlyList airports = Read();
AirportBlock[] kept = [.. airports.Where(b => !b.Ident.Equals(ident, StringComparison.OrdinalIgnoreCase))];
if (kept.Length == airports.Count) return false;
- if (kept.Length > 0) Write(kept);
+ if (kept.Length > 0)
+ {
+ Write(kept);
+ Buildings.Remove(ident);
+ }
else Delete();
return true;
}
@@ -82,6 +92,7 @@ private void Write(IEnumerable airports)
/// Removes the package's own file and folders (anything else put there is left, with its folder) and its list entry.
private void Delete()
{
+ Buildings.Delete();
File.Delete(AptDat);
foreach (string folder in new[] { NavData, Folder })
if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
diff --git a/src/OrthoStreamXP/Setup/Airports/FlattenedBuildings.cs b/src/OrthoStreamXP/Setup/Airports/FlattenedBuildings.cs
new file mode 100644
index 0000000..617fc9b
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/FlattenedBuildings.cs
@@ -0,0 +1,111 @@
+namespace OrthoStreamXP.Setup;
+
+///
+/// The flattened airports' 3D (buildings, ground polygons, roads) in the flattened airports' package. X-Plane draws a gateway
+/// airport's 3D only when the airport comes from the package the 3D is in, so it is copied out of the airport's own package's
+/// DSF tiles into tiles of the same name here (see ). buildings.txt lists, per airport, the
+/// tiles it was copied from ("LFBD", tab, path; the ident alone when there were none), so a tile shared by several airports is
+/// made again from what is left when one of them goes.
+///
+internal sealed class FlattenedBuildings(string package)
+{
+ private string ListFile => Path.Join(package, "buildings.txt");
+ private string NavData => Path.Join(package, "Earth nav data");
+
+ /// Whether the airport's 3D was looked for when it was flattened (copies older than this have none).
+ public bool Knows(string ident) => Read().Any(e => e.Ident.Equals(ident, StringComparison.OrdinalIgnoreCase));
+
+ /// Copies 's 3D from (DSF files), replacing what it had.
+ public void Set(string ident, IReadOnlyList sources)
+ {
+ List<(string Ident, string? Source)> entries = Read();
+ HashSet tiles = Tiles(entries, ident);
+ entries.RemoveAll(e => e.Ident.Equals(ident, StringComparison.OrdinalIgnoreCase));
+ if (sources.Count == 0) entries.Add((ident, null));
+ foreach (string source in sources)
+ {
+ entries.Add((ident, source));
+ tiles.Add(TileOf(source));
+ }
+ Save(entries, tiles);
+ }
+
+ /// Takes 's 3D out.
+ public void Remove(string ident)
+ {
+ List<(string Ident, string? Source)> entries = Read();
+ HashSet tiles = Tiles(entries, ident);
+ if (entries.RemoveAll(e => e.Ident.Equals(ident, StringComparison.OrdinalIgnoreCase)) > 0) Save(entries, tiles);
+ }
+
+ /// Removes every tile and the list.
+ public void Delete()
+ {
+ List<(string Ident, string? Source)> entries = Read();
+ foreach (string tile in entries.Where(e => e.Source is not null).Select(e => TileOf(e.Source!)).Distinct(StringComparer.OrdinalIgnoreCase))
+ DeleteTile(tile);
+ File.Delete(ListFile);
+ }
+
+ private void Save(List<(string Ident, string? Source)> entries, HashSet tiles)
+ {
+ foreach (string tile in tiles) Make(tile, entries.Where(e => e.Source is not null && TileOf(e.Source).Equals(tile, StringComparison.OrdinalIgnoreCase)));
+ Directory.CreateDirectory(package);
+ AtomicFile.Write(ListFile, System.Text.Encoding.UTF8.GetBytes(string.Concat(entries.Select(e => e.Source is null ? $"{e.Ident}\r\n" : $"{e.Ident}\t{e.Source}\r\n"))));
+ }
+
+ /// Makes the tile again from the airports copied into it; without any, it goes.
+ private void Make(string tile, IEnumerable<(string Ident, string? Source)> entries)
+ {
+ var merger = new AirportDsfMerger();
+ foreach (var group in entries.GroupBy(e => e.Source!, StringComparer.OrdinalIgnoreCase))
+ {
+ var idents = group.Select(e => e.Ident).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ try
+ {
+ if (!merger.Add(DsfFile.Parse(File.ReadAllBytes(group.Key)), idents))
+ Log.Warning($"{group.Key} no longer has the buildings of {string.Join(", ", idents)}");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ Log.Warning($"Could not copy the buildings of {string.Join(", ", idents)} from {group.Key}: {ex.Message}");
+ }
+ }
+ if (merger.IsEmpty)
+ {
+ DeleteTile(tile);
+ return;
+ }
+ string path = Path.Join(NavData, tile);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ AtomicFile.Write(path, merger.Build().ToBytes());
+ }
+
+ private void DeleteTile(string tile)
+ {
+ string path = Path.Join(NavData, tile);
+ File.Delete(path);
+ string folder = Path.GetDirectoryName(path)!;
+ if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
+ }
+
+ /// The tiles has 3D in now.
+ private static HashSet Tiles(List<(string Ident, string? Source)> entries, string ident) =>
+ entries.Where(e => e.Source is not null && e.Ident.Equals(ident, StringComparison.OrdinalIgnoreCase))
+ .Select(e => TileOf(e.Source!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
+
+ /// "+40-010\+44-001.dsf" of a source tile's path.
+ private static string TileOf(string source) => Path.Join(Path.GetFileName(Path.GetDirectoryName(source)), Path.GetFileName(source));
+
+ private List<(string Ident, string? Source)> Read()
+ {
+ if (!File.Exists(ListFile)) return [];
+ var entries = new List<(string, string?)>();
+ foreach (string line in File.ReadAllLines(ListFile))
+ {
+ string[] parts = line.Split('\t', 2, StringSplitOptions.TrimEntries);
+ if (parts[0].Length > 0) entries.Add((parts[0], parts.Length > 1 && parts[1].Length > 0 ? parts[1] : null));
+ }
+ return entries;
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/AirportBuildingsTests.cs b/tests/OrthoStreamXP.Tests/AirportBuildingsTests.cs
new file mode 100644
index 0000000..3907879
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/AirportBuildingsTests.cs
@@ -0,0 +1,150 @@
+using OrthoStreamXP.Setup;
+
+namespace OrthoStreamXP.Tests;
+
+public sealed class AirportBuildingsTests : IDisposable
+{
+ private const string Ebbr = """
+ 1 145 0 0 EBBR Brussels National
+ 1302 city Brussels
+ 100 45.00 35 727 0.00 1 3 0 07R 50.8890356 4.4803936 126 0 6 0 0 2 25L 50.8989489 4.5233233 0 0 6 2 1 2
+ """;
+
+ private const string Ebaw = """
+ 1 40 0 0 EBAW Antwerp
+ 1302 datum_lat 50.9894
+ 1302 datum_lon 4.4603
+ """;
+
+ private const string Tile = "X-Plane 12/Global Scenery/Global Airports/Earth nav data/+50+000/+50+004.dsf";
+
+ private readonly TempTree _tree = new();
+
+ public void Dispose() => _tree.Dispose();
+
+ private static DsfFile Dsf(string[] properties, string[] objects, int pools, byte[] commands) => new(
+ [.. new[] { "sim/west", "4", "sim/south", "50", "sim/overlay", "1", "sim/creation_agent", "WorldEditor" }.Concat(properties).Chunk(2).Select(p => new KeyValuePair(p[0], p[1]))],
+ new Dictionary>
+ {
+ [DsfFile.Objects] = objects,
+ [DsfFile.Polygons] = ["p.pol"],
+ [DsfFile.Networks] = ["roads.net"],
+ },
+ [.. Enumerable.Range(0, pools).SelectMany(i => new[] { new DsfAtom(DsfFile.Pool16, [(byte)i]), new DsfAtom(0x5343414C, [(byte)i]) }),
+ new DsfAtom(DsfFile.Pool32, [9]), new DsfAtom(0x53433332, [9])],
+ commands);
+
+ private static byte[] Filter(int index) => [32, 6, 1, 0, (byte)index, 0, 0, 0];
+
+ /// Two airports in one tile, the way WorldEditor exports Global Airports: EBAW is filter 0, EBBR filter 1.
+ private static DsfFile GlobalTile() => Dsf(
+ ["sim/filter/aptid", "EBAW", "sim/exclude_obj", "a", "sim/filter/aptid", "EBBR", "sim/exclude_obj", "b"],
+ ["x.obj", "y.obj"],
+ pools: 2,
+ [
+ 1, 0, 0, .. Filter(0), 3, 0, 7, 1, 0, // EBAW: x.obj
+ .. Filter(1), 3, 1, 7, 2, 0, // EBBR: y.obj
+ 1, 1, 0, 3, 0, 13, 0xFF, 0, 0, 0, 4, 0, // EBBR: a polygon range from pool 1
+ 32, 6, 2, 0, 1, 0, 0, 0, // a marker
+ .. Filter(0), 7, 3, 0, // EBAW again
+ .. Filter(1), 1, 0, 0, 6, 5, 2, 10, 0, 0, 0, 3, 0, 10, 0, 0, 2, 0, // EBBR: a road
+ ]);
+
+ [Fact]
+ public void Only_the_chosen_airports_filters_are_copied_with_the_state_their_commands_need()
+ {
+ var merger = new AirportDsfMerger();
+
+ Assert.True(merger.Add(GlobalTile(), new HashSet(["EBBR"])));
+ DsfFile copy = merger.Build();
+
+ Assert.Equal(
+ ["sim/west", "sim/south", "sim/overlay", "sim/creation_agent", "sim/filter/aptid", "sim/exclude_obj"],
+ copy.Properties.Select(p => p.Key));
+ Assert.Equal(["EBBR"], copy.Values("sim/filter/aptid"));
+ Assert.Equal(["b"], copy.Values("sim/exclude_obj"));
+ Assert.Equal(
+ [
+ .. Filter(0), 1, 0, 0, 5, 1, 0, 0, 0, 7, 2, 0, // y.obj
+ 1, 1, 0, 5, 0, 0, 0, 0, 13, 0xFF, 0, 0, 0, 4, 0, // the polygon
+ 32, 6, 2, 0, 1, 0, 0, 0, 1, 0, 0, 6, 5, 2, 10, 0, 0, 0, 10, 0, 0, 2, 0, // the marker, then the road from PO32 pool 0
+ ],
+ copy.Commands);
+ // The file X-Plane reads holds the same.
+ DsfFile read = DsfFile.Parse(copy.ToBytes());
+ Assert.Equal(copy.Commands, read.Commands);
+ Assert.Equal(copy.Properties, read.Properties);
+ Assert.Equal(["x.obj", "y.obj"], read.Definitions[DsfFile.Objects]);
+ }
+
+ [Fact]
+ public void Airports_from_two_files_share_definitions_and_get_their_own_pools_and_filter_numbers()
+ {
+ DsfFile other = Dsf(["sim/filter/aptid", "EBAW"], ["z.obj", "y.obj"], pools: 1, [1, 0, 0, .. Filter(0), 3, 1, 7, 0, 0]);
+ var merger = new AirportDsfMerger();
+
+ merger.Add(GlobalTile(), new HashSet(["EBBR"]));
+ merger.Add(other, new HashSet(["EBAW"]));
+ DsfFile copy = merger.Build();
+
+ Assert.Equal(["EBBR", "EBAW"], copy.Values("sim/filter/aptid"));
+ Assert.Equal(["x.obj", "y.obj", "z.obj"], copy.Definitions[DsfFile.Objects]);
+ Assert.Equal(3, copy.Geodesy.Count(a => a.Id == DsfFile.Pool16));
+ // EBAW's y.obj is the same definition as EBBR's; its pool 0 is the third one now.
+ Assert.Equal([.. Filter(1), 1, 2, 0, 5, 1, 0, 0, 0, 7, 0, 0], copy.Commands[^19..]);
+ }
+
+ [Fact]
+ public void A_file_without_the_airport_copies_nothing_and_one_that_is_not_an_overlay_is_refused()
+ {
+ var merger = new AirportDsfMerger();
+
+ Assert.False(merger.Add(GlobalTile(), new HashSet(["LFBD"])));
+ Assert.True(merger.IsEmpty);
+ DsfFile mesh = GlobalTile() with { Properties = [new("sim/overlay", "0"), new("sim/filter/aptid", "EBBR")] };
+ Assert.Throws(() => merger.Add(mesh, new HashSet(["EBBR"])));
+ }
+
+ [Fact]
+ public void Flattening_copies_the_airports_buildings_into_the_package_and_undo_takes_them_out()
+ {
+ _tree.WriteText("X-Plane 12/Global Scenery/Global Airports/Earth nav data/apt.dat", $"I\n1200 Version\n\n{Ebbr}\n\n{Ebaw}\n\n99\n");
+ _tree.WriteBytes(Tile, GlobalTile().ToBytes());
+ string package = _tree.PathOf($"X-Plane 12/Custom Scenery/{FlattenedAirports.PackageName}");
+ string copied = Path.Join(package, "Earth nav data", "+50+000", "+50+004.dsf");
+ var flattening = new AirportFlattening(_tree.PathOf("X-Plane 12"), new AirportCatalog());
+ IReadOnlyList airports = flattening.Load(CancellationToken.None);
+
+ FlattenableAirport ebbr = flattening.Flatten(airports.Single(a => a.Ident == "EBBR"));
+ Assert.Equal(["EBBR"], DsfFile.Parse(File.ReadAllBytes(copied)).Values("sim/filter/aptid"));
+ FlattenableAirport ebaw = flattening.Flatten(airports.Single(a => a.Ident == "EBAW"));
+ Assert.Equal(["EBAW", "EBBR"], DsfFile.Parse(File.ReadAllBytes(copied)).Values("sim/filter/aptid"));
+ Assert.Equal(FlattenState.Flattened, flattening.Load(CancellationToken.None).Single(a => a.Ident == "EBBR").State);
+
+ flattening.Undo(ebbr);
+ Assert.Equal(["EBAW"], DsfFile.Parse(File.ReadAllBytes(copied)).Values("sim/filter/aptid"));
+ flattening.Undo(ebaw);
+ Assert.False(Directory.Exists(package));
+ }
+
+ [Fact]
+ public void A_copy_made_without_its_buildings_is_outdated()
+ {
+ _tree.WriteText("X-Plane 12/Global Scenery/Global Airports/Earth nav data/apt.dat", $"I\n1200 Version\n\n{Ebbr}\n\n99\n");
+ _tree.WriteBytes(Tile, GlobalTile().ToBytes());
+ var flattening = new AirportFlattening(_tree.PathOf("X-Plane 12"), new AirportCatalog());
+ flattening.Flatten(flattening.Load(CancellationToken.None).Single());
+ File.Delete(_tree.PathOf($"X-Plane 12/Custom Scenery/{FlattenedAirports.PackageName}/buildings.txt"));
+
+ Assert.Equal(FlattenState.Outdated, flattening.Load(CancellationToken.None).Single().State);
+ }
+
+ [Fact]
+ public void An_airports_area_spans_its_runways_and_datum()
+ {
+ Assert.Equal((50.8890356, 4.4803936, 50.8989489, 4.5233233), new AirportBlock(Ebbr).Area());
+ Assert.Equal((50.9894, 4.4603, 50.9894, 4.4603), new AirportBlock(Ebaw).Area());
+ Assert.Equal(Path.Join("+40-010", "+44-001.dsf"), AirportDsfFinder.TilePath(44, -1));
+ Assert.Equal(Path.Join("-10-080", "-01-071.dsf"), AirportDsfFinder.TilePath(-1, -71));
+ }
+}