diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 46b659b..8e4975d 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -71,6 +71,8 @@ jobs: # sonar.qualitygate.wait=true blocks the end step until the server has # processed the report, so the job's result is the quality gate's. + # tools/ holds the developers' helper scripts, outside the app and its tests: + # analysed like the rest, but not counted for coverage. - name: Begin analysis env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} @@ -84,6 +86,7 @@ jobs: /d:sonar.scm.revision="${{ github.event.pull_request.head.sha || github.sha }}" /d:sonar.cs.opencover.reportsPaths="TestResults/**/coverage.opencover.xml" /d:sonar.cs.vstest.reportsPaths="TestResults/*.trx" + /d:sonar.coverage.exclusions="tools/**" /d:sonar.qualitygate.wait=true # A full, non-incremental build: the analyzers only see what is compiled. diff --git a/README.md b/README.md index 6f53f0a..05a0d7f 100644 --- a/README.md +++ b/README.md @@ -46,3 +46,17 @@ the packaged artifacts — tagged `latest` for `main` and `staging` for `staging ```sh dotnet build StarterNG/StarterNG.csproj ``` + +## Translations + +The texts are in `StarterNG/startercfg/lang/.xml`; `en.xml` is the reference. +The tests require every language to have every key of `en.xml` except the optional +ones (ending in `Desc`, starting with `Cmd.`), which fall back to English. After a +change to `en.xml`, or before merging a translation made from an older one: + +```sh +python tools/sync_lang.py --check # lists what is missing or no longer used +python tools/sync_lang.py # adds missing keys in English, removes the unused ones +``` + +Added keys are marked `` for the translator. diff --git a/StarterNG.Tests/GraphicsCardsTests.cs b/StarterNG.Tests/GraphicsCardsTests.cs index f793054..6ba2fce 100644 --- a/StarterNG.Tests/GraphicsCardsTests.cs +++ b/StarterNG.Tests/GraphicsCardsTests.cs @@ -99,6 +99,83 @@ public class GraphicsCardsTests Assert.Equal(new[] { "AMD Radeon RX 6700 XT", "AMD Radeon 780M" }, cards.Select(card => card.Name)); } + private static GraphicsCards WindowsReader(IReadOnlyList? dxgi, params GraphicsCard[] registry) => + new(new InMemoryFileSystem(), new FakeEnvironment().AsWindows(), new LinuxGpus(new InMemoryFileSystem(), new FakeEnvironment()), + () => Array.Empty(), () => dxgi, () => registry); + + private static DxgiAdapter Adapter(string name, uint vendor, long memory, uint flags = 0) => + new(name, vendor, (ulong)memory, flags); + + [Fact] + public void Windows_takes_the_cards_dxgi_lists_and_the_discrete_one_first() + { + var reader = WindowsReader( + new[] { Adapter("AMD Radeon(TM) Graphics", 0x1002, GiB / 2), Adapter("NVIDIA GeForce RTX 3060", 0x10DE, 12 * GiB) }, + new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2)); + + var cards = reader.List(); + + Assert.Equal(new[] { "NVIDIA GeForce RTX 3060", "AMD Radeon(TM) Graphics" }, cards.Select(card => card.Name)); + Assert.Equal(12, cards[0].MemoryGb); + } + + [Fact] + public void Software_adapters_are_no_cards() + { + var cards = DxgiAdapters.Cards(new[] + { + Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2), + Adapter("Microsoft Remote Display Adapter", 0x1414, 0), + Adapter("Some software rasterizer", 0x1234, 0, flags: 2), + Adapter("NVIDIA GeForce RTX 5060 Laptop GPU", 0x10DE, 8546942976) + }); + + Assert.Equal("NVIDIA GeForce RTX 5060 Laptop GPU", Assert.Single(cards).Name); + } + + [Fact] + public void A_card_dxgi_lists_twice_is_shown_once() + { + var cards = DxgiAdapters.Cards(new[] + { + Adapter("AMD Radeon 780M Graphics", 0x1002, GiB / 2), + Adapter("AMD Radeon 780M Graphics ", 0x1002, GiB / 2) + }); + + Assert.Equal("AMD Radeon 780M Graphics", Assert.Single(cards).Name); + } + + [Fact] + public void The_registry_answers_when_dxgi_cannot_be_asked() + { + var card = Assert.Single(WindowsReader(null, new GraphicsCard("NVIDIA GeForce RTX 3060", 12 * GiB)).List()); + + Assert.Equal("NVIDIA GeForce RTX 3060", card.Name); + } + + [Fact] + public void The_registry_answers_when_dxgi_lists_only_software() + { + var reader = WindowsReader(new[] { Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2) }, + new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2)); + + Assert.Equal("AMD Radeon(TM) Graphics", Assert.Single(reader.List()).Name); + } + + [Fact] + public void Dxgi_answers_on_this_machine() + { + if (!OperatingSystem.IsWindows()) + return; + + // Every Windows lists at least the Basic Render Driver, so an answer means the calls work. + var adapters = DxgiAdapters.Read(); + + Assert.NotNull(adapters); + Assert.NotEmpty(adapters); + Assert.All(adapters, adapter => Assert.False(string.IsNullOrWhiteSpace(adapter.Description))); + } + [Fact] public void There_are_no_cards_on_a_mac() { diff --git a/StarterNG/Infrastructure/DxgiAdapters.cs b/StarterNG/Infrastructure/DxgiAdapters.cs new file mode 100644 index 0000000..978c636 --- /dev/null +++ b/StarterNG/Infrastructure/DxgiAdapters.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using StarterNG.Domain.Settings; + +namespace StarterNG.Infrastructure; + +/// An adapter as DXGI describes it (DXGI_ADAPTER_DESC1). +/// The card's own memory; for a card in a processor, the share the firmware sets aside. +public sealed record DxgiAdapter(string Description, uint VendorId, ulong DedicatedVideoMemory, uint Flags); + +/// +/// The graphics cards of a Windows machine as DXGI lists them: the adapters Windows +/// draws with, whose drivers the simulator's OpenGL runs on too. The registry's list of +/// video devices is what each driver chose to write there, and some leave their card out of it. +/// +public static unsafe class DxgiAdapters +{ + private const uint MicrosoftVendor = 0x1414; + private const uint SoftwareFlag = 2; // DXGI_ADAPTER_FLAG_SOFTWARE + private const int NotFound = unchecked((int)0x887A0002); // DXGI_ERROR_NOT_FOUND + private const int MostAdapters = 64; + + private static readonly Guid FactoryInterface = new("770aae78-f26f-4dba-a829-253c83d1b387"); // IDXGIFactory1 + + /// The cards among the adapters: not the Microsoft Basic Render Driver or any other software one. + public static IReadOnlyList Cards(IEnumerable adapters) => + adapters + .Where(adapter => (adapter.Flags & SoftwareFlag) == 0 && adapter.VendorId != MicrosoftVendor) + .Select(adapter => new GraphicsCard(adapter.Description.Trim(), (long)adapter.DedicatedVideoMemory)) + .Where(card => card.Name.Length > 0) + // Two of the same card tell no more than one, as in the registry's list. + .DistinctBy(card => card.Name) + .ToList(); + + /// Every adapter DXGI lists, software ones too; null when DXGI could not be asked. + [SupportedOSPlatform("windows")] + public static IReadOnlyList? Read() + { + IntPtr factory; + try + { + Guid iid = FactoryInterface; + if (CreateDXGIFactory1(&iid, &factory) < 0 || factory == IntPtr.Zero) + return null; + } + catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException) + { + return null; + } + + try + { + // IDXGIFactory1::EnumAdapters1, after IUnknown's 3, IDXGIObject's 4 and IDXGIFactory's 5. + var enumAdapters1 = (delegate* unmanaged[Stdcall])Method(factory, 12); + var adapters = new List(); + for (uint i = 0; i < MostAdapters; i++) + { + IntPtr adapter; + int result = enumAdapters1(factory, i, &adapter); + if (result == NotFound) + break; + if (result < 0 || adapter == IntPtr.Zero) + return null; + + try + { + // IDXGIAdapter1::GetDesc1, after IUnknown's 3, IDXGIObject's 4 and IDXGIAdapter's 3. + var getDesc1 = (delegate* unmanaged[Stdcall])Method(adapter, 10); + AdapterDesc1 desc; + if (getDesc1(adapter, &desc) >= 0) + adapters.Add(new DxgiAdapter(new string(desc.Description), desc.VendorId, + desc.DedicatedVideoMemory, desc.Flags)); + } + finally + { + Release(adapter); + } + } + + return adapters; + } + finally + { + Release(factory); + } + } + + private static void* Method(IntPtr instance, int slot) => (*(void***)instance)[slot]; + + private static void Release(IntPtr instance) => + ((delegate* unmanaged[Stdcall])Method(instance, 2))(instance); + + [DllImport("dxgi.dll", ExactSpelling = true)] + private static extern int CreateDXGIFactory1(Guid* riid, IntPtr* factory); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct AdapterDesc1 + { + public fixed char Description[128]; + public uint VendorId; + public uint DeviceId; + public uint SubSysId; + public uint Revision; + public nuint DedicatedVideoMemory; + public nuint DedicatedSystemMemory; + public nuint SharedSystemMemory; + public uint AdapterLuidLow; + public int AdapterLuidHigh; + public uint Flags; + } +} diff --git a/StarterNG/Infrastructure/GraphicsCards.cs b/StarterNG/Infrastructure/GraphicsCards.cs index a357586..47e0390 100644 --- a/StarterNG/Infrastructure/GraphicsCards.cs +++ b/StarterNG/Infrastructure/GraphicsCards.cs @@ -30,14 +30,20 @@ public sealed class GraphicsCards private readonly IEnvironment _environment; private readonly LinuxGpus _gpus; private readonly Func> _nvidiaSmi; + private readonly Func?> _dxgi; + private readonly Func> _registry; public GraphicsCards(IFileSystem files, IEnvironment environment, LinuxGpus gpus, - Func>? nvidiaSmi = null) + Func>? nvidiaSmi = null, + Func?>? dxgi = null, + Func>? registry = null) { _files = files; _environment = environment; _gpus = gpus; _nvidiaSmi = nvidiaSmi ?? AskNvidiaSmi; + _dxgi = dxgi ?? AskDxgi; + _registry = registry ?? ReadRegistry; } /// Takes a while on Linux, where the PCI list is read: not for the UI thread. @@ -46,15 +52,34 @@ public sealed class GraphicsCards IEnumerable cards = Array.Empty(); if (_environment.IsLinux) cards = FromLinux(); - else if (_environment.IsWindows && OperatingSystem.IsWindows()) - cards = FromRegistry(); + else if (_environment.IsWindows) + cards = FromWindows(); // A program goes to the discrete card, on Windows by its own request. return cards.OrderBy(card => card.SharedMemory).ThenByDescending(card => card.MemoryBytes).ToList(); } + /// + /// DXGI's list, the adapters the simulator's OpenGL runs on. The registry's list of + /// video devices only when DXGI cannot be asked or lists no card: there each driver + /// writes what it chooses, and some leave their card out (an RTX 3060 beside a Ryzen's + /// Radeon was missing from it). + /// + private IReadOnlyList FromWindows() + { + var adapters = _dxgi(); + var cards = adapters is null ? Array.Empty() : DxgiAdapters.Cards(adapters); + return cards.Count > 0 ? cards : _registry(); + } + + private static IReadOnlyList? AskDxgi() => + OperatingSystem.IsWindows() ? DxgiAdapters.Read() : null; + + private static IReadOnlyList ReadRegistry() => + OperatingSystem.IsWindows() ? FromRegistry() : Array.Empty(); + [SupportedOSPlatform("windows")] - private static IEnumerable FromRegistry() + private static IReadOnlyList FromRegistry() { try { diff --git a/StarterNG/StarterNG.csproj b/StarterNG/StarterNG.csproj index aeb91b0..34f3ed9 100644 --- a/StarterNG/StarterNG.csproj +++ b/StarterNG/StarterNG.csproj @@ -7,6 +7,8 @@ net10.0 enable true + + true app.manifest Assets\starter.ico true diff --git a/StarterNG/startercfg/lang/zh.xml b/StarterNG/startercfg/lang/zh.xml index 2548b0c..70f7965 100644 --- a/StarterNG/startercfg/lang/zh.xml +++ b/StarterNG/startercfg/lang/zh.xml @@ -61,6 +61,8 @@ 请选择线路 请选择编组 无乘务 / 乘客 + Decoration consist + AI consist 编组没有乘务 该编组既没有乘务也没有乘客——将没有可驾驶的对象。仍要开始吗? 恢复天气 @@ -69,6 +71,10 @@ 加入收藏 移出收藏 打开文件夹 + Delete SBT + Delete {0} ({1} MB)? The simulator makes it again from the scenery files on its next load, which takes longer. + {0} stays: nothing is there to make it again, {1} is missing. Without it the scenery would lose its terrain. + Could not delete {0}. The simulator may be using it, or the folder is read-only. 可选元素 打开涂装文件夹 复制名称 @@ -98,6 +104,7 @@ 小时未知,时间从模拟开始时计算 无法读取纸带 {0}。 {0} · 记录 {1}(运行 {2},停车 {3})· 距离 {4:0.00} km · Vmax {5:0} km/h · 运行平均 {6:0} km/h · 含停车平均 {7:0} km/h + not recorded {0} {0} · {1:0.0} km · {2:0} km/h · 制动缸 {3:0.0} bar · 电流 {4} 制动缸 列车管 @@ -355,8 +362,8 @@ 语言 同时也是模拟器的语言。选择后立即保存。 + Unknown value in eu07.ini: “{0}”. It stays in the file until you change this. 模拟器没有该语言的翻译,将以英文运行。 - 全屏 窗口非活动时暂停模拟 启动时暂停 光标灵敏度: @@ -366,6 +373,7 @@ 外部设备 忽略手柄输入 + 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? 即使连接了手柄也禁用其输入。 反馈 @@ -413,8 +421,8 @@ 图形 图形 API + 更改“{0}”可能导致模拟器无法启动或画面异常。要更改吗? 完整引擎适用于所有 exe。旧版、简化版和实验版仅适用于旧版 exe;新版 exe 会改用完整引擎启动。 - 注意:实验性渲染器可能不稳定、缺少部分场景,或在某些显卡上无法启动。如果模拟器无法启动或画面异常,请回到「完整」渲染器。 显卡(Linux) 更快的(独立显卡) 由系统决定 @@ -424,16 +432,9 @@ 找到:{0}。由环境变量({1})选择显卡;启动器不会改动它们。 只有一块显卡:{0}——无从选择。 无法从 /sys/class/drm 读取显卡信息。 - 仅模拟器的 Windows 版本使用此项。 - 仅旧版渲染器读取此项,而当前选择了其他渲染器。 - 仅在设置了目标帧率(targetfps)时生效。 - 实验性渲染器不读取此项。 - 仅完整渲染器读取此项,而当前选择了其他渲染器。 - 后台暂停需要网络服务器(network.server)。 分辨率 {0}(显示器) - 使用自动分辨率时无效。 渲染比例 相对于窗口分辨率缩放内部渲染缓冲。 最大纹理分辨率 @@ -465,7 +466,12 @@ 阴影长度限制 缩短低角度太阳投出的长阴影。数值越大,截断越早。 已缩短 - 自动分辨率(无边框全屏) + Display mode + Full screen + Borderless full screen + Window + Monitor + Primary 垂直同步 将帧率与显示器刷新率同步。 烟雾显示 @@ -516,6 +522,8 @@ 禁用后可保护受电弓,避免因接触网几何缺陷而损坏。 仅在接触网下供电 禁用时,升起的受电弓即使未接触导线也能为车辆供电。 + Black box and tapes + Tapes of all trains 保存物理参数记录 将详细的行车记录写入 physicslog/ 文件夹。 保存模拟日志 @@ -541,6 +549,10 @@ 环境音量 高级 + Advanced mode + Advanced mode… + Turn off advanced mode + Turn it on 压缩 TGA 纹理 缩放高光(旧模型兼容) 减弱为旧渲染器制作的模型的光泽。 @@ -589,6 +601,48 @@ 保存 重置 设置已保存 + 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 + Consist sources + Vehicle information + Vehicle settings + Scenario details + Section level + {0} found + Increase + Decrease + Minimize + Maximize + Restore + Close + Line up + Line down + Page up + Page down + Column left + Column right + Page left + Page right + Position + Left and Right arrows step along the tape, Ctrl with them steps ten times further, Home and End go to its ends, Enter takes the black box to that moment. + Consist empty + Added {0} at position {1} of {2} + Removed {0}, {1} vehicles left + {0} reversed + {0} turned back + {0} vehicles turned + {0} moved to position {1} of {2} + Order changed + {0} replaced with {1} + {0} vehicles changed, {1} in the consist + Undone. {0} + Redone. {0} + Scenery picture + Panel divider + Settings categories 无法保存设置 未保存的更改 @@ -620,6 +674,8 @@ 处理器不支持 AVX2 该处理器不支持 AVX2,而官方模拟器需要它:将无法启动。 你可以在没有 AVX2 的情况下构建模拟器(CMake -DENABLE_AVX2=OFF)。说明: {0} 打开说明 + This processor has no AVX2 and the chosen simulator {0} needs it: it will not start. The game folder has a build without AVX2: {1}. The automatic choice takes that one. + Choose automatically 不再显示 设置载入自: @@ -653,6 +709,9 @@ 追加仓库编组 从文件添加编组… 不保存设置直接开始 + The settings have unsaved changes. Save them before starting the simulator? + Save and start + Discard changes and start 更多启动方式 不加载车辆直接开始 线路编辑器 @@ -769,10 +828,10 @@ 车辆 {0} 位于 trainset 之外:是否缺少头部? {0}:「{1}」不是数字 找不到文件 {1}(include) - 文件 {1} 在磁盘上的名称为 {0}:Linux 版 eu07 将无法加载 include {1} 没有 end 无法读取 trainset {0} 无法读取车辆 {0} + Vehicle {0} missing: no file dynamic/{1} - the simulator leaves it out, the consist runs short 放入所选线路编组 追加到所选线路编组 撤销对编组的修改 @@ -787,7 +846,6 @@ 加载时显示日志 启动时鼠标转动镜头 用鼠标点击驾驶室控件 - 全屏显示器 截图文件夹 基础绘制距离 目标帧率 @@ -819,7 +877,6 @@ 1 为不透明;数值越小,视野越能透出。 不勾选时,启动后驾驶室内出现指针。 关闭后无法使用指针模式,鼠标只能转动镜头。 - 留空:主显示器。 相对于游戏文件夹,路径中不能有空格。 线路绘制的距离;目标帧率可能会改变它。 低于此值时模拟器缩短绘制距离,高于此值时加长。 @@ -1025,9 +1082,9 @@ 高 自定义 屏幕:{0} Hz - 屏幕 {0}:最高 {1} Hz 设为 {0} FPS 预设会一次设置下面的所有项目,之后可以单独调整每一项。 + 开启垂直同步时,帧数不会超过显示器的刷新率,因此等于或高于刷新率的限制不起作用。 YYYY-MM-DD 启动器没有该语言的翻译:启动器保持英文,模拟器会使用该语言。 没有配置文件 @@ -1083,66 +1140,10 @@ 请选择含有车辆的编组 仅针对该图形部分的级别 Vulkan(推荐) - 仅在 Vulkan 下有效。 - DLSS 预设 - DLSS 重建图像所用的模型。DLSS 模式跟随缓冲缩放:约 67% 为质量,50% 为性能,33% 为超级性能。 - 帧生成 - 在已绘制的帧之间插入额外帧。仅配合 DLSS 或 DLAA。x3 和 x4 需要 RTX 50 显卡。 - NVIDIA Reflex - 减少操作与画面之间的延迟。 光线追踪(反射) - 在 SSR 找不到信息的地方补全反射。显卡需支持 ray query。 - 光线追踪范围 - 显卡(Vulkan) - 日志列表中显卡的编号,或显卡名称的一部分(例如 RTX)。留空:自动选择。 - 屏幕空间反射(SSR) - 在潮湿光滑的表面上反射屏幕中可见的内容。 - 环境光遮蔽 - 压暗角落和表面相交处。GTAO 比 SSAO 更精确。 - 遮蔽质量 - 环境光中的遮蔽 - 仅 GTAO。压暗环境光和反射,阳光和灯具保持明亮。关闭:对最终画面整体相乘,开销更低。 - 簇式光照 - 车辆灯光和路灯数量不受限制。场景灯具和驾驶室灯需要此项。 - 灯具与前照灯阴影 - 由驾驶室灯、路灯和车辆前照灯投射的阴影。 - 接触阴影 - 阴影贴图遗漏的、物体接触处的小阴影。 - 贴合场景的阴影级联(SDSM) - 按实际可见的范围分配太阳阴影分辨率。 - 驾驶室探针 - 驾驶室墙面反射的光,以及窗户中映出的内饰。 - 每 N 帧刷新一次探针 - 驾驶室映出自身 - SSR 无信息时,窗户显示驾驶室内饰而不是天空。 - 驾驶室灯光反弹 - 灯光经墙面反射后再次照亮驾驶室的比例。需配合驾驶室探针使用。 - 雾质量 - 体积云 - 地面云影 - 草 - 草地范围 - 草地密度 - 降水(粒子) - 最强降水时雨滴和雪花的数量。 - 亮部辉光(bloom) - 自动曝光 - 画面亮度随场景自动调整,例如驶入隧道时。 - 关闭 - 低 - 中 - 高 - 极致 - 开启 - 开启 + 加速 - TAA + 光线追踪反射:更精确,但开销很大。仅限 Vulkan 及支持光线追踪的显卡(NVIDIA RTX、AMD RX 6000 及更新)。级别即光线的距离;画质预设不会开启它。 DLSS (NVIDIA RTX, Vulkan) DLAA (NVIDIA RTX, Vulkan) - 自动 - K:最佳质量 - J:拖影更少 - M:用于性能模式 - L:用于超级性能 效果 分辨率与抗锯齿 光照 @@ -1150,25 +1151,6 @@ 烟雾与降水 抗锯齿 MSAA 平滑物体边缘,TAA 平滑整个画面但略有模糊。DLSS 和 DLAA 需要 Vulkan 和 NVIDIA RTX 显卡,否则模拟器使用 TAA。 - 体积雾 - 带阳光光束、云影和灯光照明的雾。关闭:使用更简单的解析雾。 - 天空中绘制的云的质量。 - DLSS、帧生成、Reflex 和光线追踪需要 Vulkan。 - 需要带 Vulkan 的 exe 以及支持的显卡。否则模拟器会以完整或旧版引擎启动。 - 自动 - DLAA、质量与均衡使用 K,性能使用 M,超级性能使用 L。驱动可能通过更新更改此设置。 - 画质最佳的变换器模型,但计算开销最大。是 DLAA、质量与均衡的默认值。 - 与 K 相似:运动物体后方的拖影略少,但闪烁更多。NVIDIA 建议改用 K。 - 为性能模式(约 50% 缩放)调校的模型,是该模式的默认值。会自行计算画面曝光。 - 为超级性能模式(约 33% 缩放)调校的模型,是该模式的默认值。会自行计算画面曝光。 - {0} 不在模拟器旁边:缺少它模拟器无法使用该 DLSS 功能。 - macOS 上无法使用 DLSS。 - 帧生成只能配合 DLSS 或 DLAA 使用。 - 帧生成会自动开启 Reflex,无论此处如何选择。 - 需要先取得整个场景的深度再着色;在未开启 SSR 和接触阴影时会多一遍渲染(OpenGL 下消耗 CPU)。 - 跳过后续处理时 AO 不起作用。 - 没有簇式光照和作为光源的驾驶室灯(gfx.lights.cab)时,探针只提供反射。 - TAA 和 DLSS 在后处理中运行:跳过后处理则边缘不会被平滑。 eu07.ini 文件 导入… 从 eu07.ini 导入设置 @@ -1180,11 +1162,8 @@ 无法写入文件: {0} 已导出到 {0} - 实验性 {0},{1} GB {0},共享内存 - OpenGL 4.6 / Vulkan 新增 - 这些仅在新版 exe 中有效。旧版 exe 会跳过它们。 开发者 供开发者和测试人员使用的设置。玩家在此处的所有选项都使用启动器自带的值,使模拟器尽可能快;关闭高级模式会恢复这些值。 diff --git a/tools/sync_lang.py b/tools/sync_lang.py new file mode 100644 index 0000000..596719e --- /dev/null +++ b/tools/sync_lang.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Brings the language files of the starter in line with en.xml. + +For every language file in StarterNG/startercfg/lang (or the codes given): + - a key en.xml has and the language lacks is added with the English text, right after the + key it follows in en.xml, and marked ; + - a key en.xml no longer has is removed. +Keys the starter falls back to English for by itself (ending in "Desc", starting with "Cmd.") +are only added with --all. Everything else in the file - comments, order, line endings - stays +as it is. + + python tools/sync_lang.py # every language + python tools/sync_lang.py zh cz # only these + python tools/sync_lang.py --check # only report; exit code 1 when a file is out of line +""" + +import argparse +import re +import sys +from pathlib import Path + +LANG_DIR = Path(__file__).resolve().parent.parent / "StarterNG" / "startercfg" / "lang" +STRING = re.compile(r'.*?', re.DOTALL) +LANGUAGE_TAG = re.compile(r"]*>") +UNTRANSLATED = "" + + +def is_optional(key): + return key.endswith("Desc") or key.startswith("Cmd.") + + +def read(path): + raw = path.read_bytes() + bom = raw.startswith(b"\xef\xbb\xbf") + text = raw[3 if bom else 0:].decode("utf-8") + newline = "\r\n" if "\r\n" in text else "\n" + return text, bom, newline + + +def write(path, text, bom): + path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8")) + + +def strings(text): + """key -> match, in the order of the file; a key given twice keeps its first.""" + found = {} + for match in STRING.finditer(text): + found.setdefault(match.group("key"), match) + return found + + +def line_start(text, pos): + return text.rfind("\n", 0, pos) + 1 + + +def line_end(text, pos): + """Just past the newline ending the line that pos is on.""" + end = text.find("\n", pos) + return len(text) if end < 0 else end + 1 + + +def removal_span(text, match): + """The element with its whole lines when nothing but blanks and a comment share them.""" + start, end = match.span() + first = line_start(text, start) + last = line_end(text, end) + before = text[first:start] + after = text[end:last].strip() + if before.strip() == "" and (after == "" or (after.startswith(""))): + return first, last + return start, end + + +def english_line(en_text, match, newline): + indent = en_text[line_start(en_text, match.start()):match.start()] + if indent.strip(): + indent = " " + element = match.group(0).replace("\r\n", "\n").replace("\n", newline) + return f"{indent}{element} {UNTRANSLATED}{newline}" + + +def insert_position(text, own, en_keys, key, after_tag): + """Just after the nearest key before this one in en.xml that the file has and keeps.""" + for previous in reversed(en_keys[:en_keys.index(key)]): + if previous in own: + return line_end(text, own[previous].end()) + return after_tag + + +def apply_edits(text, edits): + """edits: (start, end, replacement) on the original text. + + Applied from the end so the offsets stay valid. Where a removal starts at the place of an + insert, the removal goes first, or it would take away the inserted line instead of its own. + Inserts at one place keep the order of en.xml. + """ + def order(edit): + index, (start, end, _) = edit + return start, 1 if end > start else 0, index + + for _, (start, end, replacement) in sorted(enumerate(edits), key=order, reverse=True): + text = text[:start] + replacement + text[end:] + return text + + +def synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings): + edits = [(*removal_span(text, own[key]), "") for key in obsolete] + + tag = LANGUAGE_TAG.search(text) + if tag is None: + sys.exit(f"{path.name}: no element") + after_tag = line_end(text, tag.end()) + + en_keys = list(en_strings) + for key in missing: + anchor = insert_position(text, own, en_keys, key, after_tag) + edits.append((anchor, anchor, english_line(en_text, en_strings[key], newline))) + return apply_edits(text, edits) + + +def report(name, missing, obsolete, detailed): + print(f"{name}: {len(missing)} to add in English, {len(obsolete)} no longer in en.xml") + if detailed: + for key in missing: + print(f" missing {key}") + for key in obsolete: + print(f" obsolete {key}") + + +def sync(path, en_text, en_strings, add_optional, check): + """True when the file was out of line with en.xml (and, without check, is now brought in line).""" + text, bom, newline = read(path) + own = strings(text) + + obsolete = [key for key in own if key not in en_strings] + missing = [key for key in en_strings + if key not in own and (add_optional or not is_optional(key))] + if not obsolete and not missing: + print(f"{path.name}: in line with en.xml") + return False + + report(path.name, missing, obsolete, check) + if not check: + write(path, synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings), bom) + return True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("codes", nargs="*", help="language codes, e.g. zh cz; every language when none") + parser.add_argument("--all", action="store_true", help="add the optional keys (*Desc, Cmd.*) too") + parser.add_argument("--check", action="store_true", help="only report, change nothing") + args = parser.parse_args() + + en_text, _, _ = read(LANG_DIR / "en.xml") + en_strings = strings(en_text) + + if args.codes: + paths = [LANG_DIR / f"{code}.xml" for code in args.codes] + for path in paths: + if not path.is_file(): + sys.exit(f"no language file {path}") + else: + paths = sorted(p for p in LANG_DIR.glob("*.xml") if p.name != "en.xml") + + out_of_line = False + for path in paths: + out_of_line |= sync(path, en_text, en_strings, args.all, args.check) + return 1 if args.check and out_of_line else 0 + + +if __name__ == "__main__": + sys.exit(main())