From 797e2e70a7474898c65a0eac72139723d88c0e5e Mon Sep 17 00:00:00 2001 From: maj00r Date: Tue, 17 Nov 2026 02:15:45 +0100 Subject: [PATCH 1/7] feat(sceneries): a release clears the .sbt files once, and a scenery's menu deletes its own The simulator makes a scenery's .sbt on its first load and never checks it against the text again, so an older simulator's file, or one made before a scenery update, keeps showing the old terrain. - CleanupGeneration, raised by a release, clears the .sbt files once per installation on the first start, ahead of the scenery list. A file goes only while its scenery's terrain files (*_ter.scm) are all there and no terrain directive brings terrain from elsewhere; an .sbt standing in for missing terrain stays, and the log says what is missing. Which cleanup each installation had is kept in sbt-cleanup.txt in the user's folder. - "Delete SBT" in the scenery list's menu does the same for one scenery, asking first and refusing where nothing could make the file again. - The .sbt is among the files a scenery is watched by, so one made or removed reaches the list without a reload. --- StarterNG.Tests/BinaryTerrainFilesTests.cs | 157 +++++++++++ StarterNG.Tests/SceneryFileWatchTests.cs | 20 ++ StarterNG/App.axaml.cs | 3 + StarterNG/Application/AppServices.cs | 3 + .../Sceneries/BinaryTerrainFiles.cs | 257 ++++++++++++++++++ .../Sceneries/SceneryRepository.cs | 7 +- .../Infrastructure/Settings/SettingsPaths.cs | 3 + StarterNG/Views/Scenarios.axaml | 2 + StarterNG/Views/Scenarios.axaml.cs | 33 +++ StarterNG/startercfg/lang/cz.xml | 4 + StarterNG/startercfg/lang/en.xml | 4 + StarterNG/startercfg/lang/hu.xml | 4 + StarterNG/startercfg/lang/pl.xml | 4 + StarterNG/startercfg/lang/ru.xml | 4 + 14 files changed, 504 insertions(+), 1 deletion(-) create mode 100644 StarterNG.Tests/BinaryTerrainFilesTests.cs create mode 100644 StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs diff --git a/StarterNG.Tests/BinaryTerrainFilesTests.cs b/StarterNG.Tests/BinaryTerrainFilesTests.cs new file mode 100644 index 0000000..159d8d3 --- /dev/null +++ b/StarterNG.Tests/BinaryTerrainFilesTests.cs @@ -0,0 +1,157 @@ +using StarterNG.Infrastructure.Adapters; +using StarterNG.Infrastructure.Sceneries; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +public class BinaryTerrainFilesTests +{ + private const string Record = "user/sbt-cleanup.txt"; + + private static BinaryTerrainFiles Build(InMemoryFileSystem files, string root = "game") => + new(files, new GamePaths(root), TestLog.Over(files), Record); + + private static string Scenery(string name) => $"game/scenery/{name}"; + + [Fact] + public void An_sbt_whose_terrain_files_are_all_there_goes() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("kato.scn"), "include kato/kato_ter.scm end\nFirstInit\n") + .WithFile(Scenery("kato/kato_ter.scm"), "node") + .WithFile(Scenery("kato.sbt"), "EU07SBT2"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + Assert.Equal("kato.sbt", Assert.Single(cleanup.Deleted)); + Assert.False(files.FileExists(Scenery("kato.sbt"))); + } + + [Fact] + public void An_sbt_standing_in_for_missing_terrain_files_stays() + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithLegacyFile(Scenery("Lk2_Sandbox.scn"), "include nmt/nmt100_mazowieckie_ter.scm end\nFirstInit\n") + .WithFile(Scenery("lk2_sandbox.sbt"), "EU07SBT2"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + Assert.Empty(cleanup.Deleted); + Assert.Equal(("lk2_sandbox.sbt", "nmt/nmt100_mazowieckie_ter.scm"), Assert.Single(cleanup.Kept)); + Assert.True(files.FileExists(Scenery("lk2_sandbox.sbt"))); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Terrain_included_through_another_file_is_looked_for_too(bool present) + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "include td/base.inc end\nFirstInit\n") + .WithLegacyFile(Scenery("td/base.inc"), "include td/td_ter.scm 1 2 end\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + if (present) + files.WithFile(Scenery("td/td_ter.scm"), "node"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + Assert.Equal(present, cleanup.Deleted.Count == 1); + Assert.Equal(present, !files.FileExists(Scenery("td.sbt"))); + } + + [Fact] + public void A_missing_include_other_than_terrain_does_not_keep_the_sbt() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("tomaszewo.scn"), "include tomaszewo/modele.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("tomaszewo/modele.scm"), + "include;przejazdy_kombud\\1t12m_0rog_2zar_1x_1dzw.inc;p_czernica15;0;0;0;end\n") + .WithFile(Scenery("tomaszewo.sbt"), "EU07SBT2"); + + Assert.Single(Build(files).CleanUpOnce(1)!.Deleted); + } + + [Fact] + public void An_include_commented_out_needs_no_file() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "// include gone_ter.scm end\n/* include gone.inc end */\nFirstInit\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Single(Build(files).CleanUpOnce(1)!.Deleted); + } + + [Fact] + public void A_scenery_bringing_terrain_by_a_terrain_directive_keeps_its_sbt() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "terrain td.sbt endterrain\nFirstInit\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Equal("td.sbt", Assert.Single(Build(files).CleanUpOnce(1)!.Kept).File); + } + + [Fact] + public void An_sbt_of_no_scenery_stays() + { + var files = new InMemoryFileSystem() + .WithFile(Scenery("old.sbt"), "EU07SBT2"); + + Assert.Equal(("old.sbt", "old.scn"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept)); + } + + [Fact] + public void Each_generation_clears_an_installation_once() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "FirstInit\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + var sbt = Build(files); + + Assert.NotNull(sbt.CleanUpOnce(1)); + files.WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Null(sbt.CleanUpOnce(1)); + Assert.True(files.FileExists(Scenery("td.sbt"))); + + Assert.Single(sbt.CleanUpOnce(2)!.Deleted); + } + + [Fact] + public void Generation_zero_clears_nothing() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "FirstInit\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Null(Build(files).CleanUpOnce(0)); + Assert.True(files.FileExists(Scenery("td.sbt"))); + } + + [Fact] + public void Another_installation_has_a_cleanup_of_its_own() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "FirstInit\n") + .WithLegacyFile("other/scenery/td.scn", "FirstInit\n") + .WithFile("other/scenery/td.sbt", "EU07SBT2"); + + Assert.NotNull(Build(files).CleanUpOnce(1)); + + Assert.Single(Build(files, "other").CleanUpOnce(1)!.Deleted); + } + + [Fact] + public void One_scenery_s_sbt_is_found_whatever_its_case_and_deleted() + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithLegacyFile(Scenery("Kato.scn"), "FirstInit\n") + .WithFile(Scenery("kato.sbt"), "EU07SBT2"); + var sbt = Build(files); + + Assert.Equal(Path.Combine("game", "scenery", "kato.sbt"), sbt.Of(Scenery("Kato.scn"))); + Assert.Null(sbt.MissingOriginal(Scenery("Kato.scn"))); + Assert.True(sbt.Delete(Scenery("Kato.scn"))); + Assert.Null(sbt.Of(Scenery("Kato.scn"))); + } +} diff --git a/StarterNG.Tests/SceneryFileWatchTests.cs b/StarterNG.Tests/SceneryFileWatchTests.cs index d33bd3f..f731294 100644 --- a/StarterNG.Tests/SceneryFileWatchTests.cs +++ b/StarterNG.Tests/SceneryFileWatchTests.cs @@ -53,6 +53,26 @@ public class SceneryFileWatchTests Assert.Equal("Katowice Główne", change.Fresh!.Name); } + [Theory] + [InlineData(true)] + [InlineData(false)] + public void An_sbt_made_or_removed_makes_the_scenery_read_anew(bool there) + { + string sbt = TestInstallation.At("scenery", "kato.sbt"); + var files = Folder(); + if (there) + files.WithFile(sbt, "EU07SBT2"); + var (installation, watch, _) = Rig(files); + + if (there) + files.DeleteFile(sbt); + else + files.WithFile(sbt, "EU07SBT2"); + + var change = Assert.Single(watch.Look(installation.Library.Sceneries)); + Assert.Equal(!there, change.Fresh!.HasCompanionTimetable); + } + [Fact] public void An_include_that_changed_or_came_makes_the_scenery_read_anew() { diff --git a/StarterNG/App.axaml.cs b/StarterNG/App.axaml.cs index 747cf9b..86b9234 100644 --- a/StarterNG/App.axaml.cs +++ b/StarterNG/App.axaml.cs @@ -160,6 +160,9 @@ public partial class App : Avalonia.Application }); }); + // Ahead of the sceneries, so the list knows which still have their .sbt. + try { AppServices.Current.BinaryTerrain.CleanUpOnce(); } + catch (Exception ex) { Diagnostics.Log("sbt cleanup", ex); } AppServices.Current.Library.Load(progress); }).ContinueWith(load => { diff --git a/StarterNG/Application/AppServices.cs b/StarterNG/Application/AppServices.cs index 2f6f1a8..808a03a 100644 --- a/StarterNG/Application/AppServices.cs +++ b/StarterNG/Application/AppServices.cs @@ -43,6 +43,7 @@ public sealed class AppServices paths.FromRoot("starter"), paths.FromRoot("lang"))); Sceneries = new SceneryRepository(files, paths, log, new SceneryParser(clock, random)); + BinaryTerrain = new BinaryTerrainFiles(files, paths, log, settingsPaths.SbtCleanupPath()); SceneryImages = new SceneryImageLocator(files); MiniTextures = new MiniTextureIndex(files, paths); @@ -111,6 +112,8 @@ public sealed class AppServices public SceneryFileWatch SceneryFiles { get; } + public BinaryTerrainFiles BinaryTerrain { get; } + public SceneryImageLocator SceneryImages { get; } public IMiniTextureIndex MiniTextures { get; } diff --git a/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs b/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs new file mode 100644 index 0000000..2036ba0 --- /dev/null +++ b/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs @@ -0,0 +1,257 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using StarterNG.Application.Abstractions; +using StarterNG.Domain; +using StarterNG.Domain.Sceneries; +using StarterNG.Infrastructure.Adapters; + +namespace StarterNG.Infrastructure.Sceneries; + +/// +/// The sceneries' binary terrain files (.sbt): the simulator writes one beside a +/// scenery on its first load and from then on takes the terrain from it, passing +/// the scenery's terrain includes (*_ter.scm) over. It never asks whether +/// the text changed since, so a file made by an older simulator, or before the +/// scenery was updated, keeps showing what was there then. +/// +/// A file goes only when the scenery's text still holds what it was made of: some +/// sceneries come with the .sbt in place of their terrain includes, and without it +/// they would have no terrain at all. +/// +/// +public sealed class BinaryTerrainFiles +{ + /// + /// Raised by a release that wants the .sbt files made anew: each installation is + /// cleared once for each value, on the first start of a starter carrying it. + /// Zero clears nothing. + /// + public const int CleanupGeneration = 1; + + private const string Extension = ".sbt"; + + // The simulator splits its text into words at spaces, tabs, line ends and semicolons. + private static readonly Regex Word = new(@"[^\s;]+", RegexOptions.CultureInvariant); + + private readonly IFileSystem _files; + private readonly IGamePaths _paths; + private readonly IDiagnosticsLog _log; + private readonly string _recordPath; + + /// Where the cleanups done are noted, for each installation. + public BinaryTerrainFiles(IFileSystem files, IGamePaths paths, IDiagnosticsLog log, string recordPath) + { + _files = files; + _paths = paths; + _log = log; + _recordPath = recordPath; + } + + /// The scenery's own .sbt as it is on disk, whatever the case of its letters; null when it has none. + public string? Of(string sceneryPath) + { + string? file = new CaseInsensitivePaths(_files) + .Resolve(_paths.Scenery, Path.GetFileNameWithoutExtension(sceneryPath) + Extension); + return file is null ? null : Path.Combine(_paths.Scenery, file); + } + + /// + /// What the simulator would miss to make the scenery's .sbt again - the first + /// terrain file its text names and the installation lacks, or the terrain directive + /// that brings terrain from elsewhere; null when the text holds it all. + /// + public string? MissingOriginal(string sceneryPath) + { + try + { + var names = new CaseInsensitivePaths(_files, keepListings: true); + string? own = names.Resolve(_paths.Scenery, Path.GetFileName(sceneryPath)); + if (own is null) + return Path.GetFileName(sceneryPath); + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var pending = new Stack(); + pending.Push(own); + while (pending.Count > 0) + { + string file = pending.Pop(); + if (!seen.Add(file)) + continue; + + if (Scan(file, names, pending) is { } missing) + return missing; + } + + return null; + } + catch (Exception ex) + { + _log.Log($"sbt/{Path.GetFileName(sceneryPath)}", ex); + return Path.GetFileName(sceneryPath); + } + } + + /// + /// Reads one file of the scenery for its includes: the terrain ones have to be + /// there, the others are read in turn. Terrain files are not opened - they are the + /// largest of all and include nothing. + /// + private string? Scan(string file, CaseInsensitivePaths names, Stack pending) + { + string text = LegacyText.Decode(_files.ReadAllBytes(Path.Combine(_paths.Scenery, file))); + string code = SceneryCode.Mask(text, out _); + + bool includeNext = false; + for (var word = Word.Match(code); word.Success; word = word.NextMatch()) + { + string token = word.Value; + if (includeNext) + { + includeNext = false; + bool terrain = SimulatorNames.Lower(token).Contains("_ter.scm"); + string? found = names.Resolve(_paths.Scenery, token); + if (found is null && terrain) + return token; + // Any other file the simulator reads from the text, .sbt or not: missing, + // it is missing either way, and the .sbt made again lacks nothing. + if (found is not null && !terrain) + pending.Push(found); + } + else if (token.Equals("include", StringComparison.OrdinalIgnoreCase)) + includeNext = true; + else if (token.Equals("terrain", StringComparison.OrdinalIgnoreCase)) + return token; + } + + return null; + } + + /// Removes the scenery's .sbt; false when it has none or it could not go. + public bool Delete(string sceneryPath) + { + if (Of(sceneryPath) is not { } file) + return false; + + try + { + _files.DeleteFile(file); + _log.Log($"{file} removed, the simulator makes it again on the next load of the scenery"); + return true; + } + catch (Exception ex) + { + _log.Log($"sbt/{Path.GetFileName(file)}", ex); + return false; + } + } + + /// + /// Clears the .sbt files the simulator can make again, once for each + /// on this installation; null when it was done + /// already. A file that could not go leaves the cleanup to the next start. + /// + public BinaryTerrainCleanup? CleanUpOnce(int generation = CleanupGeneration) + { + if (generation <= 0 || !_files.DirectoryExists(_paths.Scenery)) + return null; + + var record = ReadRecord(); + string installation = Installation(); + if (record.TryGetValue(installation, out int done) && done >= generation) + return null; + + var deleted = new List(); + var kept = new List<(string File, string Reason)>(); + var failed = new List(); + var names = new CaseInsensitivePaths(_files); + + foreach (string sbt in _files.GetFiles(_paths.Scenery) + .Where(f => Path.GetExtension(f).Equals(Extension, StringComparison.OrdinalIgnoreCase))) + { + string name = Path.GetFileName(sbt); + string? scenery = names.Resolve(_paths.Scenery, Path.GetFileNameWithoutExtension(sbt) + ".scn"); + string? missing = scenery is null ? Path.GetFileNameWithoutExtension(sbt) + ".scn" : MissingOriginal(scenery); + if (missing is not null) + { + kept.Add((name, missing)); + _log.Log($"{name} kept: the scenery cannot be made without it, {missing} is missing"); + continue; + } + + try + { + _files.DeleteFile(sbt); + deleted.Add(name); + } + catch (Exception ex) + { + failed.Add(name); + _log.Log($"sbt/{name}", ex); + } + } + + if (deleted.Count > 0) + _log.Log($"Binary terrain files removed, the simulator makes them again: {string.Join(", ", deleted)}"); + + if (failed.Count == 0) + { + record[installation] = generation; + WriteRecord(record); + } + + return new BinaryTerrainCleanup(deleted, kept, failed); + } + + private string Installation() => + Path.TrimEndingDirectorySeparator(Path.GetFullPath(_paths.Root)); + + private Dictionary ReadRecord() + { + var record = new Dictionary( + _files.IgnoresCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + try + { + if (!_files.FileExists(_recordPath)) + return record; + + foreach (string line in _files.ReadAllLines(_recordPath)) + { + int tab = line.IndexOf('\t'); + if (tab > 0 && int.TryParse(line[..tab], out int generation)) + record[line[(tab + 1)..]] = generation; + } + } + catch (Exception ex) + { + _log.Log("sbt cleanup record", ex); + } + + return record; + } + + private void WriteRecord(Dictionary record) + { + try + { + if (Path.GetDirectoryName(_recordPath) is { Length: > 0 } folder) + _files.CreateDirectory(folder); + _files.WriteAllTextAtomic(_recordPath, + string.Concat(record.Select(entry => $"{entry.Value}\t{entry.Key}\n"))); + } + catch (Exception ex) + { + _log.Log("sbt cleanup record", ex); + } + } +} + +/// The files removed. +/// The files left, as nothing could make them again, each with what is missing. +/// The files that could not be removed. +public sealed record BinaryTerrainCleanup( + IReadOnlyList Deleted, + IReadOnlyList<(string File, string Reason)> Kept, + IReadOnlyList Failed); diff --git a/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs b/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs index 229d59a..63c02c3 100644 --- a/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs +++ b/StarterNG/Infrastructure/Sceneries/SceneryRepository.cs @@ -79,7 +79,12 @@ public sealed class SceneryRepository : ISceneryRepository // With its own .sbt the scenery's terrain comes from it, and the simulator // passes its terrain includes over without opening them. - bool binaryTerrain = Opens(Path.GetFileNameWithoutExtension(path) + ".sbt"); + // Watched with the text: made by the simulator on a load, or removed, it changes the scenery too. + string sbtName = Path.GetFileNameWithoutExtension(path) + ".sbt"; + string? sbt = ResolveInclude(sbtName); + bool binaryTerrain = sbt is not null; + string sbtPath = Path.Combine(_paths.Scenery, sbt ?? sbtName); + sources[sbtPath] = FileStamp.Of(_files, sbtPath); bool OpensInclude(string name) => Opens(name) || (binaryTerrain && SimulatorNames.Lower(name).Contains("_ter.scm")); diff --git a/StarterNG/Infrastructure/Settings/SettingsPaths.cs b/StarterNG/Infrastructure/Settings/SettingsPaths.cs index a80a297..55130cf 100644 --- a/StarterNG/Infrastructure/Settings/SettingsPaths.cs +++ b/StarterNG/Infrastructure/Settings/SettingsPaths.cs @@ -53,6 +53,9 @@ public sealed class SettingsPaths /// The sceneries starred in the list. public string FavoritesPath() => Path.Combine(UserConfigDirectory(), "favorites.txt"); + /// Which cleanup of the .sbt files each installation had. + public string SbtCleanupPath() => Path.Combine(UserConfigDirectory(), "sbt-cleanup.txt"); + public string UserConfigDirectory() => Path.GetDirectoryName(UserConfigPath()) ?? _environment.BaseDirectory; } diff --git a/StarterNG/Views/Scenarios.axaml b/StarterNG/Views/Scenarios.axaml index 7e733dd..5c541b0 100644 --- a/StarterNG/Views/Scenarios.axaml +++ b/StarterNG/Views/Scenarios.axaml @@ -45,6 +45,8 @@ Header="{Binding [ReloadSceneries], Source={x:Static starterNg:App.Loc}}" /> + diff --git a/StarterNG/Views/Scenarios.axaml.cs b/StarterNG/Views/Scenarios.axaml.cs index 326a283..856e09f 100644 --- a/StarterNG/Views/Scenarios.axaml.cs +++ b/StarterNG/Views/Scenarios.axaml.cs @@ -165,6 +165,39 @@ public partial class Scenarios : UserControl favoriteMenuItem.Header = App.Loc[scenery is not null && AppServices.Current.Favorites.Contains(scenery) ? "FavoriteRemove" : "FavoriteAdd"]; + deleteSbtMenuItem.IsEnabled = scenery is not null + && !AppServices.Current.State.SimulatorRunning + && AppServices.Current.BinaryTerrain.Of(scenery.Path) is not null; + } + + // Only a file the simulator can make again from the scenery's text goes: one + // standing in for terrain files the installation lacks takes the terrain with it. + private async void DeleteSbt_OnClick(object? sender, RoutedEventArgs e) + { + if (SelectedScenery is not { } scenery || TopLevel.GetTopLevel(this) is not Window owner) + return; + + var sbt = AppServices.Current.BinaryTerrain; + if (sbt.Of(scenery.Path) is not { } file) + return; + + string name = Path.GetFileName(file); + string title = App.Loc["DeleteSbt"]; + if (await Task.Run(() => sbt.MissingOriginal(scenery.Path)) is { } missing) + { + await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtNoOriginal"], name, missing), title, + MessageBoxButtons.Ok); + return; + } + + long megabytes = AppServices.Current.Files.GetFileSize(file) / (1024 * 1024); + if (!await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtConfirm"], name, megabytes), title, + MessageBoxButtons.YesNo)) + return; + + // Gone, the scenery follows by the watch on its files, as it would after any other change. + if (!await Task.Run(() => sbt.Delete(scenery.Path))) + await MessageBox.Show(owner, string.Format(App.Loc["DeleteSbtFailed"], name), title, MessageBoxButtons.Ok); } private void ToggleFavorite_OnClick(object? sender, RoutedEventArgs e) diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 9bbfc85..2e18be6 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -69,6 +69,10 @@ Přidat do oblíbených Odebrat z oblíbených Otevřít složku + Smazat SBT + Smazat {0} ({1} MB)? Simulátor jej znovu sestaví ze souborů scenérie při jejím dalším načtení, které potrvá déle. + Soubor {0} zůstává: není z čeho jej znovu sestavit, chybí {1}. Bez něj by scenérie přišla o terén. + Soubor {0} nelze smazat. Možná jej používá simulátor, nebo je složka jen pro čtení. Volitelné prvky Otevřít složku s texturami Kopírovat název diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index db28d6a..819f111 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -69,6 +69,10 @@ Add to favourites Remove from favourites Open folder + Delete SBT + Delete {0} ({1} MB)? The simulator makes it again from the scenery files on its next load, which takes longer. + {0} stays: nothing is there to make it again, {1} is missing. Without it the scenery would lose its terrain. + Could not delete {0}. The simulator may be using it, or the folder is read-only. Optional elements Open texture folder Copy name diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index e65ecd9..8d0c08c 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -69,6 +69,10 @@ Hozzáadás a kedvencekhez Eltávolítás a kedvencek közül Mappa megnyitása + SBT törlése + Törlöd: {0} ({1} MB)? A szimulátor a színtér fájljaiból a következő betöltéskor újra elkészíti, ami tovább tart. + {0} megmarad: nincs miből újra elkészíteni, hiányzik: {1}. Nélküle a színtér elveszítené a terepet. + Nem sikerült törölni: {0}. Lehet, hogy a szimulátor használja, vagy a mappa csak olvasható. Opcionális elemek Textúramappa megnyitása Név másolása diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 5ab0d59..b3c9fd2 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -69,6 +69,10 @@ Dodaj do ulubionych Usuń z ulubionych Otwórz folder + Usuń SBT + Usunąć {0} ({1} MB)? Symulator zbuduje go od nowa z plików scenerii przy jej następnym wczytaniu, które potrwa dłużej. + Plik {0} zostaje: sceneria nie ma z czego go odbudować, brakuje {1}. Bez niego straciłaby teren. + Nie udało się usunąć {0}. Może używa go symulator albo folder jest tylko do odczytu. Elementy opcjonalne Otwórz folder tekstury Kopiuj nazwę diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index 6e499d3..3ee4aa4 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -69,6 +69,10 @@ Добавить в избранное Удалить из избранного Открыть папку + Удалить SBT + Удалить {0} ({1} МБ)? Симулятор заново соберёт его из файлов сценария при следующей загрузке, которая займёт больше времени. + Файл {0} остаётся: его не из чего собрать заново, нет {1}. Без него сценарий лишится рельефа. + Не удалось удалить {0}. Возможно, его использует симулятор или папка только для чтения. Дополнительные элементы Открыть папку с текстурами Копировать название From 943b855f20a97dccde24d009bfe43c8dad2c2b4a Mon Sep 17 00:00:00 2001 From: maj00r Date: Tue, 17 Nov 2026 14:55:04 +0100 Subject: [PATCH 2/7] feat(warehouse): the old starter's magazyn.ini joins the warehouse at every start The old starter read starter\magazyn.ini each time it opened and wrote it on every change; this one kept its warehouse apart and took the file in only from the list's menu, so a consist saved there never showed here. - At the start, ahead of the scenery list, the consists of magazyn.ini not taken in before join the warehouse. Each one taken is remembered in userpresets.json by its name and vehicles, so one removed here stays removed while the old starter keeps it as it was. - A consist changed there replaces the one here when that one is as an earlier start brought it; one of the same name made here stays, and the old one comes in beside it as "name (magazyn.ini)". - A warehouse file that cannot be read is left alone by the import. - The file is read as UTF-8 or code page 1250, whichever it is, by hand too. --- StarterNG.Tests/OldStarterWarehouseTests.cs | 132 ++++++++++++++++++ StarterNG/App.axaml.cs | 2 + StarterNG/Classes/PresetStore.cs | 142 ++++++++++++++++---- 3 files changed, 250 insertions(+), 26 deletions(-) create mode 100644 StarterNG.Tests/OldStarterWarehouseTests.cs diff --git a/StarterNG.Tests/OldStarterWarehouseTests.cs b/StarterNG.Tests/OldStarterWarehouseTests.cs new file mode 100644 index 0000000..240c36e --- /dev/null +++ b/StarterNG.Tests/OldStarterWarehouseTests.cs @@ -0,0 +1,132 @@ +using StarterNG.Classes; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +// The old starter's magazyn.ini taken in at a start, over the fake disk. +public class OldStarterWarehouseTests +{ + private const string PresetsPath = "/home/user/.config/MaSzyna/starter/userpresets.json"; + + // As the old starter writes it: CRLF, code page 1250, the scenery's path for a name. + private const string Magazyn = + "[TRAINSET0=baltyk/baltyk_km/mpj15120]\r\n" + + "00=node -1 0 EN57AKM-1682RA dynamic pkp\\en57akm_2013_v1 EN57AKM-1682ra akm_2013_ra_male_okna 0 headdriver 255 0 enddynamic\r\n" + + "01=node -1 0 EN57AKM-1682S dynamic pkp\\en57akm_2013_v1 EN57AKM-1682s akm_2013_s 0 nobody 255 0 enddynamic\r\n" + + "02=node -1 0 EN57AKM-1682RB dynamic pkp\\en57akm_2013_v1 EN57AKM-1682rb akm_2013_rb_male_okna 0 nobody 0 0 enddynamic\r\n"; + + private static (PresetFile Presets, InMemoryFileSystem Files) Rig() + { + var files = new InMemoryFileSystem(); + return (new PresetFile(files, TestLog.Over(files), PresetsPath), files); + } + + private static List Consist(string name, string vehicle) => + OldStarterWarehouse.Read($"[TRAINSET0={name}]\r\n00=node -1 0 {vehicle} dynamic pkp\\x {vehicle} x 0 headdriver 3 0 enddynamic\r\n"); + + [Fact] + public void A_consist_of_the_old_starter_reads_as_a_trainset_with_its_vehicles() + { + var consist = Assert.Single(OldStarterWarehouse.Read(Magazyn)); + + Assert.Equal("baltyk/baltyk_km/mpj15120", consist.Name); + Assert.StartsWith("trainset baltyk/baltyk_km/mpj15120 none 0 0\n", consist.Entry); + Assert.EndsWith("endtrainset\n", consist.Entry); + var vehicles = ConsistText.VehiclesFrom(consist.Entry); + Assert.NotNull(vehicles); + Assert.Equal(new[] { "EN57AKM-1682RA", "EN57AKM-1682S", "EN57AKM-1682RB" }, vehicles!.Select(v => v.Name)); + } + + [Fact] + public void A_consist_new_in_the_old_starter_joins_the_warehouse() + { + var (presets, _) = Rig(); + presets.Save("mine", "trainset mine"); + + int added = presets.TakeFromOldStarter(OldStarterWarehouse.Read(Magazyn)); + + Assert.Equal(1, added); + Assert.Equal(new[] { "baltyk/baltyk_km/mpj15120", "mine" }, presets.Presets().Select(p => p.Name)); + } + + [Fact] + public void A_consist_removed_here_does_not_come_back_at_the_next_start() + { + var (presets, _) = Rig(); + var found = OldStarterWarehouse.Read(Magazyn); + presets.TakeFromOldStarter(found); + presets.Delete("baltyk/baltyk_km/mpj15120"); + + int added = presets.TakeFromOldStarter(found); + + Assert.Equal(0, added); + Assert.Empty(presets.Presets()); + } + + [Fact] + public void Nothing_new_leaves_the_file_unwritten() + { + var (presets, files) = Rig(); + var found = OldStarterWarehouse.Read(Magazyn); + presets.TakeFromOldStarter(found); + string before = files.ReadAllText(PresetsPath); + files.WithFile(PresetsPath, before + " "); + + presets.TakeFromOldStarter(found); + + Assert.Equal(before + " ", files.ReadAllText(PresetsPath)); + } + + [Fact] + public void A_consist_imported_by_hand_before_is_not_taken_twice() + { + var (presets, _) = Rig(); + var found = OldStarterWarehouse.Read(Magazyn); + presets.Save(found[0].Name, found[0].Entry); + + int added = presets.TakeFromOldStarter(found); + + Assert.Equal(0, added); + Assert.Single(presets.Presets()); + } + + [Fact] + public void A_consist_of_the_same_name_made_here_stays_and_the_old_one_comes_in_beside_it() + { + var (presets, _) = Rig(); + presets.Save("osobowy", "trainset osobowy none 0 0\nendtrainset\n"); + + presets.TakeFromOldStarter(Consist("osobowy", "SM42")); + + var all = presets.Presets(); + Assert.Equal(new[] { "osobowy", "osobowy" + PresetFile.OldStarterSuffix }, all.Select(p => p.Name)); + Assert.Equal("trainset osobowy none 0 0\nendtrainset\n", all[0].Entry); + Assert.Contains("SM42", all[1].Entry); + } + + [Fact] + public void A_consist_changed_in_the_old_starter_and_untouched_here_is_replaced() + { + var (presets, _) = Rig(); + presets.TakeFromOldStarter(Consist("osobowy", "SM42")); + + presets.TakeFromOldStarter(Consist("osobowy", "SU45")); + + var only = Assert.Single(presets.Presets()); + Assert.Equal("osobowy", only.Name); + Assert.Contains("SU45", only.Entry); + } + + [Fact] + public void A_warehouse_file_that_cannot_be_read_is_left_as_it_is() + { + var (presets, files) = Rig(); + files.WithFile(PresetsPath, "{ cut"); + + int added = presets.TakeFromOldStarter(OldStarterWarehouse.Read(Magazyn)); + + Assert.Equal(0, added); + Assert.Equal("{ cut", files.ReadAllText(PresetsPath)); + Assert.False(files.FileExists(PresetsPath + ".unreadable")); + } +} diff --git a/StarterNG/App.axaml.cs b/StarterNG/App.axaml.cs index 86b9234..20b1b35 100644 --- a/StarterNG/App.axaml.cs +++ b/StarterNG/App.axaml.cs @@ -163,6 +163,8 @@ public partial class App : Avalonia.Application // Ahead of the sceneries, so the list knows which still have their .sbt. try { AppServices.Current.BinaryTerrain.CleanUpOnce(); } catch (Exception ex) { Diagnostics.Log("sbt cleanup", ex); } + // Before any window lists the warehouse; it catches what it meets itself. + PresetStore.TakeFromOldStarter(); AppServices.Current.Library.Load(progress); }).ContinueWith(load => { diff --git a/StarterNG/Classes/PresetStore.cs b/StarterNG/Classes/PresetStore.cs index 69b7e82..47a4bc8 100644 --- a/StarterNG/Classes/PresetStore.cs +++ b/StarterNG/Classes/PresetStore.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -28,6 +30,9 @@ public sealed class TrainsetPreset public sealed class PresetCollection { public List Presets { get; set; } = new(); + + /// The old starter's consists taken in at a start, by . + public List OldStarterSeen { get; set; } = new(); } public static class PresetStore @@ -81,33 +86,9 @@ public static class PresetStore int added = 0; try { - string text = File.ReadAllText(path, LegacyText.CodePage1250); - var section = Regex.Matches(text, - @"\[TRAINSET\d+\s*=\s*([^\]]*)\](.*?)(?=\[TRAINSET|\z)", - RegexOptions.IgnoreCase | RegexOptions.Singleline); - - foreach (Match m in section) + foreach (var consist in OldStarterWarehouse.Read(LegacyText.Decode(File.ReadAllBytes(path)))) { - string name = m.Groups[1].Value.Trim(); - if (name.Length == 0) name = $"import_{added + 1}"; - - var nodes = new List(); - foreach (Match line in Regex.Matches(m.Groups[2].Value, @"(?m)^\s*\d+\s*=\s*(.+)$")) - { - string body = line.Groups[1].Value.Trim(); - if (!body.Contains("enddynamic", StringComparison.OrdinalIgnoreCase)) - body += " enddynamic"; - nodes.Add(body); - } - if (nodes.Count == 0) continue; - - var sb = new StringBuilder(); - sb.Append("trainset ").Append(Sanitize(name)).Append(" none 0 0\n"); - foreach (string n in nodes) - sb.Append(n).Append('\n'); - sb.Append("endtrainset\n"); - - Save(name, sb.ToString()); + Save(consist.Name, consist.Entry); added++; } } @@ -118,6 +99,26 @@ public static class PresetStore return added; } + /// + /// At the start: what the old starter put in its warehouse since the last start + /// joins this one, as that starter showed its magazyn.ini each time it was opened. + /// + public static void TakeFromOldStarter() + { + string? path = FindMagazynPath(); + if (path is null) + return; + + try + { + Disk.TakeFromOldStarter(OldStarterWarehouse.Read(LegacyText.Decode(File.ReadAllBytes(path)))); + } + catch (Exception ex) + { + Infrastructure.Diagnostics.Log($"Import {path}", ex); + } + } + private static string? FindMagazynPath() { string cwd = Directory.GetCurrentDirectory(); @@ -139,6 +140,46 @@ public static class PresetStore var m = Regex.Match(p.Entry ?? "", @"^\s*trainset\s+\S+\s+(\S+)", RegexOptions.Multiline | RegexOptions.IgnoreCase); return m.Success ? m.Groups[1].Value : ""; } +} + +/// +/// The old starter's magazyn.ini: a [TRAINSETn=name] line for each consist, then +/// its vehicles as numbered "node … enddynamic" lines. +/// +public static class OldStarterWarehouse +{ + public static List Read(string text) + { + var consists = new List(); + var sections = Regex.Matches(text, + @"\[TRAINSET\d+\s*=\s*([^\]]*)\](.*?)(?=\[TRAINSET|\z)", + RegexOptions.IgnoreCase | RegexOptions.Singleline); + + foreach (Match m in sections) + { + string name = m.Groups[1].Value.Trim(); + if (name.Length == 0) name = $"import_{consists.Count + 1}"; + + var nodes = new List(); + foreach (Match line in Regex.Matches(m.Groups[2].Value, @"(?m)^\s*\d+\s*=\s*(.+)$")) + { + string body = line.Groups[1].Value.Trim(); + if (!body.Contains("enddynamic", StringComparison.OrdinalIgnoreCase)) + body += " enddynamic"; + nodes.Add(body); + } + if (nodes.Count == 0) continue; + + var sb = new StringBuilder(); + sb.Append("trainset ").Append(Sanitize(name)).Append(" none 0 0\n"); + foreach (string n in nodes) + sb.Append(n).Append('\n'); + sb.Append("endtrainset\n"); + + consists.Add(new TrainsetPreset { Name = name, Entry = sb.ToString() }); + } + return consists; + } private static string Sanitize(string name) => string.IsNullOrWhiteSpace(name) ? "preset" : name.Replace(' ', '_'); @@ -193,6 +234,55 @@ public sealed class PresetFile Persist(col, read); } + /// Where a consist of the old starter goes when one of its name with other vehicles is here. + public const string OldStarterSuffix = " (magazyn.ini)"; + + /// + /// Takes in the old starter's consists not taken at an earlier start, so one + /// removed here stays removed while the old starter keeps it as it was. One + /// whose name is here with other vehicles comes in beside it, unless what is + /// here is that consist as an earlier start brought it, untouched since. + /// + /// How many came in. + public int TakeFromOldStarter(IReadOnlyList found) + { + // A file that cannot be read is not replaced by an import nobody asked for. + if (found.Count == 0 || !TryRead(out var col)) + return 0; + + var seenBefore = new HashSet(col.OldStarterSeen, StringComparer.Ordinal); + var seen = new HashSet(seenBefore, StringComparer.Ordinal); + int added = 0; + foreach (var consist in found) + { + if (!seen.Add(Fingerprint(consist))) + continue; + + var here = col.Presets.Find(p => string.Equals(p.Name, consist.Name, StringComparison.OrdinalIgnoreCase)); + if (here is not null && here.Entry == consist.Entry) + continue; + + string name = here is null || seenBefore.Contains(Fingerprint(here)) + ? consist.Name + : consist.Name + OldStarterSuffix; + col.Presets.RemoveAll(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)); + col.Presets.Add(new TrainsetPreset { Name = name, Entry = consist.Entry }); + added++; + } + + if (seen.Count == seenBefore.Count) + return 0; + + col.OldStarterSeen = seen.Order(StringComparer.Ordinal).ToList(); + col.Presets.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + Persist(col, read: true); + return added; + } + + /// A consist by its name and vehicles, short enough to keep each one ever taken in. + public static string Fingerprint(TrainsetPreset preset) => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(preset.Name + "\n" + preset.Entry))); + /// The file's presets; false, with none, when there is a file but they cannot be had from it. private bool TryRead(out PresetCollection col) { From 97a2c2c75c3265a372ba699ab30e937161c839d6 Mon Sep 17 00:00:00 2001 From: maj00r Date: Tue, 17 Nov 2026 22:14:45 +0100 Subject: [PATCH 3/7] fix(sceneries): an .sbt in the way of terrain files that are there can go Any terrain directive kept the scenery's .sbt, as if it brought the terrain from elsewhere. The directive names either .sbt files, which nothing makes again, or terrain files (.txtf) with their binary copies (.btf). A scenery with the terrain files has no use for its own .sbt: the simulator never writes one for it, and an old one keeps the terrain files from being used. - An .sbt named by the directive still keeps the scenery's own. - A .txtf, or its .btf, on disk lets the scenery's .sbt go; with neither, the .sbt stays and the missing .txtf is given as the reason. --- StarterNG.Tests/BinaryTerrainFilesTests.cs | 40 +++++++++++++++++++ .../Sceneries/BinaryTerrainFiles.cs | 36 ++++++++++++++++- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/StarterNG.Tests/BinaryTerrainFilesTests.cs b/StarterNG.Tests/BinaryTerrainFilesTests.cs index 159d8d3..7f7e3ff 100644 --- a/StarterNG.Tests/BinaryTerrainFilesTests.cs +++ b/StarterNG.Tests/BinaryTerrainFilesTests.cs @@ -91,6 +91,46 @@ public class BinaryTerrainFilesTests Assert.Equal("td.sbt", Assert.Single(Build(files).CleanUpOnce(1)!.Kept).File); } + [Theory] + [InlineData("td/teren.txtf")] + [InlineData("td/Teren.btf")] + public void An_sbt_in_the_way_of_terrain_files_that_are_there_goes(string onDisk) + { + var files = new InMemoryFileSystem(caseSensitive: true) + .WithLegacyFile(Scenery("td.scn"), "terrain td/teren.txtf endterrain\nFirstInit\n") + .WithFile(Scenery(onDisk), "x") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Single(Build(files).CleanUpOnce(1)!.Deleted); + Assert.False(files.FileExists(Scenery("td.sbt"))); + } + + [Fact] + public void An_sbt_standing_in_for_a_missing_terrain_file_stays() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "terrain td/a.txtf td/b.txtf endterrain\nFirstInit\n") + .WithFile(Scenery("td/a.txtf"), "x") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Equal(("td.sbt", "td/b.txtf"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept)); + } + + [Fact] + public void An_sbt_named_beside_terrain_files_keeps_the_scenery_s_own() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "terrain td/a.txtf wspolny.sbt endterrain\nFirstInit\n") + .WithFile(Scenery("td/a.txtf"), "x") + .WithFile(Scenery("wspolny.sbt"), "EU07SBT2") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + Assert.Empty(cleanup.Deleted); + Assert.Contains(("td.sbt", "terrain wspolny.sbt"), cleanup.Kept); + } + [Fact] public void An_sbt_of_no_scenery_stays() { diff --git a/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs b/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs index 2036ba0..d24103e 100644 --- a/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs +++ b/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs @@ -105,10 +105,18 @@ public sealed class BinaryTerrainFiles string code = SceneryCode.Mask(text, out _); bool includeNext = false; + bool terrainDirective = false; for (var word = Word.Match(code); word.Success; word = word.NextMatch()) { string token = word.Value; - if (includeNext) + if (terrainDirective) + { + if (token.Equals("endterrain", StringComparison.OrdinalIgnoreCase)) + terrainDirective = false; + else if (TerrainFileMissing(token, names) is { } missing) + return missing; + } + else if (includeNext) { includeNext = false; bool terrain = SimulatorNames.Lower(token).Contains("_ter.scm"); @@ -123,12 +131,36 @@ public sealed class BinaryTerrainFiles else if (token.Equals("include", StringComparison.OrdinalIgnoreCase)) includeNext = true; else if (token.Equals("terrain", StringComparison.OrdinalIgnoreCase)) - return token; + terrainDirective = true; } return null; } + /// + /// One file named by a terrain directive. An .sbt named there holds the geometry + /// of the whole scenery and nothing makes it again, so the scenery's own goes + /// only without one. A terrain file (.txtf) has its geometry in itself or in its + /// binary copy (.btf) beside it: with either one there, the scenery's .sbt only + /// keeps that terrain from being used, and the simulator asks for it to go. + /// + private string? TerrainFileMissing(string token, CaseInsensitivePaths names) + { + string extension = Path.GetExtension(token); + if (extension.Equals(Extension, StringComparison.OrdinalIgnoreCase)) + return "terrain " + token; + + if (!extension.Equals(".txtf", StringComparison.OrdinalIgnoreCase) + && !extension.Equals(".btf", StringComparison.OrdinalIgnoreCase)) + return null; + + string stem = token[..^extension.Length]; + return names.Resolve(_paths.Scenery, stem + ".txtf") is null + && names.Resolve(_paths.Scenery, stem + ".btf") is null + ? stem + ".txtf" + : null; + } + /// Removes the scenery's .sbt; false when it has none or it could not go. public bool Delete(string sceneryPath) { From 7e249a7a9a5a4e7f7a2f2354b0196a02cd519d52 Mon Sep 17 00:00:00 2001 From: maj00r Date: Tue, 17 Nov 2026 22:14:45 +0100 Subject: [PATCH 4/7] fix(settings): a first start has nothing to save before the simulator starts With no eu07.ini of the player's own, starting the simulator asked to save changes nobody made. The UART tune box and the Vulkan device box went by TextChanged, which Avalonia raises later from the dispatcher: the text the page put there while loading came back as an edit once the window was shown. Both now go by their Text property, which changes at once and is passed over while the page loads; typing in them still counts. --- StarterNG.Tests/SettingsFirstStartTests.cs | 39 ++++++++++++++++++++++ StarterNG/Views/Settings.axaml.cs | 21 +++++++++--- 2 files changed, 55 insertions(+), 5 deletions(-) create mode 100644 StarterNG.Tests/SettingsFirstStartTests.cs diff --git a/StarterNG.Tests/SettingsFirstStartTests.cs b/StarterNG.Tests/SettingsFirstStartTests.cs new file mode 100644 index 0000000..7af3962 --- /dev/null +++ b/StarterNG.Tests/SettingsFirstStartTests.cs @@ -0,0 +1,39 @@ +using StarterNG.Application; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +/// The settings page on a start with no eu07.ini of the player's own yet. +[Collection(AvaloniaControls.Name)] +public class SettingsFirstStartTests +{ + [Fact] + public void A_first_start_has_nothing_to_save_before_the_simulator_starts() + { + var files = new InMemoryFileSystem(); + files.WriteAllText(TestInstallation.At("eu07.ini"), "width 1920\nheight 1080\nendconfig\n"); + var installation = new TestInstallation(files); + installation.Environment.AsWindows(); + var services = AppServices.Initialize(installation.Paths, installation.Files, installation.Clock, + installation.Environment); + services.SettingsStore.Load(); + services.SettingsStore.StartAtHighWithoutOwnSettings(); + + HeadlessDrawing.Ensure(); + // The page reads the graphics cards away from the window and comes back to it, as in the application. + var context = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(new Avalonia.Threading.AvaloniaSynchronizationContext()); + Avalonia.Controls.Window? window = null; + try + { + var page = new StarterNG.Views.Settings(); + window = Controls.Show(page, 1600, 1000, themed: true); + Assert.False(page.HasUnsavedChanges); + } + finally + { + window?.Close(); + SynchronizationContext.SetSynchronizationContext(context); + } + } +} diff --git a/StarterNG/Views/Settings.axaml.cs b/StarterNG/Views/Settings.axaml.cs index 6dce6ff..420918f 100644 --- a/StarterNG/Views/Settings.axaml.cs +++ b/StarterNG/Views/Settings.axaml.cs @@ -966,11 +966,11 @@ public partial class Settings : UserControl, ISettingsCapture OnControlChanged(); }; UartEnabledCb.IsCheckedChanged += (_, _) => ValidateUart(); - UartTuneBox.TextChanged += (_, _) => + OnTextEdited(UartTuneBox, () => { ValidateUart(); OnControlChanged(); - }; + }); App.Loc.LanguageChanged += UpdateUartTexts; UpdateUartTexts(); } @@ -1511,7 +1511,7 @@ public partial class Settings : UserControl, ISettingsCapture nud.ValueChanged += (_, _) => OnControlChanged(); break; case TextBox box when ReferenceEquals(box, VulkanDeviceTb): - box.TextChanged += (_, _) => OnControlChanged(); + OnTextEdited(box, OnControlChanged); break; } } @@ -1521,6 +1521,18 @@ public partial class Settings : UserControl, ISettingsCapture toggle.IsCheckedChanged += (_, _) => OnControlChanged(); } + /// + /// The text as it changes, not TextChanged: that one comes later, from the + /// dispatcher, so the text the page itself put there while loading came back + /// as an edit once the window was shown - the first start asked to save. + /// + private static void OnTextEdited(TextBox box, Action edited) => + box.PropertyChanged += (_, e) => + { + if (e.Property == TextBox.TextProperty) + edited(); + }; + private void OnControlChanged() { MarkDirty(); @@ -1533,8 +1545,7 @@ public partial class Settings : UserControl, ISettingsCapture if (_loading || _dirty) return; - _dirty = true; - UpdateSaveState(); + _dirty = true; UpdateSaveState(); } /// Edits on the page, or of the keys, not saved yet: what "Niezapisane zmiany" tells. From 4b3ee43e4ab45e480b2d3a2e87f051a23a60b738 Mon Sep 17 00:00:00 2001 From: maj00r Date: Wed, 18 Nov 2026 13:04:13 +0100 Subject: [PATCH 5/7] build: the starter, the black box and the tests move to .NET 10 .NET 9 was a short-term release and its support has ended; .NET 10 is the long-term one. Avalonia 12 already ships a build for net10.0, the other packages run on it as they are. CI sets up the 10.0 SDK, and Rider's publish configurations point at the new output folder. --- .github/workflows/dotnet.yml | 8 ++++---- .github/workflows/sonar.yml | 4 ++-- Eu07.BlackBox.Viewer/Eu07.BlackBox.Viewer.csproj | 2 +- Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj | 2 +- Eu07.BlackBox/Eu07.BlackBox.csproj | 2 +- StarterNG.Tests/StarterNG.Tests.csproj | 2 +- StarterNG/StarterNG.csproj | 2 +- linuix.run/StarterNG (linux64).run.xml | 2 +- windows.run/StarterNG (win64).run.xml | 2 +- 9 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index fb83e2f..6c798ed 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -51,10 +51,10 @@ jobs: with: persist-credentials: false - - name: Setup .NET 9 + - name: Setup .NET 10 uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: 9.0.x + dotnet-version: 10.0.x - name: Test run: > @@ -141,10 +141,10 @@ jobs: with: persist-credentials: false - - name: Setup .NET 9 + - name: Setup .NET 10 uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: 9.0.x + dotnet-version: 10.0.x # NativeAOT on Linux needs a native compiler/linker toolchain. - name: Install NativeAOT dependencies diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index eb64e8a..1061e9c 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -61,10 +61,10 @@ jobs: fetch-depth: 0 persist-credentials: false - - name: Setup .NET 9 + - name: Setup .NET 10 uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: 9.0.x + dotnet-version: 10.0.x - name: Restore tools run: dotnet tool restore diff --git a/Eu07.BlackBox.Viewer/Eu07.BlackBox.Viewer.csproj b/Eu07.BlackBox.Viewer/Eu07.BlackBox.Viewer.csproj index 925103a..01f0782 100644 --- a/Eu07.BlackBox.Viewer/Eu07.BlackBox.Viewer.csproj +++ b/Eu07.BlackBox.Viewer/Eu07.BlackBox.Viewer.csproj @@ -3,7 +3,7 @@ command line, or one picked. --> WinExe - net9.0 + net10.0 enable true true diff --git a/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj b/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj index 9f92822..689e444 100644 --- a/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj +++ b/Eu07.BlackBox.Views/Eu07.BlackBox.Views.csproj @@ -3,7 +3,7 @@ only, no XAML loaded at run time, so it goes through NativeAOT and trimming in the starter and in the viewer alike. --> - net9.0 + net10.0 enable true true diff --git a/Eu07.BlackBox/Eu07.BlackBox.csproj b/Eu07.BlackBox/Eu07.BlackBox.csproj index 9f84149..31ec078 100644 --- a/Eu07.BlackBox/Eu07.BlackBox.csproj +++ b/Eu07.BlackBox/Eu07.BlackBox.csproj @@ -3,7 +3,7 @@ base library: the starter, the viewer and any other program can use it, and it goes through NativeAOT and trimming as they do. --> - net9.0 + net10.0 enable true true diff --git a/StarterNG.Tests/StarterNG.Tests.csproj b/StarterNG.Tests/StarterNG.Tests.csproj index a0ca4c9..e2b7a32 100644 --- a/StarterNG.Tests/StarterNG.Tests.csproj +++ b/StarterNG.Tests/StarterNG.Tests.csproj @@ -1,7 +1,7 @@  - net9.0 + net10.0 enable enable false diff --git a/StarterNG/StarterNG.csproj b/StarterNG/StarterNG.csproj index ca073c5..aeb91b0 100644 --- a/StarterNG/StarterNG.csproj +++ b/StarterNG/StarterNG.csproj @@ -4,7 +4,7 @@ true true true - net9.0 + net10.0 enable true app.manifest diff --git a/linuix.run/StarterNG (linux64).run.xml b/linuix.run/StarterNG (linux64).run.xml index ebe9f91..1caeeb1 100644 --- a/linuix.run/StarterNG (linux64).run.xml +++ b/linuix.run/StarterNG (linux64).run.xml @@ -1,6 +1,6 @@ - + diff --git a/windows.run/StarterNG (win64).run.xml b/windows.run/StarterNG (win64).run.xml index 541d912..666b5e6 100644 --- a/windows.run/StarterNG (win64).run.xml +++ b/windows.run/StarterNG (win64).run.xml @@ -1,6 +1,6 @@ - + From de4eb99ea14bd6894c1416cac639660da131d5b5 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 22 Nov 2026 13:00:10 +0100 Subject: [PATCH 6/7] docs(readme): a native build needs the .NET 10 SDK --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d333a83..6f53f0a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ needed on the target machine. The commands below are the same ones CI runs, see Requirements: -- .NET SDK 9 +- .NET SDK 10 - Linux: a native toolchain and zlib headers — `sudo apt install clang zlib1g-dev` (Debian/Ubuntu) or `sudo dnf install clang zlib-devel` (Fedora) - Windows: the Visual Studio C++ build tools (Desktop development with C++) From 900161a6c4901e3b64c231709100cce72fdd6a43 Mon Sep 17 00:00:00 2001 From: maj00r Date: Sun, 22 Nov 2026 15:30:51 +0100 Subject: [PATCH 7/7] fix(sceneries): an .sbt goes only when every scenery reading it can do without With an .sbt there the simulator passes over the triangles and lines of every file of the scenery, so a scenery file (.scm, .scn) that is gone keeps the .sbt whatever its name, not only one named *_ter.scm. A small terrain file is read too: some only list the files that hold the terrain. Node templates (.inc) still do not count. A word reading "terrain" outside a directive - the name of a node, of a texture - no longer hides the includes after it. An .sbt is judged by all the sceneries reading it: the one it is named after, that one with a $ ahead of its name, and any other naming it in a terrain directive. What such a scenery lacks comes with its name. Each file is read once for a cleanup, however many sceneries include it, and only around the words that matter: on an installation of 180 sceneries the cleanup at the first start took minutes and takes seconds. --- StarterNG.Tests/BinaryTerrainFilesTests.cs | 207 +++++++++++ .../Sceneries/BinaryTerrainFiles.cs | 351 +++++++++++++----- 2 files changed, 475 insertions(+), 83 deletions(-) diff --git a/StarterNG.Tests/BinaryTerrainFilesTests.cs b/StarterNG.Tests/BinaryTerrainFilesTests.cs index 7f7e3ff..71cea32 100644 --- a/StarterNG.Tests/BinaryTerrainFilesTests.cs +++ b/StarterNG.Tests/BinaryTerrainFilesTests.cs @@ -1,3 +1,5 @@ +using System.Reflection; +using StarterNG.Application.Abstractions; using StarterNG.Infrastructure.Adapters; using StarterNG.Infrastructure.Sceneries; using StarterNG.Tests.Fakes; @@ -194,4 +196,209 @@ public class BinaryTerrainFilesTests Assert.True(sbt.Delete(Scenery("Kato.scn"))); Assert.Null(sbt.Of(Scenery("Kato.scn"))); } + + // With an .sbt there the simulator passes over the triangles and lines of every file, not + // only of those named *_ter.scm: a scenery file that is gone took its shapes with it. + [Theory] + [InlineData("td/teren.scm", true)] + [InlineData("td/teren.scm", false)] + [InlineData("TD\\Czesc.SCN", false)] + public void A_missing_scenery_file_keeps_the_sbt_whatever_its_name(string include, bool present) + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), $"include td/base.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("td/base.scm"), $"include {include} 1 2 end\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + if (present) + files.WithLegacyFile(Scenery(include), "node -1 0 none triangles grass 0 0 0 endtri\n"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + if (present) + Assert.Equal("td.sbt", Assert.Single(cleanup.Deleted)); + else + Assert.Equal(("td.sbt", include), Assert.Single(cleanup.Kept)); + Assert.Equal(present, !files.FileExists(Scenery("td.sbt"))); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_terrain_file_that_only_lists_others_is_read_for_them(bool present) + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "include td/citygml_ter.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("td/citygml_ter.scm"), "include td/citygml/n-34.scm end\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + if (present) + files.WithFile(Scenery("td/citygml/n-34.scm"), "node"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + Assert.Equal(present, cleanup.Deleted.Count == 1); + if (!present) + Assert.Equal(("td.sbt", "td/citygml/n-34.scm"), Assert.Single(cleanup.Kept)); + } + + [Fact] + public void A_large_terrain_file_is_not_opened() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "include td/td_ter.scm end\nFirstInit\n") + .WithFile(Scenery("td/td_ter.scm"), new string(' ', 1024 * 1024) + "include td/gone.scm end\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Single(Build(files).CleanUpOnce(1)!.Deleted); + } + + // "terrain" starts a directive only where the simulator looks for one. As the name of a + // node or of a texture it starts nothing, and the includes after it count as any other. + [Theory] + [InlineData("node -1 0 terrain triangles grass 0 0 0 endtri")] + [InlineData("node -1 0 none triangles terrain 0 0 0 endtri")] + public void A_word_reading_terrain_hides_no_include_after_it(string node) + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), $"{node}\ninclude td/gone_ter.scm end\ninclude td/more.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("td/more.scm"), "include td/gone.scm end\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Equal(("td.sbt", "td/gone_ter.scm"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept)); + + files.WithFile(Scenery("td/gone_ter.scm"), "node"); + + var again = Build(files).CleanUpOnce(2)!; + + Assert.Equal(("td.sbt", "td/gone.scm"), Assert.Single(again.Kept)); + } + + [Fact] + public void A_word_reading_terrain_alone_does_not_keep_the_sbt() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), + "node -1 0 terrain triangles grass 0 0 0 endtri\ninclude td/td_ter.scm end\nFirstInit\n") + .WithFile(Scenery("td/td_ter.scm"), "node") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Single(Build(files).CleanUpOnce(1)!.Deleted); + } + + [Fact] + public void A_terrain_directive_is_still_read_after_a_word_reading_terrain() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), + "node -1 0 terrain triangles grass 0 0 0 endtri\nterrain td/a.txtf endterrain\nFirstInit\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Equal(("td.sbt", "td/a.txtf"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept)); + } + + // An .sbt serves every scenery naming it in a terrain directive, not only the one it is + // named after. With it gone such a scenery is read from its own text, until the simulator + // writes the file again on a load of the scenery it belongs to. + [Theory] + [InlineData("wspolny.sbt")] + [InlineData("Wspolny.SBT")] + [InlineData("$wspolny.sbt")] + public void An_sbt_another_scenery_cannot_do_without_stays(string named) + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("wspolny.scn"), "include wspolny/wspolny_ter.scm end\nFirstInit\n") + .WithFile(Scenery("wspolny/wspolny_ter.scm"), "node") + .WithFile(Scenery("wspolny.sbt"), "EU07SBT2") + .WithLegacyFile(Scenery("nocny.scn"), $"include nocny/base.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("nocny/base.scm"), $"terrain {named} endterrain\ninclude nmt/nmt100_ter.scm end\n"); + var sbt = Build(files); + + Assert.Equal("nmt/nmt100_ter.scm (nocny.scn)", sbt.MissingOriginal(Scenery("wspolny.scn"))); + + var cleanup = sbt.CleanUpOnce(1)!; + + Assert.Empty(cleanup.Deleted); + Assert.Equal(("wspolny.sbt", "nmt/nmt100_ter.scm (nocny.scn)"), Assert.Single(cleanup.Kept)); + Assert.True(files.FileExists(Scenery("wspolny.sbt"))); + } + + [Fact] + public void An_sbt_another_scenery_can_do_without_goes() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("wspolny.scn"), "include wspolny/wspolny_ter.scm end\nFirstInit\n") + .WithFile(Scenery("wspolny/wspolny_ter.scm"), "node") + .WithFile(Scenery("wspolny.sbt"), "EU07SBT2") + .WithLegacyFile(Scenery("nocny.scn"), + "terrain wspolny.sbt endterrain\ninclude wspolny/wspolny_ter.scm end\nFirstInit\n"); + var sbt = Build(files); + + Assert.Null(sbt.MissingOriginal(Scenery("wspolny.scn"))); + Assert.Equal("wspolny.sbt", Assert.Single(sbt.CleanUpOnce(1)!.Deleted)); + } + + [Fact] + public void An_sbt_of_the_same_name_in_another_folder_is_another_file() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("teren.scn"), "FirstInit\n") + .WithFile(Scenery("teren.sbt"), "EU07SBT2") + .WithFile(Scenery("l107/teren.sbt"), "EU07SBT2") + .WithLegacyFile(Scenery("lupkow.scn"), + "terrain l107/teren.sbt endterrain\ninclude nmt/nmt100_ter.scm end\nFirstInit\n"); + + var cleanup = Build(files).CleanUpOnce(1)!; + + Assert.Equal("teren.sbt", Assert.Single(cleanup.Deleted)); + Assert.True(files.FileExists(Scenery("l107/teren.sbt"))); + } + + // The simulator drops the $ a scenery editor puts ahead of the name of a changed scenery, + // and reads and writes the .sbt of the one it was made from. + [Fact] + public void An_sbt_also_serves_the_scenery_named_with_a_dollar_ahead() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("td.scn"), "FirstInit\n") + .WithLegacyFile(Scenery("$td.scn"), "include td/nowy_ter.scm end\nFirstInit\n") + .WithFile(Scenery("td.sbt"), "EU07SBT2"); + + Assert.Equal(("td.sbt", "td/nowy_ter.scm ($td.scn)"), Assert.Single(Build(files).CleanUpOnce(1)!.Kept)); + + files.WithFile(Scenery("td/nowy_ter.scm"), "node"); + + Assert.Single(Build(files).CleanUpOnce(2)!.Deleted); + } + + [Fact] + public void A_file_many_sceneries_include_is_read_once() + { + var files = new InMemoryFileSystem() + .WithLegacyFile(Scenery("dzien.scn"), "include td/base.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("noc.scn"), "include td/base.scm end\nFirstInit\n") + .WithLegacyFile(Scenery("td/base.scm"), "include td/td_ter.scm end\n") + .WithFile(Scenery("td/td_ter.scm"), "node") + .WithFile(Scenery("dzien.sbt"), "EU07SBT2") + .WithFile(Scenery("noc.sbt"), "EU07SBT2"); + var counted = DispatchProxy.Create(); + var counter = (ReadCounter)(object)counted; + counter.Files = files; + var sbt = new BinaryTerrainFiles(counted, new GamePaths("game"), TestLog.Over(files), Record); + + Assert.Equal(2, sbt.CleanUpOnce(1)!.Deleted.Count); + Assert.Single(counter.Read, path => Path.GetFileName(path) == "base.scm"); + } + + public class ReadCounter : DispatchProxy + { + public IFileSystem Files { get; set; } = null!; + + public List Read { get; } = new(); + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + if (targetMethod!.Name == nameof(IFileSystem.ReadAllBytes)) + Read.Add((string)args![0]!); + return targetMethod.Invoke(Files, args); + } + } } diff --git a/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs b/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs index d24103e..63deb87 100644 --- a/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs +++ b/StarterNG/Infrastructure/Sceneries/BinaryTerrainFiles.cs @@ -1,8 +1,8 @@ using System; +using System.Buffers; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using StarterNG.Application.Abstractions; using StarterNG.Domain; using StarterNG.Domain.Sceneries; @@ -13,13 +13,14 @@ namespace StarterNG.Infrastructure.Sceneries; /// /// The sceneries' binary terrain files (.sbt): the simulator writes one beside a /// scenery on its first load and from then on takes the terrain from it, passing -/// the scenery's terrain includes (*_ter.scm) over. It never asks whether -/// the text changed since, so a file made by an older simulator, or before the -/// scenery was updated, keeps showing what was there then. +/// the scenery's terrain includes (*_ter.scm) over, and the triangles and +/// lines of its other files with them. It never asks whether the text changed +/// since, so a file made by an older simulator, or before the scenery was updated, +/// keeps showing what was there then. /// -/// A file goes only when the scenery's text still holds what it was made of: some -/// sceneries come with the .sbt in place of their terrain includes, and without it -/// they would have no terrain at all. +/// A file goes only when the text of every scenery reading it still holds what it +/// was made of: some sceneries come with the .sbt in place of their terrain +/// includes, and without it they would have no terrain at all. /// /// public sealed class BinaryTerrainFiles @@ -33,8 +34,9 @@ public sealed class BinaryTerrainFiles private const string Extension = ".sbt"; - // The simulator splits its text into words at spaces, tabs, line ends and semicolons. - private static readonly Regex Word = new(@"[^\s;]+", RegexOptions.CultureInvariant); + // The only words that tell what comes after them; "endterrain" is found by the second. + private static readonly SearchValues Keywords = + SearchValues.Create(["include", "terrain"], StringComparison.OrdinalIgnoreCase); private readonly IFileSystem _files; private readonly IGamePaths _paths; @@ -60,103 +62,277 @@ public sealed class BinaryTerrainFiles /// /// What the simulator would miss to make the scenery's .sbt again - the first - /// terrain file its text names and the installation lacks, or the terrain directive - /// that brings terrain from elsewhere; null when the text holds it all. + /// file with geometry its text names and the installation lacks, or the terrain + /// directive that brings terrain from elsewhere; null when the text holds it all. + /// Another scenery reading the same .sbt counts too: what that one lacks comes + /// with its name. /// public string? MissingOriginal(string sceneryPath) { + string name = Path.GetFileName(sceneryPath); try { - var names = new CaseInsensitivePaths(_files, keepListings: true); - string? own = names.Resolve(_paths.Scenery, Path.GetFileName(sceneryPath)); - if (own is null) - return Path.GetFileName(sceneryPath); - - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var pending = new Stack(); - pending.Push(own); - while (pending.Count > 0) - { - string file = pending.Pop(); - if (!seen.Add(file)) - continue; - - if (Scan(file, names, pending) is { } missing) - return missing; - } - - return null; + var texts = new Texts(this); + return texts.Resolve(name) is null + ? name + : Unmakeable(Path.GetFileNameWithoutExtension(name) + Extension, texts); } catch (Exception ex) { - _log.Log($"sbt/{Path.GetFileName(sceneryPath)}", ex); - return Path.GetFileName(sceneryPath); + _log.Log($"sbt/{name}", ex); + return name; } } /// - /// Reads one file of the scenery for its includes: the terrain ones have to be - /// there, the others are read in turn. Terrain files are not opened - they are the - /// largest of all and include nothing. + /// What keeps an .sbt of the scenery folder from being made again as it is, for + /// every scenery reading it: the one it is named after, which is where the + /// simulator writes it, the same one with the $ a scenery editor puts + /// ahead of the name, which the simulator drops, and any other naming it in a + /// terrain directive. Null when all of them can do without it. /// - private string? Scan(string file, CaseInsensitivePaths names, Stack pending) + private string? Unmakeable(string sbt, Texts texts) { - string text = LegacyText.Decode(_files.ReadAllBytes(Path.Combine(_paths.Scenery, file))); - string code = SceneryCode.Mask(text, out _); + string stem = Path.GetFileNameWithoutExtension(sbt); + var sceneries = texts.Sceneries(); - bool includeNext = false; - bool terrainDirective = false; - for (var word = Word.Match(code); word.Success; word = word.NextMatch()) + // The scenery named as the file goes first: what it lacks is told without its name. + var owners = sceneries.Where(scenery => SameName(Stem(scenery), stem)).ToList(); + owners.AddRange(sceneries.Where(scenery => !SameName(Stem(scenery), stem) + && SameName(Stem(scenery).TrimStart('$'), stem))); + if (owners.Count == 0) + return stem + ".scn"; + + foreach (string owner in owners) { - string token = word.Value; - if (terrainDirective) - { - if (token.Equals("endterrain", StringComparison.OrdinalIgnoreCase)) - terrainDirective = false; - else if (TerrainFileMissing(token, names) is { } missing) - return missing; - } - else if (includeNext) - { - includeNext = false; - bool terrain = SimulatorNames.Lower(token).Contains("_ter.scm"); - string? found = names.Resolve(_paths.Scenery, token); - if (found is null && terrain) - return token; - // Any other file the simulator reads from the text, .sbt or not: missing, - // it is missing either way, and the .sbt made again lacks nothing. - if (found is not null && !terrain) - pending.Push(found); - } - else if (token.Equals("include", StringComparison.OrdinalIgnoreCase)) - includeNext = true; - else if (token.Equals("terrain", StringComparison.OrdinalIgnoreCase)) - terrainDirective = true; + var text = texts.Of(owner); + string? missing = text.Missing + ?? (text.BinaryTerrain.Count > 0 ? "terrain " + text.BinaryTerrain[0] : null); + if (missing is not null) + return SameName(Stem(owner), stem) ? missing : $"{missing} ({owner})"; + } + + // A scenery naming the file in a terrain directive takes its geometry from it. With the + // file gone the simulator reads that scenery's own text, which then has to hold it all. + foreach (string other in sceneries.Except(owners)) + { + var text = texts.Of(other); + if (text.Missing is { } missing && text.BinaryTerrain.Any(named => Names(named, stem))) + return $"{missing} ({other})"; } return null; } + private static string Stem(string file) => Path.GetFileNameWithoutExtension(file); + + private static bool SameName(string one, string other) => + one.Equals(other, StringComparison.OrdinalIgnoreCase); + /// - /// One file named by a terrain directive. An .sbt named there holds the geometry - /// of the whole scenery and nothing makes it again, so the scenery's own goes - /// only without one. A terrain file (.txtf) has its geometry in itself or in its - /// binary copy (.btf) beside it: with either one there, the scenery's .sbt only - /// keeps that terrain from being used, and the simulator asks for it to go. + /// Whether a terrain directive's word names the .sbt of the scenery folder with this + /// name, the way the simulator reads it: the $ ahead dropped, the file looked + /// for under the scenery folder. /// - private string? TerrainFileMissing(string token, CaseInsensitivePaths names) + private static bool Names(string word, string stem) { - string extension = Path.GetExtension(token); - if (extension.Equals(Extension, StringComparison.OrdinalIgnoreCase)) - return "terrain " + token; + string name = word.Replace('\\', '/').TrimStart('$').TrimStart('/'); + return !name.Contains('/') && SameName(Stem(name), stem); + } - if (!extension.Equals(".txtf", StringComparison.OrdinalIgnoreCase) - && !extension.Equals(".btf", StringComparison.OrdinalIgnoreCase)) - return null; + /// + /// The scenery files read for one question, each of them once however many + /// sceneries include it: most of an installation's sceneries share their files. + /// + private sealed class Texts + { + private readonly BinaryTerrainFiles _owner; + private readonly CaseInsensitivePaths _names; + private readonly Dictionary _resolved = new(StringComparer.Ordinal); + private readonly Dictionary _files; + private readonly Dictionary _texts; + private List? _sceneries; - string stem = token[..^extension.Length]; - return names.Resolve(_paths.Scenery, stem + ".txtf") is null - && names.Resolve(_paths.Scenery, stem + ".btf") is null + public Texts(BinaryTerrainFiles owner) + { + _owner = owner; + _names = new CaseInsensitivePaths(owner._files, keepListings: true); + var comparer = owner._files.IgnoresCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + _files = new Dictionary(comparer); + _texts = new Dictionary(comparer); + } + + /// The file named so under the scenery folder as it is on disk; null when there is none. + public string? Resolve(string name) + { + if (!_resolved.TryGetValue(name, out string? found)) + _resolved[name] = found = _names.Resolve(_owner._paths.Scenery, name); + return found; + } + + /// The sceneries of the installation, by their file names. + public IReadOnlyList Sceneries() => + _sceneries ??= _owner._files.GetFiles(_owner._paths.Scenery) + .Where(file => Path.GetExtension(file).Equals(".scn", StringComparison.OrdinalIgnoreCase)) + .Select(file => Path.GetFileName(file)) + .OrderBy(file => file, StringComparer.Ordinal) + .ToList(); + + /// The whole text of a scenery, the files it includes read in turn. + public SceneryText Of(string scenery) + { + if (_texts.TryGetValue(scenery, out var known)) + return known; + + string? missing = null; + var binaryTerrain = new List(); + try + { + var seen = new HashSet(_files.Comparer); + var pending = new Stack(); + pending.Push(scenery); + while (pending.Count > 0) + { + string file = pending.Pop(); + if (!seen.Add(file)) + continue; + + if (!_files.TryGetValue(file, out var text)) + _files[file] = text = _owner.Scan(file, this); + missing ??= text.Missing; + binaryTerrain.AddRange(text.BinaryTerrain); + foreach (string include in text.Includes) + pending.Push(include); + } + } + catch (Exception ex) + { + // Not read to its end, nothing tells what it would take to make again. + _owner._log.Log($"sbt/{scenery}", ex); + missing ??= scenery; + } + + return _texts[scenery] = new SceneryText(missing, binaryTerrain); + } + } + + /// The first file with geometry named there that the installation lacks. + /// The files it includes that are to be read in turn. + /// The .sbt files its terrain directives name. + private sealed record FileText(string? Missing, IReadOnlyList Includes, IReadOnlyList BinaryTerrain); + + /// The first file with geometry its text names that the installation lacks. + /// The .sbt files its terrain directives name. + private sealed record SceneryText(string? Missing, IReadOnlyList BinaryTerrain); + + // A terrain file larger than this is geometry and is left unopened - they are the largest + // files of all. A smaller one may be a list of the files that hold it. + private const long LargestTerrainFileRead = 1024 * 1024; + + /// + /// Reads one file of the scenery for the files it names. With an .sbt there the + /// simulator passes over every triangle and line of the text, in any file, so + /// each scenery file included has to be there for the .sbt to be made again: + /// the terrain ones (*_ter.scm) and any other .scm or .scn. The node + /// templates (.inc) do not count: a scenery naming one that is not there is + /// common, and none comes with an .sbt in its place. + /// + private FileText Scan(string file, Texts texts) + { + string text = LegacyText.Decode(_files.ReadAllBytes(Path.Combine(_paths.Scenery, file))); + string code = SceneryCode.Mask(text, out _); + + string? missing = null; + var includes = new List(); + var binaryTerrain = new List(); + bool includeNext = false; + bool terrainDirective = false; + int at = 0; + while (true) + { + if (!includeNext && !terrainDirective) + { + // Nothing is asked of the words up to the next one that may be a keyword, + // and a scenery file is mostly numbers. + int hit = code.AsSpan(at).IndexOfAny(Keywords); + if (hit < 0) + break; + for (at += hit; at > 0 && !Separates(code[at - 1]); at--) { } + } + + if (!NextWord(code, ref at, out var token)) + break; + + if (includeNext) + { + includeNext = false; + string name = token.ToString(); + bool terrain = SimulatorNames.Lower(name).Contains("_ter.scm"); + string? found = texts.Resolve(name); + if (found is null) + { + if (terrain || IsSceneryFile(name)) + missing ??= name; + } + else if (!terrain + || _files.GetFileSize(Path.Combine(_paths.Scenery, found)) <= LargestTerrainFileRead) + includes.Add(found); + } + // An include is one wherever it stands, and a word that only reads as the start of + // a terrain directive - the name of a node, of a texture - must not hide those after it. + else if (token.Equals("include", StringComparison.OrdinalIgnoreCase)) + includeNext = true; + else if (token.Equals("terrain", StringComparison.OrdinalIgnoreCase)) + terrainDirective = true; + else if (token.Equals("endterrain", StringComparison.OrdinalIgnoreCase)) + terrainDirective = false; + else if (terrainDirective) + { + var extension = Path.GetExtension(token); + if (extension.Equals(Extension, StringComparison.OrdinalIgnoreCase)) + binaryTerrain.Add(token.ToString()); + else if (extension.Equals(".txtf", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".btf", StringComparison.OrdinalIgnoreCase)) + missing ??= TerrainFileMissing(token.ToString(), texts); + } + } + + return new FileText(missing, includes, binaryTerrain); + } + + // The simulator splits its text into words at spaces, tabs, line ends and semicolons. + private static bool Separates(char c) => c == ';' || char.IsWhiteSpace(c); + + private static bool NextWord(string code, ref int at, out ReadOnlySpan word) + { + while (at < code.Length && Separates(code[at])) + at++; + int start = at; + while (at < code.Length && !Separates(code[at])) + at++; + word = code.AsSpan(start, at - start); + return at > start; + } + + private static bool IsSceneryFile(string name) + { + string extension = Path.GetExtension(name); + return extension.Equals(".scm", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".scn", StringComparison.OrdinalIgnoreCase); + } + + /// + /// A terrain file (.txtf) named by a terrain directive has its geometry in itself + /// or in its binary copy (.btf) beside it: with either one there, the scenery's + /// .sbt only keeps that terrain from being used, and the simulator asks for it + /// to go. An .sbt named there is another matter: it holds the geometry of the + /// whole scenery and nothing makes it again, so the scenery's own goes only + /// without one. + /// + private static string? TerrainFileMissing(string token, Texts texts) + { + string stem = token[..^Path.GetExtension(token).Length]; + return texts.Resolve(stem + ".txtf") is null && texts.Resolve(stem + ".btf") is null ? stem + ".txtf" : null; } @@ -198,14 +374,23 @@ public sealed class BinaryTerrainFiles var deleted = new List(); var kept = new List<(string File, string Reason)>(); var failed = new List(); - var names = new CaseInsensitivePaths(_files); + var texts = new Texts(this); foreach (string sbt in _files.GetFiles(_paths.Scenery) .Where(f => Path.GetExtension(f).Equals(Extension, StringComparison.OrdinalIgnoreCase))) { string name = Path.GetFileName(sbt); - string? scenery = names.Resolve(_paths.Scenery, Path.GetFileNameWithoutExtension(sbt) + ".scn"); - string? missing = scenery is null ? Path.GetFileNameWithoutExtension(sbt) + ".scn" : MissingOriginal(scenery); + string? missing; + try + { + missing = Unmakeable(name, texts); + } + catch (Exception ex) + { + _log.Log($"sbt/{name}", ex); + missing = Path.GetFileNameWithoutExtension(name) + ".scn"; + } + if (missing is not null) { kept.Add((name, missing));