diff --git a/StarterNG.Tests/DisplaysTests.cs b/StarterNG.Tests/DisplaysTests.cs deleted file mode 100644 index 18d83d5..0000000 --- a/StarterNG.Tests/DisplaysTests.cs +++ /dev/null @@ -1,100 +0,0 @@ -using StarterNG.Infrastructure; -using StarterNG.Tests.Fakes; - -namespace StarterNG.Tests; - -public class DisplaysTests -{ - /// A 128-byte block with an 18-byte timing at 54, as a panel's base EDID has it. - 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; - } - - /// A DisplayID 2.0 block with one type VII timing (kHz, sizes less one). - 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()); - } -} diff --git a/StarterNG.Tests/ExternalIniTests.cs b/StarterNG.Tests/ExternalIniTests.cs new file mode 100644 index 0000000..ba721d0 --- /dev/null +++ b/StarterNG.Tests/ExternalIniTests.cs @@ -0,0 +1,158 @@ +using StarterNG.Classes; +using StarterNG.Domain.Settings; +using StarterNG.Infrastructure.Settings; +using StarterNG.Tests.Fakes; + +namespace StarterNG.Tests; + +/// eu07.ini as other hands leave it: edited while the starter runs, and with lines the starter does not know. +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_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 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); + Assert.Contains("gfx.framebuffer.width 1920", saved); + Assert.Contains("gfx.framebuffer.height 1080", 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); + } +} diff --git a/StarterNG.Tests/GraphicsPresetTests.cs b/StarterNG.Tests/GraphicsPresetTests.cs index fa55f64..6de00f4 100644 --- a/StarterNG.Tests/GraphicsPresetTests.cs +++ b/StarterNG.Tests/GraphicsPresetTests.cs @@ -26,16 +26,13 @@ public class GraphicsPresetTests 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 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)); + .Where(key => lowKeys.GetValueOrDefault(key) != topKeys.GetValueOrDefault(key)); Assert.Equal(GraphicsPreset.Keys.OrderBy(k => k), differing.OrderBy(k => k)); } @@ -55,7 +52,7 @@ public class GraphicsPresetTests { // Sizes and filtering run out of steps above High. Climbs(p => p.TextureSize, 1); - Climbs(p => p.CabTextureSize, 1); + Climbs(p => p.CabTextureSize, 2); Climbs(p => p.Anisotropy, 1); // Four steps or three for six levels. @@ -65,28 +62,23 @@ public class GraphicsPresetTests 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. + // The simulator takes no more than its own 7 lights. Climbs(p => p.DynamicLights, 2); - Climbs(p => p.DrawRange, 1); - Climbs(p => p.DrawRangeFactor, 2); + Climbs(p => p.DrawRangeFactor, 3); 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); + Climbs(p => p.ShadowMap, 2); + Climbs(p => p.ShadowRange, 1); + // The old starter's steps begin at once a second: the lower levels share it. + Climbs(p => p.ReflectionsRate, 2); } [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)); + var rates = GraphicsPreset.All.Select(p => Steps.IndexOf(SliderRanges.ReflectionUpdates, p.ReflectionsRate)).ToList(); + Assert.All(rates.Zip(rates.Skip(1)), step => Assert.InRange(step.Second - step.First, 0, 2)); foreach (Func fidelity in new Func[] { p => p.SmokeFidelity, p => p.SplineFidelity }) { @@ -103,9 +95,7 @@ public class GraphicsPresetTests 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"); + .Where(key => own.GetValueOrDefault(key) != high.GetValueOrDefault(key)); Assert.Equal(new[] { "gfx.reflections.fidelity", "gfx.reflections.framerate", "gfx.shadows.cab.range", "gfx.smoke.fidelity", "splinefidelity" }, differing.OrderBy(k => k)); @@ -128,6 +118,8 @@ public class GraphicsPresetTests var again = new TestInstallation(installation.Files).SettingsStore; again.Load(); Assert.Same(GraphicsPreset.High, GraphicsPreset.Matching(again.Settings)); + // Nothing of an older starter to bring into the standard mode. + Assert.True(again.Settings.MovedToStandard); } [Fact] @@ -144,158 +136,102 @@ 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)); } [Fact] - public void The_new_renderers_scales_never_go_down() - { - void NeverDown(Func value) => Climbs(p => value(p.NewRenderer), 5); - - void TurnsOn(Func 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); - } - - [Fact] - public void Ultra_is_the_top_of_the_new_renderers_scales() - { - var ultra = GraphicsPreset.Ultra.NewRenderer; - - 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); - } - - [Fact] - public void Grass_fades_out_beyond_where_it_is_drawn_in_full() - { - var store = new TestInstallation().SettingsStore; - foreach (var preset in GraphicsPreset.All) - { - var settings = Defaults().Copy(); - 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.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() + public void Ultra_is_the_top_of_what_the_old_starter_offered() { var ultra = GraphicsPreset.Ultra; - double Top(string key) => SimulatorKeys.Named(key).Maximum; Assert.Equal(8192, ultra.TextureSize); - Assert.Equal(8192, ultra.CabTextureSize); + Assert.Equal(GraphicsRules.MaxCabTextureSize, ultra.CabTextureSize); Assert.Equal(8192, ultra.ShadowMap); - Assert.Equal(600, ultra.ShadowRange); + Assert.Equal(GraphicsRules.MaxShadowRange, ultra.ShadowRange); Assert.Equal(Steps.Anisotropy.Max(), ultra.Anisotropy); Assert.Equal(AntiAliasingMode.Msaa8, ultra.AntiAliasing); - Assert.Equal(Steps.ReflectionUpdates.Max(), ultra.ReflectionsRate); + Assert.Equal(SliderRanges.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(SliderRanges.DrawRangeFactors.Max(), ultra.DrawRangeFactor); 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); + Assert.True(ultra.Top!.Screens); } [Fact] - public void At_ultra_what_would_only_take_away_is_off() + public void No_level_goes_past_what_the_old_starter_gave() { - var top = GraphicsPreset.Ultra.Top!; + foreach (var preset in GraphicsPreset.All) + { + Assert.True(preset.ShadowRange <= GraphicsRules.MaxShadowRange, preset.NameKey); + Assert.True(preset.CabTextureSize <= GraphicsRules.MaxCabTextureSize, preset.NameKey); + } + } - // 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 No_level_sets_what_only_the_advanced_mode_shows() + { + var set = GraphicsPreset.Keys.Concat(GraphicsExtras.Keys).Concat(GraphicsTop.Keys).ToList(); + + // The rows of keys by name, the buffer and the resources are all the advanced mode's. + Assert.Empty(set.Intersect(SimulatorKeys.All.Select(key => key.Key))); + Assert.Empty(set.Intersect(new[] { "starter.bufferscale", "gfx.framebuffer.width", "gfx.framebuffer.height", + "compresstex", "python.mipmaps", "gfx.skippipeline" })); + } + + [Fact] + public void A_level_leaves_what_only_the_advanced_mode_shows_as_it_is() + { + foreach (var preset in GraphicsPreset.All) + { + var settings = Defaults().Copy(); + settings.BufferScalePercent = 80; + settings.CompressTextures = false; + settings.ScreenMipmaps = false; + settings.Extra["basedrawrange"] = "3000"; + settings.Extra["targetfps"] = "60"; + + preset.ApplyTo(settings); + + Assert.Equal(80, settings.BufferScalePercent); + Assert.False(settings.CompressTextures); + Assert.False(settings.ScreenMipmaps); + Assert.Equal("3000", settings.Extra["basedrawrange"]); + Assert.Equal("60", settings.Extra["targetfps"]); + Assert.Same(preset, GraphicsPreset.Matching(settings)); + } + } + + [Fact] + public void At_ultra_the_shadows_are_longest() + { + // The bottom of that scale. + Assert.Equal(0.2, GraphicsPreset.Ultra.Top!.ShadowAngleLimit); } [Fact] @@ -304,16 +240,14 @@ public class GraphicsPresetTests var settings = Defaults().Copy(); settings.ShadowAngleLimit = 0.8; settings.IgnoreIrrelevantTrains = true; - settings.Extra[GraphicsTop.TargetFpsKey] = "60"; - settings.Extra[GraphicsTop.TextureReleaseKey] = "2"; + settings.PythonScreens = false; 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]); + Assert.True(settings.PythonScreens); + Assert.True(settings.IgnoreIrrelevantTrains); } [Fact] @@ -335,12 +269,12 @@ public class GraphicsPresetTests { var settings = Defaults().Copy(); settings.IgnoreIrrelevantTrains = true; - settings.Extra[GraphicsTop.TargetFpsKey] = "60"; + settings.ShadowAngleLimit = 0.8; preset.ApplyTo(settings); Assert.True(settings.IgnoreIrrelevantTrains, preset.NameKey); - Assert.Equal("60", settings.Extra[GraphicsTop.TargetFpsKey]); + Assert.Equal(0.8, settings.ShadowAngleLimit); Assert.Same(preset, GraphicsPreset.Matching(settings)); } } @@ -352,26 +286,11 @@ public class GraphicsPresetTests GraphicsPreset.Ultra.ApplyTo(settings); Assert.Same(GraphicsPreset.Ultra, GraphicsPreset.Matching(settings)); - settings.Extra[GraphicsPreset.ReflectedVehiclesKey] = "250"; + settings.ReflectionsFramerate = 25; 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() { @@ -405,29 +324,17 @@ public class GraphicsPresetTests } [Fact] - public void Every_level_sets_the_buffer_and_is_not_recognised_with_another() + public void Every_level_is_within_what_the_sliders_offer() { 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)); + Assert.True(preset.TextureSize >= SliderRanges.MinTextureSize, preset.NameKey); + Assert.True(preset.ShadowMap >= SliderRanges.MinShadowMap, preset.NameKey); + Assert.True(preset.DynamicLights >= SliderRanges.MinDynamicLights, preset.NameKey); + Assert.Contains(preset.ReflectionsRate, SliderRanges.ReflectionUpdates); } } - [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() { @@ -453,14 +360,13 @@ public class GraphicsPresetTests { var settings = Defaults().Copy(); settings.MotionBlur = false; - settings.Extra[GraphicsTop.TargetFpsKey] = "60"; + settings.ShadowAngleLimit = 0.8; 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(0.8, settings.ShadowAngleLimit); Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys); } @@ -474,14 +380,12 @@ public class GraphicsPresetTests 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); } @@ -492,7 +396,6 @@ public class GraphicsPresetTests 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); @@ -502,7 +405,6 @@ public class GraphicsPresetTests 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); } @@ -512,12 +414,11 @@ public class GraphicsPresetTests var settings = Defaults().Copy(); GraphicsPreset.Ultra.ApplyTo(settings); - var applied = new GraphicsPresetMemory().Apply(GraphicsPreset.Low, settings); + 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] @@ -526,19 +427,18 @@ public class GraphicsPresetTests var memory = new GraphicsPresetMemory(); var settings = Defaults().Copy(); settings.MotionBlur = false; + settings.ShadowAngleLimit = 0.8; var extras = GraphicsExtras.Of(settings); var top = GraphicsTop.Of(settings); memory.Apply(GraphicsPreset.Minimal, settings); - var toUltra = memory.Apply(GraphicsPreset.Ultra, settings); + 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); + 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)); @@ -560,7 +460,6 @@ public class GraphicsPresetTests var applied = memory.Apply(GraphicsPreset.High, settings); Assert.True(settings.MotionBlur); - Assert.Equal(GraphicsPreset.RowKeys, applied.RowKeys); Assert.Equal(GraphicsPreset.Keys, applied.ChosenKeys); } @@ -596,33 +495,15 @@ public class GraphicsPresetTests [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); + 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.ShadowRange >= SimulatorSettings.ShadowRangeFloor(preset.ShadowMap), preset.NameKey); - Assert.Equal(0, preset.CabShadowsRange % 10); + Assert.True(Steps.IndexOf(SliderRanges.CabShadowRanges, preset.CabShadowsRange) >= 0, preset.NameKey); } } @@ -637,7 +518,7 @@ public class GraphicsPresetTests 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" }, + Assert.Equal(new[] { "dynamiclights", "gfx.extraeffects", "gfx.smoke.fidelity", "multisampling" }, GraphicsPreset.Keys.Except(inGroups).OrderBy(key => key, StringComparer.Ordinal)); } @@ -669,27 +550,22 @@ public class GraphicsPresetTests 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]); } [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_rest_with_it_is_that_level() { var groups = Groups(); foreach (var level in GraphicsPreset.All.Where(level => level.Extras is null)) @@ -697,8 +573,9 @@ public class GraphicsPresetTests var settings = Defaults().Copy(); foreach (var group in GraphicsGroup.All) settings = groups.Apply(group, level, settings); - settings.BufferScalePercent = level.BufferScale; settings.AntiAliasing = level.AntiAliasing; + settings.DynamicLights = level.DynamicLights; + settings.SmokeFidelity = level.SmokeFidelity; Assert.Same(level, GraphicsPreset.Matching(settings)); } @@ -718,14 +595,15 @@ public class GraphicsPresetTests { var groups = Groups(); var settings = AtHigh(); + settings.ShadowAngleLimit = 0.8; - var ultra = groups.Apply(GraphicsGroup.Textures, GraphicsPreset.Ultra, settings); - Assert.False(ultra.CompressTextures); - Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Textures]); + var ultra = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.Ultra, settings); + Assert.Equal(0.2, ultra.ShadowAngleLimit); + Assert.Same(GraphicsPreset.Ultra, groups.LevelsOf(ultra)[GraphicsGroup.Shadows]); - 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]); + var back = groups.Apply(GraphicsGroup.Shadows, GraphicsPreset.High, ultra); + Assert.Equal(GraphicsTop.None.ShadowAngleLimit, back.ShadowAngleLimit); + Assert.Same(GraphicsPreset.High, groups.LevelsOf(back)[GraphicsGroup.Shadows]); } [Fact] @@ -736,8 +614,9 @@ public class GraphicsPresetTests settings.Smoke = false; - var nature = Groups().Apply(GraphicsGroup.Nature, GraphicsPreset.VeryHigh, settings); - Assert.False(nature.Smoke); - Assert.Equal(GraphicsPreset.VeryHigh.SmokeFidelity, nature.SmokeFidelity); + var shadows = Groups().Apply(GraphicsGroup.Shadows, GraphicsPreset.VeryHigh, settings); + Assert.False(shadows.Smoke); + Assert.False(shadows.MotionBlur); + Assert.Equal(GraphicsPreset.VeryHigh.ShadowMap, shadows.ShadowMapResolution); } } diff --git a/StarterNG.Tests/GraphicsSettingsTests.cs b/StarterNG.Tests/GraphicsSettingsTests.cs index 9ecfcf6..74bbaf7 100644 --- a/StarterNG.Tests/GraphicsSettingsTests.cs +++ b/StarterNG.Tests/GraphicsSettingsTests.cs @@ -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,63 +37,54 @@ public class GraphicsSettingsTests private static string? Line(string text, string key) => Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal)); + // As application.cpp on master has them: a word it does not know gets the full renderer. [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("default", "default")] + [InlineData("full", "default")] + [InlineData("gl46", "default")] + [InlineData("vulkan", "default")] + [InlineData("vulkan14", "default")] [InlineData("legacy", "legacy")] [InlineData("simpleshader", "legacy")] + [InlineData("off", "legacy")] [InlineData("simple", "simple")] - [InlineData("experimental", "experimental")] - [InlineData("vulkan14", "vulkan")] - public void A_renderer_is_written_by_its_name(string read, string written) + [InlineData("experimental", "default")] + public void A_renderer_is_written_by_the_name_master_knows(string read, string written) { Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer")); } + [Fact] + public void Without_a_renderer_in_the_file_the_full_one_is_chosen() + { + Assert.Equal(0, Read("").RenderEngine); + Assert.Equal("gfxrenderer default", Line(Write(Read("")), "gfxrenderer")); + } + [Fact] public void An_older_renderer_stays_chosen_and_can_be_chosen_again() { var installation = WithIni("gfxrenderer legacy\n"); var store = installation.SettingsStore; - store.Settings.Clouds = 3; + store.Settings.FieldOfView = 50; 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); } [Fact] - public void Keys_only_an_older_simulator_reads_stay_in_the_file() + public void Keys_only_the_legacy_renderer_or_windows_read_stay_in_the_file() { 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" }; var installation = WithIni(string.Join("\n", old) + "\n"); - installation.SettingsStore.Settings.Clouds = 3; + installation.SettingsStore.Settings.FieldOfView = 50; installation.SettingsStore.Save(); @@ -101,6 +92,24 @@ public class GraphicsSettingsTests Assert.All(old, line => Assert.Contains(line, saved)); } + [Fact] + public void Keys_of_the_vulkan_renderer_master_does_not_have_go_on_a_save() + { + 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" + }; + var installation = WithIni("calibratein 0 0 0 0\n" + string.Join("\n", vulkan) + "\n"); + + installation.SettingsStore.Save(); + + string saved = installation.Files.ReadAllText(UserIni); + Assert.Contains("calibratein 0 0 0 0", saved); + Assert.All(vulkan, line => Assert.Null(Line(saved, line.Split(' ')[0]))); + } + [Fact] public void Levels_leave_the_switches_only_an_older_simulator_reads() { @@ -111,160 +120,26 @@ public class GraphicsSettingsTests Assert.Equal((false, true, true), (s.UseVbo, s.UseGLES, s.RenderAngleVulkan)); } - [Fact] - public void The_new_graphics_keys_are_read() + [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)] + public void Multisampling_is_read_as_master_reads_it(string text, AntiAliasingMode expected) { - 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"); - - 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); + Assert.Equal(expected, Read(text).AntiAliasing); } [Fact] - public void Missing_keys_take_the_simulators_defaults() - { - var s = Read(""); - - 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); - } - - [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() + public void Multisampling_is_written_to_its_own_key_only() { 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)); + Assert.Null(Line(text, "gfx.antialiasing")); } [Fact] @@ -278,10 +153,23 @@ 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_starters_own_key_or_the_framebuffer_against_the_window() { 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_framebuffer_master_reads() + { + var s = Read("width 1920\nheight 1080\nstarter.bufferscale 50\n"); + + string text = Write(s); + + Assert.Equal("gfx.framebuffer.width 960", Line(text, "gfx.framebuffer.width")); + Assert.Equal("gfx.framebuffer.height 540", Line(text, "gfx.framebuffer.height")); + Assert.Null(Line(text, "gfx.buffer.percent")); } [Fact] @@ -312,7 +200,7 @@ public class GraphicsSettingsTests { var s = new SimulatorSettings(); GraphicsPreset.High.ApplyTo(s); - s.Clouds = 4; + s.DynamicLights = 2; Assert.Null(GraphicsPreset.Matching(s)); } @@ -328,82 +216,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(SimulatorSettings.RenderEngineOf("legacy"), s.RenderEngine); 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 +285,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 +327,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); - } } diff --git a/StarterNG.Tests/MonitorsTests.cs b/StarterNG.Tests/MonitorsTests.cs new file mode 100644 index 0000000..af99b4d --- /dev/null +++ b/StarterNG.Tests/MonitorsTests.cs @@ -0,0 +1,61 @@ +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")); + } +} diff --git a/StarterNG.Tests/RenderersTests.cs b/StarterNG.Tests/RenderersTests.cs new file mode 100644 index 0000000..589a1f4 --- /dev/null +++ b/StarterNG.Tests/RenderersTests.cs @@ -0,0 +1,17 @@ +using StarterNG.Domain.Settings; + +namespace StarterNG.Tests; + +public class RenderersTests +{ + [Theory] + [InlineData("default", RendererKind.Modern)] + [InlineData("full", RendererKind.Modern)] + [InlineData("vulkan", RendererKind.Modern)] + [InlineData("legacy", RendererKind.Legacy)] + [InlineData("simple", RendererKind.Legacy)] + [InlineData("simpleshader", RendererKind.Legacy)] + [InlineData("OFF", RendererKind.Legacy)] + public void A_renderer_word_draws_with_the_renderer_master_gives_it(string word, RendererKind kind) => + Assert.Equal(kind, Renderers.KindOf(word)); +} diff --git a/StarterNG.Tests/ScreenReaderNamesTests.cs b/StarterNG.Tests/ScreenReaderNamesTests.cs index af79220..4f96972 100644 --- a/StarterNG.Tests/ScreenReaderNamesTests.cs +++ b/StarterNG.Tests/ScreenReaderNamesTests.cs @@ -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)); } diff --git a/StarterNG.Tests/SettingReachTests.cs b/StarterNG.Tests/SettingReachTests.cs deleted file mode 100644 index 68d633e..0000000 --- a/StarterNG.Tests/SettingReachTests.cs +++ /dev/null @@ -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); - } -} diff --git a/StarterNG.Tests/SettingsStoreTests.cs b/StarterNG.Tests/SettingsStoreTests.cs index 68c1730..74fd1de 100644 --- a/StarterNG.Tests/SettingsStoreTests.cs +++ b/StarterNG.Tests/SettingsStoreTests.cs @@ -492,7 +492,7 @@ 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")] + [InlineData("mousescale 2.5 0.5", false, true, "mousescale 2.5 -0.5")] // 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( @@ -540,7 +540,35 @@ public class SettingsStoreTests installation.SettingsStore.Save(); - Assert.Equal("mousescale 2 0.2", LineFor(installation, "mousescale")); + Assert.Equal("mousescale 2 0.5", LineFor(installation, "mousescale")); + } + + [Theory] + // The second number is always 0.5, as the old starter wrote it; its sign is the inversion. + [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")] + // A zero locks that axis in the simulator: the camera turns only left/right. + // X goes back to the default. + [InlineData("mousescale 0.5 0", "mousescale 0.5 0.5")] + [InlineData("mousescale 0.5 -0", "mousescale 0.5 0.5")] + [InlineData("mousescale 0 0.5", "mousescale 2 0.5")] + [InlineData("mousescale 0 0", "mousescale 2 0.5")] + [InlineData("mousescale 1.5 NaN", "mousescale 1.5 0.5")] + [InlineData("mousescale Infinity -0.5", "mousescale 2 -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 0.5 0.5\t// (3.2 0.5) komentarz")] + // A decimal comma: the simulator reads "0,2" as 0. + [InlineData("mousescale 0.5 0,2", "mousescale 0.5 0.5")] + public void A_mouse_scale_axis_that_would_not_move_gets_the_default(string line, string written) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, line + "\n")); + installation.SettingsStore.Load(); + + installation.SettingsStore.Save(); + + Assert.Equal(written, LineFor(installation, "mousescale")); } // ── A file that could not be read ──────────────────────────────────────── @@ -885,12 +913,8 @@ public class SettingsStoreTests [InlineData("default")] [InlineData("simpleshader")] [InlineData("off")] - [InlineData("opengl")] - [InlineData("gl46")] - [InlineData("vulkan14")] [InlineData("legacy")] [InlineData("simple")] - [InlineData("experimental")] public void A_renderer_word_the_simulator_reads_as_another_stays_until_changed(string word) { var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n")); @@ -901,16 +925,33 @@ public class SettingsStoreTests Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation)); } + // Words master does not know start the full renderer with a line in its log, and the + // experimental renderer is not in a player's build: a save puts "default" in their place. [Theory] - [InlineData(0, "full")] + [InlineData("full")] + [InlineData("opengl")] + [InlineData("gl46")] + [InlineData("vulkan14")] + [InlineData("experimental")] + [InlineData("null")] + public void A_renderer_word_master_does_not_run_is_saved_as_default(string word) + { + var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n")); + installation.SettingsStore.Load(); + + installation.SettingsStore.Save(); + + Assert.Contains("gfxrenderer default\n", SavedLines(installation)); + } + + [Theory] + [InlineData(0, "default")] [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) { - // application.cpp knows full (or default), experimental and simple; every - // other word - "simpleshader" and "off" from older starters - is legacy. + // application.cpp on master knows default, legacy and simple; "simpleshader" and "off" + // from older starters are legacy, and any other word gets the full renderer. var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "gfxrenderer simpleshader\n")); installation.SettingsStore.Load(); installation.SettingsStore.Settings.RenderEngine = engine == 1 ? 0 : engine; @@ -926,8 +967,10 @@ public class SettingsStoreTests [InlineData("full", 0)] [InlineData("gl46", 0)] [InlineData("opengl", 0)] - [InlineData("vulkan", 4)] - [InlineData("VULKAN14", 4)] + [InlineData("vulkan", 0)] + [InlineData("VULKAN14", 0)] + [InlineData("whatever", 0)] + [InlineData("experimental", 0)] [InlineData("simpleshader", 1)] public void A_renderer_word_stands_where_the_simulator_reads_it(string word, int engine) { @@ -935,7 +978,7 @@ public class SettingsStoreTests } [Fact] - public void The_buffer_is_written_for_old_and_new_simulators() + public void The_buffer_is_written_as_the_framebuffer_master_reads() { var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, "width 1000\nheight 500\n")); installation.SettingsStore.Load(); @@ -944,19 +987,20 @@ public class SettingsStoreTests installation.SettingsStore.Save(); string saved = SavedLines(installation); - Assert.Contains("gfx.buffer.percent 50\n", saved); + Assert.DoesNotContain("gfx.buffer.percent", saved); Assert.Contains("gfx.framebuffer.width 500\n", saved); Assert.Contains("gfx.framebuffer.height 250\n", 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", 100)] + public void The_buffer_is_read_from_the_starters_key_or_the_framebuffer(string ini, int percent) { var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, ini)); @@ -965,36 +1009,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() { diff --git a/StarterNG.Tests/SliderStepsTests.cs b/StarterNG.Tests/SliderStepsTests.cs new file mode 100644 index 0000000..5fb853b --- /dev/null +++ b/StarterNG.Tests/SliderStepsTests.cs @@ -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 = 1 / 300.0 }; + + // The simulator's own once in five minutes, shown before the old starter's 1 to 60. + Assert.Equal(1 / 300.0, 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.CabShadowRanges) { Clamps = true, Value = 15 }; + + Assert.Equal(15, steps.Value); + + steps.Value = -5; + Assert.Equal(0, steps.Value); + } +} diff --git a/StarterNG.Tests/TrainsetDisplayTests.cs b/StarterNG.Tests/TrainsetDisplayTests.cs index fdadd3b..544a72b 100644 --- a/StarterNG.Tests/TrainsetDisplayTests.cs +++ b/StarterNG.Tests/TrainsetDisplayTests.cs @@ -1,5 +1,6 @@ using StarterNG.Classes; using StarterNG.Domain; +using StarterNG.Domain.Settings; using StarterNG.Views; namespace StarterNG.Tests; @@ -58,6 +59,63 @@ 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_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)] diff --git a/StarterNG/Application/AppServices.cs b/StarterNG/Application/AppServices.cs index 2f6f1a8..838b163 100644 --- a/StarterNG/Application/AppServices.cs +++ b/StarterNG/Application/AppServices.cs @@ -63,13 +63,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); @@ -141,8 +140,6 @@ public sealed class AppServices public GraphicsCards GraphicsCards { get; } - public Displays Displays { get; } - public SettingsPaths SettingsPaths { get; } public MissingVehicleLog MissingVehicleLog { get; } diff --git a/StarterNG/Application/SettingsStore.cs b/StarterNG/Application/SettingsStore.cs index 036bf80..5f4c0ed 100644 --- a/StarterNG/Application/SettingsStore.cs +++ b/StarterNG/Application/SettingsStore.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -75,6 +76,9 @@ public sealed class SettingsStore public string SavePath => _savePath; + /// The last save found eu07.ini changed by something else and kept those changes: what is held was read again. + public bool LastSaveMerged { get; private set; } + public void RegisterCapture(ISettingsCapture capture) => _capture = capture; public void Load() @@ -92,9 +96,30 @@ public sealed class SettingsStore return; GraphicsPreset.High.ApplyTo(Settings); + // Nothing of an older starter to bring over: the settings start in the standard mode. + Settings.MovedToStandard = true; Save(); } + /// + /// A copy of eu07.ini beside it, the file name and , before + /// something changes many keys at once; one already there is left as it is. + /// + 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 @@ -160,8 +185,30 @@ 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)); + 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 { @@ -188,16 +235,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"); } - /// Whether the simulator can have DLSS on this platform at all. - public bool DlssPlatform => _serializer.DlssPlatform; - /// /// 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 +262,6 @@ 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; _serializer.Read(s, imported); @@ -234,8 +270,6 @@ public sealed class SettingsStore s.Gpu = gpu; s.LastScenery = lastScenery; s.WindowMaximized = maximized; - s.CabLampLight = cabLampLight; - s.DepthPrepassScene = depthPrepassScene; // an ini of before the tapes of the trains goes the same way as a profile SettingsSerializer.MoveToTrainTapes(s); return true; @@ -284,6 +318,86 @@ public sealed class SettingsStore return keys; } + /// + /// 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. + /// + public IReadOnlyDictionary UnreadableValues() + { + var unreadable = new Dictionary(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 && !SameValue(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.Number => double.TryParse(first, NumberStyles.Float, CultureInfo.InvariantCulture, out _), + _ => true + }; + if (!readable) + unreadable[key.Key] = raw; + } + 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 NotReadAlone = new(StringComparer.OrdinalIgnoreCase) + { + "mousescale", "gfxrenderer", "gfx.shadowmap.enabled", "gfx.framebuffer.width", "gfx.framebuffer.height" + }; + + private SimulatorSettings WithFile(ConfigFile config) + { + var s = new SimulatorSettings(); + _serializer.Read(s, config); + return s; + } + + // 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) && 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 + }; + /// /// What saving would change in the file: the keys /// changed since it was read, those it lacks, and the ones no simulator reads. @@ -296,6 +410,8 @@ public sealed class SettingsStore var shown = _capture?.ShownUnlikeSettings ?? new Dictionary(); var changes = new List(); var listed = new HashSet(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 +438,14 @@ public sealed class SettingsStore return Uart.FeaturesStand(_config.GetRaw(key), value); if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase)) return _config.GetRaw(key) == value; + if (string.Equals(key, "gfxrenderer", StringComparison.OrdinalIgnoreCase) && + !SimulatorSettings.KeptRendererWord(_config.GetRaw(key))) + return false; + if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) && + !SettingsSerializer.MouseScaleStands(_config.GetRaw(key))) + return false; + if (overCap.Contains(key)) + return false; string? synced = _synced.GetValueOrDefault(key); if (shown.TryGetValue(key, out var onScreen) && onScreen.Shown == value && onScreen.Held == synced) return true; diff --git a/StarterNG/Classes/ConfigFile.cs b/StarterNG/Classes/ConfigFile.cs index 71f3459..b2e8eaa 100644 --- a/StarterNG/Classes/ConfigFile.cs +++ b/StarterNG/Classes/ConfigFile.cs @@ -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); } @@ -252,17 +259,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++) diff --git a/StarterNG/Controls/SettingRow.cs b/StarterNG/Controls/SettingRow.cs index 5c912ef..d71873e 100644 --- a/StarterNG/Controls/SettingRow.cs +++ b/StarterNG/Controls/SettingRow.cs @@ -19,11 +19,27 @@ public class SettingRow : ContentControl AvaloniaProperty.Register(nameof(ValueText)); /// - /// 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. /// - public static readonly StyledProperty IdleNoteProperty = - AvaloniaProperty.Register(nameof(IdleNote)); + public static readonly StyledProperty AdvancedProperty = + AvaloniaProperty.Register(nameof(Advanced)); + + public bool Advanced + { + get => GetValue(AdvancedProperty); + set => SetValue(AdvancedProperty, value); + } + + /// The value eu07.ini gives the setting that the starter cannot read, said under it; null when there is none. + public static readonly StyledProperty UnknownValueProperty = + AvaloniaProperty.Register(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)); } } diff --git a/StarterNG/Controls/SettingsSection.cs b/StarterNG/Controls/SettingsSection.cs index 085a312..73d0eb1 100644 --- a/StarterNG/Controls/SettingsSection.cs +++ b/StarterNG/Controls/SettingsSection.cs @@ -7,6 +7,16 @@ namespace StarterNG.Controls; public class SettingsSection : HeaderedContentControl { + /// Every row of the section is for the advanced mode only. + public static readonly StyledProperty AdvancedProperty = + AvaloniaProperty.Register(nameof(Advanced)); + + public bool Advanced + { + get => GetValue(AdvancedProperty); + set => SetValue(AdvancedProperty, value); + } + public static readonly StyledProperty ToggleProperty = AvaloniaProperty.Register(nameof(Toggle)); diff --git a/StarterNG/Domain/Settings/GraphicsPreset.cs b/StarterNG/Domain/Settings/GraphicsPreset.cs index 2b14982..4d6af06 100644 --- a/StarterNG/Domain/Settings/GraphicsPreset.cs +++ b/StarterNG/Domain/Settings/GraphicsPreset.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; namespace StarterNG.Domain.Settings; @@ -40,176 +39,42 @@ public sealed record GraphicsExtras( } /// -/// 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. +/// What only Ultra sets, with no scale to climb: the longest shadows, at the bottom of their +/// limit, and the screens drawn. What only the advanced mode shows no level sets. /// /// 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). -/// targetfps: above 0 the simulator moves the distance factor by itself. -/// python.fpslimit: read only by the screens' separate windows -/// (pythonscreenviewer.cpp), it does nothing without them. -/// gfx.textures.releasedistance: above 0 textures of far vehicles leave the card. -/// compresstex: on saves card memory at a cost to the picture. -/// starter.ignoreirrelevant: on leaves decorative consists out of the scenario. -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) +/// python.enabled. +public sealed record GraphicsTop(double ShadowAngleLimit, bool Screens) { - 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"; - - /// Those of its keys shown as rows of . - public static readonly IReadOnlyList RowKeys = new[] - { - TargetFpsKey, ScreenWindowFpsKey, TextureReleaseKey, SkyKey, CabKey, AirCouplersKey, SmoothTractionKey - }; - /// The eu07.ini keys these values live in. - public static readonly IReadOnlyList Keys = RowKeys.Concat(new[] - { - "gfx.shadow.angle.min", "python.enabled", "python.mipmaps", "compresstex", "starter.ignoreirrelevant" - }).ToList(); + public static readonly IReadOnlyList Keys = new[] { "gfx.shadow.angle.min", "python.enabled" }; /// What they are with nothing set, as . - public static readonly GraphicsTop None = - new(0.2, 0, 100, 0, true, true, true, false, true, true, true, true); + public static readonly GraphicsTop None = new(0.2, 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 static GraphicsTop Of(SimulatorSettings s) => new(s.ShadowAngleLimit, s.PythonScreens); 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); - } -} - -/// -/// 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. -/// -/// gfx.cabprobe.interval, in frames: the lower the dearer. -/// gfx.raytracing: the Vulkan renderer's alone, off on OpenGL. -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) -{ - /// The eu07.ini keys these values live in; the fade of the grass follows its distance. - public static readonly IReadOnlyList 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); - - /// This level as it lands on : ray tracing on Vulkan only. - 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; } } /// /// A level of detail set in one go: what weighs on the graphics card. Every scale climbs in /// even steps from to , 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 . +/// levels. A level sets only what the standard mode shows, and only to what its sliders offer +/// (, the old starter's ranges): never past the old starter. The screen +/// (resolution, buffer, 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 . /// /// Its name's translation key. /// gfx.shadows.cab.range, in metres, read only by the legacy renderer. -/// Multisampling, as older simulators read it too. DLSS, once on, stays: no level does better. -/// gfx.reflections.framerate, in updates a second. -/// basedrawrange, in metres. Below 2000 it changes nothing on screen: the renderer -/// keeps at least that for signals and lights (opengl33renderer.cpp). -/// 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. -/// starter.bufferscale, in percent. Above the screen over High: on a 4K one -/// Ultra is a picture of 8K, multisampled on top. +/// multisampling. +/// gfx.reflections.framerate, in updates a second, one of the old starter's steps. /// gfx.drawrange.factor.max: how far the regulator may stretch the draw range. public sealed record GraphicsPreset( string NameKey, @@ -228,122 +93,73 @@ public sealed record GraphicsPreset( 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) { - 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"; - - /// Those of its keys shown as rows of . - public static readonly IReadOnlyList RowKeys = new[] - { - DrawRangeKey, DistanceFactorKey, SleeperKey, ReflectedInstancesKey, ReflectedVehiclesKey - }; - /// The eu07.ini keys a level sets. public static readonly IReadOnlyList Keys = new[] { - "maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "gfx.antialiasing", "dynamiclights", + "maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", "multisampling", "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(); + "splinefidelity", "gfx.drawrange.factor.max", "gfx.shadows.cab.range" + }; - /// The last resort: no shadows, no reflections, no effects, no smoke, a softer picture. + /// The last resort: no shadows, no reflections, no effects, no smoke. 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), + DynamicLights: 1, SmokeFidelity: 1, Shadows: false, ShadowMap: 1024, ShadowRange: 75, ShadowRank: 1, + EnvMap: false, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: false, + SplineFidelity: 1, DrawRangeFactor: 1, CabShadowsRange: 0, Extras: new GraphicsExtras(MotionBlur: false, ChromaticAberration: false, Smoke: false, PythonUpdateMs: 800)); 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)); + EnvMap: true, ReflectionsFidelity: 0, ReflectionsRate: 1, ExtraEffects: true, + SplineFidelity: 2, DrawRangeFactor: 1, CabShadowsRange: 0); 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)); + EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 1, ExtraEffects: true, + SplineFidelity: 2, DrawRangeFactor: 2, CabShadowsRange: 20); /// /// 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. + /// with levels to go under this one, or below what the old starter offered. /// 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)); - - /// For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m. - 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)); + EnvMap: true, ReflectionsFidelity: 1, ReflectionsRate: 3, ExtraEffects: true, + SplineFidelity: 2, DrawRangeFactor: 3, CabShadowsRange: 30); /// - /// 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 . + /// For a strong card. A map of 4096 doubles the cascades, so the range here reaches 800 m. + /// Filtering stays as High's, so the textures tell this level from Ultra. + /// + public static readonly GraphicsPreset VeryHigh = new( + "PresetVeryHigh", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 8, AntiAliasing: AntiAliasingMode.Msaa8, + DynamicLights: 7, SmokeFidelity: 3, Shadows: true, ShadowMap: 4096, ShadowRange: 400, ShadowRank: 3, + EnvMap: true, ReflectionsFidelity: 2, ReflectionsRate: 10, ExtraEffects: true, + SplineFidelity: 3, DrawRangeFactor: 3, CabShadowsRange: 50); + + /// + /// The top of every slider, which is the most the old starter gave. Not the best picture + /// throughout: a map of 8192 stretches the cascades fourfold, so shadows reach 1600 m but are + /// coarser up close than at . /// 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, + "PresetUltra", TextureSize: 8192, CabTextureSize: 4096, Anisotropy: 16, AntiAliasing: AntiAliasingMode.Msaa8, + DynamicLights: 7, SmokeFidelity: 4, Shadows: true, ShadowMap: 8192, ShadowRange: 400, 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), + SplineFidelity: 4, DrawRangeFactor: 3, CabShadowsRange: 100, 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)); + Top: new GraphicsTop(ShadowAngleLimit: 0.2, Screens: true)); public static readonly IReadOnlyList All = new[] { Minimal, Low, Medium, High, VeryHigh, Ultra }; @@ -352,8 +168,7 @@ public sealed record GraphicsPreset( s.MaxTextureSize = TextureSize; s.MaxCabTextureSize = CabTextureSize; s.TextureFiltering = Anisotropy; - if (!GraphicsRules.IsDlss(s.AntiAliasing)) - s.AntiAliasing = AntiAliasing; + s.AntiAliasing = AntiAliasing; s.CabShadowsRange = CabShadowsRange; s.DynamicLights = DynamicLights; s.SmokeFidelity = SmokeFidelity; @@ -366,14 +181,7 @@ public sealed record GraphicsPreset( 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); } @@ -381,20 +189,14 @@ public sealed record GraphicsPreset( /// Whether is at this level throughout. public bool Matches(SimulatorSettings s) => s.MaxTextureSize == TextureSize && s.MaxCabTextureSize == CabTextureSize && - Near(s.TextureFiltering, Anisotropy) && (GraphicsRules.IsDlss(s.AntiAliasing) || s.AntiAliasing == AntiAliasing) && + Near(s.TextureFiltering, Anisotropy) && s.AntiAliasing == AntiAliasing && s.DynamicLights == DynamicLights && s.SmokeFidelity == SmokeFidelity && s.RenderShadows == Shadows && 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.SplineFidelity == SplineFidelity && Near(s.DrawRangeFactor, DrawRangeFactor) && s.CabShadowsRange == CabShadowsRange && - GraphicsNewRenderer.Of(s) == NewRenderer.For(s) && (Extras is null || GraphicsExtras.Of(s) == Extras) && (Top is null || GraphicsTop.Of(s) == Top); @@ -407,31 +209,23 @@ public sealed record GraphicsPreset( return key.ParseNumber(key.RawIn(s)); } - 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; } /// /// 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. +/// of a level - the anti-aliasing, the post-processing switches, the dynamic lights and the smoke - goes only with the whole. /// /// The eu07.ini keys it sets. public sealed record GraphicsGroup(IReadOnlyList Keys) { - public static readonly GraphicsGroup DrawRange = new(new[] - { - GraphicsPreset.DrawRangeKey, GraphicsPreset.DistanceFactorKey, "splinefidelity", - GraphicsPreset.SleeperKey, "gfx.drawrange.factor.max" - }); + public static readonly GraphicsGroup DrawRange = new(new[] { "splinefidelity", "gfx.drawrange.factor.max" }); public static readonly GraphicsGroup Textures = new(new[] { - "maxtexturesize", "maxcabtexturesize", "anisotropicfiltering", - "compresstex", GraphicsTop.TextureReleaseKey + "maxtexturesize", "maxcabtexturesize", "anisotropicfiltering" }); public static readonly GraphicsGroup Shadows = new(new[] @@ -439,39 +233,20 @@ public sealed record GraphicsGroup(IReadOnlyList Keys) "shadows", "gfx.shadowmap.enabled", "shadowtune", "gfx.shadow.rank.cutoff", "gfx.shadow.angle.min", "gfx.shadows.cab.range" }); - public static readonly GraphicsGroup Lights = new(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" - }); - public static readonly GraphicsGroup Reflections = new(new[] { - "gfx.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate", - GraphicsPreset.ReflectedInstancesKey, GraphicsPreset.ReflectedVehiclesKey, "gfx.ssr", "gfx.raytracing" - }); - - public static readonly GraphicsGroup Atmosphere = new(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.envmap.enabled", "gfx.reflections.fidelity", "gfx.reflections.framerate" }); public static readonly IReadOnlyList All = new[] { - DrawRange, Textures, Shadows, Lights, Reflections, Atmosphere, Nature + DrawRange, Textures, Shadows, Reflections }; } /// What applying a level touched. -/// The keys of rows to show its values in, in that order. /// The eu07.ini keys it chose as a whole. -public sealed record PresetApplied(IReadOnlyList RowKeys, IReadOnlyList ChosenKeys); +public sealed record PresetApplied(IReadOnlyList ChosenKeys); /// /// Remembers what was there before an end of the scale, which comes back with any level @@ -498,15 +273,11 @@ public sealed class GraphicsPresetMemory comingTop?.ApplyTo(settings); preset.ApplyTo(settings); - var rows = new List(GraphicsPreset.RowKeys); var chosen = new List(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); + return new PresetApplied(chosen); } } diff --git a/StarterNG/Domain/Settings/GraphicsRules.cs b/StarterNG/Domain/Settings/GraphicsRules.cs index 16ae082..b461ed3 100644 --- a/StarterNG/Domain/Settings/GraphicsRules.cs +++ b/StarterNG/Domain/Settings/GraphicsRules.cs @@ -1,115 +1,32 @@ namespace StarterNG.Domain.Settings; /// -/// 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). /// public static class GraphicsRules { - public static bool IsDlss(AntiAliasingMode mode) => mode is AntiAliasingMode.Dlss or AntiAliasingMode.Dlaa; + /// maxcabtexturesize: the old starter's list ended at 4096. + 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; + /// The projection range of shadowtune: the old starter's list ended at 400. + public const int MaxShadowRange = 400; /// - /// 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. /// - 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); - - /// The frame generation goes with gfx.antialiasing dlss or dlaa, nothing else. - public static bool FrameGenerationAllowed(SimulatorSettings s, bool dlssPlatform) => DlssActive(s, dlssPlatform); - - /// Reflex (VK_NV_low_latency2) is the Vulkan renderer's only. - public static bool ReflexAllowed(SimulatorSettings s) => IsVulkan(s); - - /// The frame generation turns Reflex on whatever gfx.reflex says. - public static bool ReflexForced(SimulatorSettings s, bool dlssPlatform) => - FrameGenerationAllowed(s, dlssPlatform) && s.FrameGeneration > 1; - - /// Ray traced reflections: the Vulkan renderer on a GPU with ray queries. - public static bool RayTracingAllowed(SimulatorSettings s) => IsVulkan(s); - - /// The render scale is ignored by DLAA, which always draws at the size of the window. - public static bool BufferScaleUsed(SimulatorSettings s, bool dlssPlatform) => - !(DlssActive(s, dlssPlatform) && s.AntiAliasing == AntiAliasingMode.Dlaa); - - /// TAA and DLSS run in the post-processing which gfx.skippipeline leaves out. - public static bool TemporalWithoutPipeline(SimulatorSettings s) => s.SkipPipeline && IsTemporal(s.AntiAliasing); - - /// With the clustered lights the headlights come from the clusters; dynamiclights only caps the old path. - public static bool DynamicLightsUsed(SimulatorSettings s) => !s.LightsClustered; - - /// The ambient occlusion goes into the lighting only with GTAO. - public static bool AoLightingUsed(SimulatorSettings s) => s.AmbientOcclusion == 2; - - /// - /// 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). - /// - 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; - - /// - /// 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. - /// - public static bool CabProbeLights(SimulatorSettings s) => CabProbeUsed(s) && s.LightsClustered && s.CabLampLight; - - /// - /// 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. - /// - public static void Normalize(SimulatorSettings s, bool dlssPlatform) + /// Brings the values within the ranges the simulator clamps them to, and the starter's caps. + 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); diff --git a/StarterNG/Domain/Settings/Renderers.cs b/StarterNG/Domain/Settings/Renderers.cs new file mode 100644 index 0000000..e47ec98 --- /dev/null +++ b/StarterNG/Domain/Settings/Renderers.cs @@ -0,0 +1,14 @@ +namespace StarterNG.Domain.Settings; + +/// The renderers a gfxrenderer word picks, as application.cpp tells them apart. +public enum RendererKind { Modern, Legacy } + +public static class Renderers +{ + /// "legacy", "simple", "simpleshader" and "off" draw with the legacy renderer, any other word with the full one. + public static RendererKind KindOf(string renderer) => renderer.ToLowerInvariant() switch + { + "legacy" or "simple" or "simpleshader" or "off" => RendererKind.Legacy, + _ => RendererKind.Modern + }; +} diff --git a/StarterNG/Domain/Settings/SettingReach.cs b/StarterNG/Domain/Settings/SettingReach.cs deleted file mode 100644 index c7711dc..0000000 --- a/StarterNG/Domain/Settings/SettingReach.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace StarterNG.Domain.Settings; - -/// Why the simulator about to be started would pass a key over. -public enum IdleReason -{ - None, - WindowsBuildOnly, - LegacyRendererOnly, - /// Read by the full OpenGL renderer alone. - ModernRendererOnly, - /// Read by the OpenGL renderers, which the experimental one is not. - OpenGlRenderersOnly, - NeedsNetworkServer, - /// The draw range is only stretched by the frame rate regulator, which is off. - NeedsFrameRateTarget, - /// fullscreenwindowed takes the monitor's own mode instead. - MonitorModeInstead, - VulkanOnly -} - -/// What about the simulator to be started decides which keys it heeds. -/// The executable is a Windows build, under Wine or not. -/// The gfxrenderer word, as has it. -/// eu07.ini starts a network.server. -/// targetfps as eu07.ini sets it, or null where it does not. -/// fpsaverage, the older regulator's target; 0 for none. -/// fullscreenwindowed is on. -public sealed record SimulatorTarget(bool WindowsBuild, string Renderer, bool NetworkServer, - double? TargetFps = null, double FpsAverage = 0, - bool FullscreenWindowed = false); - -/// The renderers a gfxrenderer word picks, as application.cpp tells them apart. -public enum RendererKind { Modern, Legacy, Experimental } - -/// -/// 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. -/// -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 WindowsBuildOnly = new(StringComparer.OrdinalIgnoreCase) - { - "feedbackmode", "feedbackport", "showsystemconsole", "gfx.angleplatform" - }; - - // Read by openglrenderer.cpp alone; the modern path forces VBOs on. - private static readonly HashSet 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 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 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 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 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; - } - - /// - /// 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. - /// - private static bool DrawRangeRegulated(SimulatorTarget target) => - target.FpsAverage != 0 || (target.TargetFps ?? 0) != 0; - - /// "full", its other names and the Vulkan renderer are the modern kind, "experimental" its own; every other word the legacy one. - 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"; -} diff --git a/StarterNG/Domain/Settings/SimulatorKeys.cs b/StarterNG/Domain/Settings/SimulatorKeys.cs index c391fe2..f0d53c7 100644 --- a/StarterNG/Domain/Settings/SimulatorKeys.cs +++ b/StarterNG/Domain/Settings/SimulatorKeys.cs @@ -63,6 +63,12 @@ public sealed record SimulatorKey( public static class SimulatorKeys { + /// + /// The keys a player sees in the standard mode, which has what the old starter had. It had + /// none of these: they are all for the advanced mode. + /// + public static readonly IReadOnlySet Standard = new HashSet(StringComparer.OrdinalIgnoreCase); + public const string General = "general"; public const string Graphics = "graphics"; public const string Sound = "sound"; @@ -94,13 +100,12 @@ public static class SimulatorKeys Toggle("loadinglog", false, General, "IniSectionInterface"), Toggle("captureonstart", true, General, "IniSectionInterface"), Toggle("mousecontrol", true, General, "IniSectionInterface"), - Text("fullscreenmonitor", General, "IniSectionInterface"), Text("screenshotsdir", General, "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("sleeperdistance", 250, Graphics, "IniSectionRanges", 0, 1000, 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"), diff --git a/StarterNG/Domain/Settings/SimulatorSettings.cs b/StarterNG/Domain/Settings/SimulatorSettings.cs index b62bf3e..93e9a76 100644 --- a/StarterNG/Domain/Settings/SimulatorSettings.cs +++ b/StarterNG/Domain/Settings/SimulatorSettings.cs @@ -8,11 +8,8 @@ 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. 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 } +// multisampling: 0 off, then 2, 4 and 8 samples. +public enum AntiAliasingMode { Off, Msaa2, Msaa4, Msaa8 } public sealed class SimulatorSettings { @@ -34,7 +31,8 @@ public sealed class SimulatorSettings public bool InvertMouseHorizontal; public bool InvertMouseVertical; - public bool IgnoreGamepad; + /// input.gamepad no: the recommended setting, so the starter's default, though the simulator's own is yes. + public bool IgnoreGamepad = true; public int FeedbackMode = 1; public int FeedbackPort = 888; public bool UartEnabled; @@ -55,8 +53,6 @@ public sealed class SimulatorSettings public bool LogMissingVehicleFiles; public int RenderEngine; - public GraphicsBackend Backend => RenderEngine == VulkanEngine ? GraphicsBackend.Vulkan : GraphicsBackend.OpenGL; - public string VulkanDevice = ""; public int Width = 1280; public int Height = 720; public int BufferScalePercent = 100; @@ -64,9 +60,6 @@ public sealed class SimulatorSettings 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,37 +70,8 @@ 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. + // Only the legacy renderer, or only Windows builds, read these. public bool UseVbo = true; public bool RenderAngleVulkan; public bool UseGLES; @@ -127,6 +91,8 @@ public sealed class SimulatorSettings public double FpsLimit = 30; public double ShadowAngleLimit = 0.2; public bool FullscreenWindowed; + /// fullscreenmonitor: the monitor a full screen opens on, as "name:x,y"; empty for the primary one. + public string FullscreenMonitor = ""; public int SplineFidelity = 1; public bool FullPhysics = true; @@ -180,6 +146,18 @@ public sealed class SimulatorSettings public bool LargeThumbnails; public bool AutoExpandSceneryTree; + /// + /// 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. + /// + public bool AdvancedSettings; + + /// + /// 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. + /// + public bool MovedToStandard; + /// Warn at start when the processor cannot run the official simulator builds. public bool CpuNotice = true; @@ -212,25 +190,26 @@ public sealed class SimulatorSettings } /// - /// 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 starter offers. "default" is the full renderer, the one to use + /// wherever it runs; the other two draw with the legacy one. The experimental renderer is + /// not offered: the simulator a player has is built without it. /// - public static readonly string[] RenderEngines = { "full", "legacy", "simple", "experimental", "vulkan" }; + public static readonly string[] RenderEngines = { "default", "legacy", "simple" }; - /// Where "vulkan" stands among . - public const int VulkanEngine = 4; + /// + /// The words of the file that stay as they are while the choice stands: those application.cpp + /// on master knows, but "experimental". Any other word starts the full renderer with a line in + /// the log, so a save puts "default" in its place. + /// + public static bool KeptRendererWord(string? word) => + word?.Trim().ToLowerInvariant() is "default" or "legacy" or "simple" or "simpleshader" or "off"; /// Where stands among , as the simulator reads it. public static int RenderEngineOf(string word) => word.Trim().ToLowerInvariant() switch { - "full" or "default" or "opengl" or "gl46" => 0, + "legacy" or "simpleshader" or "off" => 1, "simple" => 2, - "experimental" => 3, - "vulkan" or "vulkan14" => 4, - _ => 1 + _ => 0 }; /// @@ -256,7 +235,12 @@ public sealed class SimulatorSettings /// internal double MouseScaleXMagnitude { get; set; } = 2; - internal double MouseScaleYMagnitude { get; set; } = 0.2; + /// + /// The second mousescale number, as the old starter always wrote it: 0.5, or + /// -0.5 with . Whatever else the file has there + /// goes on the next save. + /// + internal const double MouseScaleY = 0.5; /// The numbers of shadowtune the simulator skips, kept as the file has them. internal string[] ShadowTuneUnused { get; set; } = { "250", "300" }; diff --git a/StarterNG/Domain/Settings/SliderRanges.cs b/StarterNG/Domain/Settings/SliderRanges.cs new file mode 100644 index 0000000..a908e1f --- /dev/null +++ b/StarterNG/Domain/Settings/SliderRanges.cs @@ -0,0 +1,34 @@ +namespace StarterNG.Domain.Settings; + +/// +/// What the sliders offer, in either mode: the old starter's ranges (MaSzyna-EU07/Starter, +/// src/uMain.dfm), the tops of which holds to. A value the file +/// has below these is shown as it is, so opening and saving the settings never moves it. +/// +public static class SliderRanges +{ + /// maxtexturesize: its list began at 512. + public const int MinTextureSize = 512; + + /// The map size of shadowtune: its list began at 1024. + public const int MinShadowMap = 1024; + + /// dynamiclights: 1 to 7. + public const int MinDynamicLights = 1; + + /// The cursor's speed: its fastest was a mousescale of 3.2. + public const int MaxCursorSensitivity = 3; + + /// gfx.reflections.framerate, in updates a second. + public static readonly double[] ReflectionUpdates = { 1, 3, 10, 25, 60 }; + + /// gfx.drawrange.factor.max: normal, high and very high. + public static readonly double[] DrawRangeFactors = { 1, 2, 3 }; + + /// gfx.shadows.cab.range, in metres: off, then 10 to 100. + public static readonly double[] CabShadowRanges = { 0, 10, 20, 30, 50, 100 }; + + /// fpslimit: none, or up to 240, where the fastest usual monitors run. + public static readonly double[] FrameRateLimits = + { 0, 20, 25, 30, 40, 45, 50, 60, 72, 75, 90, 100, 120, 144, 165, 180, 200, 240 }; +} diff --git a/StarterNG/Domain/TexRandomizer.cs b/StarterNG/Domain/TexRandomizer.cs index c408474..b488b9c 100644 --- a/StarterNG/Domain/TexRandomizer.cs +++ b/StarterNG/Domain/TexRandomizer.cs @@ -199,23 +199,8 @@ public sealed class TexRandomizer VehicleTexture? current) { var result = new List(); - 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>? _byMini; + + /// The textures that can be drawn under any of , each once, in the catalogue's order. + private IEnumerable ByMini(IReadOnlyList 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> IndexByMini() + { + var index = new Dictionary>(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; diff --git a/StarterNG/Domain/TrainsetDisplay.cs b/StarterNG/Domain/TrainsetDisplay.cs index 3399d2e..fe68f0e 100644 --- a/StarterNG/Domain/TrainsetDisplay.cs +++ b/StarterNG/Domain/TrainsetDisplay.cs @@ -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,27 @@ public static class TrainsetDisplay !string.IsNullOrEmpty(trainset.Description) && trainset.Description.TrimStart().StartsWith("-", StringComparison.Ordinal); - /// Whether a list of the scenery's consists shows it, under the two filters those lists have. + /// Whether a list of the scenery's consists shows it, under the filters those lists have. public static bool ListedIn(Trainset trainset, bool showAi, bool drivableOnly, Trainset? current) => (showAi || !IsAi(trainset)) && (!drivableOnly || ListedAsDrivable(trainset, current)); + /// + /// 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. + /// + public static bool ListedIn(Trainset trainset, SimulatorSettings settings, Trainset? current) => + settings.AdvancedSettings + ? ListedIn(trainset, settings.ShowAiVehicles, settings.DrivableOnly, current) + : !IsEmpty(trainset) || SceneryTrainsetText.IsModified(trainset); + + /// + /// 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. + /// + public static bool StartableIn(Trainset trainset, SimulatorSettings settings) => + settings.AdvancedSettings || (!IsAi(trainset) && !trainset.Decor); + /// The consist's row in those lists: what it is made of, or the track of one with nothing on it. public static string ListLabel(Trainset trainset) => CompositionText(trainset) ?? string.Format(App.Loc["EmptyTrainset"], trainset.Track ?? ""); diff --git a/StarterNG/Infrastructure/Displays.cs b/StarterNG/Infrastructure/Displays.cs deleted file mode 100644 index 9e6bfc9..0000000 --- a/StarterNG/Infrastructure/Displays.cs +++ /dev/null @@ -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; - -/// A screen, and the fastest it refreshes. -/// The connector on Linux (eDP-1, HDMI-A-1); empty for the primary screen on Windows. -public sealed record Display(string Name, int RefreshRate); - -/// -/// 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. -/// -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; - } - - /// Every screen whose refresh rate could be read; empty where none could. - public IReadOnlyList List() - { - try - { - if (_environment.IsLinux) - return FromDrm(); - if (_environment.IsWindows && OperatingSystem.IsWindows()) - return PrimaryOnWindows() is { } rate ? new[] { new Display(string.Empty, rate) } : Array.Empty(); - } - catch (Exception) - { - // A screen we cannot read leaves the limit to the player, as before. - } - - return Array.Empty(); - } - - private IReadOnlyList FromDrm() - { - var displays = new List(); - 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); - } - } -} - -/// The timings an EDID lists, as far as a refresh rate goes. -public static class Edid -{ - /// The fastest refresh rate among the detailed timings, rounded; 0 for none. - 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; -} diff --git a/StarterNG/Infrastructure/Monitors.cs b/StarterNG/Infrastructure/Monitors.cs new file mode 100644 index 0000000..e0fe588 --- /dev/null +++ b/StarterNG/Infrastructure/Monitors.cs @@ -0,0 +1,195 @@ +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; + +/// A monitor as the simulator names it for fullscreenmonitor. +/// "name:x,y" - GLFW's name with spaces as underscores, and the monitor's place on the desktop (application.cpp). +/// The current mode's rate in Hz, which a full screen of the simulator keeps; 0 where unknown. +public sealed record DisplayMonitor(string Id, string Name, int Width, int Height, bool Primary, int RefreshRate = 0); + +/// +/// 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. +/// +public static class Monitors +{ + public static IReadOnlyList 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(); + } + + /// The id GLFW gives a monitor: its name with spaces as underscores, then where it starts. + 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 OnWindows() + { + var monitors = new List(); + 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 ── + + private static readonly Regex Output = new( + @"^(\S+) connected (primary )?(\d+)x(\d+)\+(\d+)\+(\d+)", RegexOptions.CultureInvariant); + + // 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); + + private static IReadOnlyList FromXrandr() + { + using var process = Process.Start(new ProcessStartInfo("xrandr", "--query") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }); + if (process is null) + return Array.Empty(); + string text = process.StandardOutput.ReadToEnd(); + process.WaitForExit(2000); + return Parse(text); + } + + /// The monitors of xrandr's report, each with the rate its mode in use runs at. + public static IReadOnlyList Parse(string xrandr) + { + var monitors = new List(); + 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; + } +} diff --git a/StarterNG/Infrastructure/Settings/ExecutableLocator.cs b/StarterNG/Infrastructure/Settings/ExecutableLocator.cs index b42e4d6..332fd5a 100644 --- a/StarterNG/Infrastructure/Settings/ExecutableLocator.cs +++ b/StarterNG/Infrastructure/Settings/ExecutableLocator.cs @@ -302,33 +302,6 @@ public sealed class ExecutableLocator return extension.Length == 0 || extension is ".exe" or ".x86_64" or ".run" or ".appimage"; } - /// Whether the DLSS and frame generation libraries lie next to the simulator: without them it cannot use either. - 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; - /// A path as gives it, which may be relative to the installation, made whole. public string FullPath(string path) => Path.IsPathRooted(path) ? path : Path.Combine(_paths.Root, path); diff --git a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs index 50a9a48..f0ceebb 100644 --- a/StarterNG/Infrastructure/Settings/SettingsSerializer.cs +++ b/StarterNG/Infrastructure/Settings/SettingsSerializer.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; @@ -24,16 +25,6 @@ public sealed class SettingsSerializer s.PhysicsLog = false; } - private readonly bool _dlssPlatform; - - /// Whether the simulator can have DLSS here at all (not on macOS). - 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 +36,21 @@ public sealed class SettingsSerializer s.FpsAverage = c.GetDouble("fpsaverage", 0); s.PauseOnStart = c.GetBool("pause", false); + // A zero (or NaN/Infinity) scale locks that axis in the simulator: the + // camera then turns only one way. Nothing in the starter writes such a + // number on purpose, so X takes the default. Of Y only the sign is read: + // it is written 0.5 or -0.5, as the old starter always wrote it. 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); - } + 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 +83,7 @@ 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", ""); + s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default")); s.Width = c.GetInt("width", 1280); s.Height = c.GetInt("height", 720); s.BufferScalePercent = ReadBufferScale(c); @@ -100,9 +91,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); @@ -114,34 +102,6 @@ public sealed class SettingsSerializer 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); // 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; @@ -165,6 +125,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.FullscreenMonitor = c.GetString("fullscreenmonitor", "").Trim(); s.RenderAngleVulkan = string.Equals(c.GetString("gfx.angleplatform", ""), "vulkan", StringComparison.OrdinalIgnoreCase); s.SplineFidelity = Clamp(c.GetInt("splinefidelity", 1), 1, 4); @@ -213,6 +174,8 @@ 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.CpuNotice = c.GetBool("starter.cpunotice", true); s.Gpu = string.Equals(c.GetString("starter.gpu", "discrete"), "system", StringComparison.OrdinalIgnoreCase) ? GpuPreference.System @@ -237,7 +200,7 @@ public sealed class SettingsSerializer if (c.Has(key.Key)) s.Extra[key.Key] = c.GetRaw(key.Key) ?? string.Empty; - GraphicsRules.Normalize(s, _dlssPlatform); + GraphicsRules.Normalize(s); } /// @@ -248,13 +211,20 @@ public sealed class SettingsSerializer public static readonly string[] FixedLengthKeys = { "uart", "uarttune", "uartfeature" }; /// Keys written only when they say something, besides those of . - public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "gfx.vulkan.device" }; + public static readonly string[] OptionalKeys = { "fpslimit", "gfx.angleplatform", "fullscreenmonitor" }; /// Keys no simulator reads any more, taken out of the file on a save. public static readonly string[] ObsoleteKeys = { "gfx.postfx.tonemapping", "starter.developertools", + // The OpenGL 4.6 and Vulkan renderers', which the simulator's master does not have. + "gfx.antialiasing", "gfx.buffer.percent", "gfx.vulkan.device", "gfx.dlss.preset", "gfx.framegeneration", + "gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.ssr", "gfx.lights.clustered", "gfx.lights.shadows", + "gfx.contactshadows", "gfx.shadow.sdsm", "gfx.postfx.ao", "gfx.postfx.ao.lighting", "gfx.postfx.ao.quality", + "gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.bounce", "gfx.cabprobe.reflections", "gfx.fog", + "gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows", "gfx.postfx.bloom", "gfx.postfx.autoexposure", + "gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density", "gfx.precipitation.particles", }; /// @@ -264,7 +234,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" @@ -277,7 +247,7 @@ public sealed class SettingsSerializer ? s.MouseScaleXMagnitude : s.CursorSensitivity; double mx = magnitude * (s.InvertMouseHorizontal ? -1 : 1); - double my = s.MouseScaleYMagnitude * (s.InvertMouseVertical ? -1 : 1); + double my = SimulatorSettings.MouseScaleY * (s.InvertMouseVertical ? -1 : 1); c.Set("mousescale", $"{mx.ToString("R", CultureInfo.InvariantCulture)} " + $"{my.ToString("R", CultureInfo.InvariantCulture)}"); @@ -312,26 +282,16 @@ public sealed class SettingsSerializer 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.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 into a buffer of this size and stretches it to the window. + c.SetInt("gfx.framebuffer.width", (int)Math.Round(s.Width * s.BufferScalePercent / 100.0)); + c.SetInt("gfx.framebuffer.height", (int)Math.Round(s.Height * 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. 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.SetInt("dynamiclights", s.DynamicLights); c.SetDouble("gfx.drawrange.factor.max", s.DrawRangeFactor); c.SetBool("vsync", s.VSync); @@ -344,32 +304,6 @@ public sealed class SettingsSerializer 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]} " + @@ -383,6 +317,7 @@ 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 (!string.IsNullOrWhiteSpace(s.FullscreenMonitor)) c.Set("fullscreenmonitor", s.FullscreenMonitor.Trim()); if (s.RenderAngleVulkan) c.Set("gfx.angleplatform", "vulkan"); c.SetInt("splinefidelity", s.SplineFidelity); @@ -429,6 +364,8 @@ 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.SetBool("starter.cpunotice", s.CpuNotice); c.Set("starter.gpu", s.Gpu == GpuPreference.System ? "system" : "discrete"); c.SetInt("starter.batterydefault", (int)s.ReadyOverride); @@ -447,60 +384,42 @@ 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) - { - if (!c.Has("gfx.buffer.percent")) - return Clamp(c.GetInt("starter.bufferscale", 100), 25, 200); + private static int ReadBufferScale(ConfigFile c) => + Clamp(BufferScaleIn(c), 25, GraphicsRules.MaxBufferScale); - double value = c.GetDouble("gfx.buffer.percent", 100); - return Clamp((int)Math.Round(value > 4 ? value : value * 100), 25, 200); + // The starter's own percent, or the framebuffer the file sets against its window. + private static int BufferScaleIn(ConfigFile c) + { + 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; } - private static string FirstToken(ConfigFile c, string key) + /// + /// The keys of set above what the starter lets them go to + /// (): the next save brings them down. + /// + public static IReadOnlySet OverCapKeys(ConfigFile c) { - var tokens = c.GetTokens(key); - return tokens.Length > 0 ? tokens[0].ToLowerInvariant() : string.Empty; + var keys = new HashSet(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.UnionWith(new[] { "starter.bufferscale", "gfx.framebuffer.width", "gfx.framebuffer.height" }); + return keys; } - // 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. - private static AntiAliasingMode ReadAntiAliasing(ConfigFile c) + private static AntiAliasingMode ReadAntiAliasing(ConfigFile c) => c.GetInt("multisampling", 2) switch { - var fromMultisampling = 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 - }; - } - - private static string AntiAliasingToken(AntiAliasingMode mode) => mode switch - { - AntiAliasingMode.Msaa2 => "msaax2", - AntiAliasingMode.Msaa4 => "msaax4", - AntiAliasingMode.Msaa8 => "msaax8", - AntiAliasingMode.Taa => "taa", - AntiAliasingMode.Dlss => "dlss", - AntiAliasingMode.Dlaa => "dlaa", - _ => "off" + <= 0 => AntiAliasingMode.Off, + 1 => AntiAliasingMode.Msaa2, + 2 => AntiAliasingMode.Msaa4, + _ => AntiAliasingMode.Msaa8 }; private static int MultisamplingLevel(AntiAliasingMode mode) => mode switch @@ -511,79 +430,28 @@ public sealed class SettingsSerializer _ => 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 Clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v); - private static int ParseReflex(string value) => value switch + /// + /// Whether the file's own mousescale can stay as it is: a first number neither + /// zero nor NaN/Infinity, and 0.5 or -0.5 after it. Otherwise a save writes the + /// one the starter holds. + /// + public static bool MouseScaleStands(string? raw) { - "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); + string[] tokens = (raw ?? "").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + return tokens.Length >= 2 && + TryParseMouseScale(tokens[0], out _) && + TryParseMouseScale(tokens[1], out double y) && + Math.Abs(y) == SimulatorSettings.MouseScaleY; } - 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 bool TryParseMouseScale(string token, out double scale) => + double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale) && + double.IsFinite(scale) && scale != 0; private static int SensitivityStep(double mouseScale) => (int)Math.Clamp(Math.Round(Math.Abs(mouseScale)), 1, 5); - private static double ParseDouble(string s, double fallback) => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : fallback; diff --git a/StarterNG/MainWindow.axaml.cs b/StarterNG/MainWindow.axaml.cs index 1163025..13713da 100644 --- a/StarterNG/MainWindow.axaml.cs +++ b/StarterNG/MainWindow.axaml.cs @@ -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; @@ -103,6 +104,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 += (_, _) => { @@ -507,6 +511,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 +646,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 diff --git a/StarterNG/Styles/Settings.axaml b/StarterNG/Styles/Settings.axaml index 6e238bc..2986eb9 100644 --- a/StarterNG/Styles/Settings.axaml +++ b/StarterNG/Styles/Settings.axaml @@ -81,15 +81,13 @@ TextWrapping="Wrap" Margin="0,3,0,0" /> - - + @@ -103,6 +101,13 @@ + + + @@ -113,24 +118,6 @@ - - - - - - diff --git a/StarterNG/Views/Depot.axaml b/StarterNG/Views/Depot.axaml index 1f874e1..879cd63 100644 --- a/StarterNG/Views/Depot.axaml +++ b/StarterNG/Views/Depot.axaml @@ -137,7 +137,8 @@ HorizontalContentAlignment="Center" Click="AddToWarehouseButton_OnClick" Content="{Binding [AddToWarehouse], Source={x:Static starterNg:App.Loc}}" /> - + + { + PopulateSceneryConsists(); + RebuildConsist(); + }; + _warehouse = new Warehouse(warehouseList, removeFromWarehouseButton, _hand, () => AppServices.Current.State.CurrentTrainset, ApplyFromWarehouse); _warehouse.SelectionChanged += () => @@ -598,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"]; @@ -606,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 @@ -755,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(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 AskTextureRandomizerOpts() => @@ -777,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); diff --git a/StarterNG/Views/Depot/VehicleBrowser.cs b/StarterNG/Views/Depot/VehicleBrowser.cs index 1904768..f91f7c2 100644 --- a/StarterNG/Views/Depot/VehicleBrowser.cs +++ b/StarterNG/Views/Depot/VehicleBrowser.cs @@ -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? 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; } diff --git a/StarterNG/Views/Depot/VehicleCards.cs b/StarterNG/Views/Depot/VehicleCards.cs index b399539..a567d2a 100644 --- a/StarterNG/Views/Depot/VehicleCards.cs +++ b/StarterNG/Views/Depot/VehicleCards.cs @@ -1,4 +1,5 @@ using System; +using StarterNG.Application; using System.Collections.Generic; using System.Linq; using Avalonia; @@ -116,7 +117,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 - the player, the simulator, a passenger or nobody - is for the advanced mode. + if (AppServices.Current.Settings.AdvancedSettings) + controls.Children.Add(DriverButton(item)); controls.Children.Add(FlipButton(item)); if (item.Grouped && item.Cars.Count > 1) @@ -692,10 +695,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 (AppServices.Current.Settings.AdvancedSettings) + { + 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"] + "…", diff --git a/StarterNG/Views/Depot/VehicleDetails.cs b/StarterNG/Views/Depot/VehicleDetails.cs index 1cd74e3..f006c5e 100644 --- a/StarterNG/Views/Depot/VehicleDetails.cs +++ b/StarterNG/Views/Depot/VehicleDetails.cs @@ -280,6 +280,8 @@ public sealed class VehicleDetails }; driver.MinWidth = 0; driver.HorizontalAlignment = HorizontalAlignment.Stretch; + // Shown but not changed in the standard mode: who drives is for the advanced one. + driver.IsEnabled = AppServices.Current.Settings.AdvancedSettings; var rows = new StackPanel(); rows.Children.Add(Row(App.Loc["CrewLabel"], driver)); diff --git a/StarterNG/Views/MessageBox.cs b/StarterNG/Views/MessageBox.cs index 71346d3..19692ba 100644 --- a/StarterNG/Views/MessageBox.cs +++ b/StarterNG/Views/MessageBox.cs @@ -50,6 +50,69 @@ public static class MessageBox return yes; } + /// + /// 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. + /// + public static async Task 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; + } + + /// Whether the whole window, frame and all, lies within the working area of one screen. + 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; + } + /// /// 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. diff --git a/StarterNG/Views/Scenarios.axaml.cs b/StarterNG/Views/Scenarios.axaml.cs index 77967e9..26aa6a4 100644 --- a/StarterNG/Views/Scenarios.axaml.cs +++ b/StarterNG/Views/Scenarios.axaml.cs @@ -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); + } + + /// + /// 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. + /// + 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 /// The scenery's name, marked when its files hold mistakes. 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 @@ -263,8 +301,7 @@ public partial class Scenarios : UserControl { 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; @@ -272,7 +309,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 { @@ -435,8 +472,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; @@ -1009,6 +1047,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) { @@ -1030,9 +1073,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) diff --git a/StarterNG/Views/SettingTexts.cs b/StarterNG/Views/SettingTexts.cs index 4ed764e..3a730fe 100644 --- a/StarterNG/Views/SettingTexts.cs +++ b/StarterNG/Views/SettingTexts.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Globalization; using StarterNG.Domain.Settings; @@ -29,49 +28,11 @@ internal static class SettingTexts 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"] - }; - /// A rate below one a second reads better as the time between updates. public static string ReflectionsInterval(double perSecond) { @@ -82,72 +43,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)); } - - /// What a level sets, in the words and the units of the rows it sets. - public static string PresetSummary(GraphicsPreset p) - { - var lines = new List(); - 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); - } } diff --git a/StarterNG/Views/Settings.Graphics.cs b/StarterNG/Views/Settings.Graphics.cs index a9114ee..c83ef17 100644 --- a/StarterNG/Views/Settings.Graphics.cs +++ b/StarterNG/Views/Settings.Graphics.cs @@ -2,18 +2,17 @@ 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; 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 +23,113 @@ public partial class Settings new("*") { Patterns = new[] { "*" } } }; - /// Set while the dependencies are brought in line, so the changes they make do not recurse. - private bool _updatingGraphics; - - /// - /// 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. - /// - 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; 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); + 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() + // ── 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"; + + /// fullscreen as the file has it, kept where borderless makes it of no account. + private bool _fullscreenAsRead; + + /// + /// The mode the two keys make (application.cpp): fullscreenwindowed takes the monitor's + /// own size and turns full screen on whatever fullscreen says. + /// + private static string DisplayModeOf(bool fullscreen, bool windowed) => + windowed ? BorderlessMode : fullscreen ? FullscreenMode : WindowMode; + + /// A borderless screen takes the monitor's size; a window can't be put on a monitor. + private void UpdateDisplayRows() { - if (_loading || _updatingGraphics) - return; + string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode; + Dim(ResolutionRow, mode == BorderlessMode); + Dim(MonitorRow, mode == WindowMode); + } - _updatingGraphics = true; - try - { - if (!SettingReach.IsVulkan(SelectedRenderer())) - { - 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; - } - 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; - } + /// The whole row greyed out, its label and description too, as a disabled check box is. + private static void Dim(Control row, bool off) + { + row.IsEnabled = !off; + row.Opacity = off ? 0.45 : 1; + } - UpdateGraphicsState(); + private ComboBoxItem? _primaryMonitorItem; + + private IReadOnlyList? _monitors; + + /// The monitors attached, read once. + private IReadOnlyList MonitorList => _monitors ??= Monitors.List(AppServices.Current.Environment); + + /// + /// 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. + /// + 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; } /// - /// 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. /// - 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()) - 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 ""; - } - - /// Looked up once per simulator picked: the search for it reads the installation's directory. - 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 +151,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(); @@ -337,7 +184,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) @@ -375,9 +221,6 @@ public partial class Settings AntiAliasingMode.Msaa2 => "msaax2", AntiAliasingMode.Msaa4 => "msaax4", AntiAliasingMode.Msaa8 => "msaax8", - AntiAliasingMode.Taa => "taa", - AntiAliasingMode.Dlss => "dlss", - AntiAliasingMode.Dlaa => "dlaa", _ => "off" }; @@ -386,9 +229,6 @@ public partial class Settings "msaax2" => AntiAliasingMode.Msaa2, "msaax4" => AntiAliasingMode.Msaa4, "msaax8" => AntiAliasingMode.Msaa8, - "taa" => AntiAliasingMode.Taa, - "dlss" => AntiAliasingMode.Dlss, - "dlaa" => AntiAliasingMode.Dlaa, _ => AntiAliasingMode.Off }; } diff --git a/StarterNG/Views/Settings.axaml b/StarterNG/Views/Settings.axaml index 1e4886b..cc22a16 100644 --- a/StarterNG/Views/Settings.axaml +++ b/StarterNG/Views/Settings.axaml @@ -25,6 +25,8 @@ public event Action? ThumbnailSizeChanged; + /// The standard or the advanced mode was chosen; the scenario screen follows it. + public static event Action? AdvancedModeChanged; + /// Thumbnail size the other tabs were last drawn at. private bool _drawnThumbs = AppServices.Current.Settings.LargeThumbnails; @@ -57,14 +61,14 @@ public partial class Settings : UserControl, ISettingsCapture { InitializeComponent(); - _fpsLimit = new SliderSteps(FpsLimitSlider, Steps.FrameRateLimits); - _reflections = new SliderSteps(reflectionsFramerate, Steps.ReflectionUpdates); + _fpsLimit = new SliderSteps(FpsLimitSlider, SliderRanges.FrameRateLimits); + _reflections = new SliderSteps(reflectionsFramerate, SliderRanges.ReflectionUpdates); _anisotropy = new SliderSteps(TexFilteringSlider, Steps.Anisotropy); - _drawRangeFactor = new SliderSteps(RenderRangeSlider, Steps.DrawRangeFactors); + _drawRangeFactor = new SliderSteps(RenderRangeSlider, SliderRanges.DrawRangeFactors); + _cabShadows = new SliderSteps(cabShaderSourceRange, SliderRanges.CabShadowRanges); _built = true; SettingsPathText.Text = AppServices.Current.SettingsStore.LoadedFrom; - ToolTip.SetTip(SettingsPathText, AppServices.Current.SettingsStore.LoadedFrom); this.AttachedToVisualTree += (_, _) => { @@ -104,7 +108,28 @@ public partial class Settings : UserControl, ISettingsCapture App.Loc.LanguageChanged += _keyRows.UpdateTexts; FeedbackCb.SelectionChanged += FeedbackCb_OnSelectionChanged; - SelectExeCb.SelectionChanged += (_, _) => UpdateIdleNotes(); + // What decides whether the simulator starts and draws at all is changed only on purpose. + AskBeforeChange(RenderAngleVulkanCb); + AskBeforeChange(AdditionalShadersCb); + AskBeforeChange(SkipPipelineCb); + AskBeforeChange(RenderVBOCb); + // Ignoring the gamepad is the recommended default; reading it has been trouble, so turning it on is asked. + GamepadIgnoreCb.IsCheckedChanged += async (_, _) => + { + if (!AsksFirst || IsChecked(GamepadIgnoreCb) || TopLevel.GetTopLevel(this) is not Window owner) + return; + if (!await MessageBox.Show(owner, App.Loc["ConfirmGamepadUse"], App.Loc["GamepadSignalIgnore"], + MessageBoxButtons.YesNo)) + Revert(() => GamepadIgnoreCb.IsChecked = true); + }; + RenderEngineCb.SelectionChanged += async (_, e) => + { + if (!AsksFirst || e.RemovedItems.Count == 0) + return; + object? previous = e.RemovedItems[0]; + if (!await ConfirmRenderingChange(App.Loc["RenderEngine"])) + Revert(() => RenderEngineCb.SelectedItem = previous); + }; // Coming to the page or to the list is when a new build is looked for. SelectExeCb.GotFocus += (_, _) => RefreshExecutables(); PropertyChanged += (_, e) => @@ -112,16 +137,9 @@ public partial class Settings : UserControl, ISettingsCapture if (e.Property == IsVisibleProperty && IsVisible) RefreshExecutables(); }; - FullscreenWindowedCb.IsCheckedChanged += (_, _) => UpdateIdleNotes(); - App.Loc.LanguageChanged += UpdateIdleNotes; App.Loc.LanguageChanged += UpdateGpuNote; - // targetfps decides whether the draw range factor does anything. - _keyRows.Moved += key => - { - if (string.Equals(key.Key, "targetfps", StringComparison.OrdinalIgnoreCase)) - UpdateIdleNotes(); - }; - InitGraphics(); + App.Loc.LanguageChanged += UpdateAdvancedModeButton; + App.Loc.LanguageChanged += UpdateUnknownValues; MotionBlurCb.IsCheckedChanged += (_, _) => UpdateDependentRows(); ReflectionsCubeMapCb.IsCheckedChanged += (_, _) => UpdateDependentRows(); @@ -398,9 +416,9 @@ public partial class Settings : UserControl, ISettingsCapture // A reloaded file may name another simulator, or start a server. RefreshDerivedRows(); + UpdateUnknownValues(); UpdateGpuNote(); NoteShownValues(); - UpdateGraphicsState(); UpdatePresetMarks(); } @@ -410,7 +428,8 @@ public partial class Settings : UserControl, ISettingsCapture /// private void ShowValues(SimulatorSettings s) { - FullscreenCb.IsChecked = s.Fullscreen; + // First, or a value outside the standard ranges would be moved into them on the way in. + ApplyRanges(s); PauseInactiveCb.IsChecked = s.PauseWhenInactive; PauseStartCb.IsChecked = s.PauseOnStart; CursorSensitivitySlider.Value = s.CursorSensitivity; @@ -456,7 +475,7 @@ public partial class Settings : UserControl, ISettingsCapture _reflections.Value = s.ReflectionsFramerate; shaderResolutionSlider.Value = Log2(s.ShadowMapResolution, 12); shaderRange.Value = s.ShadowProjectionRange; - cabShaderSourceRange.Value = s.CabShadowsRange; + _cabShadows.Value = s.CabShadowsRange; ShadowDisplayCb.SelectedIndex = Math.Clamp(s.ShadowRankCutoff - 1, 0, 2); ReflectionsDetailsCb.SelectedIndex = s.ReflectionsFidelity; fovSlider.Value = s.FieldOfView; @@ -464,7 +483,6 @@ public partial class Settings : UserControl, ISettingsCapture RenderScreensThreadCb.IsChecked = s.PythonThreadedUpload; _fpsLimit.Value = s.FpsLimitEnabled ? s.FpsLimit : 0; ShadowAngleLimitSlider.Value = s.ShadowAngleLimit; - FullscreenWindowedCb.IsChecked = s.FullscreenWindowed; RenderAngleVulkanCb.IsChecked = s.RenderAngleVulkan; TrackCurvesSlider.Value = s.SplineFidelity; @@ -495,6 +513,7 @@ public partial class Settings : UserControl, ISettingsCapture AutoCloseStarterCb.IsChecked = s.AutoCloseStarter; LargeThumbnailsCb.IsChecked = s.LargeThumbnails; AutoExpandTreeCb.IsChecked = s.AutoExpandSceneryTree; + UpdateAdvancedModeButton(); ReadyOverrideCb.SelectedIndex = (int)s.ReadyOverride; CompressTexCb.IsChecked = s.CompressTextures; @@ -516,7 +535,15 @@ public partial class Settings : UserControl, ISettingsCapture /// private void ShowAsEdits(SimulatorSettings s) { - ShowValues(s); + _showingEdits = true; + try + { + ShowValues(s); + } + finally + { + _showingEdits = false; + } RefreshDerivedRows(); } @@ -524,9 +551,7 @@ public partial class Settings : UserControl, ISettingsCapture private void RefreshDerivedRows() { UpdateQualityCaptions(); - UpdateIdleNotes(); UpdateDependentRows(); - UpdateGraphicsState(); } // ── Levels of detail ───────────────────────────────────────────────────── @@ -549,8 +574,7 @@ public partial class Settings : UserControl, ISettingsCapture foreach (var (section, group) in new[] { (DrawRangeSection, GraphicsGroup.DrawRange), (TexturesSection, GraphicsGroup.Textures), - (ShadowsSection, GraphicsGroup.Shadows), (LightsSection, GraphicsGroup.Lights), - (ReflectionsSection, GraphicsGroup.Reflections), (NatureSection, GraphicsGroup.Nature) + (ShadowsSection, GraphicsGroup.Shadows), (ReflectionsSection, GraphicsGroup.Reflections) }) { var levels = new ComboBox(); @@ -573,7 +597,6 @@ public partial class Settings : UserControl, ISettingsCapture foreach (var (preset, button) in _presetButtons) { button.Content = App.Loc[preset.NameKey]; - ToolTip.SetTip(button, SettingTexts.PresetSummary(preset)); } _markingLevels = true; @@ -583,7 +606,6 @@ public partial class Settings : UserControl, ISettingsCapture foreach (var level in GraphicsPreset.All) levels.Items.Add(new ComboBoxItem { Content = App.Loc[level.NameKey], Tag = level }); levels.PlaceholderText = App.Loc["PresetCustom"]; - ToolTip.SetTip(levels, App.Loc["GfxGroupLevelTip"]); } _markingLevels = false; @@ -607,8 +629,6 @@ public partial class Settings : UserControl, ISettingsCapture var trial = Trial(); var applied = _presetMemory.Apply(preset, trial); ShowAsEdits(trial); - foreach (string key in applied.RowKeys) - _keyRows.Show(key, trial.Extra[key]); // Chosen as a whole, its values are choices, not ones the screen could not show. ForgetShown(applied.ChosenKeys); @@ -682,8 +702,7 @@ public partial class Settings : UserControl, ISettingsCapture if (_cards.Count == 0) return; - CardText.Text = CardLine(_cards[0]); - ToolTip.SetTip(CardText, string.Join(Environment.NewLine, _cards.Select(CardLine))); + CardText.Text = string.Join(Environment.NewLine, _cards.Select(CardLine)); } // ── The screens' refresh rates, for the frame rate limit ───────────────── @@ -692,38 +711,51 @@ public partial class Settings : UserControl, ISettingsCapture private void BuildMonitorRates() { - var displays = AppServices.Current.Displays.List(); - if (displays.Count == 0) - return; - - MonitorRates.IsVisible = true; - UpdateMonitorRates(displays); - App.Loc.LanguageChanged += () => UpdateMonitorRates(displays); + VSyncCb.IsCheckedChanged += (_, _) => UpdateMonitorRates(); + DisplayModeCb.SelectionChanged += (_, _) => + { + UpdateDisplayRows(); + UpdateMonitorRates(); + }; + MonitorCb.SelectionChanged += (_, _) => UpdateMonitorRates(); + App.Loc.LanguageChanged += UpdateMonitorRates; + UpdateMonitorRates(); } - private void UpdateMonitorRates(IReadOnlyList displays) + /// + /// The rate of the monitor the simulator will show on, with a button to match the limit + /// to it. VSync already holds the frames to that rate, so with it on there is no button: + /// fpslimit paces frames by its own clock (framepacer.h), not the refresh, so no limit + /// of it lines up with the monitor. + /// + private void UpdateMonitorRates() { + bool vsync = IsChecked(VSyncCb); + FpsVSyncNote.IsVisible = vsync; MonitorRates.Children.Clear(); - foreach (var display in displays) + + int hz = SimulatorMonitor()?.RefreshRate ?? 0; + MonitorRates.IsVisible = hz > 0; + if (hz == 0) + return; + + MonitorRates.Children.Add(new TextBlock { - string screen = string.IsNullOrEmpty(display.Name) - ? string.Format(App.Loc["MonitorRate"], display.RefreshRate) - : string.Format(App.Loc["MonitorRateNamed"], display.Name, display.RefreshRate); - MonitorRates.Children.Add(new TextBlock - { - Text = screen, FontSize = 11, Foreground = FgDimBrush, VerticalAlignment = VerticalAlignment.Center - }); - var match = new Button - { - Content = string.Format(App.Loc["MonitorRateUse"], display.RefreshRate), - Margin = new Thickness(4, 0, 14, 0) - }; - match.Classes.Add("Outline"); - match.Classes.Add("SectionReset"); - int rate = display.RefreshRate; - match.Click += (_, _) => _fpsLimit.Value = rate; - MonitorRates.Children.Add(match); - } + Text = string.Format(App.Loc["MonitorRate"], hz), + FontSize = 11, Foreground = FgDimBrush, VerticalAlignment = VerticalAlignment.Center + }); + if (vsync) + return; + + var match = new Button + { + Content = string.Format(App.Loc["MonitorRateUse"], hz), + Margin = new Thickness(4, 0, 14, 0) + }; + match.Classes.Add("Outline"); + match.Classes.Add("SectionReset"); + match.Click += (_, _) => _fpsLimit.Value = hz; + MonitorRates.Children.Add(match); } // ── Sections back to the simulator's own values ────────────────────────── @@ -774,13 +806,7 @@ public partial class Settings : UserControl, ISettingsCapture /// Puts the section's rows at the simulator's own values, as edits waiting for Save. private void ResetSection(SettingsSection section) { - var keys = ResettableKeys(section); - ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys)); - foreach (string key in keys) - _keyRows.ShowDefault(key); - - // Put back by hand, a value is a choice like any other. - ForgetShown(keys); + ShowDefaults(ResettableKeys(section)); Announcer.Say(this, ScreenReaderNames.PickerText(ScreenReaderNames.TextOf(section.Header), App.Loc["DefaultsRestored"])); } @@ -831,7 +857,7 @@ public partial class Settings : UserControl, ISettingsCapture private string SelectedRenderer() => SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full"; - private RendererKind SelectedRendererKind() => SettingReach.KindOf(SelectedRenderer()); + private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer()); /// /// Writes the pending edits on this screen into the settings, so a save from @@ -849,7 +875,6 @@ public partial class Settings : UserControl, ISettingsCapture var language = ChangeLanguageCb.SelectedItem as ComboBoxItem; s.Language = language?.Content?.ToString() ?? App.Loc.CurrentLanguage; s.LanguageCode = language?.Tag as string ?? App.Loc.CurrentLangCode; - s.Fullscreen = IsChecked(FullscreenCb); s.PauseWhenInactive = IsChecked(PauseInactiveCb); s.PauseOnStart = IsChecked(PauseStartCb); s.CursorSensitivity = (int)CursorSensitivitySlider.Value; @@ -889,7 +914,7 @@ public partial class Settings : UserControl, ISettingsCapture s.ReflectionsFramerate = _reflections.Value; s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value; s.ShadowProjectionRange = (int)shaderRange.Value; - s.CabShadowsRange = (int)cabShaderSourceRange.Value; + s.CabShadowsRange = (int)_cabShadows.Value; s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1; s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex); s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75); @@ -901,7 +926,6 @@ public partial class Settings : UserControl, ISettingsCapture if (fpsLimit > 0) s.FpsLimit = fpsLimit; s.ShadowAngleLimit = ShadowAngleLimitSlider.Value; - s.FullscreenWindowed = IsChecked(FullscreenWindowedCb); s.RenderAngleVulkan = IsChecked(RenderAngleVulkanCb); s.SplineFidelity = (int)TrackCurvesSlider.Value; @@ -1060,6 +1084,10 @@ public partial class Settings : UserControl, ISettingsCapture CaptureInto(AppServices.Current.Settings); var store = AppServices.Current.SettingsStore; store.Save(); + // The file had changes from elsewhere, kept with these: show them. + if (store.LastSaveMerged) + ApplyToUi(); + UpdateUnknownValues(); KeyboardConfig.Instance.Save(); RedrawThumbnailsIfNeeded(); // Not saved, it is still there to be saved. @@ -1068,12 +1096,51 @@ public partial class Settings : UserControl, ISettingsCapture SaveStatus.Text = App.Loc[store.LastSaveFailed ? "SettingsNotSaved" : "SettingsSaved"]; } + // ── Rendering changes, each confirmed ────────────────────────────────── + + /// Set while a preset, a reset or a profile puts values on the screen: those are not clicks to confirm. + private bool _showingEdits; + + /// Set while a refused change is put back, which is no change to ask about. + private bool _reverting; + + private bool AsksFirst => _built && !_loading && !_showingEdits && !_reverting; + + private void AskBeforeChange(CheckBox box) => + box.IsCheckedChanged += async (_, _) => + { + if (!AsksFirst) + return; + if (!await ConfirmRenderingChange(ScreenReaderNames.TextOf(box.Content))) + Revert(() => box.IsChecked = !box.IsChecked); + }; + + private async Task ConfirmRenderingChange(string? setting) + { + if (TopLevel.GetTopLevel(this) is not Window owner) + return true; + return await MessageBox.Show(owner, string.Format(App.Loc["ConfirmRenderingChange"], setting), + App.Loc["GfxColRendering"], MessageBoxButtons.YesNo); + } + + private void Revert(Action putBack) + { + _reverting = true; + try + { + putBack(); + } + finally + { + _reverting = false; + } + } + private void RenderEngineCb_OnSelectionChanged(object? sender, SelectionChangedEventArgs e) { if (!_built) return; - OnBackendChanged(); RefreshDerivedRows(); } @@ -1129,43 +1196,6 @@ public partial class Settings : UserControl, ISettingsCapture return exes.FullPath(exes.Resolve(pick, out _)); } - /// - /// Dims the rows the simulator to be started would ignore and says why. Follows - /// the simulator and renderer picked here, before they are saved. - /// - private void UpdateIdleNotes() - { - string exe = TargetExecutable(); - var settings = AppServices.Current.Settings; - var target = new SimulatorTarget( - AppServices.Current.Executables.IsWindowsBuild(exe), - SelectedRenderer(), - settings.NetworkServer, - _keyRows.NumberIfSet("targetfps", settings), - settings.FpsAverage, - IsChecked(FullscreenWindowedCb)); - - foreach (var row in SettingsStack.GetLogicalDescendants().OfType()) - row.IdleNote = string.IsNullOrEmpty(row.ConfigKey) - ? null - : IdleText(SettingReach.Why(row.ConfigKey, target)); - - RenderEngineWarning.IsVisible = SelectedRendererKind() == RendererKind.Experimental; - } - - private static string? IdleText(IdleReason reason) => reason switch - { - IdleReason.WindowsBuildOnly => App.Loc["IdleWindowsBuildOnly"], - IdleReason.LegacyRendererOnly => App.Loc["IdleLegacyRendererOnly"], - IdleReason.ModernRendererOnly => App.Loc["IdleModernRendererOnly"], - IdleReason.OpenGlRenderersOnly => App.Loc["IdleOpenGlRenderersOnly"], - IdleReason.NeedsNetworkServer => App.Loc["IdleNeedsNetworkServer"], - IdleReason.NeedsFrameRateTarget => App.Loc["IdleNeedsFrameRateTarget"], - IdleReason.MonitorModeInstead => App.Loc["IdleMonitorMode"], - IdleReason.VulkanOnly => App.Loc["IdleVulkanOnly"], - _ => null - }; - private void RedrawThumbnailsIfNeeded() { bool large = AppServices.Current.Settings.LargeThumbnails; @@ -1285,7 +1315,6 @@ public partial class Settings : UserControl, ISettingsCapture private void UpdateShadowResolution() { int resolution = ShowPixels(ShadowResolutionRow, shaderResolutionSlider); - ToolTip.SetTip(shaderResolutionSlider, SettingTexts.ShadowMapWord(resolution)); // Below this the simulator would raise the range anyway. shaderRange.Minimum = SimulatorSettings.ShadowRangeFloor(resolution); @@ -1340,6 +1369,158 @@ public partial class Settings : UserControl, ISettingsCapture /// private void UpdateFeedbackDetailVisibility() => ApplyFilter(); + /// + /// The mode is the player's way of using the starter, not a setting of the simulator: it is + /// kept straight away, as the language is, and the scenario screen follows it. + /// + private async void AdvancedModeBtn_OnClick(object? sender, RoutedEventArgs e) + { + if (TopLevel.GetTopLevel(this) is not Window owner) + return; + + var settings = AppServices.Current.Settings; + if (!settings.AdvancedSettings) + { + if (!await MessageBox.ShowDelayed(owner, App.Loc["AdvancedModeWarning"], App.Loc["AdvancedMode"], + App.Loc["AdvancedModeOn"], 20)) + return; + + settings.AdvancedSettings = true; + AppServices.Current.SettingsStore.Save(); + } + else + { + if (!await MessageBox.Show(owner, App.Loc["AdvancedModeOffConfirm"], App.Loc["AdvancedMode"], + MessageBoxButtons.YesNo)) + return; + + // Leaving the mode leaves nothing of it behind: what only it shows goes back to the + // simulator's own values, and the page is saved with them. + ShowDefaults(AdvancedKeys()); + settings.AdvancedSettings = false; + Save(); + } + + AdvancedModeChanged?.Invoke(); + UpdateAdvancedModeButton(); + ApplyFilter(); + } + + /// + /// Once, on the first start of this starter, for the settings an older one left: the + /// standard mode, what only the advanced one shows at the simulator's own values, and + /// every slider's value within its range, saved. eu07.ini is copied aside first. + /// + public void MoveToStandardOnce() + { + var settings = AppServices.Current.Settings; + var store = AppServices.Current.SettingsStore; + if (settings.MovedToStandard || store.LoadFailed) + return; + + store.KeepCopy(".before-standard"); + _clamping = true; + try + { + ShowDefaults(AdvancedKeys()); + } + finally + { + _clamping = false; + } + // A value moved into its slider is saved as moved, not left as the file had it. + ForgetShown(SliderKeys()); + + bool wasAdvanced = settings.AdvancedSettings; + settings.AdvancedSettings = false; + settings.MovedToStandard = true; + Save(); + + if (wasAdvanced) + AdvancedModeChanged?.Invoke(); + UpdateAdvancedModeButton(); + ApplyFilter(); + } + + /// Puts at the simulator's own values, as edits waiting for Save. + private void ShowDefaults(IReadOnlyCollection keys) + { + ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys)); + foreach (string key in keys) + _keyRows.ShowDefault(key); + // Put back by hand, a value is a choice like any other. + ForgetShown(keys); + } + + /// The keys of the rows set with a slider. + private HashSet SliderKeys() + { + var keys = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var row in SettingsStack.GetLogicalDescendants().OfType()) + if (row.GetLogicalDescendants().OfType().Any()) + foreach (string key in (row.ConfigKey ?? string.Empty) + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + keys.Add(key); + return keys; + } + + /// + /// Every setting of the page at the simulator's own values, the ones only the advanced mode + /// shows too, as edits waiting for Save; the key bindings have a button of their own. + /// + private async void DefaultsButton_OnClick(object? sender, RoutedEventArgs e) + { + if (TopLevel.GetTopLevel(this) is not Window owner) + return; + if (!await MessageBox.Show(owner, App.Loc["AllDefaultsConfirm"], App.Loc["RestoreDefaults"], + MessageBoxButtons.YesNo)) + return; + + var keys = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var section in SettingsStack.GetLogicalDescendants().OfType()) + keys.UnionWith(ResettableKeys(section)); + ShowDefaults(keys); + SaveStatus.Text = App.Loc["DefaultsRestored"]; + } + + /// The keys of every row only the advanced mode shows. + private HashSet AdvancedKeys() + { + var keys = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var section in SettingsStack.GetLogicalDescendants().OfType()) + { + if (section.Advanced && !string.IsNullOrEmpty(section.ToggleKey)) + keys.Add(section.ToggleKey); + foreach (var row in section.GetLogicalDescendants().OfType()) + if (section.Advanced || row.Advanced) + foreach (string key in (row.ConfigKey ?? string.Empty) + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + keys.Add(key); + } + keys.ExceptWith(KeptOnReset); + return keys; + } + + private bool Advanced => AppServices.Current.Settings.AdvancedSettings; + + /// Under each setting, the value of eu07.ini for it the starter cannot read, as the file has it. + private void UpdateUnknownValues() + { + var unreadable = AppServices.Current.SettingsStore.UnreadableValues(); + foreach (var row in SettingsStack.GetLogicalDescendants().OfType()) + { + var keys = (row.ConfigKey ?? string.Empty) + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var found = keys.Where(unreadable.ContainsKey) + .Select(key => keys.Length > 1 ? key + " " + unreadable[key] : unreadable[key]) + .ToList(); + row.UnknownValue = found.Count > 0 ? string.Format(App.Loc["UnknownIniValue"], string.Join(", ", found)) : null; + } + } + + private void UpdateAdvancedModeButton() => + AdvancedModeBtn.Content = App.Loc[Advanced ? "AdvancedModeOff" : "AdvancedModeMenu"]; + private bool ConditionAllows(SettingRow row) { if (ReferenceEquals(row, GpuRow)) @@ -1401,6 +1582,11 @@ public partial class Settings : UserControl, ISettingsCapture SettingsScroll.IsVisible = !bindings; PresetBar.IsVisible = category is "graphics" or "effects" && !searching; + // The standard mode keeps to what a player needs; a search still finds everything, + // since whoever types a setting's name is looking for it. + bool advanced = Advanced; + bool everything = advanced || searching; + if (bindings) { _keyBindings.RebuildList(); @@ -1418,12 +1604,17 @@ public partial class Settings : UserControl, ISettingsCapture foreach (var section in panel.GetLogicalDescendants().OfType()) { bool anyInSection = false; + if (section.Level is Control level) + level.IsVisible = advanced; foreach (var row in section.GetLogicalDescendants().OfType()) { - bool visible = ConditionAllows(row) && + // A value the starter cannot read is shown in either mode, so it can be put right. + bool standard = (!section.Advanced && !row.Advanced) || !string.IsNullOrEmpty(row.UnknownValue); + bool visible = ConditionAllows(row) && (everything || standard) && (!searching || TextMatch.Contains(RowSearchText(row), query)); row.IsVisible = visible; + row.Classes.Set("HideKey", !advanced); anyInSection |= visible; if (visible && searching) _shownCount++; @@ -1441,11 +1632,17 @@ public partial class Settings : UserControl, ISettingsCapture caption.IsVisible = searching; if (CategoryItem(tag) is { } item) + { item.Classes.Set("NoHits", searching && !anyRow); + // A category with nothing for the standard mode leaves the list. + item.IsVisible = everything || anyRow; + } } if (searching) SettingsScroll.Offset = new Vector(0, 0); + else if (CategoryList.SelectedItem is ListBoxItem { IsVisible: false }) + CategoryList.SelectedIndex = 0; } private ListBoxItem? CategoryItem(string tag) => @@ -1510,9 +1707,6 @@ public partial class Settings : UserControl, ISettingsCapture case NumericUpDown nud: nud.ValueChanged += (_, _) => OnControlChanged(); break; - case TextBox box when ReferenceEquals(box, VulkanDeviceTb): - box.TextChanged += (_, _) => OnControlChanged(); - break; } } @@ -1525,7 +1719,6 @@ public partial class Settings : UserControl, ISettingsCapture { MarkDirty(); QueuePresetMarks(); - UpdateGraphicsState(); } private void MarkDirty() @@ -1556,6 +1749,31 @@ public partial class Settings : UserControl, ISettingsCapture return 200; } + /// + /// The old starter's ranges (), in either mode, with the value + /// has along with them: one from the file or a level outside them is + /// shown as it is, so opening and saving the settings never moves it - as SliderSteps does. + /// + private void ApplyRanges(SimulatorSettings s) + { + // Clamping, the ranges stay as they are and a value past them is moved in. + bool widen = !_clamping; + int minTexture = Log2(SliderRanges.MinTextureSize, 9), minShadow = Log2(SliderRanges.MinShadowMap, 10); + textureResolutionSlider.Minimum = widen ? Math.Min(minTexture, Log2(s.MaxTextureSize, 12)) : minTexture; + shaderResolutionSlider.Minimum = widen ? Math.Min(minShadow, Log2(s.ShadowMapResolution, 12)) : minShadow; + DynamicLightsSlider.Minimum = widen + ? Math.Min(SliderRanges.MinDynamicLights, s.DynamicLights) + : SliderRanges.MinDynamicLights; + CursorSensitivitySlider.Maximum = widen + ? Math.Max(SliderRanges.MaxCursorSensitivity, s.CursorSensitivity) + : SliderRanges.MaxCursorSensitivity; + foreach (var steps in new[] { _fpsLimit, _reflections, _anisotropy, _drawRangeFactor, _cabShadows }) + steps.Clamps = _clamping; + } + + /// Set while values are put on the screen moved into the sliders' ranges, not widening them. + private bool _clamping; + private static int Log2(int value, int fallback) { if (value <= 0) return fallback; @@ -1595,11 +1813,9 @@ public partial class Settings : UserControl, ISettingsCapture int reach = SimulatorSettings.ShadowReach(metres, 1 << (int)shaderResolutionSlider.Value, SelectedRendererKind() != RendererKind.Modern); ShadowRangeRow.ValueText = reach == metres ? $"{metres} m" : $"{metres} m → {reach} m"; - ToolTip.SetTip(shaderRange, SettingTexts.ShadowRangeWord(reach)); - int cabMetres = (int)cabShaderSourceRange.Value; + int cabMetres = (int)_cabShadows.Value; CabShadowRangeRow.ValueText = cabMetres <= 0 ? App.Loc["RangeDisabled"] : $"{cabMetres} m"; - ToolTip.SetTip(cabShaderSourceRange, SettingTexts.CabShadowRangeWord(cabMetres)); ReflectionsFramerateRow.ValueText = SettingTexts.ReflectionsInterval(_reflections.Value); diff --git a/StarterNG/Views/SimulatorKeyRows.cs b/StarterNG/Views/SimulatorKeyRows.cs index f90773d..917e493 100644 --- a/StarterNG/Views/SimulatorKeyRows.cs +++ b/StarterNG/Views/SimulatorKeyRows.cs @@ -83,7 +83,7 @@ internal sealed class SimulatorKeyRows // 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); diff --git a/StarterNG/Views/SliderSteps.cs b/StarterNG/Views/SliderSteps.cs index 2ba90f5..8df02ac 100644 --- a/StarterNG/Views/SliderSteps.cs +++ b/StarterNG/Views/SliderSteps.cs @@ -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; } + /// A value past either end of the list is put at that end, not added to it. + 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); diff --git a/StarterNG/startercfg/lang/cz.xml b/StarterNG/startercfg/lang/cz.xml index 9bbfc85..6ea5879 100644 --- a/StarterNG/startercfg/lang/cz.xml +++ b/StarterNG/startercfg/lang/cz.xml @@ -61,6 +61,8 @@ Vyberte scenérii Vyberte soupravu Bez osádky / cestujícího + Dekorační souprava + Souprava AI Souprava bez osádky Tato souprava nemá osádku ani cestujícího — nebude co řídit. Přesto spustit? Obnovit počasí @@ -355,8 +357,8 @@ Obecné Jazyk + Neznámá hodnota v eu07.ini: „{0}“. Zůstane v souboru, dokud ji nezměníte. Simulátor nemá překlad do tohoto jazyka a poběží v angličtině. - Celá obrazovka Pozastavit simulaci při neaktivním okně Pozastavit po spuštění Citlivost kurzoru @@ -366,6 +368,7 @@ Komunikace Ignorovat vstup z gamepadu + 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? Zpětná vazba Vypnuto @@ -407,8 +410,8 @@ Grafika Vykreslovací engine - Plný funguje s každým exe. Starý, Zjednodušený a Experimentální jen se staršími, nový místo nich spustí Plný. - 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ý“. + Změna „{0}“ může způsobit, že se simulátor nespustí nebo bude obraz vypadat špatně. Změnit? + 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. Grafická karta (Linux) Výkonnější (dedikovaná) Podle systému @@ -418,16 +421,9 @@ Nalezeno: {0}. Kartu vybírají proměnné prostředí ({1}); starter je nemění. Jedna karta: {0} – není mezi čím vybírat. Grafické karty se nepodařilo načíst z /sys/class/drm. - Funguje jen ve verzi simulátoru pro Windows. - Čte to jen renderer legacy, ale zvolen je jiný. - Funguje jen s cílovým počtem snímků (targetfps). - Experimentální renderer to nečte. - Čte to jen plný renderer, ale zvolen je jiný. - Pauza na pozadí vyžaduje síťový server (network.server). Rozlišení {0} (monitor) - Při automatickém rozlišení nefunguje. Rozlišení bufferu Maximální rozlišení textur Maximální rozlišení textur kabiny @@ -456,7 +452,14 @@ Méně snímků: chladnější a tišší počítač. S V-Sync limit nad obnovovací frekvencí nic nedělá. Omezení délky stínů Zkrácené - Automatické rozlišení (celá obrazovka bez okrajů) + Režim zobrazení + Celá obrazovka + Celá obrazovka bez okrajů + Okno + Celá obrazovka bez okrajů bere rozlišení monitoru a rychleji přepíná do jiných programů. + Monitor + Na kterém monitoru se simulátor otevře v režimu celé obrazovky. + Hlavní VSync Zobrazení kouře Násobitel částic kouře @@ -520,6 +523,12 @@ Hlasitost okolí Pokročilé + Pokročilý režim + Pokročilý režim… + Vypnout pokročilý režim + Vypnutí pokročilého režimu vrátí výchozí hodnoty všech nastavení, která jsou dostupná jen v něm, a uloží nastavení z této stránky. Vypnout? + Zapnout + Pokročilý režim zobrazí všechna nastavení simulátoru a starteru, i ta, po jejichž změně se simulátor nemusí spustit, může být nestabilní nebo vypadat špatně. Umožní také měnit obsazení souprav, soupravy AI a dekorace, takže scénář nemusí fungovat tak, jak ho autor zamýšlel. Tato nastavení měňte, jen když víte, co dělají. Potíže, které způsobí, nejsou chybami simulátoru: než chybu nahlásíte, vypněte pokročilý režim a obnovte výchozí nastavení. Přečtěte si to pozorně. Tlačítko pro zapnutí bude funkční za 20 sekund. Komprimovat textury TGA Škálovat odlesky (kompatibilita starých modelů) Zeslabuje lesk modelů dělaných pro starší renderery. @@ -569,6 +578,7 @@ Obnovit Nastavení uloženo Výchozí hodnoty obnoveny + Všechna nastavení se vrátí na výchozí. Zůstane: jazyk, vybraný simulátor, port UART a klávesy ovládání. Změny je ještě třeba uložit. Uložené nastavení obnoveno rozbaleno sbaleno @@ -796,6 +806,7 @@ include {1} bez end Soupravu {0} se nepodařilo načíst Vozidlo {0} se nepodařilo načíst + Vozidlo {0} chybí: soubor dynamic/{1} nenalezen - simulátor ho vynechá, souprava bude kratší Vložit do vybrané soupravy scenérie Připojit k vybrané soupravě scenérie Vrátit změnu soupravy @@ -810,7 +821,6 @@ Zobrazit protokol při načítání Po startu myš otáčí kamerou Ovládání prvků v kabině myší - Monitor pro celou obrazovku Složka snímků obrazovky Základní dohled vykreslování Cílová snímková frekvence @@ -849,8 +859,8 @@ Vysoká Vlastní Monitor: {0} Hz - Obrazovka {0}: až {1} Hz Nastavit {0} FPS + S VSync nebude víc snímků, než má monitor Hz, takže stejný nebo vyšší limit nic nemění. Najetím na úroveň zobrazíte hodnoty. RRRR-MM-DD Starter nemá překlad: zůstane anglicky. Simulátor dostane tento jazyk. @@ -908,73 +918,12 @@ Ve skladu: {0} Vyberte soupravu s vozidly Úroveň jen pro tuto část grafiky - Vulkan 1.4 - Funguje jen s Vulkanem. - Předvolba DLSS - Generování snímků - NVIDIA Reflex - Odrazy ray tracing - Dosah ray tracingu - Grafická karta (Vulkan) - Odrazy v prostoru obrazovky (SSR) - Okolní zastínění - Kvalita zastínění - Zastínění v okolním světle - Klastrové osvětlení - Stíny lamp a reflektorů - Kontaktní stíny - Kaskády stínů podle scény (SDSM) - Sonda kabiny - Obnovení sondy každých N snímků - Kabina odráží sebe - Odražené světlo lampy v kabině - Kvalita mlhy - Objemová oblaka - Stíny oblaků na zemi - Tráva - Dosah trávy - Hustota trávy - Srážky (částice) - Záře světlých míst (bloom) - Automatická expozice - Vypnuto - Nízká - Střední - Vysoká - Ultra - Zapnuto - Zapnuto + boost - TAA - DLSS (škálování) - DLAA (nativní rozlišení) - Automaticky - K: nejlepší kvalita - J: méně rozmazání - M: pro režim Výkon - L: pro Ultra výkon Efekty Rozlišení a vyhlazování Osvětlení Postprocessing Kouř Vyhlazování hran - Objemová mlha - DLSS, generování snímků, Reflex a ray tracing jen s Vulkanem. - Vyžaduje exe s Vulkanem a kartu, která ho podporuje. Jinak simulátor spustí Plný nebo Starý. - automaticky - 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. - Model transformer s nejlepší kvalitou obrazu, ale nejnáročnější. Výchozí pro DLAA, Kvalitu a Vyvážený. - 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. - Model pro režim Výkon (měřítko asi 50 %), tam výchozí. Expozici obrazu počítá sám. - Model pro režim Ultra výkon (měřítko asi 33 %), tam výchozí. Expozici obrazu počítá sám. - Vedle simulátoru chybí {0}: bez této knihovny simulátor tuto funkci DLSS nepoužije. - Na macOS není DLSS k dispozici. - Generování snímků funguje jen s DLSS nebo DLAA. - Generování snímků zapíná Reflex samo, ať je zde vybráno cokoli. - 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). - Při přeskočeném postprocessingu AO nefunguje. - Bez klastrového osvětlení a lampy kabiny jako světla (gfx.lights.cab) dává sonda jen odrazy. - TAA a DLSS běží v postprocessingu: při jeho přeskočení se hrany nevyhladí. Soubor eu07.ini Importovat… Importovat nastavení z eu07.ini @@ -987,9 +936,8 @@ {0} Exportováno do {0} Plný - Starý - Zjednodušený - Experimentální + Starý (nedoporučeno, pokud Plný funguje) + Zjednodušený (nedoporučeno, pokud Plný funguje) Použít renderer ANGLE Vulkan Vykreslování VBO Dosah zdrojů stínů v kabině @@ -997,6 +945,4 @@ OpenGL ES místo OpenGL. Nefunguje s rendererem legacy. {0}, {1} GB {0}, sdílená paměť - Novinky OpenGL 4.6 / Vulkan - Funguje jen s novým exe. Starší exe tato nastavení přeskočí. diff --git a/StarterNG/startercfg/lang/en.xml b/StarterNG/startercfg/lang/en.xml index db28d6a..b0daf4b 100644 --- a/StarterNG/startercfg/lang/en.xml +++ b/StarterNG/startercfg/lang/en.xml @@ -61,6 +61,8 @@ Select a scenery Select a consist No crew / passenger + Decoration consist + AI consist Consist without crew This consist has no crew and no passenger — there will be nothing to drive. Start anyway? Restore weather @@ -260,8 +262,8 @@ Whole-consist load Consist ready to go The consist starts prepared: brake pipe charged, driver’s brake valve set, batteries closed. Unchecked it starts cold and braked. - Force the consist state on launch - Overrides the depot’s "consist ready to go" box for every scenario you start. + Consist state at start + Every consist you start will be cold or ready to go, whatever the scenario says. As authored Always cold Always ready @@ -355,22 +357,23 @@ General Language - Also the simulator's language. Saved as soon as it is picked. + Language of the starter and the simulator. Saved as soon as you pick it. + Unknown value in eu07.ini: “{0}”. It stays in the file until you change this. The simulator has no translation for this language and will run in English. - Fullscreen - Pause simulation when window is inactive + Pause when window inactive Pause on start - Camera rotation sensitivity (horizontal) + Mouse sensitivity Invert mouse horizontally Invert mouse vertically External devices - Ignore gamepad control - Disables gamepad input even when one is connected. + Ignore gamepad + Ignoring the gamepad is the recommended default. Turning gamepad support on is known to cause control trouble. Change it only if you really drive with a gamepad. Change it? + Recommended. The simulator ignores a gamepad, even a connected one. Feedback - How cab feedback signals are delivered to an external panel. Keyboard modes flash LEDs: (1) Caps Lock = CA or SHP, Scroll Lock = starting resistances; (2) Caps Lock = CA, Scroll Lock = SHP. Other modes require an LPT, PoKeys55 or serial interface. + Cab signals on an external desk or on keyboard lights (Caps Lock, Scroll Lock). Off Keyboard: Caps = CA+SHP, Scroll = starting resistances Keyboard: Caps = CA, Scroll = SHP @@ -378,11 +381,11 @@ PoKeys55 (USB) COM / serial port - LPT port address - LPT port address used by the selected feedback mode. + LPT address + Address of the desk's LPT port. - UART configuration - Enable UART communication + UART + Enable UART Serial port Calibration Speed (baud) @@ -391,7 +394,7 @@ Without a port UART stays off. empty = simulator defaults Not {0} numbers: the calibration is not saved. - Print debug data to the console + Debug in console Master controller Secondary/shunting controller Train brake @@ -400,47 +403,40 @@ Radio channel Other - Select exe + Exe file Select automatically Choose file… Pick the simulator executable Use it anyway? Debug mode - Unlocks debug menus, extra panels and test shortcuts. + Debug menu and test shortcuts in the simulator. Virtual shunting - Enables an AI assistant for coupling, uncoupling and simple shunting moves while the vehicle is stopped. - Log missing vehicle files during export - Writes vehicles the starter could not find into the log. + An AI helper couples, uncouples and does simple shunting while the vehicle stands. + Log missing vehicles + When exporting, writes the missing vehicles to the log. Graphics - Render engine - Full works with every exe. Old, Simplified and Experimental only with older ones; a new exe starts Full instead. - Note: the experimental renderer may be unstable, miss parts of the scene or not start on some graphics cards. If the simulator does not start or looks wrong, go back to the “Full” renderer. - Graphics card (Linux) - Faster (discrete) - As the system decides + Renderer + Changing “{0}” can stop the simulator from starting or spoil the picture. Change it? + Use Full. Old and Simplified are only for cards Full does not work on. + Graphics card + Dedicated + System Found: {0}. The simulator will run on: {1}. Found: {0}. The screen is already driven by the right card – the starter changes nothing. Found: {0}. The system picks the card, usually the integrated one. Found: {0}. Environment variables ({1}) choose the card; the starter leaves them alone. One card: {0} – nothing to choose between. Could not read the graphics cards from /sys/class/drm. - Only the Windows build of the simulator uses this. - Only the legacy renderer reads this, and another one is chosen. - Only works with a target frame rate (targetfps). - The experimental renderer does not read this. - Only the full renderer reads this, and another one is chosen. - The pause in the background needs a network server (network.server). Resolution {0} (monitor) - Has no effect with automatic resolution. Buffer resolution - Scales the internal render buffer relative to the window resolution. - Maximum texture resolution - Maximum cabin texture resolution - Texture filtering quality - Sharpness of textures seen at an angle, such as tracks. Even x16 costs little. + The resolution the picture is drawn at. Below 100% is faster but less sharp. + Textures + Cab textures + Texture filtering + Sharpness of textures seen at an angle, like the track. Costs little. Very low Low Normal @@ -456,119 +452,132 @@ High Very high Disabled - Dynamic light sources - Maximum number of simultaneous dynamic light sources. - Draw distance stretch (max) - How many times the simulator may stretch the range when frames are to spare. Squared in the full renderer: ×3 means up to ×9. + Light sources + How many lights, like headlights, can light the surroundings at once. + Max. range stretch + How far the simulator may stretch the draw range when frames are to spare. Works with target FPS. No limit - Frame rate limit - Fewer frames: a cooler, quieter computer. With V-Sync a limit above the refresh rate does nothing. - Shadow length limit - Shortens the long shadows cast by a low sun. Higher values cut them sooner. + FPS limit + Fewer frames make a cooler and quieter computer. + Shadow length + Shortens long shadows when the sun is low. Shortened - Automatic resolution (borderless fullscreen) + Display mode + Full screen + Borderless full screen + Window + Borderless full screen takes the monitor's resolution and switches to other programs faster. + Monitor + Which monitor the simulator opens on in full screen. + Primary VSync - Synchronizes frame rate with the monitor refresh rate. - Smoke display - Smoke particles multiplier + Matches frames to the monitor refresh and removes tearing. + Smoke + Smoke amount Chromatic aberration Motion blur Additional shader effects - Reflections as cubemap - Renders reflections into a cube map, so surfaces mirror the surroundings from every direction. - Simplified depth read (compatibility) - Alternative depth-buffer read path with MSAA; enable it if your GPU has compatibility issues. - Render shadows - Reflections refresh rate - How often reflections refresh. Less often means more frames. + Reflections + Surfaces reflect their surroundings. + SkipPipeline + Draws straight to the window, with no post-processing: motion blur and the other final effects are gone. Turn on only if the picture has errors. + Draw shadows + Reflection refresh + Refreshing reflections less often means more FPS. every {0} min every {0} s {0}× a second - Shadows resolution + Shadow resolution Shadow range - How far shadows reach; the further, the softer. After the arrow: the real reach. + How far shadows reach. Further means softer shadows. - Display shadows - Sets which objects cast shadows based on material priority. Lower value = fewer shadows, higher performance. + Objects with shadows + Fewer objects with shadows means more FPS. Only important Limited All - Reflections detail level - Which objects are rendered into the reflection cubemap. - Terrain geometry only - Terrain geometry and static models - Terrain geometry, static models and vehicles + Reflection detail + What shows in reflections. + Terrain + Terrain and models + Terrain, models and vehicles View angle - Vertical camera field of view in degrees (10–75). - Render onboard computer screens - Enables cab screens driven by Python scripts. - Render screens in a separate thread + Vertical field of view of the camera. + Screens on + Screens and displays in cabs. + Screens in own thread Physics Track curves quality - How finely curved track is subdivided. Higher values are smoother but cost more CPU/GPU when loading. - Increased physics accuracy - Runs the full physics model with smaller time steps. More faithful, but heavier CPU load on large consists. - Possibility of pantograph breaking - Disabling protects the pantograph from breaking on faulty overhead line geometry. - Powered only under overhead line - When disabled, a raised pantograph can power the vehicle even without touching the wire. - Record the black box and the speedometer tapes - Records the session to one file in the physicslog/ folder and writes the tapes (.dat) of the vehicles you are in as it goes, every 2 s. - Record the speedometer tapes of every train - Writes the tapes (.dat) of every train of the scenery to the physicslog/ folder as it goes, every 2 s: one per driver of rail vehicles, not of road vehicles nor passengers. Far fewer files than the physics log of every vehicle. - Save the physics log of every vehicle - Writes the log of every vehicle of the scenery to the physicslog/ folder: a line every 0.05 s, added every 2 s. For diagnostics: on a large scenery that is hundreds of files. - Save simulation log - Keep previous logs - Creates a separate log file for each scenery instead of overwriting errors.txt. - Render 3D image - When disabled, the scenery is not drawn (black screen), but the simulation keeps running. + Higher – smoother track curves. + More accurate physics + The full physics model with a smaller time step. + Pantograph breaking + A pantograph can break on badly laid wire. + Power only from the wire + The vehicle has power only while the pantograph touches the wire. + Black box and tapes + Records the run and the speedometer tapes of the vehicles you drive (physicslog folder). + Tapes of all trains + Records the speedometer tapes of every train on the scenery (physicslog folder). + Physics log of all vehicles + A detailed log of every vehicle, for diagnostics. A big scenery makes hundreds of files. + Write log + Keep old logs + A log per scenery instead of overwriting errors.txt. + Render 3D picture + Off: black screen, the simulation keeps running. Collision damage - Damages couplers and consists during collisions and sharp jerks. - Friction multiplier - Multiplies wheel-to-rail friction. 1.00 leaves it unchanged. - Train brake step size (Num3/Num9) - Multiplies the size of a single step of the train brake handle controlled with Num3 and Num9. 1.00 leaves it unchanged. + Collisions and jerks can damage couplers and vehicles. + Friction + Wheel to rail grip. 1.00 – unchanged. + Brake valve step + How far one key press moves the train brake valve (other than FV4a). 1.00 – one position. FV4a valve speed - Multiplies how fast the locomotive brake handle (FV4a) and the local brake move. 1.00 leaves it unchanged. + How fast the FV4a valve moves while you hold the brake key. 3.00 – the simulator default. Sound Enable sound Volume - Radio volume - Vehicles volume - Positional sounds volume - Ambient volume + Radio + Vehicles + Positional sounds + Ambient Advanced + Advanced mode + Advanced mode… + Turn off advanced mode + Turning advanced mode off puts every setting only it shows back to its default and saves the settings of this page. Turn it off? + Turn it on + Advanced mode shows every setting of the simulator and the starter, including ones that can stop the simulator from starting, make it unstable or spoil the picture. It also lets you change the crews of consists, AI consists and decorations, so a scenario may not play as its author meant. Change these settings only if you know what they do. Trouble they cause is not a bug of the simulator: before reporting one, turn advanced mode off and restore the default settings. Read this carefully. The button to turn it on works in 20 seconds. Compress TGA textures - Scale specular highlights (old-model compatibility) - Tones down the shine of models made for older renderers. - Gamma correction in shaders - Gamma in the shaders instead of sRGB. For when a driver gives too bright or dark a picture. - Generate mipmaps for in-cab (Python) screen textures - Cab screens smoother from afar and at an angle, at a cost on each refresh. - Extended E3D model conversion (experimental) - Saves text models as binary E3D: faster loading, more files in the game folder. - Conservative texture memory management - Purge unused textures from GPU memory - Vehicle physics threads (0 = main thread) - Threads for vehicle physics; 0 is the main thread. More helps with many consists. - Skip decorative consists when starting + Specular scaling + Less shine on older models. + Shader gamma + Turn on if the picture is too bright or too dark. + Screen mipmaps + Cab screens look smoother from afar. + Convert models to E3D + Saves models as E3D: faster loading, more files in the game folder. + Save texture memory + Free unused textures + Physics threads + 0 – physics in the main thread. More threads help with many consists. + Skip decoration consists Starter Settings profile Apply Save as… Profile name - Automatically close starter + Close starter on launch Large thumbnails - Automatically expand scenery tree + Expand scenery tree Controls @@ -595,6 +604,7 @@ Reset Settings saved Defaults restored + Every setting goes back to its default. Kept: the language, the chosen simulator, the UART port and the key bindings. The changes still need saving. Saved settings restored expanded collapsed @@ -711,9 +721,9 @@ The new scenery wizard in the simulator's editor. Only some builds have the editor. Open the scenery editor Only some simulator builds have the scenery editor (eu07 -edit). If the selected simulator does not, the editor will not open. It works on {0} itself, not on the starter's copy, so what you save goes into the scenery. Start it? - Show log in console - Extra screen update delay - Minimum time between Python cab screen updates in milliseconds. Higher value = less frequent updates. + Log in console + Extra screens refresh + How often cab screens refresh. Less often means more FPS. Standard (200 ms) Slower (400 ms) Very slow (800 ms) @@ -739,9 +749,9 @@ Remove from rule All Picture - Renderer + Rendering Shadows - Textures and anti-aliasing + Textures Draw distance Smoothness Reflections @@ -771,7 +781,7 @@ - Resources and compatibility + Resources Log and tools Event log and tools Open the log and tools… @@ -826,68 +836,67 @@ include {1} without end Trainset {0} could not be read Vehicle {0} could not be read + Vehicle {0} missing: no file dynamic/{1} - the simulator leaves it out, the consist runs short Put into the selected scenery consist Append to the selected scenery consist Undo a change to the consist Redo a change to the consist Add to warehouse as… - Simulator UI scale - UI font size + Interface scale + Interface font Window background opacity - Show the driving aid and scenario windows on start - Open the map, training card and vehicle list on start - Transcripts window (radio and voice messages) - Show the log while loading - Mouse turns the camera on start - Click cab controls with the mouse - Full-screen monitor + Help windows at start + Map and training card at start + Message captions + Log while loading + Mouse turns camera at start + Switches by mouse Screenshots folder - Base draw range - Target frame rate - Sleeper draw distance + Draw range + Target FPS + Sleeper range Object reflection range Vehicle reflection range - Stream textures in the background - Release textures of distant vehicles - Draw the sky - Draw the cab - Motion blur shutter time - Vertical sync for screen windows - Cab screens in separate windows - Draw air hoses by how the vehicles are coupled - Smooth overhead wires (classic renderer) - Maximum sound sources - Decode sounds in the background - Load overhead wires - Recalculate track cant + Textures in background + Release vehicle textures + Sky + Cab + Blur time + Screen windows VSync + Screens in own windows + Hoses by coupling + Smooth wires + Sound sources + Sounds in background + Overhead line + Track cant Camera shake - Throw switches from the map - Route highlight on the map - Console window with the log (Windows) - The starter's messages and bulk depot tools. - Less graphics memory, longer loading. - Best left off when the graphics card has memory to spare. - May cause trouble on some graphics cards. - Leaves out consists the scenery marks as decoration. - Enlarges the simulator's windows and buttons. - Size of the text in the simulator's windows. - 1 is solid; lower values let the view show through. - Unticked, it starts with a pointer in the cab. - Off, the pointer mode is unavailable and the mouse only turns the camera. - Empty: the primary monitor. - Relative to the game folder, with no spaces in the path. - How far the scenery is drawn; a target FPS may change it. - Below this the simulator shortens the draw range, above it lengthens it. - DDS textures are read in the background: the scenery loads faster. It does not raise FPS. - Multiple of the draw range beyond which vehicle textures leave the graphics card. - Off hides the cab model; for testing. - A longer time blurs more. - Useful with several monitors or a desk with its own displays. - How many sounds may play at once. - Sound files are decoded by worker threads, for faster loading. - Without wires pantographs never break and electric locomotives always have power. - Multiplier of the cab view's sway on every axis; 0 means none. - How far ahead of and behind the vehicle the map highlights the track. + Switches from map + Route highlight + System console + Starter messages and depot tools. + Less card memory, longer loading. + Frees card memory. Turn off if you have plenty. + May cause trouble on some cards. + Does not load consists the scenery marks as decoration. + Size of windows and buttons in the simulator. + Size of text in the simulator's windows. + 1 – solid background, less – see-through. + Off: the cursor is free after start. + Off: the mouse only turns the camera. + Path relative to the game folder, without spaces. + How far the scenery is drawn. + The simulator fits the draw range to keep this FPS. 0 – off. + Faster scenery loading. Does not raise FPS. + Frees textures of far vehicles from the card. 0 – off. + Off: no cab model (for testing). + Longer – stronger blur. + For several monitors or a desk with its own displays. + How many sounds play at once. + Faster sound loading. + Off: pantographs do not break and electric locomotives always have power. + 0 – the camera does not sway. + How far ahead and behind the vehicle the map lights the track. engage the AI driver disengage the AI driver master controller up @@ -1078,8 +1087,8 @@ High Custom Screen: {0} Hz - Screen {0}: up to {1} Hz Set {0} FPS + With VSync, frames never exceed the monitor's Hz, so a limit at or above it changes nothing. Hover over a level to see its values. YYYY-MM-DD No starter translation: it stays in English. The simulator gets this language. @@ -1112,12 +1121,12 @@ scenery events stored cameras Distance factor - Shortens or lengthens how far the scenery is drawn. A target FPS overrides it. + Shortens or stretches the draw range. Very high Ultra Everything at maximum. It may be too much even for a strong card. - Screen window frame limit - Works only with screens in separate windows; without them it changes nothing. + Screen windows FPS + Only for screens in their own windows. Longest scenario {0} train {0} @@ -1137,93 +1146,13 @@ In the warehouse: {0} Pick a consist with vehicles Level for this part of the graphics only - Vulkan 1.4 - Works with Vulkan only. - DLSS preset - The model DLSS rebuilds the image with. The DLSS mode follows the buffer scale: about 67% Quality, 50% Performance, 33% Ultra Performance. - Frame generation - Extra frames between the drawn ones. With DLSS or DLAA only. x3 and x4 need an RTX 50 card. - NVIDIA Reflex - Less delay between the controls and the image. - Ray traced reflections - Fills in reflections where SSR finds nothing. The card needs ray query. - Ray tracing range - Graphics card (Vulkan) - A card's number from the list in the log, or part of its name, like RTX. Empty: chosen automatically. - Screen space reflections (SSR) - Reflections of what is on screen, on wet and smooth surfaces. - Ambient occlusion - Darkens corners and places where surfaces meet. GTAO is more accurate than SSAO. - Occlusion quality - Occlusion in ambient light - GTAO only. Darkens ambient light and reflections, sun and lamps stay bright. Off: multiplies the finished image, cheaper. - Clustered lighting - Vehicle lights and street lamps with no limit on their number. Needed for scenery lamps and the cab lamp. - Lamp and headlight shadows - Shadows cast by the cab lamp, street lamps and vehicle headlights. - Contact shadows - Small shadows where objects touch, which the shadow map misses. - Shadow cascades fitted to the scene (SDSM) - Spreads the sun shadow resolution over what is actually in view. - Cab probe - Light bounced off the cab walls and reflections of the interior in the windows. - Refresh the probe every N frames - Cab reflects itself - The windows show the cab interior instead of the sky where SSR finds nothing. - Cab lamp light bounce - How much of the lamp's light reflected off the walls lights the cab again. Works with the cab probe. - Fog quality - Volumetric clouds - Cloud shadows on the ground - Grass - Grass range - Grass density - Precipitation (particles) - Number of raindrops and snowflakes in the heaviest precipitation. - Glow of bright areas (bloom) - Automatic exposure - Image brightness adapts to the scene, for instance entering a tunnel. - Off - Low - Medium - High - Ultra - On - On + boost - TAA - DLSS (upscaling) - DLAA (native resolution) - Automatic - K: best quality - J: less smearing - M: for Performance mode - L: for Ultra Performance Effects - Resolution and anti-aliasing + Picture Lighting Post-processing Smoke - Anti-aliasing - MSAA smooths the edges of objects, TAA the whole image at the cost of a slight blur. DLSS and DLAA need Vulkan and an NVIDIA RTX card, otherwise the simulator uses TAA. - Volumetric fog - Fog with sun shafts, cloud shadows and the light of lamps. Off: the simpler analytic fog. - The quality of the clouds drawn in the sky. - DLSS, frame generation, Reflex and ray tracing need Vulkan. - Needs an exe with Vulkan and a card that supports it. Otherwise the simulator starts Full or Old. - automatic - K for DLAA, Quality and Balanced, M for Performance, L for Ultra Performance. The driver may change this with an update. - The transformer model with the best image quality, but the most expensive to compute. The default for DLAA, Quality and Balanced. - Similar to K: slightly less ghosting behind moving objects at the cost of more flicker. NVIDIA recommends K instead. - The model tuned for Performance mode (about 50% scale), its default there. Works out the image exposure itself. - The model tuned for Ultra Performance mode (about 33% scale), its default there. Works out the image exposure itself. - {0} is not next to the simulator: without it the simulator cannot use this DLSS feature. - DLSS is not available on macOS. - Frame generation works with DLSS or DLAA only. - Frame generation turns Reflex on by itself, whatever is chosen here. - Needs the depth of the whole scene before its colour; without SSR and contact shadows that is an extra pass (CPU cost on OpenGL). - With the post-processing skipped the AO does not work. - Without the clustered lighting and the cab lamp as a light (gfx.lights.cab) the probe gives the reflections only. - TAA and DLSS run in the post-processing: with it skipped the edges will not be smoothed. + Multisampling + Smooths edges. A higher level gives a smoother picture and fewer FPS. eu07.ini file Import… Import settings from eu07.ini @@ -1236,19 +1165,16 @@ {0} Exported to {0} Full - Old - Simplified - Experimental - Use ANGLE Vulkan renderer - Runs the ANGLE renderer on Vulkan instead of the default backend. Useful when OpenGL misbehaves. - Render VBO - Keeps geometry in GPU buffers (faster). Disable only if you have problems with an old GPU. - Cabin shadow sources range - Distance at which light sources still cast shadows inside the cab. Zero turns cab shadows off. - Use OpenGL ES - OpenGL ES instead of OpenGL. Does not work with the legacy renderer. + Old (not recommended) + Simplified (not recommended) + ANGLE (Vulkan) + Draws through ANGLE on Vulkan. Turn on if plain OpenGL gives trouble. + VBO + Turn off only if an older card has picture problems. + Cab shadows + How far lights cast shadows in the cab. 0 turns cab shadows off. + OpenGL ES + OpenGL ES instead of OpenGL. Does not work with the old renderer. {0}, {1} GB {0}, shared memory - New in OpenGL 4.6 / Vulkan - These work only with the new exe. An older exe skips them. diff --git a/StarterNG/startercfg/lang/hu.xml b/StarterNG/startercfg/lang/hu.xml index e65ecd9..5fe3f47 100644 --- a/StarterNG/startercfg/lang/hu.xml +++ b/StarterNG/startercfg/lang/hu.xml @@ -61,6 +61,8 @@ Válasszon pályát Válasszon szerelvényt Nincs személyzet / utas + Díszlet szerelvény + AI-szerelvény Szerelvény személyzet nélkül Ebben a szerelvényben nincs személyzet és utas sem — nem lesz mit vezetni. Mégis elindítja? Időjárás visszaállítása @@ -355,8 +357,8 @@ Általános Nyelv + Ismeretlen érték az eu07.ini-ben: „{0}”. A fájlban marad, amíg meg nem változtatja. A szimulátornak nincs fordítása erre a nyelvre, angolul fog futni. - Teljes képernyő Szimuláció szüneteltetése inaktív ablaknál Szüneteltetés indításkor Kurzorérzékenység @@ -366,6 +368,7 @@ Kommunikáció Gamepad bemenet mellőzése + Az ajánlott és alapértelmezett beállítás a gamepad figyelmen kívül hagyása. A támogatás bekapcsolása gyakran okoz gondot az irányításban. Csak akkor módosítsa, ha valóban gamepaddel vezet. Módosítja? Visszajelzés Ki @@ -407,8 +410,8 @@ Grafika Megjelenítő motor - A Teljes minden exe-vel működik. A Régi, az Egyszerűsített és a Kísérleti csak a régebbiekkel, az új helyettük a Teljeset indítja. - Figyelem: a kísérleti renderelő instabil lehet, a jelenet egyes részei hiányozhatnak, vagy egyes videokártyákon el sem indul. Ha a szimulátor nem indul el vagy hibásan jelenik meg, válts vissza a „Teljes” renderelőre. + A(z) „{0}” módosítása miatt a szimulátor nem indulhat el, vagy rossz lehet a kép. Módosítja? + A Teljes a szimulátor ajánlott renderelője. A Régi és az Egyszerűsített a klasszikus renderelővel rajzol, és nem ajánlott, ha a Teljes működik – azokhoz a videokártyákhoz valók, amelyekkel a Teljesnek gondja van. Videokártya (Linux) Erősebb (dedikált) Ahogy a rendszer dönt @@ -418,16 +421,9 @@ Találat: {0}. A kártyát környezeti változók választják ({1}); az indító nem módosítja őket. Egy kártya: {0} – nincs miből választani. Nem sikerült beolvasni a videokártyákat a /sys/class/drm alól. - Csak a szimulátor Windowsos változata használja. - Ezt csak a legacy renderelő olvassa, de más van kiválasztva. - Csak cél képkockaszámmal működik (targetfps). - A kísérleti renderelő ezt nem olvassa. - Ezt csak a teljes renderelő olvassa, de más van kiválasztva. - A háttérben szüneteléshez hálózati szerver kell (network.server). Felbontás {0} (monitor) - Automatikus felbontásnál nincs hatása. Puffer felbontása Textúrák legnagyobb felbontása Vezetőállás-textúrák legnagyobb felbontása @@ -456,7 +452,14 @@ Kevesebb képkocka: hűvösebb, csendesebb gép. V-Sync mellett a frissítés feletti korlát hatástalan. Árnyékhossz korlátozása Rövidített - Automatikus felbontás (keret nélküli teljes képernyő) + Megjelenítési mód + Teljes képernyő + Keret nélküli teljes képernyő + Ablak + A keret nélküli teljes képernyő a monitor felbontását használja, és gyorsabban vált más programokra. + Monitor + Melyik monitoron nyíljon meg a szimulátor teljes képernyőn. + Elsődleges VSync Füst megjelenítése Füstrészecskék szorzója @@ -520,6 +523,12 @@ Környezeti hangok hangereje Speciális + Haladó mód + Haladó mód… + Haladó mód kikapcsolása + A haladó mód kikapcsolása visszaállítja az alapértéket minden csak benne elérhető beállításnál, és menti az oldal beállításait. Kikapcsolja? + Bekapcsolom + A haladó mód a szimulátor és az indító minden beállítását megmutatja, azokat is, amelyek módosítása után a szimulátor nem indulhat el, instabil lehet, vagy rossz lehet a kép. A szerelvények személyzetét, az AI-szerelvényeket és a díszleteket is módosíthatja, így a forgatókönyv nem úgy működhet, ahogy a szerzője tervezte. Csak akkor módosítsa ezeket, ha tudja, mit csinálnak. Az ebből eredő gondok nem a szimulátor hibái: hibabejelentés előtt kapcsolja ki a haladó módot, és állítsa vissza az alapbeállításokat. Olvassa el figyelmesen. A bekapcsoló gomb 20 másodperc múlva működik. TGA textúrák tömörítése Csillanások skálázása (régi modellek kompatibilitása) Csökkenti a régebbi megjelenítőkhöz készült modellek csillogását. @@ -569,6 +578,7 @@ Visszaállítás A beállítások elmentve Alapértékek visszaállítva + Minden beállítás visszaáll az alapértékre. Megmarad: a nyelv, a kiválasztott szimulátor, az UART-port és a billentyűk. A változásokat még menteni kell. A mentett beállítások visszaállítva kibontva összecsukva @@ -796,6 +806,7 @@ include {1} end nélkül A(z) {0} szerelvényt nem sikerült beolvasni A(z) {0} járművet nem sikerült beolvasni + A(z) {0} jármű hiányzik: nincs dynamic/{1} fájl - a szimulátor kihagyja, a szerelvény rövidebb lesz Beillesztés a kijelölt pályaszerelvénybe Hozzáfűzés a kijelölt pályaszerelvényhez Szerelvénymódosítás visszavonása @@ -810,7 +821,6 @@ Napló megjelenítése betöltés közben Induláskor az egér a kamerát forgatja Vezetőfülke kezelőszerveinek kattintása egérrel - Teljes képernyős monitor Képernyőképek mappája Alap megjelenítési távolság Cél képkockasebesség @@ -849,8 +859,8 @@ Magas Egyéni Monitor: {0} Hz - {0} kijelző: legfeljebb {1} Hz {0} FPS beállítása + VSync mellett nem lesz több képkocka, mint a monitor Hz-e, így ennyi vagy nagyobb korlát semmit sem változtat. Vidd az egeret a szintre az értékekhez. ÉÉÉÉ-HH-NN Nincs fordítás az indítóhoz: angol marad. A szimulátor ezt a nyelvet kapja. @@ -908,73 +918,12 @@ A raktárban: {0} Válassz járműveket tartalmazó szerelvényt Csak a grafika ezen részének szintje - Vulkan 1.4 - Csak Vulkannal működik. - DLSS előbeállítás - Képkocka-generálás - NVIDIA Reflex - Sugárkövetéses tükröződés - Sugárkövetés hatótávja - Videokártya (Vulkan) - Képernyőtéri tükröződés (SSR) - Környezeti kitakarás - Kitakarás minősége - Kitakarás a környezeti fényben - Klaszteres megvilágítás - Lámpák és fényszórók árnyéka - Kontaktárnyékok - Jelenethez igazított árnyékkaszkádok (SDSM) - Fülkeszonda - Szonda frissítése N képkockánként - A fülke önmagát tükrözi - A fülkelámpa visszavert fénye - Köd minősége - Térfogati felhők - Felhők árnyéka a talajon - Fű - Fű hatótávja - Fű sűrűsége - Csapadék (részecskék) - Világos részek ragyogása (bloom) - Automatikus expozíció - Ki - Alacsony - Közepes - Magas - Ultra - Be - Be + boost - TAA - DLSS (felskálázás) - DLAA (natív felbontás) - Automatikus - K: legjobb minőség - J: kevesebb elmosódás - M: Teljesítmény módhoz - L: Ultra teljesítményhez Effektek Felbontás és élsimítás Világítás Utófeldolgozás Füst Élsimítás - Térfogati köd - A DLSS, a képkocka-generálás, a Reflex és a ray tracing csak Vulkannal működik. - Vulkanos exe és azt támogató kártya kell hozzá. Különben a szimulátor a Teljeset vagy a Régit indítja. - automatikus - K a DLAA, a Minőség és a Kiegyensúlyozott módhoz, M a Teljesítményhez, L az Ultra teljesítményhez. Az illesztőprogram frissítéskor módosíthatja. - A legjobb képminőségű transformer modell, de a legdrágább. Alapértelmezett a DLAA, a Minőség és a Kiegyensúlyozott módhoz. - A K-hoz hasonló: kevesebb szellemkép a mozgó tárgyak mögött, több villogással. Az NVIDIA inkább a K-t ajánlja. - A Teljesítmény módhoz (kb. 50%-os méretezés) való modell, ott alapértelmezett. A kép expozícióját maga számolja. - Az Ultra teljesítmény módhoz (kb. 33%-os méretezés) való modell, ott alapértelmezett. A kép expozícióját maga számolja. - A szimulátor mellett nincs {0}: e könyvtár nélkül a szimulátor nem használja ezt a DLSS-funkciót. - macOS-en a DLSS nem érhető el. - A képkocka-generálás csak DLSS-sel vagy DLAA-val működik. - A képkocka-generálás magától bekapcsolja a Reflexet, bármi van itt kiválasztva. - A teljes jelenet mélysége kell a szín előtt; SSR és kontaktárnyékok nélkül ez egy külön menet (CPU-terhelés OpenGL-ben). - Kihagyott utófeldolgozásnál az AO nem működik. - Klaszteres megvilágítás és a fülkelámpa mint fény (gfx.lights.cab) nélkül a szonda csak tükröződést ad. - A TAA és a DLSS az utófeldolgozásban fut: ha kihagyod, az élek nem simulnak ki. eu07.ini fájl Importálás… Beállítások importálása az eu07.ini fájlból @@ -987,9 +936,8 @@ {0} Exportálva ide: {0} Teljes - Régi - Egyszerűsített - Kísérleti + Régi (nem ajánlott, ha a Teljes működik) + Egyszerűsített (nem ajánlott, ha a Teljes működik) ANGLE Vulkan megjelenítő használata VBO megjelenítés Vezetőállás árnyékforrásainak hatótávolsága @@ -997,6 +945,4 @@ OpenGL ES az OpenGL helyett. A legacy megjelenítővel nem működik. {0}, {1} GB {0}, megosztott memória - OpenGL 4.6 / Vulkan újdonságok - Csak az új exe-vel működnek. A régebbi exe kihagyja ezeket a beállításokat. diff --git a/StarterNG/startercfg/lang/pl.xml b/StarterNG/startercfg/lang/pl.xml index 5ab0d59..a243577 100644 --- a/StarterNG/startercfg/lang/pl.xml +++ b/StarterNG/startercfg/lang/pl.xml @@ -61,6 +61,8 @@ Wybierz scenerię Wybierz skład Brak obsady / pasażera + Skład dekoracyjny + Skład AI Skład bez obsady Skład nie ma obsady ani pasażera — nie będzie czym kierować. Uruchomić mimo to? Przywróć pogodę @@ -260,8 +262,8 @@ Ładunki zestawienia Skład gotowy do jazdy Skład startuje przygotowany: przewód główny napełniony, kran maszynisty ustawiony, akumulatory załączone. Odznaczony startuje zimny i zahamowany. - Wymuś stan składu przy starcie - Nadpisuje pole „Skład gotowy do jazdy” w zajezdni dla każdego uruchamianego scenariusza. + Stan składu przy starcie + Każdy uruchamiany skład będzie zimny albo gotowy do jazdy, niezależnie od scenariusza. Jak w scenerii Zawsze zimny Zawsze gotowy @@ -355,22 +357,23 @@ Ogólne Język - Także język symulatora. Zapisywany od razu po wybraniu. + Język startera i symulatora. Zmiana zapisuje się od razu. + Wartość w eu07.ini jest nieznana: „{0}”. Zostaje w pliku, dopóki tego nie zmienisz. Symulator nie ma tłumaczenia na ten język i uruchomi się po angielsku. - Tryb pełnoekranowy - Wstrzymaj symulację, gdy okno nie jest aktywne + Pauza, gdy okno nieaktywne Pauza po uruchomieniu - Czułość obrotu kamery (oś pozioma) - Inwersja myszy w poziomie - Inwersja myszy w pionie + Czułość myszy + Odwróć mysz w poziomie + Odwróć mysz w pionie Urządzenia zewnętrzne - Ignoruj sterowanie z gamepada - Wyłącza obsługę gamepada, nawet gdy jest podłączony. + Ignoruj gamepad + Zalecane i domyślne jest ignorowanie gamepada. Włączenie jego obsługi bywa źródłem problemów ze sterowaniem. Zmieniaj tylko, jeśli naprawdę sterujesz gamepadem. Zmienić? + Zalecane. Symulator nie reaguje na gamepada, nawet podłączonego. Informacja zwrotna - Sposób przekazywania sygnałów kabinowych na zewnętrzny pulpit. Tryby klawiatury migają diodami: (1) Caps Lock = CA lub SHP, Scroll Lock = jazda na oporach; (2) Caps Lock = CA, Scroll Lock = SHP. Pozostałe tryby wymagają interfejsu LPT, PoKeys55 lub portu szeregowego. + Sygnalizacja z kabiny na zewnętrznym pulpicie albo diodach klawiatury (Caps Lock, Scroll Lock). Wyłączona Klawiatura: Caps = CA+SHP, Scroll = opory Klawiatura: Caps = CA, Scroll = SHP @@ -378,11 +381,11 @@ PoKeys55 (USB) COM / port szeregowy - Adres portu LPT - Adres portu LPT używanego przez wybrany tryb informacji zwrotnej. + Adres LPT + Adres portu LPT pulpitu. - Konfiguracja UART - Włącz komunikację UART + UART + Włącz UART Port szeregowy Kalibracja Prędkość (baud) @@ -391,7 +394,7 @@ Bez portu UART zostanie wyłączony. puste = wartości symulatora To nie jest {0} liczb: kalibracja nie zostanie zapisana. - Wypisuj dane debugowania w konsoli + Debug w konsoli Nastawnik główny Nastawnik manewrowy/pomocniczy Hamulec zespolony @@ -400,47 +403,40 @@ Kanał radiotelefonu Inne - Wybór exe + Plik exe Wybierz automatycznie Wybierz plik… Wskaż plik wykonywalny symulatora Użyć go mimo to? Tryb testowy - Odblokowuje menu debug, dodatkowe panele i skróty testowe. + Menu debugowania i skróty testowe w symulatorze. Wirtualny manewrowy - Włącza asystenta AI do sprzęgania, rozprzęgania i prostych manewrów, gdy pojazd stoi. - Zapisuj w logu brakujące pliki pojazdów podczas eksportu - Zapisuje w logu pojazdy, których starter nie znalazł. + Asystent AI sprzęga, rozprzęga i robi proste manewry, gdy pojazd stoi. + Loguj brakujące pojazdy + Przy eksporcie zapisuje w logu pojazdy, których brakuje. Grafika - Silnik renderowania - Pełny działa z każdym exe. Stary, Uproszczony i Eksperymentalny tylko ze starszymi exe, nowy włączy zamiast nich Pełny. - Uwaga: renderer eksperymentalny może działać niestabilnie, nie pokazywać części obiektów albo nie uruchomić się na niektórych kartach graficznych. Gdy symulator nie startuje lub wygląda źle, wróć do renderera „Pełny”. - Karta graficzna (Linux) - Wydajniejsza (dedykowana) - Jak system + Renderer + Zmiana „{0}” może sprawić, że symulator się nie uruchomi albo obraz będzie wyglądał źle. Zmienić? + Używaj Pełnego. Stary i Uproszczony są tylko dla kart, na których Pełny nie działa. + Karta graficzna + Dedykowana + Systemowa Wykryto: {0}. Symulator ruszy na: {1}. Wykryto: {0}. Ekran prowadzi już właściwa karta – starter nic nie zmienia. Wykryto: {0}. Kartę wybierze system, zwykle zintegrowaną. Wykryto: {0}. Kartę wybierają zmienne środowiskowe ({1}); starter ich nie zmienia. Jedna karta: {0} – nie ma między czym wybierać. Nie udało się odczytać kart graficznych z /sys/class/drm. - Działa tylko w wersji symulatora dla Windows. - Czyta to tylko renderer legacy, a wybrany jest inny. - Działa tylko z docelową liczbą klatek (targetfps). - Renderer eksperymentalny tego nie czyta. - Czyta to tylko renderer pełny, a wybrany jest inny. - Pauza w tle działa tylko z serwerem sieciowym (network.server). Rozdzielczość {0} (monitor) - Nie działa przy automatycznej rozdzielczości. Rozdzielczość bufora - Skaluje wewnętrzny bufor renderowania względem rozdzielczości okna. - Maksymalna rozdzielczość tekstur - Maksymalna rozdzielczość tekstur kabiny - Jakość filtrowania tekstur - Ostrość tekstur oglądanych pod kątem, np. torów. Nawet x16 kosztuje niewiele. + W jakiej rozdzielczości rysowany jest obraz. Poniżej 100% szybciej, ale mniej ostro. + Tekstury + Tekstury kabiny + Filtrowanie tekstur + Ostrość tekstur widzianych pod kątem, np. torów. Mało obciąża kartę. Bardzo niska Niska Normalna @@ -456,119 +452,132 @@ Wysoki Bardzo wysoki Wyłączone - Dynamiczne źródła światła - Maksymalna liczba jednoczesnych źródeł światła dynamicznego. - Wydłużanie zasięgu (maks.) - Ile razy symulator może wydłużyć zasięg, gdy klatek jest z zapasem. W pełnym rendererze w kwadracie: ×3 to do ×9. + Źródła światła + Ile świateł, np. reflektorów, może naraz oświetlać otoczenie. + Maks. wydłużenie zasięgu + O ile symulator może wydłużyć zasięg rysowania, gdy ma zapas klatek. Działa z docelowym FPS. Bez limitu - Limit klatek na sekundę - Mniej klatek to chłodniejszy i cichszy komputer. Z V-Sync limit powyżej odświeżania nic nie daje. - Limit długości cienia - Skraca długie cienie rzucane przez nisko stojące słońce. Wyższe wartości ucinają je wcześniej. + Limit FPS + Mniej klatek to chłodniejszy i cichszy komputer. + Długość cieni + Skraca długie cienie przy nisko stojącym słońcu. Skrócone - Automatyczna rozdzielczość (pełny ekran bez obramowania) + Tryb wyświetlania + Pełny ekran + Pełny ekran bez ramki + Okno + Pełny ekran bez ramki bierze rozdzielczość monitora i szybciej przełącza do innych programów. + Monitor + Na którym monitorze otworzy się symulator w trybie pełnoekranowym. + Główny VSync - Synchronizacja klatek z odświeżaniem monitora. - Wyświetlanie dymu - Mnożnik ilości cząsteczek dymu + Zgrywa klatki z odświeżaniem monitora i usuwa rwanie obrazu. + Dym + Ilość dymu Aberracja chromatyczna - Rozmycie podczas ruchu + Rozmycie ruchu Dodatkowe efekty shaderów - Odbicia jako cubemapa - Renderuje odbicia do mapy sześciennej, dzięki czemu powierzchnie odbijają otoczenie ze wszystkich stron. - Uproszczony odczyt głębi (zgodność) - Alternatywna ścieżka odczytu bufora głębi przy MSAA; włącz przy problemach z kompatybilnością karty graficznej. - Renderowanie cieni + Odbicia + Powierzchnie odbijają otoczenie. + SkipPipeline + Rysuje prosto do okna, bez obróbki obrazu: znika rozmycie ruchu i inne efekty końcowe. Włącz tylko przy błędach obrazu. + Rysuj cienie Odświeżanie odbić - Jak często odświeżać odbicia. Rzadziej to więcej klatek. + Rzadsze odświeżanie odbić to więcej FPS. co {0} min co {0} s {0}× na s Rozdzielczość cieni Zasięg cieni - Jak daleko sięgają cienie; im dalej, tym mniej ostre. Po strzałce zasięg rzeczywisty. + Jak daleko widać cienie. Dalej to mniej ostre cienie. - Wyświetlanie cieni - Określa, które obiekty rzucają cień według priorytetu materiału. Niższa wartość = mniej cieni, wyższa wydajność. + Obiekty z cieniem + Mniej obiektów z cieniem to więcej FPS. Tylko ważne Ograniczone Wszystkie Szczegółowość odbić - Jakie obiekty są renderowane w odbiciach cubemap. - Tylko geometria terenu - Geometria terenu i modele statyczne - Geometria terenu, modele statyczne i pojazdy + Co widać w odbiciach. + Teren + Teren i modele + Teren, modele i pojazdy Kąt widzenia - Pionowy kąt widzenia kamery w stopniach (10–75). - Renderowanie ekranów komputerów pokładowych - Włącza ekrany kabinowe obsługiwane przez skrypty Python. - Renderowanie ekranów w osobnym wątku + Pionowy kąt widzenia kamery. + Ekrany włączone + Ekrany i wyświetlacze w kabinach. + Ekrany w osobnym wątku Fizyka Jakość łuków torów - Gęstość podziału łuków torów. Wyższa wartość = gładsze łuki. - Zwiększona dokładność fizyki - Uruchamia pełny model fizyki z mniejszym krokiem czasowym. - Możliwość złamania pantografu - Wyłączenie chroni pantograf przed uszkodzeniem przy błędnej geometrii sieci. - Zasilanie tylko pod siecią trakcyjna - Gdy wyłączone, podniesiony pantograf zasila pojazd nawet bez kontaktu z drutem. - Zapisuj czarną skrzynkę i taśmy prędkościomierza - Nagrywa przejazd do jednego pliku w folderze physicslog/ i na bieżąco, co 2 s, zapisuje taśmy (.dat) pojazdów, w których jesteś. - Zapisuj taśmy prędkościomierza wszystkich pociągów - Na bieżąco, co 2 s, zapisuje taśmy (.dat) każdego pociągu scenerii do folderu physicslog/: jedną na maszynistę pojazdów szynowych, bez pojazdów drogowych i pasażerów. Znacznie mniej plików niż log fizyki każdego pojazdu. - Zapisuj log parametrów fizycznych wszystkich pojazdów - Zapisuje log każdego pojazdu scenerii do folderu physicslog/: wiersz co 0,05 s, dopisywany co 2 s. Do diagnostyki: na dużej scenerii to setki plików. - Zapisuj log z symulacji - Zachowuj poprzednie logi - Tworzy osobny plik logu dla każdej scenerii zamiast nadpisywać errors.txt. + Wyżej – gładsze łuki torów. + Dokładniejsza fizyka + Pełny model fizyki z mniejszym krokiem czasu. + Łamanie pantografów + Pantograf może się złamać na źle poprowadzonej sieci. + Zasilanie tylko z sieci + Pojazd ma prąd tylko wtedy, gdy pantograf dotyka sieci. + Czarna skrzynka i taśmy + Zapisuje przejazd i taśmy prędkościomierza pojazdów, którymi jedziesz (folder physicslog). + Taśmy wszystkich pociągów + Zapisuje taśmy prędkościomierza wszystkich pociągów na scenerii (folder physicslog). + Log fizyki wszystkich pojazdów + Szczegółowy log każdego pojazdu, do diagnostyki. Na dużej scenerii to setki plików. + Zapisuj log + Zachowuj stare logi + Osobny log dla każdej scenerii zamiast nadpisywania errors.txt. Renderuj obraz 3D - Wyłączenie pomija rysowanie scenerii (czarny ekran), ale symulacja nadal działa. + Wyłączone: czarny ekran, symulacja działa dalej. Uszkodzenia przy zderzeniu - Uszkodzenia sprzęgów i składów przy kolizjach i gwałtownym naciągu. - Mnożnik tarcia - Mnoży tarcie koła o szynę. 1,00 nie zmienia niczego. - Krok nastawy hamulca zespolonego (Num3/Num9) - Mnoży wielkość pojedynczego kroku kranu hamulca zespolonego sterowanego klawiszami Num3 i Num9. 1,00 nie zmienia niczego. - Szybkość zaworu FV4a - Mnoży szybkość przesuwania kranu hamulca lokomotywy (FV4a) i hamulca lokalnego. 1,00 nie zmienia niczego. + Kolizje i szarpnięcia mogą uszkodzić sprzęgi i pojazdy. + Tarcie + Przyczepność kół do szyn. 1,00 – bez zmian. + Krok kranu hamulca + O ile jedno naciśnięcie klawisza przesuwa kran hamulca zespolonego (poza FV4a). 1,00 – o jedną pozycję. + Szybkość kranu FV4a + Jak szybko przesuwa się kran FV4a, gdy trzymasz klawisz hamowania. 3,00 – domyślnie w symulatorze. Dźwięk Włącz dźwięk Głośność - Głośność radiotelefonu - Głośność pojazdów - Głośność dźwięków pozycjonowanych - Głośność otoczenia + Radiotelefon + Pojazdy + Dźwięki pozycjonowane + Otoczenie Zaawansowane - Kompresuj tekstury TGA - Skaluj odbicia specularne (kompatybilność ze starymi modelami) - Osłabia połysk modeli robionych pod starsze renderery. - Korekcja gamma w shaderach - Gamma w shaderach zamiast sRGB. Gdy sterownik daje za jasny lub za ciemny obraz. - Generuj mipmapy dla tekstur ekranów kabinowych (Python) - Ekrany w kabinie gładsze z daleka i pod kątem, kosztem każdego odświeżenia. - Rozszerzona konwersja modeli E3D (eksperymentalne) - Zapisuje modele tekstowe jako binarne E3D: szybsze wczytywanie, więcej plików w folderze gry. - Ostrożne zarządzanie pamięcią tekstur - Usuwaj nieużywane tekstury z pamięci GPU - Wątki fizyki pojazdów (0 = wątek główny) - Wątki fizyki pojazdów; 0 to wątek główny. Więcej pomaga przy wielu składach. - Pomijaj składy dekoracyjne przy starcie + Tryb zaawansowany + Tryb zaawansowany… + Wyłącz tryb zaawansowany + Wyłączenie trybu zaawansowanego przywróci domyślne wartości wszystkich ustawień, które są dostępne tylko w nim, i zapisze ustawienia z tej strony. Wyłączyć? + Włączam + Tryb zaawansowany pokazuje wszystkie ustawienia symulatora i startera, także te, po których zmianie symulator może się nie uruchomić, działać niestabilnie albo wyglądać źle. Pozwala też zmieniać obsadę składów, składy AI i dekoracje, przez co scenariusz może nie działać tak, jak zaplanował autor. Zmieniaj te ustawienia tylko wtedy, gdy wiesz, co robią. Kłopoty, które z nich wynikną, nie są błędami symulatora: zanim zgłosisz błąd, wyłącz tryb zaawansowany i przywróć ustawienia domyślne. Przeczytaj to uważnie. Przycisk włączenia zadziała za 20 sekund. + Kompresja tekstur TGA + Skalowanie specular + Słabszy połysk starszych modeli. + Gamma w shaderach + Włącz, gdy obraz jest za jasny albo za ciemny. + Mipmapy ekranów + Ekrany w kabinie wyglądają gładziej z daleka. + Konwersja modeli do E3D + Zapisuje modele jako E3D: szybsze wczytywanie, więcej plików w folderze gry. + Oszczędzanie pamięci tekstur + Zwalniaj nieużywane tekstury + Wątki fizyki + 0 – fizyka w głównym wątku. Więcej wątków pomaga przy wielu składach. + Pomijaj składy-dekoracje Starter Profil ustawień Zastosuj Zapisz jako… Nazwa profilu - Zamknij starter automatycznie + Zamykaj starter po uruchomieniu Duże miniaturki - Automatycznie rozwijanie drzewka scenerii + Rozwijaj drzewo scenerii Sterowanie @@ -595,6 +604,7 @@ Przywróć Zapisano ustawienia Przywrócono domyślne + Wszystkie ustawienia wrócą do domyślnych. Zostaną: język, wybrany symulator, port UART i klawisze sterowania. Zmiany trzeba jeszcze zapisać. Przywrócono zapisane ustawienia rozwinięte zwinięte @@ -711,9 +721,9 @@ Kreator nowej scenerii w edytorze symulatora. Edytor mają tylko niektóre wersje. Uruchom edytor scenerii Edytor scenerii (eu07 -edit) mają tylko niektóre wersje symulatora. Jeśli wybrany plik symulatora go nie obsługuje, edytor się nie otworzy. Edytor pracuje na samym pliku {0}, a nie na kopii przygotowanej przez starter, więc zapisane zmiany trafią do scenerii. Uruchomić? - Wyświetlaj log w konsoli - Opóźnienie odświeżania ekranów dodatkowych - Minimalny czas między aktualizacjami ekranów Python w kabinach (ms). Wyższa wartość = rzadsze odświeżanie. + Log w konsoli + Odświeżanie ekranów dodatkowych + Jak często odświeżać ekrany w kabinie. Rzadziej to więcej FPS. Standardowe (200 ms) Wolniejsze (400 ms) Bardzo wolne (800 ms) @@ -739,9 +749,9 @@ Usuń z reguły Wszystkie Obraz - Silnik renderowania + Renderowanie Cienie - Tekstury i wygładzanie + Tekstury Zasięg rysowania Płynność Odbicia @@ -768,7 +778,7 @@ Otwórz menu pojazdu - Zasoby i zgodność + Zasoby Dziennik i narzędzia Dziennik zdarzeń i narzędzia Otwórz dziennik i narzędzia… @@ -823,68 +833,67 @@ include {1} bez end Nie udało się odczytać składu {0} Nie udało się odczytać pojazdu {0} + Brak pojazdu {0}: nie ma pliku dynamic/{1} - symulator go pominie, skład będzie krótszy Wstaw do wybranego składu na scenerii Dołącz do wybranego składu na scenerii Cofnij zmianę składu Ponów zmianę składu Dodaj do magazynu jako… - Skala interfejsu symulatora - Rozmiar czcionki interfejsu - Nieprzezroczystość tła okien - Pokazuj okna pomocy jazdy i scenariusza po starcie - Otwieraj mapę, kartę szkolenia i listę pojazdów po starcie - Okno napisów (komunikaty radiowe i głosowe) - Pokazuj dziennik podczas wczytywania - Po starcie mysz obraca kamerą - Klikanie przełączników w kabinie myszą - Monitor pełnoekranowy - Folder zrzutów ekranu - Bazowy zasięg rysowania - Docelowa liczba klatek - Zasięg rysowania podkładów + Skala interfejsu + Czcionka interfejsu + Krycie tła okien + Okna pomocy po starcie + Mapa i karta szkolenia po starcie + Napisy komunikatów + Dziennik przy wczytywaniu + Mysz obraca kamerą po starcie + Przełączniki myszą + Folder zrzutów + Zasięg rysowania + Docelowy FPS + Zasięg podkładów Zasięg odbić obiektów Zasięg odbić pojazdów - Wczytuj tekstury w tle - Zwalniaj tekstury odległych pojazdów - Rysuj niebo - Rysuj kabinę - Czas naświetlania rozmycia ruchu - Synchronizacja pionowa okien ekranów - Ekrany z kabiny w osobnych oknach - Węże pneumatyczne rysowane według sprzęgnięcia - Wygładzanie przewodów sieci (renderer klasyczny) - Maksymalna liczba źródeł dźwięku - Dekoduj dźwięki w tle - Wczytuj sieć trakcyjną - Przeliczaj przechyłkę torów + Tekstury w tle + Zwalnianie tekstur pojazdów + Niebo + Kabina + Czas rozmycia + VSync okien ekranów + Ekrany w osobnych oknach + Węże wg sprzęgnięcia + Wygładzanie sieci + Źródła dźwięku + Dźwięki w tle + Sieć trakcyjna + Przechyłka torów Bujanie kamery - Przestawianie zwrotnic z mapy - Podświetlanie drogi na mapie - Okno konsoli z dziennikiem (Windows) - Komunikaty startera i zbiorcze narzędzia zajezdni. + Zwrotnice z mapy + Podświetlanie trasy + Konsola systemowa + Komunikaty startera i narzędzia zajezdni. Mniej pamięci karty, dłuższe wczytywanie. - Lepiej wyłączyć, gdy pamięci karty graficznej jest pod dostatkiem. - Na niektórych kartach graficznych może sprawiać problemy. - Pomija składy oznaczone w scenerii jako dekoracja. - Powiększa okna i przyciski interfejsu symulatora. + Zwalnia pamięć karty. Wyłącz, jeśli pamięci masz dużo. + Może powodować problemy na niektórych kartach. + Nie wczytuje składów oznaczonych w scenerii jako dekoracja. + Wielkość okien i przycisków w symulatorze. Wielkość tekstu w oknach symulatora. - 1 – tło pełne; mniejsze wartości prześwitują widok. - Bez zaznaczenia startuje z kursorem w kabinie. - Wyłączenie blokuje tryb kursora – mysz tylko obraca kamerą. - Puste: monitor główny. - Względem folderu gry, bez spacji w ścieżce. - Odległość rysowania scenerii; docelowy FPS może ją zmieniać. - Poniżej tej wartości symulator skraca zasięg rysowania, powyżej wydłuża. - Tekstury DDS czytane w tle: sceneria wczytuje się szybciej. Nie podnosi FPS. - Krotność zasięgu rysowania, poza którą tekstury pojazdów są usuwane z karty graficznej. - Wyłączenie ukrywa model kabiny – do testów. - Dłuższy czas – silniejsze rozmycie. - Przydatne przy kilku monitorach albo pulpicie z własnymi wyświetlaczami. - Ile dźwięków może grać naraz. - Pliki dźwiękowe dekodują osobne wątki – szybsze wczytywanie. - Bez sieci trakcyjnej pantografy się nie łamią, a elektrowozy zawsze mają zasilanie. - Mnożnik kołysania widoku z kabiny we wszystkich osiach; 0 – bez bujania. - Na jaką odległość przed i za pojazdem mapa podświetla tor. + 1 – tło pełne, mniej – prześwituje. + Wyłączone: po starcie kursor jest wolny. + Wyłączone: mysz tylko obraca kamerą. + Ścieżka względem folderu gry, bez spacji. + Jak daleko rysowana jest sceneria. + Symulator dopasowuje zasięg rysowania, żeby utrzymać ten FPS. 0 – wyłączone. + Szybsze wczytywanie scenerii. Nie zwiększa FPS. + Usuwa z karty tekstury dalekich pojazdów. 0 – wyłączone. + Wyłączone: bez modelu kabiny (do testów). + Dłużej – silniejsze rozmycie. + Dla kilku monitorów albo pulpitu z wyświetlaczami. + Ile dźwięków gra naraz. + Szybsze wczytywanie dźwięków. + Wyłączone: pantografy się nie łamią, elektrowozy zawsze mają prąd. + 0 – kamera nie buja. + Jak daleko przed i za pojazdem mapa podświetla tor. Domyślne Zmiany w pliku… Co zmieni zapis w eu07.ini @@ -900,8 +909,8 @@ Wysoka Własne Monitor: {0} Hz - Ekran {0}: do {1} Hz Ustaw {0} FPS + Z VSync nie będzie więcej klatek niż Hz monitora, więc limit równy lub wyższy nic nie zmienia. Najedź na zestaw, żeby zobaczyć wartości. RRRR-MM-DD Brak tłumaczenia Startera: zostaje angielski. Symulator dostanie ten język. @@ -934,12 +943,12 @@ zdarzenia scenerii zapamiętane kamery Mnożnik zasięgu - Skraca lub wydłuża zasięg rysowania scenerii. Docelowy FPS go nadpisuje. + Skraca albo wydłuża zasięg rysowania. Bardzo wysoka Ultra Wszystko na maksimum. Może być za ciężkie nawet dla mocnej karty. - Limit klatek okien ekranów - Działa tylko z ekranami w osobnych oknach; bez nich nic nie zmienia. + FPS okien ekranów + Tylko dla ekranów w osobnych oknach. Najdłuższe sceneriusz {0} pociąg {0} @@ -959,93 +968,13 @@ W magazynie: {0} Wybierz skład z pojazdami Poziom tylko tej części grafiki - Vulkan 1.4 - Działa tylko z Vulkanem. - Preset DLSS - Model, którym DLSS odtwarza obraz. Tryb DLSS wynika ze skali bufora: ok. 67% Jakość, 50% Wydajność, 33% Ultra wydajność. - Generowanie klatek - Dodatkowe klatki między rysowanymi. Tylko z DLSS lub DLAA. x3 i x4 tylko na kartach RTX 50. - NVIDIA Reflex - Mniejsze opóźnienie między sterowaniem a obrazem. - Odbicia ray tracing - Uzupełnia odbicia tam, gdzie SSR nic nie znajduje. Karta musi mieć ray query. - Zasięg ray tracingu - Karta graficzna (Vulkan) - Numer karty z listy w logu albo fragment nazwy, np. RTX. Puste: wybór automatyczny. - Odbicia w przestrzeni ekranu (SSR) - Odbicia tego, co widać na ekranie, na mokrych i gładkich powierzchniach. - Okluzja otoczenia - Przyciemnia zakamarki i styki powierzchni. GTAO jest dokładniejsze od SSAO. - Jakość okluzji - Okluzja w świetle otoczenia - Tylko z GTAO. Przyciemnia światło otoczenia i odbicia, a słońce i lampy zostają jasne. Wyłączone: mnoży gotowy obraz, taniej. - Oświetlenie klastrowe - Światła pojazdów i latarnie bez limitu liczby. Potrzebne dla lamp scenerii i lampy w kabinie. - Cienie lamp i reflektorów - Cienie rzucane przez lampę kabiny, latarnie i reflektory pojazdów. - Cienie kontaktowe - Drobne cienie w miejscach styku obiektów, których mapa cieni nie łapie. - Kaskady cieni dopasowane do sceny (SDSM) - Rozkłada rozdzielczość cieni słońca na to, co faktycznie widać. - Próbka kabiny - Światło odbite od ścian kabiny i odbicia wnętrza w szybach. - Odświeżanie próbki co N klatek - Kabina odbija siebie - W szybach widać wnętrze kabiny zamiast nieba tam, gdzie SSR nic nie znajduje. - Odbite światło lampy w kabinie - Ile światła lampy odbitego od ścian oświetla kabinę ponownie. Działa z próbką kabiny. - Jakość mgły - Chmury wolumetryczne - Cienie chmur na ziemi - Trawa - Zasięg trawy - Gęstość trawy - Opady (cząsteczki) - Liczba kropli deszczu i płatków śniegu przy największych opadach. - Poświata jasnych miejsc (bloom) - Automatyczna ekspozycja - Jasność obrazu dopasowuje się do sceny, np. przy wjeździe do tunelu. - Wyłączone - Niskie - Średnie - Wysokie - Ultra - Włączony - Włączony + boost - TAA - DLSS (skalowanie) - DLAA (natywna rozdzielczość) - Automatyczny - K: najlepsza jakość - J: mniej smużenia - M: pod tryb Wydajność - L: pod Ultra wydajność Efekty - Rozdzielczość i wygładzanie + Obraz Oświetlenie Postprocessing Dym - Wygładzanie krawędzi - MSAA wygładza krawędzie obiektów, TAA cały obraz kosztem lekkiego rozmycia. DLSS i DLAA tylko z Vulkanem na kartach NVIDIA RTX, inaczej symulator użyje TAA. - Mgła wolumetryczna - Mgła z promieniami słońca, cieniami chmur i światłem lamp. Wyłączona: prostsza mgła analityczna. - Jakość chmur rysowanych na niebie. - DLSS, generowanie klatek, Reflex i ray tracing tylko z Vulkanem. - Wymaga exe z Vulkanem i karty, która go obsługuje. Inaczej symulator włączy Pełny albo Stary. - automatycznie - K dla DLAA, Jakości i Zrównoważonego, M dla Wydajności, L dla Ultra wydajności. Sterownik może to zmienić przy aktualizacji. - Model transformer o najlepszej jakości obrazu, ale najdroższy w obliczeniach. Domyślny dla DLAA, Jakości i Zrównoważonego. - Podobny do K: trochę mniej smug za ruchomymi obiektami kosztem większego migotania. NVIDIA zaleca raczej K. - Model dobrany do trybu Wydajność (skala ok. 50%), w nim domyślny. Sam liczy ekspozycję obrazu. - Model dobrany do trybu Ultra wydajność (skala ok. 33%), w nim domyślny. Sam liczy ekspozycję obrazu. - Obok symulatora nie ma {0}: bez tej biblioteki nie użyje tej funkcji DLSS. - Na macOS DLSS nie jest dostępny. - Generowanie klatek działa tylko z DLSS albo DLAA. - Generowanie klatek włącza Reflex samo, niezależnie od tego wyboru. - Wymaga głębi całej sceny przed kolorem; bez SSR i cieni kontaktowych to dodatkowy przebieg (koszt CPU w OpenGL). - Przy pominiętym postprocessingu AO nie działa. - Bez oświetlenia klastrowego i lampy kabiny jako światła (gfx.lights.cab) próbka daje tylko odbicia. - TAA i DLSS działają w postprocessingu: gdy go pominiesz, krawędzie nie będą wygładzane. + Multisampling + Wygładza krawędzie. Wyższy poziom to gładszy obraz i mniej FPS. Plik eu07.ini Importuj… Importuj ustawienia z eu07.ini @@ -1058,19 +987,16 @@ {0} Wyeksportowano do {0} Pełny - Stary - Uproszczony - Eksperymentalny - Użyj renderera ANGLE Vulkan - Uruchamia renderer ANGLE na Vulkanie zamiast domyślnego backendu. Przydatne, gdy OpenGL sprawia problemy. - Renderowanie VBO - Trzyma geometrię w buforach karty graficznej. Wyłącz tylko przy problemach ze starszymi kartami. - Zasięg źródeł cieni w kabinie - Odległość, z jakiej źródła światła nadal rzucają cień w kabinie. Zero wyłącza cienie w kabinie. - Używaj OpenGL ES - OpenGL ES zamiast OpenGL. Nie działa z rendererem legacy. + Stary (niezalecany) + Uproszczony (niezalecany) + ANGLE (Vulkan) + Rysuje przez ANGLE na Vulkanie. Włącz, jeśli zwykły OpenGL sprawia problemy. + VBO + Wyłącz tylko, gdy starsza karta ma problemy z obrazem. + Cienie w kabinie + Do jakiej odległości światła rzucają cień w kabinie. 0 wyłącza cienie w kabinie. + OpenGL ES + OpenGL ES zamiast OpenGL. Nie działa ze starym rendererem. {0}, {1} GB {0}, pamięć wspólna - Nowości OpenGL 4.6 / Vulkan - Działa tylko z nowym exe. Starsze exe pomija te ustawienia. diff --git a/StarterNG/startercfg/lang/ru.xml b/StarterNG/startercfg/lang/ru.xml index 6e499d3..1a2aae3 100644 --- a/StarterNG/startercfg/lang/ru.xml +++ b/StarterNG/startercfg/lang/ru.xml @@ -61,6 +61,8 @@ Выберите сценерию Выберите состав Нет бригады / пассажира + Декоративный состав + Состав ИИ Состав без бригады В этом составе нет ни бригады, ни пассажира — управлять будет нечем. Всё равно запустить? Восстановить погоду @@ -355,8 +357,8 @@ Общие Язык + Неизвестное значение в eu07.ini: «{0}». Оно останется в файле, пока вы его не измените. В симуляторе нет перевода на этот язык, он запустится на английском. - Полный экран Приостанавливать симуляцию при неактивном окне Пауза при запуске Чувствительность курсора @@ -366,6 +368,7 @@ Связь Игнорировать ввод с геймпада + Рекомендуется и по умолчанию геймпад игнорируется. Включение его поддержки часто вызывает проблемы с управлением. Меняйте, только если действительно управляете геймпадом. Изменить? Обратная связь Выкл. @@ -407,8 +410,8 @@ Графика Движок отрисовки - Полный работает с любым exe. Старый, Упрощённый и Экспериментальный только со старыми, новый вместо них запустит Полный. - Внимание: экспериментальный рендерер может работать нестабильно, не показывать части сцены или не запускаться на некоторых видеокартах. Если симулятор не запускается или выглядит неправильно, вернитесь к рендереру «Полный». + Изменение «{0}» может помешать запуску симулятора или испортить изображение. Изменить? + Полный — рекомендуемый рендерер симулятора. Старый и Упрощённый рисуют классическим рендерером и не рекомендуются, если Полный работает, — они для видеокарт, с которыми у Полного проблемы. Видеокарта (Linux) Мощнее (дискретная) Как решит система @@ -418,16 +421,9 @@ Найдено: {0}. Карту выбирают переменные среды ({1}); стартер их не меняет. Одна карта: {0} – выбирать не из чего. Не удалось прочитать видеокарты из /sys/class/drm. - Работает только в версии симулятора для Windows. - Это читает только рендерер legacy, а выбран другой. - Работает только с целевой частотой кадров (targetfps). - Экспериментальный рендерер это не читает. - Это читает только полный рендерер, а выбран другой. - Пауза в фоне требует сетевого сервера (network.server). Разрешение {0} (монитор) - Не работает при автоматическом разрешении. Разрешение буфера Максимальное разрешение текстур Максимальное разрешение текстур кабины @@ -456,7 +452,14 @@ Меньше кадров: холоднее и тише компьютер. С V-Sync лимит выше частоты обновления ничего не даёт. Ограничение длины теней Укороченные - Автоматическое разрешение (полный экран без рамки) + Режим отображения + Полный экран + Полный экран без рамки + Окно + Полный экран без рамки берёт разрешение монитора и быстрее переключается на другие программы. + Монитор + На каком мониторе симулятор откроется в полноэкранном режиме. + Основной VSync Отображение дыма Множитель частиц дыма @@ -520,6 +523,12 @@ Громкость окружения Дополнительно + Расширенный режим + Расширенный режим… + Выключить расширенный режим + Выключение расширенного режима вернёт значения по умолчанию для всех настроек, доступных только в нём, и сохранит настройки этой страницы. Выключить? + Включить + Расширенный режим показывает все настройки симулятора и стартера, в том числе те, после изменения которых симулятор может не запуститься, работать нестабильно или показывать плохую картинку. Он также позволяет менять экипажи составов, составы ИИ и декорации, поэтому сценарий может работать не так, как задумал автор. Меняйте эти настройки, только если знаете, что они делают. Проблемы из-за них — не ошибки симулятора: прежде чем сообщить об ошибке, выключите расширенный режим и восстановите настройки по умолчанию. Прочитайте внимательно. Кнопка включения заработает через 20 секунд. Сжимать текстуры TGA Масштабировать блики (совместимость со старыми моделями) Ослабляет блеск моделей, сделанных для старых рендереров. @@ -569,6 +578,7 @@ Сбросить Настройки сохранены Восстановлены значения по умолчанию + Все настройки вернутся к значениям по умолчанию. Останутся: язык, выбранный симулятор, порт UART и клавиши управления. Изменения ещё нужно сохранить. Восстановлены сохранённые настройки развёрнуто свёрнуто @@ -796,6 +806,7 @@ include {1} без end Не удалось прочитать состав {0} Не удалось прочитать единицу {0} + Единица {0} отсутствует: нет файла dynamic/{1} - симулятор её пропустит, состав будет короче Вставить в выбранный состав сценерии Добавить к выбранному составу сценерии Отменить изменение состава @@ -810,7 +821,6 @@ Показывать журнал во время загрузки После запуска мышь вращает камеру Нажатие органов управления в кабине мышью - Монитор для полноэкранного режима Папка снимков экрана Базовая дальность прорисовки Целевая частота кадров @@ -849,8 +859,8 @@ Высокое Своё Монитор: {0} Гц - Экран {0}: до {1} Гц Задать {0} FPS + С VSync кадров не будет больше, чем Гц монитора, поэтому ограничение на этом уровне или выше ничего не меняет. Наведите на уровень, чтобы увидеть значения. ГГГГ-ММ-ДД Нет перевода стартера: останется английский. Симулятор получит этот язык. @@ -908,73 +918,12 @@ На складе: {0} Выберите состав с транспортом Уровень только для этой части графики - Vulkan 1.4 - Работает только с Vulkan. - Пресет DLSS - Генерация кадров - NVIDIA Reflex - Отражения с трассировкой лучей - Дальность трассировки лучей - Видеокарта (Vulkan) - Отражения в экранном пространстве (SSR) - Фоновое затенение - Качество затенения - Затенение в фоновом свете - Кластерное освещение - Тени ламп и прожекторов - Контактные тени - Каскады теней по сцене (SDSM) - Зонд кабины - Обновление зонда каждые N кадров - Кабина отражает себя - Отражённый свет лампы в кабине - Качество тумана - Объёмные облака - Тени облаков на земле - Трава - Дальность травы - Густота травы - Осадки (частицы) - Свечение ярких мест (bloom) - Автоматическая экспозиция - Выкл. - Низкое - Среднее - Высокое - Ультра - Вкл. - Вкл. + boost - TAA - DLSS (масштабирование) - DLAA (родное разрешение) - Автоматически - K: лучшее качество - J: меньше размытия - M: для режима Производительность - L: для Ультра производительность Эффекты Разрешение и сглаживание Освещение Постобработка Дым Сглаживание - Объёмный туман - DLSS, генерация кадров, Reflex и трассировка лучей только с Vulkan. - Нужен exe с Vulkan и карта с его поддержкой. Иначе симулятор запустит Полный или Старый. - автоматически - K для DLAA, «Качества» и «Баланса», M для «Производительности», L для «Ультрапроизводительности». Драйвер может изменить это при обновлении. - Модель transformer с лучшим качеством изображения, но самая затратная. По умолчанию для DLAA, «Качества» и «Баланса». - Похожа на K: чуть меньше шлейфов за движущимися объектами ценой большего мерцания. NVIDIA скорее рекомендует K. - Модель для режима «Производительность» (масштаб около 50%), в нём по умолчанию. Сама вычисляет экспозицию. - Модель для режима «Ультрапроизводительность» (масштаб около 33%), в нём по умолчанию. Сама вычисляет экспозицию. - Рядом с симулятором нет {0}: без этой библиотеки симулятор не использует эту функцию DLSS. - На macOS DLSS недоступен. - Генерация кадров работает только с DLSS или DLAA. - Генерация кадров сама включает Reflex, что бы здесь ни было выбрано. - Нужна глубина всей сцены до цвета; без SSR и контактных теней это лишний проход (нагрузка на ЦП в OpenGL). - Если постобработка пропущена, AO не работает. - Без кластерного освещения и лампы кабины как источника света (gfx.lights.cab) зонд даёт только отражения. - TAA и DLSS работают в постобработке: если её пропустить, края не сгладятся. Файл eu07.ini Импорт… Импорт настроек из eu07.ini @@ -987,9 +936,8 @@ {0} Экспортировано в {0} Полный - Старый - Упрощённый - Экспериментальный + Старый (не рекомендуется, если Полный работает) + Упрощённый (не рекомендуется, если Полный работает) Использовать рендерер ANGLE Vulkan Отрисовка VBO Дальность источников теней в кабине @@ -997,6 +945,4 @@ OpenGL ES вместо OpenGL. Не работает с рендерером legacy. {0}, {1} ГБ {0}, общая память - Новое в OpenGL 4.6 / Vulkan - Работает только с новым exe. Старый exe пропускает эти настройки.