From 07f95e93e85496fc7ee725663a98aef05b6bf8e0 Mon Sep 17 00:00:00 2001 From: flysimdev Date: Tue, 24 Nov 2026 17:56:56 +0100 Subject: [PATCH 1/2] Flatten Airports --- CLAUDE.md | 4 +- src/OrthoStreamXP/Gui/Airports/AirportRow.cs | 84 +++++++ src/OrthoStreamXP/Gui/MainWindow.xaml | 1 + .../Gui/ViewModels/AirportsViewModel.cs | 197 +++++++++++++++ .../Gui/ViewModels/MainViewModel.cs | 4 + src/OrthoStreamXP/Gui/Views/AirportsView.xaml | 97 ++++++++ .../Gui/Views/AirportsView.xaml.cs | 7 + .../Scenery/FileSystem/SceneryPackList.cs | 23 +- .../Setup/Airports/AirportBlock.cs | 100 ++++++++ .../Setup/Airports/AirportCatalog.cs | 37 +++ .../Setup/Airports/AirportFlattening.cs | 88 +++++++ .../Setup/Airports/AirportRecord.cs | 17 ++ .../Setup/Airports/AirportSources.cs | 41 ++++ .../Setup/Airports/AptDatReader.cs | 133 ++++++++++ .../Setup/Airports/FlattenedAirports.cs | 97 ++++++++ .../AirportFlatteningTests.cs | 231 ++++++++++++++++++ tests/OrthoStreamXP.Tests/ViewsTests.cs | 2 +- 17 files changed, 1156 insertions(+), 7 deletions(-) create mode 100644 src/OrthoStreamXP/Gui/Airports/AirportRow.cs create mode 100644 src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs create mode 100644 src/OrthoStreamXP/Gui/Views/AirportsView.xaml create mode 100644 src/OrthoStreamXP/Gui/Views/AirportsView.xaml.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/AirportBlock.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/AirportCatalog.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/AirportRecord.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/AirportSources.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/AptDatReader.cs create mode 100644 src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs create mode 100644 tests/OrthoStreamXP.Tests/AirportFlatteningTests.cs diff --git a/CLAUDE.md b/CLAUDE.md index bcc870a..5f4429f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,7 +35,7 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: * - `Configuration/` — `SettingsOptions`/`SettingsSchema` (the known settings and the ini reader), `SettingValues` (typed access), `SettingsException`; `MountSettings` turns the values into a mount's settings. - `Mounting/` — `MountSession`: each scenery package gets its own `PackageMount` (overlay + build scheduler + load-ahead), sharing one downloader/encoder and the aircraft-position listener. `MountStatus` is the live snapshot for the UI. - `Infrastructure/` — `Log`, `AtomicFile`. -- `Gui/` — `App`, `MainWindow`, `GuiHost`, `MountController` (drives a `MountSession` from the window) at the root; `Views/` (XAML + code-behind: Home, Setup, Settings, Cache, Log, About), `ViewModels/`, `Settings/` and `Home/` (the types those pages show), `Mvvm/` (`ObservableObject`, `RelayCommand`, converters), `Map/` (cities, flight charts). +- `Gui/` — `App`, `MainWindow`, `GuiHost`, `MountController` (drives a `MountSession` from the window) at the root; `Views/` (XAML + code-behind: Home, Setup, Settings, Cache, Airports, Log, About), `ViewModels/`, `Settings/`, `Home/` and `Airports/` (the types those pages show), `Mvvm/` (`ObservableObject`, `RelayCommand`, converters), `Map/` (cities, flight charts). - `Scenery/` — the runtime streaming pipeline: - `FileSystem/`: `SceneryFileSystem` (WinFsp `FileSystemBase`) → `SceneryOverlay` (resolves a path to a backing file, a streamed photo texture, or an in-memory terrain definition); `SceneryPacks`, `TerrainDefinitions`. - `Streaming/`: `TextureStreamer` and its read/stand-in/build types, `TextureScheduler`, `TextureCatalog`, `ReadLog`. @@ -44,7 +44,7 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: * - `Aircraft/`: `AircraftPositionListener` (X-Plane UDP), `ViewTracker`, `SceneryLoads`. - `Colour/`: `SeasonClock` (seasonal tint by simulated date/location), `ObservedSeasons` (loads the satellite record per ~500 km tile for `season = satellite`). - `Textures/` — imagery to DDS: `TextureBuilder` (fetch → stitch → resize → sharpen → mipmaps → BC1 encode → atomic write; SkiaSharp is decode-only), `TextureQuality`, `Images`, `Sharpening` (unsharp mask on brightness, not a setting: 100 % for the areas' textures below ZL18, 60 % for the airports' ZL18 and finer) at the root; `Tiles/` (`TileSource`/`TileStore`: download + cache; the low-zoom base is zoom 13 and coarser because Bing's zoom 12 is other, lighter imagery; a tile every provider definitively lacks throws `TileNotAvailableException`, and `TextureBuilder` then makes it from a parent at hand, never coarser than 13), `Dds/` (`Dds` layout/encode/decode; mip levels by `MipFilter` = 2x2 averages in linear light; BC1 by `IspcBc1` = Intel's ISPC `ispc_texcomp.dll` from `native/ispc_texcomp/` (checked in, rebuilt by its `build.ps1`), loaded from the exe's folder, with one-colour blocks and four-colour mode fixed after it and every other block's colours refined by least squares (`Bc1Refinement`); `Dds.EncodeRangeFit` is the fallback without the DLL), `Scheduling/` (priority gates), `Seasons/` (`SeasonModel` calendar, `ObservedSeason` + `GreennessYear`: grass and fields by a place's yearly NDVI against its greenest month, trees by the calendar), `Vegetation/` (`VegetationSource`: NASA GIBS monthly VIIRS NDVI, downloaded and kept under the low-zoom base; `VegetationTile`, `NdviPalette`), `Colour/` (`Exposure`, `Contrast` (fixed 60 % S-curve, always on, not a setting), `ColourTable` = the shared BC1 lookup-table recolouring, `PhotoColours` = season → contrast → exposure as one table (rounded to 565 once) applied as X-Plane reads, also used by the Settings preview). -- `Setup/` — `Settings/` (`SettingsDocument`, ini under `%LOCALAPPDATA%\OrthoStreamXP`, `QualityPreset`, `ConnectionTest`), `Cache/` (inventory, areas, eviction), `Packages/` (downloads AutoOrtho's mesh regions from GitHub into the packages folder as `OrthoStream_*` packages: `MeshCatalog`, `AssetDownload`, `ZipUnpacker`, `OverlayPackage`, `RegionInstaller`; the tiles AutoOrtho lacks come from `flysimdev/orthostreamxp-scenery`'s latest-release `supplements.json` (`SupplementCatalog`, `RegionSupplement`) and are merged into their region without replacing any file, at install or, for regions installed before, by `Gui/Packages/SupplementUpdater` at each window start), `Installation/` (`AppPaths`, `AppUpdates`, `LegacyNames` migrating older settings/cache locations, `SystemCheck`, Velopack hooks). +- `Setup/` — `Settings/` (`SettingsDocument`, ini under `%LOCALAPPDATA%\OrthoStreamXP`, `QualityPreset`, `ConnectionTest`), `Cache/` (inventory, areas, eviction), `Packages/` (downloads AutoOrtho's mesh regions from GitHub into the packages folder as `OrthoStream_*` packages: `MeshCatalog`, `AssetDownload`, `ZipUnpacker`, `OverlayPackage`, `RegionInstaller`; the tiles AutoOrtho lacks come from `flysimdev/orthostreamxp-scenery`'s latest-release `supplements.json` (`SupplementCatalog`, `RegionSupplement`) and are merged into their region without replacing any file, at install or, for regions installed before, by `Gui/Packages/SupplementUpdater` at each window start), `Airports/` (the Airports page's flattening, one airport at a time: `AptDatReader` lists the airports of an apt.dat, `AirportSources` + `AirportCatalog` pick each ident from the highest enabled package in scenery_packs.ini (`*GLOBAL_AIRPORTS*` = Global Scenery\Global Airports), `FlattenedAirports` keeps a copy of each flattened airport with `1302 flatten 1` in its own `Custom Scenery\OrthoStreamXP Flattened Airports` package listed above the airport's source; the source files are never changed, Undo removes the copy and the last one removes the package), `Installation/` (`AppPaths`, `AppUpdates`, `LegacyNames` migrating older settings/cache locations, `SystemCheck`, Velopack hooks). - `Tuning/` — flight reports, facts and the preset/setting recommendations. - Logs go to `%LOCALAPPDATA%\OrthoStreamXP\logs`. diff --git a/src/OrthoStreamXP/Gui/Airports/AirportRow.cs b/src/OrthoStreamXP/Gui/Airports/AirportRow.cs new file mode 100644 index 0000000..daa061c --- /dev/null +++ b/src/OrthoStreamXP/Gui/Airports/AirportRow.cs @@ -0,0 +1,84 @@ +using System.Windows.Input; +using OrthoStreamXP.Setup; + +namespace OrthoStreamXP.Gui; + +/// An airport on the Airports page, with its own Flatten or Undo button (one airport at a time: there is no batch). +internal sealed class AirportRow : ObservableObject +{ + private FlattenableAirport _airport; + private bool _busy; + private string? _error; + + public AirportRow(FlattenableAirport airport, AirportsViewModel page) + { + _airport = airport; + Flatten = new RelayCommand(() => _ = page.FlattenAsync(this), () => page.CanChange && CanFlatten); + Undo = new RelayCommand(() => _ = page.UndoAsync(this), () => page.CanChange && CanUndo); + } + + public FlattenableAirport Airport + { + get => _airport; + set + { + _airport = value; + Raise(null); // every property follows from it + } + } + + public string Ident => Airport.Ident; + public string Name => Airport.Name; + + /// "Brussels, BEL · from Global Airports". + public string Details + { + get + { + string from = Airport.Source is { } source ? $"from {source.Source.Name}" : "its scenery package is no longer in the scenery list"; + return Airport.Place is { } place ? $"{place} · {from}" : char.ToUpperInvariant(from[0]) + from[1..]; + } + } + + /// The airport's flattening in words; null while it is not flattened. + 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.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", + _ => null, + }; + + /// A problem to point out (an outdated or overridden copy) rather than a plain state. + public bool StateIsWarning => Airport.State == FlattenState.Outdated || (Airport.IsFlattenedHere && !Airport.InEffect); + + public bool CanFlatten => !Busy && Airport.Source is not null + && (Airport.State is FlattenState.NotFlattened or FlattenState.Outdated || (Airport.IsFlattenedHere && !Airport.InEffect)); + + public bool CanUndo => !Busy && Airport.IsFlattenedHere; + + public bool ShowFlatten => Airport.Source is not null && Airport.State != FlattenState.FlattenedByScenery && (!Airport.IsFlattenedHere || StateIsWarning); + public bool ShowUndo => Airport.IsFlattenedHere; + public string FlattenLabel => Airport.IsFlattenedHere ? "Flatten again" : "Flatten"; + + public ICommand Flatten { get; } + public ICommand Undo { get; } + + public bool Busy + { + get => _busy; + set + { + Set(ref _busy, value); + RelayCommand.Refresh(); + } + } + + public string? Error + { + get => _error; + set => Set(ref _error, value); + } +} diff --git a/src/OrthoStreamXP/Gui/MainWindow.xaml b/src/OrthoStreamXP/Gui/MainWindow.xaml index 6b7b49a..4ad8ee4 100644 --- a/src/OrthoStreamXP/Gui/MainWindow.xaml +++ b/src/OrthoStreamXP/Gui/MainWindow.xaml @@ -12,6 +12,7 @@ + diff --git a/src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs new file mode 100644 index 0000000..d95698c --- /dev/null +++ b/src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs @@ -0,0 +1,197 @@ +using System.Collections.ObjectModel; +using System.Windows.Input; +using OrthoStreamXP.Setup; + +namespace OrthoStreamXP.Gui; + +/// +/// The Airports page: find an airport or airfield and flatten the terrain under it (for an airport that sits on a bump or in a +/// hollow of the mesh), or undo that. One airport at a time. The airports are read from the apt.dat files of the packages in +/// X-Plane's scenery_packs.ini when the page is shown (only the files that changed are read again). +/// +internal sealed class AirportsViewModel : ObservableObject, IPage +{ + /// How many matches the list shows: enough to pick from, few enough to stay quick. + private const int MaxRows = 50; + + private readonly MountController _mount; + private readonly Func _xplane; + private readonly AirportCatalog _catalog = new(); + private readonly Dictionary _airports = new(StringComparer.OrdinalIgnoreCase); + private AirportFlattening? _flattening; + private string _search = ""; + private bool _loading, _changing, _moreRows; + private string? _message; + + /// The X-Plane folder of the settings; null while there is none. + public AirportsViewModel(MountController mount, Func xplane) + { + _mount = mount; + _xplane = xplane; + Refresh = new RelayCommand(() => _ = LoadAsync(), () => !Loading && !_changing); + OpenFolder = new RelayCommand(() => Shell.Open(_flattening!.PackageFolder), () => _flattening is { } f && Directory.Exists(f.PackageFolder)); + // Starting and stopping rewrite scenery_packs.ini: no change of it meanwhile. + _mount.PropertyChanged += (_, e) => + { + if (e.PropertyName != nameof(MountController.State)) return; + Raise(nameof(CanChange)); + RelayCommand.Refresh(); + }; + } + + public ObservableCollection Rows { get; } = []; + public ICommand Refresh { get; } + public ICommand OpenFolder { get; } + + /// An ICAO code (or the start of one), or part of a name or city. + public string Search + { + get => _search; + set + { + if (Set(ref _search, value ?? "")) Filter(); + } + } + + public bool Loading + { + get => _loading; + private set + { + Set(ref _loading, value); + Raise(nameof(ListText)); + RelayCommand.Refresh(); + } + } + + /// One airport is changed at a time, and none while OrthoStreamXP starts or stops. + public bool CanChange => !_changing && !Loading && (_mount.IsRunning || _mount.IsStopped); + + /// What the list below shows. + public string ListText + { + get + { + if (Loading) return "Reading the airports of your scenery…"; + if (_xplane() is null) return "Choose your X-Plane folder first (in Settings): its airports are listed here."; + if (Search.Trim().Length == 0) + return Rows.Count == 0 ? "Search for an airport by its ICAO code, name or city." : "The airports you flattened:"; + if (Rows.Count == 0) return $"No airport matches \"{Search.Trim()}\"."; + return _moreRows ? $"The first {MaxRows} matches: type more to narrow them." : ""; + } + } + + public string? Message + { + get => _message; + private set + { + Set(ref _message, value); + Raise(nameof(HasMessage)); + } + } + + public bool HasMessage => Message is not null; + + public void OnShown() => _ = LoadAsync(); + + private async Task LoadAsync() + { + if (Loading || _changing) return; // the change in progress refreshes its own row + Message = null; + if (_xplane() is not { } xplane) + { + _flattening = null; + _airports.Clear(); + Filter(); + return; + } + Loading = true; + try + { + var flattening = new AirportFlattening(xplane, _catalog); + IReadOnlyList airports = await Task.Run(() => flattening.Load(CancellationToken.None)).ConfigureAwait(true); + _flattening = flattening; + _airports.Clear(); + foreach (FlattenableAirport airport in airports) _airports[airport.Ident] = airport; + if (_airports.Count == 0) Message = $"No airports found: X-Plane's Global Airports and the packages in {Path.Join(xplane, "Custom Scenery")} list none."; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Message = $"Could not read the airports: {ex.Message}"; + Log.Warning(Message); + } + catch (Exception ex) + { + // Runs unawaited from the page: nothing that goes wrong may vanish. + Message = $"Could not read the airports: {ex.Message}"; + Log.Error("The airports could not be read", ex); + } + finally + { + Loading = false; + Filter(); + } + } + + public Task FlattenAsync(AirportRow row) => ChangeAsync(row, f => f.Flatten(row.Airport), "flattened"); + + public Task UndoAsync(AirportRow row) => ChangeAsync(row, f => f.Undo(row.Airport), "put back"); + + private async Task ChangeAsync(AirportRow row, Func change, string done) + { + if (!CanChange || _flattening is not { } flattening) return; + _changing = true; + row.Busy = true; + row.Error = null; + Raise(nameof(CanChange)); + try + { + FlattenableAirport changed = await Task.Run(() => change(flattening)).ConfigureAwait(true); + _airports[changed.Ident] = changed; + row.Airport = changed; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) + { + row.Error = $"{row.Ident} could not be {done}: {ex.Message}"; + Log.Warning(row.Error); + } + catch (Exception ex) + { + // Runs unawaited from a button: nothing that goes wrong may vanish. + row.Error = $"{row.Ident} could not be {done}: {ex.Message}"; + Log.Error(row.Error, ex); + } + finally + { + _changing = false; + row.Busy = false; + Raise(nameof(CanChange)); + RelayCommand.Refresh(); + } + } + + /// The airports matching the search (an exact code first, then codes starting with it, then names and cities); the flattened ones without a search. + private void Filter() + { + string query = Search.Trim(); + IEnumerable matches = query.Length == 0 + ? _airports.Values.Where(a => a.IsFlattenedHere).OrderBy(a => a.Ident, StringComparer.OrdinalIgnoreCase) + : _airports.Values.Select(a => (Airport: a, Rank: Rank(a, query))).Where(m => m.Rank >= 0) + .OrderBy(m => m.Rank).ThenBy(m => m.Airport.Ident, StringComparer.OrdinalIgnoreCase).Select(m => m.Airport); + FlattenableAirport[] shown = [.. matches.Take(MaxRows + 1)]; + _moreRows = shown.Length > MaxRows; + Rows.Clear(); + foreach (FlattenableAirport airport in shown.Take(MaxRows)) Rows.Add(new AirportRow(airport, this)); + Raise(nameof(ListText)); + RelayCommand.Refresh(); + } + + private static int Rank(FlattenableAirport airport, string query) + { + if (airport.Ident.Equals(query, StringComparison.OrdinalIgnoreCase)) return 0; + if (airport.Ident.StartsWith(query, StringComparison.OrdinalIgnoreCase)) return 1; + if (airport.Name.Contains(query, StringComparison.OrdinalIgnoreCase)) return 2; + return airport.Place?.Contains(query, StringComparison.OrdinalIgnoreCase) == true ? 3 : -1; + } +} diff --git a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs index 79170ea..f626f72 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs @@ -71,6 +71,7 @@ public MainViewModel() Cache = new CacheViewModel(this); Packages = new PackagesViewModel(Mount, Preferences, MeshHttp, MeshInstalls, PackagesFolder); Scenery = new SceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); + Airports = new AirportsViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); About = new AboutViewModel(); Navigation = [ @@ -79,6 +80,7 @@ public MainViewModel() new NavItem("Cache", "", Cache), new NavItem("Packages", "", Packages), new NavItem("X-Plane Custom Scenery", "", Scenery), + new NavItem("Airports", "", Airports), new NavItem("Log", "", LogPage), new NavItem("About", "", About), ]; @@ -105,6 +107,8 @@ public MainViewModel() public InstallSlot MeshInstalls { get; } = new(); /// X-Plane's scenery_packs.ini, to switch packages on or off. public SceneryViewModel Scenery { get; } + /// Flattens the terrain under an airport, one at a time, and undoes it. + public AirportsViewModel Airports { get; } public LogViewModel LogPage { get; } public AboutViewModel About { get; } public IReadOnlyList Navigation { get; } diff --git a/src/OrthoStreamXP/Gui/Views/AirportsView.xaml b/src/OrthoStreamXP/Gui/Views/AirportsView.xaml new file mode 100644 index 0000000..e445870 --- /dev/null +++ b/src/OrthoStreamXP/Gui/Views/AirportsView.xaml @@ -0,0 +1,97 @@ + + + + + + + + + + +