Compare commits

..

23 Commits

Author SHA1 Message Date
maj00r dc1f43d385 fix: on Windows the processor draws the starter's windows
Every way of the graphics card's failed on some machine. Avalonia's WinUI
composition visual left windows black on Windows 11 25H2, the Steam
overlay drew its frame counter over the swap chain of a window's own
surface, and with DirectComposition the starter vanished a few seconds
after its window came up on a Windows 10 machine with a GTX 1650, without
a word in its log, under Steam or started on its own. With
--software-render it stayed.

The processor now draws every window on Windows, and each frame is copied
into its window by GDI: no composition visual, no swap chain for an
overlay to hook. On X11 the graphics card still draws, and
--software-render still asks the processor there.
2026-12-02 18:54:12 +01:00
maj00r 121481af00 Merge pull request #68 from MaSzyna-EU07/fix/gamescope-windows
fix: under gamescope the starter fills the screen and every window can be closed
2026-11-30 17:40:43 +01:00
maj00r 92ed2c39f0 fix(settings): the graphics cards on Windows come from DXGI, as the drivers list them (#67)
The starter read the cards from the registry's list of video devices,
which each driver fills as it chooses: a player with an RTX 3060 beside
a Ryzen's Radeon saw only the Radeon. The cards now come from DXGI, the
adapters Windows draws with and whose drivers the simulator's OpenGL
runs on, without software adapters such as the Basic Render Driver.
The registry answers only when DXGI cannot be asked or lists no card.
DXGI is called through function pointers, which NativeAOT compiles
without reflection.

Co-authored-by: maj00r <maj00r@host>
2026-11-30 17:15:21 +01:00
maj00r e1800a20b9 fix: under gamescope the starter fills the screen and every window can be closed
Gamescope, SteamOS's game mode, is no window manager: it gives no
window a title bar or a close button and does not answer a request to
maximize, so it stretched the starter's first size over the screen,
and the tapes window and the black box opened from them could not be
closed at all. Under gamescope the main window now takes the size of
the screen itself, and every window over another gets a bar with its
title and a close button, takes the screen's size too and closes on
Esc, even the tapes, which otherwise stay open beside the starter.
Steam's Big Picture on a desktop keeps its window manager's bars and
is only maximized, as before.
2026-11-30 05:01:07 +01:00
maj00r 5004a2889a Merge pull request #66 from MaSzyna-EU07/fix/zh-missing-keys
fix(lang): Chinese translation has every key of en.xml again, plus a script to keep languages in line
2026-11-29 23:18:30 +01:00
maj00r 4f57881902 ci(sonar): tools/ is left out of the coverage
The quality gate of #66 failed on coverage only: tools/sync_lang.py is new code
that the C# tests don't run. tools/ holds helper scripts outside the app and its
tests, so it isn't counted for coverage; Sonar still analyses it like the rest.
2026-11-29 23:16:57 +01:00
maj00r 7a03cc0c6a fix(lang): untranslated keys marked without TODO, and sync_lang.py split up
Sonar counted each "<!-- TODO: translate -->" as an open task (S1135, 73 of them):
the added keys are marked "<!-- untranslated -->" now. sync() is split into smaller
functions (S3776); what the script does is the same, zh.xml regenerated from main
comes out identical.
2026-11-29 23:14:35 +01:00
maj00r 9fe767cf9f fix(lang): the Chinese translation has every key of en.xml again, and a script keeps languages in line
zh.xml (#45) was translated from an older en.xml: 73 keys the tests require were
missing and 97 keys en.xml no longer has were still there. The localization test
failed on main, so no package and no release were made after the merge.

tools/sync_lang.py adds the missing keys with the English text, marked
<!-- TODO: translate -->, and removes the unused ones; the rest of the file stays
as it is. --check only lists the differences. The missing Chinese keys are filled
in with it, and the README says how to use it.
2026-11-29 22:23:07 +01:00
Hirek fdcf33069d Merge pull request #45 from NishizakiHayato/NishizakiHayato-patch-1
Add Chinese translation
2026-11-29 17:48:21 +00:00
maj00r ece440e566 Merge pull request #64 from MaSzyna-EU07/fix/steam-overlay
fix: the Steam overlay no longer draws its frame counter over the starter
2026-11-28 21:14:28 +01:00
maj00r 3dfcbca711 fix: the Steam overlay no longer draws its frame counter over the starter
Steam puts its overlay into the starter, the game it launches. In a
window's own redirection surface ANGLE draws through a swap chain of
that window, and the overlay hooks its Present and draws the frame
counter and notifications over the starter. Every window now draws
into a DirectComposition surface, which is drawn without a Present and
still keeps away from the WinUI composition visual that came up black
on 25H2. The redirection surface stays only as the fallback.
2026-11-28 19:38:44 +01:00
dependabot[bot] 9668b4d3b6 build(deps): bump actions/setup-dotnet from 6.0.0 to 6.1.0 (#39)
Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 6.0.0 to 6.1.0.
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/a98b56852c35b8e3190ac28c8c2271da59106c68...0f4a354dd5547a28c70b7853dbd95d5b67886e73)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-27 18:06:07 +01:00
maj00r 42591bcddd Merge pull request #62 from MaSzyna-EU07/fix/ini-keeps-unknown-values
fix(settings): keep eu07.ini values the starter does not know until changed by hand
2026-11-27 04:06:04 +01:00
maj00r 50ca332438 fix: windows of the starter no longer come up black on Windows 11 25H2 (#63)
* fix: windows of the starter no longer come up black on Windows 11 25H2

Avalonia composes each window through a WinUI composition visual by
default, and on 25H2 that visual was often left empty: the main window
or a dialog opened later stayed black while the others drew. The
starter has no see-through windows or backdrops, so every window now
draws into its own redirection surface, still on the graphics card.
--software-render comes after and keeps its own options.

* test: the choice between window surfaces and the processor is covered

The choice moves out of Program, which no test runs, into
WindowSurfaces, where both branches are tested. Sonar's quality gate
failed on the coverage of the new code.

---------

Co-authored-by: maj00r <maj00r@host>
2026-11-27 04:00:39 +01:00
maj00r 4f749ff576 fix(physics): a // comment in a .fiz is skipped, as the game does (#61)
Include parameters written one per line with a // note after them
("68 //MaxLoad") gave the note's words as parameters of their own, so
LoadAccepted=(p3) in db/zans_v1 read "68" and the load list showed a number.

Co-authored-by: maj00r <maj00r@host>
2026-11-24 19:40:07 +01:00
maj00r b778122fb5 fix(settings): a value of eu07.ini the starter does not know stays until changed by hand
A renderer written in by hand ("gfxrenderer vulkan") went back to "default"
on the next save, the Vulkan renderer's own keys were taken out, and saying
no to reading the file again lost every change made on disk meanwhile.

Such a value is now shown as the file writes it - on its list where the
control is one, with the note under the setting otherwise - and written back
as it is until the player sets that control, even to what the starter shows
by default. The move to the standard mode puts them right, as before for the
advanced settings. Declining to read the file again no longer forgets the
change on disk: the next save goes onto it.

The default UART features in another order are no longer named unknown.
2026-11-24 18:26:56 +01:00
NishizakiHayato a3fc1dd1ac Merge branch 'MaSzyna-EU07:main' into NishizakiHayato-patch-1 2026-11-24 20:32:14 +08:00
Hirek 94112af005 Remove dependabot integration 2026-11-23 18:08:36 +01:00
Hirek dd25372bd0 Merge pull request #60 from MaSzyna-EU07/feat/settings-standard-mode
feat(settings): standard mode, consist minis, scenery and map fixes
2026-11-23 17:07:07 +00:00
NishizakiHayato 2f0f7ebe43 Update zh.xml 2026-11-14 00:20:15 +08:00
NishizakiHayato b8c1560220 Update zh.xml 2026-11-13 13:25:00 +08:00
NishizakiHayato f2fbb6d0d6 Update zh.xml 2026-11-13 11:57:08 +08:00
NishizakiHayato ad58d0f838 Add Chinese 2026-11-13 11:04:31 +08:00
29 changed files with 2493 additions and 91 deletions
-14
View File
@@ -1,14 +0,0 @@
# Pull requests for new versions of the pinned actions and of the NuGet packages,
# so a fix for a vulnerability reaches the build without anyone watching for it.
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: nuget
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
+2 -2
View File
@@ -52,7 +52,7 @@ jobs:
persist-credentials: false persist-credentials: false
- name: Setup .NET 10 - name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with: with:
dotnet-version: 10.0.x dotnet-version: 10.0.x
@@ -142,7 +142,7 @@ jobs:
persist-credentials: false persist-credentials: false
- name: Setup .NET 10 - name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with: with:
dotnet-version: 10.0.x dotnet-version: 10.0.x
+4 -1
View File
@@ -62,7 +62,7 @@ jobs:
persist-credentials: false persist-credentials: false
- name: Setup .NET 10 - name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with: with:
dotnet-version: 10.0.x dotnet-version: 10.0.x
@@ -71,6 +71,8 @@ jobs:
# sonar.qualitygate.wait=true blocks the end step until the server has # sonar.qualitygate.wait=true blocks the end step until the server has
# processed the report, so the job's result is the quality gate's. # processed the report, so the job's result is the quality gate's.
# tools/ holds the developers' helper scripts, outside the app and its tests:
# analysed like the rest, but not counted for coverage.
- name: Begin analysis - name: Begin analysis
env: env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
@@ -84,6 +86,7 @@ jobs:
/d:sonar.scm.revision="${{ github.event.pull_request.head.sha || github.sha }}" /d:sonar.scm.revision="${{ github.event.pull_request.head.sha || github.sha }}"
/d:sonar.cs.opencover.reportsPaths="TestResults/**/coverage.opencover.xml" /d:sonar.cs.opencover.reportsPaths="TestResults/**/coverage.opencover.xml"
/d:sonar.cs.vstest.reportsPaths="TestResults/*.trx" /d:sonar.cs.vstest.reportsPaths="TestResults/*.trx"
/d:sonar.coverage.exclusions="tools/**"
/d:sonar.qualitygate.wait=true /d:sonar.qualitygate.wait=true
# A full, non-incremental build: the analyzers only see what is compiled. # A full, non-incremental build: the analyzers only see what is compiled.
+14
View File
@@ -46,3 +46,17 @@ the packaged artifacts — tagged `latest` for `main` and `staging` for `staging
```sh ```sh
dotnet build StarterNG/StarterNG.csproj dotnet build StarterNG/StarterNG.csproj
``` ```
## Translations
The texts are in `StarterNG/startercfg/lang/<code>.xml`; `en.xml` is the reference.
The tests require every language to have every key of `en.xml` except the optional
ones (ending in `Desc`, starting with `Cmd.`), which fall back to English. After a
change to `en.xml`, or before merging a translation made from an older one:
```sh
python tools/sync_lang.py --check # lists what is missing or no longer used
python tools/sync_lang.py # adds missing keys in English, removes the unused ones
```
Added keys are marked `<!-- untranslated -->` for the translator.
+67
View File
@@ -68,6 +68,71 @@ public class ExternalIniTests
Assert.Contains("fieldofview 60", installation.Files.ReadAllText(UserIni)); Assert.Contains("fieldofview 60", installation.Files.ReadAllText(UserIni));
} }
[Fact]
public void A_renderer_written_in_by_hand_while_the_starter_runs_survives_its_save()
{
// Notepad: "gfxrenderer vulkan", a word the starter does not offer.
var installation = WithIni("gfxrenderer default\nfieldofview 45\n");
Edited(installation, "gfxrenderer vulkan\nfieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("gfxrenderer vulkan", saved);
Assert.Contains("fieldofview 60", saved);
Assert.Equal("vulkan", installation.SettingsStore.Settings.RendererWord);
}
[Fact]
public void A_renderer_written_in_by_hand_and_read_again_survives_the_next_save()
{
var installation = WithIni("gfxrenderer default\n");
Edited(installation, "gfxrenderer vulkan\n");
// "Wczytać ponownie?" - yes.
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Contains("gfxrenderer vulkan", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_change_on_disk_not_read_again_is_not_lost_on_the_next_save()
{
var installation = WithIni("gfxrenderer default\nfieldofview 45\nvsync no\n");
var store = installation.SettingsStore;
Edited(installation, "gfxrenderer vulkan\nfieldofview 45\nvsync yes\n");
Assert.True(store.HasChangeOnDiskToAskAbout());
// "Wczytać ponownie?" - no: not asked again about the same change.
store.LeaveChangeOnDisk();
Assert.False(store.HasChangeOnDiskToAskAbout());
store.Settings.FieldOfView = 60;
store.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("gfxrenderer vulkan", saved);
Assert.Contains("vsync yes", saved);
Assert.Contains("fieldofview 60", saved);
Assert.True(store.LastSaveMerged);
}
[Fact]
public void A_later_change_on_disk_is_asked_about_again()
{
var installation = WithIni("fieldofview 45\n");
var store = installation.SettingsStore;
Edited(installation, "fieldofview 50\n");
store.LeaveChangeOnDisk();
installation.Files.WithFile(UserIni, "fieldofview 55\n")
.WrittenAt(UserIni, installation.Files.GetLastWriteTimeUtc(UserIni).AddMinutes(1));
Assert.True(store.HasChangeOnDiskToAskAbout());
}
[Fact] [Fact]
public void A_file_nobody_else_touched_saves_as_before() public void A_file_nobody_else_touched_saves_as_before()
{ {
@@ -97,6 +162,8 @@ public class ExternalIniTests
Assert.False(unreadable.ContainsKey("gfxrenderer")); Assert.False(unreadable.ContainsKey("gfxrenderer"));
Assert.False(unreadable.ContainsKey("gfx.framebuffer.width")); Assert.False(unreadable.ContainsKey("gfx.framebuffer.width"));
Assert.False(unreadable.ContainsKey("calibratein")); Assert.False(unreadable.ContainsKey("calibratein"));
// The default features in another order: the same line.
Assert.False(WithIni("uartfeature local|main|scnd|train\n").SettingsStore.UnreadableValues().ContainsKey("uartfeature"));
// The file keeps what it says until the setting is changed. // The file keeps what it says until the setting is changed.
installation.SettingsStore.Save(); installation.SettingsStore.Save();
Assert.Contains("fieldofview abc", installation.Files.ReadAllText(UserIni)); Assert.Contains("fieldofview abc", installation.Files.ReadAllText(UserIni));
+155
View File
@@ -0,0 +1,155 @@
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using StarterNG.Controls;
namespace StarterNG.Tests;
/// <summary>Windows under gamescope, which gives them no title bar, no close button and no maximizing.</summary>
[Collection(AvaloniaControls.Name)]
public class GamescopeWindowsTests
{
static GamescopeWindowsTests()
{
HeadlessDrawing.Ensure();
DialogKeyboard.Install();
GamescopeWindows.Install(false, () => "Zamknij");
}
[Theory]
[InlineData("gamescope", null, true)]
[InlineData("Gamescope", null, true)]
[InlineData("KDE", "gamescope-0", true)]
[InlineData(null, "gamescope-0", true)]
[InlineData("KDE", null, false)]
[InlineData("KDE", "", false)]
[InlineData(null, null, false)]
public void Gamescope_is_told_by_its_session_or_by_its_display(string? desktop, string? display, bool expected)
{
var variables = new Dictionary<string, string?>
{
["XDG_CURRENT_DESKTOP"] = desktop,
["GAMESCOPE_WAYLAND_DISPLAY"] = display,
// Big Picture on a desktop, whose window manager still draws the bars.
["SteamGamepadUI"] = "1"
};
Assert.Equal(expected, GamescopeWindows.IsGamescope(name => variables.GetValueOrDefault(name)));
}
private static (Window Owner, Window Window) Open(Control content, bool gamescope, bool escapeCloses = true)
{
GamescopeWindows.Active = gamescope;
var owner = new Window();
owner.Show();
var window = new Window { Title = "Taśmy", Width = 300, Height = 200, Content = content };
DialogKeyboard.SetEscapeCloses(window, escapeCloses);
window.Show(owner);
// Headless a window says it opened before it is given its owner; it says so again once it has one.
Assert.Same(owner, window.Owner);
window.RaiseEvent(new RoutedEventArgs(Window.WindowOpenedEvent));
Controls.Settle();
return (owner, window);
}
private static Button? CloseButton(Window window) =>
window.GetVisualDescendants().OfType<Button>().FirstOrDefault(b => Equals(b.Content, "Zamknij"));
[Fact]
public void Under_gamescope_a_window_over_another_gets_its_title_and_a_close_button()
{
var content = new TextBlock { Text = "zawartość" };
var (owner, window) = Open(content, gamescope: true);
try
{
bool closed = false;
window.Closed += (_, _) => closed = true;
Assert.Contains(window.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Taśmy");
Assert.Same(content, window.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "zawartość"));
var close = CloseButton(window);
Assert.NotNull(close);
close.RaiseEvent(Controls.Click());
Assert.True(closed);
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void Under_gamescope_esc_closes_even_a_window_that_stays_open_beside_the_starter()
{
var (owner, window) = Open(new TextBox(), gamescope: true, escapeCloses: false);
try
{
bool closed = false;
window.Closed += (_, _) => closed = true;
Assert.True(Controls.Press(window, Key.Escape));
Assert.True(closed);
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void The_window_shows_what_it_had_first_and_the_bar_after_it_in_tab_order()
{
var first = new Button { Content = "Pierwszy" };
var (owner, window) = Open(new StackPanel { Children = { first } }, gamescope: true);
try
{
var grid = Assert.IsType<Grid>(window.Content);
Assert.IsType<StackPanel>(grid.Children[0]);
Assert.True(first.IsFocused);
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void A_window_that_says_twice_it_opened_gets_one_bar()
{
var (owner, window) = Open(new TextBlock { Text = "zawartość" }, gamescope: true);
try
{
window.RaiseEvent(new RoutedEventArgs(Window.WindowOpenedEvent));
Controls.Settle();
Assert.Single(window.GetVisualDescendants().OfType<Button>(), b => Equals(b.Content, "Zamknij"));
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void Elsewhere_a_window_keeps_what_it_shows_and_esc_keeps_its_choice()
{
var content = new TextBox();
var (owner, window) = Open(content, gamescope: false, escapeCloses: false);
try
{
Assert.Same(content, window.Content);
Assert.Null(CloseButton(window));
Assert.False(Controls.Press(window, Key.Escape));
}
finally
{
owner.Close();
}
}
}
+77
View File
@@ -99,6 +99,83 @@ public class GraphicsCardsTests
Assert.Equal(new[] { "AMD Radeon RX 6700 XT", "AMD Radeon 780M" }, cards.Select(card => card.Name)); Assert.Equal(new[] { "AMD Radeon RX 6700 XT", "AMD Radeon 780M" }, cards.Select(card => card.Name));
} }
private static GraphicsCards WindowsReader(IReadOnlyList<DxgiAdapter>? dxgi, params GraphicsCard[] registry) =>
new(new InMemoryFileSystem(), new FakeEnvironment().AsWindows(), new LinuxGpus(new InMemoryFileSystem(), new FakeEnvironment()),
() => Array.Empty<string>(), () => dxgi, () => registry);
private static DxgiAdapter Adapter(string name, uint vendor, long memory, uint flags = 0) =>
new(name, vendor, (ulong)memory, flags);
[Fact]
public void Windows_takes_the_cards_dxgi_lists_and_the_discrete_one_first()
{
var reader = WindowsReader(
new[] { Adapter("AMD Radeon(TM) Graphics", 0x1002, GiB / 2), Adapter("NVIDIA GeForce RTX 3060", 0x10DE, 12 * GiB) },
new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2));
var cards = reader.List();
Assert.Equal(new[] { "NVIDIA GeForce RTX 3060", "AMD Radeon(TM) Graphics" }, cards.Select(card => card.Name));
Assert.Equal(12, cards[0].MemoryGb);
}
[Fact]
public void Software_adapters_are_no_cards()
{
var cards = DxgiAdapters.Cards(new[]
{
Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2),
Adapter("Microsoft Remote Display Adapter", 0x1414, 0),
Adapter("Some software rasterizer", 0x1234, 0, flags: 2),
Adapter("NVIDIA GeForce RTX 5060 Laptop GPU", 0x10DE, 8546942976)
});
Assert.Equal("NVIDIA GeForce RTX 5060 Laptop GPU", Assert.Single(cards).Name);
}
[Fact]
public void A_card_dxgi_lists_twice_is_shown_once()
{
var cards = DxgiAdapters.Cards(new[]
{
Adapter("AMD Radeon 780M Graphics", 0x1002, GiB / 2),
Adapter("AMD Radeon 780M Graphics ", 0x1002, GiB / 2)
});
Assert.Equal("AMD Radeon 780M Graphics", Assert.Single(cards).Name);
}
[Fact]
public void The_registry_answers_when_dxgi_cannot_be_asked()
{
var card = Assert.Single(WindowsReader(null, new GraphicsCard("NVIDIA GeForce RTX 3060", 12 * GiB)).List());
Assert.Equal("NVIDIA GeForce RTX 3060", card.Name);
}
[Fact]
public void The_registry_answers_when_dxgi_lists_only_software()
{
var reader = WindowsReader(new[] { Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2) },
new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2));
Assert.Equal("AMD Radeon(TM) Graphics", Assert.Single(reader.List()).Name);
}
[Fact]
public void Dxgi_answers_on_this_machine()
{
if (!OperatingSystem.IsWindows())
return;
// Every Windows lists at least the Basic Render Driver, so an answer means the calls work.
var adapters = DxgiAdapters.Read();
Assert.NotNull(adapters);
Assert.NotEmpty(adapters);
Assert.All(adapters, adapter => Assert.False(string.IsNullOrWhiteSpace(adapter.Description)));
}
[Fact] [Fact]
public void There_are_no_cards_on_a_mac() public void There_are_no_cards_on_a_mac()
{ {
+9 -8
View File
@@ -37,18 +37,18 @@ public class GraphicsSettingsTests
private static string? Line(string text, string key) => private static string? Line(string text, string key) =>
Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal)); Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal));
// As application.cpp on master has them: a word it does not know gets the full renderer. // As application.cpp on master has them; a word the starter does not know is the file's own, written back as it is.
[Theory] [Theory]
[InlineData("default", "default")] [InlineData("default", "default")]
[InlineData("full", "default")] [InlineData("full", "full")]
[InlineData("gl46", "default")] [InlineData("gl46", "gl46")]
[InlineData("vulkan", "default")] [InlineData("vulkan", "vulkan")]
[InlineData("vulkan14", "default")] [InlineData("vulkan14", "vulkan14")]
[InlineData("legacy", "legacy")] [InlineData("legacy", "legacy")]
[InlineData("simpleshader", "legacy")] [InlineData("simpleshader", "legacy")]
[InlineData("off", "legacy")] [InlineData("off", "legacy")]
[InlineData("simple", "simple")] [InlineData("simple", "simple")]
[InlineData("experimental", "default")] [InlineData("experimental", "experimental")]
public void A_renderer_is_written_by_the_name_master_knows(string read, string written) public void A_renderer_is_written_by_the_name_master_knows(string read, string written)
{ {
Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer")); Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer"));
@@ -93,7 +93,7 @@ public class GraphicsSettingsTests
} }
[Fact] [Fact]
public void Keys_of_the_vulkan_renderer_master_does_not_have_go_on_a_save() public void Keys_of_the_vulkan_renderer_master_does_not_have_stay_on_a_save()
{ {
string[] vulkan = string[] vulkan =
{ {
@@ -107,7 +107,8 @@ public class GraphicsSettingsTests
string saved = installation.Files.ReadAllText(UserIni); string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved); Assert.Contains("calibratein 0 0 0 0", saved);
Assert.All(vulkan, line => Assert.Null(Line(saved, line.Split(' ')[0]))); // Written in by hand for a build that has that renderer: the starter does not know them, and leaves them.
Assert.All(vulkan, line => Assert.Equal(line, Line(saved, line.Split(' ')[0])));
} }
[Fact] [Fact]
+30
View File
@@ -65,6 +65,36 @@ public class PhysicsAndAssetsTests
Assert.Equal(125, physics.VMax); Assert.Equal(125, physics.VMax);
} }
[Fact]
public void Comments_between_include_parameters_are_not_parameters()
{
// As in the game: db/zans_v1/astra_rail_14_96m_86m3_ke_1.fiz feeds zans.fiz.inc this way.
const string fiz = """
include
zans.fiz.inc
21000 //masa
68 //MaxLoad
aviation_fuel,crude_oil,petrol
14.96 //L
end
""";
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(Fiz("db", "zans_v1", "astra"), fiz)
.WithFile(TestInstallation.At("dynamic", "db", "zans_v1", "zans.fiz.inc"),
"""
Param. Category=train M=(p1) Vmax=100 # masa [kg]
Load: MaxLoad=(p2) LoadQ=tonns LoadAccepted=(p3) LoadSpeed=0.1
Dimensions: L=(p4) H=4.285
"""));
var physics = installation.Physics.For("db/zans_v1/", "astra")!;
Assert.Equal(21000, physics.Mass);
Assert.Equal(68, physics.MaxLoad);
Assert.Equal("aviation_fuel,crude_oil,petrol", physics.LoadAccepted);
Assert.Equal(14.96, physics.Length);
}
[Fact] [Fact]
public void An_include_named_in_other_case_is_followed() public void An_include_named_in_other_case_is_followed()
{ {
+17 -6
View File
@@ -961,23 +961,34 @@ public class SettingsStoreTests
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation)); Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
} }
// Words master does not know start the full renderer with a line in its log, and the // A word the starter does not know is written in by hand for a build that has it, such as one with Vulkan:
// experimental renderer is not in a player's build: a save puts "default" in their place. // shown, and left as it is until another renderer is chosen.
[Theory] [Theory]
[InlineData("full")] [InlineData("full")]
[InlineData("opengl")] [InlineData("opengl")]
[InlineData("gl46")] [InlineData("gl46")]
[InlineData("vulkan")]
[InlineData("vulkan14")] [InlineData("vulkan14")]
[InlineData("experimental")] [InlineData("experimental")]
[InlineData("null")] [InlineData("null")]
public void A_renderer_word_master_does_not_run_is_saved_as_default(string word) public void A_renderer_word_the_starter_does_not_know_stays_until_another_is_chosen(string word)
{ {
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n")); var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\nfieldofview 45\n"));
installation.SettingsStore.Load(); var store = installation.SettingsStore;
store.Load();
installation.SettingsStore.Save(); Assert.Equal(word, store.Settings.RendererWord);
Assert.Equal(word, store.UnreadableValues()["gfxrenderer"]);
store.Settings.FieldOfView = 60;
store.Save();
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
// Picking one from the list, even the full renderer it runs as, is a choice.
store.Settings.RendererWord = null;
store.Settings.RenderEngine = 0;
store.Save();
Assert.Contains("gfxrenderer default\n", SavedLines(installation)); Assert.Contains("gfxrenderer default\n", SavedLines(installation));
Assert.False(store.UnreadableValues().ContainsKey("gfxrenderer"));
} }
[Theory] [Theory]
@@ -0,0 +1,182 @@
using Avalonia.Controls;
using StarterNG.Application;
using StarterNG.Controls;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
/// <summary>
/// Values of eu07.ini the starter does not know, or a control cannot show, as the settings page
/// shows them: as the file writes them, with a note, until the player sets them by hand - or the
/// move to the standard mode puts them right.
/// </summary>
[Collection(AvaloniaControls.Name)]
public class SettingsUnknownValueTests
{
// The standard mode already, unless a test moves to it.
private const string Standard = "starter.settings.standard yes\n";
private static void WithPage(string ini, Action<StarterNG.Views.Settings, AppServices, Func<string>> act)
{
var installation = new TestInstallation(new InMemoryFileSystem());
installation.Environment.AsWindows();
var services = AppServices.Initialize(installation.Paths, installation.Files, installation.Clock,
installation.Environment);
string path = services.SettingsPaths.UserConfigPath();
installation.Files.WriteAllText(path, ini);
services.SettingsStore.Load();
HeadlessDrawing.Ensure();
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(new Avalonia.Threading.AvaloniaSynchronizationContext());
Window? window = null;
try
{
var page = new StarterNG.Views.Settings();
window = Controls.Show(page, 1600, 1000, themed: true);
act(page, services, () => installation.Files.ReadAllText(path).Replace("\r\n", "\n"));
}
finally
{
window?.Close();
SynchronizationContext.SetSynchronizationContext(context);
}
}
private static ComboBox List(StarterNG.Views.Settings page, string name) => page.FindControl<ComboBox>(name)!;
private static string? Shown(ComboBox list) => (list.SelectedItem as ComboBoxItem)?.Content as string;
private static string? Note(StarterNG.Views.Settings page, string key) =>
Avalonia.LogicalTree.LogicalExtensions.GetLogicalDescendants(page).OfType<SettingRow>()
.First(row => row.ConfigKey == key).UnknownValue;
[Fact]
public void A_renderer_word_is_on_the_list_chosen_and_saved_as_it_is()
{
WithPage(Standard + "gfxrenderer vulkan\nfieldofview 45\n", (page, _, saved) =>
{
Assert.Equal("vulkan", Shown(List(page, "RenderEngineCb")));
Assert.Contains("vulkan", Note(page, "gfxrenderer"));
Assert.False(page.HasUnsavedChanges);
page.Save();
Assert.Contains("gfxrenderer vulkan\n", saved());
});
}
[Fact]
public void Another_renderer_picked_from_the_list_replaces_it()
{
WithPage(Standard + "gfxrenderer vulkan\n", (page, services, saved) =>
{
List(page, "RenderEngineCb").SelectedIndex = 0;
page.Save();
Assert.Contains("gfxrenderer default\n", saved());
Assert.Null(services.Settings.RendererWord);
Assert.Null(Note(page, "gfxrenderer"));
});
}
[Fact]
public void A_value_a_list_does_not_offer_is_listed_as_written_and_kept()
{
WithPage(Standard + "starter.batterydefault 7\ngfx.shadow.rank.cutoff 9\n", (page, _, saved) =>
{
Assert.Equal("7", Shown(List(page, "ReadyOverrideCb")));
Assert.Equal("9", Shown(List(page, "ShadowDisplayCb")));
Assert.Contains("7", Note(page, "starter.batterydefault"));
Assert.Contains("9", Note(page, "gfx.shadow.rank.cutoff"));
Assert.False(page.HasUnsavedChanges);
page.Save();
Assert.Contains("starter.batterydefault 7\n", saved());
Assert.Contains("gfx.shadow.rank.cutoff 9\n", saved());
});
}
[Fact]
public void Picking_the_value_the_starter_shows_by_default_replaces_the_files_own()
{
// "7" is read as the scenery's choice, the first on the list: picked by hand, it is written.
WithPage(Standard + "starter.batterydefault 7\n", (page, _, saved) =>
{
List(page, "ReadyOverrideCb").SelectedIndex = 0;
Assert.Null(Note(page, "starter.batterydefault"));
page.Save();
Assert.Contains("starter.batterydefault 0\n", saved());
});
}
[Fact]
public void A_list_put_back_at_the_files_value_keeps_it()
{
WithPage(Standard + "starter.batterydefault 7\n", (page, _, saved) =>
{
var list = List(page, "ReadyOverrideCb");
var fileValue = list.SelectedItem;
list.SelectedIndex = 1;
list.SelectedItem = fileValue;
page.Save();
Assert.Contains("starter.batterydefault 7\n", saved());
});
}
[Fact]
public void A_control_set_by_hand_to_the_default_replaces_a_value_it_could_not_read()
{
WithPage(Standard + "vsync moze\n", (page, _, saved) =>
{
Assert.Contains("moze", Note(page, "vsync"));
var box = page.FindControl<CheckBox>("VSyncCb")!;
box.IsChecked = true;
box.IsChecked = false;
page.Save();
Assert.Contains("vsync no\n", saved());
});
}
[Fact]
public void A_level_for_other_settings_leaves_a_value_of_the_file_alone()
{
WithPage(Standard + "starter.batterydefault 7\ngfxrenderer vulkan\n", (page, _, saved) =>
{
page.FindControl<Panel>("PresetButtons")!.Children.OfType<Button>().First()
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
Assert.Equal("7", Shown(List(page, "ReadyOverrideCb")));
page.Save();
Assert.Contains("starter.batterydefault 7\n", saved());
Assert.Contains("gfxrenderer vulkan\n", saved());
});
}
[Fact]
public void The_move_to_the_standard_mode_puts_values_of_the_file_right()
{
WithPage("gfxrenderer vulkan\nstarter.batterydefault 7\nvsync moze\ngfx.usegles yes\n", (page, _, saved) =>
{
page.MoveToStandardOnce();
string text = saved();
Assert.Contains("gfxrenderer default\n", text);
Assert.Contains("starter.batterydefault 0\n", text);
Assert.Contains("vsync no\n", text);
// What lets some machines run the simulator at all stays.
Assert.Contains("gfx.usegles yes\n", text);
Assert.Null(Note(page, "gfxrenderer"));
Assert.NotEqual("7", Shown(List(page, "ReadyOverrideCb")));
});
}
}
+9 -5
View File
@@ -14,7 +14,7 @@ public class SoftwareRenderTests
} }
[Fact] [Fact]
public void Without_the_switch_the_graphics_card_draws() public void Without_the_switch_it_is_not_asked_for()
{ {
Assert.False(SoftwareRender.AskedIn(Array.Empty<string>())); Assert.False(SoftwareRender.AskedIn(Array.Empty<string>()));
Assert.False(SoftwareRender.AskedIn(new[] { "--software" })); Assert.False(SoftwareRender.AskedIn(new[] { "--software" }));
@@ -25,21 +25,25 @@ public class SoftwareRenderTests
{ {
var options = SoftwareRender.Win32Options; var options = SoftwareRender.Win32Options;
// No WinUI composition, DirectComposition or swap chain of the graphics card's.
Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode); Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode);
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode); Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
} }
[Fact] [Fact]
public void X11_draws_on_the_processor() public void X11_draws_on_the_processor_when_asked()
{ {
Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode); Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode);
} }
[Fact] [Theory]
public void Both_platforms_options_go_to_the_same_builder() [InlineData(false)]
[InlineData(true)]
public void The_options_go_to_the_same_builder_with_or_without_the_switch(bool asked)
{ {
var builder = AppBuilder.Configure<Avalonia.Application>(); var builder = AppBuilder.Configure<Avalonia.Application>();
string[] args = asked ? new[] { SoftwareRender.Switch } : Array.Empty<string>();
Assert.Same(builder, SoftwareRender.ApplyTo(builder)); Assert.Same(builder, SoftwareRender.ApplyTo(builder, args));
} }
} }
+2
View File
@@ -28,6 +28,8 @@ public partial class App : Avalonia.Application
// Before any control exists: the names are given as controls are filled in. // Before any control exists: the names are given as controls are filled in.
ScreenReaderNames.Install(); ScreenReaderNames.Install();
DialogKeyboard.Install(); DialogKeyboard.Install();
GamescopeWindows.Install(GamescopeWindows.IsGamescope(AppServices.Current.Environment.GetVariable),
() => Loc["Close"]);
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
+71 -3
View File
@@ -49,6 +49,41 @@ public sealed class SettingsStore
// it has it: a value outside what the starter offers, its spacing, its comment. // it has it: a value outside what the starter offers, its spacing, its comment.
private IReadOnlyDictionary<string, string> _synced = new Dictionary<string, string>(); private IReadOnlyDictionary<string, string> _synced = new Dictionary<string, string>();
// Keys set by the player's hand since the file was read: written as the screen has them,
// even where that is what the starter shows for a value of the file it does not know.
private readonly HashSet<string> _chosen = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// <paramref name="keys"/> were set by hand - a control moved, a level or the defaults
/// put on them, the move to the standard mode: a save writes them, and a value of the
/// file the starter does not know goes. Until then it stays as it is.
/// </summary>
public void Choose(IEnumerable<string> keys) => _chosen.UnionWith(keys);
/// <summary>The value of the file is chosen again, as it is: it stays in the file.</summary>
public void Unchoose(IEnumerable<string> keys) => _chosen.ExceptWith(keys);
public bool IsChosen(string key) => _chosen.Contains(key);
/// <summary>
/// Whether the file's value of <paramref name="key"/> means what <paramref name="shown"/> does,
/// written its own way: yes and tak, 45 and 45.0, the UART features in another order.
/// </summary>
public bool FileMeans(string key, string? shown)
{
string? raw = FileValueOf(key);
return raw is null || shown is null ? raw == shown : Means(key, raw, shown);
}
private static bool Means(string key, string raw, string shown) =>
string.Equals(key, "uartfeature", StringComparison.OrdinalIgnoreCase)
? Uart.FeaturesStand(raw, shown)
: SameValue(raw, shown);
/// <summary>The key as the file writes it, where the simulator gets to it; null where it does not.</summary>
public string? FileValueOf(string key) =>
_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw ? null : raw;
public SettingsStore(IFileSystem files, IClock clock, IDiagnosticsLog log, SettingsPaths paths, public SettingsStore(IFileSystem files, IClock clock, IDiagnosticsLog log, SettingsPaths paths,
SettingsSerializer serializer, ExecutableLocator executables) SettingsSerializer serializer, ExecutableLocator executables)
{ {
@@ -138,6 +173,7 @@ public sealed class SettingsStore
_serializer.Read(Settings, _config); _serializer.Read(Settings, _config);
_synced = Render(Settings); _synced = Render(Settings);
_chosen.Clear();
// after the snapshot, so the next save writes it; a profile of before goes the same way as the ini would // after the snapshot, so the next save writes it; a profile of before goes the same way as the ini would
if (!LoadFailed) if (!LoadFailed)
SettingsSerializer.MoveToTrainTapes(Settings); SettingsSerializer.MoveToTrainTapes(Settings);
@@ -367,7 +403,7 @@ public sealed class SettingsStore
continue; continue;
if (_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw) if (_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw)
continue; continue;
if (read.TryGetValue(key, out string? shown) && shown == fallback && !SameValue(raw, shown)) if (read.TryGetValue(key, out string? shown) && shown == fallback && !Means(key, raw, shown))
unreadable[key] = raw; unreadable[key] = raw;
} }
@@ -385,6 +421,10 @@ public sealed class SettingsStore
if (!readable) if (!readable)
unreadable[key.Key] = raw; unreadable[key.Key] = raw;
} }
// Kept as written, and offered on the list under its own word.
if (!_config.IsPastEnd("gfxrenderer") && WithFile(_config).RendererWord is { } renderer)
unreadable["gfxrenderer"] = renderer;
return unreadable; return unreadable;
} }
@@ -473,8 +513,7 @@ public sealed class SettingsStore
return Uart.FeaturesStand(_config.GetRaw(key), value); return Uart.FeaturesStand(_config.GetRaw(key), value);
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase)) if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
return _config.GetRaw(key) == value; return _config.GetRaw(key) == value;
if (string.Equals(key, "gfxrenderer", StringComparison.OrdinalIgnoreCase) && if (_chosen.Contains(key))
!SimulatorSettings.KeptRendererWord(_config.GetRaw(key)))
return false; return false;
if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) && if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) &&
!SettingsSerializer.MouseScaleStands(_config.GetRaw(key))) !SettingsSerializer.MouseScaleStands(_config.GetRaw(key)))
@@ -567,6 +606,35 @@ public sealed class SettingsStore
} }
} }
// When the file stood as it was last asked about; a save still goes onto what it holds.
private DateTime _askedAboutUtc = DateTime.MinValue;
/// <summary>
/// Whether the file changed elsewhere since it was read here, written here or last asked
/// about. Declined (<see cref="LeaveChangeOnDisk"/>), a change is not asked about again.
/// </summary>
public bool HasChangeOnDiskToAskAbout() =>
IsConfigNewerOnDisk() && DiskWriteTimeUtc() is { } written && written > _askedAboutUtc;
/// <summary>
/// The player chose not to read the file again. The screen stays as it is, but what was
/// written in elsewhere is no more lost for that: the next save goes onto it.
/// </summary>
public void LeaveChangeOnDisk() => _askedAboutUtc = DiskWriteTimeUtc() ?? _clock.UtcNow;
private DateTime? DiskWriteTimeUtc()
{
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
try
{
return _files.FileExists(path) ? _files.GetLastWriteTimeUtc(path) : null;
}
catch (Exception)
{
return null;
}
}
public bool IsConfigNewerOnDisk() public bool IsConfigNewerOnDisk()
{ {
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath; string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
+3 -1
View File
@@ -41,7 +41,9 @@ public static class DialogKeyboard
// button or a window of its own that handles the key keep it. // button or a window of its own that handles the key keep it.
private static void OnEscape(Window window, KeyEventArgs e) private static void OnEscape(Window window, KeyEventArgs e)
{ {
if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None || !GetEscapeCloses(window)) // Under gamescope a window has no other way out than Esc and the bar it is given there.
if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None ||
!(GetEscapeCloses(window) || GamescopeWindows.Active))
return; return;
window.Close(); window.Close();
+140
View File
@@ -0,0 +1,140 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace StarterNG.Controls;
/// <summary>
/// The starter's windows under gamescope, SteamOS's game mode (or gamescope started by
/// hand): it shows one window at a time over the whole screen and is no window manager.
/// No window gets a title bar or a close button from it, and a request to maximize is
/// not answered, so gamescope stretches a window of its first size over the screen.
/// Here each window over another gets a bar with its title and a close button, Esc closes
/// it whatever it says otherwise, and every window takes the size of the screen itself.
/// </summary>
public static class GamescopeWindows
{
private static readonly AttachedProperty<bool> FittedProperty =
AvaloniaProperty.RegisterAttached<Window, bool>("GamescopeFitted", typeof(GamescopeWindows));
private static readonly IBrush BarLine = new SolidColorBrush(Color.FromArgb(0x40, 0x80, 0x80, 0x80));
private static Func<string> _closeLabel = () => "Close";
private static bool _installed;
/// <summary>
/// XDG_CURRENT_DESKTOP is gamescope in SteamOS's game mode and in the sessions made
/// after it; GAMESCOPE_WAYLAND_DISPLAY is set by any gamescope for what it starts,
/// one started by hand on a desktop too. Steam's Big Picture on a desktop is neither:
/// its window manager still draws the bars.
/// </summary>
public static bool IsGamescope(Func<string, string?> variable) =>
string.Equals(variable("XDG_CURRENT_DESKTOP"), "gamescope", StringComparison.OrdinalIgnoreCase)
|| !string.IsNullOrEmpty(variable("GAMESCOPE_WAYLAND_DISPLAY"));
/// <summary>Whether the starter runs under gamescope; set once by <see cref="Install"/>.</summary>
public static bool Active { get; set; }
public static void Install(bool active, Func<string> closeLabel)
{
Active = active;
_closeLabel = closeLabel;
if (_installed)
return;
_installed = true;
Window.WindowOpenedEvent.AddClassHandler<Window>((window, _) => OnOpened(window));
}
private static void OnOpened(Window window)
{
// The main window has a bar of its own and fills the screen from its constructor;
// the splash goes by itself. A window may say twice that it opened.
if (!Active || window.Owner is null || window.GetValue(FittedProperty))
return;
window.SetValue(FittedProperty, true);
AddTitleBar(window);
FillScreen(window);
}
/// <summary>The window's title and a close button above what it shows, after it in Tab order.</summary>
public static void AddTitleBar(Window window)
{
if (window.Content is not Control content)
return;
// Over the whole screen a window sized to what it shows keeps it in the middle.
if (window.SizeToContent != SizeToContent.Manual)
{
content.HorizontalAlignment = HorizontalAlignment.Center;
content.VerticalAlignment = VerticalAlignment.Center;
}
var title = new TextBlock
{
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0),
FontWeight = FontWeight.SemiBold,
TextTrimming = TextTrimming.CharacterEllipsis
};
title[!TextBlock.TextProperty] = window[!Window.TitleProperty];
var close = new Button
{
Content = _closeLabel(),
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(8, 4)
};
close.Classes.Add("Flat");
close.Click += (_, _) => window.Close();
var bar = new DockPanel
{
Background = Brushes.Transparent,
Children = { close, title }
};
DockPanel.SetDock(close, Dock.Right);
var line = new Border
{
BorderBrush = BarLine,
BorderThickness = new Thickness(0, 0, 0, 1),
Child = bar
};
window.Content = null;
Grid.SetRow(content, 1);
Grid.SetRow(line, 0);
// What the window shows first, so Tab and the first focus reach it before the bar.
window.Content = new Grid
{
RowDefinitions = new RowDefinitions("Auto,*"),
Children = { content, line }
};
}
/// <summary>The size and place of the screen's working area, which gamescope then shows as it is.</summary>
public static void FillScreen(Window window)
{
var screen = window.Screens.ScreenFromWindow(window)
?? window.Screens.ScreenFromPoint(window.Position)
?? window.Screens.Primary;
if (screen is null)
return;
var area = screen.WorkingArea;
double width = area.Width / screen.Scaling;
double height = area.Height / screen.Scaling;
window.SizeToContent = SizeToContent.Manual;
window.MinWidth = Math.Min(window.MinWidth, width);
window.MinHeight = Math.Min(window.MinHeight, height);
window.MaxWidth = Math.Max(window.MaxWidth, width);
window.MaxHeight = Math.Max(window.MaxHeight, height);
window.Position = area.Position;
window.Width = width;
window.Height = height;
}
}
+10 -4
View File
@@ -53,6 +53,13 @@ public sealed class SimulatorSettings
public bool LogMissingVehicleFiles; public bool LogMissingVehicleFiles;
public int RenderEngine; public int RenderEngine;
/// <summary>
/// The file's gfxrenderer word where it is none the starter knows - vulkan, written in by
/// hand for a build that has it: written back as it is until another renderer is chosen.
/// </summary>
public string? RendererWord;
public int Width = 1280; public int Width = 1280;
public int Height = 720; public int Height = 720;
public int BufferScalePercent = 100; public int BufferScalePercent = 100;
@@ -197,11 +204,10 @@ public sealed class SimulatorSettings
public static readonly string[] RenderEngines = { "default", "legacy", "simple" }; public static readonly string[] RenderEngines = { "default", "legacy", "simple" };
/// <summary> /// <summary>
/// The words of the file that stay as they are while the choice stands: those application.cpp /// The words the starter places among <see cref="RenderEngines"/>: those application.cpp on
/// on master knows, but "experimental". Any other word starts the full renderer with a line in /// master knows, but "experimental". Any other word is kept as <see cref="RendererWord"/>.
/// the log, so a save puts "default" in its place.
/// </summary> /// </summary>
public static bool KeptRendererWord(string? word) => public static bool KnownRendererWord(string? word) =>
word?.Trim().ToLowerInvariant() is "default" or "legacy" or "simple" or "simpleshader" or "off"; word?.Trim().ToLowerInvariant() is "default" or "legacy" or "simple" or "simpleshader" or "off";
/// <summary>Where <paramref name="word"/> stands among <see cref="RenderEngines"/>, as the simulator reads it.</summary> /// <summary>Where <paramref name="word"/> stands among <see cref="RenderEngines"/>, as the simulator reads it.</summary>
+114
View File
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using StarterNG.Domain.Settings;
namespace StarterNG.Infrastructure;
/// <summary>An adapter as DXGI describes it (DXGI_ADAPTER_DESC1).</summary>
/// <param name="DedicatedVideoMemory">The card's own memory; for a card in a processor, the share the firmware sets aside.</param>
public sealed record DxgiAdapter(string Description, uint VendorId, ulong DedicatedVideoMemory, uint Flags);
/// <summary>
/// The graphics cards of a Windows machine as DXGI lists them: the adapters Windows
/// draws with, whose drivers the simulator's OpenGL runs on too. The registry's list of
/// video devices is what each driver chose to write there, and some leave their card out of it.
/// </summary>
public static unsafe class DxgiAdapters
{
private const uint MicrosoftVendor = 0x1414;
private const uint SoftwareFlag = 2; // DXGI_ADAPTER_FLAG_SOFTWARE
private const int NotFound = unchecked((int)0x887A0002); // DXGI_ERROR_NOT_FOUND
private const int MostAdapters = 64;
private static readonly Guid FactoryInterface = new("770aae78-f26f-4dba-a829-253c83d1b387"); // IDXGIFactory1
/// <summary>The cards among the adapters: not the Microsoft Basic Render Driver or any other software one.</summary>
public static IReadOnlyList<GraphicsCard> Cards(IEnumerable<DxgiAdapter> adapters) =>
adapters
.Where(adapter => (adapter.Flags & SoftwareFlag) == 0 && adapter.VendorId != MicrosoftVendor)
.Select(adapter => new GraphicsCard(adapter.Description.Trim(), (long)adapter.DedicatedVideoMemory))
.Where(card => card.Name.Length > 0)
// Two of the same card tell no more than one, as in the registry's list.
.DistinctBy(card => card.Name)
.ToList();
/// <summary>Every adapter DXGI lists, software ones too; null when DXGI could not be asked.</summary>
[SupportedOSPlatform("windows")]
public static IReadOnlyList<DxgiAdapter>? Read()
{
IntPtr factory;
try
{
Guid iid = FactoryInterface;
if (CreateDXGIFactory1(&iid, &factory) < 0 || factory == IntPtr.Zero)
return null;
}
catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException)
{
return null;
}
try
{
// IDXGIFactory1::EnumAdapters1, after IUnknown's 3, IDXGIObject's 4 and IDXGIFactory's 5.
var enumAdapters1 = (delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr*, int>)Method(factory, 12);
var adapters = new List<DxgiAdapter>();
for (uint i = 0; i < MostAdapters; i++)
{
IntPtr adapter;
int result = enumAdapters1(factory, i, &adapter);
if (result == NotFound)
break;
if (result < 0 || adapter == IntPtr.Zero)
return null;
try
{
// IDXGIAdapter1::GetDesc1, after IUnknown's 3, IDXGIObject's 4 and IDXGIAdapter's 3.
var getDesc1 = (delegate* unmanaged[Stdcall]<IntPtr, AdapterDesc1*, int>)Method(adapter, 10);
AdapterDesc1 desc;
if (getDesc1(adapter, &desc) >= 0)
adapters.Add(new DxgiAdapter(new string(desc.Description), desc.VendorId,
desc.DedicatedVideoMemory, desc.Flags));
}
finally
{
Release(adapter);
}
}
return adapters;
}
finally
{
Release(factory);
}
}
private static void* Method(IntPtr instance, int slot) => (*(void***)instance)[slot];
private static void Release(IntPtr instance) =>
((delegate* unmanaged[Stdcall]<IntPtr, uint>)Method(instance, 2))(instance);
[DllImport("dxgi.dll", ExactSpelling = true)]
private static extern int CreateDXGIFactory1(Guid* riid, IntPtr* factory);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct AdapterDesc1
{
public fixed char Description[128];
public uint VendorId;
public uint DeviceId;
public uint SubSysId;
public uint Revision;
public nuint DedicatedVideoMemory;
public nuint DedicatedSystemMemory;
public nuint SharedSystemMemory;
public uint AdapterLuidLow;
public int AdapterLuidHigh;
public uint Flags;
}
}
+29 -4
View File
@@ -30,14 +30,20 @@ public sealed class GraphicsCards
private readonly IEnvironment _environment; private readonly IEnvironment _environment;
private readonly LinuxGpus _gpus; private readonly LinuxGpus _gpus;
private readonly Func<IReadOnlyList<string>> _nvidiaSmi; private readonly Func<IReadOnlyList<string>> _nvidiaSmi;
private readonly Func<IReadOnlyList<DxgiAdapter>?> _dxgi;
private readonly Func<IReadOnlyList<GraphicsCard>> _registry;
public GraphicsCards(IFileSystem files, IEnvironment environment, LinuxGpus gpus, public GraphicsCards(IFileSystem files, IEnvironment environment, LinuxGpus gpus,
Func<IReadOnlyList<string>>? nvidiaSmi = null) Func<IReadOnlyList<string>>? nvidiaSmi = null,
Func<IReadOnlyList<DxgiAdapter>?>? dxgi = null,
Func<IReadOnlyList<GraphicsCard>>? registry = null)
{ {
_files = files; _files = files;
_environment = environment; _environment = environment;
_gpus = gpus; _gpus = gpus;
_nvidiaSmi = nvidiaSmi ?? AskNvidiaSmi; _nvidiaSmi = nvidiaSmi ?? AskNvidiaSmi;
_dxgi = dxgi ?? AskDxgi;
_registry = registry ?? ReadRegistry;
} }
/// <summary>Takes a while on Linux, where the PCI list is read: not for the UI thread.</summary> /// <summary>Takes a while on Linux, where the PCI list is read: not for the UI thread.</summary>
@@ -46,15 +52,34 @@ public sealed class GraphicsCards
IEnumerable<GraphicsCard> cards = Array.Empty<GraphicsCard>(); IEnumerable<GraphicsCard> cards = Array.Empty<GraphicsCard>();
if (_environment.IsLinux) if (_environment.IsLinux)
cards = FromLinux(); cards = FromLinux();
else if (_environment.IsWindows && OperatingSystem.IsWindows()) else if (_environment.IsWindows)
cards = FromRegistry(); cards = FromWindows();
// A program goes to the discrete card, on Windows by its own request. // A program goes to the discrete card, on Windows by its own request.
return cards.OrderBy(card => card.SharedMemory).ThenByDescending(card => card.MemoryBytes).ToList(); return cards.OrderBy(card => card.SharedMemory).ThenByDescending(card => card.MemoryBytes).ToList();
} }
/// <summary>
/// DXGI's list, the adapters the simulator's OpenGL runs on. The registry's list of
/// video devices only when DXGI cannot be asked or lists no card: there each driver
/// writes what it chooses, and some leave their card out (an RTX 3060 beside a Ryzen's
/// Radeon was missing from it).
/// </summary>
private IReadOnlyList<GraphicsCard> FromWindows()
{
var adapters = _dxgi();
var cards = adapters is null ? Array.Empty<GraphicsCard>() : DxgiAdapters.Cards(adapters);
return cards.Count > 0 ? cards : _registry();
}
private static IReadOnlyList<DxgiAdapter>? AskDxgi() =>
OperatingSystem.IsWindows() ? DxgiAdapters.Read() : null;
private static IReadOnlyList<GraphicsCard> ReadRegistry() =>
OperatingSystem.IsWindows() ? FromRegistry() : Array.Empty<GraphicsCard>();
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]
private static IEnumerable<GraphicsCard> FromRegistry() private static IReadOnlyList<GraphicsCard> FromRegistry()
{ {
try try
{ {
@@ -91,7 +91,9 @@ public sealed class SettingsSerializer
s.VirtualShunting = c.GetBool("ai.trainman", true); s.VirtualShunting = c.GetBool("ai.trainman", true);
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false); s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default")); string renderer = c.GetString("gfxrenderer", "default").Trim();
s.RenderEngine = SimulatorSettings.RenderEngineOf(renderer);
s.RendererWord = renderer.Length > 0 && !SimulatorSettings.KnownRendererWord(renderer) ? renderer : null;
s.Width = c.GetInt("width", 1280); s.Width = c.GetInt("width", 1280);
s.Height = c.GetInt("height", 720); s.Height = c.GetInt("height", 720);
s.BufferScalePercent = ReadBufferScale(c); s.BufferScalePercent = ReadBufferScale(c);
@@ -226,13 +228,8 @@ public sealed class SettingsSerializer
{ {
"gfx.postfx.tonemapping", "gfx.postfx.tonemapping",
"starter.developertools", "starter.developertools",
// The OpenGL 4.6 and Vulkan renderers', which the simulator's master does not have. // The keys of the OpenGL 4.6 and Vulkan renderers (gfx.vulkan.device, gfx.raytracing...) are not here:
"gfx.antialiasing", "gfx.buffer.percent", "gfx.vulkan.device", "gfx.dlss.preset", "gfx.framegeneration", // written in by hand for a build that has them, they stay as the file has them.
"gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.ssr", "gfx.lights.clustered", "gfx.lights.shadows",
"gfx.contactshadows", "gfx.shadow.sdsm", "gfx.postfx.ao", "gfx.postfx.ao.lighting", "gfx.postfx.ao.quality",
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.bounce", "gfx.cabprobe.reflections", "gfx.fog",
"gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows", "gfx.postfx.bloom", "gfx.postfx.autoexposure",
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density", "gfx.precipitation.particles",
}; };
/// <summary> /// <summary>
@@ -286,7 +283,7 @@ public sealed class SettingsSerializer
c.SetBool("ai.trainman", s.VirtualShunting); c.SetBool("ai.trainman", s.VirtualShunting);
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles); c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]); c.Set("gfxrenderer", s.RendererWord ?? SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
c.SetInt("width", s.Width); c.SetInt("width", s.Width);
c.SetInt("height", s.Height); c.SetInt("height", s.Height);
c.SetInt("starter.bufferscale", s.BufferScalePercent); c.SetInt("starter.bufferscale", s.BufferScalePercent);
+14 -4
View File
@@ -6,8 +6,15 @@ using Avalonia;
namespace StarterNG.Infrastructure; namespace StarterNG.Infrastructure;
/// <summary> /// <summary>
/// Drawn by the processor instead of the graphics card, for a machine on which the /// On Windows the processor draws the starter's windows, and each frame is copied into its window
/// window comes up empty. Each platform reads only its own options, so both are given. /// by GDI. Every way of the graphics card's failed on some machine: Avalonia's WinUI composition
/// visual left windows black on Windows 11 25H2, the Steam overlay drew its frame counter over a
/// window's own swap chain, and with DirectComposition the starter vanished a few seconds after its
/// window came up on a Windows 10 machine with a GTX 1650, without a word in its log. A frame copied
/// by GDI has no swap chain for an overlay to hook, and lists, text and pictures are no work for the
/// processor.
/// On X11 the graphics card draws, unless <see cref="Switch"/> asks the processor, for a machine on
/// which the window comes up empty. Each platform reads only its own options.
/// </summary> /// </summary>
public static class SoftwareRender public static class SoftwareRender
{ {
@@ -27,6 +34,9 @@ public static class SoftwareRender
RenderingMode = new[] { X11RenderingMode.Software } RenderingMode = new[] { X11RenderingMode.Software }
}; };
public static AppBuilder ApplyTo(AppBuilder builder) => public static AppBuilder ApplyTo(AppBuilder builder, IEnumerable<string> args)
builder.With(Win32Options).With(X11Options); {
builder.With(Win32Options);
return AskedIn(args) ? builder.With(X11Options) : builder;
}
} }
@@ -265,10 +265,14 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
var sb = new StringBuilder(); var sb = new StringBuilder();
foreach (string line in text.Split('\n')) foreach (string line in text.Split('\n'))
{ {
// Both kinds the game skips: "68 //MaxLoad" passes one include parameter, not two.
string stripped = line; string stripped = line;
int comment = stripped.IndexOf('#'); int comment = stripped.IndexOf('#');
if (comment >= 0) if (comment >= 0)
stripped = stripped[..comment]; stripped = stripped[..comment];
int slashes = stripped.IndexOf("//", StringComparison.Ordinal);
if (slashes >= 0)
stripped = stripped[..slashes];
sb.Append(stripped).Append(' '); sb.Append(stripped).Append(' ');
} }
+6 -3
View File
@@ -57,6 +57,9 @@ public partial class MainWindow : Window
ExtendClientAreaTitleBarHeightHint = TitleBarHeight; ExtendClientAreaTitleBarHeightHint = TitleBarHeight;
FitToScreen(); FitToScreen();
// Gamescope does not maximize a window: it would stretch the first size over the screen.
if (GamescopeWindows.Active)
GamescopeWindows.FillScreen(this);
// Ahead of the layout a new size starts: changed during it, the bar keeps the old width. // Ahead of the layout a new size starts: changed during it, the bar keeps the old width.
Resized += (_, e) => FitTopBar(e.ClientSize.Width); Resized += (_, e) => FitTopBar(e.ClientSize.Width);
Opened += (_, _) => FitTopBar(ClientSize.Width); Opened += (_, _) => FitTopBar(ClientSize.Width);
@@ -432,7 +435,7 @@ public partial class MainWindow : Window
private bool wantsMaximized() private bool wantsMaximized()
{ {
// make sure the window fills the whole screen on gamescope sessions // make sure the window fills the whole screen on gamescope sessions
if (Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP") == "gamescope") if (GamescopeWindows.Active)
return true; return true;
// catch being launched via Steam Big Picture mode as well // catch being launched via Steam Big Picture mode as well
@@ -845,7 +848,7 @@ public partial class MainWindow : Window
{ {
if (_askingAboutSettings || (DateTime.UtcNow - _openedUtc).TotalSeconds < 3) if (_askingAboutSettings || (DateTime.UtcNow - _openedUtc).TotalSeconds < 3)
return; return;
if (!AppServices.Current.SettingsStore.IsConfigNewerOnDisk()) if (!AppServices.Current.SettingsStore.HasChangeOnDiskToAskAbout())
return; return;
_askingAboutSettings = true; _askingAboutSettings = true;
@@ -862,7 +865,7 @@ public partial class MainWindow : Window
SettingsView?.ReloadFromSettings(); SettingsView?.ReloadFromSettings();
} }
else else
AppServices.Current.SettingsStore.TouchConfigAge(); AppServices.Current.SettingsStore.LeaveChangeOnDisk();
} }
finally finally
{ {
+7 -5
View File
@@ -10,7 +10,8 @@ namespace StarterNG;
static class Program static class Program
{ {
private static bool _softwareRender; // What --software-render is looked for in; none for the designer, which calls BuildAvaloniaApp itself.
private static string[] _args = Array.Empty<string>();
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args)
@@ -19,7 +20,7 @@ static class Program
var graphics = SystemGraphicsLibraries.TakeOnWindows(); var graphics = SystemGraphicsLibraries.TakeOnWindows();
graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly); graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly);
_softwareRender = SoftwareRender.AskedIn(args); _args = args;
// Composition root first: everything below, including the crash handlers, // Composition root first: everything below, including the crash handlers,
// resolves its collaborators from this graph. // resolves its collaborators from this graph.
@@ -73,13 +74,14 @@ static class Program
}; };
} }
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) => // On Windows the processor draws; on X11 the graphics card, unless --software-render.
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder; private static AppBuilder WithSoftwareRender(this AppBuilder builder) =>
SoftwareRender.ApplyTo(builder, _args);
public static AppBuilder BuildAvaloniaApp() public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>() => AppBuilder.Configure<App>()
.UsePlatformDetect() .UsePlatformDetect()
.WithSoftwareRenderIfAsked() .WithSoftwareRender()
.WithInterFont() .WithInterFont()
.WithDiagnosticsLogging() .WithDiagnosticsLogging()
.AfterSetup(_ => LogUiExceptions()); .AfterSetup(_ => LogUiExceptions());
+2
View File
@@ -7,6 +7,8 @@
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport> <BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<!-- DXGI is asked through function pointers, which NativeAOT compiles without reflection. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest>app.manifest</ApplicationManifest> <ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>Assets\starter.ico</ApplicationIcon> <ApplicationIcon>Assets\starter.ico</ApplicationIcon>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault> <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
+39 -3
View File
@@ -25,7 +25,7 @@ public partial class Settings
private void ShowGraphics(SimulatorSettings s) private void ShowGraphics(SimulatorSettings s)
{ {
RenderEngineCb.SelectedIndex = s.RenderEngine; ShowRenderer(s);
SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing)); SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing));
_fullscreenAsRead = s.Fullscreen; _fullscreenAsRead = s.Fullscreen;
SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed)); SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed));
@@ -35,8 +35,18 @@ public partial class Settings
private void CaptureGraphics(SimulatorSettings s) private void CaptureGraphics(SimulatorSettings s)
{ {
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex); if (_fileRendererItem is not null && ReferenceEquals(RenderEngineCb.SelectedItem, _fileRendererItem))
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb)); {
s.RenderEngine = 0;
s.RendererWord = _fileRendererItem.Tag as string;
}
else
{
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
s.RendererWord = null;
}
if (!ShowsFileValue(AntiAliasingCb))
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
s.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty; s.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty;
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode; string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
@@ -45,6 +55,32 @@ public partial class Settings
s.Fullscreen = mode == BorderlessMode ? _fullscreenAsRead : mode == FullscreenMode; s.Fullscreen = mode == BorderlessMode ? _fullscreenAsRead : mode == FullscreenMode;
} }
/// <summary>The renderer the file names in a word the list does not offer, listed under that word.</summary>
private ComboBoxItem? _fileRendererItem;
private void ShowRenderer(SimulatorSettings s)
{
if (_fileRendererItem is not null)
{
if (s.RendererWord is not null && Equals(_fileRendererItem.Tag, s.RendererWord))
{
RenderEngineCb.SelectedItem = _fileRendererItem;
return;
}
RenderEngineCb.Items.Remove(_fileRendererItem);
_fileRendererItem = null;
}
if (s.RendererWord is { } word)
{
_fileRendererItem = new ComboBoxItem { Tag = word, Content = word };
RenderEngineCb.Items.Add(_fileRendererItem);
RenderEngineCb.SelectedItem = _fileRendererItem;
}
else
RenderEngineCb.SelectedIndex = s.RenderEngine;
}
// ── How the simulator shows: full screen, borderless or in a window ────── // ── How the simulator shows: full screen, borderless or in a window ──────
private const string FullscreenMode = "fullscreen"; private const string FullscreenMode = "fullscreen";
+126 -19
View File
@@ -416,9 +416,19 @@ public partial class Settings : UserControl, ISettingsCapture
// A reloaded file may name another simulator, or start a server. // A reloaded file may name another simulator, or start a server.
RefreshDerivedRows(); RefreshDerivedRows();
UpdateUnknownValues();
UpdateGpuNote(); UpdateGpuNote();
NoteShownValues(); NoteShownValues();
// The language is the starter's to keep (App.Initialize), and a value written another way is no unknown one.
var store = AppServices.Current.SettingsStore;
_unlikeOnScreen = new HashSet<string>(
_shownUnlikeSettings.Where(pair => !string.Equals(pair.Key, "lang", StringComparison.OrdinalIgnoreCase) &&
!store.FileMeans(pair.Key, pair.Value.Shown))
.Select(pair => pair.Key),
StringComparer.OrdinalIgnoreCase);
ShowFileValueItems(FileValues());
// A list at the file's value now hands over what the settings hold.
NoteShownValues();
UpdateUnknownValues();
UpdatePresetMarks(); UpdatePresetMarks();
} }
@@ -533,12 +543,24 @@ public partial class Settings : UserControl, ISettingsCapture
/// Puts <paramref name="s"/> on the screen as edits waiting for Save: what it /// Puts <paramref name="s"/> on the screen as edits waiting for Save: what it
/// changes marks the screen dirty, as a change by hand would. /// changes marks the screen dirty, as a change by hand would.
/// </summary> /// </summary>
private void ShowAsEdits(SimulatorSettings s) /// <param name="chosen">The keys these edits choose; a list at the file's value keeps it for any other.</param>
private void ShowAsEdits(SimulatorSettings s, IReadOnlyCollection<string> chosen)
{ {
var store = AppServices.Current.SettingsStore;
var held = store.Render(AppServices.Current.Settings);
var shown = store.Render(s);
var atFileValue = FileValueLists()
.Where(pair => ShowsFileValue(pair.List) && !chosen.Contains(pair.Key, StringComparer.OrdinalIgnoreCase) &&
held.GetValueOrDefault(pair.Key) == shown.GetValueOrDefault(pair.Key))
.Select(pair => (pair.List, Item: pair.List.SelectedItem))
.ToList();
_showingEdits = true; _showingEdits = true;
try try
{ {
ShowValues(s); ShowValues(s);
foreach (var (list, item) in atFileValue)
list.SelectedItem = item;
} }
finally finally
{ {
@@ -628,7 +650,7 @@ public partial class Settings : UserControl, ISettingsCapture
{ {
var trial = Trial(); var trial = Trial();
var applied = _presetMemory.Apply(preset, trial); var applied = _presetMemory.Apply(preset, trial);
ShowAsEdits(trial); ShowAsEdits(trial, applied.ChosenKeys.ToList());
// Chosen as a whole, its values are choices, not ones the screen could not show. // Chosen as a whole, its values are choices, not ones the screen could not show.
ForgetShown(applied.ChosenKeys); ForgetShown(applied.ChosenKeys);
@@ -640,7 +662,7 @@ public partial class Settings : UserControl, ISettingsCapture
private void ApplyGroupLevel(GraphicsGroup group, GraphicsPreset level) private void ApplyGroupLevel(GraphicsGroup group, GraphicsPreset level)
{ {
var trial = Groups.Apply(group, level, Trial()); var trial = Groups.Apply(group, level, Trial());
ShowAsEdits(trial); ShowAsEdits(trial, group.Keys.ToList());
foreach (string key in group.Keys.Where(key => SimulatorKeys.All.Any(known => known.Key == key))) foreach (string key in group.Keys.Where(key => SimulatorKeys.All.Any(known => known.Key == key)))
_keyRows.Show(key, SimulatorKeys.Named(key).RawIn(trial)); _keyRows.Show(key, SimulatorKeys.Named(key).RawIn(trial));
@@ -825,9 +847,11 @@ public partial class Settings : UserControl, ISettingsCapture
private void NoteShownValues() => private void NoteShownValues() =>
_shownUnlikeSettings = AppServices.Current.SettingsStore.ShownUnlike(Trial()); _shownUnlikeSettings = AppServices.Current.SettingsStore.ShownUnlike(Trial());
/// <summary><paramref name="keys"/> are the player's choice now: a value of the file the screen could not show goes on a save.</summary>
private void ForgetShown(IEnumerable<string> keys) private void ForgetShown(IEnumerable<string> keys)
{ {
var forgotten = new HashSet<string>(keys, StringComparer.OrdinalIgnoreCase); var forgotten = new HashSet<string>(keys, StringComparer.OrdinalIgnoreCase);
AppServices.Current.SettingsStore.Choose(forgotten);
_shownUnlikeSettings = _shownUnlikeSettings _shownUnlikeSettings = _shownUnlikeSettings
.Where(pair => !forgotten.Contains(pair.Key)) .Where(pair => !forgotten.Contains(pair.Key))
.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase); .ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
@@ -855,7 +879,7 @@ public partial class Settings : UserControl, ISettingsCapture
} }
private string SelectedRenderer() => private string SelectedRenderer() =>
SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full"; SelectedTag(RenderEngineCb) ?? SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer()); private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer());
@@ -882,7 +906,8 @@ public partial class Settings : UserControl, ISettingsCapture
s.InvertMouseVertical = IsChecked(MouseVertInvertCb); s.InvertMouseVertical = IsChecked(MouseVertInvertCb);
s.IgnoreGamepad = IsChecked(GamepadIgnoreCb); s.IgnoreGamepad = IsChecked(GamepadIgnoreCb);
s.FeedbackMode = Math.Max(0, FeedbackCb.SelectedIndex); // A list at the file's own value leaves the setting as it was read.
if (!ShowsFileValue(FeedbackCb)) s.FeedbackMode = Math.Max(0, FeedbackCb.SelectedIndex);
s.FeedbackPort = (int)(FeedbackPortNud.Value ?? 888); s.FeedbackPort = (int)(FeedbackPortNud.Value ?? 888);
CaptureUart(s); CaptureUart(s);
@@ -894,7 +919,7 @@ public partial class Settings : UserControl, ISettingsCapture
s.LogMissingVehicleFiles = IsChecked(LogMissingVehicleFilesCb); s.LogMissingVehicleFiles = IsChecked(LogMissingVehicleFilesCb);
CaptureGraphics(s); CaptureGraphics(s);
s.Gpu = SelectedGpu(); if (!ShowsFileValue(GpuCb)) s.Gpu = SelectedGpu();
ReadResolution(s); ReadResolution(s);
s.BufferScalePercent = (int)bufferScale.Value; s.BufferScalePercent = (int)bufferScale.Value;
s.MaxTextureSize = 1 << (int)textureResolutionSlider.Value; s.MaxTextureSize = 1 << (int)textureResolutionSlider.Value;
@@ -915,8 +940,8 @@ public partial class Settings : UserControl, ISettingsCapture
s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value; s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value;
s.ShadowProjectionRange = (int)shaderRange.Value; s.ShadowProjectionRange = (int)shaderRange.Value;
s.CabShadowsRange = (int)_cabShadows.Value; s.CabShadowsRange = (int)_cabShadows.Value;
s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1; if (!ShowsFileValue(ShadowDisplayCb)) s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex); if (!ShowsFileValue(ReflectionsDetailsCb)) s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75); s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75);
s.PythonScreens = IsChecked(RenderScreensCb); s.PythonScreens = IsChecked(RenderScreensCb);
s.PythonThreadedUpload = IsChecked(RenderScreensThreadCb); s.PythonThreadedUpload = IsChecked(RenderScreensThreadCb);
@@ -951,12 +976,14 @@ public partial class Settings : UserControl, ISettingsCapture
s.AmbientVolume = (int)AmbientVolumeSlider.Value; s.AmbientVolume = (int)AmbientVolumeSlider.Value;
s.SkipPipeline = IsChecked(SkipPipelineCb); s.SkipPipeline = IsChecked(SkipPipelineCb);
s.DebugLogVisible = IsChecked(DebugLogVisibleCb); s.DebugLogVisible = IsChecked(DebugLogVisibleCb);
s.PythonScreenUpdateRate = ParsePriorityTag((PyScreenPriorityCb.SelectedItem as ComboBoxItem)?.Tag); if (!ShowsFileValue(PyScreenPriorityCb))
s.PythonScreenUpdateRate = ParsePriorityTag((PyScreenPriorityCb.SelectedItem as ComboBoxItem)?.Tag);
s.AutoCloseStarter = IsChecked(AutoCloseStarterCb); s.AutoCloseStarter = IsChecked(AutoCloseStarterCb);
s.LargeThumbnails = IsChecked(LargeThumbnailsCb); s.LargeThumbnails = IsChecked(LargeThumbnailsCb);
s.AutoExpandSceneryTree = IsChecked(AutoExpandTreeCb); s.AutoExpandSceneryTree = IsChecked(AutoExpandTreeCb);
s.ReadyOverride = (ConsistReadyOverride)Math.Clamp(ReadyOverrideCb.SelectedIndex, 0, 2); if (!ShowsFileValue(ReadyOverrideCb))
s.ReadyOverride = (ConsistReadyOverride)Math.Clamp(ReadyOverrideCb.SelectedIndex, 0, 2);
s.CompressTextures = IsChecked(CompressTexCb); s.CompressTextures = IsChecked(CompressTexCb);
s.ScaleSpeculars = IsChecked(ScaleSpecularsCb); s.ScaleSpeculars = IsChecked(ScaleSpecularsCb);
@@ -1420,6 +1447,8 @@ public partial class Settings : UserControl, ISettingsCapture
store.KeepCopy(".before-standard"); store.KeepCopy(".before-standard");
var moved = AdvancedKeys(); var moved = AdvancedKeys();
// A value the starter does not know, or a control cannot show, is put right too.
moved.UnionWith(FileValues().Keys);
moved.ExceptWith(SettingsStore.KeptOnMoveToStandard); moved.ExceptWith(SettingsStore.KeptOnMoveToStandard);
_clamping = true; _clamping = true;
try try
@@ -1447,7 +1476,7 @@ public partial class Settings : UserControl, ISettingsCapture
/// <summary>Puts <paramref name="keys"/> at the simulator's own values, as edits waiting for Save.</summary> /// <summary>Puts <paramref name="keys"/> at the simulator's own values, as edits waiting for Save.</summary>
private void ShowDefaults(IReadOnlyCollection<string> keys) private void ShowDefaults(IReadOnlyCollection<string> keys)
{ {
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys)); ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys), keys);
foreach (string key in keys) foreach (string key in keys)
_keyRows.ShowDefault(key); _keyRows.ShowDefault(key);
// Put back by hand, a value is a choice like any other. // Put back by hand, a value is a choice like any other.
@@ -1505,10 +1534,86 @@ public partial class Settings : UserControl, ISettingsCapture
private bool Advanced => AppServices.Current.Settings.AdvancedSettings; private bool Advanced => AppServices.Current.Settings.AdvancedSettings;
/// <summary>Under each setting, the value of eu07.ini for it the starter cannot read, as the file has it.</summary> /// <summary>A value of eu07.ini a list does not offer, listed under the file's own words.</summary>
private sealed record FileValue(string Raw);
/// <summary>The lists that take a value of the file they do not offer, with their keys.</summary>
private IEnumerable<(ComboBox List, string Key)> FileValueLists() => new[]
{
(FeedbackCb, "feedbackmode"), (GpuCb, "starter.gpu"), (ShadowDisplayCb, "gfx.shadow.rank.cutoff"),
(ReflectionsDetailsCb, "gfx.reflections.fidelity"), (PyScreenPriorityCb, "python.updatetime"),
(ReadyOverrideCb, "starter.batterydefault"), (AntiAliasingCb, "multisampling")
};
private static bool ShowsFileValue(ComboBox list) => list.SelectedItem is ComboBoxItem { Tag: FileValue };
// Keys the controls showed otherwise than the file has them when it was read.
private HashSet<string> _unlikeOnScreen = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The values of eu07.ini the starter does not know, or that a control cannot show, as the
/// file writes them, but for those the player has set since.
/// </summary>
private Dictionary<string, string> FileValues()
{
var store = AppServices.Current.SettingsStore;
var values = new Dictionary<string, string>(store.UnreadableValues(), StringComparer.OrdinalIgnoreCase);
foreach (string key in _unlikeOnScreen)
if (!values.ContainsKey(key) && store.FileValueOf(key) is { } raw)
values[key] = raw;
foreach (string key in values.Keys.Where(store.IsChosen).ToList())
values.Remove(key);
return values;
}
/// <summary>
/// The lists put at the file's value where they do not offer it, chosen as it is until the player picks another.
/// </summary>
private void ShowFileValueItems(IReadOnlyDictionary<string, string> values)
{
WhileLoading(() =>
{
foreach (var (list, key) in FileValueLists())
{
foreach (var item in list.Items.OfType<ComboBoxItem>().Where(item => item.Tag is FileValue).ToList())
list.Items.Remove(item);
if (!values.TryGetValue(key, out string? raw))
continue;
var shown = new ComboBoxItem { Tag = new FileValue(raw), Content = raw };
list.Items.Add(shown);
list.SelectedItem = shown;
}
});
}
/// <summary>The keys of the row <paramref name="control"/> sits in.</summary>
private static string[] RowKeys(Control control) =>
(control.FindLogicalAncestorOfType<SettingRow>()?.ConfigKey ?? string.Empty)
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
/// <summary>
/// A control moved: its keys are the player's choice now, written as the screen has them -
/// but for a list put back at the file's own value, which stays as the file has it.
/// </summary>
private void ChosenByHand(Control control)
{
if (_loading || _showingEdits)
return;
var keys = RowKeys(control);
if (keys.Length == 0)
return;
if (control is ComboBox list &&
(ShowsFileValue(list) || (_fileRendererItem is not null && ReferenceEquals(list.SelectedItem, _fileRendererItem))))
AppServices.Current.SettingsStore.Unchoose(keys);
else
ForgetShown(keys);
UpdateUnknownValues();
}
/// <summary>Under each setting, the value of eu07.ini for it the starter does not know or cannot show, as the file has it.</summary>
private void UpdateUnknownValues() private void UpdateUnknownValues()
{ {
var unreadable = AppServices.Current.SettingsStore.UnreadableValues(); var unreadable = FileValues();
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>()) foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
{ {
var keys = (row.ConfigKey ?? string.Empty) var keys = (row.ConfigKey ?? string.Empty)
@@ -1698,16 +1803,16 @@ public partial class Settings : UserControl, ISettingsCapture
case { Tag: SimulatorKey }: case { Tag: SimulatorKey }:
break; break;
case CheckBox cb: case CheckBox cb:
cb.IsCheckedChanged += (_, _) => OnControlChanged(); cb.IsCheckedChanged += (_, _) => OnControlChanged(cb);
break; break;
case Slider slider: case Slider slider:
slider.ValueChanged += (_, _) => OnControlChanged(); slider.ValueChanged += (_, _) => OnControlChanged(slider);
break; break;
case ComboBox combo: case ComboBox combo:
combo.SelectionChanged += (_, _) => OnControlChanged(); combo.SelectionChanged += (_, _) => OnControlChanged(combo);
break; break;
case NumericUpDown nud: case NumericUpDown nud:
nud.ValueChanged += (_, _) => OnControlChanged(); nud.ValueChanged += (_, _) => OnControlChanged(nud);
break; break;
} }
} }
@@ -1729,8 +1834,10 @@ public partial class Settings : UserControl, ISettingsCapture
edited(); edited();
}; };
private void OnControlChanged() private void OnControlChanged(Control? control = null)
{ {
if (control is not null)
ChosenByHand(control);
MarkDirty(); MarkDirty();
QueuePresetMarks(); QueuePresetMarks();
} }
File diff suppressed because it is too large Load Diff
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Brings the language files of the starter in line with en.xml.
For every language file in StarterNG/startercfg/lang (or the codes given):
- a key en.xml has and the language lacks is added with the English text, right after the
key it follows in en.xml, and marked <!-- untranslated -->;
- a key en.xml no longer has is removed.
Keys the starter falls back to English for by itself (ending in "Desc", starting with "Cmd.")
are only added with --all. Everything else in the file - comments, order, line endings - stays
as it is.
python tools/sync_lang.py # every language
python tools/sync_lang.py zh cz # only these
python tools/sync_lang.py --check # only report; exit code 1 when a file is out of line
"""
import argparse
import re
import sys
from pathlib import Path
LANG_DIR = Path(__file__).resolve().parent.parent / "StarterNG" / "startercfg" / "lang"
STRING = re.compile(r'<String key="(?P<key>[^"]+)">.*?</String>', re.DOTALL)
LANGUAGE_TAG = re.compile(r"<Language\b[^>]*>")
UNTRANSLATED = "<!-- untranslated -->"
def is_optional(key):
return key.endswith("Desc") or key.startswith("Cmd.")
def read(path):
raw = path.read_bytes()
bom = raw.startswith(b"\xef\xbb\xbf")
text = raw[3 if bom else 0:].decode("utf-8")
newline = "\r\n" if "\r\n" in text else "\n"
return text, bom, newline
def write(path, text, bom):
path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
def strings(text):
"""key -> match, in the order of the file; a key given twice keeps its first."""
found = {}
for match in STRING.finditer(text):
found.setdefault(match.group("key"), match)
return found
def line_start(text, pos):
return text.rfind("\n", 0, pos) + 1
def line_end(text, pos):
"""Just past the newline ending the line that pos is on."""
end = text.find("\n", pos)
return len(text) if end < 0 else end + 1
def removal_span(text, match):
"""The element with its whole lines when nothing but blanks and a comment share them."""
start, end = match.span()
first = line_start(text, start)
last = line_end(text, end)
before = text[first:start]
after = text[end:last].strip()
if before.strip() == "" and (after == "" or (after.startswith("<!--") and after.endswith("-->"))):
return first, last
return start, end
def english_line(en_text, match, newline):
indent = en_text[line_start(en_text, match.start()):match.start()]
if indent.strip():
indent = " "
element = match.group(0).replace("\r\n", "\n").replace("\n", newline)
return f"{indent}{element} {UNTRANSLATED}{newline}"
def insert_position(text, own, en_keys, key, after_tag):
"""Just after the nearest key before this one in en.xml that the file has and keeps."""
for previous in reversed(en_keys[:en_keys.index(key)]):
if previous in own:
return line_end(text, own[previous].end())
return after_tag
def apply_edits(text, edits):
"""edits: (start, end, replacement) on the original text.
Applied from the end so the offsets stay valid. Where a removal starts at the place of an
insert, the removal goes first, or it would take away the inserted line instead of its own.
Inserts at one place keep the order of en.xml.
"""
def order(edit):
index, (start, end, _) = edit
return start, 1 if end > start else 0, index
for _, (start, end, replacement) in sorted(enumerate(edits), key=order, reverse=True):
text = text[:start] + replacement + text[end:]
return text
def synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings):
edits = [(*removal_span(text, own[key]), "") for key in obsolete]
tag = LANGUAGE_TAG.search(text)
if tag is None:
sys.exit(f"{path.name}: no <Language> element")
after_tag = line_end(text, tag.end())
en_keys = list(en_strings)
for key in missing:
anchor = insert_position(text, own, en_keys, key, after_tag)
edits.append((anchor, anchor, english_line(en_text, en_strings[key], newline)))
return apply_edits(text, edits)
def report(name, missing, obsolete, detailed):
print(f"{name}: {len(missing)} to add in English, {len(obsolete)} no longer in en.xml")
if detailed:
for key in missing:
print(f" missing {key}")
for key in obsolete:
print(f" obsolete {key}")
def sync(path, en_text, en_strings, add_optional, check):
"""True when the file was out of line with en.xml (and, without check, is now brought in line)."""
text, bom, newline = read(path)
own = strings(text)
obsolete = [key for key in own if key not in en_strings]
missing = [key for key in en_strings
if key not in own and (add_optional or not is_optional(key))]
if not obsolete and not missing:
print(f"{path.name}: in line with en.xml")
return False
report(path.name, missing, obsolete, check)
if not check:
write(path, synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings), bom)
return True
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("codes", nargs="*", help="language codes, e.g. zh cz; every language when none")
parser.add_argument("--all", action="store_true", help="add the optional keys (*Desc, Cmd.*) too")
parser.add_argument("--check", action="store_true", help="only report, change nothing")
args = parser.parse_args()
en_text, _, _ = read(LANG_DIR / "en.xml")
en_strings = strings(en_text)
if args.codes:
paths = [LANG_DIR / f"{code}.xml" for code in args.codes]
for path in paths:
if not path.is_file():
sys.exit(f"no language file {path}")
else:
paths = sorted(p for p in LANG_DIR.glob("*.xml") if p.name != "en.xml")
out_of_line = False
for path in paths:
out_of_line |= sync(path, en_text, en_strings, args.all, args.check)
return 1 if args.check and out_of_line else 0
if __name__ == "__main__":
sys.exit(main())