Compare commits

...

63 Commits

Author SHA1 Message Date
maj00r 25e58fa8ae fix(editor): the editor opens without a question
The scenery editor starts straight away, as the simulation does; the question
that it works on the scenery file itself goes, with its texts in every language.
2026-12-04 23:27:16 +01:00
maj00r e0a0f46018 fix(editor): no warning that only some simulator builds have the editor
Every simulator build now opens the scenery editor (eu07 -edit), so the
question before it says only what still matters: the editor works on the
scenery file itself, not on the starter's copy. The tip of the new scenery
wizard no longer says the editor is missing from some builds either.
2026-12-04 23:25:20 +01:00
Hirek 98e67b6867 Merge pull request #74 from MaSzyna-EU07/feat/settings-basic-advanced
whole these
2026-12-04 21:44:48 +00:00
Hirek 9656b25532 Merge branch 'main' into feat/settings-basic-advanced 2026-12-04 22:43:14 +01:00
maj00r 381c815528 Merge pull request #69 from MaSzyna-EU07/fix/overcast-labels
fix(weather): the overcast list says what the simulator makes of it, rain and snow among it
2026-12-03 11:24:20 +01:00
maj00r 6d81ec700d Merge pull request #72 from MaSzyna-EU07/feat/standard-crew
feat: in the standard mode the crew of the player's consists can be changed
2026-12-03 11:23:42 +01:00
maj00r 705f2049fd Merge pull request #71 from MaSzyna-EU07/fix/software-render-windows
fix: on Windows the processor draws the starter's windows
2026-12-03 11:23:13 +01:00
maj00r 9583117eea feat: in the standard mode the crew of the player's consists can be changed
The crew button, the crew menu on a card and the crew list in the vehicle
details now work in the standard mode too, for every consist the player may
start in. The simulator's own consists and the decorations keep the crew the
scenario gave them; the advanced mode changes any crew, as before.
2026-12-02 20:33:50 +01:00
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
Hirek a095cdee0c Merge pull request #70 from MaSzyna-EU07/feat/settings-basic-advanced
Feat/settings basic advanced
2026-11-30 19:39:49 +00:00
Hirek 43600f29c6 fix(exit): no box of the starter after eu07_starter.exe or the simulator already said why
Started through eu07_starter.exe, a simulator that failed got two boxes in a
row: the one of eu07_starter.exe, then the starter's own with the exit code.
The starter's box is now left out where the player already has one:
- an error code of the system (0xC...) through eu07_starter.exe: it explained
  the code, or caught the crash the simulator then reported in its own box;
  Ctrl+C (0xC000013A), which it leaves without a word, still gets the box;
- code 1 through eu07_starter.exe with the simulator's log not written since
  the start: eu07_starter.exe did not start it (missing, refused by its checks,
  or the player's No) and said why;
- 0xE0450010, the simulator's own notice of a processor it cannot run on,
  with or without eu07_starter.exe.
The log of the starter still records each of these exits.
2026-11-30 20:37:23 +01:00
Hirek 4a71dd957b feat(exe): on Windows the automatic choice starts eu07_starter.exe
The simulator builds eu07_starter.exe beside eu07.exe (starter/eu07_starter.cpp):
it checks the processor and the libraries first, explains a start the system
refuses with a bare code, writes the minidump of a crash from outside, passes the
arguments on and returns the simulator's exit code. The automatic search now
takes it ahead of eu07.exe on Windows.

A simulator picked by hand stays. Without AVX2 a build without it still comes
first, as the starter would start the AVX2 build. Under Wine nothing changes.
2026-11-30 20:33:36 +01:00
Hirek f791edcb3c Merge remote-tracking branch 'origin/staging' into feat/settings-basic-advanced 2026-11-30 20:29:35 +01:00
Hirek aff8a1b8c9 Merge branch 'main' into feat/settings-basic-advanced 2026-11-30 20:28:54 +01:00
maj00r cb9c8cbb08 test(weather): a rain or snow option is themed in a window and names itself there too 2026-11-30 19:29:18 +01:00
maj00r a87c1ebc4c fix(weather): rain or snow is named by a control of its own, with no reflection binding
The two precipitation options were renamed by a Binding made in code,
which reads its path by reflection: unsafe for the NativeAOT starter
and flagged as such by the analysis. A PrecipitationItem now names
itself from the starter's texts and follows a change of language, and
the weather tab only tells it whether it snows.
2026-11-30 19:22:26 +01:00
maj00r 1aac7faae1 fix(weather): the overcast list says what the simulator makes of it, rain and snow among it
The simulator reads the overcast as clear up to 0.1, clouds up to 1 and
precipitation above it: rain above 1 °C, snow at or below, denser from
1.35 on. A negative value it draws anew from 0 up to its size. The list
named -1.5 "Clear", though it rained one run in three, 1.1 "Cloudy" and
1.5 "Storm", which the simulator has none of, so rain was nowhere to be
picked by name. The list is now clear, light, moderate clouds, cloudy,
light rain and rain, the last two named snow when the temperature set
makes it snow. Random draws only from these, and a negative overcast in
a scenery is shown as random rather than clear.
2026-11-30 19:14:15 +01:00
Hirek 71ec32864f Merge pull request #65 from MaSzyna-EU07/feat/settings-basic-advanced
Settings for new exe
2026-11-30 17:08:00 +00: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
Hirek cbdb7e0c84 fix(lang): sync_lang.py leaves the developer tab's rows to English, as the test does
The developer tab's rows (Ini.*) and the words of its lists (Choice.*) come in
English where a language lacks them (SimulatorKeyRows), and
LocalizationTests counts them optional. sync_lang.py added them to every
language as untranslated copies; now it adds them, as the other optional keys,
only with --all, and --check finds every language in line.
2026-11-30 17:34:29 +01:00
Hirek 493f5bcc23 Merge branch 'main' into feat/settings-basic-advanced
# Conflicts:
#	StarterNG/startercfg/lang/zh.xml
2026-11-30 17:33:57 +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 7c2d259fdc feat(settings): the physical models of the simulator, and Arcade and Realistic levels of realism
The Physics tab has a section of driving realism with the models the simulator
reads (utilities/Globals.cpp):
- couplerphysics: the legacy couplings, or the physical ones (play, give,
  breaking) of the player's train or of every train;
- physics.derailment: off, classic (the simulator's own monitor), physical;
- physics.collisions: classic or physical (the simulator's own);
- physics.trackbuckling: off, from the scenery (its own), also from heat;
- deer: animals by the track;
with the crash damage, the breaking pantographs, the power from the wires only
and the state of a consist at its start, moved here from General.

Two levels set them in one go: Arcade forgives - no derailment, the legacy
couplings and collisions, no buckling, no damage, power without the wires, every
consist ready to drive; Realistic takes the physical models - the couplings of
the player's train, the derailment by its criteria (a track's own speed limit
still derails nothing), the crush of the ends, buckling in the heat - and the
consists as the scenario has them. The simulator's own values stand between the
two and show as custom; each setting can still be changed on its own.

The developer tab has physics.derailment.trustlimits,
controlcoupling.enginecheck, ai.brakesetting.cw1 and physics.trackcheck. A list
takes the other words the simulator reads for its own (couplerphysics true,
physics.derailment no), and a word of a list is named per key where it means
something of its own there.
2026-11-29 20:16:24 +01:00
Hirek cf3a6a4ca8 feat(settings): the choice of the simulator and ray tracing in the standard mode
- The exe the start button runs is chosen in a section of its own in General,
  not only in the developer tab: several builds may sit side by side.
- Ray-traced reflections have a row of their own among the details of the
  picture: off, or Low, Medium, High, Very high, a level being how far the rays
  reach (gfx.raytracing.range 250, 500, 1000, 2000 m). No level of detail turns
  them on or off, as they cost far more than anything a level sets; turned off,
  the reach stays for the next time. A reach no level has is shown as it is and
  kept. Only Vulkan draws them, so with OpenGL chosen the row is dimmed.
- gfx.raytracing.range is in the developer tab too, and the list follows its row.
2026-11-29 19:50:21 +01:00
Hirek 76de23c706 feat(settings): a standard mode a player understands, on Vulkan, and a developer tab for the rest
- The renderer is Vulkan, written whatever the file had: the simulator's own is
  OpenGL 4.6, to which it falls back by itself where Vulkan does not run.
  OpenGL 4.6 is chosen only in the developer tab. The words of the renderers the
  simulator no longer has (legacy, simple, ...) are read as it reads them.
- The standard mode shows what a player understands: the language, the interface
  scale, the pauses and the mouse; the screen with its render scale, VSync, frame
  limit and field of view; four levels of detail - Low, Medium, High, Very high -
  and a level for each part of the picture to take further (textures, shadows,
  reflections, lighting and sky, draw distance and grass, smoke, rain and snow);
  the anti-aliasing with TAA, MSAA and DLSS/DLAA; the effects of taste; the sound;
  the physics a player changes, the recording, the devices and the keys. A search
  in the standard mode finds nothing more.
- The levels set the keys of the OpenGL 4.6 and Vulkan renderers too: lamp and
  contact shadows, SSR, the cab probe, AO, fog, clouds, grass, rain and snow.
  High is about the simulator's own values and where a new player starts; Very
  high is the most worth having, without ray tracing, MSAA x8 or the largest
  shadow maps.
- Everything else is in the Developer tab, which only the advanced mode shows,
  behind its warning: the renderer and what only Vulkan reads, the details of
  the picture, the switches of the optimisations, the logs and diagnostics, and
  the choice of the simulator.
- What makes the simulator faster stays on in the standard mode. Where the
  simulator's own default is off, the starter writes it on: gfx.gpucull,
  gfx.textures.streaming, sound.asyncload, physics.sleepheld, physics.roadlod.
  Leaving the advanced mode puts the developer tab back at the starter's values;
  the details of the picture stay as their levels hold them.
- A player in the standard mode of an older starter is moved once
  (starter.settings.revision 2): Vulkan, and the developer tab at the starter's
  values, eu07.ini copied aside to eu07.ini.before-revision2 first. A player in
  the advanced mode keeps what they chose.
- The keys the simulator reads now are written: gfx.antialiasing, below the older
  multisampling that older simulators read, and gfx.buffer.percent for the render
  scale. The ones it no longer goes by are taken out of the file on a save:
  usevbo, gfx.usegles, gfx.angleplatform, gfx.framebuffer.width/height,
  starter.bufferscale, shadows, gfx.shadows.cab.range, smoothtraction, skyenabled,
  hideconsole, slowmotion. A simulator without gfx.buffer.percent draws at the
  whole window. gfx.reflections.fidelity missing from the file is read as the
  simulator's own 2.
- The developer tab's rows and the words of its lists come in English where a
  language lacks them; the standard mode's texts are in every language.
2026-11-29 19:29:46 +01:00
Hirek def5f15a81 feat(settings): a key eu07.ini sets twice is left once, on the line the simulator reads
The simulator reads eu07.ini top down and goes by the last line of a key before
endconfig; the earlier ones only mislead whoever reads the file. They are taken
out on every save, and once at start where the player's own file has any; the
starter's log names the keys.

The keys the simulator takes more than one line of stay every one
(network.server, python.viewport, extraviewport, test.vehicle), and so do the
lines past endconfig, in comments, and the lines of numbers that carry on the
value of the line above.
2026-11-29 19:29:33 +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
maj00r 5d8790301d Merge branch 'main' into feat/settings-standard-mode
# Conflicts:
#	StarterNG/Views/Settings.axaml.cs
2026-11-23 17:41:33 +01:00
Hirek e0d3988d4a Merge pull request #58 from MaSzyna-EU07/chore/net10
build: the starter, the black box and the tests move to .NET 10
2026-11-23 16:37:41 +00:00
Hirek 57821887e4 Merge pull request #57 from MaSzyna-EU07/feat/sbt-cleanup
Feat/sbt cleanup
2026-11-23 16:37:28 +00:00
maj00r 5ec7a4b539 fix(settings): a borderless screen draws into a buffer of the monitor's size, not the resolution row's
With fullscreenwindowed the simulator takes the window's size from the monitor and leaves width and height unread (application.cpp), but its full renderer still draws into gfx.framebuffer.width and height (opengl33renderer.cpp). Those were written from the resolution row, greyed out in that mode: 1280x720 stretched over a larger monitor. Borderless, they are now -1, the simulator's own word for a buffer of the window's size, or with a smaller render scale that part of the chosen monitor's size, the primary one's when none is chosen. A size left in a borderless file goes on the next save.
2026-11-22 14:53:18 +01:00
maj00r d429d041ff fix(settings): a monitor's name outside ASCII is written as the UTF-8 the simulator compares
The simulator compares the word after fullscreenmonitor byte by byte with GLFW's name of the monitor, which is UTF-8 (application.cpp, find_monitor), and has no other way to name one. eu07.ini is written in code page 1250, so a name with a letter outside ASCII never matched and the game opened on the primary monitor. That one word now goes into the file as its UTF-8 bytes, the rest staying in the code page; a name an earlier save left in the code page is read as it is and put right by the next save.
2026-11-22 14:52:51 +01:00
maj00r f7a58e8431 fix(settings): the move to the standard mode puts the render scale back with the frame buffer
The row of the render scale, which only the advanced mode shows, has the keys of the frame buffer's size, while the scale itself is read from starter.bufferscale: put back without it, the two came out as they were, and a player moved to the standard mode kept a blurred picture with no setting for it on the screen. The percent now goes wherever the buffer's size does, on the move, on leaving the advanced mode and on a section put back.
2026-11-22 14:51:59 +01:00
maj00r 77b0c23cea fix(settings): the cursor's speed is read and written as the old starter did, its four levels
The old starter (src/uSettings.pas) showed a mousescale as one of four levels - low below 1.3, high above 1.9, very high above 2.7, standard between - and wrote 1.0, 1.5, 2.3 or 3.2 for them, with 0.5 after it, the signs being the inversions. The slider had three whole steps instead, so a 3.2 was the top only by rounding and anything above 3 was cut to 3 on the move to the standard mode.
2026-11-22 14:47:05 +01:00
maj00r de4eb99ea1 docs(readme): a native build needs the .NET 10 SDK 2026-11-22 13:00:10 +01:00
maj00r 34beec588d fix(settings): an import or a profile keeps the mode, the move keeps the card and GLES
Importing an eu07.ini or applying a profile took starter.settings.standard and
starter.settings.advanced from the other file. An older one says "standard no",
so the next start moved the player again and reset what was just imported, this
time with no copy kept; "advanced yes" opened the advanced mode past the
warning. Both are now this installation's, like its simulator and its card.

The one-time move to the standard mode no longer resets starter.gpu and
gfx.usegles: some machines run the simulator only on the integrated card or
with OpenGL ES, and the move is done without asking.
2026-11-22 12:40:46 +01:00
maj00r bc4adfe6fa perf(blackbox): the map's marks thin out where they crowd, the most telling kept
From afar the signals, stop and horn points, signal passings and vehicles of a
scenery covered each other. Each now takes a square of a few pixels, asked for
in the order of what it tells - a signal at stop, a missed stop, a horn not
sounded, the user's train - so a crowd shows its most telling mark on top, and
close up, where they stand apart, every one is drawn. The stop wedges show only
close enough to tell apart.
2026-11-22 12:40:45 +01:00
maj00r c70fd94783 fix(sonar): numbers read from the file are compared within a tolerance
Equals is as exact as == to SonarCloud (S1244). Two numbers count as the
same within a billionth of the larger one, and mousescale's second number
as 0.5 within a billionth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:14:49 +01:00
maj00r 5d966be11c fix(sonar): no exact float compares, xrandr from its own path, its regexes timed
The quality gate of SonarCloud stopped on three exact compares of doubles
(S1244), the regexes reading xrandr without a timeout (S6444) and xrandr run
from whatever PATH finds (S4036). The compares meant to tell one number from
another keep doing so with Equals; the scroll lane's margin is compared within
a tenth of a pixel. xrandr is run from where distributions put it, or not at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:11:28 +01:00
maj00r 93f914c868 feat(settings): a standard mode as the old starter's panel, the rest behind a warning
The settings keep only the keys master reads, Vulkan left out. The standard
mode is the old starter's panel; the advanced mode opens behind a warning
whose yes takes a click only after 20 seconds in front of the player.

- Sliders go by fixed steps (SliderRanges), held to the standard ranges there:
  fpslimit up to 240, sleeperdistance up to 1000 m.
- On the first start everyone is moved to the standard mode once: what is
  outside it goes back to its default, the sliders' values to their ranges,
  and a copy of eu07.ini is kept as eu07.ini.before-standard.
- "Restore defaults" puts every setting back, the language, the simulator,
  the UART port and the control keys kept.
- Monitors and renderers are found anew (Monitors, Renderers), Displays and
  SettingReach gone.
- mousescale writes its second number as the old starter did, 0.5 or -0.5
  for an inverted vertical axis; an axis that would not move gets the default.
- Depot, in the standard mode: no AI or drivable-only filters, empty consists
  not listed, the crew shown but not changed.
- Randomizing the textures of a whole scenery no longer rebuilds the view per
  consist, and finds its candidates by mini, so the window keeps answering.
- A long operator in the vehicle list is cut short instead of over the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:02:29 +01:00
maj00r de943cf461 perf(blackbox): the map draws its rails by cells in view, at a detail its zoom needs
The tracks are cut into 500 m cells, so only those in view are drawn, and kept
at a few levels of detail, so that from afar a track is drawn with fewer points
than the pixels it covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:02:20 +01:00
maj00r e63aa71bf8 fix(scenery): a vehicle without its .fiz is a fault, an include ending the file is read
A vehicle whose .fiz is not in its folder under dynamic is left out by the
simulator, so its trainset runs short: the scenery check now names the
missing file. An include that is the last thing in the file, with no end,
is inlined as the simulator reads it, and still reported as not closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:02:20 +01:00
maj00r ecf3067d85 feat(consists): the consist lists show the vehicles' minis, alike ones under one caption
The scenery's consists and the warehouse's are listed as a strip of minis at
their own 30 px, vehicles alike next to each other taken together under one
caption ("412W ×20"). A consist wider than the list scrolls sideways in its
row, with a lane for the bar under the captions. A warehouse consist's strip
follows an edit as soon as it is saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 22:47:39 +01:00
maj00r 4b3ee43e4a 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.
2026-11-18 13:04:13 +01: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
108 changed files with 8695 additions and 4758 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
+6 -6
View File
@@ -51,10 +51,10 @@ jobs:
with:
persist-credentials: false
- name: Setup .NET 9
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
- name: Setup .NET 10
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.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
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
- name: Setup .NET 10
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.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
+6 -3
View File
@@ -61,16 +61,18 @@ jobs:
fetch-depth: 0
persist-credentials: false
- name: Setup .NET 9
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
- name: Setup .NET 10
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 9.0.x
dotnet-version: 10.0.x
- name: Restore tools
run: dotnet tool restore
# 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.
# tools/ holds the developers' helper scripts, outside the app and its tests:
# analysed like the rest, but not counted for coverage.
- name: Begin analysis
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
@@ -84,6 +86,7 @@ jobs:
/d:sonar.scm.revision="${{ github.event.pull_request.head.sha || github.sha }}"
/d:sonar.cs.opencover.reportsPaths="TestResults/**/coverage.opencover.xml"
/d:sonar.cs.vstest.reportsPaths="TestResults/*.trx"
/d:sonar.coverage.exclusions="tools/**"
/d:sonar.qualitygate.wait=true
# A full, non-incremental build: the analyzers only see what is compiled.
@@ -3,7 +3,7 @@
command line, or one picked. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<PublishTrimmed>true</PublishTrimmed>
@@ -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. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>
+161 -74
View File
@@ -25,8 +25,12 @@ public sealed class MapView : Control
private Recording? _recording;
private int _builtRevision = -1;
private int _builtTracks = -1;
private StreamGeometry? _tracks;
private readonly List<(int Index, int Branch, StreamGeometry Way)> _switchWays = new();
private TrackLayer? _tracks;
private readonly List<(int Index, int Branch, IReadOnlyList<System.Numerics.Vector3> Points)> _switchWays = new();
// The switches as they lay when last drawn, and their ways in two geometries: not taken, taken.
private int[] _switchStates = Array.Empty<int>();
private StreamGeometry? _waysOff, _waysOn;
private string? _hoverShown;
private readonly StreamGeometry?[] _trail = new StreamGeometry?[5];
private Rect _world;
@@ -135,33 +139,24 @@ public sealed class MapView : Control
{
_builtTracks = recording.Tracks.Count;
_switchWays.Clear();
var tracks = new StreamGeometry();
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
using (var g = tracks.Open())
foreach (var track in recording.Tracks)
{
foreach (var track in recording.Tracks)
if (track.Points.Count < 2)
continue;
foreach (var p in track.Points)
{
if (track.Points.Count < 2)
continue;
foreach (var p in track.Points)
{
left = Math.Min(left, -p.X);
right = Math.Max(right, -p.X);
top = Math.Min(top, -p.Z);
bottom = Math.Max(bottom, -p.Z);
}
if (track.Kind == TrackKind.SwitchBranch)
{
var way = new StreamGeometry();
using (var w = way.Open())
Polyline(w, track.Points);
_switchWays.Add((track.Index, track.Branch, way));
}
else
Polyline(g, track.Points);
left = Math.Min(left, -p.X);
right = Math.Max(right, -p.X);
top = Math.Min(top, -p.Z);
bottom = Math.Max(bottom, -p.Z);
}
if (track.Kind == TrackKind.SwitchBranch)
_switchWays.Add((track.Index, track.Branch, track.Points));
}
_tracks = tracks;
_tracks = new TrackLayer(recording.Tracks);
_switchStates = Array.Empty<int>();
_waysOff = _waysOn = null;
_world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default;
}
BuildTrail(recording);
@@ -247,29 +242,26 @@ public sealed class MapView : Control
double pixel = 1 / _scale;
using (context.PushTransform(toScreen))
{
// The tracks on a dark casing, so they stand out where they cross and run close.
// The tracks on a dark casing, so they stand out where they cross and run close. Only the
// cells in view, at the detail a pixel can show.
var casing = new Pen(Palette.TrackCasing, 5 * pixel, lineCap: PenLineCap.Round);
if (_tracks is not null)
context.DrawGeometry(null, casing, _tracks);
foreach (var (_, _, way) in _switchWays)
context.DrawGeometry(null, casing, way);
if (_tracks is not null)
context.DrawGeometry(null, new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round), _tracks);
var off = new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round);
var on = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
// The ways not taken under those taken.
foreach (var (index, branch, way) in _switchWays)
var fill = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round);
if (_tracks is { } layer)
{
int state = recording.SwitchAt(index, _time);
if (state >= 0 && state != branch)
context.DrawGeometry(null, off, way);
}
foreach (var (index, branch, way) in _switchWays)
{
int state = recording.SwitchAt(index, _time);
if (state < 0 || state == branch)
context.DrawGeometry(null, on, way);
var view = PlaneInView(size, 6 * pixel);
int level = TrackLayer.LevelFor(_scale);
foreach (var cell in layer.CellsIn(view, level))
context.DrawGeometry(null, casing, cell.Casing);
foreach (var cell in layer.CellsIn(view, level))
if (cell.Fill is { } tracks)
context.DrawGeometry(null, fill, tracks);
}
// The ways not taken under those taken, each set one geometry, made again only when a switch moves.
UpdateSwitchWays(recording);
if (_waysOff is not null)
context.DrawGeometry(null, new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round), _waysOff);
if (_waysOn is not null)
context.DrawGeometry(null, fill, _waysOn);
// The way the train went, in the colour of the judgement.
for (int kind = 0; kind < _trail.Length; kind++)
if (_trail[kind] is { } trail)
@@ -280,12 +272,67 @@ public sealed class MapView : Control
DrawHornPoints(context, recording);
DrawSignals(context, recording);
DrawPassings(context, recording);
DrawVehicles(context, recording);
// Once a frame: the vehicles and the hover both go by them.
var vehicles = recording.VehiclesAt(_time);
DrawVehicles(context, recording, vehicles);
DrawUserTrain(context, recording);
DrawCamera(context, recording);
DrawScale(context, size);
DrawLegend(context, size);
DrawHover(context, recording);
DrawHover(context, recording, vehicles);
}
/// <summary>The part of the map's plane on screen, with a margin in plane units.</summary>
private Rect PlaneInView(Size size, double margin)
{
double halfWidth = size.Width / 2 / _scale, halfHeight = size.Height / 2 / _scale;
return new Rect(-_centerX - halfWidth - margin, -_centerZ - halfHeight - margin,
2 * (halfWidth + margin), 2 * (halfHeight + margin));
}
private void UpdateSwitchWays(Recording recording)
{
bool changed = _switchStates.Length != _switchWays.Count;
if (changed)
_switchStates = new int[_switchWays.Count];
for (int i = 0; i < _switchWays.Count; i++)
{
int state = recording.SwitchAt(_switchWays[i].Index, _time);
if (state != _switchStates[i] || changed)
{
_switchStates[i] = state;
changed = true;
}
}
if (!changed && (_waysOff is not null || _waysOn is not null || _switchWays.Count == 0))
return;
var off = new StreamGeometry();
var on = new StreamGeometry();
bool anyOff = false, anyOn = false;
using (var gOff = off.Open())
using (var gOn = on.Open())
{
for (int i = 0; i < _switchWays.Count; i++)
{
var (_, branch, points) = _switchWays[i];
if (points.Count < 2)
continue;
int state = _switchStates[i];
if (state >= 0 && state != branch)
{
Polyline(gOff, points);
anyOff = true;
}
else
{
Polyline(gOn, points);
anyOn = true;
}
}
}
_waysOff = anyOff ? off : null;
_waysOn = anyOn ? on : null;
}
private bool Visible(Point p, double margin = 20) =>
@@ -295,15 +342,24 @@ public sealed class MapView : Control
{
double radius = _scale > 0.5 ? 4.5 : _scale > 0.1 ? 3.5 : 2.5;
var outline = new Pen(Palette.Background, 1);
// From afar a station's signals are one crowd: one dot to a few pixels, those at stop kept first.
var marks = new List<(AspectChange? Aspect, Point At, int Rank)>();
foreach (var signal in recording.Signals)
{
var p = ToScreen(signal.Position.X, signal.Position.Z);
if (!Visible(p))
continue;
context.DrawEllipse(Palette.Of(recording.AspectAt(signal.Index, _time)), outline, p, radius, radius);
var aspect = recording.AspectAt(signal.Index, _time);
marks.Add((aspect, p, SignalRank(aspect)));
}
foreach (var (aspect, p) in MarkGrid.Thin(marks, radius * 2 + 1))
context.DrawEllipse(Palette.Of(aspect), outline, p, radius, radius);
}
/// <summary>How much a signal's dot tells: at stop most, then a speed, then go, then nothing known.</summary>
internal static int SignalRank(AspectChange? aspect) =>
aspect is not { } a ? 3 : a.Speed1 == 0 ? 0 : a.Speed1 < 0 && a.Speed2 != 0 ? 2 : 1;
/// <summary>
/// The stop points (W4): a white plate, blue where the user's train stopped, red where it
/// missed the stop; the name of the station once close enough to read it.
@@ -345,21 +401,28 @@ public sealed class MapView : Control
double size = _scale > 0.5 ? 4 : 3;
var outline = new Pen(Palette.MapBackground, 1);
var labels = new List<(Point At, string Name, IBrush Fill)>();
// A station has a plate for each track and length of train: from afar one to a few pixels,
// a missed stop kept first, then one stopped at. The wedges only close enough to tell apart.
var marks = new List<((MapStopPoint Point, IBrush Fill) Item, Point At, int Rank)>();
foreach (var point in recording.StopPoints)
{
var p = ToScreen(point.Position.X, point.Position.Z);
if (!Visible(p))
continue;
var fill = outcomes.TryGetValue((Math.Round(point.Position.X, 1), Math.Round(point.Position.Z, 1)), out var kind)
? kind == StationKind.Missed ? Palette.Bad : Palette.Station
: Palette.StopPoint;
bool known = outcomes.TryGetValue((Math.Round(point.Position.X, 1), Math.Round(point.Position.Z, 1)), out var kind);
var fill = known ? kind == StationKind.Missed ? Palette.Bad : Palette.Station : Palette.StopPoint;
int rank = !known ? 2 : kind == StationKind.Missed ? 0 : 1;
marks.Add(((point, fill), p, rank));
}
foreach (var ((point, fill), p) in MarkGrid.Thin(marks, near ? size * 2 + 1 : size * 3))
{
var plate = new Rect(p.X - size, p.Y - size * 1.3, size * 2, size * 2.6);
// a W32 hollow, in the colour a W4 would be filled with
if (point.ForShortTrains)
context.DrawRectangle(Palette.MapBackground, new Pen(fill, 1.5), plate, 1.5, 1.5);
else
context.DrawRectangle(fill, outline, plate, 1.5, 1.5);
if (point.HasHeading)
if (point.HasHeading && near)
DrawStopWay(context, p, point.Heading, size, fill, outline);
labels.Add((p, StationNames.Display(point.Station), fill));
}
@@ -373,7 +436,8 @@ public sealed class MapView : Control
taken.Add(new Rect(mark.X - 10, mark.Y - 24, 170, 34));
}
var culture = System.Globalization.CultureInfo.CurrentCulture;
foreach (var (p, name, fill) in labels)
// The plates came the least telling first; the names go the other way, a missed stop's first.
foreach (var (p, name, fill) in Enumerable.Reverse(labels))
{
if (!near && !named.Add(name))
continue;
@@ -401,15 +465,18 @@ public sealed class MapView : Control
var checks = recording.UserHornChecks().Where(c => c.Request.Time <= _time).ToList();
double size = _scale > 0.5 ? 5 : 3.5;
var outline = new Pen(Palette.MapBackground, 1);
// One to a few pixels from afar: a horn not sounded kept first, then one sounded.
var marks = new List<(IBrush Fill, Point At, int Rank)>();
foreach (var point in recording.HornPoints)
{
var p = ToScreen(point.Position.X, point.Position.Z);
if (!Visible(p))
continue;
var check = checks.LastOrDefault(c => c.Request.Position.DistanceTo(point.Position) < 1);
var fill = check is null ? Palette.HornPoint : check.Sounded ? Palette.Good : Palette.Bad;
context.DrawGeometry(fill, outline, Diamond(p, size));
marks.Add(check is null ? (Palette.HornPoint, p, 2) : check.Sounded ? (Palette.Good, p, 1) : (Palette.Bad, p, 0));
}
foreach (var (fill, p) in MarkGrid.Thin(marks, size * 2 + 1))
context.DrawGeometry(fill, outline, Diamond(p, size));
}
internal static StreamGeometry Diamond(Point p, double size)
@@ -454,37 +521,48 @@ public sealed class MapView : Control
{
var passed = new Pen(Palette.Within, 1.5);
var danger = new Pen(Palette.Over, 2.5);
// One ring to a few pixels, one at danger kept first.
var marks = new List<(bool AtDanger, Point At, int Rank)>();
foreach (var passing in recording.UserPassings())
{
if (passing.Time > _time)
continue;
var p = ToScreen(passing.Position.X, passing.Position.Z);
if (!Visible(p))
continue;
if (passing.AtDanger)
if (Visible(p))
marks.Add((passing.AtDanger, p, passing.AtDanger ? 0 : 1));
}
foreach (var (atDanger, p) in MarkGrid.Thin(marks, 12))
{
if (atDanger)
context.DrawEllipse(null, danger, p, 10, 10);
else
context.DrawEllipse(null, passed, p, 7, 7);
}
}
private void DrawVehicles(DrawingContext context, Recording recording)
private void DrawVehicles(DrawingContext context, Recording recording, IReadOnlyList<VehicleState> vehicles)
{
int user = recording.CabAt(_time) is { } sample && _time - sample.Time < 1.5 ? sample.Vehicle : 0;
foreach (var state in recording.VehiclesAt(_time))
// From afar a train's cars are each wider on screen than they are long: one to a few
// pixels, the user's own kept first, then those driven by the AI.
var marks = new List<(VehicleState State, Point At, int Rank)>();
foreach (var state in vehicles)
{
var center = ToScreen(state.Position.X, state.Position.Z);
if (Visible(center, (recording.Vehicle(state.Id)?.Length ?? 15) * _scale + 10))
marks.Add((state, center, state.Id == user ? 0 : state.Driving == Driver.Ai ? 1 : 2));
}
foreach (var (state, center) in MarkGrid.Thin(marks, 5))
{
var info = recording.Vehicle(state.Id);
var brush = state.Id == user ? Palette.UserTrain : state.Driving == Driver.Ai ? Palette.VehicleAi : Palette.Vehicle;
DrawVehicle(context, state.Position.X, state.Position.Z, state.Heading, info?.Length ?? 15, info?.Width ?? 3, brush);
DrawVehicle(context, center, state.Heading, info?.Length ?? 15, info?.Width ?? 3, brush);
}
}
private void DrawVehicle(DrawingContext context, double x, double z, double heading, double length, double width,
private void DrawVehicle(DrawingContext context, Point center, double heading, double length, double width,
IBrush brush)
{
var center = ToScreen(x, z);
if (!Visible(center, length * _scale + 10))
return;
// The front from +z towards +x: up the screen and to the left.
double fx = Math.Sin(heading), fz = Math.Cos(heading);
double half = Math.Max(length * _scale, 5) / 2, side = Math.Max(width * _scale, 3) / 2;
@@ -602,10 +680,19 @@ public sealed class MapView : Control
}
/// <summary>The name of the signal or the vehicle under the pointer.</summary>
private void DrawHover(DrawingContext context, Recording recording)
private void DrawHover(DrawingContext context, Recording recording, IReadOnlyList<VehicleState> vehicles)
{
if (_pointer is not { } pointer || _dragFrom is not null)
_hoverShown = _pointer is { } at && _dragFrom is null ? HoverLabel(recording, at, vehicles) : null;
if (_hoverShown is not { } label || _pointer is not { } pointer)
return;
var text = Text(label, Palette.Text, 12);
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
}
private string? HoverLabel(Recording recording, Point pointer, IReadOnlyList<VehicleState> vehicles)
{
string? label = null;
double best = 10;
foreach (var signal in recording.Signals)
@@ -646,7 +733,7 @@ public sealed class MapView : Control
label = string.Format(culture, Strings["HornHover"], point.Name, point.Duration);
}
}
foreach (var state in recording.VehiclesAt(_time))
foreach (var state in vehicles)
{
double d = Distance(ToScreen(state.Position.X, state.Position.Z), pointer);
if (d < best && recording.Vehicle(state.Id) is { } info)
@@ -657,12 +744,7 @@ public sealed class MapView : Control
: $"{info.Name} ({info.Train}) · {Math.Abs(state.SpeedKmh):0} km/h";
}
}
if (label is null)
return;
var text = Text(label, Palette.Text, 12);
var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8);
context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6);
context.DrawText(text, new Point(box.Left + 8, box.Top + 4));
return label;
}
/// <summary>An aspect as the speeds it gives: stop, a speed, or go.</summary>
@@ -724,8 +806,13 @@ public sealed class MapView : Control
_centerX = _dragCenter.X + moved.X / _scale;
_centerZ = _dragCenter.Z + moved.Y / _scale;
}
InvalidateVisual();
return;
}
InvalidateVisual();
// Not dragged, the map is the same: drawn again only for a label to show, follow the pointer or go.
if (_hoverShown is not null ||
(_recording is { } recording && HoverLabel(recording, position, recording.VehiclesAt(_time)) is not null))
InvalidateVisual();
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
+47
View File
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using Avalonia;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The marks of a map thinned out on the screen: one to a square of a few pixels, the first
/// to ask for a square keeps it. Asked in the order of how much a mark tells, a crowd seen from
/// afar shows its most telling marks, each clear of the next, and close up, where the marks
/// stand apart anyway, every one is drawn.
/// </summary>
internal sealed class MarkGrid
{
private readonly double _cell;
private readonly HashSet<(long, long)> _taken = new();
/// <param name="cell">The side of a square in pixels: about the size of the mark.</param>
public MarkGrid(double cell) => _cell = Math.Max(cell, 1);
/// <summary>Whether the mark at this point of the screen is drawn: its square was free.</summary>
public bool Take(Point p) =>
_taken.Add(((long)Math.Floor(p.X / _cell), (long)Math.Floor(p.Y / _cell)));
/// <summary>
/// The items whose marks are drawn: those in view, the most telling first - a lower rank
/// tells more - each in a square no other took before it.
/// </summary>
public static List<(T Item, Point At)> Thin<T>(IEnumerable<(T Item, Point At, int Rank)> marks, double cell)
{
var ranked = new List<(T Item, Point At, int Rank)>(marks);
// Stable: of marks alike, the one first in the recording keeps its square, frame after frame.
var order = new int[ranked.Count];
for (int i = 0; i < order.Length; i++)
order[i] = i;
Array.Sort(order, (a, b) => ranked[a].Rank != ranked[b].Rank ? ranked[a].Rank.CompareTo(ranked[b].Rank) : a.CompareTo(b));
var grid = new MarkGrid(cell);
var kept = new List<(T, Point)>();
foreach (int i in order)
if (grid.Take(ranked[i].At))
kept.Add((ranked[i].Item, ranked[i].At));
// Drawn the least telling first: where marks of next squares touch, the telling one lies on top.
kept.Reverse();
return kept;
}
}
+184
View File
@@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using Avalonia;
using Avalonia.Media;
namespace Eu07.BlackBox.Views;
/// <summary>
/// The rails of a scenery made ready to draw fast: cut into square cells so that only those in
/// view are drawn, and kept at a few levels of detail so that from afar a track is drawn with
/// fewer points than there are pixels it covers. The casing takes the switches' ways too, which
/// it is drawn under in one colour; the fill is the plain tracks alone.
/// </summary>
public sealed class TrackLayer
{
/// <summary>The side of a cell in metres.</summary>
public const double CellSize = 500;
/// <summary>The points of a track closer than this to the last kept are left out, by level.</summary>
public static readonly double[] Tolerances = { 0, 2, 8, 32, 128 };
/// <summary>A part of the map: what is drawn of it, and where it lies in the map's plane.</summary>
public sealed record Cell(Rect Bounds, StreamGeometry Casing, StreamGeometry? Fill);
private readonly List<Cell>[] _levels;
public TrackLayer(IReadOnlyList<MapTrack> tracks)
{
_levels = new List<Cell>[Tolerances.Length];
for (int level = 0; level < Tolerances.Length; level++)
_levels[level] = BuildLevel(tracks, Tolerances[level]);
}
/// <summary>The level whose left-out points stay within <paramref name="pixels"/> on screen at this scale.</summary>
public static int LevelFor(double scale, double pixels = 0.75)
{
int level = 0;
for (int i = 1; i < Tolerances.Length; i++)
if (Tolerances[i] * scale <= pixels)
level = i;
return level;
}
/// <summary>The cells of the level that reach into <paramref name="view"/>, a rectangle of the map's plane.</summary>
public IEnumerable<Cell> CellsIn(Rect view, int level)
{
foreach (var cell in _levels[Math.Clamp(level, 0, _levels.Length - 1)])
if (cell.Bounds.Intersects(view))
yield return cell;
}
public int CellCount(int level) => _levels[level].Count;
/// <summary>The points of a track with those nearer than <paramref name="tolerance"/> to the last kept left out; its ends stay.</summary>
public static List<Vector3> Simplified(IReadOnlyList<Vector3> points, double tolerance)
{
var kept = new List<Vector3>(points.Count);
if (points.Count == 0)
return kept;
kept.Add(points[0]);
double square = tolerance * tolerance;
for (int i = 1; i < points.Count - 1; i++)
{
var last = kept[^1];
double dx = points[i].X - last.X, dz = points[i].Z - last.Z;
if (dx * dx + dz * dz >= square)
kept.Add(points[i]);
}
if (points.Count > 1)
kept.Add(points[^1]);
return kept;
}
private sealed class Builder
{
public readonly List<List<Point>> Casing = new();
public readonly List<List<Point>> Fill = new();
public double Left = double.MaxValue, Top = double.MaxValue, Right = double.MinValue, Bottom = double.MinValue;
public void Grow(Point p)
{
Left = Math.Min(Left, p.X);
Right = Math.Max(Right, p.X);
Top = Math.Min(Top, p.Y);
Bottom = Math.Max(Bottom, p.Y);
}
}
private static List<Cell> BuildLevel(IReadOnlyList<MapTrack> tracks, double tolerance)
{
var cells = new Dictionary<(long, long), Builder>();
foreach (var track in tracks)
{
if (track.Points.Count < 2)
continue;
bool fill = track.Kind != TrackKind.SwitchBranch;
var points = tolerance > 0 ? Simplified(track.Points, tolerance) : (IReadOnlyList<Vector3>)track.Points;
// A run of the track's points in one cell; a segment over a border goes with the cell it ends in,
// which starts from the point before, so its bounds cover the whole segment.
List<Point>? casingRun = null, fillRun = null;
(long, long) current = default;
for (int i = 0; i < points.Count; i++)
{
var p = Plane(points[i]);
var key = ((long)Math.Floor(p.X / CellSize), (long)Math.Floor(p.Y / CellSize));
if (casingRun is null || key != current)
{
var builder = Of(cells, key);
var start = casingRun is null ? (Point?)null : casingRun[^1];
casingRun = new List<Point>();
builder.Casing.Add(casingRun);
fillRun = null;
if (fill)
{
fillRun = new List<Point>();
builder.Fill.Add(fillRun);
}
if (start is { } joined)
{
// The segment from the last cell starts there, so the line has no gap at the border.
casingRun.Add(joined);
fillRun?.Add(joined);
builder.Grow(joined);
}
current = key;
}
casingRun.Add(p);
fillRun?.Add(p);
Of(cells, key).Grow(p);
}
}
var result = new List<Cell>(cells.Count);
foreach (var builder in cells.Values)
{
var casing = Geometry(builder.Casing);
if (casing is null)
continue;
var bounds = new Rect(new Point(builder.Left, builder.Top), new Point(builder.Right, builder.Bottom));
result.Add(new Cell(bounds, casing, Geometry(builder.Fill)));
}
return result;
}
private static Builder Of(Dictionary<(long, long), Builder> cells, (long, long) key)
{
if (!cells.TryGetValue(key, out var builder))
cells[key] = builder = new Builder();
return builder;
}
private static StreamGeometry? Geometry(List<List<Point>> runs)
{
StreamGeometry? geometry = null;
StreamGeometryContext? g = null;
try
{
foreach (var run in runs)
{
if (run.Count < 2)
continue;
if (geometry is null)
{
geometry = new StreamGeometry();
g = geometry.Open();
}
g!.BeginFigure(run[0], false);
for (int i = 1; i < run.Count; i++)
g.LineTo(run[i]);
g.EndFigure(false);
}
}
finally
{
g?.Dispose();
}
return geometry;
}
// As MapView draws the plane: x to the left, z up the screen.
private static Point Plane(Vector3 p) => new(-p.X, -p.Z);
}
+1 -1
View File
@@ -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. -->
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>
+15 -1
View File
@@ -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++)
@@ -46,3 +46,17 @@ the packaged artifacts — tagged `latest` for `main` and `staging` for `staging
```sh
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
@@ -0,0 +1,67 @@
using Avalonia;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
/// <summary>The marks of the black box map thinned out where they crowd, the most telling kept.</summary>
public class MarkGridTests
{
[Fact]
public void A_crowd_in_one_square_leaves_its_most_telling_mark()
{
var kept = MarkGrid.Thin(new[]
{
("go", new Point(1, 1), 2),
("stop", new Point(3, 2), 0),
("speed", new Point(4, 4), 1)
}, 6);
Assert.Equal(["stop"], kept.Select(k => k.Item));
}
[Fact]
public void Marks_apart_by_more_than_a_square_are_all_kept()
{
var marks = Enumerable.Range(0, 20).Select(i => (i, new Point(i * 10, 5), 1)).ToList();
Assert.Equal(20, MarkGrid.Thin(marks, 6).Count);
}
[Fact]
public void Of_marks_alike_the_first_keeps_its_square_and_the_telling_ones_are_drawn_last()
{
var kept = MarkGrid.Thin(new[]
{
("first", new Point(1, 1), 1),
("second", new Point(2, 2), 1),
("apart", new Point(50, 50), 0)
}, 6);
Assert.Equal(["first", "apart"], kept.Select(k => k.Item));
}
[Fact]
public void A_row_closer_than_a_square_keeps_one_to_each()
{
// A hundred marks a pixel apart are as many squares of six as they cover.
var marks = Enumerable.Range(0, 100).Select(i => (i, new Point(i, 0), 1)).ToList();
Assert.Equal(17, MarkGrid.Thin(marks, 6).Count);
}
[Theory]
[InlineData(0f, 40f, 0)] // at stop
[InlineData(40f, -1f, 1)] // a speed
[InlineData(-1f, -1f, 2)] // go
public void A_signal_at_stop_tells_most(float speed1, float speed2, int rank)
{
Assert.Equal(rank, MapView.SignalRank(new AspectChange(0, 1, speed1, speed2, "")));
}
[Fact]
public void A_signal_not_yet_seen_tells_least()
{
Assert.Equal(3, MapView.SignalRank(null));
}
}
@@ -0,0 +1,79 @@
using System.Numerics;
using Avalonia;
using Eu07.BlackBox;
using Eu07.BlackBox.Views;
namespace StarterNG.Tests.BlackBox;
/// <summary>The rails of the black box map made ready to draw only what is in view, at the detail a pixel shows.</summary>
[Collection(AvaloniaControls.Name)]
public class TrackLayerTests
{
public TrackLayerTests() => HeadlessDrawing.Ensure();
private static MapTrack Track(int index, TrackKind kind, params (float X, float Z)[] points) =>
new(index, $"t{index}", kind, kind == TrackKind.SwitchBranch ? 0 : -1, 0,
points.Select(p => new Vector3(p.X, 0, p.Z)).ToList());
[Theory]
[InlineData(2.0, 0)] // close up: every point
[InlineData(0.3, 1)] // 2 m are 0.6 px, 8 m would be 2.4
[InlineData(0.05, 2)] // 8 m are 0.4 px, 32 m would be 1.6
[InlineData(0.002, 4)] // the whole of a big scenery: 128 m are 0.26 px
public void The_level_leaves_out_no_more_than_a_pixel_shows(double scale, int level)
{
Assert.Equal(level, TrackLayer.LevelFor(scale));
}
[Fact]
public void Only_the_cells_in_view_are_drawn()
{
var layer = new TrackLayer(new[]
{
Track(1, TrackKind.Normal, (0, 0), (100, 0)),
Track(2, TrackKind.Normal, (-5000, -5000), (-5100, -5000))
});
// The plane shows x to the left: the first track lies at -100..0, the second at 5000..5100.
var near = layer.CellsIn(new Rect(-200, -50, 300, 100), 0).ToList();
Assert.Single(near);
Assert.Equal(2, layer.CellCount(0));
}
[Fact]
public void A_track_across_cells_is_drawn_without_a_gap_at_the_border()
{
var layer = new TrackLayer(new[] { Track(1, TrackKind.Normal, (-400, 0), (-600, 0), (-800, 0)) });
var cells = layer.CellsIn(new Rect(-10000, -10000, 20000, 20000), 0).ToList();
// The segment over the border goes with the cell it ends in, from the point the line left the last one:
// that cell reaches back to it, so it is drawn whenever any of the segment is in view.
var cell = Assert.Single(cells);
Assert.Equal(400, cell.Bounds.Left);
Assert.Equal(800, cell.Bounds.Right);
Assert.Single(layer.CellsIn(new Rect(450, -10, 20, 20), 0));
}
[Fact]
public void A_switch_way_is_in_the_casing_but_not_in_the_plain_fill()
{
var layer = new TrackLayer(new[] { Track(7, TrackKind.SwitchBranch, (0, 0), (30, 5)) });
var cell = Assert.Single(layer.CellsIn(new Rect(-100, -100, 200, 200), 0));
Assert.NotNull(cell.Casing);
Assert.Null(cell.Fill);
}
[Fact]
public void Simplifying_keeps_the_ends_and_drops_points_closer_than_the_tolerance()
{
var points = new[] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(2, 0, 0), new Vector3(10, 0, 0), new Vector3(11, 0, 0) };
var kept = TrackLayer.Simplified(points, 5);
Assert.Equal(new[] { 0f, 10f, 11f }, kept.Select(p => p.X));
}
}
+44
View File
@@ -174,6 +174,50 @@ public class ConfigFileTests
Assert.Equal(new[] { "// width 800", "endconfig", "// width 1920", "// height 600", "" }, Lines(config));
}
private static readonly string[] Repeatable = { "network.server", "python.viewport" };
[Fact]
public void A_key_set_twice_keeps_only_the_line_the_simulator_reads()
{
var config = ConfigFile.Parse("width 800\nheight 600\nWIDTH 1024\t// mine\nwidth 1920\nfullscreen yes\n");
var removed = config.RemoveDuplicates(Repeatable);
Assert.Equal(new[] { "height 600", "width 1920", "fullscreen yes", "" }, Lines(config));
Assert.Equal("1920", config.GetRaw("width"));
Assert.Equal(new[] { "width", "WIDTH" }, removed);
}
[Fact]
public void Keys_the_simulator_takes_many_of_stay_every_one()
{
const string text = "network.server zmq tcp://a\nnetwork.server zmq tcp://b\npython.viewport a\npython.viewport b\n";
var config = ConfigFile.Parse(text);
Assert.Empty(config.RemoveDuplicates(Repeatable));
Assert.Equal(ConfigFile.Parse(text).ToText(), config.ToText());
}
[Fact]
public void Past_endconfig_and_in_comments_nothing_is_removed()
{
const string text = "width 800\nendconfig\nwidth 1920\nheight 1\nheight 2\n";
var config = ConfigFile.Parse("// width 640\n/* width 700\nwidth 720 */\n" + text);
Assert.Empty(config.RemoveDuplicates(Repeatable));
Assert.Equal("800", config.GetRaw("width"));
}
[Fact]
public void A_line_of_numbers_carrying_on_a_value_is_no_key_of_its_own()
{
const string text = "uarttune\n0 0 0\n0 0 0\nwidth 800\n";
var config = ConfigFile.Parse(text);
Assert.Empty(config.RemoveDuplicates(Repeatable));
Assert.Equal(ConfigFile.Parse(text).ToText(), config.ToText());
}
[Fact]
public void Without_endconfig_a_new_key_goes_at_the_end_as_it_did()
{
+68
View File
@@ -0,0 +1,68 @@
using StarterNG.Classes;
using StarterNG.Domain;
namespace StarterNG.Tests;
public class ConsistRunsTests
{
private static List<Dynamic> Vehicles(params string[] skins) =>
new Trainset(string.Concat(
"trainset a tor 0 0\n",
string.Concat(skins.Select((s, i) => $"node -1 0 v{i} dynamic d {s} m 0 nobody 3 0 enddynamic\n")),
"endtrainset")).Vehicles;
private static List<(string Skin, int Count)> Runs(List<Dynamic> vehicles, Func<Dynamic, int, string?> keyOf) =>
ConsistRuns.Of(vehicles, keyOf).Select(r => (r.First.SkinFile!, r.Count)).ToList();
[Fact]
public void Vehicles_alike_next_to_each_other_make_one_run()
{
var vehicles = Vehicles("eu07", "412w", "412w", "412w", "eaos", "eaos");
Assert.Equal(
[("eu07", 1), ("412w", 3), ("eaos", 2)],
Runs(vehicles, (v, _) => v.SkinFile));
}
[Fact]
public void Vehicles_alike_apart_stay_apart()
{
var vehicles = Vehicles("412w", "eaos", "412w");
Assert.Equal(
[("412w", 1), ("eaos", 1), ("412w", 1)],
Runs(vehicles, (v, _) => v.SkinFile));
}
[Fact]
public void Alike_goes_by_the_key_whatever_its_case()
{
var vehicles = Vehicles("412W", "412w");
Assert.Equal([("412W", 2)], Runs(vehicles, (v, _) => v.SkinFile));
}
[Fact]
public void A_vehicle_with_no_key_stands_alone()
{
var vehicles = Vehicles("x", "x", "x");
Assert.Equal(
[("x", 1), ("x", 1), ("x", 1)],
Runs(vehicles, (_, _) => null));
}
[Fact]
public void The_place_in_the_consist_can_set_a_vehicle_apart()
{
var vehicles = Vehicles("sm42", "sm42", "sm42");
Assert.Equal(
[("sm42", 1), ("sm42", 2)],
Runs(vehicles, (v, i) => i == 0 ? "head" : v.SkinFile));
}
[Fact]
public void No_vehicles_no_runs() =>
Assert.Empty(ConsistRuns.Of([], (v, _) => v.SkinFile));
}
-100
View File
@@ -1,100 +0,0 @@
using StarterNG.Infrastructure;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class DisplaysTests
{
/// <summary>A 128-byte block with an 18-byte timing at 54, as a panel's base EDID has it.</summary>
private static byte[] BaseBlock(int pixelClock10KHz, int hActive, int hBlank, int vActive, int vBlank,
int extensions = 0)
{
var edid = new byte[128];
new byte[] { 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }.CopyTo(edid, 0);
edid[126] = (byte)extensions;
int at = 54;
edid[at] = (byte)pixelClock10KHz;
edid[at + 1] = (byte)(pixelClock10KHz >> 8);
edid[at + 2] = (byte)hActive;
edid[at + 3] = (byte)hBlank;
edid[at + 4] = (byte)((hActive >> 8) << 4 | hBlank >> 8);
edid[at + 5] = (byte)vActive;
edid[at + 6] = (byte)vBlank;
edid[at + 7] = (byte)((vActive >> 8) << 4 | vBlank >> 8);
return edid;
}
/// <summary>A DisplayID 2.0 block with one type VII timing (kHz, sizes less one).</summary>
private static byte[] DisplayIdBlock(int pixelClockKHz, int hActive, int hBlank, int vActive, int vBlank)
{
var block = new byte[128];
block[0] = 0x70;
block[1] = 0x20;
block[2] = 23; // one data block: 3 bytes of header, 20 of timing
block[3] = 2;
int at = 5;
block[at] = 0x22;
block[at + 2] = 20;
int t = at + 3, clock = pixelClockKHz - 1;
block[t] = (byte)clock;
block[t + 1] = (byte)(clock >> 8);
block[t + 2] = (byte)(clock >> 16);
void Put(int offset, int value)
{
block[t + offset] = (byte)(value - 1);
block[t + offset + 1] = (byte)((value - 1) >> 8);
}
Put(4, hActive);
Put(6, hBlank);
Put(12, vActive);
Put(14, vBlank);
return block;
}
[Fact]
public void A_plain_monitor_gives_its_preferred_timing()
{
// 1920x1080 at 148.5 MHz: the usual 60 Hz.
Assert.Equal(60, Edid.HighestRefreshRate(BaseBlock(14850, 1920, 280, 1080, 45)));
}
[Fact]
public void A_fast_panel_found_only_in_displayid_is_read_there()
{
// As the eDP panel of a gaming laptop: 60 Hz in the base block, 165 Hz in DisplayID.
var edid = BaseBlock(15394, 1920, 160, 1200, 35, extensions: 1)
.Concat(DisplayIdBlock(423250, 1920, 160, 1200, 33)).ToArray();
Assert.Equal(165, Edid.HighestRefreshRate(edid));
}
[Fact]
public void Something_too_short_for_an_edid_has_no_rate()
{
Assert.Equal(0, Edid.HighestRefreshRate(new byte[] { 0, 0xFF }));
Assert.Equal(0, Edid.HighestRefreshRate(new byte[128]));
}
[Fact]
public void Only_connected_screens_are_listed_by_their_connector()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithFile("/sys/class/drm/card1-eDP-1/status", "connected\n")
.WithFile("/sys/class/drm/card1-HDMI-A-1/status", "disconnected\n")
.WithFile("/sys/class/drm/card1/device/uevent", "DRIVER=amdgpu\n");
files.WriteAllBytes("/sys/class/drm/card1-eDP-1/edid", BaseBlock(14850, 1920, 280, 1080, 45));
files.WriteAllBytes("/sys/class/drm/card1-HDMI-A-1/edid", BaseBlock(14850, 1920, 280, 1080, 45));
var displays = new Displays(files, new FakeEnvironment()).List();
Assert.Equal(new[] { new Display("eDP-1", 60) }, displays);
}
[Fact]
public void Off_linux_without_windows_nothing_is_read()
{
var environment = new FakeEnvironment { IsLinux = false, IsMacOS = true };
Assert.Empty(new Displays(new InMemoryFileSystem(), environment).List());
}
}
+48
View File
@@ -230,6 +230,54 @@ public class ExecutableLocatorTests
Assert.Equal(ExeProblem.None, installation.Executables.Validate(build));
}
private static string Automatic(TestInstallation installation) =>
Path.GetFileName(installation.Executables.Resolve(new SimulatorSettings(), out _));
private static TestInstallation OnWindows(bool lacksAvx2, params string[] names)
{
var files = new InMemoryFileSystem();
foreach (string name in names)
files.WithFile(TestInstallation.At(name), PortableExecutable);
var installation = new TestInstallation(files, lacksAvx2: lacksAvx2);
installation.Environment.AsWindows();
return installation;
}
[Fact]
public void On_windows_the_simulators_own_starter_is_picked_ahead_of_the_simulator()
{
var installation = OnWindows(false, "eu07.exe", "eu07_starter.exe", "eu07_2026-11-15_abc.exe");
Assert.Equal("eu07_starter.exe", Automatic(installation));
}
[Fact]
public void A_simulator_picked_by_hand_stays_although_the_starter_is_there()
{
var installation = OnWindows(false, "eu07.exe", "eu07_starter.exe");
var settings = new SimulatorSettings { SelectExeAutomatically = false, ExecutablePath = "eu07.exe" };
Assert.Equal("eu07.exe", installation.Executables.Resolve(settings, out _));
}
[Fact]
public void Without_avx2_a_build_without_it_still_comes_before_the_starter()
{
var installation = OnWindows(true, "eu07.exe", "eu07_starter.exe", "eu07_noavx2.exe");
Assert.Equal("eu07_noavx2.exe", Automatic(installation));
}
[Fact]
public void Under_wine_the_simulator_is_started_without_its_windows_starter()
{
var installation = WithWine(new InMemoryFileSystem()
.WithFile(TestInstallation.At("eu07.exe"), PortableExecutable)
.WithFile(TestInstallation.At("eu07_starter.exe"), PortableExecutable));
Assert.Equal("eu07.exe", Automatic(installation));
}
[Fact]
public void Wine_is_never_looked_for_on_windows()
{
+226
View File
@@ -0,0 +1,226 @@
using StarterNG.Classes;
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
/// <summary>eu07.ini as other hands leave it: edited while the starter runs, and with lines the starter does not know.</summary>
public class ExternalIniTests
{
private static readonly string UserIni = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
private static TestInstallation WithIni(string text)
{
var installation = new TestInstallation(new InMemoryFileSystem().WithFile(UserIni, text));
installation.Environment.With("HOME", "/home/kolejarz");
installation.SettingsStore.Load();
return installation;
}
private static SimulatorSettings Read(string text)
{
var s = new SimulatorSettings();
new SettingsSerializer().Read(s, ConfigFile.Parse(text));
return s;
}
[Fact]
public void A_key_inside_a_block_comment_is_not_read()
{
Assert.False(Read("/*\nfullscreen yes\n*/\n").Fullscreen);
Assert.False(Read("/* fullscreen yes */\n").Fullscreen);
}
[Fact]
public void A_comment_glued_to_a_value_is_not_part_of_it()
{
Assert.True(Read("fullscreen yes//na pelnym ekranie\n").Fullscreen);
}
[Fact]
public void A_save_keeps_what_was_changed_on_disk_meanwhile()
{
var installation = WithIni("fieldofview 45\n");
Edited(installation, "fieldofview 45\nvsync yes\ncalibratein 1 2 3 4\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("fieldofview 60", saved);
Assert.Contains("calibratein 1 2 3 4", saved);
Assert.Contains("vsync yes", saved);
// What is held is the file again: a later save does not take the other change back.
Assert.True(installation.SettingsStore.Settings.VSync);
Assert.True(installation.SettingsStore.LastSaveMerged);
}
[Fact]
public void A_key_changed_both_here_and_on_disk_takes_the_players_value()
{
var installation = WithIni("fieldofview 45\n");
Edited(installation, "fieldofview 70\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
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 null", a word the starter does not offer.
var installation = WithIni("gfxrenderer default\nfieldofview 45\n");
Edited(installation, "gfxrenderer null\nfieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("gfxrenderer null", saved);
Assert.Contains("fieldofview 60", saved);
Assert.Equal("null", 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]
public void A_file_nobody_else_touched_saves_as_before()
{
var installation = WithIni("fieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
Assert.False(installation.SettingsStore.LastSaveMerged);
Assert.Contains("fieldofview 60", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_known_key_with_a_value_the_starter_cannot_read_is_named_with_that_value()
{
var installation = WithIni("fieldofview abc\nfullscreen moze\nui.scale duzo\nvsync tak\nwidth 1920.0\n" +
"gfxrenderer legacy\nwidth 1920\ngfx.framebuffer.width 960\ncalibratein 1 2\n");
var unreadable = installation.SettingsStore.UnreadableValues();
Assert.Equal("abc", unreadable["fieldofview"]);
Assert.Equal("moze", unreadable["fullscreen"]);
Assert.Equal("duzo", unreadable["ui.scale"]);
// Read another way, derived from other keys, or not the starter's: none of them unknown.
Assert.False(unreadable.ContainsKey("vsync"));
Assert.False(unreadable.ContainsKey("width"));
Assert.False(unreadable.ContainsKey("gfxrenderer"));
Assert.False(unreadable.ContainsKey("gfx.framebuffer.width"));
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.
installation.SettingsStore.Save();
Assert.Contains("fieldofview abc", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void Values_above_what_the_old_starter_gave_are_brought_down_on_the_next_save()
{
var installation = WithIni("maxcabtexturesize 8192\nshadowtune 4096 250 600 300\n" +
"width 1920\nheight 1080\ngfx.framebuffer.width 2880\ngfx.framebuffer.height 1620\n" +
"fieldofview 50\n");
var store = installation.SettingsStore;
Assert.Equal(GraphicsRules.MaxCabTextureSize, store.Settings.MaxCabTextureSize);
Assert.Equal(GraphicsRules.MaxShadowRange, store.Settings.ShadowProjectionRange);
Assert.Equal(GraphicsRules.MaxBufferScale, store.Settings.BufferScalePercent);
// Read, only brought down: not a value the starter cannot read.
Assert.Empty(store.UnreadableValues());
store.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("maxcabtexturesize 4096", saved);
Assert.Contains("shadowtune 4096 250 400 300", saved);
// The render scale is the simulator's own key now, at the whole window.
Assert.Contains("gfx.buffer.percent 1", saved);
Assert.DoesNotContain("\ngfx.framebuffer.width", "\n" + saved);
Assert.Contains("fieldofview 50", saved);
}
[Fact]
public void Values_within_the_caps_are_left_as_the_file_has_them()
{
var installation = WithIni("maxcabtexturesize 2048\nshadowtune 2048 250 300 300\n");
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("maxcabtexturesize 2048", saved);
Assert.Contains("shadowtune 2048 250 300 300", saved);
}
// Another program writes the file a minute after the starter read it.
private static void Edited(TestInstallation installation, string text) =>
installation.Files.WithFile(UserIni, text)
.WrittenAt(UserIni, installation.Files.GetLastWriteTimeUtc(UserIni).AddMinutes(1));
[Fact]
public void Lines_the_starter_does_not_know_survive_a_save_in_place()
{
const string ini = "// moj komentarz\nfoo bar baz\n\nfullscreen no\nzmq.address tcp://*:5555\n";
var installation = WithIni(ini);
installation.SettingsStore.Settings.Fullscreen = true;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni).Replace("\r\n", "\n");
Assert.StartsWith("// moj komentarz\nfoo bar baz\n\nfullscreen yes\nzmq.address tcp://*:5555\n", saved);
}
}
+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));
}
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]
public void There_are_no_cards_on_a_mac()
{
+226 -584
View File
@@ -13,108 +13,199 @@ public class GraphicsPresetTests
return installation.SettingsStore.Settings;
}
private static SimulatorSettings AtHigh()
private static SimulatorSettings At(GraphicsPreset preset)
{
var settings = Defaults().Copy();
GraphicsPreset.High.ApplyTo(settings);
preset.ApplyTo(settings);
return settings;
}
private static SimulatorSettings AtHigh() => At(GraphicsPreset.High);
/// <summary>The keys two renderings give different values, a key one leaves out at its default.</summary>
private static IEnumerable<string> Differing(IReadOnlyDictionary<string, string> one, IReadOnlyDictionary<string, string> other)
{
string? Value(IReadOnlyDictionary<string, string> keys, string key) =>
keys.TryGetValue(key, out string? value) ? value : SimulatorKeys.All.FirstOrDefault(k => k.Key == key)?.Default;
return one.Keys.Union(other.Keys).Where(key => Value(one, key) != Value(other, key));
}
[Fact]
public void The_keys_named_are_the_keys_a_level_sets()
public void A_level_sets_no_key_but_those_it_names()
{
var store = new TestInstallation().SettingsStore;
var low = Defaults().Copy();
var top = Defaults().Copy();
// Ray tracing is one of them, and only Vulkan has it.
low.RenderEngine = top.RenderEngine = SimulatorSettings.VulkanEngine;
(GraphicsPreset.Minimal with { Extras = null }).ApplyTo(low);
(GraphicsPreset.Ultra with { Extras = null, Top = null }).ApplyTo(top);
var own = store.Render(Defaults());
foreach (var preset in GraphicsPreset.All)
Assert.Empty(Differing(own, store.Render(At(preset))).Except(GraphicsPreset.AllKeys));
}
var lowKeys = store.Render(low);
var topKeys = store.Render(top);
var differing = lowKeys.Keys.Union(topKeys.Keys)
.Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key))
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal));
[Fact]
public void Every_key_of_a_level_belongs_to_one_part_or_to_the_anti_aliasing()
{
var inGroups = GraphicsGroup.All.SelectMany(group => group.Keys).ToList();
Assert.Equal(GraphicsPreset.Keys.OrderBy(k => k), differing.OrderBy(k => k));
Assert.Equal(inGroups.Distinct(), inGroups);
Assert.Empty(GraphicsPreset.All.SelectMany(preset => preset.Keys.Keys).Except(inGroups));
}
// ── The scale ────────────────────────────────────────────────────────────
private static void Climbs(Func<GraphicsPreset, double> value, int repeatsAllowed)
private static void Climbs(Func<GraphicsPreset, double> value)
{
var values = GraphicsPreset.All.Select(value).ToList();
Assert.Equal(values.OrderBy(v => v), values);
Assert.True(values.Count - values.Distinct().Count() <= repeatsAllowed, string.Join(", ", values));
}
[Fact]
public void Every_slider_moves_from_level_to_level_as_far_as_it_has_steps_for_six()
public void Every_part_of_the_picture_gets_better_or_stays_from_level_to_level()
{
// Sizes and filtering run out of steps above High.
Climbs(p => p.TextureSize, 1);
Climbs(p => p.CabTextureSize, 1);
Climbs(p => p.Anisotropy, 1);
Climbs(p => p.TextureSize);
Climbs(p => p.CabTextureSize);
Climbs(p => p.Anisotropy);
Climbs(p => p.ShadowMap);
Climbs(p => p.ShadowRange);
Climbs(p => p.ShadowRank);
Climbs(p => p.ReflectionsFidelity);
Climbs(p => p.ReflectionsRate);
Climbs(p => p.SplineFidelity);
Climbs(p => p.DrawRangeFactor);
Climbs(p => p.SmokeFidelity);
// Four steps or three for six levels.
Climbs(p => (int)p.AntiAliasing, 2);
Climbs(p => p.SmokeFidelity, 2);
Climbs(p => p.SplineFidelity, 2);
Climbs(p => p.ReflectionsFidelity, 3);
Climbs(p => p.ShadowRank, 3);
// The simulator takes no more than its own 7 lights, and draws no less than 2 km.
Climbs(p => p.DynamicLights, 2);
Climbs(p => p.DrawRange, 1);
Climbs(p => p.DrawRangeFactor, 2);
Climbs(p => p.CabShadowsRange, 1);
Climbs(p => p.ShadowMap, 1);
Climbs(p => p.ShadowRange, 0);
Climbs(p => p.ReflectionsRate, 0);
Climbs(p => p.DistanceFactor, 0);
Climbs(p => p.BufferScale, 0);
Climbs(p => p.SleeperDistance, 0);
Climbs(p => p.ReflectedInstances, 0);
Climbs(p => p.ReflectedVehicles, 0);
}
[Fact]
public void No_step_up_a_scale_is_more_than_a_few_steps_of_its_slider()
{
// In steps of what the screen offers, so Ultra does not jump to the top from far below.
var rates = GraphicsPreset.All.Select(p => Steps.IndexOf(Steps.ReflectionUpdates, p.ReflectionsRate)).ToList();
Assert.All(rates.Zip(rates.Skip(1)), step => Assert.InRange(step.Second - step.First, 1, 4));
foreach (Func<GraphicsPreset, int> fidelity in new Func<GraphicsPreset, int>[] { p => p.SmokeFidelity, p => p.SplineFidelity })
foreach (string name in GraphicsPreset.Low.Keys.Keys)
{
var levels = GraphicsPreset.All.Select(fidelity).ToList();
Assert.All(levels.Zip(levels.Skip(1)), step => Assert.InRange(step.Second - step.First, 0, 1));
var key = SimulatorKeys.Named(name);
Climbs(p => key.Kind switch
{
SimulatorKeyKind.Choice => key.ChoiceIndex(p.Keys[name]),
SimulatorKeyKind.Toggle => SimulatorKey.ParseToggle(p.Keys[name]) ? 1 : 0,
_ => key.ParseNumber(p.Keys[name])
});
}
}
[Fact]
public void High_is_the_simulators_own_but_where_that_is_the_bottom_of_a_scale()
public void Every_level_sets_the_same_keys()
{
var store = new TestInstallation().SettingsStore;
var own = store.Render(Defaults());
var high = store.Render(AtHigh());
var differing = own.Keys.Union(high.Keys)
.Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key))
.Where(key => !GraphicsPreset.RowKeys.Contains(key))
.Where(key => !key.StartsWith("gfx.framebuffer", StringComparison.Ordinal) && key != "gfx.buffer.percent");
Assert.Equal(new[] { "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.shadows.cab.range",
"gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k));
Assert.Equal(1, Defaults().SmokeFidelity);
Assert.Equal(1, Defaults().SplineFidelity);
foreach (var preset in GraphicsPreset.All)
Assert.Equal(GraphicsPreset.High.Keys.Keys.OrderBy(k => k), preset.Keys.Keys.OrderBy(k => k));
}
[Fact]
public void A_player_with_no_settings_of_their_own_starts_at_high()
public void Every_value_of_a_level_is_one_its_row_offers()
{
foreach (var preset in GraphicsPreset.All)
foreach (var (name, value) in preset.Keys)
{
var key = SimulatorKeys.Named(name);
switch (key.Kind)
{
case SimulatorKeyKind.Choice:
Assert.True(key.ChoiceIndex(value) >= 0, $"{preset.NameKey} {name} {value}");
break;
case SimulatorKeyKind.Number:
Assert.InRange(key.ParseNumber(value), key.Minimum, key.Maximum);
break;
}
}
}
[Fact]
public void High_is_the_simulators_own_but_for_the_smoke_and_the_track_curves()
{
var store = new TestInstallation().SettingsStore;
var differing = Differing(store.Render(Defaults()), store.Render(AtHigh()));
Assert.Equal(new[] { "gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k, StringComparer.Ordinal));
}
[Fact]
public void Very_high_is_not_everything_at_its_top()
{
var top = GraphicsPreset.VeryHigh;
Assert.True(top.AntiAliasing <= AntiAliasingMode.Msaa4);
Assert.True(top.ShadowMap <= 4096);
Assert.False(top.Keys.ContainsKey("gfx.raytracing"));
Assert.NotEqual("ultra", top.Keys["gfx.clouds"]);
Assert.NotEqual("ultra", top.Keys["gfx.fog.quality"]);
}
[Fact]
public void Low_draws_no_screen_space_effects()
{
Assert.Equal(AntiAliasingMode.Off, GraphicsPreset.Low.AntiAliasing);
Assert.Equal("no", GraphicsPreset.Low.Keys["gfx.ssr"]);
Assert.Equal("no", GraphicsPreset.Low.Keys["gfx.postfx.ao"]);
Assert.Equal("no", GraphicsPreset.Low.Keys["gfx.contactshadows"]);
}
[Fact]
public void Every_level_sits_on_the_steps_the_screen_offers()
{
foreach (var preset in GraphicsPreset.All)
{
Assert.True(Steps.IndexOf(Steps.Anisotropy, preset.Anisotropy) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(SliderRanges.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(SliderRanges.DrawRangeFactors, preset.DrawRangeFactor) >= 0, preset.NameKey);
foreach (int size in new[] { preset.TextureSize, preset.CabTextureSize, preset.ShadowMap })
Assert.True(size is >= 512 and <= 8192 && (size & (size - 1)) == 0, preset.NameKey);
Assert.True(preset.CabTextureSize <= GraphicsRules.MaxCabTextureSize, preset.NameKey);
Assert.True(preset.ShadowRange >= SimulatorSettings.ShadowRangeFloor(preset.ShadowMap), preset.NameKey);
Assert.True(preset.ShadowRange <= GraphicsRules.MaxShadowRange, preset.NameKey);
}
}
[Fact]
public void A_level_leaves_the_screen_and_the_matters_of_taste_as_they_are()
{
var settings = Defaults().Copy();
settings.MotionBlur = false;
settings.ChromaticAberration = false;
settings.Smoke = false;
settings.PythonScreens = false;
settings.FieldOfView = 60;
settings.BufferScalePercent = 75;
settings.Backend = GraphicsBackend.OpenGL;
GraphicsPreset.VeryHigh.ApplyTo(settings);
Assert.False(settings.MotionBlur);
Assert.False(settings.ChromaticAberration);
Assert.False(settings.Smoke);
Assert.False(settings.PythonScreens);
Assert.Equal(60, settings.FieldOfView);
Assert.Equal(75, settings.BufferScalePercent);
Assert.Equal(GraphicsBackend.OpenGL, settings.Backend);
}
[Fact]
public void A_level_applied_is_recognised_until_one_value_moves()
{
foreach (var preset in GraphicsPreset.All)
{
var settings = At(preset);
Assert.Same(preset, GraphicsPreset.Matching(settings));
settings.Extra["gfx.ssr"] = preset.Keys["gfx.ssr"] == "high" ? "low" : "high";
Assert.Null(GraphicsPreset.Matching(settings));
}
}
[Fact]
public void A_level_is_recognised_with_its_words_written_as_numbers()
{
var settings = AtHigh();
settings.Extra["gfx.ssr"] = "2";
settings.Extra["gfx.lights.shadows"] = "2";
Assert.Same(GraphicsPreset.High, GraphicsPreset.Matching(settings));
}
// ── The first start ──────────────────────────────────────────────────────
[Fact]
public void A_player_with_no_settings_of_their_own_starts_at_high_on_vulkan()
{
var installation = new TestInstallation();
var store = installation.SettingsStore;
@@ -128,6 +219,10 @@ public class GraphicsPresetTests
var again = new TestInstallation(installation.Files).SettingsStore;
again.Load();
Assert.Same(GraphicsPreset.High, GraphicsPreset.Matching(again.Settings));
Assert.Equal(GraphicsBackend.Vulkan, again.Settings.Backend);
// Nothing of an older starter to bring into the standard mode, nor of an older layout.
Assert.True(again.Settings.MovedToStandard);
Assert.Equal(SimulatorSettings.CurrentRevision, again.Settings.Revision);
}
[Fact]
@@ -144,485 +239,78 @@ public class GraphicsPresetTests
again.StartAtHighWithoutOwnSettings();
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(again.Settings));
Assert.False(again.Settings.MovedToStandard);
}
[Fact]
public void High_is_what_the_new_simulator_does_with_nothing_set()
public void A_copy_of_the_file_is_kept_once_and_not_written_over()
{
Assert.Equal(GraphicsPreset.High.NewRenderer, GraphicsNewRenderer.Of(Defaults()));
var installation = new TestInstallation();
var store = installation.SettingsStore;
store.Load();
store.Settings.FieldOfView = 50;
store.Save();
string copy = store.SavePath + ".before-standard";
store.KeepCopy(".before-standard");
string first = installation.Files.ReadAllText(copy);
Assert.Equal(installation.Files.ReadAllText(store.SavePath), first);
store.Settings.FieldOfView = 60;
store.Save();
store.KeepCopy(".before-standard");
Assert.Equal(first, installation.Files.ReadAllText(copy));
}
// ── Ray tracing ──────────────────────────────────────────────────────────
[Theory]
[InlineData("no", "500", RayTracing.Off)]
[InlineData("no", "123", RayTracing.Off)]
[InlineData("yes", "250", 0)]
[InlineData("yes", "500", 1)]
[InlineData("yes", "1000", 2)]
[InlineData("yes", "2000", 3)]
public void Ray_tracing_is_off_or_at_the_level_of_its_reach(string enabled, string range, int level) =>
Assert.Equal(level, RayTracing.LevelOf(enabled, range));
[Fact]
public void Ray_tracing_at_a_reach_no_level_has_is_at_none()
{
Assert.Null(RayTracing.LevelOf("yes", "750"));
}
[Fact]
public void The_new_renderers_scales_never_go_down()
public void Ray_tracing_is_off_by_default_and_its_levels_reach_further_one_by_one()
{
void NeverDown(Func<GraphicsNewRenderer, double> value) => Climbs(p => value(p.NewRenderer), 5);
void TurnsOn(Func<GraphicsNewRenderer, bool> on)
{
var values = GraphicsPreset.All.Select(p => on(p.NewRenderer)).ToList();
Assert.Equal(values.OrderBy(value => value), values);
}
NeverDown(r => r.LampShadows);
NeverDown(r => r.ContactShadows);
NeverDown(r => r.Occlusion);
NeverDown(r => r.OcclusionSlices);
NeverDown(r => r.OcclusionSteps);
NeverDown(r => r.CabProbe);
NeverDown(r => r.ScreenReflections);
NeverDown(r => r.FogQuality);
NeverDown(r => r.Clouds);
TurnsOn(r => r.OcclusionLighting);
TurnsOn(r => r.CabProbeReflections);
TurnsOn(r => r.RayTracing);
TurnsOn(r => r.VolumetricFog);
TurnsOn(r => r.CloudShadows);
TurnsOn(r => r.Grass);
TurnsOn(r => r.Bloom);
Climbs(p => p.NewRenderer.GrassDistance, 0);
Climbs(p => p.NewRenderer.GrassDensity, 0);
Climbs(p => p.NewRenderer.Precipitation, 1);
// Frames between refreshes, so the dearer the fewer.
Climbs(p => -p.NewRenderer.CabProbeInterval, 2);
Assert.Equal(RayTracing.Off, RayTracing.LevelOf(Defaults()));
var ranges = RayTracing.Levels.Select(level => level.Range).ToList();
Assert.Equal(ranges.OrderBy(r => r).Distinct(), ranges);
var key = SimulatorKeys.Named(RayTracing.RangeKey);
Assert.All(ranges, range => Assert.InRange(range, key.Minimum, key.Maximum));
}
[Fact]
public void Ultra_is_the_top_of_the_new_renderers_scales()
public void Turned_off_ray_tracing_keeps_its_reach_for_the_next_time()
{
var ultra = GraphicsPreset.Ultra.NewRenderer;
var settings = Defaults().Copy();
RayTracing.Apply(settings, 3);
RayTracing.Apply(settings, RayTracing.Off);
Assert.Equal(3, ultra.LampShadows);
Assert.Equal(3, ultra.ContactShadows);
Assert.Equal(2, ultra.Occlusion);
Assert.Equal((6, 8), (ultra.OcclusionSlices, ultra.OcclusionSteps));
Assert.Equal(3, ultra.CabProbe);
Assert.Equal(3, ultra.ScreenReflections);
Assert.True(ultra.RayTracing && ultra.VolumetricFog);
Assert.Equal(4, ultra.FogQuality);
Assert.Equal(4, ultra.Clouds);
Assert.Equal(300, ultra.GrassDistance);
Assert.Equal(2.0, ultra.GrassDensity);
Assert.Equal(262144, ultra.Precipitation);
Assert.Equal("no", settings.Extra[RayTracing.Key]);
Assert.Equal("2000", settings.Extra[RayTracing.RangeKey]);
}
[Fact]
public void Grass_fades_out_beyond_where_it_is_drawn_in_full()
public void No_level_of_detail_turns_ray_tracing_on_or_off()
{
var store = new TestInstallation().SettingsStore;
foreach (var preset in GraphicsPreset.All)
{
var settings = Defaults().Copy();
RayTracing.Apply(settings, 2);
preset.ApplyTo(settings);
Assert.True(int.Parse(store.Render(settings)["gfx.grass.fadedistance"]) > preset.NewRenderer.GrassDistance, preset.NameKey);
}
}
[Fact]
public void A_level_set_in_the_new_renderers_rows_is_told_from_the_others()
{
var settings = Defaults().Copy();
GraphicsPreset.Medium.ApplyTo(settings);
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
settings.FogQuality = 4;
Assert.Null(GraphicsPreset.Matching(settings));
}
[Fact]
public void What_is_left_to_the_player_stays_through_a_level()
{
var settings = Defaults().Copy();
settings.RenderEngine = SimulatorSettings.VulkanEngine;
settings.AntiAliasing = AntiAliasingMode.Dlss;
settings.FrameGeneration = 2;
settings.VulkanDevice = "RTX";
foreach (var preset in GraphicsPreset.All)
{
preset.ApplyTo(settings);
Assert.Equal(2, RayTracing.LevelOf(settings));
Assert.Same(preset, GraphicsPreset.Matching(settings));
Assert.Equal(AntiAliasingMode.Dlss, settings.AntiAliasing);
Assert.Equal(2, settings.FrameGeneration);
Assert.Equal("RTX", settings.VulkanDevice);
}
}
[Fact]
public void Ultra_is_the_top_of_everything_the_screen_offers()
{
var ultra = GraphicsPreset.Ultra;
double Top(string key) => SimulatorKeys.Named(key).Maximum;
Assert.Equal(8192, ultra.TextureSize);
Assert.Equal(8192, ultra.CabTextureSize);
Assert.Equal(8192, ultra.ShadowMap);
Assert.Equal(600, ultra.ShadowRange);
Assert.Equal(Steps.Anisotropy.Max(), ultra.Anisotropy);
Assert.Equal(AntiAliasingMode.Msaa8, ultra.AntiAliasing);
Assert.Equal(Steps.ReflectionUpdates.Max(), ultra.ReflectionsRate);
Assert.Equal(4, ultra.SmokeFidelity);
Assert.Equal(4, ultra.SplineFidelity);
Assert.Equal(200, ultra.BufferScale);
Assert.Equal(Top(GraphicsPreset.DrawRangeKey), ultra.DrawRange);
Assert.Equal(Top(GraphicsPreset.DistanceFactorKey), ultra.DistanceFactor);
Assert.Equal(Top(GraphicsPreset.SleeperKey), ultra.SleeperDistance);
Assert.Equal(Steps.DrawRangeFactors.Max(), ultra.DrawRangeFactor);
Assert.Equal(Top(GraphicsPreset.ReflectedInstancesKey), ultra.ReflectedInstances);
Assert.Equal(Top(GraphicsPreset.ReflectedVehiclesKey), ultra.ReflectedVehicles);
Assert.Equal(100, ultra.CabShadowsRange);
var extras = ultra.Extras!;
Assert.Equal(200, extras.PythonUpdateMs);
Assert.True(extras.MotionBlur && extras.ChromaticAberration && extras.Smoke);
var top = ultra.Top!;
Assert.Equal(Top(GraphicsTop.ScreenWindowFpsKey), top.ScreenWindowFps);
Assert.True(top.Screens && top.ScreenMipmaps && top.Sky && top.Cab && top.AirCouplers && top.SmoothTraction);
}
[Fact]
public void At_ultra_what_would_only_take_away_is_off()
{
var top = GraphicsPreset.Ultra.Top!;
// The longest shadows, the bottom of that scale.
Assert.Equal(0.2, top.ShadowAngleLimit);
Assert.Equal(0, top.TargetFps);
Assert.Equal(0, top.TextureRelease);
Assert.False(top.CompressTextures);
Assert.False(top.SkipDecor);
}
[Fact]
public void Ultra_undoes_what_was_moved_earlier()
{
var settings = Defaults().Copy();
settings.ShadowAngleLimit = 0.8;
settings.IgnoreIrrelevantTrains = true;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
settings.Extra[GraphicsTop.TextureReleaseKey] = "2";
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
Assert.Equal(0.2, settings.ShadowAngleLimit);
Assert.False(settings.IgnoreIrrelevantTrains);
Assert.Equal("0", settings.Extra[GraphicsTop.TargetFpsKey]);
Assert.Equal("0", settings.Extra[GraphicsTop.TextureReleaseKey]);
}
[Fact]
public void Ultra_leaves_the_screens_in_their_own_windows_to_the_player()
{
var settings = Defaults().Copy();
settings.Extra["python.displaywindows"] = "yes";
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.Equal("yes", settings.Extra["python.displaywindows"]);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
}
[Fact]
public void The_other_levels_leave_what_only_ultra_sets()
{
foreach (var preset in GraphicsPreset.All.Where(preset => preset != GraphicsPreset.Ultra))
{
var settings = Defaults().Copy();
settings.IgnoreIrrelevantTrains = true;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
preset.ApplyTo(settings);
Assert.True(settings.IgnoreIrrelevantTrains, preset.NameKey);
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
Assert.Same(preset, GraphicsPreset.Matching(settings));
}
}
[Fact]
public void Ultra_is_not_recognised_with_one_of_its_values_moved()
{
var settings = Defaults().Copy();
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
settings.Extra[GraphicsPreset.ReflectedVehiclesKey] = "250";
Assert.Null(GraphicsPreset.Matching(settings));
}
[Fact]
public void No_level_asks_for_a_range_the_renderer_would_raise_anyway()
{
Assert.All(GraphicsPreset.All, preset => Assert.True(preset.DrawRange >= 2000, preset.NameKey));
}
[Fact]
public void The_view_only_shortens_going_down_the_levels()
{
var factors = GraphicsPreset.All.Select(preset => preset.DistanceFactor).ToList();
Assert.Equal(factors.OrderBy(factor => factor), factors);
Assert.Equal(1, GraphicsPreset.High.DistanceFactor);
}
[Fact]
public void Shadows_reach_further_with_every_level_that_has_them()
{
static double Reach(GraphicsPreset preset) =>
SimulatorSettings.ShadowReach(preset.ShadowRange, preset.ShadowMap, legacyRenderer: false);
var reaches = GraphicsPreset.All.Where(preset => preset.Shadows).Select(Reach).ToList();
Assert.Equal(reaches.Distinct().OrderBy(reach => reach), reaches);
Assert.Equal(250, Reach(GraphicsPreset.High));
Assert.Equal(800, Reach(GraphicsPreset.VeryHigh));
}
[Fact]
public void Without_extras_the_settings_are_what_the_simulator_goes_by()
{
Assert.Equal(GraphicsExtras.None, GraphicsExtras.Of(Defaults()));
Assert.Equal(GraphicsTop.None, GraphicsTop.Of(Defaults()));
}
[Fact]
public void A_level_leaves_what_only_the_lowest_one_sets()
{
var settings = Defaults().Copy();
settings.MotionBlur = false;
GraphicsPreset.Low.ApplyTo(settings);
Assert.False(settings.MotionBlur);
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
}
[Fact]
public void Every_level_sets_the_buffer_and_is_not_recognised_with_another()
{
foreach (var preset in GraphicsPreset.All)
{
var settings = Defaults().Copy();
settings.BufferScalePercent = 120;
preset.ApplyTo(settings);
Assert.Equal(preset.BufferScale, settings.BufferScalePercent);
settings.BufferScalePercent = 120;
Assert.Null(GraphicsPreset.Matching(settings));
}
}
[Fact]
public void The_buffer_is_the_screen_at_high_and_climbs_through_it()
{
Assert.Equal(100, GraphicsPreset.High.BufferScale);
Assert.Equal(200, GraphicsPreset.Ultra.BufferScale);
Assert.InRange(GraphicsPreset.Minimal.BufferScale, 50, 100);
}
[Fact]
public void The_lowest_level_is_not_recognised_with_one_of_its_extras_undone()
{
var settings = Defaults().Copy();
GraphicsPreset.Minimal.ApplyTo(settings);
settings.Smoke = true;
Assert.Null(GraphicsPreset.Matching(settings));
}
[Fact]
public void The_extras_sit_on_the_steps_the_screen_offers()
{
foreach (var extras in new[] { GraphicsPreset.Minimal.Extras!, GraphicsPreset.Ultra.Extras! })
Assert.Contains(extras.PythonUpdateMs, new[] { 200, 400, 800, 1600 });
}
// ── Leaving an end of the scale ──────────────────────────────────────────
[Fact]
public void A_level_between_the_ends_chooses_only_its_own_keys()
{
var settings = Defaults().Copy();
settings.MotionBlur = false;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Medium, settings);
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
Assert.False(settings.MotionBlur);
Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]);
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
}
[Fact]
public void Leaving_the_lowest_level_brings_back_what_was_there_before_it()
{
var memory = new GraphicsPresetMemory();
var settings = Defaults().Copy();
settings.MotionBlur = false;
var before = GraphicsExtras.Of(settings);
var entering = memory.Apply(GraphicsPreset.Minimal, settings);
Assert.Equal(GraphicsPreset.Minimal.Extras, GraphicsExtras.Of(settings));
Assert.Equal(GraphicsPreset.RowKeys, entering.RowKeys);
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), entering.ChosenKeys);
var leaving = memory.Apply(GraphicsPreset.Medium, settings);
Assert.Equal(before, GraphicsExtras.Of(settings));
Assert.Same(GraphicsPreset.Medium, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys, leaving.RowKeys);
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys), leaving.ChosenKeys);
}
[Fact]
public void Leaving_ultra_brings_back_what_was_there_before_it()
{
var memory = new GraphicsPresetMemory();
var settings = Defaults().Copy();
settings.MotionBlur = false;
settings.ShadowAngleLimit = 0.8;
settings.Extra[GraphicsTop.TargetFpsKey] = "60";
var extras = GraphicsExtras.Of(settings);
var top = GraphicsTop.Of(settings);
memory.Apply(GraphicsPreset.Ultra, settings);
var applied = memory.Apply(GraphicsPreset.VeryHigh, settings);
Assert.Equal(extras, GraphicsExtras.Of(settings));
Assert.Equal(top, GraphicsTop.Of(settings));
Assert.Same(GraphicsPreset.VeryHigh, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
Assert.Equal(GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys), applied.ChosenKeys);
}
[Fact]
public void Leaving_an_end_chosen_before_this_run_gives_the_simulators_own_values()
{
var settings = Defaults().Copy();
GraphicsPreset.Ultra.ApplyTo(settings);
var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Low, settings);
Assert.Equal(GraphicsExtras.None, GraphicsExtras.Of(settings));
Assert.Equal(GraphicsTop.None, GraphicsTop.Of(settings));
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), applied.RowKeys);
}
[Fact]
public void One_end_to_the_other_keeps_what_was_there_before_either()
{
var memory = new GraphicsPresetMemory();
var settings = Defaults().Copy();
settings.MotionBlur = false;
var extras = GraphicsExtras.Of(settings);
var top = GraphicsTop.Of(settings);
memory.Apply(GraphicsPreset.Minimal, settings);
var toUltra = memory.Apply(GraphicsPreset.Ultra, settings);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toUltra.RowKeys);
var toMinimal = memory.Apply(GraphicsPreset.Minimal, settings);
Assert.Same(GraphicsPreset.Minimal, GraphicsPreset.Matching(settings));
// Ultra's own values go, Minimal has no say over them.
Assert.Equal(top, GraphicsTop.Of(settings));
Assert.Equal(GraphicsPreset.RowKeys.Concat(GraphicsTop.RowKeys), toMinimal.RowKeys);
memory.Apply(GraphicsPreset.Medium, settings);
Assert.Equal(extras, GraphicsExtras.Of(settings));
}
[Fact]
public void What_was_remembered_comes_back_only_once()
{
var memory = new GraphicsPresetMemory();
var settings = Defaults().Copy();
settings.MotionBlur = false;
memory.Apply(GraphicsPreset.Minimal, settings);
memory.Apply(GraphicsPreset.Medium, settings);
Assert.False(settings.MotionBlur);
// Moved since, and no end left behind this time: it stays as moved.
settings.MotionBlur = true;
var applied = memory.Apply(GraphicsPreset.High, settings);
Assert.True(settings.MotionBlur);
Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys);
Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys);
}
[Fact]
public void A_level_applied_twice_at_an_end_remembers_what_came_before_the_first()
{
var memory = new GraphicsPresetMemory();
var settings = Defaults().Copy();
settings.MotionBlur = false;
var before = GraphicsExtras.Of(settings);
memory.Apply(GraphicsPreset.Minimal, settings);
memory.Apply(GraphicsPreset.Minimal, settings);
memory.Apply(GraphicsPreset.Low, settings);
Assert.Equal(before, GraphicsExtras.Of(settings));
}
[Fact]
public void A_level_applied_is_recognised_until_one_value_moves()
{
foreach (var preset in GraphicsPreset.All)
{
var settings = Defaults().Copy();
preset.ApplyTo(settings);
Assert.Same(preset, GraphicsPreset.Matching(settings));
settings.DynamicLights = 6;
Assert.Null(GraphicsPreset.Matching(settings));
}
}
[Fact]
public void Every_level_sits_on_the_steps_the_screen_offers()
{
void OnSteps(double value, string name)
{
var key = SimulatorKeys.Named(name);
Assert.InRange(value, key.Minimum, key.Maximum);
double steps = value / key.Step;
Assert.Equal(Math.Round(steps), steps, 6);
}
foreach (var preset in GraphicsPreset.All)
{
OnSteps(preset.DistanceFactor, GraphicsPreset.DistanceFactorKey);
OnSteps(preset.DrawRange, GraphicsPreset.DrawRangeKey);
OnSteps(preset.SleeperDistance, GraphicsPreset.SleeperKey);
OnSteps(preset.ReflectedInstances, GraphicsPreset.ReflectedInstancesKey);
OnSteps(preset.ReflectedVehicles, GraphicsPreset.ReflectedVehiclesKey);
Assert.InRange(preset.NewRenderer.CabProbeInterval, 1, 120);
Assert.InRange(preset.NewRenderer.GrassDistance, 20, 300);
Assert.Equal(0, preset.NewRenderer.GrassDistance % 10);
Assert.Equal(0, preset.NewRenderer.GrassDensity % 0.25);
Assert.Contains(preset.NewRenderer.Precipitation, new[] { 16384, 32768, 65536, 131072, 262144 });
Assert.True(Steps.IndexOf(Steps.Anisotropy, preset.Anisotropy) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(Steps.ReflectionUpdates, preset.ReflectionsRate) >= 0, preset.NameKey);
Assert.True(Steps.IndexOf(Steps.DrawRangeFactors, preset.DrawRangeFactor) >= 0, preset.NameKey);
foreach (int size in new[] { preset.TextureSize, preset.CabTextureSize, preset.ShadowMap })
Assert.True(size is >= 512 and <= 8192 && (size & (size - 1)) == 0, preset.NameKey);
Assert.True(preset.ShadowRange >= SimulatorSettings.ShadowRangeFloor(preset.ShadowMap), preset.NameKey);
Assert.Equal(0, preset.CabShadowsRange % 10);
}
}
@@ -630,17 +318,6 @@ public class GraphicsPresetTests
private static GraphicsGroupLevels Groups() => new(new TestInstallation().SettingsStore);
[Fact]
public void Every_key_a_level_sets_but_those_of_the_whole_belongs_to_one_part()
{
var inGroups = GraphicsGroup.All.SelectMany(group => group.Keys).ToList();
Assert.Equal(inGroups.Distinct(), inGroups);
Assert.Empty(inGroups.Except(GraphicsPreset.Keys).Except(GraphicsExtras.Keys).Except(GraphicsTop.Keys));
Assert.Equal(new[] { "gfx.antialiasing", "gfx.buffer.percent", "gfx.extraeffects", "gfx.postfx.bloom", "multisampling", "starter.bufferscale" },
GraphicsPreset.Keys.Except(inGroups).OrderBy(key => key, StringComparer.Ordinal));
}
[Fact]
public void One_part_moves_alone()
{
@@ -652,9 +329,10 @@ public class GraphicsPresetTests
Assert.Equal(GraphicsPreset.Low.ShadowMap, moved.ShadowMapResolution);
Assert.Equal(GraphicsPreset.Low.ShadowRange, moved.ShadowProjectionRange);
Assert.Equal(GraphicsPreset.Low.ShadowRank, moved.ShadowRankCutoff);
Assert.Equal("low", moved.Extra["gfx.lights.shadows"]);
Assert.Equal(settings.MaxTextureSize, moved.MaxTextureSize);
Assert.Equal(settings.DynamicLights, moved.DynamicLights);
Assert.Equal(settings.BufferScalePercent, moved.BufferScalePercent);
Assert.Equal(settings.Extra["gfx.ssr"], moved.Extra["gfx.ssr"]);
Assert.Equal(settings.AntiAliasing, moved.AntiAliasing);
var levels = groups.LevelsOf(moved);
Assert.Same(GraphicsPreset.Low, levels[GraphicsGroup.Shadows]);
@@ -663,41 +341,33 @@ public class GraphicsPresetTests
}
[Fact]
public void Every_part_shows_ultra_when_the_whole_is_at_ultra()
public void Every_part_shows_the_level_the_whole_is_at()
{
var settings = Defaults().Copy();
GraphicsPreset.Ultra.ApplyTo(settings);
Assert.All(Groups().LevelsOf(settings).Values, level => Assert.Same(GraphicsPreset.Ultra, level));
// The row of a key at the simulator's own value leaves it out of the file.
settings.Extra.Remove(GraphicsTop.TextureReleaseKey);
Assert.Same(GraphicsPreset.Ultra, Groups().LevelsOf(settings)[GraphicsGroup.Textures]);
foreach (var preset in GraphicsPreset.All)
Assert.All(Groups().LevelsOf(At(preset)).Values, level => Assert.Same(preset, level));
}
[Fact]
public void A_part_moved_by_hand_is_at_no_level_and_the_others_keep_theirs()
{
var settings = AtHigh();
settings.DynamicLights = 6;
settings.ReflectionsFidelity = 0;
var levels = Groups().LevelsOf(settings);
Assert.Null(levels[GraphicsGroup.Lights]);
Assert.Null(levels[GraphicsGroup.Reflections]);
Assert.Same(GraphicsPreset.High, levels[GraphicsGroup.Shadows]);
}
[Fact]
public void Every_part_at_a_level_and_the_buffer_with_it_is_that_level()
public void Every_part_at_a_level_and_the_anti_aliasing_with_it_is_that_level()
{
var groups = Groups();
foreach (var level in GraphicsPreset.All.Where(level => level.Extras is null))
foreach (var level in GraphicsPreset.All)
{
var settings = Defaults().Copy();
foreach (var group in GraphicsGroup.All)
settings = groups.Apply(group, level, settings);
settings.BufferScalePercent = level.BufferScale;
settings.AntiAliasing = level.AntiAliasing;
Assert.Same(level, GraphicsPreset.Matching(settings));
@@ -712,32 +382,4 @@ public class GraphicsPresetTests
foreach (var level in GraphicsPreset.All)
Assert.Same(level, groups.LevelsOf(groups.Apply(group, level, Defaults()))[group]);
}
[Fact]
public void Leaving_an_end_in_a_part_gives_the_simulators_own_for_what_only_the_end_sets()
{
var groups = Groups();
var settings = AtHigh();
var ultra = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.Ultra, settings);
Assert.False(ultra.CompressTextures);
Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Textures]);
var back = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.High, ultra);
Assert.Equal(GraphicsTop.None.CompressTextures, back.CompressTextures);
Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Textures]);
}
[Fact]
public void A_level_in_a_part_between_the_ends_leaves_what_only_an_end_sets()
{
var settings = AtHigh();
settings.MotionBlur = false;
settings.Smoke = false;
var nature = Groups().Apply(GraphicsGroup.Nature, GraphicsPreset.VeryHigh, settings);
Assert.False(nature.Smoke);
Assert.Equal(GraphicsPreset.VeryHigh.SmokeFidelity, nature.SmokeFidelity);
}
}
+164 -396
View File
@@ -17,17 +17,17 @@ public class GraphicsSettingsTests
return installation;
}
private static SimulatorSettings Read(string text, bool dlssPlatform = true)
private static SimulatorSettings Read(string text)
{
var s = new SimulatorSettings();
new SettingsSerializer(dlssPlatform).Read(s, ConfigFile.Parse(text));
new SettingsSerializer().Read(s, ConfigFile.Parse(text));
return s;
}
private static string Write(SimulatorSettings s, string text = "", bool dlssPlatform = true)
private static string Write(SimulatorSettings s, string text = "")
{
var c = ConfigFile.Parse(text);
new SettingsSerializer(dlssPlatform).Write(s, c);
new SettingsSerializer().Write(s, c);
return c.ToText();
}
@@ -37,234 +37,137 @@ public class GraphicsSettingsTests
private static string? Line(string text, string key) =>
Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal));
// As utilities/Globals.cpp has them; a word the simulator does not know is the file's own, written back as it is.
[Theory]
[InlineData("full", GraphicsBackend.OpenGL)]
[InlineData("default", GraphicsBackend.OpenGL)]
[InlineData("gl46", GraphicsBackend.OpenGL)]
[InlineData("legacy", GraphicsBackend.OpenGL)]
[InlineData("experimental", GraphicsBackend.OpenGL)]
[InlineData("vulkan", GraphicsBackend.Vulkan)]
[InlineData("vulkan14", GraphicsBackend.Vulkan)]
public void The_renderer_is_read_with_the_aliases_the_simulator_takes(string value, GraphicsBackend expected)
{
Assert.Equal(expected, Read($"gfxrenderer {value}\n").Backend);
}
[Theory]
[InlineData("full", "full")]
[InlineData("gl46", "full")]
[InlineData("legacy", "legacy")]
[InlineData("simpleshader", "legacy")]
[InlineData("simple", "simple")]
[InlineData("experimental", "experimental")]
[InlineData("vulkan14", "vulkan")]
public void A_renderer_is_written_by_its_name(string read, string written)
[InlineData("vulkan", "vulkan")]
[InlineData("VULKAN14", "vulkan")]
[InlineData("default", "default")]
[InlineData("full", "default")]
[InlineData("gl46", "default")]
[InlineData("opengl", "default")]
[InlineData("legacy", "default")]
[InlineData("simple", "default")]
[InlineData("experimental", "default")]
[InlineData("null", "null")]
public void A_renderer_is_written_by_the_name_the_simulator_reads_it_as(string read, string written)
{
Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer"));
}
[Fact]
public void An_older_renderer_stays_chosen_and_can_be_chosen_again()
public void Without_a_renderer_in_the_file_vulkan_is_chosen_and_written()
{
var installation = WithIni("gfxrenderer legacy\n");
var store = installation.SettingsStore;
store.Settings.Clouds = 3;
store.Save();
Assert.Contains("gfxrenderer legacy", installation.Files.ReadAllText(UserIni));
store.Settings.RenderEngine = SimulatorSettings.VulkanEngine;
store.Save();
Assert.Contains("gfxrenderer vulkan", installation.Files.ReadAllText(UserIni));
Assert.Equal(GraphicsBackend.Vulkan, store.Settings.Backend);
store.Settings.RenderEngine = SimulatorSettings.RenderEngineOf("simple");
store.Save();
Assert.Contains("gfxrenderer simple", installation.Files.ReadAllText(UserIni));
Assert.Equal(GraphicsBackend.OpenGL, store.Settings.Backend);
// The simulator's own is OpenGL: the starter writes Vulkan whatever the file had.
Assert.Equal(GraphicsBackend.Vulkan, Read("").Backend);
Assert.Equal("gfxrenderer vulkan", Line(Write(Read("")), "gfxrenderer"));
}
[Fact]
public void Keys_only_an_older_simulator_reads_stay_in_the_file()
public void Opengl_stays_chosen_and_vulkan_can_be_chosen_again()
{
var installation = WithIni("gfxrenderer default\n");
var store = installation.SettingsStore;
Assert.Equal(GraphicsBackend.OpenGL, store.Settings.Backend);
store.Settings.FieldOfView = 50;
store.Save();
Assert.Contains("gfxrenderer default", installation.Files.ReadAllText(UserIni));
store.Settings.Backend = GraphicsBackend.Vulkan;
store.Save();
Assert.Equal("gfxrenderer vulkan", Line(installation.Files.ReadAllText(UserIni), "gfxrenderer"));
}
[Fact]
public void Keys_the_simulator_no_longer_goes_by_are_taken_out_on_a_save()
{
string[] old =
{
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes",
"gfx.framebuffer.width 1920", "gfx.framebuffer.height 1080", "gfx.shadows.cab.range 20"
"usevbo no", "gfx.angleplatform vulkan", "gfx.usegles yes", "gfx.shadows.cab.range 20", "shadows yes",
"skyenabled yes", "smoothtraction yes", "gfx.framebuffer.width 1280", "gfx.framebuffer.height 720",
"starter.bufferscale 100"
};
var installation = WithIni(string.Join("\n", old) + "\n");
installation.SettingsStore.Settings.Clouds = 3;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.All(old, line => Assert.Contains(line, saved));
Assert.All(old, line => Assert.Null(Line(saved, line.Split(' ')[0])));
}
[Fact]
public void Levels_leave_the_switches_only_an_older_simulator_reads()
public void Keys_of_the_new_renderers_are_kept_as_the_file_has_them()
{
var s = new SimulatorSettings { UseVbo = false, UseGLES = true, RenderAngleVulkan = true };
string[] vulkan =
{
"gfx.antialiasing dlss", "gfx.dlss.preset k", "gfx.framegeneration x2", "gfx.reflex on",
"gfx.raytracing yes", "gfx.ssr high", "gfx.postfx.ao gtao", "gfx.clouds ultra", "gfx.grass yes",
"gfx.buffer.percent 0.67", "gfx.vulkan.device RTX", "gfx.fog yes", "gfx.cabprobe medium", "gfx.gpucull no"
};
var installation = WithIni("calibratein 0 0 0 0\nmultisampling 0\n" + string.Join("\n", vulkan) + "\n");
GraphicsPreset.Ultra.ApplyTo(s);
installation.SettingsStore.Save();
Assert.Equal((false, true, true), (s.UseVbo, s.UseGLES, s.RenderAngleVulkan));
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved);
Assert.All(vulkan, line => Assert.Equal(line, Line(saved, line.Split(' ')[0])));
Assert.Equal(AntiAliasingMode.Dlss, installation.SettingsStore.Settings.AntiAliasing);
Assert.Equal(67, installation.SettingsStore.Settings.BufferScalePercent);
}
[Fact]
public void The_new_graphics_keys_are_read()
public void The_faster_choices_the_simulator_does_not_make_itself_are_written()
{
var s = Read("gfxrenderer vulkan\n" +
"gfx.antialiasing dlss\ngfx.dlss.preset K\ngfx.framegeneration x3\ngfx.reflex boost\n" +
"gfx.raytracing yes\ngfx.raytracing.range 800\ngfx.ssr high\ngfx.postfx.ao ssao\ngfx.postfx.ao.quality 4 6\n" +
"gfx.lights.shadows low\ngfx.contactshadows 3\ngfx.fog analytic\ngfx.fog.quality ultra\n" +
"gfx.clouds ultra\ngfx.clouds.shadows no\ngfx.grass no\ngfx.grass.distance 120\ngfx.grass.density 1.5\n" +
"gfx.buffer.percent 0.67\ngfx.vulkan.device RTX\n");
var installation = WithIni("width 1280\n");
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
Assert.Equal("k", s.DlssPreset);
Assert.Equal(3, s.FrameGeneration);
Assert.Equal(2, s.Reflex);
Assert.True(s.RayTracing);
Assert.Equal(800, s.RayTracingRange);
Assert.Equal(3, s.Ssr);
Assert.Equal(1, s.AmbientOcclusion);
Assert.Equal((4, 6), (s.AoSlices, s.AoSteps));
Assert.Equal(1, s.LightShadows);
Assert.Equal(3, s.ContactShadows);
Assert.False(s.VolumetricFog);
Assert.Equal(4, s.FogQuality);
Assert.Equal(4, s.Clouds);
Assert.False(s.CloudShadows);
Assert.False(s.Grass);
Assert.Equal(120, s.GrassDistance);
Assert.Equal(1.5, s.GrassDensity);
Assert.Equal(67, s.BufferScalePercent);
Assert.Equal("RTX", s.VulkanDevice);
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
foreach (var key in SimulatorKeys.All.Where(key => key.Writes))
Assert.Equal($"{key.Key} {key.Default}", Line(saved, key.Key));
Assert.Equal("gfx.gpucull yes", Line(saved, "gfx.gpucull"));
}
[Theory]
[InlineData("multisampling 0\n", AntiAliasingMode.Off)]
[InlineData("multisampling 1\n", AntiAliasingMode.Msaa2)]
[InlineData("multisampling 2\n", AntiAliasingMode.Msaa4)]
[InlineData("multisampling 3\n", AntiAliasingMode.Msaa8)]
[InlineData("", AntiAliasingMode.Msaa4)]
[InlineData("gfx.antialiasing taa\n", AntiAliasingMode.Taa)]
[InlineData("multisampling 3\ngfx.antialiasing taa\n", AntiAliasingMode.Taa)]
[InlineData("gfx.antialiasing taa\nmultisampling 3\n", AntiAliasingMode.Msaa8)]
[InlineData("multisampling 2\ngfx.antialiasing dlaa\n", AntiAliasingMode.Dlaa)]
[InlineData("multisampling 1\ngfx.antialiasing off\n", AntiAliasingMode.Off)]
public void The_anti_aliasing_is_read_from_the_key_further_down(string text, AntiAliasingMode expected)
{
Assert.Equal(expected, Read(text).AntiAliasing);
}
[Theory]
[InlineData(AntiAliasingMode.Msaa2, "1", "msaax2")]
[InlineData(AntiAliasingMode.Taa, "0", "taa")]
[InlineData(AntiAliasingMode.Dlss, "0", "dlss")]
[InlineData(AntiAliasingMode.Off, "0", "off")]
public void The_anti_aliasing_is_written_to_both_keys(AntiAliasingMode mode, string multisampling, string word)
{
string text = Write(new SimulatorSettings { AntiAliasing = mode });
Assert.Equal($"multisampling {multisampling}", Line(text, "multisampling"));
Assert.Equal($"gfx.antialiasing {word}", Line(text, "gfx.antialiasing"));
}
[Fact]
public void Missing_keys_take_the_simulators_defaults()
public void A_save_puts_the_newer_anti_aliasing_key_below_the_older()
{
var s = Read("");
var installation = WithIni("gfx.antialiasing msaax4\nwidth 1280\nmultisampling 2\n");
installation.SettingsStore.Settings.AntiAliasing = AntiAliasingMode.Taa;
Assert.Equal(GraphicsBackend.OpenGL, s.Backend);
Assert.Equal(AntiAliasingMode.Msaa4, s.AntiAliasing);
Assert.Equal(2, s.Ssr);
Assert.Equal(2, s.AmbientOcclusion);
Assert.Equal(2, s.LightShadows);
Assert.Equal(0, s.ContactShadows);
Assert.True(s.VolumetricFog);
Assert.Equal(2, s.FogQuality);
Assert.Equal(2, s.Clouds);
Assert.False(s.RayTracing);
Assert.Equal(1, s.FrameGeneration);
}
installation.SettingsStore.Save();
[Fact]
public void The_tokens_written_are_the_ones_the_simulator_parses()
{
var s = Read("gfxrenderer vulkan\n");
s.AntiAliasing = AntiAliasingMode.Dlaa;
s.FrameGeneration = 4;
s.Reflex = 1;
s.LightShadows = 3;
s.ContactShadows = 0;
s.Clouds = 4;
s.VolumetricFog = false;
s.FogQuality = 1;
s.AmbientOcclusion = 1;
s.Ssr = 2;
s.RayTracing = true;
string text = Write(s);
Assert.Equal("gfx.antialiasing dlaa", Line(text, "gfx.antialiasing"));
Assert.Equal("multisampling 0", Line(text, "multisampling"));
Assert.Equal("gfx.framegeneration x4", Line(text, "gfx.framegeneration"));
Assert.Equal("gfx.reflex on", Line(text, "gfx.reflex"));
Assert.Equal("gfx.lights.shadows high", Line(text, "gfx.lights.shadows"));
Assert.Equal("gfx.contactshadows no", Line(text, "gfx.contactshadows"));
Assert.Equal("gfx.clouds ultra", Line(text, "gfx.clouds"));
Assert.Equal("gfx.fog analytic", Line(text, "gfx.fog"));
Assert.Equal("gfx.fog.quality low", Line(text, "gfx.fog.quality"));
Assert.Equal("gfx.postfx.ao ssao", Line(text, "gfx.postfx.ao"));
Assert.Equal("gfx.ssr medium", Line(text, "gfx.ssr"));
Assert.Equal("gfx.raytracing yes", Line(text, "gfx.raytracing"));
Assert.Equal("gfx.buffer.percent 100", Line(text, "gfx.buffer.percent"));
}
[Fact]
public void Msaa_is_written_to_both_keys_for_older_simulators()
{
var s = Read("multisampling 1\n");
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
string text = Write(s);
Assert.Equal("multisampling 1", Line(text, "multisampling"));
Assert.Equal("gfx.antialiasing msaax2", Line(text, "gfx.antialiasing"));
}
[Fact]
public void Of_the_two_anti_aliasing_keys_the_later_one_wins_as_in_the_simulator()
{
Assert.Equal(AntiAliasingMode.Taa, Read("multisampling 2\ngfx.antialiasing taa\n").AntiAliasing);
Assert.Equal(AntiAliasingMode.Msaa4, Read("gfx.antialiasing taa\nmultisampling 2\n").AntiAliasing);
}
[Fact]
public void On_opengl_the_vulkan_only_features_are_written_off()
{
var s = Read("gfxrenderer full\ngfx.antialiasing dlss\ngfx.framegeneration x2\ngfx.reflex on\ngfx.raytracing yes\n");
Assert.Equal(AntiAliasingMode.Taa, s.AntiAliasing);
Assert.Equal(1, s.FrameGeneration);
Assert.Equal(0, s.Reflex);
Assert.False(s.RayTracing);
string text = Write(s);
Assert.Equal("gfx.antialiasing taa", Line(text, "gfx.antialiasing"));
Assert.Equal("gfx.framegeneration off", Line(text, "gfx.framegeneration"));
Assert.Equal("gfx.reflex off", Line(text, "gfx.reflex"));
Assert.Equal("gfx.raytracing no", Line(text, "gfx.raytracing"));
}
[Fact]
public void Frame_generation_needs_dlss_even_on_vulkan()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing taa\ngfx.framegeneration x2\ngfx.reflex on\n");
Assert.Equal(1, s.FrameGeneration);
Assert.Equal(1, s.Reflex);
Assert.False(GraphicsRules.ReflexForced(s, true));
}
[Fact]
public void Frame_generation_turns_reflex_on()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlss\ngfx.framegeneration x2\n");
Assert.True(GraphicsRules.ReflexForced(s, true));
}
[Fact]
public void Without_a_dlss_platform_dlss_falls_back_to_taa()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlss\n", dlssPlatform: false);
Assert.Equal(AntiAliasingMode.Taa, s.AntiAliasing);
}
[Fact]
public void Dlaa_ignores_the_render_scale()
{
var s = Read("gfxrenderer vulkan\ngfx.antialiasing dlaa\n");
Assert.False(GraphicsRules.BufferScaleUsed(s, true));
s.AntiAliasing = AntiAliasingMode.Dlss;
Assert.True(GraphicsRules.BufferScaleUsed(s, true));
var lines = Lines(installation.Files.ReadAllText(UserIni)).ToList();
Assert.True(lines.IndexOf("gfx.antialiasing taa") > lines.IndexOf("multisampling 0"));
Assert.Equal(AntiAliasingMode.Taa, Read(installation.Files.ReadAllText(UserIni)).AntiAliasing);
}
[Fact]
@@ -278,22 +181,37 @@ public class GraphicsSettingsTests
}
[Fact]
public void The_render_scale_reads_the_old_starter_key_when_the_new_one_is_missing()
public void The_render_scale_is_the_buffer_percent_or_what_an_older_starter_left()
{
Assert.Equal(50, Read("gfx.buffer.percent 0.5\n").BufferScalePercent);
Assert.Equal(75, Read("gfx.buffer.percent 75\n").BufferScalePercent);
Assert.Equal(75, Read("starter.bufferscale 75\n").BufferScalePercent);
Assert.Equal(50, Read("starter.bufferscale 75\ngfx.buffer.percent 50\n").BufferScalePercent);
Assert.Equal(50, Read("width 1920\ngfx.framebuffer.width 960\n").BufferScalePercent);
Assert.Equal(100, Read("").BufferScalePercent);
}
[Fact]
public void The_render_scale_is_written_as_the_buffer_percent()
{
var s = Read("width 1920\nheight 1080\nstarter.bufferscale 50\n");
string text = Write(s);
Assert.Equal("gfx.buffer.percent 0.5", Line(text, "gfx.buffer.percent"));
Assert.Null(Line(text, "gfx.framebuffer.width"));
Assert.Null(Line(text, "starter.bufferscale"));
}
[Fact]
public void A_level_is_recognised_after_it_is_applied_and_survives_a_save()
{
for (int engine = 0; engine < SimulatorSettings.RenderEngines.Length; engine++)
foreach (var backend in new[] { GraphicsBackend.Vulkan, GraphicsBackend.OpenGL })
{
foreach (var level in GraphicsPreset.All)
{
var installation = WithIni("");
var store = installation.SettingsStore;
store.Settings.RenderEngine = engine;
store.Settings.Backend = backend;
level.ApplyTo(store.Settings);
Assert.Same(level, GraphicsPreset.Matching(store.Settings));
@@ -303,6 +221,7 @@ public class GraphicsSettingsTests
again.Environment.With("HOME", "/home/kolejarz");
again.SettingsStore.Load();
Assert.Same(level, GraphicsPreset.Matching(again.SettingsStore.Settings));
Assert.Equal(backend, again.SettingsStore.Settings.Backend);
}
}
}
@@ -312,7 +231,7 @@ public class GraphicsSettingsTests
{
var s = new SimulatorSettings();
GraphicsPreset.High.ApplyTo(s);
s.Clouds = 4;
s.ShadowRankCutoff = 1;
Assert.Null(GraphicsPreset.Matching(s));
}
@@ -328,82 +247,62 @@ public class GraphicsSettingsTests
}
[Fact]
public void Ray_tracing_comes_with_ultra_on_vulkan_only()
public void No_level_leaves_decorative_consists_out()
{
var vulkan = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine };
var opengl = new SimulatorSettings();
foreach (var level in GraphicsPreset.All)
{
var s = new SimulatorSettings { IgnoreIrrelevantTrains = false };
level.ApplyTo(s);
Assert.False(s.IgnoreIrrelevantTrains, level.NameKey);
GraphicsPreset.Ultra.ApplyTo(vulkan);
GraphicsPreset.Ultra.ApplyTo(opengl);
Assert.True(vulkan.RayTracing);
Assert.False(opengl.RayTracing);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(opengl));
}
[Fact]
public void A_level_keeps_dlss_on_vulkan()
{
var s = new SimulatorSettings { RenderEngine = SimulatorSettings.VulkanEngine, AntiAliasing = AntiAliasingMode.Dlss };
GraphicsPreset.Ultra.ApplyTo(s);
Assert.Equal(AntiAliasingMode.Dlss, s.AntiAliasing);
Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(s));
}
[Fact]
public void A_level_replaces_taa_with_its_own_multisampling()
{
var s = new SimulatorSettings { AntiAliasing = AntiAliasingMode.Taa };
GraphicsPreset.Medium.ApplyTo(s);
Assert.Equal(AntiAliasingMode.Msaa2, s.AntiAliasing);
s.IgnoreIrrelevantTrains = true;
level.ApplyTo(s);
Assert.True(s.IgnoreIrrelevantTrains, level.NameKey);
}
}
[Fact]
public void An_import_takes_the_settings_but_keeps_this_installations_simulator_and_the_unmanaged_lines()
{
var installation = WithIni("starter.exe.auto no\nstarter.exe.path eu07_local.exe\ncalibratein 0 0 0 0\ngfx.clouds low\n");
installation.Files.WithFile("/backup/eu07.ini", "starter.exe.auto no\nstarter.exe.path eu07_other.exe\ngfx.clouds ultra\ngfxrenderer vulkan\n");
var installation = WithIni("starter.exe.auto no\nstarter.exe.path eu07_local.exe\ncalibratein 0 0 0 0\nfieldofview 45\n");
installation.Files.WithFile("/backup/eu07.ini", "starter.exe.auto no\nstarter.exe.path eu07_other.exe\nfieldofview 60\ngfxrenderer legacy\n");
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
var s = installation.SettingsStore.Settings;
Assert.Equal(4, s.Clouds);
Assert.Equal(GraphicsBackend.Vulkan, s.Backend);
Assert.Equal(60, s.FieldOfView);
Assert.Equal(GraphicsBackend.OpenGL, s.Backend);
Assert.Equal("eu07_local.exe", s.ExecutablePath);
// Nothing is written until saved, and the save keeps the user's own lines.
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved);
Assert.Contains("gfx.clouds ultra", saved);
Assert.Contains("fieldofview 60", saved);
Assert.Contains("starter.exe.path eu07_local.exe", saved);
}
[Fact]
public void An_import_of_a_missing_file_changes_nothing()
{
var installation = WithIni("gfx.clouds low\n");
var installation = WithIni("fieldofview 50\n");
Assert.False(installation.SettingsStore.ImportFrom("/nowhere/eu07.ini"));
Assert.Equal(1, installation.SettingsStore.Settings.Clouds);
Assert.Equal(50, installation.SettingsStore.Settings.FieldOfView);
}
[Fact]
public void An_export_writes_a_complete_file_elsewhere_and_leaves_the_users_one_alone()
{
var installation = WithIni("calibratein 0 0 0 0\ngfx.clouds low\n");
installation.SettingsStore.Settings.Clouds = 3;
var installation = WithIni("calibratein 0 0 0 0\nfieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
Assert.True(installation.SettingsStore.ExportTo("/export/eu07.ini"));
string exported = installation.Files.ReadAllText("/export/eu07.ini");
Assert.Contains("calibratein 0 0 0 0", exported);
Assert.Contains("gfx.clouds high", exported);
Assert.Contains("gfx.clouds low", installation.Files.ReadAllText(UserIni));
Assert.Contains("fieldofview 60", exported);
Assert.Contains("fieldofview 45", installation.Files.ReadAllText(UserIni));
}
[Fact]
@@ -417,30 +316,34 @@ public class GraphicsSettingsTests
}
[Fact]
public void The_dlss_libraries_are_looked_for_next_to_a_windows_build()
public void The_gamepad_is_ignored_unless_the_file_turns_it_on()
{
var files = new InMemoryFileSystem()
.WithDirectory(TestInstallation.Root)
.WithExecutable(TestInstallation.At("eu07.exe"), "MZ binary")
.WithFile(TestInstallation.At("nvngx_dlss.dll"), "dll");
var installation = new TestInstallation(files);
Assert.Equal((true, false), installation.Executables.DlssLibraries(TestInstallation.At("eu07.exe")));
files.WithFile(TestInstallation.At("nvngx_dlssg.dll"), "dll");
Assert.Equal((true, true), installation.Executables.DlssLibraries(TestInstallation.At("eu07.exe")));
Assert.True(Read("").IgnoreGamepad);
Assert.Equal("input.gamepad no", Line(Write(Read("")), "input.gamepad"));
Assert.False(Read("input.gamepad yes\n").IgnoreGamepad);
Assert.True(Read("input.gamepad no\n").IgnoreGamepad);
}
[Fact]
public void The_dlss_libraries_of_a_linux_build_are_the_shared_objects()
public void The_standard_mode_is_where_a_player_starts_and_the_choice_is_kept()
{
var files = new InMemoryFileSystem()
.WithDirectory(TestInstallation.Root)
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
.WithFile(TestInstallation.At("libnvidia-ngx-dlssg.so.310.4.0"), "so");
var installation = new TestInstallation(files);
Assert.False(Read("").AdvancedSettings);
Assert.True(Read("starter.settings.advanced yes\n").AdvancedSettings);
Assert.Equal((false, true), installation.Executables.DlssLibraries(TestInstallation.At("eu07")));
var s = Read("");
s.AdvancedSettings = true;
Assert.Equal("starter.settings.advanced yes", Line(Write(s), "starter.settings.advanced"));
}
[Fact]
public void The_move_to_the_standard_mode_is_marked_in_the_file()
{
Assert.False(Read("").MovedToStandard);
Assert.True(Read("starter.settings.standard yes\n").MovedToStandard);
var s = Read("");
s.MovedToStandard = true;
Assert.Equal("starter.settings.standard yes", Line(Write(s), "starter.settings.standard"));
}
[Fact]
@@ -455,139 +358,4 @@ public class GraphicsSettingsTests
c.Set("b", "9");
Assert.Equal("b 9\nc 3\na 1\n", c.ToText().Replace("\r\n", "\n"));
}
[Fact]
public void The_ao_lighting_and_cab_probe_keys_survive_a_round_trip_in_the_simulators_form()
{
var s = Read("gfx.postfx.ao.lighting no\ngfx.cabprobe high\ngfx.cabprobe.interval 12\ngfx.cabprobe.bounce 2.5\ngfx.cabprobe.reflections no\n");
Assert.False(s.AoLighting);
Assert.Equal(3, s.CabProbe);
Assert.Equal(12, s.CabProbeInterval);
Assert.Equal(2.5, s.CabProbeBounce);
Assert.False(s.CabProbeReflections);
string text = Write(s);
Assert.Equal("gfx.postfx.ao.lighting no", Line(text, "gfx.postfx.ao.lighting"));
Assert.Equal("gfx.cabprobe high", Line(text, "gfx.cabprobe"));
Assert.Equal("gfx.cabprobe.interval 12", Line(text, "gfx.cabprobe.interval"));
Assert.Equal("gfx.cabprobe.bounce 2.5", Line(text, "gfx.cabprobe.bounce"));
Assert.Equal("gfx.cabprobe.reflections no", Line(text, "gfx.cabprobe.reflections"));
var again = Read(text);
Assert.Equal((s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections),
(again.AoLighting, again.CabProbe, again.CabProbeInterval, again.CabProbeBounce, again.CabProbeReflections));
}
[Fact]
public void Missing_ao_lighting_and_cab_probe_keys_take_the_simulators_defaults_and_are_written_like_its_export()
{
var s = Read("");
Assert.Equal((true, 2, 4, 1.0, true), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections));
string text = Write(s);
Assert.Equal("gfx.postfx.ao.lighting yes", Line(text, "gfx.postfx.ao.lighting"));
Assert.Equal("gfx.cabprobe medium", Line(text, "gfx.cabprobe"));
Assert.Equal("gfx.cabprobe.interval 4", Line(text, "gfx.cabprobe.interval"));
Assert.Equal("gfx.cabprobe.bounce 1", Line(text, "gfx.cabprobe.bounce"));
Assert.Equal("gfx.cabprobe.reflections yes", Line(text, "gfx.cabprobe.reflections"));
}
[Fact]
public void Unknown_ao_lighting_and_cab_probe_values_fall_back_to_the_simulators_defaults()
{
var s = Read("gfx.postfx.ao.lighting maybe\ngfx.cabprobe bogus\ngfx.cabprobe.interval abc\ngfx.cabprobe.bounce x\ngfx.cabprobe.reflections ?\n");
Assert.Equal((true, 2, 4, 1.0, true), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeBounce, s.CabProbeReflections));
}
[Theory]
[InlineData("no", 0)]
[InlineData("0", 0)]
[InlineData("low", 1)]
[InlineData("1", 1)]
[InlineData("medium", 2)]
[InlineData("yes", 2)]
[InlineData("2", 2)]
[InlineData("high", 3)]
[InlineData("3", 3)]
public void The_cab_probe_level_is_read_with_the_aliases_the_simulator_takes(string value, int expected)
{
Assert.Equal(expected, Read($"gfx.cabprobe {value}\n").CabProbe);
}
[Fact]
public void The_cab_probe_numbers_are_kept_within_the_simulators_ranges()
{
var s = Read("gfx.cabprobe.interval 500\ngfx.cabprobe.bounce 9\n");
Assert.Equal((120, 4.0), (s.CabProbeInterval, s.CabProbeBounce));
s = Read("gfx.cabprobe.interval 0\ngfx.cabprobe.bounce -1\n");
Assert.Equal((1, 0.0), (s.CabProbeInterval, s.CabProbeBounce));
}
[Fact]
public void The_ao_lighting_counts_with_gtao_only()
{
Assert.True(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao gtao\n")));
Assert.False(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao ssao\n")));
Assert.False(GraphicsRules.AoLightingUsed(Read("gfx.postfx.ao no\n")));
}
[Theory]
[InlineData("gfx.ssr no\ngfx.contactshadows no\n", true)]
[InlineData("gfx.ssr low\ngfx.contactshadows no\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows low\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.depthprepass.scene yes\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.postfx.ao.lighting no\n", false)]
[InlineData("gfx.ssr no\ngfx.contactshadows no\ngfx.postfx.ao ssao\n", false)]
public void The_ao_lighting_adds_the_depth_pass_only_when_nothing_else_draws_it(string text, bool expected)
{
Assert.Equal(expected, GraphicsRules.AoLightingAddsDepthPrepass(Read(text)));
}
[Theory]
[InlineData("gfx.cabprobe medium\n", true, true)]
[InlineData("gfx.cabprobe no\n", false, false)]
[InlineData("gfx.cabprobe low\ngfx.lights.clustered no\n", true, false)]
[InlineData("gfx.cabprobe high\ngfx.lights.cab no\n", true, false)]
public void The_cab_probe_lights_the_cab_only_with_its_lamp_as_a_light(string text, bool used, bool lights)
{
var s = Read(text);
Assert.Equal(used, GraphicsRules.CabProbeUsed(s));
Assert.Equal(lights, GraphicsRules.CabProbeLights(s));
}
[Theory]
[InlineData(0, false, 0, 8, false)]
[InlineData(1, false, 0, 8, false)]
[InlineData(2, false, 1, 8, true)]
[InlineData(3, true, 2, 4, true)]
[InlineData(4, true, 3, 3, true)]
[InlineData(5, true, 3, 2, true)]
public void A_level_sets_the_ao_lighting_and_the_cab_probe(int place, bool aoLighting, int probe, int interval, bool reflections)
{
var level = GraphicsPreset.All[place];
var s = new SimulatorSettings { CabProbeBounce = 2.5 };
level.ApplyTo(s);
Assert.Equal((aoLighting, probe, interval, reflections), (s.AoLighting, s.CabProbe, s.CabProbeInterval, s.CabProbeReflections));
Assert.Equal(2.5, s.CabProbeBounce);
Assert.Same(level, GraphicsPreset.Matching(s));
}
[Fact]
public void An_import_keeps_the_lamp_switch_of_the_users_own_file()
{
var installation = WithIni("gfx.lights.cab no\n");
installation.Files.WithFile("/backup/eu07.ini", "gfx.lights.cab yes\ngfx.cabprobe high\n");
Assert.True(installation.SettingsStore.ImportFrom("/backup/eu07.ini"));
Assert.False(installation.SettingsStore.Settings.CabLampLight);
Assert.Equal(3, installation.SettingsStore.Settings.CabProbe);
}
}
+5 -1
View File
@@ -31,9 +31,13 @@ public class LocalizationTests
var english = Strings(all.Single(l => l.Code == "en").Path);
var other = Strings(all.Single(l => l.Code == code).Path);
// The developer tab's rows (Ini.*) and the words of their lists (Choice.*) come in English where a
// language lacks them (SimulatorKeyRows), as the descriptions do.
var missing = english.Keys
.Where(key => !key.EndsWith("Desc", StringComparison.Ordinal) &&
!key.StartsWith("Cmd.", StringComparison.Ordinal))
!key.StartsWith("Cmd.", StringComparison.Ordinal) &&
!key.StartsWith("Ini.", StringComparison.Ordinal) &&
!key.StartsWith("Choice.", StringComparison.Ordinal))
.Where(key => !other.ContainsKey(key));
Assert.Empty(missing);
+139
View File
@@ -0,0 +1,139 @@
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class MonitorsTests
{
[Fact]
public void A_monitor_is_named_as_the_simulator_names_it()
{
Assert.Equal("Generic_PnP_Monitor:1920,0", Monitors.IdOf("Generic PnP Monitor", 1920, 0));
Assert.Equal("HDMI-1:-1280,-200", Monitors.IdOf("HDMI-1", -1280, -200));
}
[Fact]
public void Xrandr_lists_the_connected_outputs_with_their_place()
{
const string report =
"Screen 0: minimum 320 x 200, current 4480 x 1440, maximum 16384 x 16384\n" +
"eDP-1 connected primary 1920x1080+0+360 (normal left inverted right x axis y axis) 344mm x 194mm\n" +
" 1920x1080 60.00*+\n" +
"HDMI-1 connected 2560x1440+1920+0 (normal left inverted right x axis y axis) 597mm x 336mm\n" +
"DP-1 disconnected (normal left inverted right x axis y axis)\n" +
"DP-2 connected (normal left inverted right x axis y axis)\n";
var monitors = Monitors.Parse(report);
Assert.Equal(2, monitors.Count);
Assert.Equal(new DisplayMonitor("eDP-1:0,360", "eDP-1", 1920, 1080, true, 60), monitors[0]);
Assert.Equal(new DisplayMonitor("HDMI-1:1920,0", "HDMI-1", 2560, 1440, false), monitors[1]);
}
[Fact]
public void Xrandr_gives_each_monitor_the_rate_its_mode_runs_at()
{
const string report =
"DP-1 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 597mm x 336mm\n" +
" 2560x1440 59.95 + 165.08* 143.97\n" +
" 1920x1080 60.00 50.00\n" +
"HDMI-1 connected 1920x1080+2560+0 (normal left inverted right x axis y axis) 527mm x 296mm\n" +
" 1920x1080 60.00*+ 50.00\n" +
"DP-2 disconnected (normal left inverted right x axis y axis)\n" +
" 1280x1024 75.02*\n";
var monitors = Monitors.Parse(report);
Assert.Equal(new[] { 165, 60 }, monitors.Select(m => m.RefreshRate));
}
[Fact]
public void The_monitor_is_written_only_when_one_is_chosen()
{
var s = new StarterNG.Domain.Settings.SimulatorSettings();
var c = StarterNG.Classes.ConfigFile.Parse("");
new StarterNG.Infrastructure.Settings.SettingsSerializer().Write(s, c);
Assert.False(c.Has("fullscreenmonitor"));
s.FullscreenMonitor = "HDMI-1:1920,0";
new StarterNG.Infrastructure.Settings.SettingsSerializer().Write(s, c);
Assert.Equal("HDMI-1:1920,0", c.GetRaw("fullscreenmonitor"));
}
[Fact]
public void The_size_is_of_the_monitor_named_or_of_the_primary_one()
{
var monitors = new[]
{
new DisplayMonitor("eDP-1:0,360", "eDP-1", 1920, 1080, true),
new DisplayMonitor("HDMI-1:1920,0", "HDMI-1", 2560, 1440, false)
};
Assert.Equal((2560, 1440), Monitors.SizeOf(monitors, "HDMI-1:1920,0"));
Assert.Equal((1920, 1080), Monitors.SizeOf(monitors, ""));
// Not connected: the simulator goes to the primary one.
Assert.Equal((1920, 1080), Monitors.SizeOf(monitors, "DP-3:4480,0"));
Assert.Null(Monitors.SizeOf(Array.Empty<DisplayMonitor>(), "HDMI-1:1920,0"));
}
// ── A name outside ASCII: the simulator compares the file's bytes with GLFW's UTF-8 name ──
private static readonly string UserIni = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
private static StarterNG.Tests.Fakes.TestInstallation WithIni(byte[] ini)
{
var files = new StarterNG.Tests.Fakes.InMemoryFileSystem();
files.WriteAllBytes(UserIni, ini);
var installation = new StarterNG.Tests.Fakes.TestInstallation(files);
installation.Environment.With("HOME", "/home/kolejarz");
installation.SettingsStore.Load();
return installation;
}
private static bool Holds(byte[] file, byte[] part) => file.AsSpan().IndexOf(part) >= 0;
[Theory]
[InlineData("Obecný_monitor_PnP:1920,0")]
[InlineData("Écran_à_Ábc:0,0")]
[InlineData("Монитор_Рабочий:-1920,0")]
[InlineData("显示器:0,0")]
public void A_monitors_name_goes_into_the_file_as_the_utf8_the_simulator_compares(string id)
{
var cp1250 = StarterNG.Infrastructure.Adapters.LegacyText.CodePage1250;
var installation = WithIni(cp1250.GetBytes("lang pl\n// zażółć\nfullscreen yes\n"));
installation.SettingsStore.Settings.FullscreenMonitor = id;
installation.SettingsStore.Save();
byte[] saved = installation.Files.ReadAllBytes(UserIni);
Assert.True(Holds(saved, System.Text.Encoding.UTF8.GetBytes("fullscreenmonitor " + id)));
// The rest of the file stays in the simulator's code page.
Assert.True(Holds(saved, cp1250.GetBytes("// zażółć")));
Assert.Equal(id, WithIni(saved).SettingsStore.Settings.FullscreenMonitor);
}
[Fact]
public void A_monitors_name_written_in_the_code_page_is_read_and_goes_as_utf8_on_a_save()
{
const string id = "Obecný_monitor_PnP:1920,0";
var cp1250 = StarterNG.Infrastructure.Adapters.LegacyText.CodePage1250;
var installation = WithIni(cp1250.GetBytes($"fullscreen yes\nfullscreenmonitor {id}\n"));
Assert.Equal(id, installation.SettingsStore.Settings.FullscreenMonitor);
installation.SettingsStore.Save();
byte[] saved = installation.Files.ReadAllBytes(UserIni);
Assert.True(Holds(saved, System.Text.Encoding.UTF8.GetBytes("fullscreenmonitor " + id)));
Assert.False(Holds(saved, cp1250.GetBytes("fullscreenmonitor " + id)));
}
[Fact]
public void An_ascii_name_of_a_monitor_stays_as_the_file_has_it()
{
var installation = WithIni(System.Text.Encoding.ASCII.GetBytes("fullscreenmonitor HDMI-1:1920,0\n"));
installation.SettingsStore.Save();
Assert.True(Holds(installation.Files.ReadAllBytes(UserIni),
System.Text.Encoding.ASCII.GetBytes("fullscreenmonitor HDMI-1:1920,0")));
}
}
+30
View File
@@ -65,6 +65,36 @@ public class PhysicsAndAssetsTests
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]
public void An_include_named_in_other_case_is_followed()
{
+105
View File
@@ -0,0 +1,105 @@
using StarterNG.Domain.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class PhysicsPresetTests
{
private static SimulatorSettings Defaults()
{
var installation = new TestInstallation();
installation.SettingsStore.Load();
return installation.SettingsStore.Settings.Copy();
}
[Fact]
public void The_simulators_own_physics_are_neither_arcade_nor_realistic()
{
Assert.Null(PhysicsPreset.Matching(Defaults()));
}
[Fact]
public void A_level_of_realism_applied_is_recognised_until_one_setting_moves()
{
foreach (var preset in PhysicsPreset.All)
{
var settings = Defaults();
preset.ApplyTo(settings);
Assert.Same(preset, PhysicsPreset.Matching(settings));
settings.CrashDamage = !settings.CrashDamage;
Assert.Null(PhysicsPreset.Matching(settings));
}
}
[Fact]
public void Arcade_forgives_and_realistic_takes_the_physical_models()
{
var arcade = Defaults();
PhysicsPreset.Arcade.ApplyTo(arcade);
Assert.False(arcade.CrashDamage);
Assert.False(arcade.LiveTraction);
Assert.Equal(ConsistReadyOverride.AlwaysReady, arcade.ReadyOverride);
Assert.Equal("off", arcade.Extra["physics.derailment"]);
var realistic = Defaults();
PhysicsPreset.Realistic.ApplyTo(realistic);
Assert.True(realistic.CrashDamage);
Assert.Equal(ConsistReadyOverride.Scenery, realistic.ReadyOverride);
Assert.Equal("yes", realistic.Extra["couplerphysics"]);
Assert.Equal("new", realistic.Extra["physics.derailment"]);
Assert.Equal("new", realistic.Extra["physics.collisions"]);
Assert.Equal("auto", realistic.Extra["physics.trackbuckling"]);
}
[Fact]
public void Every_value_of_a_level_is_one_its_row_offers()
{
foreach (var preset in PhysicsPreset.All)
foreach (var (name, value) in preset.Keys)
Assert.True(SimulatorKeys.Named(name).ChoiceIndex(value) >= 0, $"{preset.NameKey} {name} {value}");
Assert.All(PhysicsPreset.All.SelectMany(preset => preset.Keys.Keys), key => Assert.Contains(key, PhysicsPreset.AllKeys));
}
[Fact]
public void No_level_of_realism_touches_the_picture_nor_a_level_of_detail_the_realism()
{
var settings = Defaults();
GraphicsPreset.Low.ApplyTo(settings);
PhysicsPreset.Realistic.ApplyTo(settings);
Assert.Same(GraphicsPreset.Low, GraphicsPreset.Matching(settings));
GraphicsPreset.VeryHigh.ApplyTo(settings);
Assert.Same(PhysicsPreset.Realistic, PhysicsPreset.Matching(settings));
}
[Theory]
[InlineData("couplerphysics", "true", "yes")]
[InlineData("couplerphysics", "1", "yes")]
[InlineData("physics.derailment", "no", "off")]
[InlineData("physics.trackbuckling", "no", "off")]
[InlineData("couplerphysics", "no", "no")]
public void A_word_the_simulator_takes_for_another_stands_for_it(string name, string raw, string word)
{
var key = SimulatorKeys.Named(name);
Assert.Equal(key.ChoiceIndex(word), key.ChoiceIndex(raw));
}
[Fact]
public void A_level_of_realism_survives_a_save()
{
var installation = new TestInstallation();
var store = installation.SettingsStore;
store.Load();
PhysicsPreset.Realistic.ApplyTo(store.Settings);
store.Save();
var again = new TestInstallation(installation.Files).SettingsStore;
again.Load();
Assert.Same(PhysicsPreset.Realistic, PhysicsPreset.Matching(again.Settings));
string saved = installation.Files.ReadAllText(store.SavePath);
Assert.Contains("physics.derailment new", saved);
Assert.Contains("couplerphysics yes", saved);
}
}
+72
View File
@@ -0,0 +1,72 @@
using Avalonia.Controls;
using StarterNG.Controls;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class PrecipitationItemTests
{
// Shown in whatever language the tests run in: the key alone, or English once a test built the application.
private static void ShowsText(string key, PrecipitationItem item)
{
Assert.Equal(key, item.Key);
Assert.Equal(AppLanguage.Text(key), item.Content);
}
[Fact]
public void Light_precipitation_is_light_rain_until_told_it_snows()
{
var item = new PrecipitationItem();
ShowsText("OvercastRainLight", item);
item.Snow = true;
ShowsText("OvercastSnowLight", item);
}
[Fact]
public void Heavy_precipitation_is_rain_or_snow()
{
var item = new PrecipitationItem { Heavy = true };
ShowsText("OvercastRain", item);
item.Snow = true;
ShowsText("OvercastSnow", item);
}
[Fact]
public void The_option_keeps_its_name_in_a_dropdown_and_out_of_it()
{
var item = new PrecipitationItem { Heavy = true, Snow = true };
var combo = new ComboBox { Items = { item } };
ShowsText("OvercastSnow", item);
combo.Items.Remove(item);
item.Snow = false;
ShowsText("OvercastRain", item);
}
[Fact]
public void In_a_window_the_option_looks_like_any_other_and_still_follows_the_temperature()
{
var item = new PrecipitationItem { Heavy = true };
var combo = new ComboBox { Items = { new ComboBoxItem { Content = "Bezchmurnie" }, item } };
var window = Controls.Show(combo, themed: true);
combo.IsDropDownOpen = true;
window.UpdateLayout();
Assert.NotNull(item.Template);
item.Snow = true;
ShowsText("OvercastSnow", item);
window.Close();
item.Snow = false;
ShowsText("OvercastRain", item);
}
}
+81 -2
View File
@@ -270,7 +270,7 @@ public class ScenerySyntaxTests
trainset td/rozklad tdo_n1734 0.0 0.1
//$o Skład gotowy na żeberku.
endtrainset
include koniec.scm
include koniec.scm end
""";
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, _ => true);
@@ -331,13 +331,61 @@ public class ScenerySyntaxTests
Assert.Equal((SceneryFaultKind.MissingInclude, "x.scn", 2, null, "brak.scm"), Seen(Assert.Single(faults)));
}
[Fact]
public void A_vehicle_without_its_fiz_is_reported_as_one_the_simulator_leaves_out()
{
// As on Bałtyk Cargo: the wagons of a folder gone empty drop out of the consist.
const string scn = """
trainset none tor1 0 0.1
node -1 0 sm42 dynamic PKP\SM42_V1 6D-468 6D -1 headdriver 3 0 enddynamic
node -1 0 eaos-33 dynamic PKP\412W_V1 5340976-0 412wc 0 nobody 3 60 wegiel3 enddynamic
node -1 0 eaos-34 dynamic PKP\412W_V1 5351442-9 412W 0 nobody 0 60 mial1 enddynamic
endtrainset
node -1 0 auto dynamic car car car tor1 0 headdriver 0 0 enddynamic
""";
var asked = new List<(string, string)>();
var scenery = TestScenery.Parser().Parse("scenery/x.scn", scn, loadsVehicle: (folder, mmd) =>
{
asked.Add((folder, mmd));
return !folder.Equals(@"PKP\412W_V1", StringComparison.Ordinal);
});
Assert.Equal(new[]
{
(SceneryFaultKind.VehicleMissing, "x.scn", 3, (string?)"eaos-33", (string?)@"PKP\412W_V1/412wc.fiz"),
(SceneryFaultKind.VehicleMissing, "x.scn", 4, "eaos-34", @"PKP\412W_V1/412W.fiz")
}, scenery.Faults.Select(Seen));
Assert.Contains(("car", "car"), asked);
// Still listed whole: the starter writes them as they are, for when they are back.
Assert.Equal(3, Assert.Single(scenery.Trainsets).Vehicles.Count);
}
[Fact]
public void A_vehicle_folder_there_but_empty_is_no_vehicle()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/x.scn",
"trainset none tor1 0 0\n" +
"node -1 0 a1 dynamic PKP\\430W_V2 skin 430W 0 nobody 3 0 enddynamic\n" +
"node -1 0 a2 dynamic PKP\\412W_V1 skin 412W 0 nobody 0 0 enddynamic\n" +
"endtrainset\n")
.WithLegacyFile("game/dynamic/pkp/430w_v2/430w.fiz", "")
.WithLegacyFile("game/dynamic/pkp/412w_v1/412w.mmd", "");
var faults = TestScenery.Repository(files).Load("game/scenery/x.scn")!.Faults;
Assert.Equal((SceneryFaultKind.VehicleMissing, "x.scn", 3, "a2", @"PKP\412W_V1/412W.fiz"), Seen(Assert.Single(faults)));
}
[Fact]
public void An_include_named_in_another_case_is_found_as_the_simulator_finds_it()
{
var files = new InMemoryFileSystem(caseSensitive: true)
.WithLegacyFile("game/scenery/x.scn", "FirstInit\ninclude Tomaszewo/Auta.SCM end\n")
.WithLegacyFile("game/scenery/tomaszewo/auta.scm",
"trainset auto road1 0 50\nnode -1 0 a1 dynamic car car car 0 headdriver 3 0 enddynamic\nendtrainset\n");
"trainset auto road1 0 50\nnode -1 0 a1 dynamic car car car 0 headdriver 3 0 enddynamic\nendtrainset\n")
.WithLegacyFile("game/dynamic/car/car.fiz", "");
var repository = TestScenery.Repository(files);
var scenery = repository.Load("game/scenery/x.scn")!;
@@ -378,4 +426,35 @@ public class ScenerySyntaxTests
Assert.Equal(sbt, scenery.HasCompanionTimetable);
Assert.Equal(sbt ? 0 : 1, scenery.Faults.Count);
}
[Fact]
public void An_include_with_no_end_is_a_fault_even_as_the_last_line()
{
const string scn = "FirstInit\ntrainset a t 0 0\nendtrainset\ninclude dekoracje.scm //Sklady dekoracyjne\n";
var faults = TestScenery.Parser().Parse("scenery/x.scn", scn).Faults.Select(f => (f.Kind, f.Line)).ToList();
Assert.Equal(new[] { (SceneryFaultKind.IncludeNotClosed, 4) }, faults);
}
[Fact]
public void The_consists_of_a_last_include_with_no_end_are_listed_as_the_simulator_loads_them()
{
const string decorations = "trainset d1 t1 0 0\nnode -1 0 a dynamic d s m 0 nobody 3 0 enddynamic\nendtrainset\n";
string text = SceneryIncludes.Inline("FirstInit\ninclude dekoracje.scm //Sklady dekoracyjne\n",
name => (name, decorations));
Assert.Contains(SceneryIncludes.BeginMarker + "dekoracje.scm", text);
Assert.Contains("trainset d1 t1 0 0", text);
}
[Fact]
public void An_include_with_no_end_before_more_of_the_file_is_left_alone()
{
string text = SceneryIncludes.Inline("FirstInit\ninclude dekoracje.scm\ntrainset a t 0 0\nendtrainset\n",
name => (name, "trainset d1 t1 0 0\nendtrainset\n"));
Assert.DoesNotContain(SceneryIncludes.BeginMarker, text);
}
}
+27 -1
View File
@@ -78,10 +78,36 @@ public class SceneryWeatherTests
{
var weather = new SceneryWeather { Overcast = 0.42, OvercastRandom = true };
Assert.Equal(-1.5, weather.EffectiveOvercast(new StubRandom()));
Assert.Equal(0, weather.EffectiveOvercast(new StubRandom()));
Assert.Equal(0.42, new SceneryWeather { Overcast = 0.42 }.EffectiveOvercast(new StubRandom()));
}
[Fact]
public void No_random_overcast_preset_is_one_the_simulator_would_draw_again()
{
var weather = new SceneryWeather { OvercastRandom = true };
for (int i = 0; i < 10; i++)
Assert.InRange(weather.EffectiveOvercast(new StubRandom(i)), 0, 2);
}
[Fact]
public void A_negative_overcast_in_the_scenery_is_read_as_random()
{
var weather = TestScenery.Parser(new DateTime(2026, 1, 1))
.Parse("scenery/x.scn", "atmo 0 0 0 50 900 0 0 0 -1.5 endatmo").Weather;
Assert.True(weather.OvercastRandom);
Assert.False(weather.Changed);
}
[Theory]
[InlineData(2, false)]
[InlineData(1, true)]
[InlineData(-10, true)]
public void Precipitation_is_snow_at_or_below_one_degree(double temperature, bool snow) =>
Assert.Equal(snow, SceneryWeather.Snows(temperature));
private static string Rewritten(string scn) =>
SceneryWeatherWriter.Rewrite(scn, new SceneryWeather(), new StubRandom());
+1 -3
View File
@@ -158,14 +158,12 @@ public class ScreenReaderNamesTests
var slider = new Slider();
var row = new SettingRow { Label = "Ekran", Content = Row(check, slider) };
row.Description = "Gra zajmie cały ekran.";
row.IdleNote = "Ten symulator nie zna tego ustawienia.";
Assert.Equal("Gra zajmie cały ekran., Ten symulator nie zna tego ustawienia.", AutomationProperties.GetHelpText(check));
Assert.Equal("Gra zajmie cały ekran.", AutomationProperties.GetHelpText(check));
Assert.Equal(AutomationProperties.GetHelpText(check), AutomationProperties.GetHelpText(slider));
Assert.Null(AutomationProperties.GetName(check));
row.Description = null;
row.IdleNote = null;
Assert.Null(AutomationProperties.GetHelpText(check));
}
-154
View File
@@ -1,154 +0,0 @@
using StarterNG.Domain.Settings;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
public class SettingReachTests
{
private static SimulatorTarget Linux(string renderer = "full", bool server = false) =>
new(WindowsBuild: false, renderer, server);
[Theory]
[InlineData("feedbackmode")]
[InlineData("feedbackport")]
[InlineData("showsystemconsole")]
[InlineData("gfx.angleplatform")]
public void Windows_only_keys_idle_on_a_linux_build(string key)
{
Assert.Equal(IdleReason.WindowsBuildOnly, SettingReach.Why(key, Linux()));
Assert.Equal(IdleReason.None, SettingReach.Why(key, Linux() with { WindowsBuild = true }));
}
[Theory]
[InlineData("full", IdleReason.LegacyRendererOnly)]
[InlineData("experimental", IdleReason.LegacyRendererOnly)]
[InlineData("legacy", IdleReason.None)]
[InlineData("simpleshader", IdleReason.None)]
[InlineData("simple", IdleReason.None)]
public void Legacy_renderer_keys_follow_the_renderer(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("smoothtraction", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("usevbo", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.shadows.cab.range", Linux(renderer)));
}
[Fact]
public void Pausing_in_the_background_needs_a_network_server()
{
Assert.Equal(IdleReason.NeedsNetworkServer, SettingReach.Why("inactivepause", Linux()));
Assert.Equal(IdleReason.None, SettingReach.Why("inactivepause", Linux(server: true)));
}
[Fact]
public void The_starters_own_keys_never_idle()
{
Assert.Equal(IdleReason.None, SettingReach.Why("starter.autoclose", Linux()));
}
[Theory]
[InlineData("width, height")]
[InlineData("fullscreen")]
public void The_monitors_own_mode_overrides_size_and_full_screen(string key)
{
Assert.Equal(IdleReason.MonitorModeInstead,
SettingReach.Why(key, Linux() with { FullscreenWindowed = true }));
Assert.Equal(IdleReason.None, SettingReach.Why(key, Linux()));
}
[Fact]
public void An_ordinary_key_works_everywhere()
{
Assert.Equal(IdleReason.None, SettingReach.Why("fieldofview", Linux()));
}
[Theory]
[InlineData("full", IdleReason.None)]
[InlineData("legacy", IdleReason.ModernRendererOnly)]
[InlineData("experimental", IdleReason.ModernRendererOnly)]
public void Effects_of_the_full_renderer_follow_the_renderer(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("gfx.postfx.motionblur.enabled", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.envmap.enabled", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("sleeperdistance", Linux(renderer)));
}
[Theory]
[InlineData("vulkan", IdleReason.None)]
[InlineData("vulkan14", IdleReason.None)]
[InlineData("full", IdleReason.VulkanOnly)]
[InlineData("gl46", IdleReason.VulkanOnly)]
[InlineData("legacy", IdleReason.VulkanOnly)]
public void What_only_vulkan_reads_follows_the_renderer(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("gfx.dlss.preset", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.framegeneration", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.raytracing", Linux(renderer)));
// Both renderers of the new simulator read this one.
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.postfx.ao", Linux(renderer)));
}
[Theory]
[InlineData("vulkan")]
[InlineData("vulkan14")]
[InlineData("opengl")]
[InlineData("gl46")]
public void The_new_simulators_renderers_read_what_the_full_one_does(string renderer)
{
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.envmap.enabled", Linux(renderer)));
Assert.Equal(IdleReason.None, SettingReach.Why("multisampling", Linux(renderer)));
}
[Theory]
[InlineData("full", IdleReason.None)]
[InlineData("legacy", IdleReason.None)]
[InlineData("experimental", IdleReason.OpenGlRenderersOnly)]
public void The_experimental_renderer_passes_over_what_only_opengl_reads(string renderer, IdleReason expected)
{
Assert.Equal(expected, SettingReach.Why("multisampling", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("anisotropicfiltering", Linux(renderer)));
Assert.Equal(expected, SettingReach.Why("gfx.smoke", Linux(renderer)));
// ...but reads the rest of the reflections and shadows.
Assert.Equal(IdleReason.None, SettingReach.Why("gfx.reflections.fidelity", Linux(renderer)));
Assert.Equal(IdleReason.None, SettingReach.Why("shadowtune", Linux(renderer)));
}
[Theory]
[InlineData(null, 0, false)]
[InlineData(0.0, 0, false)]
[InlineData(60.0, 0, true)]
[InlineData(null, 50, true)] // fpsaverage, the older regulator
public void The_draw_range_factor_needs_a_regulator(double? targetFps, double fpsAverage, bool regulated)
{
var target = Linux() with { TargetFps = targetFps, FpsAverage = fpsAverage };
Assert.Equal(regulated ? IdleReason.None : IdleReason.NeedsFrameRateTarget,
SettingReach.Why("gfx.drawrange.factor.max", target));
}
// ── The rest of the target ───────────────────────────────────────────────
[Fact]
public void A_windows_build_is_told_from_its_header()
{
var files = new InMemoryFileSystem()
.WithExecutable(TestInstallation.At("eu07"), "\u007fELF binary")
.WithFile(TestInstallation.At("eu07.exe"), "MZ binary");
var installation = new TestInstallation(files);
Assert.False(installation.Executables.IsWindowsBuild("eu07"));
Assert.True(installation.Executables.IsWindowsBuild("eu07.exe"));
}
[Fact]
public void A_network_server_in_the_ini_is_noticed()
{
string ini = Path.Combine("/home/kolejarz", ".config", "MaSzyna", "eu07.ini");
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(ini, "network.server tcp 0.0.0.0:7424\n"));
installation.Environment.With("HOME", "/home/kolejarz");
installation.SettingsStore.Load();
Assert.True(installation.SettingsStore.Settings.NetworkServer);
}
}
+251 -92
View File
@@ -57,6 +57,34 @@ public class SettingsStoreTests
Assert.Equal(UserIni, installation.SettingsStore.LoadedFrom);
}
[Fact]
public void A_key_set_twice_in_the_players_ini_is_left_once_on_the_first_start()
{
var installation = WithHome(new InMemoryFileSystem()
.WithFile(UserIni, "width 800\nheight 1080\nnetwork.server zmq a\nnetwork.server zmq b\nwidth 1920\n"));
installation.SettingsStore.Load();
installation.SettingsStore.RemoveDuplicatesNow();
string saved = SavedLines(installation);
Assert.DoesNotContain("width 800", saved);
Assert.Contains("width 1920\n", saved);
Assert.Contains("network.server zmq a\n", saved);
Assert.Contains("network.server zmq b\n", saved);
Assert.Equal(1920, installation.SettingsStore.Settings.Width);
}
[Fact]
public void An_ini_setting_each_key_once_is_not_written_on_the_first_start()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1920\n"));
installation.SettingsStore.Load();
installation.SettingsStore.RemoveDuplicatesNow();
Assert.Equal("width 1920\n", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_language_the_starter_does_not_ship_survives_a_round_trip()
{
@@ -492,10 +520,8 @@ public class SettingsStoreTests
[InlineData("mousescale 1.5 0.5", false, true, "mousescale 1.5 -0.5")]
[InlineData("mousescale 1.5 0.5", true, false, "mousescale -1.5 0.5")]
[InlineData("mousescale -1.5 -0.5", false, false, "mousescale 1.5 0.5")]
[InlineData("mousescale 2.5 0.123456", false, true, "mousescale 2.5 -0.123456")]
// Further than the slider goes.
[InlineData("mousescale 12 0.5", true, false, "mousescale -12 0.5")]
public void A_mouse_scale_keeps_its_numbers_when_an_axis_is_inverted(
[InlineData("mousescale 3.2 0.5", true, true, "mousescale -3.2 -0.5")]
public void An_inverted_axis_is_the_sign_of_its_number(
string line, bool invertX, bool invertY, string written)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
@@ -508,10 +534,69 @@ public class SettingsStoreTests
Assert.Equal(written, LineFor(installation, "mousescale"));
}
[Fact]
public void A_mouse_scale_nobody_changed_stays_as_the_file_has_it()
[Theory]
[InlineData("mousescale 1.0 0.5")]
[InlineData("mousescale 1 0.5")]
[InlineData("mousescale 1.5 0.5")]
[InlineData("mousescale -2.3 0.5")]
[InlineData("mousescale 3.2 -0.5")]
public void A_mouse_scale_of_the_old_starter_stays_as_the_file_has_it(string line)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "mousescale 1.5 0.5\n"));
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Equal(line, LineFor(installation, "mousescale"));
}
[Theory]
// The old starter's four speeds (src/uSettings.pas): low, standard, high, very high.
[InlineData(1, "mousescale 1.0 0.5")]
[InlineData(2, "mousescale 1.5 0.5")]
[InlineData(3, "mousescale 2.3 0.5")]
[InlineData(4, "mousescale 3.2 0.5")]
public void The_sensitivity_is_written_as_the_old_starter_wrote_it(int level, string written)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "mousescale 12 0.5\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.CursorSensitivity = level;
installation.SettingsStore.Save();
Assert.Equal(written, LineFor(installation, "mousescale"));
}
[Theory]
// Low below 1.3, high above 1.9, very high above 2.7, standard between - whatever the sign.
[InlineData("0", 1)]
[InlineData("0.2", 1)]
[InlineData("1.29", 1)]
[InlineData("1.3", 2)]
[InlineData("1.5", 2)]
[InlineData("1.9", 2)]
[InlineData("2", 3)]
[InlineData("-2.3", 3)]
[InlineData("2.7", 3)]
[InlineData("3", 4)]
[InlineData("-3.2", 4)]
[InlineData("12", 4)]
// Not a number the old starter could read: its list stayed at standard.
[InlineData("Infinity", 2)]
[InlineData("fast", 2)]
public void The_sensitivity_is_read_as_the_old_starter_read_it(string x, int level)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"mousescale {x} 0.5\n"));
installation.SettingsStore.Load();
Assert.Equal(level, installation.SettingsStore.Settings.CursorSensitivity);
}
[Fact]
public void Without_a_mouse_scale_the_old_starters_standard_is_written()
{
var installation = WithHome();
installation.SettingsStore.Load();
installation.SettingsStore.Save();
@@ -519,28 +604,35 @@ public class SettingsStoreTests
Assert.Equal("mousescale 1.5 0.5", LineFor(installation, "mousescale"));
}
[Fact]
public void Moving_the_sensitivity_replaces_the_scale_it_stood_for()
[Theory]
// The second number is always 0.5, as the old starter wrote it; its sign is the inversion.
[InlineData("mousescale 1.5 0.2", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 0.23", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 -0.23", "mousescale 1.5 -0.5")]
[InlineData("mousescale 1.5 -2", "mousescale 1.5 -0.5")]
[InlineData("mousescale 1.5 0", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 -0", "mousescale 1.5 0.5")]
[InlineData("mousescale 1.5 NaN", "mousescale 1.5 0.5")]
// A decimal comma: the simulator reads "0,2" as 0.
[InlineData("mousescale 1.5 0,2", "mousescale 1.5 0.5")]
// The first is one of that starter's four speeds, the one of the level the file's number has.
[InlineData("mousescale 0.5 0.5", "mousescale 1.0 0.5")]
[InlineData("mousescale 0 0.5", "mousescale 1.0 0.5")]
[InlineData("mousescale 2 0.5", "mousescale 2.3 0.5")]
[InlineData("mousescale -3 0.5", "mousescale -3.2 0.5")]
[InlineData("mousescale 12 0.2", "mousescale 3.2 0.5")]
[InlineData("mousescale Infinity -0.5", "mousescale 1.5 -0.5")]
// One number: the simulator takes the next word of the file ("mousecontrol") for Y, and reads it as 0.
[InlineData("mousescale 1.5", "mousescale 1.5 0.5")]
[InlineData("mousescale 0.5\t// (3.2 0.5) komentarz", "mousescale 1.0 0.5\t// (3.2 0.5) komentarz")]
public void A_mouse_scale_the_old_starter_would_not_write_goes_on_a_save(string line, string written)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "mousescale 1.5 0.5\n"));
installation.SettingsStore.Load();
Assert.Equal(2, installation.SettingsStore.Settings.CursorSensitivity);
installation.SettingsStore.Settings.CursorSensitivity = 3;
installation.SettingsStore.Save();
Assert.Equal("mousescale 3 0.5", LineFor(installation, "mousescale"));
}
[Fact]
public void The_default_mouse_scale_is_written_as_before()
{
var installation = WithHome();
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Equal("mousescale 2 0.2", LineFor(installation, "mousescale"));
Assert.Equal(written, LineFor(installation, "mousescale"));
}
// ── A file that could not be read ────────────────────────────────────────
@@ -859,13 +951,12 @@ public class SettingsStoreTests
Assert.Equal(floor, SimulatorSettings.ShadowRangeFloor(mapSize));
[Theory]
[InlineData(150, 1024, false, 150)]
[InlineData(150, 4096, false, 300)]
[InlineData(150, 4096, true, 150)]
[InlineData(100, 8192, false, 1200)]
[InlineData(400, 8192, false, 1600)]
public void Shadows_reach_as_far_as_the_renderer_stretches_them(int range, int mapSize, bool legacy, int reach) =>
Assert.Equal(reach, SimulatorSettings.ShadowReach(range, mapSize, legacy));
[InlineData(150, 1024, 150)]
[InlineData(150, 4096, 300)]
[InlineData(100, 8192, 1200)]
[InlineData(400, 8192, 1600)]
public void Shadows_reach_as_far_as_the_renderer_stretches_them(int range, int mapSize, int reach) =>
Assert.Equal(reach, SimulatorSettings.ShadowReach(range, mapSize));
[Theory]
[InlineData("anisotropicfiltering 12")]
@@ -883,11 +974,12 @@ public class SettingsStoreTests
[Theory]
[InlineData("default")]
[InlineData("simpleshader")]
[InlineData("off")]
[InlineData("full")]
[InlineData("opengl")]
[InlineData("gl46")]
[InlineData("vulkan14")]
[InlineData("simpleshader")]
[InlineData("off")]
[InlineData("legacy")]
[InlineData("simple")]
[InlineData("experimental")]
@@ -901,62 +993,90 @@ public class SettingsStoreTests
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
}
// A word the starter does not know is written in by hand: "null" of the test runs, or one of a newer simulator.
// Shown, and left as it is until another renderer is chosen.
[Theory]
[InlineData(0, "full")]
[InlineData(1, "legacy")]
[InlineData(2, "simple")]
[InlineData(3, "experimental")]
[InlineData(4, "vulkan")]
public void A_chosen_renderer_is_saved_as_the_simulator_reads_it(int engine, string saved)
[InlineData("null")]
[InlineData("whatever")]
public void A_renderer_word_the_starter_does_not_know_stays_until_another_is_chosen(string word)
{
// application.cpp knows full (or default), experimental and simple; every
// other word - "simpleshader" and "off" from older starters - is legacy.
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\nfieldofview 45\n"));
var store = installation.SettingsStore;
store.Load();
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 renderer it runs as, is a choice.
store.Settings.RendererWord = null;
store.Settings.Backend = GraphicsBackend.Vulkan;
store.Save();
Assert.Contains("gfxrenderer vulkan\n", SavedLines(installation));
Assert.False(store.UnreadableValues().ContainsKey("gfxrenderer"));
}
[Theory]
[InlineData(GraphicsBackend.Vulkan, "vulkan")]
[InlineData(GraphicsBackend.OpenGL, "default")]
public void A_chosen_renderer_is_saved_as_the_simulator_reads_it(GraphicsBackend backend, string saved)
{
// utilities/Globals.cpp knows default (OpenGL 4.6) and vulkan; the words of the renderers it no longer has
// it reads as default.
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfxrenderer simpleshader\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.RenderEngine = engine == 1 ? 0 : engine;
installation.SettingsStore.Settings.Backend = backend == GraphicsBackend.Vulkan ? GraphicsBackend.OpenGL : GraphicsBackend.Vulkan;
installation.SettingsStore.Save();
installation.SettingsStore.Settings.RenderEngine = engine;
installation.SettingsStore.Settings.Backend = backend;
installation.SettingsStore.Save();
Assert.Contains($"gfxrenderer {saved}\n", SavedLines(installation));
}
[Theory]
[InlineData("full", 0)]
[InlineData("gl46", 0)]
[InlineData("opengl", 0)]
[InlineData("vulkan", 4)]
[InlineData("VULKAN14", 4)]
[InlineData("simpleshader", 1)]
public void A_renderer_word_stands_where_the_simulator_reads_it(string word, int engine)
[InlineData("full", GraphicsBackend.OpenGL)]
[InlineData("gl46", GraphicsBackend.OpenGL)]
[InlineData("opengl", GraphicsBackend.OpenGL)]
[InlineData("default", GraphicsBackend.OpenGL)]
[InlineData("vulkan", GraphicsBackend.Vulkan)]
[InlineData("VULKAN14", GraphicsBackend.Vulkan)]
[InlineData("whatever", GraphicsBackend.OpenGL)]
[InlineData("experimental", GraphicsBackend.OpenGL)]
[InlineData("simpleshader", GraphicsBackend.OpenGL)]
public void A_renderer_word_stands_where_the_simulator_reads_it(string word, GraphicsBackend backend)
{
Assert.Equal(engine, SimulatorSettings.RenderEngineOf(word));
Assert.Equal(backend, SimulatorSettings.BackendOf(word));
}
[Fact]
public void The_buffer_is_written_for_old_and_new_simulators()
public void The_buffer_is_written_as_the_simulator_reads_it()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1000\nheight 500\n"));
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni,
"width 1000\nheight 500\ngfx.framebuffer.width 1000\ngfx.framebuffer.height 500\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.BufferScalePercent = 50;
installation.SettingsStore.Save();
string saved = SavedLines(installation);
Assert.Contains("gfx.buffer.percent 50\n", saved);
Assert.Contains("gfx.framebuffer.width 500\n", saved);
Assert.Contains("gfx.framebuffer.height 250\n", saved);
Assert.Contains("gfx.buffer.percent 0.5\n", saved);
Assert.DoesNotContain("\ngfx.framebuffer.width", saved);
Assert.DoesNotContain("\ngfx.framebuffer.height", saved);
}
[Theory]
[InlineData("gfx.buffer.percent 0.5\n", 50)]
[InlineData("gfx.buffer.percent 75\n", 75)]
[InlineData("gfx.buffer.percent 10\n", 25)]
[InlineData("gfx.buffer.percent 300\n", 200)]
[InlineData("width 1000\ngfx.framebuffer.width 500\n", 50)]
[InlineData("width 1000\ngfx.framebuffer.width 100\n", 25)]
[InlineData("width 1000\ngfx.framebuffer.width 3000\n", 100)]
[InlineData("gfx.framebuffer.width 500\n", 100)]
[InlineData("starter.bufferscale 60\n", 60)]
[InlineData("starter.bufferscale 60\ngfx.buffer.percent 80\n", 80)]
public void The_buffer_is_read_from_the_key_the_new_simulator_goes_by(string ini, int percent)
[InlineData("starter.bufferscale 60\nwidth 1000\ngfx.framebuffer.width 800\n", 60)]
[InlineData("gfx.buffer.percent 0.5\n", 50)]
[InlineData("gfx.buffer.percent 0.6\nstarter.bufferscale 80\n", 60)]
public void The_buffer_is_read_from_the_simulators_key_or_what_an_older_starter_left(string ini, int percent)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
@@ -965,36 +1085,6 @@ public class SettingsStoreTests
Assert.Equal(percent, installation.SettingsStore.Settings.BufferScalePercent);
}
[Fact]
public void The_two_anti_aliasing_keys_untouched_keep_their_order()
{
// Moving them would change which of the two the simulator goes by.
const string ini = "gfx.antialiasing taa\nwidth 800\nmultisampling 2\n";
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
installation.SettingsStore.Load();
installation.SettingsStore.Save();
string saved = SavedLines(installation);
Assert.True(saved.IndexOf("gfx.antialiasing taa", StringComparison.Ordinal) < saved.IndexOf("multisampling 2", StringComparison.Ordinal), saved);
}
[Fact]
public void A_chosen_anti_aliasing_is_saved_below_multisampling_for_the_later_line_to_count()
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfx.antialiasing msaax4\nwidth 800\nmultisampling 2\n"));
installation.SettingsStore.Load();
installation.SettingsStore.Settings.AntiAliasing = AntiAliasingMode.Taa;
installation.SettingsStore.Save();
string saved = SavedLines(installation);
Assert.True(saved.IndexOf("multisampling ", StringComparison.Ordinal) < saved.IndexOf("gfx.antialiasing taa", StringComparison.Ordinal), saved);
var again = WithHome(installation.Files);
again.SettingsStore.Load();
Assert.Equal(AntiAliasingMode.Taa, again.SettingsStore.Settings.AntiAliasing);
}
[Fact]
public void A_field_of_view_down_to_ten_degrees_survives_a_save()
{
@@ -1196,6 +1286,25 @@ public class SettingsStoreTests
Assert.Equal(60, store.Settings.FieldOfView);
}
// The render scale put back is the whole window, whichever way the file had it.
[Theory]
[InlineData("width 1920\nheight 1080\ngfx.buffer.percent 0.5\n")]
[InlineData("width 1920\nheight 1080\nstarter.bufferscale 50\n")]
[InlineData("width 1920\nheight 1080\ngfx.framebuffer.width 960\ngfx.framebuffer.height 540\n")]
public void The_render_scale_put_back_is_the_whole_window(string ini)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini));
var store = installation.SettingsStore;
store.Load();
Assert.Equal(50, store.Settings.BufferScalePercent);
var reset = store.WithDefaults(store.Settings, new[] { "gfx.buffer.percent" });
Assert.Equal(100, reset.BufferScalePercent);
Assert.Equal(1920, reset.Width);
Assert.Equal("1", store.Render(reset)["gfx.buffer.percent"]);
}
// ── What the screen shows otherwise ──────────────────────────────────────
[Fact]
@@ -1452,6 +1561,56 @@ public class SettingsStoreTests
Assert.False(installation.SettingsStore.Settings.PhysicsLogTrains);
}
// An older file says "standard no": taken in, it would move the player again on the next
// start, and its "advanced yes" would open the advanced mode past the warning.
private const string OlderModeLines = "starter.settings.standard no\nstarter.settings.advanced yes\nfieldofview 50\n";
[Fact]
public void An_imported_ini_leaves_the_mode_as_this_installation_has_it()
{
string backup = Path.Combine("/home/kolejarz", "backup", "eu07.ini");
var files = new InMemoryFileSystem()
.WithFile(UserIni, "starter.settings.standard yes\nstarter.settings.advanced no\n")
.WithFile(backup, OlderModeLines);
var store = WithHome(files).SettingsStore;
store.Load();
Assert.True(store.ImportFrom(backup));
store.Save();
Assert.Equal(50, store.Settings.FieldOfView);
Assert.True(store.Settings.MovedToStandard);
Assert.False(store.Settings.AdvancedSettings);
string written = files.ReadAllText(UserIni, System.Text.Encoding.UTF8);
Assert.Contains("starter.settings.standard yes", written);
Assert.Contains("starter.settings.advanced no", written);
}
[Fact]
public void A_profile_leaves_the_mode_as_this_installation_has_it()
{
var files = new InMemoryFileSystem()
.WithFile(UserIni, "starter.settings.standard yes\nstarter.settings.advanced no\n")
.WithFile(Profile, OlderModeLines);
var store = WithHome(files).SettingsStore;
store.Load();
Assert.True(store.TryLoadProfile(Profile));
store.Save();
Assert.Equal(50, store.Settings.FieldOfView);
Assert.True(store.Settings.MovedToStandard);
Assert.False(store.Settings.AdvancedSettings);
string written = files.ReadAllText(UserIni, System.Text.Encoding.UTF8);
Assert.Contains("starter.settings.standard yes", written);
Assert.Contains("starter.settings.advanced no", written);
}
[Theory]
[InlineData("starter.gpu")]
public void The_move_to_the_standard_mode_keeps_what_lets_a_machine_run_the_simulator(string key) =>
Assert.Contains(key, StarterNG.Application.SettingsStore.KeptOnMoveToStandard);
[Fact]
public void An_imported_ini_from_before_the_tapes_of_the_trains_is_moved_as_a_profile_is()
{
@@ -0,0 +1,308 @@
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 SettingRow Row(StarterNG.Views.Settings page, string key) =>
Avalonia.LogicalTree.LogicalExtensions.GetLogicalDescendants(page).OfType<SettingRow>()
.First(row => row.ConfigKey == key);
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 null\nfieldofview 45\n", (page, _, saved) =>
{
Assert.Equal("null", Shown(List(page, "RenderEngineCb")));
Assert.Contains("null", Note(page, "gfxrenderer"));
Assert.False(page.HasUnsavedChanges);
page.Save();
Assert.Contains("gfxrenderer null\n", saved());
});
}
[Fact]
public void The_standard_mode_has_the_choice_of_the_simulator_and_of_ray_tracing_but_not_of_the_renderer()
{
WithPage(Standard, (page, _, _) =>
{
Assert.True(Row(page, "starter.exe.path").IsEffectivelyVisible);
Assert.True(Row(page, "gfx.raytracing, gfx.raytracing.range").IsVisible);
Assert.False(Row(page, "gfxrenderer").IsVisible);
});
}
[Fact]
public void A_level_of_realism_picked_is_saved_and_marked_until_a_setting_moves()
{
WithPage(Standard, (page, services, saved) =>
{
var buttons = page.FindControl<StackPanel>("PhysicsPresetButtons")!.Children.OfType<Button>().ToList();
var state = page.FindControl<TextBlock>("PhysicsPresetState")!;
Assert.Equal(App.Loc["PresetCustom"], state.Text);
buttons[1].RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
Controls.Settle();
Assert.True(buttons[1].Classes.Contains("Accent"));
Assert.Equal("new", (((ComboBox)Row(page, "physics.derailment").Content!).SelectedItem as ComboBoxItem)?.Tag);
page.Save();
Assert.Contains("physics.derailment new\n", saved());
Assert.Contains("couplerphysics yes\n", saved());
Assert.Contains("crashdamage yes\n", saved());
page.FindControl<CheckBox>("CrashDamageCb")!.IsChecked = false;
Controls.Settle();
Assert.Equal(App.Loc["PresetCustom"], state.Text);
Assert.False(buttons[1].Classes.Contains("Accent"));
});
}
[Fact]
public void A_level_of_ray_tracing_picked_is_saved_as_its_reach()
{
WithPage(Standard, (page, services, saved) =>
{
var list = List(page, "RayTracingCb");
Assert.Equal(App.Loc["RayTracingOff"], Shown(list));
list.SelectedIndex = 3;
page.Save();
Assert.Contains("gfx.raytracing yes\n", saved());
Assert.Contains("gfx.raytracing.range 1000\n", saved());
list.SelectedIndex = 0;
page.Save();
Assert.Contains("gfx.raytracing no\n", saved());
Assert.Contains("gfx.raytracing.range 1000\n", saved());
});
}
[Fact]
public void A_reach_of_ray_tracing_no_level_has_is_shown_as_it_is_and_kept()
{
WithPage(Standard + "gfx.raytracing yes\ngfx.raytracing.range 750\n", (page, _, saved) =>
{
Assert.Contains("750", Shown(List(page, "RayTracingCb")));
Assert.False(page.HasUnsavedChanges);
page.Save();
Assert.Contains("gfx.raytracing.range 750\n", saved());
});
}
[Fact]
public void Another_renderer_picked_from_the_list_replaces_it()
{
WithPage(Standard + "gfxrenderer null\n", (page, services, saved) =>
{
List(page, "RenderEngineCb").SelectedIndex = 1;
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 null\nstarter.batterydefault 7\nvsync moze\nstarter.gpu system\n", (page, _, saved) =>
{
page.MoveToStandardOnce();
string text = saved();
Assert.Contains("gfxrenderer vulkan\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("starter.gpu system\n", text);
Assert.Null(Note(page, "gfxrenderer"));
Assert.NotEqual("7", Shown(List(page, "ReadyOverrideCb")));
});
}
// A player of the standard mode of an older starter: Vulkan, every optimisation on and the developer's settings
// at the starter's own values, the picture's level and what the player chose in the standard mode as it was.
[Fact]
public void The_standard_mode_of_an_older_layout_moves_to_vulkan_and_the_fast_choices()
{
WithPage(Standard + "gfxrenderer default\ngfx.gpucull no\nphysicslog yes\nfriction 2\nmaxtexturesize 1024\n" +
"fieldofview 60\ngfx.ssr low\nblackbox yes\n", (page, services, saved) =>
{
page.MoveToStandardOnce();
string text = saved();
Assert.Contains("gfxrenderer vulkan\n", text);
Assert.Contains("gfx.gpucull yes\n", text);
Assert.Contains("physicslog no\n", text);
Assert.Contains("friction 1\n", text);
Assert.Contains("maxtexturesize 1024\n", text);
Assert.Contains("gfx.ssr low\n", text);
Assert.Contains("fieldofview 60\n", text);
Assert.Contains("blackbox yes\n", text);
Assert.Contains($"starter.settings.revision {StarterNG.Domain.Settings.SimulatorSettings.CurrentRevision}\n", text);
});
}
[Fact]
public void The_advanced_mode_of_an_older_layout_keeps_what_its_developer_chose()
{
WithPage(Standard + "starter.settings.advanced yes\ngfxrenderer default\ngfx.gpucull no\n", (page, services, saved) =>
{
page.MoveToStandardOnce();
string text = saved();
Assert.Contains("gfxrenderer default\n", text);
Assert.Contains("gfx.gpucull no\n", text);
Assert.True(services.Settings.AdvancedSettings);
Assert.Equal(StarterNG.Domain.Settings.SimulatorSettings.CurrentRevision, services.Settings.Revision);
});
}
[Fact]
public void The_layout_of_this_starter_is_moved_to_once_only()
{
WithPage(Standard + "starter.settings.revision 2\ngfxrenderer default\n", (page, _, saved) =>
{
page.MoveToStandardOnce();
Assert.Contains("gfxrenderer default\n", saved());
});
}
}
@@ -67,4 +67,18 @@ public class SimulatorAftermathTests
Assert.Equal(new[] { "opening" }, tail);
}
[Fact]
public void The_simulator_ran_when_it_wrote_its_log_since_the_start()
{
var installation = new TestInstallation(new InMemoryFileSystem()
.WithFile(TestInstallation.At("log.txt"), "opening\r\n"));
var aftermath = new SimulatorAftermath(installation.Files, installation.Paths, installation.Log);
var written = installation.Files.LastWriteTimeUtc;
Assert.True(aftermath.SimulatorRanSince(written.AddMinutes(-1)));
Assert.False(aftermath.SimulatorRanSince(written.AddMinutes(10)));
Assert.False(new SimulatorAftermath(new InMemoryFileSystem(), installation.Paths, installation.Log)
.SimulatorRanSince(written));
}
}
+33
View File
@@ -47,6 +47,39 @@ public class SimulatorExitTests
Assert.Equal(["Bad file: texture"], exit.CleanErrors);
}
private static SimulatorExit Ended(uint code) => new(unchecked((int)code), Session, []);
[Theory]
[InlineData(0xC0000135u)] // a library missing, explained by eu07_starter.exe
[InlineData(0xC000001Du)] // an instruction the processor lacks
[InlineData(0xC0000005u)] // a crash: its minidump by eu07_starter.exe, its box by the simulator
public void An_error_code_of_the_system_was_explained_by_the_simulators_starter(uint code)
{
Assert.True(Ended(code).AlreadyExplained(throughStarter: true, simulatorRan: true));
Assert.False(Ended(code).AlreadyExplained(throughStarter: false, simulatorRan: true));
}
[Fact]
public void A_close_by_ctrl_c_is_left_without_a_word_by_the_simulators_starter()
{
Assert.False(Ended(0xC000013A).AlreadyExplained(throughStarter: true, simulatorRan: true));
}
[Fact]
public void A_refusal_of_the_simulators_starter_is_one_where_the_simulator_never_ran()
{
Assert.True(Ended(1).AlreadyExplained(throughStarter: true, simulatorRan: false));
Assert.False(Ended(1).AlreadyExplained(throughStarter: true, simulatorRan: true));
Assert.False(Ended(1).AlreadyExplained(throughStarter: false, simulatorRan: false));
Assert.False(Ended(3).AlreadyExplained(throughStarter: true, simulatorRan: false));
}
[Fact]
public void A_processor_the_simulator_cannot_run_on_it_tells_of_itself()
{
Assert.True(Ended(SimulatorExit.UnsupportedProcessor).AlreadyExplained(throughStarter: false, simulatorRan: true));
}
[Fact]
public async Task A_real_process_leaves_its_exit_code_and_error_stream()
{
+54
View File
@@ -0,0 +1,54 @@
using StarterNG.Domain.Settings;
using StarterNG.Views;
namespace StarterNG.Tests;
[Collection(AvaloniaControls.Name)]
public class SliderStepsTests
{
[Fact]
public void The_old_starters_steps_are_offered_and_a_value_outside_them_stays()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.ReflectionUpdates) { Value = 0.5 };
// Twice a second is none of the steps: shown among them, between once in five seconds and once a second.
Assert.Equal(0.5, steps.Value);
Assert.Equal(SliderRanges.ReflectionUpdates.Length, slider.Maximum);
slider.Value = slider.Maximum;
Assert.Equal(60, steps.Value);
}
[Fact]
public void A_frame_limit_above_the_list_stays_as_the_file_has_it()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.FrameRateLimits) { Value = 300 };
Assert.Equal(300, steps.Value);
Assert.Equal(SliderRanges.FrameRateLimits.Length, slider.Maximum);
}
[Fact]
public void Clamping_puts_a_value_past_either_end_at_that_end()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.FrameRateLimits) { Clamps = true, Value = 300 };
Assert.Equal(240, steps.Value);
Assert.Equal(SliderRanges.FrameRateLimits.Length - 1, slider.Maximum);
}
[Fact]
public void Clamping_leaves_a_value_between_two_steps_where_it_is()
{
var slider = new Avalonia.Controls.Slider();
var steps = new SliderSteps(slider, SliderRanges.DrawRangeFactors) { Clamps = true, Value = 1.5 };
Assert.Equal(1.5, steps.Value);
steps.Value = -5;
Assert.Equal(1, steps.Value);
}
}
+9 -5
View File
@@ -14,7 +14,7 @@ public class SoftwareRenderTests
}
[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(new[] { "--software" }));
@@ -25,21 +25,25 @@ public class SoftwareRenderTests
{
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[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
}
[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);
}
[Fact]
public void Both_platforms_options_go_to_the_same_builder()
[Theory]
[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>();
string[] args = asked ? new[] { SoftwareRender.Switch } : Array.Empty<string>();
Assert.Same(builder, SoftwareRender.ApplyTo(builder));
Assert.Same(builder, SoftwareRender.ApplyTo(builder, args));
}
}
+4 -4
View File
@@ -152,12 +152,12 @@ public class StartSimulationTests
}
[Theory]
[InlineData(0)]
[InlineData(3)]
public void Any_renderer_is_left_for_the_simulator_to_take(int renderer)
[InlineData(StarterNG.Domain.Settings.GraphicsBackend.Vulkan)]
[InlineData(StarterNG.Domain.Settings.GraphicsBackend.OpenGL)]
public void Any_renderer_is_left_for_the_simulator_to_take(StarterNG.Domain.Settings.GraphicsBackend renderer)
{
var (start, launcher, installation) = Rig(files => files.WithExecutable(Build, "\u007fELF binary"));
installation.SettingsStore.Settings.RenderEngine = renderer;
installation.SettingsStore.Settings.Backend = renderer;
Assert.Equal(SimulationStartOutcome.Started, start.Execute(freeFly: true, saveSettings: false).Outcome);
Assert.NotNull(launcher.Executable);
+1 -1
View File
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
+72
View File
@@ -1,5 +1,6 @@
using StarterNG.Classes;
using StarterNG.Domain;
using StarterNG.Domain.Settings;
using StarterNG.Views;
namespace StarterNG.Tests;
@@ -58,6 +59,77 @@ public class TrainsetDisplayTests
Assert.False(TrainsetDisplay.ListedIn(picked, showAi: false, drivableOnly: true, current: picked));
}
private static SimulatorSettings Mode(bool advanced) =>
new() { AdvancedSettings = advanced, ShowAiVehicles = true, DrivableOnly = false };
[Fact]
public void The_standard_mode_lists_every_consist_but_starts_only_in_one_a_player_drives()
{
var standard = Mode(advanced: false);
var decor = new Trainset("trainset a tor 0 0 //$decor\nnode -1 0 v1 dynamic d s m 0 headdriver 3 0 enddynamic\nendtrainset");
Assert.True(decor.Decor);
foreach (var consist in new[] { Consist(), Consist(description: "-ai"), Consist(driver: "nobody"), decor })
Assert.True(TrainsetDisplay.ListedIn(consist, standard, current: null));
Assert.True(TrainsetDisplay.StartableIn(Consist(), standard));
Assert.True(TrainsetDisplay.StartableIn(Consist(driver: "nobody"), standard));
Assert.False(TrainsetDisplay.StartableIn(Consist(description: "-ai"), standard));
Assert.False(TrainsetDisplay.StartableIn(decor, standard));
Assert.True(TrainsetDisplay.StartableIn(decor, Mode(advanced: true)));
}
[Fact]
public void The_standard_mode_changes_the_crew_but_not_in_the_simulators_own_consists()
{
var standard = Mode(advanced: false);
var decor = new Trainset("trainset a tor 0 0 //$decor\nnode -1 0 v1 dynamic d s m 0 headdriver 3 0 enddynamic\nendtrainset");
Assert.True(TrainsetDisplay.CrewEditableIn(Consist(), standard));
Assert.True(TrainsetDisplay.CrewEditableIn(Consist(driver: "nobody"), standard));
Assert.True(TrainsetDisplay.CrewEditableIn(null, standard));
Assert.False(TrainsetDisplay.CrewEditableIn(Consist(description: "-ai"), standard));
Assert.False(TrainsetDisplay.CrewEditableIn(decor, standard));
Assert.True(TrainsetDisplay.CrewEditableIn(Consist(description: "-ai"), Mode(advanced: true)));
}
[Fact]
public void The_filters_work_in_the_advanced_mode()
{
var settings = Mode(advanced: true);
settings.ShowAiVehicles = false;
Assert.False(TrainsetDisplay.ListedIn(Consist(description: "-ai"), settings, current: null));
Assert.True(TrainsetDisplay.ListedIn(Consist(), settings, current: null));
settings.DrivableOnly = true;
Assert.False(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), settings, current: null));
}
[Fact]
public void The_standard_mode_has_no_filters_and_leaves_out_empty_consists()
{
var standard = new SimulatorSettings { AdvancedSettings = false, ShowAiVehicles = false, DrivableOnly = true };
var empty = new Trainset("trainset a tor 0 0\nendtrainset");
Assert.True(TrainsetDisplay.ListedIn(Consist(description: "-ai"), standard, current: null));
Assert.True(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), standard, current: null));
Assert.False(TrainsetDisplay.ListedIn(empty, standard, current: null));
Assert.False(TrainsetDisplay.ListedIn(empty, standard, current: empty));
}
[Fact]
public void The_advanced_mode_lists_by_its_own_filters()
{
var advanced = Mode(advanced: true);
Assert.True(TrainsetDisplay.ListedIn(Consist(description: "-ai"), advanced, current: null));
Assert.True(TrainsetDisplay.ListedIn(Consist(driver: "nobody"), advanced, current: null));
advanced.ShowAiVehicles = false;
Assert.False(TrainsetDisplay.ListedIn(Consist(description: "-ai"), advanced, current: null));
}
[Theory]
[InlineData(eDriverType.Headdriver, 0)]
[InlineData(eDriverType.Reardriver, 1)]
+17
View File
@@ -98,6 +98,23 @@ public class WarehouseEditTests
Assert.Null(Stored("edit-changed"));
}
[Fact]
public void A_write_tells_the_list_the_name_and_the_entry_and_no_write_tells_nothing()
{
var told = new List<(string Name, string Entry)>();
_edit.Saved += (name, entry) => told.Add((name, entry));
var trainset = _edit.Open(Preset("edit-told"));
_edit.Save();
Assert.Empty(told);
trainset.Vehicles.Add(trainset.Vehicles[0].Clone());
_edit.Save();
Assert.Equal([("edit-told", ConsistText.Serialize(trainset))], told);
PresetStore.Delete("edit-told");
}
[Fact]
public void Nothing_is_written_with_nothing_open()
{
+3
View File
@@ -28,11 +28,14 @@ public partial class App : Avalonia.Application
// Before any control exists: the names are given as controls are filled in.
ScreenReaderNames.Install();
DialogKeyboard.Install();
GamescopeWindows.Install(GamescopeWindows.IsGamescope(AppServices.Current.Environment.GetVariable),
() => Loc["Close"]);
AvaloniaXamlLoader.Load(this);
AppServices.Current.SettingsStore.Load();
AppServices.Current.SettingsStore.StartAtHighWithoutOwnSettings();
AppServices.Current.SettingsStore.RemoveDuplicatesNow();
KeyboardConfig.Instance.Load();
+2 -4
View File
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using StarterNG.Application.Abstractions;
using StarterNG.Domain.Settings;
@@ -64,13 +65,12 @@ public sealed class AppServices
SceneryFiles = new SceneryFileWatch(files, Sceneries, Library, State);
Executables = new ExecutableLocator(files, paths, environment, log);
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(dlssPlatform: !environment.IsMacOS), Executables);
SettingsStore = new SettingsStore(files, clock, log, settingsPaths, new SettingsSerializer(), Executables);
MissingVehicleLog = new MissingVehicleLog(SettingsStore.Settings, missingAssets, Library, log);
Favorites = new FavoriteSceneries(files, log, settingsPaths.FavoritesPath());
Tapes = new HaslerTapes(files, paths, log, clock, Timetables, () => State.SimulatorRunning);
Gpus = new LinuxGpus(files, environment);
GraphicsCards = new GraphicsCards(files, environment, Gpus);
Displays = new Displays(files, environment);
StartSimulation = new StartSimulation(State, SettingsStore, Library.Vehicles, Executables,
files, paths, Processes, random, log, Gpus, environment,
new WineConfigLink(files, environment, settingsPaths, log), Tapes);
@@ -144,8 +144,6 @@ public sealed class AppServices
public GraphicsCards GraphicsCards { get; }
public Displays Displays { get; }
public SettingsPaths SettingsPaths { get; }
public MissingVehicleLog MissingVehicleLog { get; }
+2 -13
View File
@@ -12,10 +12,7 @@ public sealed class GraphicsGroupLevels
public GraphicsGroupLevels(SettingsStore store) => _store = store;
/// <summary>
/// The level each group is at in <paramref name="settings"/>, null where it is at none. At
/// Ultra the level under it fits too, as it leaves alone what only Ultra sets: the highest counts.
/// </summary>
/// <summary>The level each group is at in <paramref name="settings"/>, null where it is at none.</summary>
public IReadOnlyDictionary<GraphicsGroup, GraphicsPreset?> LevelsOf(SimulatorSettings settings)
{
var now = _store.Render(settings);
@@ -24,18 +21,10 @@ public sealed class GraphicsGroupLevels
(GraphicsPreset?)rendered.LastOrDefault(level => Same(group, level.Keys, now)).Level);
}
/// <summary>
/// A copy of <paramref name="settings"/> with the group at <paramref name="level"/>. What only
/// an end of the scale sets goes back to the simulator's own on leaving that end.
/// </summary>
/// <summary>A copy of <paramref name="settings"/> with the group at <paramref name="level"/>.</summary>
public SimulatorSettings Apply(GraphicsGroup group, GraphicsPreset level, SimulatorSettings settings)
{
var current = LevelsOf(settings)[group];
var source = settings.Copy();
if (level.Extras is null && current?.Extras is not null)
GraphicsExtras.None.ApplyTo(source);
if (level.Top is null && current?.Top is not null)
GraphicsTop.None.ApplyTo(source);
level.ApplyTo(source);
return _store.WithKeysOf(settings, source, group.Keys);
}
+276 -13
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
@@ -48,6 +49,41 @@ public sealed class SettingsStore
// it has it: a value outside what the starter offers, its spacing, its comment.
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,
SettingsSerializer serializer, ExecutableLocator executables)
{
@@ -75,6 +111,9 @@ public sealed class SettingsStore
public string SavePath => _savePath;
/// <summary>The last save found eu07.ini changed by something else and kept those changes: what is held was read again.</summary>
public bool LastSaveMerged { get; private set; }
public void RegisterCapture(ISettingsCapture capture) => _capture = capture;
public void Load()
@@ -92,9 +131,31 @@ public sealed class SettingsStore
return;
GraphicsPreset.High.ApplyTo(Settings);
// Nothing of an older starter to bring over: the settings start in the standard mode, of this layout.
Settings.MovedToStandard = true;
Settings.Revision = SimulatorSettings.CurrentRevision;
Save();
}
/// <summary>
/// A copy of eu07.ini beside it, the file name and <paramref name="suffix"/>, before
/// something changes many keys at once; one already there is left as it is.
/// </summary>
public void KeepCopy(string suffix)
{
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
string copy = path + suffix;
try
{
if (_files.FileExists(path) && !_files.FileExists(copy))
_files.CopyFile(path, copy, overwrite: false);
}
catch (Exception e)
{
_log.Log($"{copy} could not be made: {e.Message}");
}
}
public void LoadFrom(string path)
{
try
@@ -113,12 +174,37 @@ public sealed class SettingsStore
_serializer.Read(Settings, _config);
_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
if (!LoadFailed)
SettingsSerializer.MoveToTrainTapes(Settings);
TouchConfigAge();
}
/// <summary>
/// What lets some machines run the simulator at all: the card it is put on (offloading to the discrete one
/// fails with some drivers). The move to the standard mode, done without asking, leaves it as it is.
/// </summary>
public static readonly IReadOnlySet<string> KeptOnMoveToStandard =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "starter.gpu" };
/// <summary>
/// The mode is this installation's, like its simulator and its card: another file, a
/// backup or a profile of an older starter, says nothing of it. Without this, its
/// "starter.settings.standard no" would move the player again on the next start, and its
/// "starter.settings.advanced yes" would open the advanced mode past the warning.
/// The returned action puts the mode back as it was when this was called.
/// </summary>
private Action KeepMode()
{
bool advanced = Settings.AdvancedSettings, moved = Settings.MovedToStandard;
return () =>
{
Settings.AdvancedSettings = advanced;
Settings.MovedToStandard = moved;
};
}
/// <summary>
/// Reads a profile into the settings; true when it read cleanly. A read that failed
/// would leave defaults to be saved over the real settings, so those are read again.
@@ -127,9 +213,13 @@ public sealed class SettingsStore
{
if (_files.FileExists(path))
{
var mode = KeepMode();
LoadFrom(path);
if (!LoadFailed)
{
mode();
return true;
}
}
if (LoadFailed)
@@ -160,8 +250,32 @@ public sealed class SettingsStore
return;
}
// Edited by other hands since it was read or written here: their file is what the changes
// go onto, so a key the player left alone keeps what was put there meanwhile.
bool merged = false;
if (string.Equals(path, _savePath, StringComparison.Ordinal) && IsConfigNewerOnDisk())
{
try
{
_config = ConfigFile.Parse(_files.ReadAllText(path, _encoding));
merged = true;
}
catch (Exception ex)
{
_log.Log($"re-reading {path} before saving", ex);
}
}
ApplyChanges(_config, Changes(Settings));
RemoveDuplicates(_config, path);
KeepAntiAliasingLast(_config);
if (merged)
{
// What is held follows the file: the player's changes and the others' together.
_serializer.Read(Settings, _config);
}
_synced = Render(Settings);
LastSaveMerged = merged;
try
{
@@ -179,6 +293,32 @@ public sealed class SettingsStore
}
}
/// <summary>The lines of a key set again above the one the simulator reads go, and the log says which.</summary>
private void RemoveDuplicates(ConfigFile config, string path)
{
var removed = config.RemoveDuplicates(SettingsSerializer.RepeatableKeys);
if (removed.Count > 0)
_log.Log($"{path}: lines of keys set again further down removed: {string.Join(", ", removed)}");
}
/// <summary>
/// The player's own eu07.ini, as read, set a key more than once: it is saved at once, without the lines the
/// simulator passes over. A file of the installation, read for want of the player's own, is left alone.
/// </summary>
public void RemoveDuplicatesNow()
{
if (LoadFailed || !string.Equals(LoadedFrom, _savePath, StringComparison.Ordinal) ||
ConfigFile.Parse(_config.ToText()).RemoveDuplicates(SettingsSerializer.RepeatableKeys).Count == 0)
return;
Save();
}
/// <summary>
/// Of gfx.antialiasing and the older multisampling the simulator heeds the one further down, so the newer goes
/// below the older, which only the simulators before it read.
/// </summary>
private static void KeepAntiAliasingLast(ConfigFile config) => config.MoveAfter("gfx.antialiasing", "multisampling");
private static void ApplyChanges(ConfigFile config, IReadOnlyList<IniChange> changes)
{
foreach (var change in changes)
@@ -188,16 +328,8 @@ public sealed class SettingsStore
else
config.Set(change.Key, change.After);
}
// Each sets the mode as the simulator reads it, so the new one has to come later to count.
// Untouched, the two keep their order: moving them would change which one decides.
if (changes.Any(change => change.Key is "gfx.antialiasing" or "multisampling"))
config.MoveAfter("gfx.antialiasing", "multisampling");
}
/// <summary>Whether the simulator can have DLSS on this platform at all.</summary>
public bool DlssPlatform => _serializer.DlssPlatform;
/// <summary>
/// Takes the settings of another eu07.ini (a backup, a file from another machine)
/// into the current ones, keeping what belongs to this installation: the chosen
@@ -223,9 +355,7 @@ public sealed class SettingsStore
var gpu = s.Gpu;
string lastScenery = s.LastScenery;
bool maximized = s.WindowMaximized;
// Only read for the dependencies and never written, so they stay as this user's file has them.
bool cabLampLight = s.CabLampLight;
bool depthPrepassScene = s.DepthPrepassScene;
var mode = KeepMode();
_serializer.Read(s, imported);
@@ -234,8 +364,7 @@ public sealed class SettingsStore
s.Gpu = gpu;
s.LastScenery = lastScenery;
s.WindowMaximized = maximized;
s.CabLampLight = cabLampLight;
s.DepthPrepassScene = depthPrepassScene;
mode();
// an ini of before the tapes of the trains goes the same way as a profile
SettingsSerializer.MoveToTrainTapes(s);
return true;
@@ -256,6 +385,8 @@ public sealed class SettingsStore
var copy = ConfigFile.Parse(_config.ToText());
ApplyChanges(copy, Changes(settings ?? Settings));
copy.RemoveDuplicates(SettingsSerializer.RepeatableKeys);
KeepAntiAliasingLast(copy);
try
{
@@ -284,6 +415,95 @@ public sealed class SettingsStore
return keys;
}
/// <summary>
/// The keys the starter knows that the file gives a value it cannot read, with that value:
/// the setting shows its default, while the file keeps its own until the setting is changed.
/// A value read another way (tak, 1.0, a clamped number) is no unknown one.
/// </summary>
public IReadOnlyDictionary<string, string> UnreadableValues()
{
var unreadable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var defaults = Render(WithFile(new ConfigFile()));
var read = Render(WithFile(_config));
var overCap = SettingsSerializer.OverCapKeys(_config);
foreach (var (key, fallback) in defaults)
{
// Read, only brought down to the cap.
if (NotReadAlone.Contains(key) || overCap.Contains(key))
continue;
if (_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw)
continue;
if (read.TryGetValue(key, out string? shown) && shown == fallback && !Means(key, raw, shown))
unreadable[key] = raw;
}
foreach (var key in SimulatorKeys.All)
{
if (_config.IsPastEnd(key.Key) || _config.GetRaw(key.Key) is not { Length: > 0 } raw)
continue;
string first = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)[0];
bool readable = key.Kind switch
{
SimulatorKeyKind.Toggle => Bool(first) is not null,
SimulatorKeyKind.Choice => key.ChoiceIndex(first) >= 0,
SimulatorKeyKind.Number => double.TryParse(first, NumberStyles.Float, CultureInfo.InvariantCulture, out _),
_ => true
};
if (!readable)
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;
}
// Written from other keys, or rewritten on purpose whatever they say: what they hold is no setting of their own.
private static readonly HashSet<string> NotReadAlone = new(StringComparer.OrdinalIgnoreCase)
{
"mousescale", "gfxrenderer", "multisampling"
};
private SimulatorSettings WithFile(ConfigFile config)
{
var s = new SimulatorSettings();
_serializer.Read(s, config);
return s;
}
// Two numbers written apart that the file and the screen mean alike: 45 and 45.0, 0.1 and 1e-1.
private static bool SameNumber(double x, double y) =>
Math.Abs(x - y) <= 1e-9 * Math.Max(1, Math.Max(Math.Abs(x), Math.Abs(y)));
// The same value in other words: yes and tak, 45 and 45.0.
private static bool SameValue(string raw, string shown)
{
var a = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
var b = shown.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (string.Equals(a[i], b[i], StringComparison.OrdinalIgnoreCase))
continue;
if (double.TryParse(a[i], NumberStyles.Float, CultureInfo.InvariantCulture, out double x) &&
double.TryParse(b[i], NumberStyles.Float, CultureInfo.InvariantCulture, out double y) && SameNumber(x, y))
continue;
if (Bool(a[i]) is { } p && p == Bool(b[i]))
continue;
return false;
}
return true;
}
private static bool? Bool(string word) => word.ToLowerInvariant() switch
{
"yes" or "true" or "1" or "tak" => true,
"no" or "false" or "0" or "nie" => false,
_ => null
};
/// <summary>
/// What saving <paramref name="settings"/> would change in the file: the keys
/// changed since it was read, those it lacks, and the ones no simulator reads.
@@ -296,6 +516,8 @@ public sealed class SettingsStore
var shown = _capture?.ShownUnlikeSettings ?? new Dictionary<string, ShownValue>();
var changes = new List<IniChange>();
var listed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// Above the starter's caps the file is brought down, though nothing on screen moved.
var overCap = SettingsSerializer.OverCapKeys(_config);
foreach (string key in SettingsSerializer.ObsoleteKeys)
Add(key, null);
@@ -322,6 +544,17 @@ public sealed class SettingsStore
return Uart.FeaturesStand(_config.GetRaw(key), value);
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
return _config.GetRaw(key) == value;
if (_chosen.Contains(key))
return false;
if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) &&
!SettingsSerializer.MouseScaleStands(_config.GetRaw(key)))
return false;
if (overCap.Contains(key))
return false;
// The simulator goes by this to the letter: a monitor's name it does not find. The file's own is no
// choice to keep.
if (string.Equals(key, "fullscreenmonitor", StringComparison.OrdinalIgnoreCase) && _config.GetRaw(key) != value)
return false;
string? synced = _synced.GetValueOrDefault(key);
if (shown.TryGetValue(key, out var onScreen) && onScreen.Shown == value && onScreen.Held == synced)
return true;
@@ -370,6 +603,7 @@ public sealed class SettingsStore
/// <summary>A copy of <paramref name="settings"/> with <paramref name="keys"/> as <paramref name="source"/> has them.</summary>
public SimulatorSettings WithKeysOf(SimulatorSettings settings, SimulatorSettings source, IReadOnlyCollection<string> keys)
{
keys = SettingsSerializer.WithCompanions(keys);
var taken = Render(source);
var config = new ConfigFile();
@@ -398,6 +632,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()
{
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
+24 -2
View File
@@ -58,6 +58,28 @@ public sealed class SimulatorAftermath
}
}
private string SimulatorLogPath => _paths.FromRoot("log.txt");
private bool LogWrittenSince(string path, DateTime startedUtc) =>
_files.FileExists(path) && _files.GetLastWriteTimeUtc(path) >= startedUtc - StartSlack;
/// <summary>
/// Whether the simulator ran at all since <paramref name="startedUtc"/>: it opens its log
/// first thing, so one not written since is the session before's.
/// </summary>
public bool SimulatorRanSince(DateTime startedUtc)
{
try
{
return LogWrittenSince(SimulatorLogPath, startedUtc);
}
catch (Exception ex)
{
_log.Log($"reading {SimulatorLogPath}", ex);
return true;
}
}
/// <summary>
/// The end of the simulator's own log, for when it died without a word on its
/// error stream. A log not written since the start is the session before's, the
@@ -65,10 +87,10 @@ public sealed class SimulatorAftermath
/// </summary>
public IReadOnlyList<string> SimulatorLogTail(int count, DateTime startedUtc)
{
string path = _paths.FromRoot("log.txt");
string path = SimulatorLogPath;
try
{
if (!_files.FileExists(path) || _files.GetLastWriteTimeUtc(path) < startedUtc - StartSlack)
if (!LogWrittenSince(path, startedUtc))
return Array.Empty<string>();
var lines = LegacyText.Decode(_files.ReadAllBytes(path))
+28
View File
@@ -16,6 +16,34 @@ public sealed record SimulatorExit(int ExitCode, TimeSpan RunTime, IReadOnlyList
public bool Failed => ExitCode != 0 || Quick;
/// <summary>The code eu07.exe ends with when its check of the processor has told the player (utilities/cpu_features.h).</summary>
public const uint UnsupportedProcessor = 0xE0450010;
// What eu07_starter.exe returns when it does not start the simulator: missing, refused by its checks of the
// system after a box that said why, or the player's No to a start anyway.
private const int StarterRefused = 1;
// A close by Ctrl+C: the one error code eu07_starter.exe leaves without a word.
private const uint ControlCExit = 0xC000013A;
/// <summary>
/// Whether the player already has a box saying why, so the starter's own would only repeat it. The simulator
/// tells of a processor it cannot run on itself. Started through eu07_starter.exe (<paramref name="throughStarter"/>),
/// an error code of the system was explained by it, or the crash it caught reported by the simulator, and a
/// refusal of its own is one where the simulator never ran (<paramref name="simulatorRan"/>: its log was written).
/// </summary>
public bool AlreadyExplained(bool throughStarter, bool simulatorRan)
{
uint code = unchecked((uint)ExitCode);
if (code == UnsupportedProcessor)
return true;
if (!throughStarter)
return false;
if ((code & 0xF0000000) == 0xC0000000)
return code != ControlCExit;
return ExitCode == StarterRefused && !simulatorRan;
}
/// <summary>The error stream without its colour codes and blank lines.</summary>
public IReadOnlyList<string> CleanErrors =>
Errors.Select(line => AnsiCode.Replace(line, "").TrimEnd())
+4
View File
@@ -58,5 +58,9 @@ public sealed class WarehouseEdit
PresetStore.Save(Name, entry);
_saved = entry;
Saved?.Invoke(Name, entry);
}
/// <summary>The consist was written under its name, with this entry - for the list showing it.</summary>
public event Action<string, string>? Saved;
}
+83 -4
View File
@@ -19,6 +19,9 @@ public sealed class ConfigFile
// Its first line, or -1 when the file runs to its end.
private int _end = -1;
// While lines are indexed: the one at hand starts inside a block comment.
private bool _inBlock;
public static ConfigFile Parse(string text)
{
var cfg = new ConfigFile();
@@ -37,7 +40,10 @@ public sealed class ConfigFile
private void IndexLine(int line)
{
if (!TryParseKey(_lines[line], out string key))
// The simulator skips what /* */ encloses, over as many lines as it runs.
bool startsInBlock = _inBlock;
_inBlock = EndsInBlock(_lines[line], startsInBlock);
if (startsInBlock || !TryParseKey(_lines[line], out string key))
return;
if (_end < 0 && key.Equals(EndKey, StringComparison.OrdinalIgnoreCase))
@@ -52,6 +58,7 @@ public sealed class ConfigFile
{
_index.Clear();
_end = -1;
_inBlock = false;
for (int line = 0; line < _lines.Count; line++)
IndexLine(line);
}
@@ -197,6 +204,42 @@ public sealed class ConfigFile
_index.Remove(key);
}
/// <summary>
/// Deletes the lines that set a key again where a later line, the one the simulator goes by, sets it too:
/// reading top down, it heeds the last of them, so the earlier ones only mislead whoever reads the file.
/// Past endconfig nothing is read, so nothing there is touched, nor the keys the simulator takes more than
/// one of (<paramref name="repeatable"/>), nor a line starting with no letter, which may carry on the value
/// of the line above. Returns the keys of the lines deleted.
/// </summary>
public IReadOnlyList<string> RemoveDuplicates(IReadOnlyCollection<string> repeatable)
{
var removed = new List<string>();
bool inBlock = false;
int end = _end < 0 ? _lines.Count : _end;
var keep = new List<string>(_lines.Count);
for (int line = 0; line < _lines.Count; line++)
{
bool startsInBlock = inBlock;
inBlock = EndsInBlock(_lines[line], startsInBlock);
if (line < end && !startsInBlock && TryParseKey(_lines[line], out string key) && char.IsLetter(key[0]) &&
!repeatable.Contains(key, StringComparer.OrdinalIgnoreCase) &&
_index.TryGetValue(key, out int read) && read != line && read < end &&
!EndsInBlock(_lines[line], false))
{
removed.Add(key);
continue;
}
keep.Add(_lines[line]);
}
if (removed.Count == 0)
return removed;
_lines.Clear();
_lines.AddRange(keep);
Reindex();
return removed;
}
public void SetBool(string key, bool value) => Set(key, value ? "yes" : "no");
public void SetInt(string key, int value) =>
Set(key, value.ToString(CultureInfo.InvariantCulture));
@@ -252,17 +295,53 @@ public sealed class ConfigFile
}
}
// Where a comment starts as the simulator's parser sees one: // or /* anywhere, even glued
// to a value, but not within quotes, which it keeps whole.
private static int FindCommentStart(string body)
{
for (int i = 0; i + 1 < body.Length; i++)
bool quoted = false;
for (int i = 0; i < body.Length; i++)
{
if (body[i] == '/' && body[i + 1] == '/' &&
(i == 0 || char.IsWhiteSpace(body[i - 1])))
if (body[i] == '"')
quoted = !quoted;
else if (!quoted && i + 1 < body.Length && body[i] == '/' && body[i + 1] is '/' or '*')
return i;
}
return -1;
}
// Whether a block comment is still open at the end of the line.
private static bool EndsInBlock(string raw, bool inBlock)
{
bool quoted = false;
for (int i = 0; i < raw.Length; i++)
{
if (inBlock)
{
if (raw[i] == '*' && i + 1 < raw.Length && raw[i + 1] == '/')
{
inBlock = false;
i++;
}
continue;
}
if (raw[i] == '"')
quoted = !quoted;
else if (!quoted && raw[i] == '/' && i + 1 < raw.Length)
{
if (raw[i + 1] == '/')
return false;
if (raw[i + 1] == '*')
{
inBlock = true;
i++;
}
}
}
return inBlock;
}
private static int IndexOfWhitespace(string s)
{
for (int i = 0; i < s.Length; i++)
+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.
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;
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;
}
}
+61
View File
@@ -0,0 +1,61 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.LogicalTree;
namespace StarterNG.Controls;
/// <summary>
/// An overcast option above 1, where the simulator rains or, at 1 °C and below, snows:
/// named for what falls, light or not, in the starter's language.
/// </summary>
public class PrecipitationItem : ComboBoxItem
{
public static readonly StyledProperty<bool> HeavyProperty =
AvaloniaProperty.Register<PrecipitationItem, bool>(nameof(Heavy));
public static readonly StyledProperty<bool> SnowProperty =
AvaloniaProperty.Register<PrecipitationItem, bool>(nameof(Snow));
public PrecipitationItem() => UpdateText();
/// <summary>Rain or snow rather than light rain or light snow.</summary>
public bool Heavy
{
get => GetValue(HeavyProperty);
set => SetValue(HeavyProperty, value);
}
public bool Snow
{
get => GetValue(SnowProperty);
set => SetValue(SnowProperty, value);
}
protected override Type StyleKeyOverride => typeof(ComboBoxItem);
/// <summary>The key of the text the option is named by.</summary>
public string Key => (Snow ? "OvercastSnow" : "OvercastRain") + (Heavy ? "" : "Light");
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == HeavyProperty || change.Property == SnowProperty)
UpdateText();
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
AppLanguage.Changed += UpdateText;
UpdateText();
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
AppLanguage.Changed -= UpdateText;
base.OnDetachedFromLogicalTree(e);
}
private void UpdateText() => Content = AppLanguage.Text(Key);
}
+25 -18
View File
@@ -19,11 +19,27 @@ public class SettingRow : ContentControl
AvaloniaProperty.Register<SettingRow, string?>(nameof(ValueText));
/// <summary>
/// Why the simulator to be started would pass this setting over; the row dims
/// and says so. The input stays usable - the file may serve another build.
/// A setting for those who know what it does: the standard mode leaves it out, as
/// one a player can break the game with or has no need of.
/// </summary>
public static readonly StyledProperty<string?> IdleNoteProperty =
AvaloniaProperty.Register<SettingRow, string?>(nameof(IdleNote));
public static readonly StyledProperty<bool> AdvancedProperty =
AvaloniaProperty.Register<SettingRow, bool>(nameof(Advanced));
public bool Advanced
{
get => GetValue(AdvancedProperty);
set => SetValue(AdvancedProperty, value);
}
/// <summary>The value eu07.ini gives the setting that the starter cannot read, said under it; null when there is none.</summary>
public static readonly StyledProperty<string?> UnknownValueProperty =
AvaloniaProperty.Register<SettingRow, string?>(nameof(UnknownValue));
public string? UnknownValue
{
get => GetValue(UnknownValueProperty);
set => SetValue(UnknownValueProperty, value);
}
public string? Label
{
@@ -49,12 +65,6 @@ public class SettingRow : ContentControl
set => SetValue(ValueTextProperty, value);
}
public string? IdleNote
{
get => GetValue(IdleNoteProperty);
set => SetValue(IdleNoteProperty, value);
}
public SettingRow()
{
UpdatePseudoClasses();
@@ -68,22 +78,19 @@ public class SettingRow : ContentControl
change.Property == DescriptionProperty ||
change.Property == ConfigKeyProperty ||
change.Property == ValueTextProperty ||
change.Property == IdleNoteProperty ||
change.Property == UnknownValueProperty ||
change.Property == ContentProperty)
UpdatePseudoClasses();
if (change.Property == IdleNoteProperty)
ToolTip.SetTip(this, string.IsNullOrEmpty(IdleNote) ? null : IdleNote);
if (change.Property == LabelProperty || change.Property == ContentProperty)
ScreenReaderNames.NameInputs(Content, Label);
if (change.Property == ValueTextProperty || change.Property == ContentProperty)
ScreenReaderNames.TellValue(Content, ValueText);
if (change.Property == DescriptionProperty || change.Property == IdleNoteProperty ||
if (change.Property == DescriptionProperty || change.Property == UnknownValueProperty ||
change.Property == ContentProperty)
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
}
// Again once in the window: a panel given as content may be filled after it was set.
@@ -92,7 +99,7 @@ public class SettingRow : ContentControl
base.OnLoaded(e);
ScreenReaderNames.NameInputs(Content, Label);
ScreenReaderNames.TellValue(Content, ValueText);
ScreenReaderNames.DescribeInputs(Content, Description, IdleNote);
ScreenReaderNames.DescribeInputs(Content, Description, UnknownValue);
}
private void UpdatePseudoClasses()
@@ -102,6 +109,6 @@ public class SettingRow : ContentControl
PseudoClasses.Set(":no-key", string.IsNullOrEmpty(ConfigKey));
PseudoClasses.Set(":no-value", string.IsNullOrEmpty(ValueText));
PseudoClasses.Set(":no-content", Content is null);
PseudoClasses.Set(":idle", !string.IsNullOrEmpty(IdleNote));
PseudoClasses.Set(":unknown", !string.IsNullOrEmpty(UnknownValue));
}
}
+10
View File
@@ -7,6 +7,16 @@ namespace StarterNG.Controls;
public class SettingsSection : HeaderedContentControl
{
/// <summary>Every row of the section is for the advanced mode only.</summary>
public static readonly StyledProperty<bool> AdvancedProperty =
AvaloniaProperty.Register<SettingsSection, bool>(nameof(Advanced));
public bool Advanced
{
get => GetValue(AdvancedProperty);
set => SetValue(AdvancedProperty, value);
}
public static readonly StyledProperty<object?> ToggleProperty =
AvaloniaProperty.Register<SettingsSection, object?>(nameof(Toggle));
+42
View File
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using StarterNG.Classes;
namespace StarterNG.Domain;
/// <summary>A stretch of a consist made of vehicles alike, shown as one picture with a count.</summary>
public sealed record ConsistRun(Dynamic First, int Count);
public static class ConsistRuns
{
/// <summary>
/// The consist's vehicles in order, those next to each other that look alike taken together.
/// </summary>
/// <param name="keyOf">
/// What makes two vehicles alike, given the vehicle and its place in the consist.
/// No key keeps the vehicle on its own.
/// </param>
public static List<ConsistRun> Of(IReadOnlyList<Dynamic> vehicles, Func<Dynamic, int, string?> keyOf)
{
var runs = new List<ConsistRun>();
string? prevKey = null;
for (int i = 0; i < vehicles.Count; i++)
{
string? key = keyOf(vehicles[i], i);
if (key is not null && prevKey is not null && runs.Count > 0 &&
string.Equals(key, prevKey, StringComparison.OrdinalIgnoreCase))
{
var last = runs[^1];
runs[^1] = last with { Count = last.Count + 1 };
}
else
{
runs.Add(new ConsistRun(vehicles[i], 1));
}
prevKey = key;
}
return runs;
}
}
@@ -64,6 +64,13 @@ public enum SceneryFaultKind
/// <summary>An include with no <c>end</c>, which swallows what follows it.</summary>
IncludeNotClosed,
/// <summary>
/// A vehicle whose <c>.fiz</c> is not in its folder under dynamic: the simulator
/// leaves it out, and its trainset runs short. <see cref="SceneryFault.Token"/>
/// names the file.
/// </summary>
VehicleMissing,
/// <summary>A trainset the starter could not read, for a reason none of the above names.</summary>
TrainsetUnreadable,
@@ -15,9 +15,10 @@ namespace StarterNG.Domain.Sceneries;
/// include, so they are not loaded twice.
/// </summary>
/// <remarks>
/// Only the plain <c>include path end</c> form: an include with parameters needs
/// them put in, and one whose <c>end</c> is not on its line is read by the
/// simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
/// Only the plain <c>include path end</c> form, or <c>include path</c> as the last
/// thing in the file, where the simulator runs out of words before it would
/// look for an <c>end</c>: an include with parameters needs them put in, and one
/// whose <c>end</c> is not on its line is read by the simulator in ways not worth guessing. One marked <c>$optional</c> stays too:
/// whether it is loaded is the player's to choose. Each inlined file is wrapped in
/// marker comments, which is how a trainset is told to belong to it.
/// </remarks>
@@ -29,7 +30,8 @@ public static class SceneryIncludes
private static readonly Regex FirstInit = new(@"\bFirstInit\b", RegexOptions.IgnoreCase);
private static readonly Regex Include = new(
@"^[ \t]*include[ \t]+(\S+)[ \t]+end\b[^\r\n]*", RegexOptions.Multiline | RegexOptions.IgnoreCase);
@"^[ \t]*include[ \t]+(\S+?)(?:[ \t]+end\b[^\r\n]*|[ \t]*(?://[^\r\n]*)?\s*\z)",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
private static readonly Regex HasTrainset = new(@"^[ \t]*trainset\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
+24 -4
View File
@@ -33,13 +33,18 @@ public static class ScenerySyntax
/// Whether the simulator opens an include, named as the include names it; null
/// leaves includes unchecked.
/// </param>
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null)
/// <param name="loadsVehicle">
/// Whether the simulator finds a vehicle's definition, by its folder under dynamic
/// and its .mmd's name, as the scenery writes them; null leaves vehicles unchecked.
/// </param>
public static Result Scan(string text, string file, Func<string, bool>? opensInclude = null,
Func<string, string, bool>? loadsVehicle = null)
{
string code = SceneryCode.Mask(text, out int unclosed);
var tokens = SceneryCode.Tokens(code);
var lines = new SceneryLines(text, file);
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true);
var simulator = new Reading(tokens, lines, opensInclude, asSimulator: true, loadsVehicle);
simulator.Run();
var author = new Reading(tokens, lines, null, asSimulator: false);
author.Run();
@@ -110,7 +115,8 @@ public static class ScenerySyntax
}
private sealed class Reading(
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator)
List<SceneryCode.Token> tokens, SceneryLines lines, Func<string, bool>? opensInclude, bool asSimulator,
Func<string, string, bool>? loadsVehicle = null)
{
public readonly List<(int Start, int End, string Name)> Trainsets = new();
public readonly List<(int, int)> Loose = new();
@@ -253,6 +259,9 @@ public static class ScenerySyntax
return tokens.Count - 1;
}
if (complete)
Definition(at, name);
var (fault, trackless) = CheckFields(at, complete, inTrainset, name);
if (fault is null && !closed)
fault = SceneryFaultKind.VehicleNotClosed;
@@ -267,6 +276,16 @@ public static class ScenerySyntax
return end;
}
// Without its .fiz the simulator makes nothing of the vehicle, and reads on to the next.
private void Definition(int at, string name)
{
string folder = tokens[at + 5].Text;
string mmd = tokens[at + 7].Text;
if (loadsVehicle is null || !Plain(folder) || !Plain(mmd) || loadsVehicle(folder, mmd))
return;
Fault(SceneryFaultKind.VehicleMissing, tokens[at].Index, name, $"{folder}/{mmd}.fiz");
}
// As the author meant it: there to be listed, whatever is wrong with it.
private int ListVehicle(int at, bool complete, bool closed, int meant)
{
@@ -378,7 +397,8 @@ public static class ScenerySyntax
while (end < tokens.Count && tokens[end].Text != "end")
end++;
int last = Math.Min(end, tokens.Count - 1);
if (Lost(at + 1, last) is not null)
// No "end" at all is a mistake too, even where the file runs out before it costs anything.
if (end >= tokens.Count || Lost(at + 1, last) is not null)
Fault(SceneryFaultKind.IncludeNotClosed, token.Index, token: name, swallowed: (at + 1, last));
return last;
}
+8 -1
View File
@@ -8,7 +8,14 @@ public sealed class SceneryWeather
public const int FogMin = 10;
public const int FogMax = 10000;
private static readonly double[] OvercastPresets = { -1.5, 0, 0.3, 0.7, 1, 1.1, 1.5 };
/// <summary>
/// What the simulator makes of each: up to 0.1 clear, 0.5 scattered, 0.9 broken,
/// 1 overcast; above 1 it rains or snows, the denser from 1.35 on.
/// </summary>
private static readonly double[] OvercastPresets = { 0, 0.3, 0.7, 1, 1.1, 1.5 };
/// <summary>The simulator rains above 1 °C and snows at that or below.</summary>
public static bool Snows(double temperature) => temperature <= 1;
private string _authoredTime = "10:30";
private string _authoredTimeOverride = "10:30";
+100 -418
View File
@@ -1,512 +1,194 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace StarterNG.Domain.Settings;
/// <summary>
/// What only the two ends of the scale touch: the effects left to taste at every other
/// level and how often the screens refresh. The lowest level gives them up, the highest
/// takes the most there is.
/// </summary>
/// <param name="PythonUpdateMs">python.updatetime, one of the steps of its list.</param>
public sealed record GraphicsExtras(
bool MotionBlur,
bool ChromaticAberration,
bool Smoke,
int PythonUpdateMs)
{
/// <summary>The eu07.ini keys these values live in.</summary>
public static readonly IReadOnlyList<string> Keys = new[]
{
"gfx.postfx.motionblur.enabled", "gfx.postfx.chromaticaberration.enabled",
"gfx.smoke", "python.updatetime"
};
/// <summary>The simulator's own, for leaving a level chosen before this run: what was there earlier is gone.</summary>
public static readonly GraphicsExtras None = new(true, true, true, 200);
public static GraphicsExtras Of(SimulatorSettings s) =>
new(s.MotionBlur, s.ChromaticAberration, s.Smoke, s.PythonScreenUpdateRate);
public void ApplyTo(SimulatorSettings s)
{
s.MotionBlur = MotionBlur;
s.ChromaticAberration = ChromaticAberration;
s.Smoke = Smoke;
s.PythonScreenUpdateRate = PythonUpdateMs;
}
}
/// <summary>
/// What only Ultra sets, switches and limits with no scale to climb. Not every best is the
/// top of a scale: shadows are longest with the limit at its bottom, the regulator and the
/// release of textures would only take away, off.
/// Left to the player, picture unchanged: separate windows for the screens
/// (python.displaywindows, python.vsync), texture streaming, the frame pacing.
/// </summary>
/// <param name="ShadowAngleLimit">gfx.shadow.angle.min: how low the sun counts for shadows, so how long they
/// get: up to 5× the height of what casts them at 0.2, no longer than it at 1 (opengl33renderer.cpp).</param>
/// <param name="TargetFps">targetfps: above 0 the simulator moves the distance factor by itself.</param>
/// <param name="ScreenWindowFps">python.fpslimit: read only by the screens' separate windows
/// (pythonscreenviewer.cpp), it does nothing without them.</param>
/// <param name="TextureRelease">gfx.textures.releasedistance: above 0 textures of far vehicles leave the card.</param>
/// <param name="CompressTextures">compresstex: on saves card memory at a cost to the picture.</param>
/// <param name="SkipDecor">starter.ignoreirrelevant: on leaves decorative consists out of the scenario.</param>
public sealed record GraphicsTop(
double ShadowAngleLimit,
double TargetFps,
double ScreenWindowFps,
double TextureRelease,
bool Screens,
bool ScreenMipmaps,
bool CompressTextures,
bool SkipDecor,
bool Sky,
bool Cab,
bool AirCouplers,
bool SmoothTraction)
{
public const string TargetFpsKey = "targetfps";
public const string ScreenWindowFpsKey = "python.fpslimit";
public const string TextureReleaseKey = "gfx.textures.releasedistance";
public const string SkyKey = "skyenabled";
public const string CabKey = "rendercab";
public const string AirCouplersKey = "newaircouplers";
public const string SmoothTractionKey = "smoothtraction";
/// <summary>Those of its keys shown as rows of <see cref="SimulatorKeys"/>.</summary>
public static readonly IReadOnlyList<string> RowKeys = new[]
{
TargetFpsKey, ScreenWindowFpsKey, TextureReleaseKey, SkyKey, CabKey, AirCouplersKey, SmoothTractionKey
};
/// <summary>The eu07.ini keys these values live in.</summary>
public static readonly IReadOnlyList<string> Keys = RowKeys.Concat(new[]
{
"gfx.shadow.angle.min", "python.enabled", "python.mipmaps", "compresstex", "starter.ignoreirrelevant"
}).ToList();
/// <summary>What they are with nothing set, as <see cref="GraphicsExtras.None"/>.</summary>
public static readonly GraphicsTop None =
new(0.2, 0, 100, 0, true, true, true, false, true, true, true, true);
public static GraphicsTop Of(SimulatorSettings s) =>
new(s.ShadowAngleLimit, GraphicsPreset.NumberOf(s, TargetFpsKey),
GraphicsPreset.NumberOf(s, ScreenWindowFpsKey), GraphicsPreset.NumberOf(s, TextureReleaseKey),
s.PythonScreens, s.ScreenMipmaps, s.CompressTextures, s.IgnoreIrrelevantTrains,
GraphicsPreset.ToggleOf(s, SkyKey), GraphicsPreset.ToggleOf(s, CabKey),
GraphicsPreset.ToggleOf(s, AirCouplersKey), GraphicsPreset.ToggleOf(s, SmoothTractionKey));
public void ApplyTo(SimulatorSettings s)
{
void Number(string key, double value) => s.Extra[key] = value.ToString(CultureInfo.InvariantCulture);
void Toggle(string key, bool value) => s.Extra[key] = SimulatorKey.FormatToggle(value);
s.ShadowAngleLimit = ShadowAngleLimit;
Number(TargetFpsKey, TargetFps);
Number(ScreenWindowFpsKey, ScreenWindowFps);
Number(TextureReleaseKey, TextureRelease);
s.PythonScreens = Screens;
s.ScreenMipmaps = ScreenMipmaps;
s.CompressTextures = CompressTextures;
s.IgnoreIrrelevantTrains = SkipDecor;
Toggle(SkyKey, Sky);
Toggle(CabKey, Cab);
Toggle(AirCouplersKey, AirCouplers);
Toggle(SmoothTractionKey, SmoothTraction);
}
}
/// <summary>
/// What only the simulators with the OpenGL 4.6 and Vulkan 1.4 renderers read, the others pass it
/// over. High is what they do with nothing set. Left to the player: frame generation, Reflex, the
/// choice of the card, automatic exposure, the fitted cascades and the bounced light of the cab.
/// </summary>
/// <param name="CabProbeInterval">gfx.cabprobe.interval, in frames: the lower the dearer.</param>
/// <param name="RayTracing">gfx.raytracing: the Vulkan renderer's alone, off on OpenGL.</param>
public sealed record GraphicsNewRenderer(
int LampShadows,
int ContactShadows,
int Occlusion,
int OcclusionSlices,
int OcclusionSteps,
bool OcclusionLighting,
int CabProbe,
int CabProbeInterval,
bool CabProbeReflections,
int ScreenReflections,
bool RayTracing,
bool VolumetricFog,
int FogQuality,
int Clouds,
bool CloudShadows,
bool Grass,
int GrassDistance,
double GrassDensity,
int Precipitation,
bool Bloom)
{
/// <summary>The eu07.ini keys these values live in; the fade of the grass follows its distance.</summary>
public static readonly IReadOnlyList<string> Keys = new[]
{
"gfx.lights.shadows", "gfx.contactshadows", "gfx.postfx.ao", "gfx.postfx.ao.quality", "gfx.postfx.ao.lighting",
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.reflections", "gfx.ssr", "gfx.raytracing",
"gfx.fog", "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows",
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density",
"gfx.precipitation.particles", "gfx.postfx.bloom"
};
public static GraphicsNewRenderer Of(SimulatorSettings s) =>
new(s.LightShadows, s.ContactShadows, s.AmbientOcclusion, s.AoSlices, s.AoSteps, s.AoLighting,
s.CabProbe, s.CabProbeInterval, s.CabProbeReflections, s.Ssr, s.RayTracing,
s.VolumetricFog, s.FogQuality, s.Clouds, s.CloudShadows,
s.Grass, s.GrassDistance, s.GrassDensity, s.PrecipitationParticles, s.Bloom);
/// <summary>This level as it lands on <paramref name="s"/>: ray tracing on Vulkan only.</summary>
public GraphicsNewRenderer For(SimulatorSettings s) =>
GraphicsRules.RayTracingAllowed(s) ? this : this with { RayTracing = false };
public void ApplyTo(SimulatorSettings s)
{
s.LightShadows = LampShadows;
s.ContactShadows = ContactShadows;
s.AmbientOcclusion = Occlusion;
s.AoSlices = OcclusionSlices;
s.AoSteps = OcclusionSteps;
s.AoLighting = OcclusionLighting;
s.CabProbe = CabProbe;
s.CabProbeInterval = CabProbeInterval;
s.CabProbeReflections = CabProbeReflections;
s.Ssr = ScreenReflections;
s.RayTracing = RayTracing && GraphicsRules.RayTracingAllowed(s);
s.VolumetricFog = VolumetricFog;
s.FogQuality = FogQuality;
s.Clouds = Clouds;
s.CloudShadows = CloudShadows;
s.Grass = Grass;
s.GrassDistance = GrassDistance;
s.GrassDensity = GrassDensity;
s.PrecipitationParticles = Precipitation;
s.Bloom = Bloom;
}
}
/// <summary>
/// A level of detail set in one go: what weighs on the graphics card. Every scale climbs in
/// even steps from <see cref="Minimal"/> to <see cref="Ultra"/>, as far as it has steps for six
/// levels. The screen (resolution, field of view), the frame pacing and the effects that are a
/// matter of taste - motion blur, chromatic aberration - stay as they are, except at the
/// two ends of the scale, which have <see cref="Extras"/>.
/// A level of detail set in one go, as games offer them: what weighs on the graphics card, from Low for a weak or
/// old card to Very high for a strong one. High is about the simulator's own values, the start of a player with no
/// settings of their own; Very high is the most worth having, not everything at its top - ray tracing, MSAA x8 and
/// the largest shadow maps cost far more than they show, and stay for the developer tab. The screen (resolution,
/// render scale, field of view), the frame pacing and the effects that are a matter of taste - motion blur,
/// chromatic aberration - are no level's.
/// </summary>
/// <param name="NameKey">Its name's translation key.</param>
/// <param name="CabShadowsRange">gfx.shadows.cab.range, in metres, read only by the legacy renderer.</param>
/// <param name="AntiAliasing">Multisampling, as older simulators read it too. DLSS, once on, stays: no level does better.</param>
/// <param name="ReflectionsRate">gfx.reflections.framerate, in updates a second.</param>
/// <param name="DrawRange">basedrawrange, in metres. Below 2000 it changes nothing on screen: the renderer
/// keeps at least that for signals and lights (opengl33renderer.cpp).</param>
/// <param name="DistanceFactor">heightbase: the only thing that draws less than those 2 km, and draws
/// shapes, wires and sections nearer. A regulating targetfps moves it from there.</param>
/// <param name="BufferScale">starter.bufferscale, in percent. Above the screen over High: on a 4K one
/// Ultra is a picture of 8K, multisampled on top.</param>
/// <param name="DrawRangeFactor">gfx.drawrange.factor.max: how far the regulator may stretch the draw range.</param>
/// <param name="Keys">The <see cref="SimulatorKeys"/> it sets, in the file's words.</param>
public sealed record GraphicsPreset(
string NameKey,
int TextureSize,
int CabTextureSize,
double Anisotropy,
bool ExtraEffects,
AntiAliasingMode AntiAliasing,
int DynamicLights,
int SmokeFidelity,
bool Shadows,
int ShadowMap,
int ShadowRange,
int ShadowRank,
bool EnvMap,
int ReflectionsFidelity,
double ReflectionsRate,
bool ExtraEffects,
int SplineFidelity,
double DrawRange,
double DistanceFactor,
int BufferScale,
double SleeperDistance,
double DrawRangeFactor,
double ReflectedInstances,
double ReflectedVehicles,
int CabShadowsRange,
GraphicsNewRenderer NewRenderer,
GraphicsExtras? Extras = null,
GraphicsTop? Top = null)
int SmokeFidelity,
IReadOnlyDictionary<string, string> Keys)
{
public const string DrawRangeKey = "basedrawrange";
public const string DistanceFactorKey = "heightbase";
public const string SleeperKey = "sleeperdistance";
public const string ReflectedInstancesKey = "gfx.reflections.range_instances";
public const string ReflectedVehiclesKey = "gfx.reflections.range_vehicles";
/// <summary>Those of its keys shown as rows of <see cref="SimulatorKeys"/>.</summary>
public static readonly IReadOnlyList<string> RowKeys = new[]
{
DrawRangeKey, DistanceFactorKey, SleeperKey, ReflectedInstancesKey, ReflectedVehiclesKey
};
/// <summary>The simulator's own rate of the reflections: once in five minutes, or a kilometre on.</summary>
public const double ReflectionsSeldom = 1 / 300.0;
/// <summary>The eu07.ini keys a level sets.</summary>
public static readonly IReadOnlyList<string> Keys = new[]
{
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "gfx.antialiasing", "dynamiclights",
"gfx.smoke.fidelity", "shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff",
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.extraeffects",
"splinefidelity", DrawRangeKey, DistanceFactorKey, "starter.bufferscale", "gfx.buffer.percent", SleeperKey,
"gfx.drawrange.factor.max", ReflectedInstancesKey, ReflectedVehiclesKey, "gfx.shadows.cab.range"
}.Concat(GraphicsNewRenderer.Keys).ToList();
public static IReadOnlyList<string> AllKeys =>
GraphicsGroup.All.SelectMany(group => group.Keys).Concat(GraphicsGroup.AntiAliasingKeys).ToList();
/// <summary>The last resort: no shadows, no reflections, no effects, no smoke, a softer picture.</summary>
public static readonly GraphicsPreset Minimal = new(
"PresetMinimal", TextureSize: 512, CabTextureSize: 512, Anisotropy: 1, AntiAliasing: AntiAliasingMode.Off,
DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 512, ShadowRange: 75, ShadowRank: 1,
EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1 / 300.0, ExtraEffects: false,
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.6, BufferScale: 70,
SleeperDistance: 100, DrawRangeFactor: 1, ReflectedInstances: 250, ReflectedVehicles: 50, CabShadowsRange: 0,
NewRenderer: new GraphicsNewRenderer(LampShadows: 0, ContactShadows: 0, Occlusion: 0, OcclusionSlices: 2, OcclusionSteps: 3,
OcclusionLighting: false, CabProbe: 0, CabProbeInterval: 8, CabProbeReflections: false, ScreenReflections: 0,
RayTracing: false, VolumetricFog: false, FogQuality: 1, Clouds: 0, CloudShadows: false, Grass: false,
GrassDistance: 30, GrassDensity: 0.25, Precipitation: 16384, Bloom: false),
Extras: new GraphicsExtras(MotionBlur: false, ChromaticAberration: false, Smoke: false, PythonUpdateMs: 800));
private static Dictionary<string, string> Values(params (string Key, string Value)[] values) =>
values.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
/// <summary>For a weak or old card, or a laptop on its own graphics: the shadows short, no screen-space effects.</summary>
public static readonly GraphicsPreset Low = new(
"PresetLow", TextureSize: 1024, CabTextureSize: 1024, Anisotropy: 2, AntiAliasing: AntiAliasingMode.Off,
DynamicLights: 3, SmokeFidelity: 1, Shadows: true, ShadowMap: 1024, ShadowRange: 125, ShadowRank: 2,
EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1 / 60.0, ExtraEffects: true,
SplineFidelity: 1, DrawRange: 2000, DistanceFactor: 0.7, BufferScale: 80,
SleeperDistance: 150, DrawRangeFactor: 1.5, ReflectedInstances: 400, ReflectedVehicles: 100, CabShadowsRange: 0,
NewRenderer: new GraphicsNewRenderer(LampShadows: 1, ContactShadows: 0, Occlusion: 1, OcclusionSlices: 2, OcclusionSteps: 3,
OcclusionLighting: false, CabProbe: 0, CabProbeInterval: 8, CabProbeReflections: false, ScreenReflections: 1,
RayTracing: false, VolumetricFog: true, FogQuality: 1, Clouds: 1, CloudShadows: false, Grass: true,
GrassDistance: 40, GrassDensity: 0.5, Precipitation: 32768, Bloom: true));
"PresetLow", TextureSize: 1024, CabTextureSize: 1024, Anisotropy: 4, ExtraEffects: false,
AntiAliasing: AntiAliasingMode.Off, ShadowMap: 1024, ShadowRange: 125, ShadowRank: 1,
ReflectionsFidelity: 0, ReflectionsRate: ReflectionsSeldom, SplineFidelity: 1, DrawRangeFactor: 1,
SmokeFidelity: 1,
Values(("gfx.lights.shadows", "low"), ("gfx.contactshadows", "no"), ("gfx.ssr", "no"), ("gfx.cabprobe", "low"),
("gfx.postfx.ao", "no"), ("gfx.fog.quality", "low"), ("gfx.clouds", "low"),
("gfx.grass", "yes"), ("gfx.grass.distance", "40"), ("gfx.grass.fadedistance", "50"),
("gfx.grass.density", "0.5"), ("gfx.precipitation.particles", "16384")));
public static readonly GraphicsPreset Medium = new(
"PresetMedium", TextureSize: 2048, CabTextureSize: 2048, Anisotropy: 4, AntiAliasing: AntiAliasingMode.Msaa2,
DynamicLights: 5, SmokeFidelity: 2, Shadows: true, ShadowMap: 1024, ShadowRange: 175, ShadowRank: 2,
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1 / 30.0, ExtraEffects: true,
SplineFidelity: 2, DrawRange: 2250, DistanceFactor: 0.85, BufferScale: 90,
SleeperDistance: 200, DrawRangeFactor: 2, ReflectedInstances: 550, ReflectedVehicles: 150, CabShadowsRange: 20,
NewRenderer: new GraphicsNewRenderer(LampShadows: 1, ContactShadows: 0, Occlusion: 1, OcclusionSlices: 3, OcclusionSteps: 4,
OcclusionLighting: false, CabProbe: 1, CabProbeInterval: 8, CabProbeReflections: true, ScreenReflections: 1,
RayTracing: false, VolumetricFog: true, FogQuality: 1, Clouds: 1, CloudShadows: true, Grass: true,
GrassDistance: 50, GrassDensity: 0.75, Precipitation: 32768, Bloom: true));
"PresetMedium", TextureSize: 2048, CabTextureSize: 2048, Anisotropy: 8, ExtraEffects: true,
AntiAliasing: AntiAliasingMode.Msaa2, ShadowMap: 2048, ShadowRange: 175, ShadowRank: 2,
ReflectionsFidelity: 1, ReflectionsRate: ReflectionsSeldom, SplineFidelity: 2, DrawRangeFactor: 2,
SmokeFidelity: 1,
Values(("gfx.lights.shadows", "low"), ("gfx.contactshadows", "no"), ("gfx.ssr", "low"), ("gfx.cabprobe", "low"),
("gfx.postfx.ao", "ssao"), ("gfx.fog.quality", "medium"), ("gfx.clouds", "low"),
("gfx.grass", "yes"), ("gfx.grass.distance", "60"), ("gfx.grass.fadedistance", "70"),
("gfx.grass.density", "1"), ("gfx.precipitation.particles", "32768")));
/// <summary>
/// Where a player with no settings of their own starts. The simulator's own values (Globals.h),
/// but for smoke, track curves, reflections and cab shadows: theirs are the bottom of a scale
/// with levels to go under this one.
/// </summary>
/// <summary>Where a player with no settings of their own starts: about the simulator's own values.</summary>
public static readonly GraphicsPreset High = new(
"PresetHigh", TextureSize: 4096, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa4,
DynamicLights: 7, SmokeFidelity: 2, Shadows: true, ShadowMap: 2048, ShadowRange: 250, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 0.1, ExtraEffects: true,
SplineFidelity: 2, DrawRange: 2500, DistanceFactor: 1, BufferScale: 100,
SleeperDistance: 250, DrawRangeFactor: 3, ReflectedInstances: 750, ReflectedVehicles: 250, CabShadowsRange: 40,
NewRenderer: new GraphicsNewRenderer(LampShadows: 2, ContactShadows: 0, Occlusion: 2, OcclusionSlices: 3, OcclusionSteps: 4,
OcclusionLighting: true, CabProbe: 2, CabProbeInterval: 4, CabProbeReflections: true, ScreenReflections: 2,
RayTracing: false, VolumetricFog: true, FogQuality: 2, Clouds: 2, CloudShadows: true, Grass: true,
GrassDistance: 60, GrassDensity: 1, Precipitation: 65536, Bloom: true));
/// <summary>For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m.</summary>
public static readonly GraphicsPreset VeryHigh = new(
"PresetVeryHigh", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
DynamicLights: 7, SmokeFidelity: 3, Shadows: true, ShadowMap: 4096, ShadowRange: 400, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 2, ExtraEffects: true,
SplineFidelity: 3, DrawRange: 5000, DistanceFactor: 2, BufferScale: 150,
SleeperDistance: 2000, DrawRangeFactor: 3, ReflectedInstances: 1500, ReflectedVehicles: 1000, CabShadowsRange: 70,
NewRenderer: new GraphicsNewRenderer(LampShadows: 3, ContactShadows: 2, Occlusion: 2, OcclusionSlices: 4, OcclusionSteps: 6,
OcclusionLighting: true, CabProbe: 3, CabProbeInterval: 3, CabProbeReflections: true, ScreenReflections: 3,
RayTracing: false, VolumetricFog: true, FogQuality: 3, Clouds: 3, CloudShadows: true, Grass: true,
GrassDistance: 120, GrassDensity: 1.5, Precipitation: 131072, Bloom: true));
"PresetHigh", TextureSize: 4096, CabTextureSize: 4096, Anisotropy: 8, ExtraEffects: true,
AntiAliasing: AntiAliasingMode.Msaa4, ShadowMap: 2048, ShadowRange: 250, ShadowRank: 3,
ReflectionsFidelity: 2, ReflectionsRate: ReflectionsSeldom, SplineFidelity: 2, DrawRangeFactor: 3,
SmokeFidelity: 2,
Values(("gfx.lights.shadows", "medium"), ("gfx.contactshadows", "no"), ("gfx.ssr", "medium"),
("gfx.cabprobe", "medium"), ("gfx.postfx.ao", "gtao"), ("gfx.fog.quality", "medium"),
("gfx.clouds", "medium"), ("gfx.grass", "yes"), ("gfx.grass.distance", "60"),
("gfx.grass.fadedistance", "70"), ("gfx.grass.density", "1"), ("gfx.precipitation.particles", "65536")));
/// <summary>
/// Every value at the top of what the screen offers. Not the best picture throughout: a map
/// of 8192 stretches the cascades fourfold, so shadows reach 2400 m but are coarser up close
/// than at <see cref="VeryHigh"/>.
/// For a strong card. A map of 4096 doubles the cascades, so the range here reaches 600 m; the textures of the
/// cab stay at 4096, the most the starter gives them.
/// </summary>
public static readonly GraphicsPreset Ultra = new(
"PresetUltra", TextureSize: 8192, CabTextureSize: 8192, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8,
DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 600, ShadowRank: 3,
EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 60, ExtraEffects: true,
SplineFidelity: 4, DrawRange: 10000, DistanceFactor: 3, BufferScale: 200,
SleeperDistance: 5000, DrawRangeFactor: 3, ReflectedInstances: 3000, ReflectedVehicles: 2000, CabShadowsRange: 100,
NewRenderer: new GraphicsNewRenderer(LampShadows: 3, ContactShadows: 3, Occlusion: 2, OcclusionSlices: 6, OcclusionSteps: 8,
OcclusionLighting: true, CabProbe: 3, CabProbeInterval: 2, CabProbeReflections: true, ScreenReflections: 3,
RayTracing: true, VolumetricFog: true, FogQuality: 4, Clouds: 4, CloudShadows: true, Grass: true,
GrassDistance: 300, GrassDensity: 2, Precipitation: 262144, Bloom: true),
Extras: new GraphicsExtras(MotionBlur: true, ChromaticAberration: true, Smoke: true, PythonUpdateMs: 200),
Top: new GraphicsTop(ShadowAngleLimit: 0.2, TargetFps: 0, ScreenWindowFps: 200, TextureRelease: 0,
Screens: true, ScreenMipmaps: true, CompressTextures: false, SkipDecor: false,
Sky: true, Cab: true, AirCouplers: true, SmoothTraction: true));
public static readonly GraphicsPreset VeryHigh = new(
"PresetVeryHigh", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 16, ExtraEffects: true,
AntiAliasing: AntiAliasingMode.Msaa4, ShadowMap: 4096, ShadowRange: 300, ShadowRank: 3,
ReflectionsFidelity: 2, ReflectionsRate: 1, SplineFidelity: 3, DrawRangeFactor: 3,
SmokeFidelity: 3,
Values(("gfx.lights.shadows", "high"), ("gfx.contactshadows", "low"), ("gfx.ssr", "high"),
("gfx.cabprobe", "high"), ("gfx.postfx.ao", "gtao"), ("gfx.fog.quality", "high"),
("gfx.clouds", "high"), ("gfx.grass", "yes"), ("gfx.grass.distance", "100"),
("gfx.grass.fadedistance", "120"), ("gfx.grass.density", "1.25"), ("gfx.precipitation.particles", "65536")));
public static readonly IReadOnlyList<GraphicsPreset> All = new[] { Minimal, Low, Medium, High, VeryHigh, Ultra };
public static readonly IReadOnlyList<GraphicsPreset> All = new[] { Low, Medium, High, VeryHigh };
public void ApplyTo(SimulatorSettings s)
{
s.MaxTextureSize = TextureSize;
s.MaxCabTextureSize = CabTextureSize;
s.TextureFiltering = Anisotropy;
if (!GraphicsRules.IsDlss(s.AntiAliasing))
s.AntiAliasing = AntiAliasing;
s.CabShadowsRange = CabShadowsRange;
s.DynamicLights = DynamicLights;
s.SmokeFidelity = SmokeFidelity;
s.RenderShadows = Shadows;
s.ExtraEffects = ExtraEffects;
s.AntiAliasing = AntiAliasing;
s.RenderShadows = true;
s.ShadowMapResolution = ShadowMap;
s.ShadowProjectionRange = ShadowRange;
s.ShadowRankCutoff = ShadowRank;
s.EnvMap = EnvMap;
s.EnvMap = true;
s.ReflectionsFidelity = ReflectionsFidelity;
s.ReflectionsFramerate = ReflectionsRate;
s.ExtraEffects = ExtraEffects;
s.SplineFidelity = SplineFidelity;
s.Extra[DrawRangeKey] = DrawRange.ToString(CultureInfo.InvariantCulture);
s.Extra[DistanceFactorKey] = DistanceFactor.ToString(CultureInfo.InvariantCulture);
s.BufferScalePercent = BufferScale;
s.Extra[SleeperKey] = SleeperDistance.ToString(CultureInfo.InvariantCulture);
s.DrawRangeFactor = DrawRangeFactor;
s.Extra[ReflectedInstancesKey] = ReflectedInstances.ToString(CultureInfo.InvariantCulture);
s.Extra[ReflectedVehiclesKey] = ReflectedVehicles.ToString(CultureInfo.InvariantCulture);
NewRenderer.ApplyTo(s);
Extras?.ApplyTo(s);
Top?.ApplyTo(s);
s.SmokeFidelity = SmokeFidelity;
foreach (var (key, value) in Keys)
s.Extra[key] = value;
}
/// <summary>Whether <paramref name="s"/> is at this level throughout.</summary>
public bool Matches(SimulatorSettings s) =>
s.MaxTextureSize == TextureSize && s.MaxCabTextureSize == CabTextureSize &&
Near(s.TextureFiltering, Anisotropy) && (GraphicsRules.IsDlss(s.AntiAliasing) || s.AntiAliasing == AntiAliasing) &&
s.DynamicLights == DynamicLights && s.SmokeFidelity == SmokeFidelity &&
s.RenderShadows == Shadows && s.ShadowMapResolution == ShadowMap &&
Near(s.TextureFiltering, Anisotropy) && s.ExtraEffects == ExtraEffects && s.AntiAliasing == AntiAliasing &&
s.RenderShadows && s.ShadowMapResolution == ShadowMap &&
s.ShadowProjectionRange == ShadowRange && s.ShadowRankCutoff == ShadowRank &&
s.EnvMap == EnvMap && s.ReflectionsFidelity == ReflectionsFidelity &&
Near(s.ReflectionsFramerate, ReflectionsRate) && s.ExtraEffects == ExtraEffects &&
s.SplineFidelity == SplineFidelity && Near(NumberOf(s, DrawRangeKey), DrawRange) &&
Near(NumberOf(s, DistanceFactorKey), DistanceFactor) &&
s.BufferScalePercent == BufferScale &&
Near(NumberOf(s, SleeperKey), SleeperDistance) && Near(s.DrawRangeFactor, DrawRangeFactor) &&
Near(NumberOf(s, ReflectedInstancesKey), ReflectedInstances) &&
Near(NumberOf(s, ReflectedVehiclesKey), ReflectedVehicles) &&
s.CabShadowsRange == CabShadowsRange &&
GraphicsNewRenderer.Of(s) == NewRenderer.For(s) &&
(Extras is null || GraphicsExtras.Of(s) == Extras) &&
(Top is null || GraphicsTop.Of(s) == Top);
s.EnvMap && s.ReflectionsFidelity == ReflectionsFidelity &&
Near(s.ReflectionsFramerate, ReflectionsRate) &&
s.SplineFidelity == SplineFidelity && Near(s.DrawRangeFactor, DrawRangeFactor) &&
s.SmokeFidelity == SmokeFidelity &&
Keys.All(pair => SameValue(SimulatorKeys.Named(pair.Key), pair.Value, s));
/// <summary>The level <paramref name="s"/> is at throughout, if any.</summary>
public static GraphicsPreset? Matching(SimulatorSettings s) => All.FirstOrDefault(preset => preset.Matches(s));
internal static double NumberOf(SimulatorSettings s, string name)
/// <summary>Whether <paramref name="s"/> gives the key the value <paramref name="value"/> means, written its own way.</summary>
private static bool SameValue(SimulatorKey key, string value, SimulatorSettings s)
{
var key = SimulatorKeys.Named(name);
return key.ParseNumber(key.RawIn(s));
string raw = key.RawIn(s);
return key.Kind switch
{
SimulatorKeyKind.Toggle => SimulatorKey.ParseToggle(raw) == SimulatorKey.ParseToggle(value),
SimulatorKeyKind.Number => Near(key.ParseNumber(raw), key.ParseNumber(value)),
SimulatorKeyKind.Choice => key.ChoiceIndex(raw) == key.ChoiceIndex(value),
_ => string.Equals(raw.Trim(), value, StringComparison.OrdinalIgnoreCase)
};
}
internal static bool ToggleOf(SimulatorSettings s, string name) =>
SimulatorKey.ParseToggle(SimulatorKeys.Named(name).RawIn(s));
// As the file rounds it: 1/300 comes back as 0.003333.
// As the file rounds it.
private static bool Near(double value, double target) =>
Math.Abs(value - target) <= Math.Abs(target) * 2e-4 + 1e-9;
}
/// <summary>
/// A part of the picture with a level of its own, as its section on the screen has it. The rest
/// of a level - the buffer, the anti-aliasing, the post-processing switches, the frame pacing, the sky and the cab - goes only with the whole.
/// A part of the picture with a level of its own: one row of the standard mode, which the levels set in one go and
/// the player can take further up or down. The anti-aliasing has a row of its own.
/// </summary>
/// <param name="NameKey">Its row's translation key.</param>
/// <param name="Keys">The eu07.ini keys it sets.</param>
public sealed record GraphicsGroup(IReadOnlyList<string> Keys)
public sealed record GraphicsGroup(string NameKey, IReadOnlyList<string> Keys)
{
public static readonly GraphicsGroup DrawRange = new(new[]
/// <summary>The keys of the anti-aliasing, which a level sets too.</summary>
public static readonly IReadOnlyList<string> AntiAliasingKeys = new[] { "gfx.antialiasing", "multisampling" };
public static readonly GraphicsGroup Textures = new("GroupTextures", new[]
{
GraphicsPreset.DrawRangeKey, GraphicsPreset.DistanceFactorKey, "splinefidelity",
GraphicsPreset.SleeperKey, "gfx.drawrange.factor.max"
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "gfx.extraeffects"
});
public static readonly GraphicsGroup Textures = new(new[]
public static readonly GraphicsGroup Shadows = new("GroupShadows", new[]
{
"maxtexturesize", "maxcabtexturesize", "anisotropicfiltering",
"compresstex", GraphicsTop.TextureReleaseKey
"gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff", "gfx.lights.shadows", "gfx.contactshadows"
});
public static readonly GraphicsGroup Shadows = new(new[]
public static readonly GraphicsGroup Reflections = new("GroupReflections", new[]
{
"shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff", "gfx.shadow.angle.min", "gfx.shadows.cab.range"
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.ssr", "gfx.cabprobe"
});
public static readonly GraphicsGroup Lights = new(new[]
public static readonly GraphicsGroup Lighting = new("GroupLighting", new[]
{
"dynamiclights", "gfx.lights.shadows", "gfx.contactshadows", "gfx.postfx.ao", "gfx.postfx.ao.quality",
"gfx.postfx.ao.lighting", "gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.reflections"
"gfx.postfx.ao", "gfx.fog.quality", "gfx.clouds"
});
public static readonly GraphicsGroup Reflections = new(new[]
public static readonly GraphicsGroup DrawRange = new("GroupDrawRange", new[]
{
"gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate",
GraphicsPreset.ReflectedInstancesKey, GraphicsPreset.ReflectedVehiclesKey, "gfx.ssr", "gfx.raytracing"
"splinefidelity", "gfx.drawrange.factor.max", "gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance",
"gfx.grass.density"
});
public static readonly GraphicsGroup Atmosphere = new(new[]
public static readonly GraphicsGroup Particles = new("GroupParticles", new[]
{
"gfx.fog", "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows"
});
public static readonly GraphicsGroup Nature = new(new[]
{
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density",
"gfx.smoke", "gfx.smoke.fidelity", "gfx.precipitation.particles"
"gfx.smoke.fidelity", "gfx.precipitation.particles"
});
public static readonly IReadOnlyList<GraphicsGroup> All = new[]
{
DrawRange, Textures, Shadows, Lights, Reflections, Atmosphere, Nature
Textures, Shadows, Reflections, Lighting, DrawRange, Particles
};
}
/// <summary>What applying a level touched.</summary>
/// <param name="RowKeys">The keys of <see cref="SimulatorKeys"/> rows to show its values in, in that order.</param>
/// <param name="ChosenKeys">The eu07.ini keys it chose as a whole.</param>
public sealed record PresetApplied(IReadOnlyList<string> RowKeys, IReadOnlyList<string> ChosenKeys);
/// <summary>
/// Remembers what was there before an end of the scale, which comes back with any level
/// between. Leaving one chosen before this run, what was there earlier is gone, so the
/// simulator's own values take its place.
/// </summary>
public sealed class GraphicsPresetMemory
{
private GraphicsExtras? _beforeExtras;
private GraphicsTop? _beforeTop;
/// <summary>Puts <paramref name="preset"/> in <paramref name="settings"/>, with what an end of the scale left behind.</summary>
public PresetApplied Apply(GraphicsPreset preset, SimulatorSettings settings)
{
var current = GraphicsPreset.Matching(settings);
var coming = preset.Extras is not null ? null
: _beforeExtras ?? (current?.Extras is not null ? GraphicsExtras.None : null);
_beforeExtras = preset.Extras is not null ? _beforeExtras ?? GraphicsExtras.Of(settings) : null;
var comingTop = preset.Top is not null ? null
: _beforeTop ?? (current?.Top is not null ? GraphicsTop.None : null);
_beforeTop = preset.Top is not null ? _beforeTop ?? GraphicsTop.Of(settings) : null;
coming?.ApplyTo(settings);
comingTop?.ApplyTo(settings);
preset.ApplyTo(settings);
var rows = new List<string>(GraphicsPreset.RowKeys);
var chosen = new List<string>(GraphicsPreset.Keys);
if (preset.Extras is not null || coming is not null)
chosen.AddRange(GraphicsExtras.Keys);
if (preset.Top is not null || comingTop is not null)
{
chosen.AddRange(GraphicsTop.Keys);
rows.AddRange(GraphicsTop.RowKeys);
}
return new PresetApplied(rows, chosen);
}
}
+15 -98
View File
@@ -1,115 +1,32 @@
namespace StarterNG.Domain.Settings;
/// <summary>
/// What the simulator does with combinations of graphics settings, mirrored here so
/// the starter only offers what takes effect and writes eu07.ini the way the
/// simulator will run it (utilities/Globals.cpp, rendering/vulkan14, rendering/opengl46).
/// What the simulator does with graphics values, mirrored here so the starter writes
/// eu07.ini the way the simulator will run it (utilities/Globals.cpp), and how far the
/// starter lets them go: no further than the old starter did (MaSzyna-EU07/Starter).
/// </summary>
public static class GraphicsRules
{
public static bool IsDlss(AntiAliasingMode mode) => mode is AntiAliasingMode.Dlss or AntiAliasingMode.Dlaa;
/// <summary>maxcabtexturesize: the old starter's list ended at 4096.</summary>
public const int MaxCabTextureSize = 4096;
public static bool IsTemporal(AntiAliasingMode mode) => mode == AntiAliasingMode.Taa || IsDlss(mode);
public static bool IsVulkan(SimulatorSettings s) => s.Backend == GraphicsBackend.Vulkan;
/// <summary>The projection range of shadowtune: the old starter's list ended at 400.</summary>
public const int MaxShadowRange = 400;
/// <summary>
/// DLSS is the Vulkan renderer's only (the OpenGL one takes TAA instead), and the
/// DLSS SDK has no macOS libraries.
/// The frame buffer, in percent of the window. The old starter's choice of buffer
/// (gfx.framebuffer.fidelity) is not read by the simulator, so it always had the window's size.
/// </summary>
public static bool DlssAllowed(SimulatorSettings s, bool dlssPlatform) => dlssPlatform && IsVulkan(s);
public const int MaxBufferScale = 100;
public static bool DlssActive(SimulatorSettings s, bool dlssPlatform) =>
DlssAllowed(s, dlssPlatform) && IsDlss(s.AntiAliasing);
/// <summary>The frame generation goes with gfx.antialiasing dlss or dlaa, nothing else.</summary>
public static bool FrameGenerationAllowed(SimulatorSettings s, bool dlssPlatform) => DlssActive(s, dlssPlatform);
/// <summary>Reflex (VK_NV_low_latency2) is the Vulkan renderer's only.</summary>
public static bool ReflexAllowed(SimulatorSettings s) => IsVulkan(s);
/// <summary>The frame generation turns Reflex on whatever gfx.reflex says.</summary>
public static bool ReflexForced(SimulatorSettings s, bool dlssPlatform) =>
FrameGenerationAllowed(s, dlssPlatform) && s.FrameGeneration > 1;
/// <summary>Ray traced reflections: the Vulkan renderer on a GPU with ray queries.</summary>
public static bool RayTracingAllowed(SimulatorSettings s) => IsVulkan(s);
/// <summary>The render scale is ignored by DLAA, which always draws at the size of the window.</summary>
public static bool BufferScaleUsed(SimulatorSettings s, bool dlssPlatform) =>
!(DlssActive(s, dlssPlatform) && s.AntiAliasing == AntiAliasingMode.Dlaa);
/// <summary>TAA and DLSS run in the post-processing which gfx.skippipeline leaves out.</summary>
public static bool TemporalWithoutPipeline(SimulatorSettings s) => s.SkipPipeline && IsTemporal(s.AntiAliasing);
/// <summary>With the clustered lights the headlights come from the clusters; dynamiclights only caps the old path.</summary>
public static bool DynamicLightsUsed(SimulatorSettings s) => !s.LightsClustered;
/// <summary>The ambient occlusion goes into the lighting only with GTAO.</summary>
public static bool AoLightingUsed(SimulatorSettings s) => s.AmbientOcclusion == 2;
/// <summary>
/// The AO in the lighting needs the depth of the whole scene drawn before its colour. SSR, contact
/// shadows and gfx.depthprepass.scene draw it anyway; without them it is an extra pass (CPU time on OpenGL).
/// </summary>
public static bool AoLightingAddsDepthPrepass(SimulatorSettings s) =>
AoLightingUsed(s) && s.AoLighting && s.Ssr == 0 && s.ContactShadows == 0 && !s.DepthPrepassScene;
public static bool CabProbeUsed(SimulatorSettings s) => s.CabProbe > 0;
/// <summary>
/// The light bounced around the cab comes from the cab lamp as a light, which needs the clustered lights
/// and gfx.lights.cab; without them the probe gives the reflections only.
/// </summary>
public static bool CabProbeLights(SimulatorSettings s) => CabProbeUsed(s) && s.LightsClustered && s.CabLampLight;
/// <summary>
/// Brings the settings to what the simulator would run with: the Vulkan-only
/// features off on OpenGL, DLSS falling back to TAA, values within the ranges
/// the simulator clamps them to.
/// </summary>
public static void Normalize(SimulatorSettings s, bool dlssPlatform)
/// <summary>Brings the values within the ranges the simulator clamps them to, and the starter's caps.</summary>
public static void Normalize(SimulatorSettings s)
{
if (IsDlss(s.AntiAliasing) && !DlssAllowed(s, dlssPlatform))
s.AntiAliasing = AntiAliasingMode.Taa;
s.FrameGeneration = FrameGenerationAllowed(s, dlssPlatform) ? Clamp(s.FrameGeneration, 1, 4) : 1;
s.Reflex = ReflexAllowed(s) ? Clamp(s.Reflex, 0, 2) : 0;
if (!RayTracingAllowed(s))
s.RayTracing = false;
if (!IsKnownDlssPreset(s.DlssPreset))
s.DlssPreset = "default";
s.MaxTextureSize = PowerOfTwo(s.MaxTextureSize, 64, 8192);
s.MaxCabTextureSize = PowerOfTwo(s.MaxCabTextureSize, 512, 8192);
s.MaxCabTextureSize = PowerOfTwo(s.MaxCabTextureSize, 512, MaxCabTextureSize);
s.ShadowMapResolution = PowerOfTwo(s.ShadowMapResolution, 512, 8192);
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, 200);
s.LightShadows = Clamp(s.LightShadows, 0, 3);
s.ContactShadows = Clamp(s.ContactShadows, 0, 3);
s.AmbientOcclusion = Clamp(s.AmbientOcclusion, 0, 2);
s.AoSlices = Clamp(s.AoSlices, 1, 8);
s.AoSteps = Clamp(s.AoSteps, 1, 16);
s.CabProbe = Clamp(s.CabProbe, 0, 3);
s.CabProbeInterval = Clamp(s.CabProbeInterval, 1, 120);
s.CabProbeBounce = s.CabProbeBounce < 0 ? 0 : (s.CabProbeBounce > 4 ? 4 : s.CabProbeBounce);
s.Ssr = Clamp(s.Ssr, 0, 3);
s.RayTracingRange = Clamp(s.RayTracingRange, 10, 5000);
s.FogQuality = Clamp(s.FogQuality, 1, 4);
s.Clouds = Clamp(s.Clouds, 0, 4);
s.GrassDistance = Clamp(s.GrassDistance, 5, 500);
s.GrassDensity = s.GrassDensity < 0 ? 0 : (s.GrassDensity > 4 ? 4 : s.GrassDensity);
s.PrecipitationParticles = Clamp(s.PrecipitationParticles, 0, 1 << 20);
}
public static readonly string[] DlssPresets = { "default", "j", "k", "l", "m" };
public static bool IsKnownDlssPreset(string? preset)
{
foreach (string known in DlssPresets)
if (string.Equals(known, preset, System.StringComparison.OrdinalIgnoreCase))
return true;
return false;
s.ShadowProjectionRange = s.ShadowProjectionRange > MaxShadowRange ? MaxShadowRange : s.ShadowProjectionRange;
s.BufferScalePercent = Clamp(s.BufferScalePercent, 25, MaxBufferScale);
}
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StarterNG.Domain.Settings;
/// <summary>
/// How true to life the driving is, set in one go. Arcade forgives: no derailment, the legacy couplings and
/// collisions, no damage, no broken pantograph, power without the wires, every consist ready to drive. Realistic
/// takes the physical models of the simulator: the couplings of the player's train with their play and their
/// breaking, the derailment by its criteria (a track's own speed limit still derails nothing, as
/// physics.derailment.trustlimits keeps it), the crush of the ends in a collision, the track buckling in the heat,
/// and the consists as the scenario has them. The simulator's own values stand between the two.
/// </summary>
/// <param name="NameKey">Its name's translation key.</param>
/// <param name="Keys">The <see cref="SimulatorKeys"/> it sets, in the file's words.</param>
public sealed record PhysicsPreset(
string NameKey,
bool CrashDamage,
bool PantographsBreak,
bool PowerFromWiresOnly,
ConsistReadyOverride ReadyOverride,
IReadOnlyDictionary<string, string> Keys)
{
/// <summary>The eu07.ini keys a level sets.</summary>
public static readonly IReadOnlyList<string> AllKeys = new[]
{
"crashdamage", "enabletraction", "livetraction", "starter.batterydefault",
"couplerphysics", "physics.derailment", "physics.collisions", "physics.trackbuckling"
};
private static Dictionary<string, string> Values(params (string Key, string Value)[] values) =>
values.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
public static readonly PhysicsPreset Arcade = new(
"PhysicsArcade", CrashDamage: false, PantographsBreak: false, PowerFromWiresOnly: false,
ReadyOverride: ConsistReadyOverride.AlwaysReady,
Values(("couplerphysics", "no"), ("physics.derailment", "off"), ("physics.collisions", "old"),
("physics.trackbuckling", "off")));
public static readonly PhysicsPreset Realistic = new(
"PhysicsRealistic", CrashDamage: true, PantographsBreak: true, PowerFromWiresOnly: true,
ReadyOverride: ConsistReadyOverride.Scenery,
Values(("couplerphysics", "yes"), ("physics.derailment", "new"), ("physics.collisions", "new"),
("physics.trackbuckling", "auto")));
public static readonly IReadOnlyList<PhysicsPreset> All = new[] { Arcade, Realistic };
public void ApplyTo(SimulatorSettings s)
{
s.CrashDamage = CrashDamage;
s.EnableTraction = PantographsBreak;
s.LiveTraction = PowerFromWiresOnly;
s.ReadyOverride = ReadyOverride;
foreach (var (key, value) in Keys)
s.Extra[key] = value;
}
/// <summary>Whether <paramref name="s"/> is at this level throughout.</summary>
public bool Matches(SimulatorSettings s) =>
s.CrashDamage == CrashDamage && s.EnableTraction == PantographsBreak && s.LiveTraction == PowerFromWiresOnly &&
s.ReadyOverride == ReadyOverride &&
Keys.All(pair => SimulatorKeys.Named(pair.Key) is var key &&
key.ChoiceIndex(key.RawIn(s)) == key.ChoiceIndex(pair.Value));
/// <summary>The level <paramref name="s"/> is at throughout, if any.</summary>
public static PhysicsPreset? Matching(SimulatorSettings s) => All.FirstOrDefault(preset => preset.Matches(s));
}
+61
View File
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
namespace StarterNG.Domain.Settings;
/// <summary>
/// The ray-traced reflections as the standard mode offers them: off, or on at one of four levels, a level being how
/// far the rays reach (gfx.raytracing.range). Only the Vulkan renderer on a card with ray queries draws them. No
/// level of detail turns them on or off: they cost far more than anything a level sets, so they are the player's
/// own choice.
/// </summary>
public static class RayTracing
{
public const string Key = "gfx.raytracing";
public const string RangeKey = "gfx.raytracing.range";
/// <summary>The levels, as the other parts of the picture name theirs, and the reach of each in metres.</summary>
public static readonly IReadOnlyList<(string NameKey, int Range)> Levels = new[]
{
("PresetLow", 250), ("PresetMedium", 500), ("PresetHigh", 1000), ("PresetVeryHigh", 2000)
};
/// <summary>Off.</summary>
public const int Off = -1;
/// <summary>
/// Where <paramref name="s"/> stands: <see cref="Off"/>, the index of its level, or null for a reach none of
/// them has.
/// </summary>
public static int? LevelOf(SimulatorSettings s) => LevelOf(SimulatorKeys.Named(Key).RawIn(s), SimulatorKeys.Named(RangeKey).RawIn(s));
/// <summary>The level of the two keys as the file writes them.</summary>
public static int? LevelOf(string enabled, string range)
{
if (!SimulatorKey.ParseToggle(enabled))
return Off;
double metres = SimulatorKeys.Named(RangeKey).ParseNumber(range);
for (int i = 0; i < Levels.Count; i++)
if (Math.Abs(Levels[i].Range - metres) < 0.5)
return i;
return null;
}
/// <summary>
/// The two keys at <paramref name="level"/>, in the file's words. Off leaves the reach as it is, for the next
/// time they are turned on.
/// </summary>
public static (string Enabled, string? Range) ValuesOf(int level) =>
level == Off
? (SimulatorKey.FormatToggle(false), null)
: (SimulatorKey.FormatToggle(true), Levels[level].Range.ToString(System.Globalization.CultureInfo.InvariantCulture));
public static void Apply(SimulatorSettings s, int level)
{
var (enabled, range) = ValuesOf(level);
s.Extra[Key] = enabled;
if (range is not null)
s.Extra[RangeKey] = range;
}
}
-132
View File
@@ -1,132 +0,0 @@
using System;
using System.Collections.Generic;
namespace StarterNG.Domain.Settings;
/// <summary>Why the simulator about to be started would pass a key over.</summary>
public enum IdleReason
{
None,
WindowsBuildOnly,
LegacyRendererOnly,
/// <summary>Read by the full OpenGL renderer alone.</summary>
ModernRendererOnly,
/// <summary>Read by the OpenGL renderers, which the experimental one is not.</summary>
OpenGlRenderersOnly,
NeedsNetworkServer,
/// <summary>The draw range is only stretched by the frame rate regulator, which is off.</summary>
NeedsFrameRateTarget,
/// <summary>fullscreenwindowed takes the monitor's own mode instead.</summary>
MonitorModeInstead,
VulkanOnly
}
/// <summary>What about the simulator to be started decides which keys it heeds.</summary>
/// <param name="WindowsBuild">The executable is a Windows build, under Wine or not.</param>
/// <param name="Renderer">The gfxrenderer word, as <see cref="SimulatorSettings.RenderEngines"/> has it.</param>
/// <param name="NetworkServer">eu07.ini starts a network.server.</param>
/// <param name="TargetFps">targetfps as eu07.ini sets it, or null where it does not.</param>
/// <param name="FpsAverage">fpsaverage, the older regulator's target; 0 for none.</param>
/// <param name="FullscreenWindowed">fullscreenwindowed is on.</param>
public sealed record SimulatorTarget(bool WindowsBuild, string Renderer, bool NetworkServer,
double? TargetFps = null, double FpsAverage = 0,
bool FullscreenWindowed = false);
/// <summary>The renderers a gfxrenderer word picks, as application.cpp tells them apart.</summary>
public enum RendererKind { Modern, Legacy, Experimental }
/// <summary>
/// Where an eu07.ini key takes effect, from the simulator's sources: a key it
/// reads but leaves alone on the platform, render path or setup at hand.
/// </summary>
public static class SettingReach
{
// The keyboard lights, LPT and PoKeys behind feedback live in Console.cpp,
// which only the Windows build compiles; the system console and ANGLE are
// Windows-only in application.cpp.
private static readonly HashSet<string> WindowsBuildOnly = new(StringComparer.OrdinalIgnoreCase)
{
"feedbackmode", "feedbackport", "showsystemconsole", "gfx.angleplatform"
};
// Read by openglrenderer.cpp alone; the modern path forces VBOs on.
private static readonly HashSet<string> LegacyRendererOnly = new(StringComparer.OrdinalIgnoreCase)
{
"smoothtraction", "gfx.shadows.cab.range", "usevbo"
};
// Read by opengl33renderer.cpp and the shaders it builds (glsl_common.cpp) alone.
private static readonly HashSet<string> ModernRendererOnly = new(StringComparer.OrdinalIgnoreCase)
{
"gfx.postfx.chromaticaberration.enabled", "gfx.postfx.motionblur.enabled",
"gfx.postfx.motionblur.shutter", "gfx.extraeffects", "gfx.envmap.enabled", "gfx.skippipeline",
"rendercab", "sleeperdistance"
};
// Read by both OpenGL renderers but not by the experimental one, which sets its
// own anisotropy, draws no smoke and has no frame rate regulator.
private static readonly HashSet<string> OpenGlRenderersOnly = new(StringComparer.OrdinalIgnoreCase)
{
"anisotropicfiltering", "multisampling", "dynamiclights", "gfx.smoke", "gfx.smoke.fidelity",
"gfx.reflections.framerate", "gfx.reflections.range_vehicles", "gfx.shadow.angle.min",
"scalespeculars", "gfx.drawrange.factor.max"
};
private static readonly HashSet<string> VulkanRendererOnly = new(StringComparer.OrdinalIgnoreCase)
{
"gfx.dlss.preset", "gfx.framegeneration", "gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.vulkan.device"
};
// application.cpp: fullscreenwindowed takes its size from the monitor and always
// goes full screen. "width, height" is how the settings screen names that row.
private static readonly HashSet<string> OverriddenByMonitorMode = new(StringComparer.OrdinalIgnoreCase)
{
"width, height", "fullscreen"
};
public static IdleReason Why(string key, SimulatorTarget target)
{
// The starter's own keys mean nothing to any simulator, and need not.
if (key.StartsWith("starter.", StringComparison.OrdinalIgnoreCase))
return IdleReason.None;
if (WindowsBuildOnly.Contains(key) && !target.WindowsBuild)
return IdleReason.WindowsBuildOnly;
if (OverriddenByMonitorMode.Contains(key) && target.FullscreenWindowed)
return IdleReason.MonitorModeInstead;
var renderer = KindOf(target.Renderer);
if (LegacyRendererOnly.Contains(key) && renderer != RendererKind.Legacy)
return IdleReason.LegacyRendererOnly;
if (ModernRendererOnly.Contains(key) && renderer != RendererKind.Modern)
return IdleReason.ModernRendererOnly;
if (OpenGlRenderersOnly.Contains(key) && renderer == RendererKind.Experimental)
return IdleReason.OpenGlRenderersOnly;
if (VulkanRendererOnly.Contains(key) && !IsVulkan(target.Renderer))
return IdleReason.VulkanOnly;
// on_focus_change pauses only a simulator that serves the network.
if (string.Equals(key, "inactivepause", StringComparison.OrdinalIgnoreCase) && !target.NetworkServer)
return IdleReason.NeedsNetworkServer;
if (string.Equals(key, "gfx.drawrange.factor.max", StringComparison.OrdinalIgnoreCase) &&
!DrawRangeRegulated(target))
return IdleReason.NeedsFrameRateTarget;
return IdleReason.None;
}
/// <summary>
/// Whether the renderer moves the draw range with the frame rate - the only use
/// of gfx.drawrange.factor.max: targetfps does it, as the older fpsaverage does.
/// </summary>
private static bool DrawRangeRegulated(SimulatorTarget target) =>
target.FpsAverage != 0 || (target.TargetFps ?? 0) != 0;
/// <summary>"full", its other names and the Vulkan renderer are the modern kind, "experimental" its own; every other word the legacy one.</summary>
public static RendererKind KindOf(string renderer) => renderer.ToLowerInvariant() switch
{
"full" or "default" or "opengl" or "gl46" or "vulkan" or "vulkan14" => RendererKind.Modern,
"experimental" => RendererKind.Experimental,
_ => RendererKind.Legacy
};
public static bool IsVulkan(string renderer) => renderer.ToLowerInvariant() is "vulkan" or "vulkan14";
}
+159 -41
View File
@@ -5,13 +5,14 @@ using System.Linq;
namespace StarterNG.Domain.Settings;
public enum SimulatorKeyKind { Toggle, Number, Text }
public enum SimulatorKeyKind { Toggle, Number, Text, Choice }
/// <summary>
/// An eu07.ini key the simulator reads that needs no logic of the starter's own:
/// a switch, a number or a word, shown as one row of the settings. The default
/// is the simulator's own, from Globals.h, used while the file does not carry
/// the key.
/// a switch, a number, a word or one of a few words, shown as one row of the settings.
/// The default is the simulator's own, from Globals.h, used while the file does not
/// carry the key - but for a key the starter <see cref="Writes"/>, where it is the
/// starter's own: the faster choice the simulator does not make by itself.
/// </summary>
public sealed record SimulatorKey(
string Key,
@@ -24,7 +25,9 @@ public sealed record SimulatorKey(
double Step = 1,
string Unit = "",
bool ZeroIsOff = false,
int Repeat = 1)
int Repeat = 1,
bool Writes = false,
IReadOnlyList<string>? Choices = null)
{
/// <summary>The label's translation key; the explanation's adds "Desc".</summary>
public string LabelKey => "Ini." + Key;
@@ -36,6 +39,42 @@ public sealed record SimulatorKey(
public static string FormatToggle(bool value) => value ? "yes" : "no";
/// <summary>The words of a level the simulator takes for 0 to 3 as well.</summary>
public static readonly IReadOnlyList<string> Levels = new[] { "no", "low", "medium", "high" };
/// <summary>
/// Where <paramref name="raw"/> stands among the <see cref="Choices"/>: its word, or the number the simulator
/// takes for a level (gfx.ssr 2 is medium); -1 for one it is not.
/// </summary>
public int ChoiceIndex(string raw)
{
if (Choices is null)
return -1;
string word = FirstToken(raw);
for (int i = 0; i < Choices.Count; i++)
if (string.Equals(Choices[i], word, StringComparison.OrdinalIgnoreCase))
return i;
// The other words the simulator takes for one of them (couplerphysics true, physics.derailment no).
string? alias = word.ToLowerInvariant() switch
{
"true" or "1" => "yes",
"no" => "off",
_ => null
};
if (alias is not null)
for (int i = 0; i < Choices.Count; i++)
if (string.Equals(Choices[i], alias, StringComparison.Ordinal))
return i;
if (ReferenceEquals(Choices, Levels) &&
int.TryParse(word, NumberStyles.Integer, CultureInfo.InvariantCulture, out int level) &&
level >= 0 && level < Choices.Count)
return level;
return -1;
}
/// <summary>The label's translation key of the word <paramref name="choice"/>.</summary>
public static string ChoiceLabelKey(string choice) => "Choice." + choice;
/// <summary>The key's value in <paramref name="s"/>, in the file's words: what is set, or else the default.</summary>
public string RawIn(SimulatorSettings s) => s.Extra.TryGetValue(Key, out string? raw) ? raw : Default;
@@ -63,14 +102,29 @@ public sealed record SimulatorKey(
public static class SimulatorKeys
{
/// <summary>
/// The keys a player sees in the standard mode. The rest are the developer tab's, which only the advanced
/// mode shows: a player in the standard mode has them at their defaults, the fast choice.
/// </summary>
public static readonly IReadOnlySet<string> Standard = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"ui.scale",
"couplerphysics", "physics.derailment", "physics.collisions", "physics.trackbuckling", "deer"
};
public const string General = "general";
public const string Graphics = "graphics";
public const string Sound = "sound";
public const string Physics = "physics";
public const string Advanced = "advanced";
private static SimulatorKey Toggle(string key, bool value, string category, string section) =>
new(key, SimulatorKeyKind.Toggle, SimulatorKey.FormatToggle(value), category, section);
public const string RendererSection = "IniSectionRenderer";
public const string QualitySection = "IniSectionQuality";
public const string PerformanceSection = "IniSectionPerformance";
public const string LogsSection = "IniSectionLogs";
private static SimulatorKey Toggle(string key, bool value, string category, string section, bool writes = false) =>
new(key, SimulatorKeyKind.Toggle, SimulatorKey.FormatToggle(value), category, section, Writes: writes);
private static SimulatorKey Number(string key, double value, string category, string section,
double min, double max, double step, string unit = "",
@@ -81,48 +135,112 @@ public static class SimulatorKeys
private static SimulatorKey Text(string key, string category, string section) =>
new(key, SimulatorKeyKind.Text, string.Empty, category, section);
private static SimulatorKey Choice(string key, string value, string section, IReadOnlyList<string>? choices = null,
string category = Advanced) =>
new(key, SimulatorKeyKind.Choice, value, category, section, Choices: choices ?? SimulatorKey.Levels);
public const string RealismSection = "RealismSection";
public static SimulatorKey Named(string key) => All.First(k => k.Key == key);
public static IReadOnlyList<SimulatorKey> All { get; } = new[]
{
Number("ui.scale", 1, General, "IniSectionInterface", 0.5, 3, 0.05, "×"),
Number("ui.fontsize", 13, General, "IniSectionInterface", 8, 32, 1, " px"),
Number("ui.bg.opacity", 0.94, General, "IniSectionInterface", 0.1, 1, 0.05),
Toggle("gui.defaultwindows", true, General, "IniSectionInterface"),
Toggle("gui.trainingdefault", false, General, "IniSectionInterface"),
Toggle("gui.showtranscripts", true, General, "IniSectionInterface"),
Toggle("loadinglog", false, General, "IniSectionInterface"),
Toggle("captureonstart", true, General, "IniSectionInterface"),
Toggle("mousecontrol", true, General, "IniSectionInterface"),
Text("fullscreenmonitor", General, "IniSectionInterface"),
Text("screenshotsdir", General, "IniSectionInterface"),
Number("ui.fontsize", 13, Advanced, "IniSectionInterface", 8, 32, 1, " px"),
Number("ui.bg.opacity", 0.94, Advanced, "IniSectionInterface", 0.1, 1, 0.05),
Toggle("gui.defaultwindows", true, Advanced, "IniSectionInterface"),
Toggle("gui.trainingdefault", false, Advanced, "IniSectionInterface"),
Toggle("gui.showtranscripts", true, Advanced, "IniSectionInterface"),
Toggle("captureonstart", true, Advanced, "IniSectionInterface"),
Toggle("mousecontrol", true, Advanced, "IniSectionInterface"),
Text("screenshotsdir", Advanced, "IniSectionInterface"),
Number("basedrawrange", 2500, Graphics, "IniSectionRanges", 500, 10000, 250, " m"),
Number("heightbase", 1, Graphics, "IniSectionRanges", 0.5, 3, 0.05, "×"),
Number("targetfps", 0, Graphics, "IniSectionRanges", 0, 240, 5, " FPS", zeroIsOff: true),
Number("sleeperdistance", 250, Graphics, "IniSectionRanges", 0, 5000, 50, " m", zeroIsOff: true),
Number("gfx.reflections.range_instances", 750, Graphics, "IniSectionRanges", 0, 3000, 50, " m"),
Number("gfx.reflections.range_vehicles", 250, Graphics, "IniSectionRanges", 0, 2000, 50, " m"),
Toggle("gfx.textures.streaming", false, Graphics, "IniSectionRanges"),
Number("gfx.textures.releasedistance", 0, Graphics, "IniSectionRanges", 0, 10, 0.5, "×", zeroIsOff: true),
Toggle("skyenabled", true, Graphics, "IniSectionRanges"),
Toggle("rendercab", true, Graphics, "IniSectionRanges"),
Number("gfx.postfx.motionblur.shutter", 0.01, Graphics, "IniSectionRanges", 0.001, 0.1, 0.001, " s"),
Number("python.fpslimit", 100, Graphics, "IniSectionRanges", 5, 200, 5, " FPS"),
Toggle("python.vsync", true, Graphics, "IniSectionRanges"),
Toggle("python.displaywindows", false, Graphics, "IniSectionRanges"),
Toggle("newaircouplers", true, Graphics, "IniSectionRanges"),
Toggle("smoothtraction", true, Graphics, "IniSectionRanges"),
// The renderer: what only Vulkan reads, and the shaders of either.
Text("gfx.vulkan.device", Advanced, RendererSection),
Toggle("gfx.vulkan.renderthread", true, Advanced, RendererSection),
Number("gfx.threads", 0, Advanced, RendererSection, 0, 64, 1, zeroIsOff: true),
Toggle("gfx.vulkan.asyncresources", true, Advanced, RendererSection),
Toggle("gfx.vulkan.parallelpasses", true, Advanced, RendererSection),
Toggle("gfx.vulkan.parallelmodels", true, Advanced, RendererSection),
Toggle("gfx.vulkan.asynccompute", false, Advanced, RendererSection),
Number("gfx.vulkan.framesinflight", 2, Advanced, RendererSection, 2, 3, 1),
Toggle("gfx.shaders.binaries", true, Advanced, RendererSection),
Number("sound.maxsources", 30, Sound, "IniSectionAudio", 8, 256, 8),
Toggle("sound.asyncload", false, Sound, "IniSectionAudio"),
// The parts of the picture of the OpenGL 4.6 and Vulkan renderers the levels set, one by one.
Choice("gfx.lights.shadows", "medium", QualitySection),
Choice("gfx.contactshadows", "no", QualitySection),
Toggle("gfx.shadow.sdsm", false, Advanced, QualitySection),
Choice("gfx.ssr", "medium", QualitySection),
Toggle("gfx.raytracing", false, Advanced, QualitySection),
Number("gfx.raytracing.range", 500, Advanced, QualitySection, 10, 5000, 10, " m"),
Choice("gfx.cabprobe", "medium", QualitySection),
Toggle("gfx.water.realistic", false, Advanced, QualitySection),
Choice("gfx.postfx.ao", "gtao", QualitySection, new[] { "no", "ssao", "gtao" }),
Choice("gfx.fog.quality", "medium", QualitySection, new[] { "low", "medium", "high", "ultra" }),
Choice("gfx.clouds", "medium", QualitySection, new[] { "no", "low", "medium", "high", "ultra" }),
Toggle("gfx.postfx.bloom", true, Advanced, QualitySection),
Toggle("gfx.grass", true, Advanced, QualitySection),
Number("gfx.grass.distance", 60, Advanced, QualitySection, 5, 500, 5, " m"),
Number("gfx.grass.fadedistance", 70, Advanced, QualitySection, 5, 600, 5, " m"),
Number("gfx.grass.density", 1, Advanced, QualitySection, 0, 4, 0.25, "×"),
Number("gfx.precipitation.particles", 65536, Advanced, QualitySection, 0, 262144, 4096),
Choice("gfx.dlss.preset", "default", QualitySection, new[] { "default", "j", "k", "l", "m" }),
Choice("gfx.framegeneration", "off", QualitySection, new[] { "off", "x2", "x3", "x4" }),
Choice("gfx.reflex", "off", QualitySection, new[] { "off", "on", "boost" }),
Toggle("loadtraction", true, Physics, "IniSectionPhysics"),
Toggle("rollfix", true, Physics, "IniSectionPhysics"),
Number("shakefactor", 1, Physics, "IniSectionPhysics", 0, 3, 0.1, "×", repeat: 3),
Toggle("map.manualswitchcontrol", false, Physics, "IniSectionPhysics"),
Number("map.highlightdistance", 3000, Physics, "IniSectionPhysics", 0, 10000, 250, " m", zeroIsOff: true),
Number("basedrawrange", 2500, Advanced, "IniSectionRanges", 500, 10000, 250, " m"),
Number("heightbase", 1, Advanced, "IniSectionRanges", 0.5, 3, 0.05, "×"),
Number("targetfps", 0, Advanced, "IniSectionRanges", 0, 240, 5, " FPS", zeroIsOff: true),
Number("sleeperdistance", 250, Advanced, "IniSectionRanges", 0, 1000, 50, " m", zeroIsOff: true),
Number("gfx.reflections.range_instances", 750, Advanced, "IniSectionRanges", 0, 3000, 50, " m"),
Number("gfx.reflections.range_vehicles", 250, Advanced, "IniSectionRanges", 0, 2000, 50, " m"),
Toggle("rendercab", true, Advanced, "IniSectionRanges"),
Number("gfx.postfx.motionblur.shutter", 0.01, Advanced, "IniSectionRanges", 0.001, 0.1, 0.001, " s"),
Number("python.fpslimit", 100, Advanced, "IniSectionRanges", 5, 200, 5, " FPS"),
Toggle("python.vsync", true, Advanced, "IniSectionRanges"),
Toggle("python.displaywindows", false, Advanced, "IniSectionRanges"),
Toggle("newaircouplers", true, Advanced, "IniSectionRanges"),
Toggle("showsystemconsole", false, Advanced, "IniSectionConsole"),
// What makes the simulator faster at no cost to the picture. Where the simulator's own default is the
// slower one, the starter writes its own: the standard mode keeps them all on.
Toggle("gfx.gpucull", true, Advanced, PerformanceSection, writes: true),
Toggle("gfx.gpucull.occlusion", true, Advanced, PerformanceSection),
Toggle("gfx.depthprepass", true, Advanced, PerformanceSection),
Toggle("gfx.textures.streaming", true, Advanced, PerformanceSection, writes: true),
Number("gfx.textures.releasedistance", 0, Advanced, PerformanceSection, 0, 10, 0.5, "×", zeroIsOff: true),
Toggle("sound.asyncload", true, Advanced, PerformanceSection, writes: true),
Toggle("physics.sleepheld", true, Advanced, PerformanceSection, writes: true),
Toggle("physics.roadlod", true, Advanced, PerformanceSection, writes: true),
Toggle("performance.multithreading", true, Advanced, PerformanceSection),
Toggle("file.binary.terrain", true, Advanced, PerformanceSection),
Toggle("gfx.smoke.gpu", true, Advanced, PerformanceSection),
Toggle("gfx.weather.occlusion", true, Advanced, PerformanceSection),
Toggle("gfx.clouds.interleave", true, Advanced, PerformanceSection),
Toggle("screens.gpupost", true, Advanced, PerformanceSection),
Number("screens.cabframes", 4, Advanced, PerformanceSection, 1, 60, 1),
Number("screens.externalframes", 30, Advanced, PerformanceSection, 1, 120, 1),
Number("sound.maxsources", 30, Advanced, "IniSectionAudio", 8, 256, 8),
// How true to life the driving is: the physics/ models of utilities/Globals.cpp, from the legacy ones on.
Choice("couplerphysics", "no", RealismSection, new[] { "no", "yes", "all" }, Physics),
Choice("physics.derailment", "monitor", RealismSection, new[] { "off", "monitor", "new", "old" }, Physics),
Choice("physics.collisions", "new", RealismSection, new[] { "old", "new", "monitor" }, Physics),
Choice("physics.trackbuckling", "scenery", RealismSection, new[] { "off", "scenery", "auto" }, Physics),
Toggle("deer", false, Physics, RealismSection),
Toggle("physics.derailment.trustlimits", true, Advanced, "IniSectionPhysics"),
Toggle("controlcoupling.enginecheck", true, Advanced, "IniSectionPhysics"),
Toggle("ai.brakesetting.cw1", true, Advanced, "IniSectionPhysics"),
Toggle("loadtraction", true, Advanced, "IniSectionPhysics"),
Toggle("rollfix", true, Advanced, "IniSectionPhysics"),
Number("shakefactor", 1, Advanced, "IniSectionPhysics", 0, 3, 0.1, "×", repeat: 3),
Toggle("map.manualswitchcontrol", false, Advanced, "IniSectionPhysics"),
Number("map.highlightdistance", 3000, Advanced, "IniSectionPhysics", 0, 10000, 250, " m", zeroIsOff: true),
Toggle("loadinglog", false, Advanced, LogsSection),
Toggle("showsystemconsole", false, Advanced, LogsSection),
Number("debug.perflog", 0, Advanced, LogsSection, 0, 60, 1, " s", zeroIsOff: true),
Toggle("crashdump.full", false, Advanced, LogsSection),
Toggle("physics.trackcheck", false, Advanced, LogsSection),
};
}
+83 -73
View File
@@ -8,11 +8,13 @@ public enum ConsistReadyOverride { Scenery = 0, AlwaysCold = 1, AlwaysReady = 2
public enum ExeProblem { None, NotFound, NotExecutable, WrongPlatform, NotAProgram }
// gfxrenderer: the OpenGL renderer ("full", read by every build) or the Vulkan 1.4 one.
public enum GraphicsBackend { OpenGL = 0, Vulkan = 1 }
// gfx.antialiasing (and the older multisampling, 0 off, then 2, 4 and 8 samples). Dlss and Dlaa are the Vulkan
// renderer's only, on an NVIDIA RTX card with a build that has DLSS; the simulator falls back to TAA elsewhere.
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8, Msaa16, Taa, Dlss, Dlaa }
// gfx.antialiasing. Dlss and Dlaa are the Vulkan renderer's only; the simulator falls back to TAA elsewhere.
public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8, Taa, Dlss, Dlaa }
// gfxrenderer: the Vulkan 1.4 renderer, which the simulator leaves for the OpenGL one where it cannot run, or the
// OpenGL 4.6 one ("default").
public enum GraphicsBackend { Vulkan, OpenGL }
public sealed class SimulatorSettings
{
@@ -34,7 +36,8 @@ public sealed class SimulatorSettings
public bool InvertMouseHorizontal;
public bool InvertMouseVertical;
public bool IgnoreGamepad;
/// <summary>input.gamepad no: the recommended setting, so the starter's default, though the simulator's own is yes.</summary>
public bool IgnoreGamepad = true;
public int FeedbackMode = 1;
public int FeedbackPort = 888;
public bool UartEnabled;
@@ -54,19 +57,24 @@ public sealed class SimulatorSettings
public bool VirtualShunting = true;
public bool LogMissingVehicleFiles;
public int RenderEngine;
public GraphicsBackend Backend => RenderEngine == VulkanEngine ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGL;
public string VulkanDevice = "";
/// <summary>The renderer: Vulkan unless the advanced mode chose OpenGL.</summary>
public GraphicsBackend Backend = GraphicsBackend.Vulkan;
/// <summary>
/// The file's gfxrenderer word where it is none the starter knows - "null" of the test runs, or one of a
/// newer simulator: written back as it is until another renderer is chosen.
/// </summary>
public string? RendererWord;
public int Width = 1280;
public int Height = 720;
/// <summary>gfx.buffer.percent, in percent: the part of the window the picture is drawn at, then stretched to it.</summary>
public int BufferScalePercent = 100;
public int MaxTextureSize = 4096;
public int MaxCabTextureSize = 4096;
public double TextureFiltering = 8;
public AntiAliasingMode AntiAliasing = AntiAliasingMode.Msaa4;
public string DlssPreset = "default";
public int FrameGeneration = 1;
public int Reflex;
public int DynamicLights = 7;
public double DrawRangeFactor = 3.0;
public bool VSync;
@@ -77,41 +85,6 @@ public sealed class SimulatorSettings
public bool ExtraEffects = true;
public bool EnvMap = true;
public bool RenderShadows = true;
public bool ShadowSdsm;
public int LightShadows = 2;
public int ContactShadows;
public bool LightsClustered = true;
public int AmbientOcclusion = 2;
public int AoSlices = 3;
public int AoSteps = 4;
public bool AoLighting = true;
public int CabProbe = 2;
public int CabProbeInterval = 4;
public double CabProbeBounce = 1.0;
public bool CabProbeReflections = true;
// Read from eu07.ini only, for the dependencies shown: the starter offers no switch for them.
public bool CabLampLight { get; internal set; } = true;
public bool DepthPrepassScene { get; internal set; }
public int Ssr = 2;
public bool RayTracing;
public int RayTracingRange = 500;
public bool VolumetricFog = true;
public int FogQuality = 2;
public int Clouds = 2;
public bool CloudShadows = true;
public bool Grass = true;
public int GrassDistance = 60;
public double GrassDensity = 1.0;
public int PrecipitationParticles = 65536;
public bool Bloom = true;
public bool AutoExposure = true;
// Only the older simulators read these.
public bool UseVbo = true;
public bool RenderAngleVulkan;
public bool UseGLES;
public int CabShadowsRange;
/// <summary>Updates of the reflections a second; the simulator's own is one in five minutes.</summary>
public double ReflectionsFramerate = 1 / 300.0;
@@ -119,7 +92,7 @@ public sealed class SimulatorSettings
/// <summary>The third number of shadowtune; the second and fourth go unread.</summary>
public int ShadowProjectionRange = 250;
public int ShadowRankCutoff = 3;
public int ReflectionsFidelity;
public int ReflectionsFidelity = 2;
public int FieldOfView = 45;
public bool PythonScreens = true;
public bool PythonThreadedUpload = true;
@@ -127,6 +100,8 @@ public sealed class SimulatorSettings
public double FpsLimit = 30;
public double ShadowAngleLimit = 0.2;
public bool FullscreenWindowed;
/// <summary>fullscreenmonitor: the monitor a full screen opens on, as "name:x,y"; empty for the primary one.</summary>
public string FullscreenMonitor = "";
public int SplineFidelity = 1;
public bool FullPhysics = true;
@@ -180,6 +155,28 @@ public sealed class SimulatorSettings
public bool LargeThumbnails;
public bool AutoExpandSceneryTree;
/// <summary>
/// Every setting on show, the ones a player can break the game with too. Off, the standard
/// mode keeps the settings, the consists and the scenario to what a driver needs.
/// </summary>
public bool AdvancedSettings;
/// <summary>
/// The settings were brought into the standard mode once, on the first start of this
/// starter: the advanced ones to their defaults, the sliders into their ranges.
/// </summary>
public bool MovedToStandard;
/// <summary>
/// starter.settings.revision: the layout of the settings this file was last brought to. Below
/// <see cref="CurrentRevision"/>, a player in the standard mode is moved to it once: the renderer and what
/// only the developer tab shows at the starter's own values, the fast ones.
/// </summary>
public int Revision;
/// <summary>The layout of this starter: the standard mode on Vulkan, the rest in the developer tab.</summary>
public const int CurrentRevision = 2;
/// <summary>Warn at start when the processor cannot run the official simulator builds.</summary>
public bool CpuNotice = true;
@@ -212,26 +209,20 @@ public sealed class SimulatorSettings
}
/// <summary>
/// The gfxrenderer words the simulator tells apart (application.cpp): every
/// other word - the "simpleshader" and "off" older starters offered among them -
/// gets the legacy renderer. A simulator with the OpenGL 4.6 and Vulkan 1.4
/// renderers runs everything but "vulkan" as the first, and "vulkan" too when
/// it was built without it or the card cannot run it.
/// The gfxrenderer words the simulator knows (utilities/Globals.cpp): the Vulkan ones, the OpenGL ones and
/// those of the renderers it no longer has, which it reads as OpenGL. Any other word is kept as
/// <see cref="RendererWord"/>.
/// </summary>
public static readonly string[] RenderEngines = { "full", "legacy", "simple", "experimental", "vulkan" };
public static bool KnownRendererWord(string? word) =>
word?.Trim().ToLowerInvariant() is "vulkan" or "vulkan14" or "default" or "full" or "opengl" or "gl46"
or "legacy" or "simple" or "simpleshader" or "off" or "experimental";
/// <summary>Where "vulkan" stands among <see cref="RenderEngines"/>.</summary>
public const int VulkanEngine = 4;
/// <summary>The renderer <paramref name="word"/> picks, as the simulator reads it.</summary>
public static GraphicsBackend BackendOf(string word) =>
word.Trim().ToLowerInvariant() is "vulkan" or "vulkan14" ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGL;
/// <summary>Where <paramref name="word"/> stands among <see cref="RenderEngines"/>, as the simulator reads it.</summary>
public static int RenderEngineOf(string word) => word.Trim().ToLowerInvariant() switch
{
"full" or "default" or "opengl" or "gl46" => 0,
"simple" => 2,
"experimental" => 3,
"vulkan" or "vulkan14" => 4,
_ => 1
};
/// <summary>The gfxrenderer word of <paramref name="backend"/>.</summary>
public static string WordOf(GraphicsBackend backend) => backend == GraphicsBackend.Vulkan ? "vulkan" : "default";
/// <summary>
/// The least shadow range the simulator keeps for a map size: a map above
@@ -240,23 +231,42 @@ public sealed class SimulatorSettings
public static int ShadowRangeFloor(int mapSize) => mapSize <= 2048 ? 75 : 75 * mapSize / 2048;
/// <summary>
/// How far shadows actually reach. The full renderer's cascades stretch with a
/// map above 2048 px (opengl33renderer.cpp), on top of the floor; the legacy
/// one draws a single map out to the range itself.
/// How far shadows actually reach: the cascades stretch with a map above 2048 px
/// (rendering/common/shadowfit.cpp), on top of the floor.
/// </summary>
public static int ShadowReach(int range, int mapSize, bool legacyRenderer)
public static int ShadowReach(int range, int mapSize)
{
int reach = Math.Max(range, ShadowRangeFloor(mapSize));
return legacyRenderer || mapSize <= 2048 ? reach : reach * (mapSize / 2048);
return mapSize <= 2048 ? reach : reach * (mapSize / 2048);
}
/// <summary>
/// The file's own first mousescale number. The slider takes whole steps: this
/// stands for as long as <see cref="CursorSensitivity"/> is the step nearest it.
/// The first mousescale number of each level of <see cref="CursorSensitivity"/>, 1 to 4, as
/// the old starter wrote them (MaSzyna-EU07/Starter, src/uSettings.pas): low, standard, high
/// and very high, negative with <see cref="InvertMouseHorizontal"/>. Whatever else the file
/// has there goes on the next save.
/// </summary>
internal double MouseScaleXMagnitude { get; set; } = 2;
internal static readonly double[] MouseScales = { 1.0, 1.5, 2.3, 3.2 };
internal double MouseScaleYMagnitude { get; set; } = 0.2;
/// <summary>The first mousescale number <paramref name="level"/> stands for.</summary>
internal static double MouseScaleOf(int level) => MouseScales[Math.Clamp(level, 1, MouseScales.Length) - 1];
/// <summary>
/// The level the old starter showed for a first mousescale number: low below 1.3, high
/// above 1.9, very high above 2.7 and standard between, whatever its sign.
/// </summary>
internal static int MouseLevelOf(double scale)
{
double size = Math.Abs(scale);
return size > 2.7 ? 4 : size > 1.9 ? 3 : size < 1.3 ? 1 : 2;
}
/// <summary>
/// The second mousescale number, as the old starter always wrote it: 0.5, or
/// -0.5 with <see cref="InvertMouseVertical"/>. Whatever else the file has there
/// goes on the next save.
/// </summary>
internal const double MouseScaleY = 0.5;
/// <summary>The numbers of shadowtune the simulator skips, kept as the file has them.</summary>
internal string[] ShadowTuneUnused { get; set; } = { "250", "300" };
+31
View File
@@ -0,0 +1,31 @@
namespace StarterNG.Domain.Settings;
/// <summary>
/// What the sliders offer, in either mode: the old starter's ranges (MaSzyna-EU07/Starter,
/// src/uMain.dfm), the tops of which <see cref="GraphicsRules"/> holds to. A value the file
/// has below these is shown as it is, so opening and saving the settings never moves it.
/// </summary>
public static class SliderRanges
{
/// <summary>maxtexturesize: its list began at 512.</summary>
public const int MinTextureSize = 512;
/// <summary>The map size of shadowtune: its list began at 1024.</summary>
public const int MinShadowMap = 1024;
/// <summary>dynamiclights: 1 to 7.</summary>
public const int MinDynamicLights = 1;
/// <summary>
/// gfx.reflections.framerate, in updates a second: from the simulator's own once in five minutes, which the
/// levels below Very high keep, up to every frame.
/// </summary>
public static readonly double[] ReflectionUpdates = { 1 / 300.0, 1 / 60.0, 0.2, 1, 3, 10, 25, 60 };
/// <summary>gfx.drawrange.factor.max: normal, high and very high.</summary>
public static readonly double[] DrawRangeFactors = { 1, 2, 3 };
/// <summary>fpslimit: none, or up to 240, where the fastest usual monitors run.</summary>
public static readonly double[] FrameRateLimits =
{ 0, 20, 25, 30, 40, 45, 50, 60, 72, 75, 90, 100, 120, 144, 165, 180, 200, 240 };
}
+44 -16
View File
@@ -199,23 +199,8 @@ public sealed class TexRandomizer
VehicleTexture? current)
{
var result = new List<VehicleTexture>();
foreach (var t in _db.Textures)
foreach (var t in ByMini(minis))
{
if (t.Wreck) continue;
if (WithoutArchival && t.ResolvedArchived) continue;
if (_db.IsSetFollower(t)) continue;
string candidateMini = t.ResolvedClass;
if (string.IsNullOrEmpty(candidateMini))
candidateMini = _db.ResolveMiniName(t) ?? "";
if (string.IsNullOrEmpty(candidateMini)) continue;
bool miniOk = minis.Any(m =>
string.Equals(m, candidateMini, StringComparison.OrdinalIgnoreCase) ||
string.Equals(m, t.TextureMini, StringComparison.OrdinalIgnoreCase) ||
string.Equals(m, t.MiniRef, StringComparison.OrdinalIgnoreCase));
if (!miniOk) continue;
if (!string.IsNullOrEmpty(owner) &&
!string.Equals(owner, t.Meta?.Operator, StringComparison.OrdinalIgnoreCase))
continue;
@@ -236,6 +221,49 @@ public sealed class TexRandomizer
return result;
}
// The textures that can be drawn, by every mini name they answer to, in the catalogue's
// order. Made once: a scenery's worth of consists looks them up hundreds of times.
private Dictionary<string, List<(int Order, VehicleTexture Texture)>>? _byMini;
/// <summary>The textures that can be drawn under any of <paramref name="minis"/>, each once, in the catalogue's order.</summary>
private IEnumerable<VehicleTexture> ByMini(IReadOnlyList<string> minis)
{
_byMini ??= IndexByMini();
var found = new List<(int Order, VehicleTexture Texture)>();
foreach (string mini in minis)
if (!string.IsNullOrEmpty(mini) && _byMini.TryGetValue(mini, out var textures))
found.AddRange(textures);
return found.Distinct().OrderBy(entry => entry.Order).Select(entry => entry.Texture);
}
private Dictionary<string, List<(int Order, VehicleTexture Texture)>> IndexByMini()
{
var index = new Dictionary<string, List<(int, VehicleTexture)>>(StringComparer.OrdinalIgnoreCase);
int order = 0;
foreach (var t in _db.Textures)
{
order++;
if (t.Wreck) continue;
if (WithoutArchival && t.ResolvedArchived) continue;
if (_db.IsSetFollower(t)) continue;
string candidateMini = t.ResolvedClass;
if (string.IsNullOrEmpty(candidateMini))
candidateMini = _db.ResolveMiniName(t) ?? "";
if (string.IsNullOrEmpty(candidateMini)) continue;
foreach (string? name in new[] { candidateMini, t.TextureMini, t.MiniRef }
.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (string.IsNullOrEmpty(name)) continue;
if (!index.TryGetValue(name, out var list))
index[name] = list = new List<(int, VehicleTexture)>();
list.Add((order, t));
}
}
return index;
}
public static int? ParseRevisionYear(string? revision)
{
if (string.IsNullOrWhiteSpace(revision)) return null;
+27 -1
View File
@@ -8,6 +8,7 @@ using StarterNG.Classes;
using StarterNG.Domain.Sceneries;
using StarterNG.Domain.Vehicles;
using StarterNG.Application;
using StarterNG.Domain.Settings;
namespace StarterNG.Domain;
@@ -30,10 +31,35 @@ public static class TrainsetDisplay
!string.IsNullOrEmpty(trainset.Description) &&
trainset.Description.TrimStart().StartsWith("-", StringComparison.Ordinal);
/// <summary>Whether a list of the scenery's consists shows it, under the two filters those lists have.</summary>
/// <summary>Whether a list of the scenery's consists shows it, under the filters those lists have.</summary>
public static bool ListedIn(Trainset trainset, bool showAi, bool drivableOnly, Trainset? current) =>
(showAi || !IsAi(trainset)) && (!drivableOnly || ListedAsDrivable(trainset, current));
/// <summary>
/// Whether a list of the scenery's consists shows it: in the advanced mode under the filters
/// the settings hold; in the standard mode, which has no filters, every consist with vehicles
/// on it, and one emptied here, so it can be filled again or saved.
/// </summary>
public static bool ListedIn(Trainset trainset, SimulatorSettings settings, Trainset? current) =>
settings.AdvancedSettings
? ListedIn(trainset, settings.ShowAiVehicles, settings.DrivableOnly, current)
: !IsEmpty(trainset) || SceneryTrainsetText.IsModified(trainset);
/// <summary>
/// Whether the simulator may start with the player in it: in the standard mode not in one
/// the simulator drives itself nor in a decoration, which the scenario keeps as they are.
/// </summary>
public static bool StartableIn(Trainset trainset, SimulatorSettings settings) =>
settings.AdvancedSettings || (!IsAi(trainset) && !trainset.Decor);
/// <summary>
/// Whether the crew of the consist being edited may be changed: in the standard mode
/// only in one the player may start in - the simulator's own consists and the
/// decorations keep the crew the scenario gave them.
/// </summary>
public static bool CrewEditableIn(Trainset? trainset, SimulatorSettings settings) =>
trainset is null || StartableIn(trainset, settings);
/// <summary>The consist's row in those lists: what it is made of, or the track of one with nothing on it.</summary>
public static string ListLabel(Trainset trainset) =>
CompositionText(trainset) ?? string.Format(App.Loc["EmptyTrainset"], trainset.Track ?? "");
@@ -56,6 +56,34 @@ public static class LegacyText
private static readonly byte[] Utf8Bom = { 0xEF, 0xBB, 0xBF };
/// <summary>
/// <paramref name="text"/> as the characters that, written in code page 1250 with the rest
/// of the file, give its UTF-8 bytes: for a word the simulator compares with a UTF-8 one
/// byte by byte, as fullscreenmonitor with GLFW's name of the monitor. ASCII stays as it is.
/// </summary>
public static string Utf8As1250(string text) =>
IsAscii(text) ? text : CodePage1250.GetString(Encoding.UTF8.GetBytes(text));
/// <summary>
/// The other way: what a word of a code page 1250 file says when its bytes are UTF-8.
/// One whose bytes are not UTF-8 was written in the code page itself and stays as read.
/// </summary>
public static string Utf8From1250(string text)
{
if (IsAscii(text))
return text;
byte[] bytes = CodePage1250.GetBytes(text);
return Utf8.IsValid(bytes) && CodePage1250.GetString(bytes) == text ? Encoding.UTF8.GetString(bytes) : text;
}
private static bool IsAscii(string text)
{
foreach (char c in text)
if (c > 0x7F)
return false;
return true;
}
private static Encoding Resolve()
{
try
-188
View File
@@ -1,188 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>A screen, and the fastest it refreshes.</summary>
/// <param name="Name">The connector on Linux (eDP-1, HDMI-A-1); empty for the primary screen on Windows.</param>
public sealed record Display(string Name, int RefreshRate);
/// <summary>
/// The screens attached, for a frame rate limit to match: on Linux from the EDID
/// each connected connector of /sys/class/drm passes on - the most the panel can
/// do, which the desktop may not be using - and on Windows the primary screen's
/// current mode.
/// </summary>
public sealed class Displays
{
private const string DrmClass = "/sys/class/drm";
private static readonly Regex Connector = new(@"^card\d+-(.+)$", RegexOptions.CultureInvariant);
private readonly IFileSystem _files;
private readonly IEnvironment _environment;
public Displays(IFileSystem files, IEnvironment environment)
{
_files = files;
_environment = environment;
}
/// <summary>Every screen whose refresh rate could be read; empty where none could.</summary>
public IReadOnlyList<Display> List()
{
try
{
if (_environment.IsLinux)
return FromDrm();
if (_environment.IsWindows && OperatingSystem.IsWindows())
return PrimaryOnWindows() is { } rate ? new[] { new Display(string.Empty, rate) } : Array.Empty<Display>();
}
catch (Exception)
{
// A screen we cannot read leaves the limit to the player, as before.
}
return Array.Empty<Display>();
}
private IReadOnlyList<Display> FromDrm()
{
var displays = new List<Display>();
foreach (string directory in _files.GetDirectories(DrmClass))
{
var match = Connector.Match(Path.GetFileName(directory));
if (!match.Success || match.Groups[1].Value.StartsWith("Writeback", StringComparison.Ordinal))
continue;
try
{
string status = Path.Combine(directory, "status");
if (!_files.FileExists(status) || _files.ReadAllText(status).Trim() != "connected")
continue;
int rate = Edid.HighestRefreshRate(_files.ReadAllBytes(Path.Combine(directory, "edid")));
if (rate > 0)
displays.Add(new Display(match.Groups[1].Value, rate));
}
catch (Exception)
{
// One connector we cannot read says nothing of the others.
}
}
return displays;
}
// DEVMODEW: dmSize at 68, dmDisplayFrequency at 184, 220 bytes with no driver data.
private const int DevModeSize = 220;
private const int DevModeSizeOffset = 68;
private const int DisplayFrequencyOffset = 184;
private const int CurrentSettings = -1;
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int EnumDisplaySettingsW(IntPtr deviceName, int modeNum, IntPtr devMode);
private static int? PrimaryOnWindows()
{
IntPtr mode = Marshal.AllocHGlobal(DevModeSize);
try
{
for (int i = 0; i < DevModeSize; i++)
Marshal.WriteByte(mode, i, 0);
Marshal.WriteInt16(mode, DevModeSizeOffset, DevModeSize);
if (EnumDisplaySettingsW(IntPtr.Zero, CurrentSettings, mode) == 0)
return null;
int rate = Marshal.ReadInt32(mode, DisplayFrequencyOffset);
// 0 and 1 stand for the hardware's default rate.
return rate > 1 ? rate : null;
}
finally
{
Marshal.FreeHGlobal(mode);
}
}
}
/// <summary>The timings an EDID lists, as far as a refresh rate goes.</summary>
public static class Edid
{
/// <summary>The fastest refresh rate among the detailed timings, rounded; 0 for none.</summary>
public static int HighestRefreshRate(byte[] edid)
{
if (edid.Length < 128)
return 0;
// The base block's four descriptors.
double best = 0;
for (int at = 54; at + 18 <= 126; at += 18)
best = Math.Max(best, DetailedTiming(edid, at));
for (int block = 128; block + 128 <= edid.Length; block += 128)
{
switch (edid[block])
{
// CTA-861: detailed timings from the offset in its third byte on.
case 0x02 when edid[block + 2] >= 4:
for (int at = block + edid[block + 2]; at + 18 <= block + 127; at += 18)
best = Math.Max(best, DetailedTiming(edid, at));
break;
// DisplayID, where a panel faster than 60 Hz often keeps its only fast mode.
case 0x70:
best = Math.Max(best, DisplayId(edid, block));
break;
}
}
return (int)Math.Round(best);
}
// An 18-byte detailed timing; a pixel clock of zero marks some other descriptor.
private static double DetailedTiming(byte[] e, int at)
{
int clock = e[at] | e[at + 1] << 8;
if (clock == 0)
return 0;
int hActive = e[at + 2] | (e[at + 4] & 0xF0) << 4, hBlank = e[at + 3] | (e[at + 4] & 0x0F) << 8;
int vActive = e[at + 5] | (e[at + 7] & 0xF0) << 4, vBlank = e[at + 6] | (e[at + 7] & 0x0F) << 8;
return Rate(clock * 10_000.0, hActive + hBlank, vActive + vBlank);
}
// Data blocks from the sixth byte on; type I timings (DisplayID 1.3) count the
// pixel clock in 10 kHz, type VII (2.0) in kHz, and both store each size less one.
private static double DisplayId(byte[] e, int block)
{
double best = 0;
int end = Math.Min(block + 5 + e[block + 2], block + 127);
for (int at = block + 5; at + 3 <= end;)
{
int tag = e[at], length = e[at + 2];
if (tag == 0 && length == 0)
break;
int payload = at + 3;
if (tag is 0x03 or 0x22)
{
for (int t = payload; t + 20 <= Math.Min(payload + length, end); t += 20)
{
double clock = (e[t] | e[t + 1] << 8 | e[t + 2] << 16) + 1;
clock *= tag == 0x03 ? 10_000 : 1_000;
int hTotal = (e[t + 4] | e[t + 5] << 8) + 1 + (e[t + 6] | e[t + 7] << 8) + 1;
int vTotal = (e[t + 12] | e[t + 13] << 8) + 1 + (e[t + 14] | e[t + 15] << 8) + 1;
best = Math.Max(best, Rate(clock, hTotal, vTotal));
}
}
at = payload + length;
}
return best;
}
private static double Rate(double pixelClock, int hTotal, int vTotal) =>
hTotal > 0 && vTotal > 0 ? pixelClock / ((double)hTotal * vTotal) : 0;
}
+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 LinuxGpus _gpus;
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,
Func<IReadOnlyList<string>>? nvidiaSmi = null)
Func<IReadOnlyList<string>>? nvidiaSmi = null,
Func<IReadOnlyList<DxgiAdapter>?>? dxgi = null,
Func<IReadOnlyList<GraphicsCard>>? registry = null)
{
_files = files;
_environment = environment;
_gpus = gpus;
_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>
@@ -46,15 +52,34 @@ public sealed class GraphicsCards
IEnumerable<GraphicsCard> cards = Array.Empty<GraphicsCard>();
if (_environment.IsLinux)
cards = FromLinux();
else if (_environment.IsWindows && OperatingSystem.IsWindows())
cards = FromRegistry();
else if (_environment.IsWindows)
cards = FromWindows();
// A program goes to the discrete card, on Windows by its own request.
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")]
private static IEnumerable<GraphicsCard> FromRegistry()
private static IReadOnlyList<GraphicsCard> FromRegistry()
{
try
{
+222
View File
@@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using StarterNG.Application.Abstractions;
namespace StarterNG.Infrastructure;
/// <summary>A monitor as the simulator names it for fullscreenmonitor.</summary>
/// <param name="Id">"name:x,y" - GLFW's name with spaces as underscores, and the monitor's place on the desktop (application.cpp).</param>
/// <param name="RefreshRate">The current mode's rate in Hz, which a full screen of the simulator keeps; 0 where unknown.</param>
public sealed record DisplayMonitor(string Id, string Name, int Width, int Height, bool Primary, int RefreshRate = 0);
/// <summary>
/// The monitors the simulator can start on, named as GLFW names them: on Windows the
/// monitor's device string under its adapter, on Linux the RandR output that xrandr lists.
/// </summary>
public static class Monitors
{
public static IReadOnlyList<DisplayMonitor> List(IEnvironment environment)
{
try
{
if (environment.IsWindows && OperatingSystem.IsWindows())
return OnWindows();
if (environment.IsLinux)
return FromXrandr();
}
catch (Exception)
{
// Without the list the player still has the primary monitor.
}
return Array.Empty<DisplayMonitor>();
}
/// <summary>
/// The size of the monitor a full screen of the simulator goes to (application.cpp): the one
/// <paramref name="id"/> names, or the primary one when it names none or one not connected.
/// Null where neither is among <paramref name="monitors"/>.
/// </summary>
public static (int Width, int Height)? SizeOf(IReadOnlyList<DisplayMonitor> monitors, string id)
{
DisplayMonitor? primary = null;
foreach (var m in monitors)
{
if (id.Length > 0 && m.Id == id)
return (m.Width, m.Height);
if (m.Primary)
primary ??= m;
}
return primary is null ? null : (primary.Width, primary.Height);
}
/// <summary>The id GLFW gives a monitor: its name with spaces as underscores, then where it starts.</summary>
public static string IdOf(string name, int x, int y) => $"{name.Replace(' ', '_')}:{x},{y}";
// ── Windows: as win32_monitor.c of GLFW walks them ───────────────────────
// DISPLAY_DEVICEW: cb, DeviceName[32], DeviceString[128], StateFlags, DeviceID[128], DeviceKey[128].
private const int DisplayDeviceSize = 840;
private const int DeviceNameOffset = 4;
private const int DeviceStringOffset = 68;
private const int StateFlagsOffset = 324;
private const int Active = 0x1;
private const int PrimaryDevice = 0x4;
// DEVMODEW: dmSize at 68, dmPosition at 76, dmPelsWidth and dmPelsHeight at 172 and 176,
// dmDisplayFrequency at 184.
private const int DevModeSize = 220;
private const int DevModeSizeOffset = 68;
private const int PositionOffset = 76;
private const int WidthOffset = 172;
private const int HeightOffset = 176;
private const int DisplayFrequencyOffset = 184;
private const int CurrentSettings = -1;
private const int RotatedMode = 0x4;
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int EnumDisplayDevicesW(IntPtr device, int index, IntPtr displayDevice, int flags);
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int EnumDisplaySettingsExW(IntPtr deviceName, int modeNum, IntPtr devMode, int flags);
private static IReadOnlyList<DisplayMonitor> OnWindows()
{
var monitors = new List<DisplayMonitor>();
IntPtr adapter = Blank(DisplayDeviceSize, 0, DisplayDeviceSize);
IntPtr display = Blank(DisplayDeviceSize, 0, DisplayDeviceSize);
IntPtr mode = Blank(DevModeSize, DevModeSizeOffset, DevModeSize);
try
{
for (int a = 0; EnumDisplayDevicesW(IntPtr.Zero, a, adapter, 0) != 0; a++)
{
if ((Marshal.ReadInt32(adapter, StateFlagsOffset) & Active) == 0)
continue;
IntPtr adapterName = adapter + DeviceNameOffset;
Clear(mode, DevModeSize, DevModeSizeOffset);
if (EnumDisplaySettingsExW(adapterName, CurrentSettings, mode, RotatedMode) == 0)
continue;
int x = Marshal.ReadInt32(mode, PositionOffset), y = Marshal.ReadInt32(mode, PositionOffset + 4);
int width = Marshal.ReadInt32(mode, WidthOffset), height = Marshal.ReadInt32(mode, HeightOffset);
bool primary = (Marshal.ReadInt32(adapter, StateFlagsOffset) & PrimaryDevice) != 0;
// 0 and 1 stand for the hardware's default rate.
int rate = Marshal.ReadInt32(mode, DisplayFrequencyOffset);
// A monitor under the adapter gives its own name; with none, the adapter's stands.
string name = Marshal.PtrToStringUni(adapter + DeviceStringOffset) ?? string.Empty;
Clear(display, DisplayDeviceSize, 0);
Marshal.WriteInt32(display, 0, DisplayDeviceSize);
for (int d = 0; EnumDisplayDevicesW(adapterName, d, display, 0) != 0; d++)
{
if ((Marshal.ReadInt32(display, StateFlagsOffset) & Active) == 0)
continue;
name = Marshal.PtrToStringUni(display + DeviceStringOffset) ?? name;
break;
}
monitors.Add(new DisplayMonitor(IdOf(name, x, y), name, width, height, primary, rate > 1 ? rate : 0));
Clear(adapter, DisplayDeviceSize, 0);
Marshal.WriteInt32(adapter, 0, DisplayDeviceSize);
}
}
finally
{
Marshal.FreeHGlobal(adapter);
Marshal.FreeHGlobal(display);
Marshal.FreeHGlobal(mode);
}
return monitors;
}
private static IntPtr Blank(int size, int sizeOffset, int sizeValue)
{
IntPtr block = Marshal.AllocHGlobal(size);
Clear(block, size, sizeOffset);
if (sizeOffset == 0)
Marshal.WriteInt32(block, 0, sizeValue);
else
Marshal.WriteInt16(block, sizeOffset, (short)sizeValue);
return block;
}
private static void Clear(IntPtr block, int size, int sizeOffset)
{
for (int i = 0; i < size; i++)
Marshal.WriteByte(block, i, 0);
if (sizeOffset > 0)
Marshal.WriteInt16(block, sizeOffset, (short)size);
}
// ── Linux: the connected RandR outputs, as x11_monitor.c of GLFW names them ──
// A line of xrandr is short; one that takes longer than this to match is no report of monitors.
private static readonly TimeSpan MatchTimeout = TimeSpan.FromSeconds(1);
private static readonly Regex Output = new(
@"^(\S+) connected (primary )?(\d+)x(\d+)\+(\d+)\+(\d+)", RegexOptions.CultureInvariant, MatchTimeout);
// A mode line under an output: the rate in use is the one marked with a star.
private static readonly Regex CurrentRate = new(@"^\s+\S+.*?\s(\d+(?:\.\d+)?)\*", RegexOptions.CultureInvariant, MatchTimeout);
// Where distributions put xrandr: run from there, not from whatever PATH finds first.
private static readonly string[] XrandrPlaces = { "/usr/bin/xrandr", "/usr/local/bin/xrandr", "/bin/xrandr" };
private static IReadOnlyList<DisplayMonitor> FromXrandr()
{
string? xrandr = Array.Find(XrandrPlaces, System.IO.File.Exists);
if (xrandr is null)
return Array.Empty<DisplayMonitor>();
using var process = Process.Start(new ProcessStartInfo(xrandr, "--query")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
});
if (process is null)
return Array.Empty<DisplayMonitor>();
string text = process.StandardOutput.ReadToEnd();
process.WaitForExit(2000);
return Parse(text);
}
/// <summary>The monitors of xrandr's report, each with the rate its mode in use runs at.</summary>
public static IReadOnlyList<DisplayMonitor> Parse(string xrandr)
{
var monitors = new List<DisplayMonitor>();
bool underConnected = false;
foreach (string line in xrandr.Split('\n'))
{
var m = Output.Match(line);
if (m.Success)
{
string name = m.Groups[1].Value;
int width = int.Parse(m.Groups[3].Value), height = int.Parse(m.Groups[4].Value);
int x = int.Parse(m.Groups[5].Value), y = int.Parse(m.Groups[6].Value);
monitors.Add(new DisplayMonitor(IdOf(name, x, y), name, width, height, m.Groups[2].Success));
underConnected = true;
continue;
}
if (line.Length > 0 && !char.IsWhiteSpace(line[0]))
{
// Another output, connected without a place on the desktop or not at all.
underConnected = false;
continue;
}
var rate = CurrentRate.Match(line);
if (underConnected && rate.Success && monitors[^1].RefreshRate == 0)
monitors[^1] = monitors[^1] with
{
RefreshRate = (int)Math.Round(double.Parse(rate.Groups[1].Value, CultureInfo.InvariantCulture))
};
}
return monitors;
}
}
@@ -24,7 +24,12 @@ public sealed class SceneryParser
/// Whether the simulator opens an include, as the include names it; null leaves
/// includes unchecked.
/// </param>
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null)
/// <param name="loadsVehicle">
/// Whether the simulator finds a vehicle's .fiz, by its folder and .mmd name as
/// written; null leaves vehicles unchecked.
/// </param>
public Scenery Parse(string path, string content, Func<string, bool>? opensInclude = null,
Func<string, string, bool>? loadsVehicle = null)
{
string original = content;
@@ -38,7 +43,7 @@ public sealed class SceneryParser
// Read from the text with its optional includes blanked, which keeps every
// place where it was, so a fault's line is the line in the file.
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude);
var syntax = ScenerySyntax.Scan(content, System.IO.Path.GetFileName(path), opensInclude, loadsVehicle);
var faults = syntax.Faults.ToList();
var inlined = SceneryIncludes.Ranges(content);
@@ -281,7 +286,11 @@ public sealed class SceneryParser
if (numbers.Count >= 6 &&
double.TryParse(numbers[^1], NumberStyles.Float, CultureInfo.InvariantCulture, out double overcast))
weather.Overcast = overcast;
{
// The simulator draws a negative overcast anew each run, from 0 up to its size.
weather.OvercastRandom = overcast < 0;
weather.Overcast = Math.Max(overcast, 0);
}
}
private static string? MatchAllDirectives(string content, string letter)
@@ -103,7 +103,7 @@ public sealed class SceneryRepository : ISceneryRepository
string own = LegacyText.Decode(_files.ReadAllBytes(path), out var ownEncoding);
string text = SceneryIncludes.Inline(own, ReadInclude);
var scenery = _parser.Parse(path, text, OpensInclude);
var scenery = _parser.Parse(path, text, OpensInclude, LoadsVehicle);
scenery.HasCompanionTimetable = binaryTerrain;
scenery.Sources = sources;
scenery.TextEncoding = ownEncoding;
@@ -124,6 +124,15 @@ public sealed class SceneryRepository : ISceneryRepository
/// </summary>
private bool Opens(string name) => ResolveInclude(name) is not null;
/// <summary>
/// Whether the simulator finds a vehicle's definition - its .fiz, named after its
/// .mmd, in its folder under dynamic - whatever the case of the letters. Without
/// it the simulator leaves the vehicle out; a folder there all the same, empty,
/// makes no difference.
/// </summary>
private bool LoadsVehicle(string folder, string mmd) =>
_names.Resolve(_paths.Dynamic, $"{folder}/{mmd}.fiz") is not null;
/// <summary>
/// An include's file as it is named on disk, from the scenery folder, whatever
/// the case of its letters - as Windows, or Wine, finds it: whose consists the
@@ -55,6 +55,19 @@ public sealed class ExecutableLocator
public string CanonicalName => _environment.IsWindows ? "eu07.exe" : "eu07";
/// <summary>
/// The simulator's own starter on Windows, built beside eu07.exe: it checks the processor and the
/// libraries first, explains a start the system refuses with a bare code, writes the minidump of a
/// crash from outside, passes the arguments on and returns the simulator's exit code.
/// </summary>
public const string WindowsStarterName = "eu07_starter.exe";
// Picked ahead of the simulator next to it on Windows alone: under Wine neither its checks nor its
// minidumps are of any use.
private bool IsWindowsStarter(string path) =>
_environment.IsWindows &&
string.Equals(Path.GetFileName(path), WindowsStarterName, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// The simulator to start: the one picked in the settings, or the best one in
/// the installation. A pick that is not there - the settings live per user and
@@ -95,6 +108,7 @@ public sealed class ExecutableLocator
.Where(IsCandidate)
.OrderBy(Rank)
.ThenByDescending(path => _lacksAvx2 && IsNoAvx2(path) ? _files.GetLastWriteTimeUtc(path) : DateTime.MinValue)
.ThenBy(path => IsWindowsStarter(path) ? 0 : 1)
.ThenBy(path => string.Equals(Path.GetFileName(path), CanonicalName,
StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(path => Path.GetFileName(path).Length);
@@ -302,33 +316,6 @@ public sealed class ExecutableLocator
return extension.Length == 0 || extension is ".exe" or ".x86_64" or ".run" or ".appimage";
}
/// <summary>Whether the DLSS and frame generation libraries lie next to the simulator: without them it cannot use either.</summary>
public (bool Dlss, bool FrameGeneration) DlssLibraries(string executable)
{
try
{
// Resolve hands back either a path of its own search or the bare name of the pick.
string full = _files.FileExists(executable) ? executable : FullPath(executable);
string? directory = Path.GetDirectoryName(full);
if (string.IsNullOrEmpty(directory) || !_files.DirectoryExists(directory))
return (false, false);
bool windowsBuild = _files.FileExists(full)
? Format(full) == BinaryFormat.PortableExecutable
: _environment.IsWindows;
return windowsBuild
? (Has(directory, "nvngx_dlss.dll"), Has(directory, "nvngx_dlssg.dll"))
: (Has(directory, "libnvidia-ngx-dlss.so*"), Has(directory, "libnvidia-ngx-dlssg.so*"));
}
catch (Exception)
{
return (false, false);
}
}
private bool Has(string directory, string pattern) => _files.GetFiles(directory, pattern).Count > 0;
/// <summary>A path as <see cref="Resolve"/> gives it, which may be relative to the installation, made whole.</summary>
public string FullPath(string path) =>
Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path);
@@ -1,9 +1,11 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using StarterNG.Classes;
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure.Adapters;
namespace StarterNG.Infrastructure.Settings;
@@ -24,16 +26,6 @@ public sealed class SettingsSerializer
s.PhysicsLog = false;
}
private readonly bool _dlssPlatform;
/// <param name="dlssPlatform">Whether the simulator can have DLSS here at all (not on macOS).</param>
public SettingsSerializer(bool dlssPlatform = true)
{
_dlssPlatform = dlssPlatform;
}
public bool DlssPlatform => _dlssPlatform;
public void Read(SimulatorSettings s, ConfigFile c)
{
s.LanguageWasSet = c.Has("lang");
@@ -45,20 +37,19 @@ public sealed class SettingsSerializer
s.FpsAverage = c.GetDouble("fpsaverage", 0);
s.PauseOnStart = c.GetBool("pause", false);
// As the old starter read it (src/uSettings.pas): of X its level and its sign, of Y
// only the sign. Both are written as that starter wrote them, one of its four speeds
// and 0.5, whatever the file had. A number that cannot be read leaves the standard level.
var mouse = c.GetTokens("mousescale");
if (mouse.Length >= 1 && double.TryParse(mouse[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double mx))
if (mouse.Length >= 1 && TryParseMouseScale(mouse[0], out double mx))
{
s.InvertMouseHorizontal = mx < 0;
s.MouseScaleXMagnitude = Math.Abs(mx);
s.CursorSensitivity = SensitivityStep(mx);
}
if (mouse.Length >= 2 && double.TryParse(mouse[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double my))
{
s.InvertMouseVertical = my < 0;
s.MouseScaleYMagnitude = Math.Abs(my);
s.CursorSensitivity = SimulatorSettings.MouseLevelOf(mx);
}
if (mouse.Length >= 1)
s.InvertMouseVertical = mouse.Length >= 2 && TryParseMouseScale(mouse[1], out double my) && my < 0;
s.IgnoreGamepad = !c.GetBool("input.gamepad", true);
s.IgnoreGamepad = !c.GetBool("input.gamepad", false);
s.FeedbackMode = Clamp(c.GetInt("feedbackmode", 1), 0, 5);
s.FeedbackPort = c.GetInt("feedbackport", 888);
s.UartEnabled = c.Has("uart");
@@ -91,8 +82,10 @@ public sealed class SettingsSerializer
s.VirtualShunting = c.GetBool("ai.trainman", true);
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "full"));
s.VulkanDevice = c.GetString("gfx.vulkan.device", "");
// Vulkan unless the file says otherwise: the simulator's own is OpenGL, so the starter always writes it.
string renderer = c.GetString("gfxrenderer", SimulatorSettings.WordOf(GraphicsBackend.Vulkan)).Trim();
s.Backend = SimulatorSettings.BackendOf(renderer);
s.RendererWord = renderer.Length > 0 && !SimulatorSettings.KnownRendererWord(renderer) ? renderer : null;
s.Width = c.GetInt("width", 1280);
s.Height = c.GetInt("height", 720);
s.BufferScalePercent = ReadBufferScale(c);
@@ -100,9 +93,6 @@ public sealed class SettingsSerializer
s.MaxCabTextureSize = c.GetInt("maxcabtexturesize", 4096);
s.TextureFiltering = Math.Max(1, c.GetDouble("anisotropicfiltering", 8));
s.AntiAliasing = ReadAntiAliasing(c);
s.DlssPreset = c.GetString("gfx.dlss.preset", "default").ToLowerInvariant();
s.FrameGeneration = ParseFrameGeneration(FirstToken(c, "gfx.framegeneration"));
s.Reflex = ParseReflex(FirstToken(c, "gfx.reflex"));
s.DynamicLights = Clamp(c.GetInt("dynamiclights", 7), 0, 7);
s.DrawRangeFactor = c.GetDouble("gfx.drawrange.factor.max", 3.0);
s.VSync = c.GetBool("vsync", false);
@@ -112,36 +102,7 @@ public sealed class SettingsSerializer
s.MotionBlur = c.GetBool("gfx.postfx.motionblur.enabled", true);
s.ExtraEffects = c.GetBool("gfx.extraeffects", true);
s.EnvMap = c.GetBool("gfx.envmap.enabled", true);
s.UseVbo = c.GetBool("usevbo", true);
s.RenderShadows = c.GetBool("shadows", true);
s.ShadowSdsm = c.GetBool("gfx.shadow.sdsm", false);
s.LightShadows = ParseLevel(FirstToken(c, "gfx.lights.shadows"), 2, 3);
s.ContactShadows = ParseLevel(FirstToken(c, "gfx.contactshadows"), 0, 3);
s.LightsClustered = c.GetBool("gfx.lights.clustered", true);
s.AmbientOcclusion = ParseAmbientOcclusion(FirstToken(c, "gfx.postfx.ao"));
var aoQuality = c.GetTokens("gfx.postfx.ao.quality");
s.AoSlices = aoQuality.Length >= 1 ? ParseInt(aoQuality[0], 3) : 3;
s.AoSteps = aoQuality.Length >= 2 ? ParseInt(aoQuality[1], 4) : 4;
s.AoLighting = c.GetBool("gfx.postfx.ao.lighting", true);
s.CabProbe = ParseCabProbe(FirstToken(c, "gfx.cabprobe"));
s.CabProbeInterval = c.GetInt("gfx.cabprobe.interval", 4);
s.CabProbeBounce = c.GetDouble("gfx.cabprobe.bounce", 1.0);
s.CabProbeReflections = c.GetBool("gfx.cabprobe.reflections", true);
s.CabLampLight = c.GetBool("gfx.lights.cab", true);
s.DepthPrepassScene = c.GetBool("gfx.depthprepass.scene", false);
s.Ssr = ParseLevel(FirstToken(c, "gfx.ssr"), 2, 3);
s.RayTracing = c.GetBool("gfx.raytracing", false);
s.RayTracingRange = (int)Math.Round(c.GetDouble("gfx.raytracing.range", 500));
s.VolumetricFog = ParseVolumetricFog(FirstToken(c, "gfx.fog"));
s.FogQuality = ParseFogQuality(FirstToken(c, "gfx.fog.quality"));
s.Clouds = ParseLevel(FirstToken(c, "gfx.clouds"), 2, 4);
s.CloudShadows = c.GetBool("gfx.clouds.shadows", true);
s.Grass = c.GetBool("gfx.grass", true);
s.GrassDistance = (int)Math.Round(c.GetDouble("gfx.grass.distance", 60));
s.GrassDensity = c.GetDouble("gfx.grass.density", 1.0);
s.PrecipitationParticles = c.GetInt("gfx.precipitation.particles", 65536);
s.Bloom = c.GetBool("gfx.postfx.bloom", true);
s.AutoExposure = c.GetBool("gfx.postfx.autoexposure", true);
s.RenderShadows = c.GetBool("gfx.shadowmap.enabled", true);
// A negative rate counts as its size; none at all, as never.
double reflections = Math.Abs(c.GetDouble("gfx.reflections.framerate", 1 / 300.0));
s.ReflectionsFramerate = reflections > 0 ? reflections : 1 / 300.0;
@@ -153,9 +114,9 @@ public sealed class SettingsSerializer
if (shadowTune.Length >= 2) s.ShadowTuneUnused[0] = shadowTune[1];
if (shadowTune.Length >= 4) s.ShadowTuneUnused[1] = shadowTune[3];
s.CabShadowsRange = (int)Math.Round(c.GetDouble("gfx.shadows.cab.range", 0));
s.ShadowRankCutoff = c.GetInt("gfx.shadow.rank.cutoff", 3);
s.ReflectionsFidelity = Clamp(c.GetInt("gfx.reflections.fidelity", 0), 0, 2);
// the simulator's own: track sections, models and vehicles (Globals.h)
s.ReflectionsFidelity = Clamp(c.GetInt("gfx.reflections.fidelity", 2), 0, 2);
s.FieldOfView = Clamp((int)Math.Round(c.GetDouble("fieldofview", 45)), 10, 75);
s.PythonScreens = c.GetBool("python.enabled", true);
s.PythonThreadedUpload = c.GetBool("python.threadedupload", true);
@@ -165,7 +126,7 @@ public sealed class SettingsSerializer
if (s.FpsLimitEnabled) s.FpsLimit = fpsLimit;
s.ShadowAngleLimit = c.GetDouble("gfx.shadow.angle.min", 0.2);
s.FullscreenWindowed = c.GetBool("fullscreenwindowed", false);
s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase);
s.FullscreenMonitor = LegacyText.Utf8From1250(c.GetString("fullscreenmonitor", "").Trim());
s.SplineFidelity = Clamp(c.GetInt("splinefidelity", 1), 1, 4);
s.FullPhysics = c.GetBool("fullphysics", true);
@@ -201,7 +162,6 @@ public sealed class SettingsSerializer
s.CompressTextures = c.GetBool("compresstex", true);
s.ScaleSpeculars = c.GetBool("scalespeculars", true);
s.UseGLES = c.GetBool("gfx.usegles", false);
s.ShaderGamma = c.GetBool("gfx.shadergamma", false);
s.ScreenMipmaps = c.GetBool("python.mipmaps", true);
s.ExtendedModelConversion = c.GetInt("convertmodels", 0) != 0;
@@ -213,6 +173,9 @@ public sealed class SettingsSerializer
s.AutoCloseStarter = c.GetBool("starter.autoclose", false);
s.LargeThumbnails = c.GetBool("starter.largethumbnails", false);
s.AutoExpandSceneryTree = c.GetBool("starter.expandtree", false);
s.AdvancedSettings = c.GetBool("starter.settings.advanced", false);
s.MovedToStandard = c.GetBool("starter.settings.standard", false);
s.Revision = c.GetInt("starter.settings.revision", 0);
s.CpuNotice = c.GetBool("starter.cpunotice", true);
s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase)
? GpuPreference.System
@@ -236,8 +199,11 @@ public sealed class SettingsSerializer
foreach (var key in SimulatorKeys.All)
if (c.Has(key.Key))
s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty;
// the faster choice the simulator's own default is not: written whether or not the file had it
else if (key.Writes)
s.Extra[key.Key] = key.Default;
GraphicsRules.Normalize(s, _dlssPlatform);
GraphicsRules.Normalize(s);
}
/// <summary>
@@ -247,14 +213,36 @@ public sealed class SettingsSerializer
/// </summary>
public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" };
/// <summary>Keys written only when they say something, besides those of <see cref="SimulatorKeys"/>.</summary>
public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "gfx.vulkan.device" };
/// <summary>
/// Keys the simulator takes more than one line of (utilities/Globals.cpp), each adding one more: of these a
/// line again is no duplicate.
/// </summary>
public static readonly string[] RepeatableKeys = { "network.server", "python.viewport", "extraviewport", "test.vehicle" };
/// <summary>Keys no simulator reads any more, taken out of the file on a save.</summary>
/// <summary>Keys written only when they say something, besides those of <see cref="SimulatorKeys"/>.</summary>
public static readonly string[] OptionalKeys = { "fpslimit", "fullscreenmonitor" };
/// <summary>
/// Keys the simulator no longer goes by, taken out of the file on a save: those of the renderers it has no more,
/// which it logs as unsupported (usevbo, gfx.usegles, gfx.angleplatform, the frame buffer's size in pixels in
/// place of gfx.buffer.percent), those it reads and does nothing with, and the starter's own of before.
/// </summary>
public static readonly string[] ObsoleteKeys =
{
"gfx.postfx.tonemapping",
"starter.developertools",
"usevbo",
"gfx.usegles",
"gfx.angleplatform",
"gfx.framebuffer.width",
"gfx.framebuffer.height",
"starter.bufferscale",
"shadows",
"gfx.shadows.cab.range",
"smoothtraction",
"skyenabled",
"hideconsole",
"slowmotion",
};
/// <summary>
@@ -264,7 +252,7 @@ public sealed class SettingsSerializer
public void Write(SimulatorSettings settings, ConfigFile c)
{
var s = settings.Copy();
GraphicsRules.Normalize(s, _dlssPlatform);
GraphicsRules.Normalize(s);
c.Set("lang", string.IsNullOrWhiteSpace(s.LanguageCode)
? "en"
@@ -273,14 +261,11 @@ public sealed class SettingsSerializer
c.SetBool("inactivepause", s.PauseWhenInactive);
c.SetBool("pause", s.PauseOnStart);
double magnitude = SensitivityStep(s.MouseScaleXMagnitude) == s.CursorSensitivity
? s.MouseScaleXMagnitude
: s.CursorSensitivity;
double mx = magnitude * (s.InvertMouseHorizontal ? -1 : 1);
double my = s.MouseScaleYMagnitude * (s.InvertMouseVertical ? -1 : 1);
double mx = SimulatorSettings.MouseScaleOf(s.CursorSensitivity) * (s.InvertMouseHorizontal ? -1 : 1);
double my = SimulatorSettings.MouseScaleY * (s.InvertMouseVertical ? -1 : 1);
c.Set("mousescale",
$"{mx.ToString("R", CultureInfo.InvariantCulture)} " +
$"{my.ToString("R", CultureInfo.InvariantCulture)}");
$"{mx.ToString("0.0", CultureInfo.InvariantCulture)} " +
$"{my.ToString("0.0", CultureInfo.InvariantCulture)}");
c.SetBool("input.gamepad", !s.IgnoreGamepad);
c.SetInt("feedbackmode", s.FeedbackMode);
@@ -311,27 +296,18 @@ public sealed class SettingsSerializer
c.SetBool("ai.trainman", s.VirtualShunting);
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
if (!string.IsNullOrWhiteSpace(s.VulkanDevice)) c.Set("gfx.vulkan.device", s.VulkanDevice.Trim());
c.Set("gfxrenderer", s.RendererWord ?? SimulatorSettings.WordOf(s.Backend));
c.SetInt("width", s.Width);
c.SetInt("height", s.Height);
c.SetInt("starter.bufferscale", s.BufferScalePercent);
int fbw = (int)Math.Round(s.Width * s.BufferScalePercent / 100.0);
int fbh = (int)Math.Round(s.Height * s.BufferScalePercent / 100.0);
// The size for the simulators before gfx.buffer.percent, which pass that one over and the other way round.
c.SetInt("gfx.framebuffer.width", fbw);
c.SetInt("gfx.framebuffer.height", fbh);
c.SetInt("gfx.buffer.percent", s.BufferScalePercent);
// The simulator draws at this part of the window and stretches it to the window.
c.SetDouble("gfx.buffer.percent", s.BufferScalePercent / 100.0);
c.SetInt("maxtexturesize", s.MaxTextureSize);
c.SetInt("maxcabtexturesize", s.MaxCabTextureSize);
c.SetDouble("anisotropicfiltering", s.TextureFiltering);
// multisampling is what older simulators read; gfx.antialiasing overrides it in the new ones, but only from
// a later line, since each key sets the mode as it is read.
// The older key for the simulators before gfx.antialiasing; of the two, the simulator heeds the one further
// down, which SettingsStore keeps gfx.antialiasing.
c.SetInt("multisampling", MultisamplingLevel(s.AntiAliasing));
c.Set("gfx.antialiasing", AntiAliasingToken(s.AntiAliasing));
c.Set("gfx.dlss.preset", s.DlssPreset);
c.Set("gfx.framegeneration", s.FrameGeneration > 1 ? $"x{s.FrameGeneration}" : "off");
c.Set("gfx.reflex", s.Reflex switch { 1 => "on", 2 => "boost", _ => "off" });
c.Set("gfx.antialiasing", AntiAliasingWord(s.AntiAliasing));
c.SetInt("dynamiclights", s.DynamicLights);
c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor);
c.SetBool("vsync", s.VSync);
@@ -341,40 +317,11 @@ public sealed class SettingsSerializer
c.SetBool("gfx.postfx.motionblur.enabled", s.MotionBlur);
c.SetBool("gfx.extraeffects", s.ExtraEffects);
c.SetBool("gfx.envmap.enabled", s.EnvMap);
c.SetBool("usevbo", s.UseVbo);
c.SetBool("shadows", s.RenderShadows);
c.SetBool("gfx.shadowmap.enabled", s.RenderShadows);
c.SetBool("gfx.shadow.sdsm", s.ShadowSdsm);
c.Set("gfx.lights.shadows", LevelToken(s.LightShadows));
c.Set("gfx.contactshadows", LevelToken(s.ContactShadows));
c.SetBool("gfx.lights.clustered", s.LightsClustered);
c.Set("gfx.postfx.ao", s.AmbientOcclusion switch { 1 => "ssao", 2 => "gtao", _ => "no" });
c.Set("gfx.postfx.ao.quality", $"{s.AoSlices} {s.AoSteps}");
c.SetBool("gfx.postfx.ao.lighting", s.AoLighting);
c.Set("gfx.cabprobe", LevelToken(s.CabProbe));
c.SetInt("gfx.cabprobe.interval", s.CabProbeInterval);
c.SetDouble("gfx.cabprobe.bounce", s.CabProbeBounce);
c.SetBool("gfx.cabprobe.reflections", s.CabProbeReflections);
c.Set("gfx.ssr", LevelToken(s.Ssr));
c.SetBool("gfx.raytracing", s.RayTracing);
c.SetInt("gfx.raytracing.range", s.RayTracingRange);
c.Set("gfx.fog", s.VolumetricFog ? "yes" : "analytic");
c.Set("gfx.fog.quality", LevelToken(s.FogQuality));
c.Set("gfx.clouds", LevelToken(s.Clouds));
c.SetBool("gfx.clouds.shadows", s.CloudShadows);
c.SetBool("gfx.grass", s.Grass);
c.SetInt("gfx.grass.distance", s.GrassDistance);
// The grass thins out past its distance; the simulator's own default keeps a sixth of it for that.
c.SetInt("gfx.grass.fadedistance", Math.Min(600, s.GrassDistance + Math.Max(10, s.GrassDistance / 6)));
c.SetDouble("gfx.grass.density", s.GrassDensity);
c.SetInt("gfx.precipitation.particles", s.PrecipitationParticles);
c.SetBool("gfx.postfx.bloom", s.Bloom);
c.SetBool("gfx.postfx.autoexposure", s.AutoExposure);
c.Set("gfx.reflections.framerate", s.ReflectionsFramerate.ToString("0.######", CultureInfo.InvariantCulture));
c.Set("shadowtune",
$"{s.ShadowMapResolution} {s.ShadowTuneUnused[0]} " +
$"{s.ShadowProjectionRange} {s.ShadowTuneUnused[1]}");
c.SetInt("gfx.shadows.cab.range", s.CabShadowsRange);
c.SetInt("gfx.shadow.rank.cutoff", s.ShadowRankCutoff);
c.SetInt("gfx.reflections.fidelity", s.ReflectionsFidelity);
c.SetInt("fieldofview", s.FieldOfView);
@@ -383,7 +330,9 @@ public sealed class SettingsSerializer
if (s.FpsLimitEnabled) c.SetDouble("fpslimit", s.FpsLimit);
c.SetDouble("gfx.shadow.angle.min", s.ShadowAngleLimit);
c.SetBool("fullscreenwindowed", s.FullscreenWindowed);
if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan");
// The simulator compares the word with GLFW's name of the monitor, which is UTF-8.
if (!string.IsNullOrWhiteSpace(s.FullscreenMonitor))
c.Set("fullscreenmonitor", LegacyText.Utf8As1250(s.FullscreenMonitor.Trim()));
c.SetInt("splinefidelity", s.SplineFidelity);
c.SetBool("fullphysics", s.FullPhysics);
@@ -417,7 +366,6 @@ public sealed class SettingsSerializer
c.SetBool("compresstex", s.CompressTextures);
c.SetBool("scalespeculars", s.ScaleSpeculars);
c.SetBool("gfx.usegles", s.UseGLES);
c.SetBool("gfx.shadergamma", s.ShaderGamma);
c.SetBool("python.mipmaps", s.ScreenMipmaps);
c.Set("convertmodels", s.ExtendedModelConversion ? "143" : "0");
@@ -429,6 +377,9 @@ public sealed class SettingsSerializer
c.SetBool("starter.autoclose", s.AutoCloseStarter);
c.SetBool("starter.largethumbnails", s.LargeThumbnails);
c.SetBool("starter.expandtree", s.AutoExpandSceneryTree);
c.SetBool("starter.settings.advanced", s.AdvancedSettings);
c.SetBool("starter.settings.standard", s.MovedToStandard);
c.SetInt("starter.settings.revision", s.Revision);
c.SetBool("starter.cpunotice", s.CpuNotice);
c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete");
c.SetInt("starter.batterydefault", (int)s.ReadyOverride);
@@ -447,56 +398,96 @@ public sealed class SettingsSerializer
c.Set(key.Key, value.Trim());
}
// What the simulator goes by: up to 4 a part of the window, above it percents.
private static int ReadBufferScale(ConfigFile c)
/// <summary>
/// <paramref name="keys"/> with the keys that say the same setting along with them: the anti-aliasing is
/// written in two keys, the older for the simulators before the newer one.
/// </summary>
public static IReadOnlyCollection<string> WithCompanions(IReadOnlyCollection<string> keys)
{
if (!c.Has("gfx.buffer.percent"))
return Clamp(c.GetInt("starter.bufferscale", 100), 25, 200);
double value = c.GetDouble("gfx.buffer.percent", 100);
return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200);
if (!keys.Intersect(GraphicsGroup.AntiAliasingKeys, StringComparer.OrdinalIgnoreCase).Any())
return keys;
var all = new HashSet<string>(keys, StringComparer.OrdinalIgnoreCase);
all.UnionWith(GraphicsGroup.AntiAliasingKeys);
return all;
}
private static string FirstToken(ConfigFile c, string key)
private static int ReadBufferScale(ConfigFile c) =>
Clamp(BufferScaleIn(c), 25, GraphicsRules.MaxBufferScale);
/// <summary>
/// The render scale in percent: gfx.buffer.percent as the simulator reads it (a fraction, or above 4 a percent),
/// else what a starter of before left - its own percent, or the frame buffer the file set against its window.
/// </summary>
private static int BufferScaleIn(ConfigFile c)
{
var tokens = c.GetTokens(key);
return tokens.Length > 0 ? tokens[0].ToLowerInvariant() : string.Empty;
if (c.Has("gfx.buffer.percent"))
{
double part = c.GetDouble("gfx.buffer.percent", 1);
return (int)Math.Round(part > 4 ? part : part * 100);
}
if (c.Has("starter.bufferscale"))
return c.GetInt("starter.bufferscale", 100);
int width = c.GetInt("width", 0);
int framebuffer = c.GetInt("gfx.framebuffer.width", 0);
return width > 0 && framebuffer > 0 ? (int)Math.Round(framebuffer * 100.0 / width) : 100;
}
// The names the simulator takes for Vulkan; every other word is OpenGL to the screen, and stays in the file until changed.
// Whichever of the two keys comes later in the file decides, as each sets the mode when the simulator reads it.
/// <summary>
/// The keys of <paramref name="c"/> set above what the starter lets them go to
/// (<see cref="GraphicsRules"/>): the next save brings them down.
/// </summary>
public static IReadOnlySet<string> OverCapKeys(ConfigFile c)
{
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (c.GetInt("maxcabtexturesize", 0) > GraphicsRules.MaxCabTextureSize)
keys.Add("maxcabtexturesize");
var shadowTune = c.GetTokens("shadowtune");
if (shadowTune.Length >= 3 && ParseDouble(shadowTune[2], 0) > GraphicsRules.MaxShadowRange)
keys.Add("shadowtune");
if (BufferScaleIn(c) > GraphicsRules.MaxBufferScale)
keys.Add("gfx.buffer.percent");
return keys;
}
/// <summary>
/// The anti-aliasing as the simulator reads it: of gfx.antialiasing and the older multisampling, the one further
/// down the file, and with neither its own MSAA x4.
/// </summary>
private static AntiAliasingMode ReadAntiAliasing(ConfigFile c)
{
var fromMultisampling = c.GetInt("multisampling", 2) switch
if (c.Has("gfx.antialiasing") && c.LineOf("gfx.antialiasing") > c.LineOf("multisampling") &&
AntiAliasingOfWord(c.GetString("gfx.antialiasing", "")) is { } mode)
return mode;
return c.GetInt("multisampling", 2) switch
{
<= 0 => AntiAliasingMode.Off,
1 => AntiAliasingMode.Msaa2,
2 => AntiAliasingMode.Msaa4,
_ => AntiAliasingMode.Msaa8
};
if (!c.Has("gfx.antialiasing") ||
(c.Has("multisampling") && c.LineOf("multisampling") > c.LineOf("gfx.antialiasing")))
return fromMultisampling;
return FirstToken(c, "gfx.antialiasing") switch
{
"off" or "no" or "none" or "0" => AntiAliasingMode.Off,
"msaax2" => AntiAliasingMode.Msaa2,
"msaax4" => AntiAliasingMode.Msaa4,
"msaax8" or "msaax16" => AntiAliasingMode.Msaa8,
"taa" => AntiAliasingMode.Taa,
"dlss" => AntiAliasingMode.Dlss,
"dlaa" => AntiAliasingMode.Dlaa,
_ => fromMultisampling
3 => AntiAliasingMode.Msaa8,
_ => AntiAliasingMode.Msaa16
};
}
private static string AntiAliasingToken(AntiAliasingMode mode) => mode switch
/// <summary>The mode of a gfx.antialiasing word; null for one the simulator does not know.</summary>
private static AntiAliasingMode? AntiAliasingOfWord(string word) => word.Trim().ToLowerInvariant() switch
{
"off" or "no" or "none" or "0" => AntiAliasingMode.Off,
"msaax2" => AntiAliasingMode.Msaa2,
"msaax4" => AntiAliasingMode.Msaa4,
"msaax8" => AntiAliasingMode.Msaa8,
"msaax16" => AntiAliasingMode.Msaa16,
"taa" => AntiAliasingMode.Taa,
"dlss" => AntiAliasingMode.Dlss,
"dlaa" => AntiAliasingMode.Dlaa,
_ => null
};
public static string AntiAliasingWord(AntiAliasingMode mode) => mode switch
{
AntiAliasingMode.Msaa2 => "msaax2",
AntiAliasingMode.Msaa4 => "msaax4",
AntiAliasingMode.Msaa8 => "msaax8",
AntiAliasingMode.Msaa16 => "msaax16",
AntiAliasingMode.Taa => "taa",
AntiAliasingMode.Dlss => "dlss",
AntiAliasingMode.Dlaa => "dlaa",
@@ -508,82 +499,30 @@ public sealed class SettingsSerializer
AntiAliasingMode.Msaa2 => 1,
AntiAliasingMode.Msaa4 => 2,
AntiAliasingMode.Msaa8 => 3,
AntiAliasingMode.Msaa16 => 4,
_ => 0
};
private static int ParseFrameGeneration(string value) => value switch
{
"x2" or "on" or "yes" or "2" => 2,
"x3" or "3" => 3,
"x4" or "4" => 4,
_ => 1
};
private static int ParseReflex(string value) => value switch
{
"on" or "yes" or "1" => 1,
"boost" or "2" => 2,
_ => 0
};
// no/low/medium/high(/ultra) or the number of the level; an absent key keeps the simulator's default.
private static int ParseLevel(string value, int fallback, int max)
{
if (value.Length == 0)
return fallback;
int level = value switch
{
"low" or "1" => 1,
"medium" or "yes" or "true" or "2" => 2,
"high" or "3" => 3,
"ultra" or "4" => 4,
_ => 0
};
return Math.Min(level, max);
}
private static string LevelToken(int level) => level switch
{
1 => "low",
2 => "medium",
3 => "high",
4 => "ultra",
_ => "no"
};
// As the simulator reads it, but a value it does not know keeps its default (medium) rather than turning the probe off.
private static int ParseCabProbe(string value) => value switch
{
"no" or "false" or "off" or "0" => 0,
"low" or "1" => 1,
"high" or "3" => 3,
_ => 2
};
private static int ParseAmbientOcclusion(string value) => value switch
{
"" => 2,
"yes" or "true" or "1" or "gtao" => 2,
"ssao" => 1,
_ => 0
};
private static bool ParseVolumetricFog(string value) =>
value is not ("analytic" or "old" or "no" or "false" or "0");
private static int ParseFogQuality(string value) => value switch
{
"low" or "1" => 1,
"high" or "3" => 3,
"ultra" or "4" => 4,
_ => 2
};
private static int Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);
private static int SensitivityStep(double mouseScale) =>
(int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5);
/// <summary>
/// Whether the file's own mousescale can stay as it is: one of the old starter's four
/// speeds, and 0.5 or -0.5 after it. Otherwise a save writes the one the starter holds,
/// as every save of the old starter did.
/// </summary>
public static bool MouseScaleStands(string? raw)
{
string[] tokens = (raw ?? "").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
return tokens.Length >= 2 &&
TryParseMouseScale(tokens[0], out double x) &&
Math.Abs(Math.Abs(x) - SimulatorSettings.MouseScaleOf(SimulatorSettings.MouseLevelOf(x))) < 1e-9 &&
TryParseMouseScale(tokens[1], out double y) &&
Math.Abs(Math.Abs(y) - SimulatorSettings.MouseScaleY) < 1e-9;
}
private static bool TryParseMouseScale(string token, out double scale) =>
double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale) &&
double.IsFinite(scale);
private static double ParseDouble(string s, double fallback) =>
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : fallback;
+14 -4
View File
@@ -6,8 +6,15 @@ using Avalonia;
namespace StarterNG.Infrastructure;
/// <summary>
/// Drawn by the processor instead of the graphics card, for a machine on which the
/// window comes up empty. Each platform reads only its own options, so both are given.
/// On Windows the processor draws the starter's windows, and each frame is copied into its window
/// 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>
public static class SoftwareRender
{
@@ -27,6 +34,9 @@ public static class SoftwareRender
RenderingMode = new[] { X11RenderingMode.Software }
};
public static AppBuilder ApplyTo(AppBuilder builder) =>
builder.With(Win32Options).With(X11Options);
public static AppBuilder ApplyTo(AppBuilder builder, IEnumerable<string> args)
{
builder.With(Win32Options);
return AskedIn(args) ? builder.With(X11Options) : builder;
}
}
@@ -265,10 +265,14 @@ public sealed class FizPhysicsRepository : IPhysicsRepository
var sb = new StringBuilder();
foreach (string line in text.Split('\n'))
{
// Both kinds the game skips: "68 //MaxLoad" passes one include parameter, not two.
string stripped = line;
int comment = stripped.IndexOf('#');
if (comment >= 0)
stripped = stripped[..comment];
int slashes = stripped.IndexOf("//", StringComparison.Ordinal);
if (slashes >= 0)
stripped = stripped[..slashes];
sb.Append(stripped).Append(' ');
}
+35 -16
View File
@@ -18,6 +18,7 @@ using StarterNG.Infrastructure;
using StarterNG.Views;
using StarterNG.Application;
using StarterNG.Application.Abstractions;
using StarterNG.Domain;
using StarterNG.Domain.Settings;
namespace StarterNG;
@@ -56,6 +57,9 @@ public partial class MainWindow : Window
ExtendClientAreaTitleBarHeightHint = TitleBarHeight;
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.
Resized += (_, e) => FitTopBar(e.ClientSize.Width);
Opened += (_, _) => FitTopBar(ClientSize.Width);
@@ -103,6 +107,9 @@ public partial class MainWindow : Window
AddHandler(KeyDownEvent, OnTabWithNothingFocused, RoutingStrategies.Tunnel);
AppServices.Current.State.Changed += UpdateStartButton;
Views.Settings.AdvancedModeChanged += UpdateStartButton;
// Settings an older starter left are brought into the standard mode, once.
SettingsView.MoveToStandardOnce();
Opened += (_, _) =>
{
@@ -428,7 +435,7 @@ public partial class MainWindow : Window
private bool wantsMaximized()
{
// make sure the window fills the whole screen on gamescope sessions
if (Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP") == "gamescope")
if (GamescopeWindows.Active)
return true;
// catch being launched via Steam Big Picture mode as well
@@ -507,6 +514,15 @@ public partial class MainWindow : Window
return;
}
// The standard mode edits every consist but starts only in one the player drives.
if (!TrainsetDisplay.StartableIn(trainset, AppServices.Current.Settings))
{
startButton.Content = App.Loc[trainset.Decor ? "StartDecor" : "StartAi"];
ToolTip.SetTip(startButton, null);
startButton.IsEnabled = false;
return;
}
bool staffed = HasStartableVehicle(trainset);
startButton.Content = staffed ? App.Loc["Start"] : App.Loc["StartNoStaff"];
ToolTip.SetTip(startButton, staffed ? null : App.Loc["StartNoStaffConfirm"]);
@@ -633,6 +649,9 @@ public partial class MainWindow : Window
// would start a second simulator.
if (_starting || DateTime.UtcNow - _startedUtc < StartCooldown)
return;
// A shortcut starts the same way the button does, and only where the button may.
if (!freeFly && !startButton.IsEnabled)
return;
_starting = true;
try
@@ -682,20 +701,10 @@ public partial class MainWindow : Window
}
/// <summary>
/// The scenery editor, which only some simulator builds have - said up front,
/// since one without it simply does not open it, and it writes to the scenery
/// itself. With none selected there is nothing to write to: the simulator's
/// wizard makes a new one.
/// The scenery editor on the selected scenery; with none selected, the
/// simulator's wizard makes a new one.
/// </summary>
private async Task LaunchEditorAsync()
{
if (AppServices.Current.State.CurrentScenery is { } scenery &&
!await MessageBox.Show(this, string.Format(App.Loc["StartEditorWarning"], Path.GetFileName(scenery.Path)),
App.Loc["StartEditor"], MessageBoxButtons.YesNo))
return;
await FollowStartAsync(AppServices.Current.StartSimulation.ExecuteEditor);
}
private Task LaunchEditorAsync() => FollowStartAsync(AppServices.Current.StartSimulation.ExecuteEditor);
/// <summary>Reports a start that failed, or steps aside for the simulator that started.</summary>
/// <param name="start">The start, run again once what stopped it is put right.</param>
@@ -794,6 +803,16 @@ public partial class MainWindow : Window
if (!exit.Failed)
return;
bool throughStarter = string.Equals(Path.GetFileName(executable),
Infrastructure.Settings.ExecutableLocator.WindowsStarterName,
StringComparison.OrdinalIgnoreCase);
if (exit.AlreadyExplained(throughStarter, AppServices.Current.Aftermath.SimulatorRanSince(startedUtc)))
{
Diagnostics.Log($"The simulator ended with {exit.DescribeCode()}, already explained to the player" +
(throughStarter ? $" (started through {Path.GetFileName(executable)})" : ""));
return;
}
var words = exit.CleanErrors.Count > 0
? exit.CleanErrors
: AppServices.Current.Aftermath.SimulatorLogTail(12, startedUtc);
@@ -829,7 +848,7 @@ public partial class MainWindow : Window
{
if (_askingAboutSettings || (DateTime.UtcNow - _openedUtc).TotalSeconds < 3)
return;
if (!AppServices.Current.SettingsStore.IsConfigNewerOnDisk())
if (!AppServices.Current.SettingsStore.HasChangeOnDiskToAskAbout())
return;
_askingAboutSettings = true;
@@ -846,7 +865,7 @@ public partial class MainWindow : Window
SettingsView?.ReloadFromSettings();
}
else
AppServices.Current.SettingsStore.TouchConfigAge();
AppServices.Current.SettingsStore.LeaveChangeOnDisk();
}
finally
{
+7 -5
View File
@@ -10,7 +10,8 @@ namespace StarterNG;
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]
public static void Main(string[] args)
@@ -19,7 +20,7 @@ static class Program
var graphics = SystemGraphicsLibraries.TakeOnWindows();
graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly);
_softwareRender = SoftwareRender.AskedIn(args);
_args = args;
// Composition root first: everything below, including the crash handlers,
// resolves its collaborators from this graph.
@@ -73,13 +74,14 @@ static class Program
};
}
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder;
// On Windows the processor draws; on X11 the graphics card, unless --software-render.
private static AppBuilder WithSoftwareRender(this AppBuilder builder) =>
SoftwareRender.ApplyTo(builder, _args);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithSoftwareRenderIfAsked()
.WithSoftwareRender()
.WithInterFont()
.WithDiagnosticsLogging()
.AfterSetup(_ => LogUiExceptions());
+3 -1
View File
@@ -4,9 +4,11 @@
<PublishAot>true</PublishAot>
<PublishTrimmed>true</PublishTrimmed>
<IsAotCompatible>true</IsAotCompatible>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<!-- DXGI is asked through function pointers, which NativeAOT compiles without reflection. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>Assets\starter.ico</ApplicationIcon>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
+11 -24
View File
@@ -81,15 +81,13 @@
TextWrapping="Wrap"
Margin="0,3,0,0" />
<!-- Why the chosen simulator would ignore the setting. Under
the explanation, at full strength while the rest dims. -->
<TextBlock Name="PART_IdleNote"
<!-- A value of eu07.ini the starter cannot read: amber, as the other warnings. -->
<TextBlock Name="PART_Unknown"
Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2"
Text="{TemplateBinding IdleNote}"
Text="{TemplateBinding UnknownValue}"
IsVisible="False"
FontSize="12"
FontStyle="Italic"
Foreground="{StaticResource CarbonFg}"
Foreground="#D9A43A"
TextWrapping="Wrap"
Margin="0,3,0,0" />
@@ -103,6 +101,13 @@
<Style Selector="^:no-key /template/ SelectableTextBlock#PART_ConfigKey">
<Setter Property="IsVisible" Value="False" />
</Style>
<!-- The standard mode: the eu07.ini key means nothing to a player. -->
<Style Selector="^.HideKey /template/ SelectableTextBlock#PART_ConfigKey">
<Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="^:unknown /template/ TextBlock#PART_Unknown">
<Setter Property="IsVisible" Value="True" />
</Style>
<Style Selector="^:no-value /template/ TextBlock#PART_Value">
<Setter Property="IsVisible" Value="False" />
</Style>
@@ -113,24 +118,6 @@
<Setter Property="Grid.Column" Value="1" />
<Setter Property="Grid.ColumnSpan" Value="2" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_IdleNote">
<Setter Property="IsVisible" Value="True" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_Label">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ ContentPresenter#PART_Content">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_Value">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ TextBlock#PART_Description">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="^:idle /template/ SelectableTextBlock#PART_ConfigKey">
<Setter Property="Opacity" Value="0.45" />
</Style>
<!-- A checkbox is its own label, so let it take the label column too.
Alignment stays Stretch: a bare slider in a labelless row still
wants the full width. -->
+2 -1
View File
@@ -137,7 +137,8 @@
HorizontalContentAlignment="Center"
Click="AddToWarehouseButton_OnClick"
Content="{Binding [AddToWarehouse], Source={x:Static starterNg:App.Loc}}" />
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Spacing="16"
<!-- The advanced mode's own: the standard mode lists every consist with vehicles. -->
<StackPanel Name="consistFilters" DockPanel.Dock="Bottom" Orientation="Horizontal" Spacing="16"
Margin="2,6,0,0">
<CheckBox Name="depotDrivableOnlyCheck" FontSize="12"
IsCheckedChanged="ConsistFilter_OnChanged"
+38 -16
View File
@@ -69,6 +69,13 @@ public partial class Depot : UserControl
if (Design.IsDesignMode)
return;
// The standard mode lists other consists and leaves the crew of the simulator's own alone.
Settings.AdvancedModeChanged += () =>
{
PopulateSceneryConsists();
RebuildConsist();
};
_warehouse = new Warehouse(warehouseList, removeFromWarehouseButton, _hand,
() => AppServices.Current.State.CurrentTrainset, ApplyFromWarehouse);
_warehouse.SelectionChanged += () =>
@@ -77,6 +84,7 @@ public partial class Depot : UserControl
EditWarehouseSelection();
};
_warehouse.Renamed += _warehouseEdit.Renamed;
_warehouseEdit.Saved += _warehouse.RefreshEntry;
_browser = new VehicleBrowser(categoryCombo, classCombo, vehicleListBox, searchBox,
hideArchivalCheck, miniPreview, addVehicleButton, _db, _minis, OpenVehicleBase)
@@ -597,6 +605,7 @@ public partial class Depot : UserControl
depotShowAiCheck.IsChecked = AppServices.Current.Settings.ShowAiVehicles;
depotDrivableOnlyCheck.IsChecked = AppServices.Current.Settings.DrivableOnly;
consistFilters.IsVisible = AppServices.Current.Settings.AdvancedSettings;
_listScenery = AppServices.Current.State.CurrentScenery ?? _sceneries.FirstOrDefault();
sceneryConsistsTab.Header = App.Loc["SceneryConsists"];
@@ -605,12 +614,11 @@ public partial class Depot : UserControl
if (_listScenery != null)
{
bool showAi = AppServices.Current.Settings.ShowAiVehicles;
bool drivableOnly = AppServices.Current.Settings.DrivableOnly;
var settings = AppServices.Current.Settings;
foreach (var trainset in _listScenery.Trainsets)
{
if (!TrainsetDisplay.ListedIn(trainset, showAi, drivableOnly, AppServices.Current.State.CurrentTrainset))
if (!TrainsetDisplay.ListedIn(trainset, settings, AppServices.Current.State.CurrentTrainset))
continue;
var entry = new ListBoxItem
@@ -754,17 +762,29 @@ public partial class Depot : UserControl
if (scenery.Trainsets.Count == 0) return;
if (await AskTextureRandomizerOpts() is not { } opts) return;
var editing = _consist.EditingTrainset;
// Each consist goes through a consist of its own, off the screen: the strip and the
// list are drawn again once at the end, not for every consist on the way, and one
// randomizer looks the candidates up for all of them.
var work = new Consist(_db, _info);
var rnd = TextureRandomizer(opts);
var changed = new HashSet<Trainset>(ReferenceEqualityComparer.Instance);
foreach (var trainset in scenery.Trainsets)
{
_consist.LoadFrom(trainset);
if (ApplyTextureRandomizer(opts))
WriteBackToScenery();
work.LoadFrom(trainset);
if (work.Count == 0 || rnd.Apply(work, texture => work.MakeDynamic(texture, scenery)) <= 0)
continue;
work.AutoConnectAll();
trainset.Vehicles = work.Flatten();
changed.Add(trainset);
}
if (changed.Count == 0)
return;
if (editing != null)
if (_consist.EditingTrainset is { } editing && changed.Contains(editing))
_consist.LoadFrom(editing);
RebuildConsist();
RefreshConsistListLabels();
if (AppServices.Current.State.CurrentTrainset is { } current && changed.Contains(current))
AppServices.Current.State.NotifyChanged();
}
private async Task<TextureRandomizerDialog.Options?> AskTextureRandomizerOpts() =>
@@ -776,19 +796,21 @@ public partial class Depot : UserControl
{
if (_consist.Count == 0) return false;
var rnd = new TexRandomizer(_db, _rng)
{
WithoutArchival = opts.WithoutArchival,
RevisionTolerance = opts.RevisionTolerance,
RevYear = opts.RevYear
};
if (rnd.Apply(_consist, NewVehicle) <= 0)
if (TextureRandomizer(opts).Apply(_consist, NewVehicle) <= 0)
return false;
_consist.AutoConnectAll();
return true;
}
private TexRandomizer TextureRandomizer(TextureRandomizerDialog.Options opts) =>
new(_db, _rng)
{
WithoutArchival = opts.WithoutArchival,
RevisionTolerance = opts.RevisionTolerance,
RevYear = opts.RevYear
};
private void RandomOrderButton_OnClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e) =>
_consist.RandomizeOrder(_rng);
+18 -9
View File
@@ -4,6 +4,7 @@ using System.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
@@ -536,8 +537,21 @@ public sealed class VehicleBrowser
// mostly by who runs them.
private static Control BrowserLabel(VehicleTexture texture, IReadOnlyList<VehicleTexture>? set)
{
// Clear of the scroll bar, which lies over the right edge of the list.
var row = new DockPanel { Margin = new Thickness(0, 0, 10, 0) };
// Clear of the scroll bar, which lies over the right edge of the list. The name comes
// first: a long operator is cut short to a width of its own, and either ends in "…"
// rather than running into the other.
var row = new Grid { Margin = new Thickness(0, 0, 10, 0), ColumnDefinitions = new ColumnDefinitions("*,Auto") };
var name = new TextBlock { TextTrimming = TextTrimming.CharacterEllipsis };
name.Inlines!.Add(new Run(BrowserName(texture)));
if (set is { Count: > 1 })
{
var count = new Run($" ×{set.Count}");
if (Avalonia.Application.Current?.TryGetResource("CarbonFgDim", null, out var dim) == true && dim is IBrush brush)
count.Foreground = brush;
name.Inlines.Add(count);
}
row.Children.Add(name);
string? op = texture.Meta?.Operator;
if (!string.IsNullOrWhiteSpace(op) && op != "?")
@@ -546,19 +560,14 @@ public sealed class VehicleBrowser
{
Text = op,
Opacity = 0.55,
MaxWidth = 110,
Margin = new Thickness(8, 0, 0, 0),
TextTrimming = TextTrimming.CharacterEllipsis
};
DockPanel.SetDock(operatorText, Dock.Right);
Grid.SetColumn(operatorText, 1);
row.Children.Add(operatorText);
}
var name = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
name.Children.Add(new TextBlock { Text = BrowserName(texture) });
if (set is { Count: > 1 })
name.Children.Add(new TextBlock { Text = $"×{set.Count}", Opacity = 0.55 });
row.Children.Add(name);
return row;
}
+14 -5
View File
@@ -1,4 +1,5 @@
using System;
using StarterNG.Application;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
@@ -48,6 +49,9 @@ public sealed class VehicleCards
public Dynamic? PressedCar { get; set; }
private bool CrewEditable =>
TrainsetDisplay.CrewEditableIn(_consist.EditingTrainset, AppServices.Current.Settings);
public VehicleCards(Panel consistStack, VehicleCatalog db, Consist consist,
Cargo cargo, MiniTextures minis, Cursor hand,
Action redraw, Action refreshDetails, Action<Dynamic> selectInBrowser,
@@ -116,7 +120,9 @@ public sealed class VehicleCards
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 1, 0, 2)
};
controls.Children.Add(DriverButton(item));
// Who sits in the cab; in the standard mode not in the simulator's own consists.
if (CrewEditable)
controls.Children.Add(DriverButton(item));
controls.Children.Add(FlipButton(item));
if (item.Grouped && item.Cars.Count > 1)
@@ -692,10 +698,13 @@ public sealed class VehicleCards
else if (_consist.CanJoin(item, index))
menu.AddItem(App.Loc["TipJoin"], () => _consist.Join(item));
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
foreach (var (type, key) in CrewChoices.All)
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
menu.Items.Add(crew);
if (CrewEditable)
{
var crew = new MenuItem { Header = App.Loc["CrewLabel"] };
foreach (var (type, key) in CrewChoices.All)
crew.Items.Add(MenuItems.Choice(App.Loc[key], item.Driver == type, () => _consist.SetCrew(item, type)));
menu.Items.Add(crew);
}
// The member the panels show, not always the first car of a unit.
menu.AddItem(App.Loc["WagonNumber"] + "…",
+2
View File
@@ -280,6 +280,8 @@ public sealed class VehicleDetails
};
driver.MinWidth = 0;
driver.HorizontalAlignment = HorizontalAlignment.Stretch;
// Shown but not changed in the standard mode in the simulator's own consists.
driver.IsEnabled = TrainsetDisplay.CrewEditableIn(_consist.EditingTrainset, AppServices.Current.Settings);
var rows = new StackPanel();
rows.Children.Add(Row(App.Loc["CrewLabel"], driver));
+43 -5
View File
@@ -62,11 +62,7 @@ public sealed class Warehouse
var entry = new ListBoxItem
{
Tag = preset.Name,
Content = new TextBlock
{
Text = preset.Name,
TextTrimming = TextTrimming.CharacterEllipsis
}
Content = EntryContent(preset.Name, preset.Entry)
};
_list.Items.Add(entry);
if (current is not null && string.Equals(current, preset.Name, StringComparison.Ordinal))
@@ -81,6 +77,48 @@ public sealed class Warehouse
SelectionChanged?.Invoke();
}
/// <summary>
/// The consist's name, and under it its vehicles as minis - as the scenery's consists
/// are listed - so one is told from another without opening it.
/// </summary>
private static Control EntryContent(string presetName, string entry)
{
var name = new TextBlock
{
Text = presetName,
TextTrimming = TextTrimming.CharacterEllipsis
};
if (ConsistText.VehiclesFrom(entry) is not { } vehicles)
return name;
var content = new StackPanel
{
Spacing = 2,
Margin = new Thickness(0, 3),
Children = { name, TrainsetRow.ScrollingStrip(vehicles) }
};
// Read by its name, not by every caption under it.
Avalonia.Automation.AutomationProperties.SetName(content, presetName);
return content;
}
/// <summary>
/// Redraws one consist's entry after it was edited and saved, so its minis follow the
/// edit at once - the rest of the list, its selection and where it is scrolled stay.
/// </summary>
public void RefreshEntry(string name, string entry)
{
foreach (var obj in _list.Items)
{
if (obj is ListBoxItem { Tag: string tag } item &&
string.Equals(tag, name, StringComparison.OrdinalIgnoreCase))
{
item.Content = EntryContent(tag, entry);
return;
}
}
}
private string? SelectedName() => (_list.SelectedItem as ListBoxItem)?.Tag as string;
public TrainsetPreset? SelectedPreset() => SelectedName() is { } name ? PresetNamed(name) : null;
+63
View File
@@ -50,6 +50,69 @@ public static class MessageBox
return yes;
}
/// <summary>
/// A warning to read before saying yes: the yes button counts down and only then
/// takes a click. Enter and Esc both decline, so nothing is agreed to by habit.
/// </summary>
public static async Task<bool> ShowDelayed(Window owner, string message, string title, string yesText,
int seconds)
{
var win = FixedDialog(title, 520);
bool yes = false;
var yesBtn = DialogButton($"{yesText} ({seconds})", "Accent", 120, () => { yes = true; win.Close(); });
var noBtn = DialogButton(App.Loc["Cancel"], "Flat", 80, () => win.Close());
yesBtn.IsEnabled = false;
noBtn.IsDefault = true;
noBtn.IsCancel = true;
ReadMessage(win, noBtn, message);
int left = seconds;
var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += (_, _) =>
{
// Only time spent with the warning in front of the player counts: the window active and all of it on a screen.
if (!win.IsActive || win.WindowState == WindowState.Minimized || !WhollyOnScreen(win))
return;
left--;
if (left > 0)
{
yesBtn.Content = $"{yesText} ({left})";
return;
}
timer.Stop();
yesBtn.Content = yesText;
yesBtn.IsEnabled = true;
};
win.Closed += (_, _) => timer.Stop();
win.Content = new StackPanel
{
Margin = new Avalonia.Thickness(16),
Spacing = 16,
Children =
{
new SelectableTextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
ButtonRow(yesBtn, noBtn)
}
};
timer.Start();
await win.ShowDialog(owner);
return yes;
}
/// <summary>Whether the whole window, frame and all, lies within the working area of one screen.</summary>
internal static bool WhollyOnScreen(Window win)
{
var size = win.FrameSize ?? win.ClientSize;
var rect = new Avalonia.PixelRect(win.Position, Avalonia.PixelSize.FromSize(size, win.RenderScaling));
foreach (var screen in win.Screens.All)
if (screen.WorkingArea.Contains(rect))
return true;
return false;
}
/// <summary>
/// A question with two answers and a way back: true for the first, false for the second, null when cancelled
/// or the window is closed - closing it never picks one of the answers.
+4 -5
View File
@@ -189,13 +189,12 @@
HorizontalAlignment="Stretch"
SelectionChanged="Weather_OnSelectionChanged">
<ComboBoxItem Tag="random" Content="{Binding [OvercastRandom], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="-1.5" Content="{Binding [OvercastClear], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="0" Content="{Binding [OvercastFair], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="0" Content="{Binding [OvercastClear], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="0.3" Content="{Binding [OvercastLight], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="0.7" Content="{Binding [OvercastModerate], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="1" Content="{Binding [OvercastHeavy], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="1.1" Content="{Binding [OvercastCloudy], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="1.5" Content="{Binding [OvercastStorm], Source={x:Static starterNg:App.Loc}}" />
<ComboBoxItem Tag="1" Content="{Binding [OvercastCloudy], Source={x:Static starterNg:App.Loc}}" />
<ctl:PrecipitationItem Tag="1.1" Name="weatherPrecipitationLight" />
<ctl:PrecipitationItem Tag="1.5" Name="weatherPrecipitation" Heavy="True" />
</ComboBox>
<Border Grid.Row="11" Grid.Column="0" Grid.ColumnSpan="5"
+52 -16
View File
@@ -45,6 +45,7 @@ public partial class Scenarios : UserControl
{
InitializeComponent();
SyncConsistRowHeight();
Settings.AdvancedModeChanged += OnAdvancedModeChanged;
Sceneries = AppServices.Current.Library.Sceneries;
@@ -86,6 +87,43 @@ public partial class Scenarios : UserControl
state.StartingVehicleName = vehicle;
}
private void OnAdvancedModeChanged()
{
RefreshVehicleList();
RefreshFaultMarks(sceneryList.Items);
if (SelectedScenery is { } scenery)
PopulateFaults(scenery);
}
/// <summary>
/// The scenery files' mistakes - written wrong, or vehicles the simulator will not
/// find - are for those who mend sceneries: shown in the advanced mode only.
/// </summary>
private static bool ShowsFaults => AppServices.Current.Settings.AdvancedSettings;
// The tree's marks put on or taken off where they stand, the selection and what is
// unfolded kept.
private void RefreshFaultMarks(ItemCollection items)
{
foreach (var obj in items)
{
if (obj is not TreeViewItem node)
continue;
if (node.Tag is int index && index < Sceneries.Count)
{
string? label = node.Header switch
{
string text => text,
StackPanel { Children: [TextBlock name, ..] } => name.Text,
_ => null
};
if (label is not null)
node.Header = SceneryHeader(label, Sceneries[index]);
}
RefreshFaultMarks(node.Items);
}
}
private void BuildSceneryTree()
{
sceneryList.Items.Clear();
@@ -119,7 +157,7 @@ public partial class Scenarios : UserControl
/// <summary>The scenery's name, marked when its files hold mistakes.</summary>
private object SceneryHeader(string label, Scenery scenery)
{
if (scenery.Faults.Count == 0)
if (!ShowsFaults || scenery.Faults.Count == 0)
return label;
var mark = new Material.Icons.Avalonia.MaterialIcon
@@ -290,20 +328,13 @@ public partial class Scenarios : UserControl
}
/// <summary>A consist's label in a list of them, here and on the depot page.</summary>
internal static TextBlock TrainsetListContent(Trainset trainset) =>
new Avalonia.Controls.TextBlock
{
Text = TrainsetDisplay.ListLabel(trainset),
TextTrimming = Avalonia.Media.TextTrimming.CharacterEllipsis,
TextWrapping = Avalonia.Media.TextWrapping.NoWrap
};
internal static Control TrainsetListContent(Trainset trainset) => TrainsetRow.Build(trainset);
private void PopulateVehicleList(Scenery scn)
{
vehicleList.Items.Clear();
bool showAi = AppServices.Current.Settings.ShowAiVehicles;
bool drivableOnly = AppServices.Current.Settings.DrivableOnly;
var settings = AppServices.Current.Settings;
var current = AppServices.Current.State.CurrentTrainset;
ListBoxItem? currentRow = null;
@@ -311,7 +342,7 @@ public partial class Scenarios : UserControl
{
var trainset = scn.Trainsets[i];
if (!TrainsetDisplay.ListedIn(trainset, showAi, drivableOnly, current)) continue;
if (!TrainsetDisplay.ListedIn(trainset, settings, current)) continue;
var listItem = new ListBoxItem
{
@@ -474,8 +505,9 @@ public partial class Scenarios : UserControl
private void PopulateFaults(Scenery scenery)
{
var faults = scenery.Faults;
faultsTab.IsVisible = faults.Count > 0;
if (faults.Count == 0)
bool shown = ShowsFaults && faults.Count > 0;
faultsTab.IsVisible = shown;
if (!shown)
{
if (infoTabs.SelectedItem == faultsTab)
infoTabs.SelectedIndex = 0;
@@ -799,6 +831,7 @@ public partial class Scenarios : UserControl
weatherTemp.ValueText = weatherTempLabel.Text;
weatherFog.ValueText = weatherFogLabel.Text;
weatherDayDate.Text = string.Format(LanguageCulture, App.Loc["DayOfYear"], SelectedDayOfYear());
weatherPrecipitationLight.Snow = weatherPrecipitation.Snow = SceneryWeather.Snows(weatherTemp.Value);
weatherRestore.IsEnabled = _currentScenery?.Weather.Changed ?? false;
}
@@ -1048,6 +1081,11 @@ public partial class Scenarios : UserControl
});
var db = AppServices.Current.Library.Vehicles;
// The start goes by the vehicle's name, so of several named alike only the first is the one marked.
string? picked = AppServices.Current.State.StartingVehicleName;
var pickedVehicle = string.IsNullOrEmpty(picked)
? null
: trainset.Vehicles.FirstOrDefault(v => string.Equals(v.Name, picked, StringComparison.OrdinalIgnoreCase));
foreach (var train in trainset.Vehicles)
{
@@ -1069,9 +1107,7 @@ public partial class Scenarios : UserControl
})
: MiniTextures.MissingVisual(train.SkinFile, thumbH);
bool selected = !string.IsNullOrEmpty(train.Name) &&
string.Equals(train.Name, AppServices.Current.State.StartingVehicleName,
StringComparison.OrdinalIgnoreCase);
bool selected = ReferenceEquals(train, pickedVehicle);
// The vehicle started in gets a frame over its picture as well as the lines above and below:
// two thin lines alone were hard to see. Drawn over the picture, it moves no vehicle aside.
if (selected)
-115
View File
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using StarterNG.Domain.Settings;
@@ -24,54 +23,8 @@ internal static class SettingTexts
public static string Anisotropy(double value) => "x" + value.ToString("0.#", CultureInfo.CurrentCulture);
public static string AntiAliasing(AntiAliasingMode mode) => mode switch
{
AntiAliasingMode.Msaa2 => "MSAA x2",
AntiAliasingMode.Msaa4 => "MSAA x4",
AntiAliasingMode.Msaa8 => "MSAA x8",
AntiAliasingMode.Taa => App.Loc["AaTaa"],
AntiAliasingMode.Dlss => App.Loc["AaDlss"],
AntiAliasingMode.Dlaa => App.Loc["AaDlaa"],
_ => App.Loc["MsaaNone"]
};
private static string Level(int level) => App.Loc[level switch
{
1 => "LevelLow",
2 => "LevelMedium",
3 => "LevelHigh",
4 => "LevelUltra",
_ => "LevelOff"
}];
public static string TwoDecimals(double value) => value.ToString("0.00", CultureInfo.CurrentCulture);
public static string ShadowMapWord(int pixels) => pixels switch
{
<= 512 => App.Loc["QualityVeryLow"],
<= 1024 => App.Loc["QualityLow"],
<= 2048 => App.Loc["QualityModerate"],
<= 4096 => App.Loc["QualityHigh"],
_ => App.Loc["QualityVeryHigh"]
};
public static string ShadowRangeWord(int metres) => metres switch
{
<= 100 => App.Loc["RangeLow"],
<= 150 => App.Loc["RangeModerate"],
<= 250 => App.Loc["RangeHigh"],
_ => App.Loc["RangeVeryHigh"]
};
public static string CabShadowRangeWord(int metres) => metres switch
{
<= 10 => App.Loc["RangeVeryLow"],
<= 20 => App.Loc["RangeLow"],
<= 30 => App.Loc["RangeStandard"],
<= 50 => App.Loc["RangeHigh"],
_ => App.Loc["RangeVeryHigh"]
};
/// <summary>A rate below one a second reads better as the time between updates.</summary>
public static string ReflectionsInterval(double perSecond)
{
@@ -82,72 +35,4 @@ internal static class SettingTexts
? string.Format(App.Loc["EveryMinutes"], (seconds / 60).ToString("0.#", CultureInfo.CurrentCulture))
: string.Format(App.Loc["EverySeconds"], seconds.ToString("0.#", CultureInfo.CurrentCulture));
}
/// <summary>What a level sets, in the words and the units of the rows it sets.</summary>
public static string PresetSummary(GraphicsPreset p)
{
var lines = new List<string>();
void Add(string label, string value) => lines.Add(App.Loc[label] + ": " + value);
string YesNo(bool on) => App.Loc[on ? "Yes" : "No"];
string Whole(double value) => value.ToString("0.#", CultureInfo.CurrentCulture);
Add("MaxTexResolution", p.TextureSize + " px");
Add("MaxTexCabResolution", p.CabTextureSize + " px");
Add("TexFilteringQuality", Anisotropy(p.Anisotropy));
Add("AntiAliasing", AntiAliasing(p.AntiAliasing));
Add("DynamicLights", p.DynamicLights.ToString(CultureInfo.CurrentCulture));
Add("SmokeParticlesMultiplier", Fidelity(p.SmokeFidelity));
Add("RenderShadows", YesNo(p.Shadows));
if (p.Shadows)
{
Add("ShadowsResolution", p.ShadowMap + " px");
Add("ShaderRange", SimulatorSettings.ShadowReach(p.ShadowRange, p.ShadowMap, legacyRenderer: false) + " m");
Add("ShadowDisplay", App.Loc[p.ShadowRank switch { 1 => "CSROnlyImportant", 2 => "CSRLimited", _ => "CSRAll" }]);
}
Add("ReflectionsCubeMap", YesNo(p.EnvMap));
if (p.EnvMap)
{
Add("ReflectionsDetails", App.Loc[p.ReflectionsFidelity switch { 0 => "RDTerrain", 1 => "RDTerrainModels", _ => "RDTerrainModelsVehicles" }]);
Add("ReflectionsFramerate", ReflectionsInterval(p.ReflectionsRate));
}
Add("AdditionalShadersEffects", YesNo(p.ExtraEffects));
Add("TrackCurvesQuality", Fidelity(p.SplineFidelity));
Add("Ini.basedrawrange", Whole(p.DrawRange) + " m");
Add("Ini.heightbase", "×" + p.DistanceFactor.ToString("0.##", CultureInfo.CurrentCulture));
Add("BufforResolution", p.BufferScale + "%");
Add("Ini." + GraphicsPreset.SleeperKey, Whole(p.SleeperDistance) + " m");
Add("RenderRange", "×" + Whole(p.DrawRangeFactor));
Add("Ini." + GraphicsPreset.ReflectedInstancesKey, Whole(p.ReflectedInstances) + " m");
Add("Ini." + GraphicsPreset.ReflectedVehiclesKey, Whole(p.ReflectedVehicles) + " m");
var renderer = p.NewRenderer;
Add("LightShadows", Level(renderer.LampShadows));
Add("ContactShadows", Level(renderer.ContactShadows));
Add("AmbientOcclusion", renderer.Occlusion switch { 1 => "SSAO", 2 => "GTAO", _ => App.Loc["LevelOff"] });
Add("CabProbe", Level(renderer.CabProbe));
Add("Ssr", Level(renderer.ScreenReflections));
Add("RayTracing", YesNo(renderer.RayTracing));
Add("VolumetricFog", renderer.VolumetricFog ? Level(renderer.FogQuality) : App.Loc["No"]);
Add("Clouds", Level(renderer.Clouds));
Add("Grass", renderer.Grass ? renderer.GrassDistance + " m" : App.Loc["No"]);
Add("Bloom", YesNo(renderer.Bloom));
if (p.Extras is { } extras)
{
Add("MotionBlur", YesNo(extras.MotionBlur));
Add("ChromaticAberration", YesNo(extras.ChromaticAberration));
Add("SmokeDisplay", YesNo(extras.Smoke));
Add("PyScreenPriority", App.Loc[extras.PythonUpdateMs <= 200 ? "PyPriorityNormal" : "PyPriorityLowest"]);
}
if (p.Top is { } top)
{
lines.Insert(0, App.Loc["PresetUltraNote"]);
Add("ShadowAngleLimit", TwoDecimals(top.ShadowAngleLimit));
Add("Ini." + GraphicsTop.TargetFpsKey, YesNo(top.TargetFps > 0));
Add("Ini." + GraphicsTop.TextureReleaseKey, YesNo(top.TextureRelease > 0));
Add("CompressTextures", YesNo(top.CompressTextures));
Add("IgnoreIrrelevantTrains", YesNo(top.SkipDecor));
}
return string.Join("\n", lines);
}
}
+122 -247
View File
@@ -2,18 +2,18 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using StarterNG.Application;
using StarterNG.Domain.Settings;
using StarterNG.Infrastructure;
using StarterNG.Infrastructure.Settings;
namespace StarterNG.Views;
// What the graphics and effects categories add to the screen: the controls of the settings the
// new renderers read, the dependencies between them (what the simulator only does on Vulkan,
// with DLSS, ...), and the import and export of eu07.ini.
// What the graphics and effects categories add to the screen: the renderer and the
// anti-aliasing, and the import and export of eu07.ini.
public partial class Settings
{
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
@@ -24,264 +24,148 @@ public partial class Settings
new("*") { Patterns = new[] { "*" } }
};
/// <summary>Set while the dependencies are brought in line, so the changes they make do not recurse.</summary>
private bool _updatingGraphics;
/// <summary>
/// What only Vulkan has, as it was when OpenGL got chosen, so that going back to
/// Vulkan brings it back instead of leaving it switched off.
/// </summary>
private (AntiAliasingMode AntiAliasing, int FrameGeneration, int Reflex, bool RayTracing)? _vulkanChoices;
private string? _dlssProbedFor;
private (bool Dlss, bool FrameGeneration) _dlssProbe;
private static bool DlssPlatform => AppServices.Current.SettingsStore.DlssPlatform;
private void InitGraphics()
{
// The notes are worked out here, not bound, so they follow a change of language by hand.
App.Loc.LanguageChanged += UpdateGraphicsState;
SelectExeCb.SelectionChanged += (_, _) => UpdateGraphicsState();
}
private void ShowGraphics(SimulatorSettings s)
{
RenderEngineCb.SelectedIndex = s.RenderEngine;
VulkanDeviceTb.Text = s.VulkanDevice;
ShowRenderer(s);
SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing));
SelectTag(DlssPresetCb, s.DlssPreset);
SelectTag(FrameGenerationCb, s.FrameGeneration.ToString(Invariant));
SelectTag(ReflexCb, s.Reflex.ToString(Invariant));
ShadowSdsmCb.IsChecked = s.ShadowSdsm;
LightsClusteredCb.IsChecked = s.LightsClustered;
SelectTag(LightShadowsCb, s.LightShadows.ToString(Invariant));
SelectTag(ContactShadowsCb, s.ContactShadows.ToString(Invariant));
SelectTag(AmbientOcclusionCb, s.AmbientOcclusion.ToString(Invariant));
SelectOrAddTag(AoQualityCb, $"{s.AoSlices} {s.AoSteps}", $"{s.AoSlices} / {s.AoSteps}");
AoLightingCb.IsChecked = s.AoLighting;
SelectTag(CabProbeCb, s.CabProbe.ToString(Invariant));
CabProbeIntervalNud.Value = s.CabProbeInterval;
CabProbeBounceSlider.Value = s.CabProbeBounce;
CabProbeReflectionsCb.IsChecked = s.CabProbeReflections;
SelectTag(SsrCb, s.Ssr.ToString(Invariant));
RayTracingCb.IsChecked = s.RayTracing;
RayTracingRangeSlider.Value = s.RayTracingRange;
VolumetricFogCb.IsChecked = s.VolumetricFog;
SelectTag(FogQualityCb, s.FogQuality.ToString(Invariant));
SelectTag(CloudsCb, s.Clouds.ToString(Invariant));
CloudShadowsCb.IsChecked = s.CloudShadows;
BloomCb.IsChecked = s.Bloom;
AutoExposureCb.IsChecked = s.AutoExposure;
GrassCb.IsChecked = s.Grass;
GrassDistanceSlider.Value = s.GrassDistance;
GrassDensitySlider.Value = s.GrassDensity;
string particles = s.PrecipitationParticles.ToString(Invariant);
SelectOrAddTag(PrecipitationCb, particles, particles);
_fullscreenAsRead = s.Fullscreen;
SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed));
ShowMonitor(s.FullscreenMonitor);
UpdateDisplayRows();
}
private void CaptureGraphics(SimulatorSettings s)
{
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
s.VulkanDevice = VulkanDeviceTb.Text?.Trim() ?? "";
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
s.DlssPreset = SelectedTag(DlssPresetCb) ?? "default";
s.FrameGeneration = TagInt(FrameGenerationCb, 1);
s.Reflex = TagInt(ReflexCb, 0);
if (_fileRendererItem is not null && ReferenceEquals(RenderEngineCb.SelectedItem, _fileRendererItem))
{
s.RendererWord = _fileRendererItem.Tag as string;
}
else
{
s.Backend = SelectedBackend();
s.RendererWord = null;
}
if (!ShowsFileValue(AntiAliasingCb))
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
s.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty;
s.ShadowSdsm = IsChecked(ShadowSdsmCb);
s.LightsClustered = IsChecked(LightsClusteredCb);
s.LightShadows = TagInt(LightShadowsCb, 2);
s.ContactShadows = TagInt(ContactShadowsCb, 0);
s.AmbientOcclusion = TagInt(AmbientOcclusionCb, 2);
var ao = (SelectedTag(AoQualityCb) ?? "3 4").Split(' ');
s.AoSlices = ao.Length > 0 && int.TryParse(ao[0], NumberStyles.Integer, Invariant, out int slices) ? slices : 3;
s.AoSteps = ao.Length > 1 && int.TryParse(ao[1], NumberStyles.Integer, Invariant, out int steps) ? steps : 4;
s.AoLighting = IsChecked(AoLightingCb);
s.CabProbe = TagInt(CabProbeCb, 2);
s.CabProbeInterval = (int)(CabProbeIntervalNud.Value ?? 4);
s.CabProbeBounce = CabProbeBounceSlider.Value;
s.CabProbeReflections = IsChecked(CabProbeReflectionsCb);
s.Ssr = TagInt(SsrCb, 2);
s.RayTracing = IsChecked(RayTracingCb);
s.RayTracingRange = (int)RayTracingRangeSlider.Value;
s.VolumetricFog = IsChecked(VolumetricFogCb);
s.FogQuality = TagInt(FogQualityCb, 2);
s.Clouds = TagInt(CloudsCb, 2);
s.CloudShadows = IsChecked(CloudShadowsCb);
s.Bloom = IsChecked(BloomCb);
s.AutoExposure = IsChecked(AutoExposureCb);
s.Grass = IsChecked(GrassCb);
s.GrassDistance = (int)GrassDistanceSlider.Value;
s.GrassDensity = GrassDensitySlider.Value;
s.PrecipitationParticles = TagInt(PrecipitationCb, 65536);
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
s.FullscreenWindowed = mode == BorderlessMode;
// Borderless overrides fullscreen in the simulator, so the file's own word for it stays.
s.Fullscreen = mode == BorderlessMode ? _fullscreenAsRead : mode == FullscreenMode;
}
private void OnBackendChanged()
/// <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 (_loading || _updatingGraphics)
return;
_updatingGraphics = true;
try
if (_fileRendererItem is not null)
{
if (!SettingReach.IsVulkan(SelectedRenderer()))
if (s.RendererWord is not null && Equals(_fileRendererItem.Tag, s.RendererWord))
{
var s = Trial();
_vulkanChoices ??= (s.AntiAliasing, s.FrameGeneration, s.Reflex, s.RayTracing);
if (GraphicsRules.IsDlss(s.AntiAliasing))
SelectTag(AntiAliasingCb, "taa");
FrameGenerationCb.SelectedIndex = 0;
ReflexCb.SelectedIndex = 0;
RayTracingCb.IsChecked = false;
RenderEngineCb.SelectedItem = _fileRendererItem;
return;
}
else if (_vulkanChoices is { } kept)
{
if (GraphicsRules.IsDlss(kept.AntiAliasing) && DlssPlatform && SelectedTag(AntiAliasingCb) == "taa")
SelectTag(AntiAliasingCb, AntiAliasingTag(kept.AntiAliasing));
SelectTag(FrameGenerationCb, kept.FrameGeneration.ToString(Invariant));
SelectTag(ReflexCb, kept.Reflex.ToString(Invariant));
RayTracingCb.IsChecked = kept.RayTracing;
_vulkanChoices = null;
}
}
finally
{
_updatingGraphics = false;
RenderEngineCb.Items.Remove(_fileRendererItem);
_fileRendererItem = null;
}
UpdateGraphicsState();
if (s.RendererWord is { } word)
{
_fileRendererItem = new ComboBoxItem { Tag = word, Content = word };
RenderEngineCb.Items.Add(_fileRendererItem);
RenderEngineCb.SelectedItem = _fileRendererItem;
}
else
SelectTag(RenderEngineCb, SimulatorSettings.WordOf(s.Backend));
}
// ── How the simulator shows: full screen, borderless or in a window ──────
private const string FullscreenMode = "fullscreen";
private const string BorderlessMode = "borderless";
private const string WindowMode = "window";
/// <summary>fullscreen as the file has it, kept where borderless makes it of no account.</summary>
private bool _fullscreenAsRead;
/// <summary>
/// The mode the two keys make (application.cpp): fullscreenwindowed takes the monitor's
/// own size and turns full screen on whatever fullscreen says.
/// </summary>
private static string DisplayModeOf(bool fullscreen, bool windowed) =>
windowed ? BorderlessMode : fullscreen ? FullscreenMode : WindowMode;
/// <summary>A borderless screen takes the monitor's size; a window can't be put on a monitor.</summary>
private void UpdateDisplayRows()
{
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
Dim(ResolutionRow, mode == BorderlessMode);
Dim(MonitorRow, mode == WindowMode);
}
/// <summary>The whole row greyed out, its label and description too, as a disabled check box is.</summary>
private static void Dim(Control row, bool off)
{
row.IsEnabled = !off;
row.Opacity = off ? 0.45 : 1;
}
private ComboBoxItem? _primaryMonitorItem;
private IReadOnlyList<DisplayMonitor>? _monitors;
/// <summary>The monitors attached, read once.</summary>
private IReadOnlyList<DisplayMonitor> MonitorList => _monitors ??= Monitors.List(AppServices.Current.Environment);
/// <summary>
/// The monitor the simulator will show on (application.cpp): a full screen, borderless or
/// not, goes to the one chosen, or the primary one when that is not connected; a window
/// opens where the system puts it, as a rule the primary one. Null where no monitor could be read.
/// </summary>
private DisplayMonitor? SimulatorMonitor()
{
string? chosen = SelectedTag(DisplayModeCb) == WindowMode ? null : SelectedTag(MonitorCb);
DisplayMonitor? primary = null;
foreach (var m in MonitorList)
{
if (!string.IsNullOrEmpty(chosen) && m.Id == chosen)
return m;
if (m.Primary)
primary ??= m;
}
return primary;
}
/// <summary>
/// Brings the graphics controls in line with one another the way the simulator
/// treats them, and says why something is off.
/// The monitors found, listed once, with the primary one first; a monitor the file names
/// that is not connected now stays on the list under its own name.
/// </summary>
private void UpdateGraphicsState()
private void ShowMonitor(string id)
{
if (!_built || _loading || _updatingGraphics)
return;
_updatingGraphics = true;
try
if (_primaryMonitorItem is null)
{
var s = Trial();
bool vulkan = GraphicsRules.IsVulkan(s);
bool dlssAllowed = GraphicsRules.DlssAllowed(s, DlssPlatform);
foreach (var item in AntiAliasingCb.Items.OfType<ComboBoxItem>())
if (item.Tag is "dlss" or "dlaa")
item.IsEnabled = dlssAllowed;
if (GraphicsRules.IsDlss(s.AntiAliasing) && !dlssAllowed)
SelectTag(AntiAliasingCb, "taa");
s = Trial();
bool dlss = GraphicsRules.DlssActive(s, DlssPlatform);
DlssPresetRow.IsEnabled = dlss;
FrameGenerationRow.IsEnabled = dlss;
if (!dlss && FrameGenerationCb.SelectedIndex > 0)
FrameGenerationCb.SelectedIndex = 0;
ReflexRow.IsEnabled = vulkan;
if (!vulkan && ReflexCb.SelectedIndex > 0)
ReflexCb.SelectedIndex = 0;
VulkanDeviceRow.IsEnabled = vulkan;
RayTracingRow.IsEnabled = vulkan;
if (!vulkan)
RayTracingCb.IsChecked = false;
s = Trial();
BufferScaleRow.IsEnabled = GraphicsRules.BufferScaleUsed(s, DlssPlatform);
RayTracingRangeRow.IsEnabled = vulkan && s.RayTracing;
DynamicLightsRow.IsEnabled = GraphicsRules.DynamicLightsUsed(s);
AoQualityRow.IsEnabled = s.AmbientOcclusion > 0;
AoLightingRow.IsEnabled = GraphicsRules.AoLightingUsed(s);
bool probe = GraphicsRules.CabProbeUsed(s);
CabProbeIntervalRow.IsEnabled = probe;
CabProbeReflectionsRow.IsEnabled = probe;
CabProbeBounceRow.IsEnabled = GraphicsRules.CabProbeLights(s);
FogQualityRow.IsEnabled = s.VolumetricFog;
CloudShadowsRow.IsEnabled = s.Clouds > 0;
GrassDistanceRow.IsEnabled = s.Grass;
GrassDensityRow.IsEnabled = s.Grass;
DlssPresetInfo.Text = App.Loc[(SelectedTag(DlssPresetCb) ?? "default") switch
_primaryMonitorItem = new ComboBoxItem { Tag = string.Empty, Content = App.Loc["MonitorPrimary"] };
App.Loc.LanguageChanged += () => _primaryMonitorItem.Content = App.Loc["MonitorPrimary"];
MonitorCb.Items.Add(_primaryMonitorItem);
var monitors = MonitorList;
for (int i = 0; i < monitors.Count; i++)
{
"k" => "DlssPresetInfoK",
"j" => "DlssPresetInfoJ",
"m" => "DlssPresetInfoM",
"l" => "DlssPresetInfoL",
_ => "DlssPresetInfoDefault"
}];
SetNote(RenderEngineNote, App.Loc[vulkan ? "REVulkanNote" : "REOpenGLNote"]);
SetNote(AntiAliasingNote, AntiAliasingRemark(s, dlss));
SetNote(FrameGenerationNote, FrameGenerationRemark(s, dlss));
SetNote(ReflexNote, GraphicsRules.ReflexForced(s, DlssPlatform) ? App.Loc["ReflexForcedNote"] : "");
SetNote(AoLightingNote, AoLightingRemark(s));
SetNote(CabProbeNote, GraphicsRules.CabProbeUsed(s) && !GraphicsRules.CabProbeLights(s) ? App.Loc["CabProbeReflectionsOnlyNote"] : "");
SetNote(SkipPipelineNote, GraphicsRules.TemporalWithoutPipeline(s) ? App.Loc["TemporalNeedsPipelineNote"] : "");
var m = monitors[i];
MonitorCb.Items.Add(new ComboBoxItem
{
Tag = m.Id,
Content = $"{i + 1}. {m.Name} – {m.Width}×{m.Height}"
});
}
}
finally
{
_updatingGraphics = false;
}
}
private string AntiAliasingRemark(SimulatorSettings s, bool dlss)
{
if (!DlssPlatform && GraphicsRules.IsVulkan(s))
return App.Loc["DlssNoPlatformNote"];
if (GraphicsRules.TemporalWithoutPipeline(s))
return App.Loc["TemporalNeedsPipelineNote"];
if (dlss && !DlssLibraries(s).Dlss)
return string.Format(App.Loc["DlssMissingLibraryNote"], DlssLibraryName(frameGeneration: false));
return "";
if (IndexOfTag(MonitorCb, id) < 0)
MonitorCb.Items.Add(new ComboBoxItem { Tag = id, Content = id });
SelectTag(MonitorCb, id);
}
private static string AoLightingRemark(SimulatorSettings s)
{
if (!GraphicsRules.AoLightingUsed(s) || !s.AoLighting)
return "";
if (s.SkipPipeline)
return App.Loc["AoNeedsPipelineNote"];
return GraphicsRules.AoLightingAddsDepthPrepass(s) ? App.Loc["AoLightingPrepassNote"] : "";
}
private string FrameGenerationRemark(SimulatorSettings s, bool dlss)
{
if (!dlss)
return GraphicsRules.IsVulkan(s) ? App.Loc["FrameGenerationNeedsDlssNote"] : "";
if (s.FrameGeneration > 1 && !DlssLibraries(s).FrameGeneration)
return string.Format(App.Loc["DlssMissingLibraryNote"], DlssLibraryName(frameGeneration: true));
return "";
}
/// <summary>Looked up once per simulator picked: the search for it reads the installation's directory.</summary>
private (bool Dlss, bool FrameGeneration) DlssLibraries(SimulatorSettings s)
{
string key = s.SelectExeAutomatically ? "\u0001auto" : s.ExecutablePath;
if (_dlssProbedFor != key)
{
var executables = AppServices.Current.Executables;
_dlssProbe = executables.DlssLibraries(executables.Resolve(s, out _));
_dlssProbedFor = key;
}
return _dlssProbe;
}
private static string DlssLibraryName(bool frameGeneration) =>
AppServices.Current.Environment.IsWindows
? (frameGeneration ? "nvngx_dlssg.dll" : "nvngx_dlss.dll")
: (frameGeneration ? "libnvidia-ngx-dlssg.so" : "libnvidia-ngx-dlss.so");
private async void ImportIniButton_OnClick(object? sender, RoutedEventArgs e)
{
if (TopLevel.GetTopLevel(this) is not Window owner)
@@ -303,7 +187,6 @@ public partial class Settings
return;
}
_vulkanChoices = null;
ApplyToUi();
// What came from the other file is a choice to save, not a value the screen could not show.
_shownUnlikeSettings = new Dictionary<string, ShownValue>();
@@ -337,7 +220,6 @@ public partial class Settings
}
SaveStatus.Text = string.Format(App.Loc["ExportIniDone"], Path.GetFileName(path));
ToolTip.SetTip(SaveStatus, path);
}
private static void SetNote(TextBlock note, string text)
@@ -370,22 +252,15 @@ public partial class Settings
cb.SelectedIndex = index;
}
private static string AntiAliasingTag(AntiAliasingMode mode) => mode switch
{
AntiAliasingMode.Msaa2 => "msaax2",
AntiAliasingMode.Msaa4 => "msaax4",
AntiAliasingMode.Msaa8 => "msaax8",
AntiAliasingMode.Taa => "taa",
AntiAliasingMode.Dlss => "dlss",
AntiAliasingMode.Dlaa => "dlaa",
_ => "off"
};
// The list's tags are the gfx.antialiasing words.
private static string AntiAliasingTag(AntiAliasingMode mode) => SettingsSerializer.AntiAliasingWord(mode);
private static AntiAliasingMode AntiAliasingFromTag(string? tag) => tag switch
{
"msaax2" => AntiAliasingMode.Msaa2,
"msaax4" => AntiAliasingMode.Msaa4,
"msaax8" => AntiAliasingMode.Msaa8,
"msaax16" => AntiAliasingMode.Msaa16,
"taa" => AntiAliasingMode.Taa,
"dlss" => AntiAliasingMode.Dlss,
"dlaa" => AntiAliasingMode.Dlaa,
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+41 -3
View File
@@ -77,13 +77,14 @@ internal sealed class SimulatorKeyRows
TickFrequency = key.Step,
IsSnapToTickEnabled = true
},
SimulatorKeyKind.Choice => ChoiceList(key),
_ => new TextBox { MinWidth = 200 }
};
// Marks the input as one of these rows, which tell about their own changes.
input.Tag = key;
var setting = new SettingRow { ConfigKey = key.Key, Content = input };
var setting = new SettingRow { ConfigKey = key.Key, Content = input, Advanced = !SimulatorKeys.Standard.Contains(key.Key) };
var row = new Row(key, setting, input);
_rows.Add(row);
@@ -102,11 +103,35 @@ internal sealed class SimulatorKeyRows
case TextBox text:
text.TextChanged += (_, _) => OnEdited(row);
break;
case ComboBox list:
list.SelectionChanged += (_, _) => OnEdited(row);
break;
}
return setting;
}
/// <summary>The list of the words of a <see cref="SimulatorKeyKind.Choice"/>, each item tagged with its word.</summary>
private static ComboBox ChoiceList(SimulatorKey key)
{
var list = new ComboBox { MinWidth = 160 };
foreach (string choice in key.Choices ?? Array.Empty<string>())
list.Items.Add(new ComboBoxItem { Tag = choice, Content = ChoiceText(key, choice) });
return list;
}
/// <summary>
/// A word of a list as the player reads it: as that key names it (the "new" of the derailment), else as every
/// list names it (no, low, high...), translated where the language has it, else in English, else as the
/// simulator writes it (DLSS's preset letters).
/// </summary>
private static string ChoiceText(SimulatorKey key, string choice) =>
App.Loc.OptOrEnglish(SimulatorKey.ChoiceLabelKey(key.Key + "." + choice)) is { Length: > 0 } own ? own
: App.Loc.OptOrEnglish(SimulatorKey.ChoiceLabelKey(choice)) is { Length: > 0 } text ? text : choice;
/// <summary>The developer tab's rows are named in the language where it has them, else in English.</summary>
private static string Text(string key) => App.Loc.OptOrEnglish(key);
/// <summary>
/// Only a value other than the one shown counts: a text box reports the text it
/// was given after the fact, and a slider reports its own clamping.
@@ -118,6 +143,9 @@ internal sealed class SimulatorKeyRows
Changed?.Invoke();
}
/// <summary>What the row of <paramref name="key"/> holds now, in the file's words; null for a key with no row.</summary>
public string? ValueOf(string key) => Find(key) is { } row ? Current(row) : null;
/// <summary>The row of <paramref name="key"/>, wherever it was put.</summary>
public SettingRow? RowOf(string key) => Find(key)?.Setting;
@@ -147,8 +175,8 @@ internal sealed class SimulatorKeyRows
foreach (var row in _rows)
{
string label = App.Loc[row.Key.LabelKey];
row.Setting.Description = App.Loc[row.Key.DescriptionKey];
string label = Text(row.Key.LabelKey) is { Length: > 0 } named ? named : row.Key.Key;
row.Setting.Description = Text(row.Key.DescriptionKey);
switch (row.Input)
{
@@ -159,6 +187,11 @@ internal sealed class SimulatorKeyRows
row.Setting.Label = label;
text.PlaceholderText = App.Loc["IniDefault"];
break;
case ComboBox list:
row.Setting.Label = label;
foreach (var item in list.Items.OfType<ComboBoxItem>())
item.Content = ChoiceText(row.Key, item.Tag as string ?? string.Empty);
break;
default:
row.Setting.Label = label;
UpdateValueText(row);
@@ -224,6 +257,10 @@ internal sealed class SimulatorKeyRows
case TextBox text:
text.Text = raw.Trim();
break;
case ComboBox list:
int at = row.Key.ChoiceIndex(raw);
list.SelectedIndex = at >= 0 ? at : row.Key.ChoiceIndex(row.Key.Default);
break;
}
}
@@ -232,6 +269,7 @@ internal sealed class SimulatorKeyRows
CheckBox box => SimulatorKey.FormatToggle(box.IsChecked == true),
Slider slider => row.Key.FormatNumber(slider.Value),
TextBox text => (text.Text ?? string.Empty).Trim(),
ComboBox { SelectedItem: ComboBoxItem { Tag: string word } } => word,
_ => string.Empty
};
+6
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using StarterNG.Domain.Settings;
@@ -28,11 +29,16 @@ internal sealed class SliderSteps
slider.Maximum = steps.Count - 1;
}
/// <summary>A value past either end of the list is put at that end, not added to it.</summary>
public bool Clamps { get; set; }
public double Value
{
get => _shown[Math.Clamp((int)Math.Round(_slider.Value), 0, _shown.Count - 1)];
set
{
if (Clamps)
value = Math.Clamp(value, _steps.Min(), _steps.Max());
_shown = Steps.With(_steps, value);
_slider.Maximum = _shown.Count - 1;
int at = Steps.IndexOf(_shown, value);
+189
View File
@@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using StarterNG.Application;
using StarterNG.Classes;
using StarterNG.Domain;
namespace StarterNG.Views;
/// <summary>
/// A consist's row in a list of them: its vehicles as minis, each stretch of vehicles
/// alike as one picture with its name and count under it, so the consist reads at a glance.
/// </summary>
internal static class TrainsetRow
{
/// <summary>The height the minis are made at: shown at it they stay sharp.</summary>
private const int MiniHeight = 30;
private static readonly MiniTextures Minis = new();
/// <summary>Room under the captions for the scroll bar of a consist wider than the list.</summary>
private const double ScrollBarLane = 10;
private static readonly IBrush AiTagBack = new SolidColorBrush(Color.Parse("#9098A0"));
private static readonly IBrush AiTagText = new SolidColorBrush(Color.Parse("#15171B"));
public static Control Build(Trainset trainset)
{
string label = TrainsetDisplay.ListLabel(trainset);
Control row;
if (TrainsetDisplay.IsEmpty(trainset))
{
row = new TextBlock
{
Text = label,
FontStyle = FontStyle.Italic,
Opacity = 0.7,
TextTrimming = TextTrimming.CharacterEllipsis,
TextWrapping = TextWrapping.NoWrap,
VerticalAlignment = VerticalAlignment.Center
};
}
else
{
bool ai = TrainsetDisplay.IsAi(trainset);
var panel = new DockPanel { Margin = new Thickness(0, 3), LastChildFill = true };
if (ai)
{
var tag = AiTag();
tag.Margin = new Thickness(8, 0, 0, 0);
DockPanel.SetDock(tag, Dock.Right);
panel.Children.Add(tag);
}
// A consist longer than the list is wide scrolls sideways in its own row. The wheel
// still scrolls the list: only shift with the wheel, or a touchpad, moves the strip.
panel.Children.Add(ScrollingStrip(trainset.Vehicles, ai));
row = panel;
}
ToolTip.SetTip(row, label);
AutomationProperties.SetName(row, label);
return row;
}
/// <summary>
/// The vehicles' minis with their captions, scrolling sideways when wider than the room
/// they get - here and for the warehouse's consists.
/// </summary>
public static Control ScrollingStrip(IReadOnlyList<Dynamic> vehicles, bool dimmed = false)
{
var strip = Strip(vehicles, dimmed);
var scroller = new ScrollViewer
{
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = strip
};
// The bar lies over the content; a consist that scrolls gets a lane under its
// captions for it, so the bar does not cross them. One that fits stays as low as it was.
scroller.ScrollChanged += (_, _) =>
{
double below = scroller.Extent.Width > scroller.Viewport.Width + 0.5 ? ScrollBarLane : 0;
if (Math.Abs(strip.Margin.Bottom - below) > 0.1)
strip.Margin = new Thickness(0, 0, 0, below);
};
return scroller;
}
/// <summary>
/// The minis, one next to the other with nothing between, as the vehicles stand coupled.
/// </summary>
private static Control Strip(IReadOnlyList<Dynamic> vehicles, bool dimmed)
{
var strip = new StackPanel { Orientation = Orientation.Horizontal, Opacity = dimmed ? 0.6 : 1 };
var runs = ConsistRuns.Of(vehicles, (v, i) => $"{MiniName(v)}|{Caption(v, i)}");
int place = 0;
foreach (var run in runs)
{
strip.Children.Add(RunView(run, place));
place += run.Count;
}
return strip;
}
private static Control RunView(ConsistRun run, int place)
{
var v = run.First;
var bmp = Minis.Get(MiniName(v), MiniHeight);
Control picture;
double width;
if (bmp is not null)
{
width = bmp.Size.Height > 0 ? bmp.Size.Width * MiniHeight / bmp.Size.Height : MiniHeight;
// Fill at a width worked out here, not Uniform: rounding at a scale such as 125 %
// left a line of the background between two vehicles.
picture = MiniTextures.Sharp(new Image
{
Source = bmp,
Width = width,
Height = MiniHeight,
Stretch = Stretch.Fill
});
}
else
{
picture = MiniTextures.MissingVisual(v.SkinFile, MiniHeight);
width = picture.Width;
}
string caption = Caption(v, place);
if (run.Count > 1)
caption += $" ×{run.Count}";
return new StackPanel
{
Orientation = Orientation.Vertical,
Spacing = 2,
Width = width,
Children =
{
picture,
new TextBlock
{
Text = caption,
FontSize = 11,
Padding = new Thickness(3, 0),
HorizontalAlignment = HorizontalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis,
TextWrapping = TextWrapping.NoWrap
}
}
};
}
private static Control AiTag() =>
new Border
{
Background = AiTagBack,
Padding = new Thickness(4, 0),
VerticalAlignment = VerticalAlignment.Center,
Child = new TextBlock
{
Text = "AI",
FontSize = 10,
FontWeight = FontWeight.Bold,
Foreground = AiTagText
}
};
/// <summary>A vehicle leading the consist under its own name, the rest under their class - as the composition text has them.</summary>
private static string Caption(Dynamic v, int place) =>
TrainsetDisplay.VehicleLabel(v, head: place == 0 && TrainsetDisplay.IsPowered(v));
/// <summary>The mini the consist strip shows for the vehicle.</summary>
private static string? MiniName(Dynamic v)
{
string? mini = AppServices.Current.Library.Vehicles.MiniFor(v.DataFolder, v.SkinFile, v.MmdFile) ?? v.SkinFile;
if (!AppServices.Current.MiniTextures.Has(mini) && AppServices.Current.MiniTextures.Has(v.SkinFile))
mini = v.SkinFile;
return mini;
}
}
+77 -100
View File
@@ -48,12 +48,13 @@
<String key="SeasonWinter">Zima</String>
<String key="OvercastRandom">Náhodné</String>
<String key="OvercastClear">Jasno</String>
<String key="OvercastFair">Skoro jasno</String>
<String key="OvercastLight">Slabá oblačnost</String>
<String key="OvercastModerate">Mírná oblačnost</String>
<String key="OvercastHeavy">Silná oblačnost</String>
<String key="OvercastCloudy">Zataženo</String>
<String key="OvercastStorm">Bouřka</String>
<String key="OvercastRainLight">Slabý déšť</String>
<String key="OvercastRain">Déšť</String>
<String key="OvercastSnowLight">Slabé sněžení</String>
<String key="OvercastSnow">Sněžení</String>
<String key="WeatherDateTime">Datum a čas</String>
<String key="WeatherConditions">Povětrnostní podmínky</String>
<String key="Consist">Souprava</String>
@@ -61,6 +62,8 @@
<String key="StartNoScenery">Vyberte scenérii</String>
<String key="StartNoTrain">Vyberte soupravu</String>
<String key="StartNoStaff">Bez osádky / cestujícího</String>
<String key="StartDecor">Dekorační souprava</String>
<String key="StartAi">Souprava AI</String>
<String key="StartNoStaffTitle">Souprava bez osádky</String>
<String key="StartNoStaffConfirm">Tato souprava nemá osádku ani cestujícího — nebude co řídit. Přesto spustit?</String>
<String key="RestoreWeather">Obnovit počasí</String>
@@ -359,8 +362,8 @@
<String key="General">Obecné</String>
<String key="Language">Jazyk</String>
<String key="UnknownIniValue">Neznámá hodnota v eu07.ini: „{0}“. Zůstane v souboru, dokud ji nezměníte.</String>
<String key="LanguageSimMissing">Simulátor nemá překlad do tohoto jazyka a poběží v angličtině.</String>
<String key="Fullscreen">Celá obrazovka</String>
<String key="PauseSimInactive">Pozastavit simulaci při neaktivním okně</String>
<String key="PauseSimStart">Pozastavit po spuštění</String>
<String key="CursorSensitivity">Citlivost kurzoru</String>
@@ -370,6 +373,7 @@
<String key="Communication">Komunikace</String>
<String key="GamepadSignalIgnore">Ignorovat vstup z gamepadu</String>
<String key="ConfirmGamepadUse">Doporučené a výchozí je gamepad ignorovat. Zapnutí jeho podpory bývá zdrojem potíží s ovládáním. Měňte jen tehdy, když opravdu ovládáte gamepadem. Změnit?</String>
<String key="Feedback">Zpětná vazba</String>
<String key="FeedbackOff">Vypnuto</String>
@@ -410,9 +414,9 @@
<String key="LogMissingVehicleFiles">Zaznamenat chybějící soubory vozidel při exportu</String>
<String key="Graphic">Grafika</String>
<String key="RenderEngine">Vykreslovací engine</String>
<String key="RenderEngineDesc">Plný funguje s každým exe. Starý, Zjednodušený a Experimentální jen se staršími, nový místo nich spustí Plný.</String>
<String key="REExperimentalWarning">Upozornění: experimentální renderer může být nestabilní, nezobrazovat části scény nebo se na některých grafických kartách nespustit. Pokud se simulátor nespustí nebo vypadá špatně, vraťte se k rendereru „Plný“.</String>
<String key="RenderEngine">Grafické API</String>
<String key="ConfirmRenderingChange">Změna „{0}“ může způsobit, že se simulátor nespustí nebo bude obraz vypadat špatně. Změnit?</String>
<String key="RenderEngineDesc">Plný je doporučený renderer simulátoru. Starý a Zjednodušený kreslí klasickým rendererem a nejsou doporučeny, pokud Plný funguje – jsou pro grafické karty, se kterými má Plný potíže.</String>
<String key="GpuChoice">Grafická karta (Linux)</String>
<String key="GpuDiscrete">Výkonnější (dedikovaná)</String>
<String key="GpuSystem">Podle systému</String>
@@ -422,17 +426,10 @@
<String key="GpuNotePlayer">Nalezeno: {0}. Kartu vybírají proměnné prostředí ({1}); starter je nemění.</String>
<String key="GpuNoteOne">Jedna karta: {0} – není mezi čím vybírat.</String>
<String key="GpuNoteUnread">Grafické karty se nepodařilo načíst z /sys/class/drm.</String>
<String key="IdleWindowsBuildOnly">Funguje jen ve verzi simulátoru pro Windows.</String>
<String key="IdleLegacyRendererOnly">Čte to jen renderer legacy, ale zvolen je jiný.</String>
<String key="IdleNeedsFrameRateTarget">Funguje jen s cílovým počtem snímků (targetfps).</String>
<String key="IdleOpenGlRenderersOnly">Experimentální renderer to nečte.</String>
<String key="IdleModernRendererOnly">Čte to jen plný renderer, ale zvolen je jiný.</String>
<String key="IdleNeedsNetworkServer">Pauza na pozadí vyžaduje síťový server (network.server).</String>
<String key="Resolution">Rozlišení</String>
<String key="ResolutionOnMonitor">{0} (monitor)</String>
<String key="IdleMonitorMode">Při automatickém rozlišení nefunguje.</String>
<String key="BufforResolution">Rozlišení bufferu</String>
<String key="BufforResolution">Měřítko vykreslování</String>
<String key="MaxTexResolution">Maximální rozlišení textur</String>
<String key="MaxTexCabResolution">Maximální rozlišení textur kabiny</String>
<String key="TexFilteringQuality">Kvalita filtrování textur</String>
@@ -460,7 +457,14 @@
<String key="FpsLimitDesc">Méně snímků: chladnější a tišší počítač. S V-Sync limit nad obnovovací frekvencí nic nedělá.</String>
<String key="ShadowAngleLimit">Omezení délky stínů</String>
<String key="ShadowLimitShort">Zkrácené</String>
<String key="FullscreenWindowed">Automatické rozlišení (celá obrazovka bez okrajů)</String>
<String key="DisplayMode">Režim zobrazení</String>
<String key="DisplayModeFullscreen">Celá obrazovka</String>
<String key="DisplayModeBorderless">Celá obrazovka bez okrajů</String>
<String key="DisplayModeWindow">Okno</String>
<String key="DisplayModeDesc">Celá obrazovka bez okrajů bere rozlišení monitoru a rychleji přepíná do jiných programů.</String>
<String key="FullscreenMonitor">Monitor</String>
<String key="FullscreenMonitorDesc">Na kterém monitoru se simulátor otevře v režimu celé obrazovky.</String>
<String key="MonitorPrimary">Hlavní</String>
<String key="VSync">VSync</String>
<String key="SmokeDisplay">Zobrazení kouře</String>
<String key="SmokeParticlesMultiplier">Násobitel částic kouře</String>
@@ -524,6 +528,12 @@
<String key="AmbientVolume">Hlasitost okolí</String>
<String key="Advanced">Pokročilé</String>
<String key="AdvancedMode">Pokročilý režim</String>
<String key="AdvancedModeMenu">Pokročilý režim…</String>
<String key="AdvancedModeOff">Vypnout pokročilý režim</String>
<String key="AdvancedModeOffConfirm">Vypnutí pokročilého režimu vrátí vše z karty Vývojář na hodnoty spouštěče – Vulkan a všechny optimalizace zapnuté – a uloží nastavení této stránky. Kvalita grafiky zůstane taková, jak ji ukazuje karta Grafika. Vypnout?</String>
<String key="AdvancedModeOn">Zapnout</String>
<String key="AdvancedModeWarning">Pokročilý režim je určen vývojářům a testerům. Otevírá kartu Vývojář se všemi nastaveními simulátoru: rendererem (OpenGL místo Vulkanu), podrobnostmi obrazu, přepínači optimalizací, protokoly a diagnostikou. Po změně mnoha z nich se simulátor nemusí spustit, může běžet pomaleji či nestabilně nebo vypadat špatně. Umožňuje také měnit osádky souprav, soupravy AI a dekorace, takže scénář nemusí fungovat tak, jak jej autor zamýšlel.&#10;&#10;Potíže způsobené těmito nastaveními nejsou chybami simulátoru: než chybu nahlásíte, vypněte pokročilý režim, což vrátí vše z karty Vývojář na hodnoty spouštěče.&#10;&#10;Přečtěte si to pozorně. Tlačítko pro zapnutí bude funkční za 20 sekund.</String>
<String key="CompressTextures">Komprimovat textury TGA</String>
<String key="ScaleSpeculars">Škálovat odlesky (kompatibilita starých modelů)</String>
<String key="ScaleSpecularsDesc">Zeslabuje lesk modelů dělaných pro starší renderery.</String>
@@ -573,6 +583,7 @@
<String key="Reset">Obnovit</String>
<String key="SettingsSaved">Nastavení uloženo</String>
<String key="DefaultsRestored">Výchozí hodnoty obnoveny</String>
<String key="AllDefaultsConfirm">Všechna nastavení se vrátí na výchozí. Zůstane: jazyk, vybraný simulátor, port UART a klávesy ovládání.&#10;&#10;Změny je ještě třeba uložit.</String>
<String key="SettingsRestored">Uložené nastavení obnoveno</String>
<String key="TreeExpanded">rozbaleno</String>
<String key="TreeCollapsed">sbaleno</String>
@@ -686,9 +697,8 @@
<String key="StartFreeFly">Spustit bez vozidla</String>
<String key="StartEditorShort">Editor scenérie</String>
<String key="StartEditorWizard">Vytvořit novou scenérii</String>
<String key="StartEditorWizardTip">Průvodce novou scenérií v editoru simulátoru. Editor mají jen některé verze.</String>
<String key="StartEditorWizardTip">Průvodce novou scenérií v editoru simulátoru.</String>
<String key="StartEditor">Spustit editor scenérie</String>
<String key="StartEditorWarning">Editor scenérie (eu07 -edit) mají jen některé verze simulátoru. Pokud ho vybraný simulátor nepodporuje, editor se neotevře. Editor pracuje přímo se souborem {0}, ne s kopií od starteru, takže uložené změny se zapíší do scenérie. Spustit?</String>
<String key="DebugLogVisible">Zobrazovat průběh simulace</String>
<String key="PyScreenPriority">Frekvence obnovení doplňkových obrazovek</String>
<String key="PyPriorityNormal">Standardní</String>
@@ -745,7 +755,7 @@
<String key="ShortcutCardMenu">Otevřít nabídku vozidla</String>
<!-- Package author's tab - awaiting translation -->
<String key="AdvancedResources">Prostředky a kompatibilita</String>
<String key="AdvancedResources">Výkon</String>
<String key="AdvancedLogTools">Protokol a nástroje</String>
<String key="LogAndTools">Protokol událostí a nástroje</String>
<String key="OpenLogTools">Otevřít protokol a nástroje…</String>
@@ -800,6 +810,7 @@
<String key="SyntaxIncludeNotClosed">include {1} bez end</String>
<String key="SyntaxTrainsetUnreadable">Soupravu {0} se nepodařilo načíst</String>
<String key="SyntaxVehicleUnreadable">Vozidlo {0} se nepodařilo načíst</String>
<String key="SyntaxVehicleMissing">Vozidlo {0} chybí: soubor dynamic/{1} nenalezen - simulátor ho vynechá, souprava bude kratší</String>
<String key="WarehouseUseInScenery">Vložit do vybrané soupravy scenérie</String>
<String key="WarehouseAppendToScenery">Připojit k vybrané soupravě scenérie</String>
<String key="ShortcutUndo">Vrátit změnu soupravy</String>
@@ -814,7 +825,6 @@
<String key="Ini.loadinglog">Zobrazit protokol při načítání</String>
<String key="Ini.captureonstart">Po startu myš otáčí kamerou</String>
<String key="Ini.mousecontrol">Ovládání prvků v kabině myší</String>
<String key="Ini.fullscreenmonitor">Monitor pro celou obrazovku</String>
<String key="Ini.screenshotsdir">Složka snímků obrazovky</String>
<String key="Ini.basedrawrange">Základní dohled vykreslování</String>
<String key="Ini.targetfps">Cílová snímková frekvence</String>
@@ -823,13 +833,11 @@
<String key="Ini.gfx.reflections.range_vehicles">Dosah odrazů vozidel</String>
<String key="Ini.gfx.textures.streaming">Načítat textury na pozadí</String>
<String key="Ini.gfx.textures.releasedistance">Uvolňovat textury vzdálených vozidel</String>
<String key="Ini.skyenabled">Vykreslovat oblohu</String>
<String key="Ini.rendercab">Vykreslovat kabinu</String>
<String key="Ini.gfx.postfx.motionblur.shutter">Doba závěrky rozmazání pohybu</String>
<String key="Ini.python.vsync">Vertikální synchronizace oken obrazovek</String>
<String key="Ini.python.displaywindows">Obrazovky z kabiny v samostatných oknech</String>
<String key="Ini.newaircouplers">Vzduchové hadice podle spojení vozidel</String>
<String key="Ini.smoothtraction">Vyhlazení trolejového vedení (klasický renderer)</String>
<String key="Ini.sound.maxsources">Maximální počet zdrojů zvuku</String>
<String key="Ini.sound.asyncload">Dekódovat zvuky na pozadí</String>
<String key="Ini.loadtraction">Načítat trolejové vedení</String>
@@ -847,15 +855,14 @@
<String key="IniChangesNone">Uložení v eu07.ini nic nezmění.</String>
<String key="IniChangesKeyboard">Změněné klávesy se uloží do eu07_input-keyboard.ini.</String>
<String key="GfxColPresets">Kvalita grafiky</String>
<String key="PresetMinimal">Minimální</String>
<String key="PresetLow">Nízká</String>
<String key="PresetMedium">Střední</String>
<String key="PresetHigh">Vysoká</String>
<String key="PresetCustom">Vlastní</String>
<String key="MonitorRate">Monitor: {0} Hz</String>
<String key="MonitorRateNamed">Obrazovka {0}: až {1} Hz</String>
<String key="MonitorRateUse">Nastavit {0} FPS</String>
<String key="GfxPresetDesc">Najetím na úroveň zobrazíte hodnoty.</String>
<String key="FpsVSyncNote">S VSync nebude víc snímků, než má monitor Hz, takže stejný nebo vyšší limit nic nemění.</String>
<String key="GfxPresetDesc">Úroveň nastaví všechny části níže najednou; každou pak lze změnit zvlášť.</String>
<String key="TextureBaseDateHint">RRRR-MM-DD</String>
<String key="LanguageStarterMissing">Starter nemá překlad: zůstane anglicky. Simulátor dostane tento jazyk.</String>
<String key="ProfileNone">Žádné profily</String>
@@ -889,8 +896,6 @@
<String key="Ini.heightbase">Násobitel dosahu</String>
<String key="Ini.heightbase.Desc">Zkracuje nebo prodlužuje dohlednost scenérie. Cílové FPS ji přepíše.</String>
<String key="PresetVeryHigh">Velmi vysoká</String>
<String key="PresetUltra">Ultra</String>
<String key="PresetUltraNote">Vše na maximum. Může to být moc i pro silnou kartu.</String>
<String key="Ini.python.fpslimit">Limit snímků oken obrazovek</String>
<String key="Ini.python.fpslimit.Desc">Funguje jen s obrazovkami v samostatných oknech; bez nich nic nemění.</String>
<String key="ShadowLimitNone">Nejdelší</String>
@@ -912,73 +917,12 @@
<String key="WarehouseSaved">Ve skladu: {0}</String>
<String key="WarehouseNothingToAdd">Vyberte soupravu s vozidly</String>
<String key="GfxGroupLevelTip">Úroveň jen pro tuto část grafiky</String>
<String key="REVulkan">Vulkan 1.4</String>
<String key="IdleVulkanOnly">Funguje jen s Vulkanem.</String>
<String key="DlssPreset">Předvolba DLSS</String>
<String key="FrameGeneration">Generování snímků</String>
<String key="Reflex">NVIDIA Reflex</String>
<String key="RayTracing">Odrazy ray tracing</String>
<String key="RayTracingRange">Dosah ray tracingu</String>
<String key="VulkanDevice">Grafická karta (Vulkan)</String>
<String key="Ssr">Odrazy v prostoru obrazovky (SSR)</String>
<String key="AmbientOcclusion">Okolní zastínění</String>
<String key="AmbientOcclusionQuality">Kvalita zastínění</String>
<String key="AoLighting">Zastínění v okolním světle</String>
<String key="LightsClustered">Klastrové osvětlení</String>
<String key="LightShadows">Stíny lamp a reflektorů</String>
<String key="ContactShadows">Kontaktní stíny</String>
<String key="ShadowSdsm">Kaskády stínů podle scény (SDSM)</String>
<String key="CabProbe">Sonda kabiny</String>
<String key="CabProbeInterval">Obnovení sondy každých N snímků</String>
<String key="CabProbeReflections">Kabina odráží sebe</String>
<String key="CabProbeBounce">Odražené světlo lampy v kabině</String>
<String key="FogQuality">Kvalita mlhy</String>
<String key="Clouds">Objemová oblaka</String>
<String key="CloudShadows">Stíny oblaků na zemi</String>
<String key="Grass">Tráva</String>
<String key="GrassDistance">Dosah trávy</String>
<String key="GrassDensity">Hustota trávy</String>
<String key="Precipitation">Srážky (částice)</String>
<String key="Bloom">Záře světlých míst (bloom)</String>
<String key="AutoExposure">Automatická expozice</String>
<String key="LevelOff">Vypnuto</String>
<String key="LevelLow">Nízká</String>
<String key="LevelMedium">Střední</String>
<String key="LevelHigh">Vysoká</String>
<String key="LevelUltra">Ultra</String>
<String key="ReflexOn">Zapnuto</String>
<String key="ReflexBoost">Zapnuto + boost</String>
<String key="AaTaa">TAA</String>
<String key="AaDlss">DLSS (škálování)</String>
<String key="AaDlaa">DLAA (nativní rozlišení)</String>
<String key="DlssPresetDefault">Automaticky</String>
<String key="DlssPresetK">K: nejlepší kvalita</String>
<String key="DlssPresetJ">J: méně rozmazání</String>
<String key="DlssPresetM">M: pro režim Výkon</String>
<String key="DlssPresetL">L: pro Ultra výkon</String>
<String key="Effects">Efekty</String>
<String key="GfxColImage">Rozlišení a vyhlazování</String>
<String key="GfxColLights">Osvětlení</String>
<String key="GfxColPostFx">Postprocessing</String>
<String key="GfxColNature">Kouř</String>
<String key="GfxColNature">Kouř a srážky</String>
<String key="AntiAliasing">Vyhlazování hran</String>
<String key="VolumetricFog">Objemová mlha</String>
<String key="REOpenGLNote">DLSS, generování snímků, Reflex a ray tracing jen s Vulkanem.</String>
<String key="REVulkanNote">Vyžaduje exe s Vulkanem a kartu, která ho podporuje. Jinak simulátor spustí Plný nebo Starý.</String>
<String key="VulkanDeviceAuto">automaticky</String>
<String key="DlssPresetInfoDefault">K pro DLAA, Kvalitu a Vyvážený, M pro Výkon, L pro Ultra výkon. Ovladač to může při aktualizaci změnit.</String>
<String key="DlssPresetInfoK">Model transformer s nejlepší kvalitou obrazu, ale nejnáročnější. Výchozí pro DLAA, Kvalitu a Vyvážený.</String>
<String key="DlssPresetInfoJ">Podobný K: o něco méně šmouh za pohyblivými objekty za cenu většího blikání. NVIDIA doporučuje spíše K.</String>
<String key="DlssPresetInfoM">Model pro režim Výkon (měřítko asi 50 %), tam výchozí. Expozici obrazu počítá sám.</String>
<String key="DlssPresetInfoL">Model pro režim Ultra výkon (měřítko asi 33 %), tam výchozí. Expozici obrazu počítá sám.</String>
<String key="DlssMissingLibraryNote">Vedle simulátoru chybí {0}: bez této knihovny simulátor tuto funkci DLSS nepoužije.</String>
<String key="DlssNoPlatformNote">Na macOS není DLSS k dispozici.</String>
<String key="FrameGenerationNeedsDlssNote">Generování snímků funguje jen s DLSS nebo DLAA.</String>
<String key="ReflexForcedNote">Generování snímků zapíná Reflex samo, ať je zde vybráno cokoli.</String>
<String key="AoLightingPrepassNote">Potřebuje hloubku celé scény před barvou; bez SSR a kontaktních stínů je to průchod navíc (zátěž CPU v OpenGL).</String>
<String key="AoNeedsPipelineNote">Při přeskočeném postprocessingu AO nefunguje.</String>
<String key="CabProbeReflectionsOnlyNote">Bez klastrového osvětlení a lampy kabiny jako světla (gfx.lights.cab) dává sonda jen odrazy.</String>
<String key="TemporalNeedsPipelineNote">TAA a DLSS běží v postprocessingu: při jeho přeskočení se hrany nevyhladí.</String>
<String key="SettingsFile">Soubor eu07.ini</String>
<String key="ImportIni">Importovat…</String>
<String key="ImportIniTitle">Importovat nastavení z eu07.ini</String>
@@ -990,17 +934,50 @@
<String key="ExportIniFailed">Soubor se nepodařilo zapsat:
{0}</String>
<String key="ExportIniDone">Exportováno do {0}</String>
<String key="REFull">Plný</String>
<String key="REOld">Starý</String>
<String key="RESimp">Zjednodušený</String>
<String key="REExperimental">Experimentální</String>
<String key="RenderAngleVulkan">Použít renderer ANGLE Vulkan</String>
<String key="RenderVBO">Vykreslování VBO</String>
<String key="CabShadowsRange">Dosah zdrojů stínů v kabině</String>
<String key="UseGLES">Použít OpenGL ES</String>
<String key="UseGLESDesc">OpenGL ES místo OpenGL. Nefunguje s rendererem legacy.</String>
<String key="GpuCard">{0}, {1} GB</String>
<String key="GpuCardShared">{0}, sdílená paměť</String>
<String key="GfxColNewRenderer">Novinky OpenGL 4.6 / Vulkan</String>
<String key="GfxNewRendererNote">Funguje jen s novým exe. Starší exe tato nastavení přeskočí.</String>
<String key="DeveloperTab">Vývojář</String>
<String key="DeveloperTabNote">Nastavení pro vývojáře a testery. Hráč tu má vše na hodnotách spouštěče, se kterými simulátor běží nejrychleji; vypnutí pokročilého režimu je vrátí.</String>
<String key="MouseSection">Myš</String>
<String key="RecordingSection">Záznam jízdy</String>
<String key="DevSimulation">Simulace</String>
<String key="GfxColQuality">Podrobnosti kvality</String>
<String key="GroupTextures">Textury</String>
<String key="GroupShadows">Stíny</String>
<String key="GroupReflections">Odrazy</String>
<String key="GroupLighting">Osvětlení a obloha</String>
<String key="GroupDrawRange">Dohled a tráva</String>
<String key="GroupParticles">Kouř, déšť a sníh</String>
<String key="AaDlss">DLSS (NVIDIA RTX, Vulkan)</String>
<String key="AaDlaa">DLAA (NVIDIA RTX, Vulkan)</String>
<String key="REVulkan">Vulkan (doporučeno)</String>
<String key="REOpenGL">OpenGL 4.6</String>
<String key="IniSectionRenderer">Renderer</String>
<String key="IniSectionPerformance">Výkon</String>
<String key="SimulatorSection">Simulátor</String>
<String key="RayTracing">Ray tracing (odrazy)</String>
<String key="RayTracingOff">Vypnuto</String>
<String key="RealismSection">Realismus jízdy</String>
<String key="PhysicsPresets">Úroveň realismu</String>
<String key="PhysicsArcade">Arkádový</String>
<String key="PhysicsRealistic">Realistický</String>
<String key="BrakeKeysSection">Brzda z klávesnice</String>
<String key="Ini.couplerphysics">Spřáhla</String>
<String key="Ini.physics.derailment">Vykolejení</String>
<String key="Ini.physics.collisions">Srážky</String>
<String key="Ini.physics.trackbuckling">Vybočení koleje v horku</String>
<String key="Ini.deer">Zvěř u trati</String>
<String key="Choice.couplerphysics.no">Zjednodušená</String>
<String key="Choice.couplerphysics.yes">Fyzikální – vlak hráče</String>
<String key="Choice.couplerphysics.all">Fyzikální – všechny vlaky</String>
<String key="Choice.physics.derailment.off">Vypnuto</String>
<String key="Choice.physics.derailment.monitor">Klasické</String>
<String key="Choice.physics.derailment.new">Fyzikální</String>
<String key="Choice.physics.derailment.old">Klasické, bez protokolu</String>
<String key="Choice.physics.collisions.old">Klasické</String>
<String key="Choice.physics.collisions.new">Fyzikální</String>
<String key="Choice.physics.collisions.monitor">Klasické, fyzikální do protokolu</String>
<String key="Choice.physics.trackbuckling.off">Vypnuto</String>
<String key="Choice.physics.trackbuckling.scenery">Ze scenérie</String>
<String key="Choice.physics.trackbuckling.auto">I z horka</String>
</Language>

Some files were not shown because too many files have changed in this diff Show More