From 812fb2d740208bf27256a597fc17a7b30f2ef23d Mon Sep 17 00:00:00 2001 From: dazacode Date: Sun, 29 Nov 2026 02:10:12 -0800 Subject: [PATCH 1/3] Support VIctory-NVIDIA v2026.11.29.01: mods, its own controls, memory VIctory-NVIDIA v2026.11.29.01 loads every DLL in %LOCALAPPDATA%\victory\mods at each start, reads generic USB pads and has its own mouse and keyboard controls, and sizes its pools for small PCs itself. - Mods: Settings, Mods & controls (Windows) lists the mods folder, adds a DLL (never overwriting one), turns a mod off (renamed to .dll.off, which the game skips) or on, removes one, and opens the folder. Actions name the file on disk, so a mod there both on and off is two rows, each acting on its own file. - The keyboard-as-controller hook is removed: with the game's own mouse and keyboard it would send keys twice. The section shows where the game's bindings.ini is. Settings files with the old fields still load. - Memory saver on a `victory play` start: also the switches this build reads (two pipeline workers; Very light: a smaller VRAM reserve for later render targets), from its docs/windows-memory.md. A player's own value wins. - Fix and verify tells Windows' commit limit (memory guard plus driver refusals with 0x8007000E, or an allocation with nothing left to commit) from a full card, and says how to let Windows manage the page file. New advice: two pipeline workers for VIctory-NVIDIA on 16 GB of RAM, not offered when a `victory play` start already sends it. - Agent tool: `status` looked for a VIctory-NVIDIA build under the diag profile; the launcher builds release. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + scripts/vilauncher-agent.mjs | 11 +- src-tauri/known-problems/known-problems.json | 21 + src-tauri/locales/es/launcher.json | 15 +- src-tauri/locales/fr/launcher.json | 15 +- src-tauri/locales/ru/launcher.json | 15 +- src-tauri/locales/zh-CN/launcher.json | 15 +- src-tauri/locales/zh-TW/launcher.json | 15 +- src-tauri/src/controller_keys.rs | 444 ------------------- src-tauri/src/diagnose.rs | 50 ++- src-tauri/src/launcher.rs | 127 +++++- src-tauri/src/launcher/actions.rs | 78 ++-- src-tauri/src/launcher/view.rs | 44 +- src-tauri/src/main.rs | 2 +- src-tauri/src/mods.rs | 286 ++++++++++++ src/dev/mock.ts | 74 ++-- src/features/settings/controller-keys.tsx | 109 ----- src/features/settings/mods.tsx | 94 ++++ src/features/settings/settings-view.tsx | 5 +- src/i18n/messages/en/settings.ts | 42 +- src/i18n/messages/es/settings.ts | 42 +- src/i18n/messages/fr/settings.ts | 42 +- src/i18n/messages/ru/settings.ts | 42 +- src/i18n/messages/zh-CN/settings.ts | 42 +- src/i18n/messages/zh-TW/settings.ts | 42 +- src/lib/types.ts | 36 +- 26 files changed, 907 insertions(+), 814 deletions(-) delete mode 100644 src-tauri/src/controller_keys.rs create mode 100644 src-tauri/src/mods.rs delete mode 100644 src/features/settings/controller-keys.tsx create mode 100644 src/features/settings/mods.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 6caa822..251d752 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ The release notes for each tag are taken from the section for that version. +## Unreleased + +### New +- **Mods for VIctory-NVIDIA** (*Settings → Mods & controls*, Windows): VIctory-NVIDIA v2026.11.29.01 loads every DLL in `%LOCALAPPDATA%\victory\mods` at each start (its PR #1892). The launcher lists them, adds a DLL, turns one off (renamed to `.dll.off`, which the game skips) or on again, removes one, and opens the folder. It never downloads or runs a mod itself, and never overwrites one. +- **Memory saver on VIctory-NVIDIA:** most of its switches are KLBF Lab's, which this build does not read. On a `victory play` start it now also sends the ones the build does read for the same need, from its docs/windows-memory.md: two pipeline workers (Light and up), and a smaller VRAM reserve for later render targets, given back once they settle (Very light). A value of your own wins. +- **Short of Windows memory, told apart:** when the game's memory guard reports the commit limit (RAM and page file) and the driver refuses pipelines with `0x8007000E`, Fix and verify now says the PC is short, not the card, and how to let Windows manage the page file. For VIctory-NVIDIA on 16 GB of RAM, two pipeline workers is offered as a possible setting. + +### Changed +- **Keyboard-as-controller keys removed:** VIctory-NVIDIA now reads generic USB pads beside Xbox and PlayStation ones, and has its own mouse and keyboard controls (F1, MOUSE AND KEYBOARD; keys in `bindings.ini`). The launcher's keyboard hook would have sent keys twice, so it is gone; *Mods & controls* shows where the game's own keys are. Saved settings from before still load. + +### Fixed +- **Agent tool:** `status` said a VIctory-NVIDIA build was not installed. The project has a `diag` profile, and the tool looked for the program there; the launcher builds `release`, as the tool now does too. + ## 1.2.2 ### New diff --git a/scripts/vilauncher-agent.mjs b/scripts/vilauncher-agent.mjs index 36fadb0..9fd2c06 100644 --- a/scripts/vilauncher-agent.mjs +++ b/scripts/vilauncher-agent.mjs @@ -272,13 +272,10 @@ async function readBuilt(targetDir) { } } -async function readCargoProfile(repoDir) { - try { - const text = await readFile(join(repoDir, "Cargo.toml"), "utf8"); - return text.includes("[profile.diag]") ? "diag" : "release"; - } catch { - return "release"; - } +// Mirrors launcher.rs detect_build_profile(): players always get the release build, even when +// the project also has a `diag` profile (VIctory-NVIDIA does), so its program is under release. +async function readCargoProfile(_repoDir) { + return "release"; } // Mirrors launcher.rs project_installed(): the recorded Rust install, else the victory program under the profile. diff --git a/src-tauri/known-problems/known-problems.json b/src-tauri/known-problems/known-problems.json index 7511893..8080683 100644 --- a/src-tauri/known-problems/known-problems.json +++ b/src-tauri/known-problems/known-problems.json @@ -10,6 +10,27 @@ "summary": "Black or incorrect surfaces.", "source": "Research brief, Phase 1: one A/B run reported black or incorrect surfaces with VICTORY_INPLACE=1. Single run; no repo doc names this switch.", "status": "single_run_report" + }, + { + "id": "victory-nvidia-commit-pipeline-workers", + "project": "VIctory-NVIDIA", + "switch": "VICTORY_PIPELINE_WORKERS=2", + "summary": "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.", + "source": "trustno1-coder/VIctory-NVIDIA docs/windows-memory.md (v2026.11.29.01): on 32 GB of RAM and an 8 GB RTX 3060 Ti the first scene load reached the commit limit and closed; with two pipeline workers it loaded past that point. A run of v2026.11.29.01 on an 8 GB RTX 4060 with 16 GB of RAM had 1137 pipelines refused with 0x8007000E while the memory guard reported commit under its floor.", + "status": "single_run_report", + "advice": { + "switch": "VICTORY_PIPELINE_WORKERS=2", + "evidence": "single_run_report", + "source": "docs/windows-memory.md, Reproduction on 32 GB RAM and an 8 GB RTX 3060 Ti", + "when": [ + { + "ram_gb_at_most": 16 + }, + { + "windows_only": true + } + ] + } } ] } diff --git a/src-tauri/locales/es/launcher.json b/src-tauri/locales/es/launcher.json index af78de4..bf95aa5 100644 --- a/src-tauri/locales/es/launcher.json +++ b/src-tauri/locales/es/launcher.json @@ -166,5 +166,18 @@ "CrossOver was not found in Applications.": "No se encontró CrossOver en Aplicaciones.", "The CrossOver bottle {bottle} was not found.": "No se encontró la botella de CrossOver {bottle}.", "The Wine program {wine} is not there.": "El programa Wine {wine} no está ahí.", - "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} es un programa de Windows. Elige un entorno (CrossOver o Wine) en Configuración, bajo Compilaciones de Windows en este Mac, o compila el proyecto desde el código fuente en macOS." + "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} es un programa de Windows. Elige un entorno (CrossOver o Wine) en Configuración, bajo Compilaciones de Windows en este Mac, o compila el proyecto desde el código fuente en macOS.", + "Mods are loaded on Windows only: this PC has no mods folder.": "Los mods solo se cargan en Windows: este PC no tiene carpeta de mods.", + "{file} is not the name of a mod DLL.": "{file} no es el nombre de una DLL de mod.", + "The mod {file} is not in the mods folder.": "El mod {file} no está en la carpeta de mods.", + "{file} is in the mods folder twice (on and off): remove one.": "{file} está dos veces en la carpeta de mods (activado y desactivado): quita uno.", + "Could not rename {file}: {e}": "No se pudo renombrar {file}: {e}", + "{file} is not a file.": "{file} no es un archivo.", + "A mod named {file} is already in the mods folder.": "Ya hay un mod llamado {file} en la carpeta de mods.", + "Could not make the mods folder: {e}": "No se pudo crear la carpeta de mods: {e}", + "Could not copy {file}: {e}": "No se pudo copiar {file}: {e}", + "Could not remove {file}: {e}": "No se pudo quitar {file}: {e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows se quedó sin memoria para el juego (RAM y archivo de paginación).", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "El juego pidió a Windows más memoria de la que dejaban la RAM y el archivo de paginación, así que se rechazaron pipelines de shaders y faltaron sus dibujados. Cierra otros programas y deja que Windows administre el tamaño del archivo de paginación (Sistema, Acerca de, Configuración avanzada del sistema, Rendimiento, Memoria virtual) y reinicia. Reparar y verificar también activa el ahorro de memoria, que en VIctory-NVIDIA prepara dos shaders a la vez en lugar de hasta ocho.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Menos pipelines de shaders preparados a la vez (2 en lugar de hasta 8), para que el juego se mantenga por debajo del límite de memoria confirmada de Windows (RAM y archivo de paginación) en un PC con 16 GB de RAM. Los shaders tardan más en terminarse la primera vez." } diff --git a/src-tauri/locales/fr/launcher.json b/src-tauri/locales/fr/launcher.json index ece9c99..298914b 100644 --- a/src-tauri/locales/fr/launcher.json +++ b/src-tauri/locales/fr/launcher.json @@ -166,5 +166,18 @@ "CrossOver was not found in Applications.": "CrossOver est introuvable dans Applications.", "The CrossOver bottle {bottle} was not found.": "La bouteille CrossOver {bottle} est introuvable.", "The Wine program {wine} is not there.": "Le programme Wine {wine} est introuvable.", - "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} est un programme Windows. Choisissez un runner (CrossOver ou Wine) dans les réglages, sous « Fichiers Windows sur ce Mac », ou compilez le projet depuis les sources sous macOS." + "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} est un programme Windows. Choisissez un runner (CrossOver ou Wine) dans les réglages, sous « Fichiers Windows sur ce Mac », ou compilez le projet depuis les sources sous macOS.", + "Mods are loaded on Windows only: this PC has no mods folder.": "Les mods ne se chargent que sous Windows : ce PC n'a pas de dossier de mods.", + "{file} is not the name of a mod DLL.": "{file} n'est pas le nom d'une DLL de mod.", + "The mod {file} is not in the mods folder.": "Le mod {file} n'est pas dans le dossier des mods.", + "{file} is in the mods folder twice (on and off): remove one.": "{file} est deux fois dans le dossier des mods (activé et désactivé) : supprimez-en un.", + "Could not rename {file}: {e}": "Impossible de renommer {file} : {e}", + "{file} is not a file.": "{file} n'est pas un fichier.", + "A mod named {file} is already in the mods folder.": "Un mod nommé {file} est déjà dans le dossier des mods.", + "Could not make the mods folder: {e}": "Impossible de créer le dossier des mods : {e}", + "Could not copy {file}: {e}": "Impossible de copier {file} : {e}", + "Could not remove {file}: {e}": "Impossible de supprimer {file} : {e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows a manqué de mémoire pour le jeu (RAM et fichier d'échange).", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "Le jeu a demandé à Windows plus de mémoire que la RAM et le fichier d'échange n'en laissaient : des pipelines de shaders ont été refusés et leurs rendus ont manqué. Fermez les autres programmes et laissez Windows gérer la taille du fichier d'échange (Système, Informations système, Paramètres système avancés, Performances, Mémoire virtuelle), puis redémarrez. Corriger et vérifier active aussi l'économiseur de mémoire qui, sur VIctory-NVIDIA, prépare deux shaders à la fois au lieu de huit au plus.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Moins de pipelines de shaders préparés à la fois (2 au lieu de 8 au plus) : le jeu reste sous la limite de mémoire validée de Windows (RAM et fichier d’échange) sur un PC avec 16 Go de RAM. Les shaders mettent plus de temps à se terminer la première fois." } diff --git a/src-tauri/locales/ru/launcher.json b/src-tauri/locales/ru/launcher.json index fbd258d..33a9e00 100644 --- a/src-tauri/locales/ru/launcher.json +++ b/src-tauri/locales/ru/launcher.json @@ -166,5 +166,18 @@ "CrossOver was not found in Applications.": "CrossOver не найден в «Программах».", "The CrossOver bottle {bottle} was not found.": "Бутылка CrossOver {bottle} не найдена.", "The Wine program {wine} is not there.": "Программа Wine {wine} не найдена.", - "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} — программа для Windows. Выберите слой совместимости (CrossOver или Wine) в Настройках в разделе «Сборки Windows на этом Mac» или соберите проект из исходников на macOS." + "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} — программа для Windows. Выберите слой совместимости (CrossOver или Wine) в Настройках в разделе «Сборки Windows на этом Mac» или соберите проект из исходников на macOS.", + "Mods are loaded on Windows only: this PC has no mods folder.": "Моды загружаются только в Windows: на этом ПК нет папки модов.", + "{file} is not the name of a mod DLL.": "{file} — не имя DLL мода.", + "The mod {file} is not in the mods folder.": "Мода {file} нет в папке модов.", + "{file} is in the mods folder twice (on and off): remove one.": "{file} есть в папке модов дважды (включённый и выключенный): удалите один.", + "Could not rename {file}: {e}": "Не удалось переименовать {file}: {e}", + "{file} is not a file.": "{file} — не файл.", + "A mod named {file} is already in the mods folder.": "Мод с именем {file} уже есть в папке модов.", + "Could not make the mods folder: {e}": "Не удалось создать папку модов: {e}", + "Could not copy {file}: {e}": "Не удалось скопировать {file}: {e}", + "Could not remove {file}: {e}": "Не удалось удалить {file}: {e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows не хватило памяти для игры (ОЗУ и файл подкачки).", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "Игра запросила у Windows больше памяти, чем оставалось в ОЗУ и файле подкачки, поэтому конвейеры шейдеров были отклонены, а их отрисовка пропала. Закройте другие программы и позвольте Windows автоматически выбирать размер файла подкачки (Система, О программе, Дополнительные параметры системы, Быстродействие, Виртуальная память), затем перезагрузите ПК. «Исправить и проверить» также включает экономию памяти: в VIctory-NVIDIA она готовит два шейдера одновременно вместо восьми.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Меньше конвейеров шейдеров одновременно (2 вместо до 8), чтобы игра не выходила за предел выделенной памяти Windows (ОЗУ и файл подкачки) на ПК с 16 ГБ ОЗУ. В первый раз шейдеры готовятся дольше." } diff --git a/src-tauri/locales/zh-CN/launcher.json b/src-tauri/locales/zh-CN/launcher.json index 1fc5088..00510ca 100644 --- a/src-tauri/locales/zh-CN/launcher.json +++ b/src-tauri/locales/zh-CN/launcher.json @@ -166,5 +166,18 @@ "Install the project first.": "请先安装项目。", "Memory stack": "内存精简补丁", "Cuts VRAM and private memory with no change to what is drawn. On the author's RTX 5080 16 GB: VRAM about 12.6 GB down to 8.55 GB, private commit about 26 GB down to about 20.5 GB.": "降低显存与私有内存用量,画面完全不变。在作者的 RTX 5080 16 GB 上:显存约从 12.6 GB 降到 8.55 GB,私有提交约从 26 GB 降到约 20.5 GB。", - "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "开启后,内存精简补丁会提交到这个项目的 vilauncher/memory-stack 分支,并把项目切换到该分支。只有接近补丁基准(e94251a)的项目才能应用。差异更大的分支无法应用这些补丁:启动器会说明原因,且不做任何更改。开启后第一次运行会重新生成着色器(会有几分钟缺少画面)。关闭后会回到项目原本的分支。" + "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "开启后,内存精简补丁会提交到这个项目的 vilauncher/memory-stack 分支,并把项目切换到该分支。只有接近补丁基准(e94251a)的项目才能应用。差异更大的分支无法应用这些补丁:启动器会说明原因,且不做任何更改。开启后第一次运行会重新生成着色器(会有几分钟缺少画面)。关闭后会回到项目原本的分支。", + "Mods are loaded on Windows only: this PC has no mods folder.": "模组只能在 Windows 上加载:这台电脑没有模组文件夹。", + "{file} is not the name of a mod DLL.": "{file} 不是模组 DLL 的名称。", + "The mod {file} is not in the mods folder.": "模组 {file} 不在模组文件夹中。", + "{file} is in the mods folder twice (on and off): remove one.": "{file} 在模组文件夹中有两份(已启用和已停用):请移除其中一份。", + "Could not rename {file}: {e}": "无法重命名 {file}:{e}", + "{file} is not a file.": "{file} 不是文件。", + "A mod named {file} is already in the mods folder.": "模组文件夹中已有名为 {file} 的模组。", + "Could not make the mods folder: {e}": "无法创建模组文件夹:{e}", + "Could not copy {file}: {e}": "无法复制 {file}:{e}", + "Could not remove {file}: {e}": "无法移除 {file}:{e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows 给游戏的内存不足(内存和页面文件)。", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "游戏向 Windows 申请的内存超过了内存和页面文件剩余的量,因此着色器管线被拒绝,相应的绘制缺失。请关闭其他程序,并让 Windows 自动管理页面文件大小(系统、系统信息、高级系统设置、性能、虚拟内存),然后重启。“修复并验证”也会开启内存节省,在 VIctory-NVIDIA 上它每次只准备两个着色器,而不是最多八个。", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同时准备的着色器管线更少(2 个,而不是最多 8 个),这样在 16 GB 内存的电脑上,游戏不会超出 Windows 的提交内存上限(内存和页面文件)。第一次准备着色器会更久。" } diff --git a/src-tauri/locales/zh-TW/launcher.json b/src-tauri/locales/zh-TW/launcher.json index f682141..bd95ef8 100644 --- a/src-tauri/locales/zh-TW/launcher.json +++ b/src-tauri/locales/zh-TW/launcher.json @@ -166,5 +166,18 @@ "Install the project first.": "請先安裝專案。", "Memory stack": "記憶體精簡修補", "Cuts VRAM and private memory with no change to what is drawn. On the author's RTX 5080 16 GB: VRAM about 12.6 GB down to 8.55 GB, private commit about 26 GB down to about 20.5 GB.": "降低顯示記憶體與私有記憶體用量,畫面完全不變。在作者的 RTX 5080 16 GB 上:顯示記憶體約從 12.6 GB 降到 8.55 GB,私有提交約從 26 GB 降到約 20.5 GB。", - "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "開啟後,記憶體精簡修補程式會提交到這個專案的 vilauncher/memory-stack 分支,並把專案切換到該分支。只有接近修補程式基準(e94251a)的專案才能套用。差異更大的分支無法套用這些修補程式:啟動器會說明原因,且不做任何變更。開啟後第一次執行會重新產生著色器(會有幾分鐘缺少畫面)。關閉後會回到專案原本的分支。" + "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "開啟後,記憶體精簡修補程式會提交到這個專案的 vilauncher/memory-stack 分支,並把專案切換到該分支。只有接近修補程式基準(e94251a)的專案才能套用。差異更大的分支無法套用這些修補程式:啟動器會說明原因,且不做任何變更。開啟後第一次執行會重新產生著色器(會有幾分鐘缺少畫面)。關閉後會回到專案原本的分支。", + "Mods are loaded on Windows only: this PC has no mods folder.": "模組只能在 Windows 上載入:這台電腦沒有模組資料夾。", + "{file} is not the name of a mod DLL.": "{file} 不是模組 DLL 的名稱。", + "The mod {file} is not in the mods folder.": "模組 {file} 不在模組資料夾中。", + "{file} is in the mods folder twice (on and off): remove one.": "{file} 在模組資料夾中有兩份(已啟用和已停用):請移除其中一份。", + "Could not rename {file}: {e}": "無法重新命名 {file}:{e}", + "{file} is not a file.": "{file} 不是檔案。", + "A mod named {file} is already in the mods folder.": "模組資料夾中已有名為 {file} 的模組。", + "Could not make the mods folder: {e}": "無法建立模組資料夾:{e}", + "Could not copy {file}: {e}": "無法複製 {file}:{e}", + "Could not remove {file}: {e}": "無法移除 {file}:{e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows 給遊戲的記憶體不足(記憶體和分頁檔)。", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "遊戲向 Windows 要求的記憶體超過了記憶體和分頁檔剩餘的量,因此著色器管線被拒絕,相應的繪製缺失。請關閉其他程式,並讓 Windows 自動管理分頁檔大小(系統、關於、進階系統設定、效能、虛擬記憶體),然後重新開機。「修復並驗證」也會開啟記憶體節省,在 VIctory-NVIDIA 上它一次只準備兩個著色器,而不是最多八個。", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同時準備的著色器管線更少(2 個,而不是最多 8 個),這樣在 16 GB 記憶體的電腦上,遊戲不會超出 Windows 的認可記憶體上限(記憶體和分頁檔)。第一次準備著色器會更久。" } diff --git a/src-tauri/src/controller_keys.rs b/src-tauri/src/controller_keys.rs deleted file mode 100644 index 064bb92..0000000 --- a/src-tauri/src/controller_keys.rs +++ /dev/null @@ -1,444 +0,0 @@ -//! Keyboard keys for the game's controller controls. -//! -//! VIctory's input layer reads a pad from the keyboard when no controller is connected: -//! a fixed table maps keys to pad buttons and sticks. Here the player can give each of -//! those controls another key. While the game window is in front, a low-level keyboard -//! hook sends the layer's own key for the control whose key was pressed. Off by default. -//! Only Windows has the hook; elsewhere the settings are kept and nothing is sent. - -use std::collections::BTreeMap; - -/// One control the layer reads from the keyboard, with the key the layer uses for it. -pub struct Control { - pub id: &'static str, - pub label: &'static str, - /// Windows virtual-key code the layer reads (the same as the browser's keyCode). - pub default_key: u16, -} - -pub const CONTROLS: &[Control] = &[ - Control { - id: "menu", - label: "Menu", - default_key: 0x1B, - }, - Control { - id: "view", - label: "View", - default_key: 0x09, - }, - Control { - id: "a", - label: "A", - default_key: 0x0D, - }, - Control { - id: "b", - label: "B", - default_key: 0x08, - }, - Control { - id: "x", - label: "X", - default_key: 0x58, - }, - Control { - id: "y", - label: "Y", - default_key: 0x59, - }, - Control { - id: "up", - label: "D-pad up", - default_key: 0x26, - }, - Control { - id: "down", - label: "D-pad down", - default_key: 0x28, - }, - Control { - id: "left", - label: "D-pad left", - default_key: 0x25, - }, - Control { - id: "right", - label: "D-pad right", - default_key: 0x27, - }, - Control { - id: "left_shoulder", - label: "Left shoulder", - default_key: 0x51, - }, - Control { - id: "right_shoulder", - label: "Right shoulder", - default_key: 0x45, - }, - Control { - id: "left_stick_click", - label: "Left stick click", - default_key: 0x46, - }, - Control { - id: "right_stick_click", - label: "Right stick click", - default_key: 0x48, - }, - Control { - id: "left_stick_up", - label: "Left stick up", - default_key: 0x57, - }, - Control { - id: "left_stick_left", - label: "Left stick left", - default_key: 0x41, - }, - Control { - id: "left_stick_down", - label: "Left stick down", - default_key: 0x53, - }, - Control { - id: "left_stick_right", - label: "Left stick right", - default_key: 0x44, - }, - Control { - id: "right_stick_up", - label: "Right stick up", - default_key: 0x49, - }, - Control { - id: "right_stick_left", - label: "Right stick left", - default_key: 0x4A, - }, - Control { - id: "right_stick_down", - label: "Right stick down", - default_key: 0x4B, - }, - Control { - id: "right_stick_right", - label: "Right stick right", - default_key: 0x4C, - }, - Control { - id: "left_trigger", - label: "Left trigger", - default_key: 0x5A, - }, - Control { - id: "right_trigger", - label: "Right trigger", - default_key: 0x43, - }, -]; - -pub fn control(id: &str) -> Option<&'static Control> { - CONTROLS.iter().find(|c| c.id == id) -} - -/// The key the player uses for a control: their own, else the layer's. -pub fn key_of(bindings: &BTreeMap, control: &Control) -> u16 { - bindings - .get(control.id) - .copied() - .unwrap_or(control.default_key) -} - -/// Whether `key` may be given to control `id`: a real key, and not one another control uses. -pub fn check_key(bindings: &BTreeMap, id: &str, key: u16) -> Result<(), String> { - // 0 and 0xFF are not keys; the rest stay with Windows or are modifiers the game needs. - const RESERVED: &[u16] = &[ - 0x03, 0x10, 0x11, 0x12, 0x14, 0x2C, 0x5B, 0x5C, 0x5D, 0x90, 0x91, 0xA0, 0xA1, 0xA2, 0xA3, - 0xA4, 0xA5, - ]; - if key == 0 || key == 0xFF || RESERVED.contains(&key) { - return Err("That key cannot be used for a controller control.".into()); - } - for other in CONTROLS.iter().filter(|c| c.id != id) { - if key_of(bindings, other) == key { - return Err(format!("{} already uses that key.", other.label)); - } - } - Ok(()) -} - -/// What the game should see for a key the player pressed. -#[cfg_attr(not(windows), allow(dead_code))] -#[derive(Debug, PartialEq, Eq)] -pub enum Step { - /// Unchanged: the key reaches the game as pressed. - Pass, - /// The layer's key for the control the player pressed. - Send(u16), - /// Nothing: the key is the layer's own key for a control the player moved elsewhere. - Swallow, -} - -#[cfg_attr(not(windows), allow(dead_code))] -pub fn translate(bindings: &BTreeMap, pressed: u16) -> Step { - if let Some(control) = CONTROLS.iter().find(|c| key_of(bindings, c) == pressed) { - return if control.default_key == pressed { - Step::Pass - } else { - Step::Send(control.default_key) - }; - } - if CONTROLS.iter().any(|c| c.default_key == pressed) { - Step::Swallow - } else { - Step::Pass - } -} - -#[cfg(windows)] -mod hook { - use super::{translate, Step}; - use std::collections::{BTreeMap, HashMap}; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::sync::{Mutex, Once}; - use windows_sys::Win32::Foundation::{CloseHandle, LPARAM, LRESULT, WPARAM}; - use windows_sys::Win32::System::Threading::{ - OpenProcess, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION, - }; - use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ - MapVirtualKeyW, SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, - KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC, - }; - use windows_sys::Win32::UI::WindowsAndMessaging::{ - CallNextHookEx, GetForegroundWindow, GetMessageW, GetWindowThreadProcessId, - SetWindowsHookExW, KBDLLHOOKSTRUCT, LLKHF_INJECTED, MSG, WH_KEYBOARD_LL, WM_KEYDOWN, - WM_KEYUP, WM_SYSKEYDOWN, WM_SYSKEYUP, - }; - - /// The game's program name: every VIctory build starts `victory.exe`. - const GAME_EXE: &str = "victory.exe"; - - static ENABLED: AtomicBool = AtomicBool::new(false); - static HOOK_STARTED: Once = Once::new(); - - struct State { - bindings: BTreeMap, - /// Keys held down whose presses were changed, and what each sent. Kept across - /// settings changes, so the release is always seen and nothing stays pressed. - held: HashMap, - } - - static STATE: Mutex> = Mutex::new(None); - - fn lock() -> std::sync::MutexGuard<'static, Option> { - STATE.lock().unwrap_or_else(|e| e.into_inner()) - } - - pub fn configure(on: bool, bindings: BTreeMap) { - { - let mut state = lock(); - let held = state.take().map(|old| old.held).unwrap_or_default(); - *state = Some(State { bindings, held }); - } - ENABLED.store(on, Ordering::Relaxed); - if on { - HOOK_STARTED.call_once(|| { - std::thread::spawn(|| unsafe { - let hook = SetWindowsHookExW( - WH_KEYBOARD_LL, - Some(keyboard_hook), - std::ptr::null_mut(), - 0, - ); - if hook.is_null() { - return; - } - let mut message: MSG = std::mem::zeroed(); - // The hook runs on this thread, so it needs a message loop for as long as the launcher runs. - while GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) > 0 {} - }); - }); - } - } - - unsafe extern "system" fn keyboard_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { - if code >= 0 { - let info = &*(lparam as *const KBDLLHOOKSTRUCT); - let message = wparam as u32; - let down = message == WM_KEYDOWN || message == WM_SYSKEYDOWN; - let up = message == WM_KEYUP || message == WM_SYSKEYUP; - // Keys this hook sent are flagged injected: letting them through avoids a loop. - if (down || up) && info.flags & LLKHF_INJECTED == 0 { - let key = info.vkCode as u16; - // A release is always handled, so a key pressed in the game cannot stay down - // when the focus moves away or the setting changes. - let consumed = if up { - release(key) - } else { - ENABLED.load(Ordering::Relaxed) && game_in_front() && press(key) - }; - if consumed { - return 1; - } - } - } - CallNextHookEx(std::ptr::null_mut(), code, wparam, lparam) - } - - /// A key went down in the game. Returns true when the key is consumed. - fn press(key: u16) -> bool { - let mut guard = lock(); - let Some(state) = guard.as_mut() else { - return false; - }; - if state.held.contains_key(&key) { - return true; - } - match translate(&state.bindings, key) { - Step::Pass => false, - Step::Send(sent) => { - state.held.insert(key, Step::Send(sent)); - drop(guard); - // SAFETY: SendInput with one well-formed input. - unsafe { send(sent, true) }; - true - } - Step::Swallow => { - state.held.insert(key, Step::Swallow); - true - } - } - } - - /// A key went up. Releases what its press sent. Returns true when the key is consumed. - fn release(key: u16) -> bool { - let mut guard = lock(); - let Some(state) = guard.as_mut() else { - return false; - }; - match state.held.remove(&key) { - None => false, - Some(Step::Send(sent)) => { - drop(guard); - // SAFETY: as above. - unsafe { send(sent, false) }; - true - } - Some(_) => true, - } - } - - /// Whether the window in front belongs to the game. - unsafe fn game_in_front() -> bool { - let window = GetForegroundWindow(); - if window.is_null() { - return false; - } - let mut pid = 0u32; - GetWindowThreadProcessId(window, &mut pid); - let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); - if process.is_null() { - return false; - } - let mut buffer = [0u16; 1024]; - let mut length = buffer.len() as u32; - let named = QueryFullProcessImageNameW(process, 0, buffer.as_mut_ptr(), &mut length) != 0; - CloseHandle(process); - named && { - let path = String::from_utf16_lossy(&buffer[..length as usize]); - std::path::Path::new(&path) - .file_name() - .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(GAME_EXE)) - } - } - - unsafe fn send(key: u16, down: bool) { - // Arrows, paging, insert and delete are extended keys. - let extended = matches!(key, 0x21..=0x28 | 0x2D | 0x2E); - let mut flags = 0; - if !down { - flags |= KEYEVENTF_KEYUP; - } - if extended { - flags |= KEYEVENTF_EXTENDEDKEY; - } - let input = INPUT { - r#type: INPUT_KEYBOARD, - Anonymous: INPUT_0 { - ki: KEYBDINPUT { - wVk: key, - wScan: MapVirtualKeyW(u32::from(key), MAPVK_VK_TO_VSC) as u16, - dwFlags: flags, - time: 0, - dwExtraInfo: 0, - }, - }, - }; - SendInput(1, &input, std::mem::size_of::() as i32); - } -} - -/// Applies the player's settings: whether the keys are on, and their key choices. -pub fn configure(on: bool, bindings: &BTreeMap) { - #[cfg(windows)] - hook::configure(on, bindings.clone()); - #[cfg(not(windows))] - let _ = (on, bindings); -} - -#[cfg(test)] -mod tests { - use super::*; - - fn bind(pairs: &[(&str, u16)]) -> BTreeMap { - pairs - .iter() - .map(|(id, key)| (id.to_string(), *key)) - .collect() - } - - #[test] - fn with_no_changes_every_key_passes() { - let none = BTreeMap::new(); - assert_eq!(translate(&none, 0x0D), Step::Pass); - assert_eq!(translate(&none, 0x46), Step::Pass); - assert_eq!(translate(&none, 0x20), Step::Pass); - } - - #[test] - fn a_moved_control_sends_the_layers_key_and_its_old_key_is_swallowed() { - // A (Enter in the layer) moved to F: F sends Enter, Enter itself is swallowed, - // and other keys are untouched. - let moved = bind(&[("a", 0x46)]); - assert_eq!(translate(&moved, 0x46), Step::Send(0x0D)); - assert_eq!(translate(&moved, 0x0D), Step::Swallow); - assert_eq!(translate(&moved, 0x58), Step::Pass); - } - - #[test] - fn a_key_already_in_use_is_refused_and_a_freed_key_is_allowed() { - let none = BTreeMap::new(); - // X is the layer's X key for control x: another control cannot take it. - assert!(check_key(&none, "a", 0x58).is_err()); - // Once X moves to K, X is free for another control. - let moved = bind(&[("x", 0x4B)]); - assert!(check_key(&moved, "a", 0x58).is_ok()); - // Keys the layer never reads for a control are not refused for that reason. - assert!(check_key(&none, "a", 0x20).is_ok()); - assert!(check_key(&none, "a", 0).is_err()); - // Modifiers, Windows and lock keys stay with the system. - assert!(check_key(&none, "a", 0x12).is_err()); - assert!(check_key(&none, "a", 0x5B).is_err()); - } - - #[test] - fn every_control_has_a_distinct_default_key() { - for (i, a) in CONTROLS.iter().enumerate() { - for b in &CONTROLS[i + 1..] { - assert_ne!(a.default_key, b.default_key, "{} and {}", a.id, b.id); - } - } - } -} diff --git a/src-tauri/src/diagnose.rs b/src-tauri/src/diagnose.rs index 8dcf590..6c7ff7e 100644 --- a/src-tauri/src/diagnose.rs +++ b/src-tauri/src/diagnose.rs @@ -1193,10 +1193,30 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { advice: None, }); } - if has(&["out of memory", "0x8007000E"]) { + // VIctory-NVIDIA's memory guard puts a driver compile off when it would leave Windows' + // commit (RAM and page file together) under its floor, and the driver refuses one with + // 0x8007000E when there is none: then the PC is short, not the card, and the refused + // pipelines stay unmade, their draws missing (freezes, a black picture). + // The guard's line alone is a compile put off and made later; with a refusal, or an + // allocation that found no commit left (the runtime's abort), the PC ran short. + let refused = has(&["out of memory", "0x8007000E", "0x8007000e"]); + let commit = + has(&["left to commit"]) || refused && has(&["the commit left would fall under its floor"]); + if commit || refused { + let (title, detail) = if commit { + ( + msg_str!("Windows ran short of memory for the game (RAM and page file)."), + msg_str!("The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight."), + ) + } else { + ( + "The game ran out of memory.", + "Fix and verify lowers the render scale, turns on the texture fix and the memory saver, and lowers an output above 1080p to 1080p.", + ) + }; found.push(Finding { - title: "The game ran out of memory.".to_string(), - detail: "Fix and verify lowers the render scale, turns on the texture fix and the memory saver, and lowers an output above 1080p to 1080p.".to_string(), + title: title.to_string(), + detail: detail.to_string(), fix: Some(FIX_GRAPHICS_MEMORY), heavy: false, data: None, @@ -1536,6 +1556,30 @@ mod tests { assert!(from_log(&bad).iter().any(|f| f.fix == Some(FIX_CACHE))); } + #[test] + fn short_commit_is_told_from_a_full_card() { + // VIctory-NVIDIA v2026.11.29.01 on an RTX 4060 with 16 GB of RAM: the memory guard and + // the driver's refusals, 1137 pipelines never made. + let commit = vec![ + r#"WARN victory_gpu::memguard: memory guard: a compile is put off (it is made again later; the process goes on) what="c0ffd16bf5bacb43" so_far=1024 free_physical_mb=1664 free_commit_mb=1765 reason="the commit left would fall under its floor""#.to_string(), + r#"WARN victory_gpu::pipeline::refused: host pipeline failed (logged once per key) key="37e19ccb4f889f63" stage="compute" hr=0x8007000e lacks="" reason="compute 0x8007000e""#.to_string(), + ]; + let found = from_log(&commit); + let memory: Vec<_> = found + .iter() + .filter(|f| f.fix == Some(FIX_GRAPHICS_MEMORY)) + .collect(); + assert_eq!(memory.len(), 1, "one finding, so the fix runs once"); + assert!(memory[0].title.contains("page file")); + // The guard's line alone is a compile made later: no finding. + assert!(from_log(&commit[..1]).is_empty()); + // A refusal alone (the card's own memory) keeps the plain finding. + let card = vec![commit[1].clone()]; + let found = from_log(&card); + assert_eq!(found.len(), 1); + assert_eq!(found[0].title, "The game ran out of memory."); + } + #[test] fn a_missing_build_is_a_heavy_finding() { let root = temp("missing-build"); diff --git a/src-tauri/src/launcher.rs b/src-tauri/src/launcher.rs index a28833e..527dfe0 100644 --- a/src-tauri/src/launcher.rs +++ b/src-tauri/src/launcher.rs @@ -186,10 +186,9 @@ pub(crate) struct Saved { skip_update_warning: bool, /// Let AI agents read logs and, when the player confirms each step, apply patches. Off by default. agent_access: bool, - /// Keyboard keys drive the game's controller controls (controller_keys.rs). Off by default. - controller_keys_on: bool, - /// The key the player chose for a controller control, by control id; absent: the layer's own. - controller_key_bindings: std::collections::BTreeMap, + // The keyboard-as-controller hook (`controller_keys_on`, `controller_key_bindings`) is gone: + // VIctory-NVIDIA reads mouse and keyboard itself (F1, MOUSE AND KEYBOARD; bindings.ini) and + // pads of every kind. Settings files that still have those fields read as before. /// Ids of the responsibility warnings the player accepted ("import-repo", "agent-access", "agent-patch"). acknowledged: Vec, /// The window's language as a tag ("en", "zh-TW", "zh-CN"); none: the system's. @@ -1917,7 +1916,6 @@ impl App { } pub(crate) fn new(ctx: Ctx, mut saved: Saved) -> App { - crate::controller_keys::configure(saved.controller_keys_on, &saved.controller_key_bindings); if saved.render_scale <= 0.0 { saved.render_scale = 0.5; } @@ -2470,7 +2468,7 @@ fn install( data: &data, cache: &cache, last_log: &[], - switches: &l.extra, + switches: &check_switches(l, starts_native(&exe, l)), installed: true, game_ok: game_files_ok(&l.game_dir), unplugged: !drive_connected(&l.game_dir), @@ -4209,7 +4207,7 @@ fn run_fixes( data: &data, cache: &cache, last_log: &last_log, - switches: &l.extra, + switches: &check_switches(l, starts_native(&exe, l)), installed: true, game_ok: game_files_ok(&l.game_dir), unplugged: !drive_connected(&l.game_dir), @@ -4408,6 +4406,116 @@ not a switch ); } +/// The memory saver on VIctory-NVIDIA (`victory play`). That build sizes its own pools for a +/// PC under 24 GB of RAM and a card of 8 GB or less, so the launcher only adds what its +/// docs/windows-memory.md measured against the crashes the saver is for: +/// - Light and up: two pipeline workers. Each compile asks the driver for commit; a 32 GB PC +/// with 8 workers' worth of compiles reached the Windows commit limit and closed, with two +/// it loaded past that point (the default is up to 8 on a PC with 32 GB or less). +/// - Very light: the VRAM kept for render targets that may come later, lowered from its +/// 2,560 MiB (8 GB card) default to 768 MiB and given back once the targets settle (8 s): +/// with the default it was never given back on Series S, where targets stay under 1.5 GiB. +fn native_memory_switches(memory: MemorySaver) -> &'static [(&'static str, &'static str)] { + match memory { + MemorySaver::Normal => &[], + MemorySaver::Light => &[("VICTORY_PIPELINE_WORKERS", "2")], + MemorySaver::VeryLight => &[ + ("VICTORY_PIPELINE_WORKERS", "2"), + ("VICTORY_CARD_ROOM_FOR_TARGETS_MB", "768"), + ("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS", "8000"), + ], + } +} + +#[test] +fn memory_saver_on_native_play_sends_switches_the_build_reads() { + let root = + std::env::temp_dir().join(format!("vilauncher-nvidia-memory-{}", std::process::id())); + let mut launch = test_launch(root.clone()); + let set = |launch: &Launch| -> Vec { + let command = native_nvidia_command( + &root.join("victory.exe"), + &root, + &test_project(), + launch, + &[], + ); + command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .filter(|arg| arg.starts_with("VICTORY_")) + .collect() + }; + launch.graphics.memory = MemorySaver::Normal; + assert!(!set(&launch) + .iter() + .any(|a| a.starts_with("VICTORY_PIPELINE_WORKERS"))); + launch.graphics.memory = MemorySaver::Light; + let light = set(&launch); + assert!(light.contains(&"VICTORY_PIPELINE_WORKERS=2".to_string())); + assert!(!light + .iter() + .any(|a| a.starts_with("VICTORY_CARD_ROOM_FOR_TARGETS"))); + launch.graphics.memory = MemorySaver::VeryLight; + let very = set(&launch); + assert!(very.contains(&"VICTORY_CARD_ROOM_FOR_TARGETS_MB=768".to_string())); + // The player's own value wins. + launch.extra = "VICTORY_PIPELINE_WORKERS=4".into(); + let own = set(&launch); + assert!(own.contains(&"VICTORY_PIPELINE_WORKERS=4".to_string())); + assert!(!own.contains(&"VICTORY_PIPELINE_WORKERS=2".to_string())); +} + +/// Whether a start of `exe` with `l` goes through the build's own `victory play`, as [`play`] +/// decides it: the build offers it, and `play` takes this start's launch arguments. +fn starts_native(exe: &Path, l: &Launch) -> bool { + victory_help(exe, "play") + .filter(|help| has_native_play(help)) + .is_some_and(|help| native_nvidia_args(l, &help).is_ok()) +} + +/// The switches a start sends, as the checks read them: the player's and the fixes' lines, +/// and, on a start through `victory play` (`native`), the memory saver's that only that start +/// sends, so advice already in effect is not offered and advice that is not still is. +fn check_switches(l: &Launch, native: bool) -> String { + let mut text = l.extra.clone(); + if native { + for (key, value) in native_memory_switches(l.graphics.memory) { + text.push_str(&format!("\n{key}={value}")); + } + } + text +} + +#[test] +fn advice_the_memory_saver_already_sends_is_not_offered() { + let mut launch = test_launch(std::env::temp_dir()); + launch.graphics.memory = MemorySaver::Light; + let manifest = crate::known_problems::shipped().unwrap(); + let hardware = crate::known_problems::Hardware { + gpus: vec![(Some("nvidia"), "NVIDIA GeForce RTX 4060".into())], + ram_gb: Some(16.0), + os_build: None, + windows: true, + }; + let offered = |switches: &str| { + crate::known_problems::advice_for(&manifest, "owner_VIctory-NVIDIA", &hardware, switches) + .iter() + .any(|entry| entry.id == "victory-nvidia-commit-pipeline-workers") + }; + // Through `victory play` the saver sends it: not offered. + assert!(!offered(&check_switches(&launch, true))); + // Through `run` (no native play, or a launch argument it does not take) it is not sent. + assert!(offered(&check_switches(&launch, false))); + launch.graphics.memory = MemorySaver::Normal; + assert!(offered(&check_switches(&launch, true))); + // A program that is not there has no native play. + assert!(!starts_native( + &std::env::temp_dir().join("no-such-victory.exe"), + &launch + )); +} + fn native_nvidia_command( exe: &Path, root: &Path, @@ -4452,6 +4560,11 @@ fn native_nvidia_command( } } } + // The memory saver's own switches are mostly KLBF Lab's, which this build does not read. + // These are the ones it does read for the same need; a player's own value wins. + for (key, value) in native_memory_switches(l.graphics.memory) { + switches.entry(key).or_insert(value); + } // `victory play` puts `--set` over what the F1 menu saved, so a switch the player // chose in F1 would be undone at every start: those are left to the menu. let saved = victory_menu_file() diff --git a/src-tauri/src/launcher/actions.rs b/src-tauri/src/launcher/actions.rs index 63e4b37..ab87999 100644 --- a/src-tauri/src/launcher/actions.rs +++ b/src-tauri/src/launcher/actions.rs @@ -87,15 +87,6 @@ pub(crate) enum Action { SetUpdateWarning { show: bool, }, - /// Turns the keyboard-as-controller keys on or off (controller_keys.rs). - SetControllerKeys { - on: bool, - }, - /// Gives a controller control another key; `key` None goes back to the layer's own. - SetControllerKey { - control: String, - key: Option, - }, /// Let AI agents help with builds (off by default; turning it on needs the "agent-access" warning first). SetAgentAccess { enabled: bool, @@ -268,6 +259,19 @@ pub(crate) enum Action { ImportSaveZip { path: String, }, + /// Copies a DLL into VIctory-NVIDIA's mods folder (mods.rs), on. + ModAdd { + path: String, + }, + /// Turns a mod in the mods folder on or off, by its name there (`x.dll` or `x.dll.off`). + ModSetOn { + entry: String, + on: bool, + }, + /// Deletes a mod from the mods folder, by its name there. + ModRemove { + entry: String, + }, ExportSave { source: String, path: String, @@ -519,34 +523,6 @@ impl App { self.saved.skip_update_warning = !show; Value::Null } - Action::SetControllerKeys { on } => { - self.saved.controller_keys_on = on; - crate::controller_keys::configure(on, &self.saved.controller_key_bindings); - Value::Null - } - Action::SetControllerKey { control, key } => { - if crate::controller_keys::control(&control).is_none() { - return Err(format!("There is no controller control {control}.")); - } - match key { - Some(key) => { - crate::controller_keys::check_key( - &self.saved.controller_key_bindings, - &control, - key, - )?; - self.saved.controller_key_bindings.insert(control, key); - } - None => { - self.saved.controller_key_bindings.remove(&control); - } - } - crate::controller_keys::configure( - self.saved.controller_keys_on, - &self.saved.controller_key_bindings, - ); - Value::Null - } Action::SetAgentAccess { enabled } => { self.saved.agent_access = enabled; Value::Null @@ -957,6 +933,17 @@ impl App { ("workspace", _) => workspace(), ("cache", _) => cache_root(), ("saves", _) => shared_saves().unwrap_or_else(|| workspace().join("data")), + ("mods", _) => crate::mods::folder().ok_or(NO_MODS)?, + // The game's own mouse and keyboard keys: its file is shown where it is. + ("bindings", _) => { + let home = crate::mods::victory_home().ok_or(NO_MODS)?; + let file = home.join("bindings.ini"); + if file.is_file() { + reveal(&file)?; + return Ok(Outcome::Value(Value::Null)); + } + home + } ("update", _) => match &self.updater.state { updater::State::Downloaded(update) => update .path @@ -1023,6 +1010,20 @@ impl App { .map_err(|error| msg!("Could not import the save: {error}"))?; json!(name) } + Action::ModAdd { path } => { + let folder = crate::mods::folder().ok_or(NO_MODS)?; + json!(crate::mods::add(&folder, Path::new(&path))?) + } + Action::ModSetOn { entry, on } => { + let folder = crate::mods::folder().ok_or(NO_MODS)?; + crate::mods::set_on(&folder, &entry, on)?; + Value::Null + } + Action::ModRemove { entry } => { + let folder = crate::mods::folder().ok_or(NO_MODS)?; + crate::mods::remove(&folder, &entry)?; + Value::Null + } Action::ExportSave { source, path } => { let destination = PathBuf::from(path); let destination = if destination.extension().is_none() { @@ -1411,6 +1412,9 @@ fn open_link(url: &str) -> Result<(), String> { crate::platform::open_url(url) } +/// VIctory-NVIDIA loads its mods with LoadLibrary: there is a mods folder on Windows only. +const NO_MODS: &str = msg_str!("Mods are loaded on Windows only: this PC has no mods folder."); + fn open_folder(path: &Path) -> Result<(), String> { crate::platform::open_folder(path) } diff --git a/src-tauri/src/launcher/view.rs b/src-tauri/src/launcher/view.rs index 3dc5a2d..d36db69 100644 --- a/src-tauri/src/launcher/view.rs +++ b/src-tauri/src/launcher/view.rs @@ -52,34 +52,24 @@ struct ListView { items: Vec, } -/// The keyboard-as-controller settings: on or off, and every control with its key. +/// VIctory-NVIDIA's mods folder (mods.rs) and what is in it. None where there is none (off +/// Windows). #[derive(Serialize)] -pub(crate) struct ControllerKeysView { - on: bool, - controls: Vec, +pub(crate) struct ModsView { + folder: String, + items: Vec, + /// `bindings.ini`, the game's own mouse and keyboard keys, is in the runtime's home. + bindings: bool, } -#[derive(Serialize)] -pub(crate) struct ControlView { - id: &'static str, - label: &'static str, - default_key: u16, - key: u16, -} - -fn controller_keys_view(saved: &super::Saved) -> ControllerKeysView { - ControllerKeysView { - on: saved.controller_keys_on, - controls: crate::controller_keys::CONTROLS - .iter() - .map(|control| ControlView { - id: control.id, - label: control.label, - default_key: control.default_key, - key: crate::controller_keys::key_of(&saved.controller_key_bindings, control), - }) - .collect(), - } +fn mods_view() -> Option { + let home = crate::mods::victory_home()?; + let folder = home.join("mods"); + Some(ModsView { + items: crate::mods::list(&folder), + folder: folder.display().to_string(), + bindings: home.join("bindings.ini").is_file(), + }) } impl super::App { @@ -236,7 +226,7 @@ struct SettingsView { backgrounds_dir: String, skip_update_warning: bool, agent_access: bool, - controller_keys: ControllerKeysView, + mods: Option, acknowledged: Vec, /// The player's language choice; none: the system's. language: Option, @@ -444,7 +434,7 @@ impl App { backgrounds_dir: crate::backgrounds::folder().display().to_string(), skip_update_warning: self.saved.skip_update_warning, agent_access: self.saved.agent_access, - controller_keys: controller_keys_view(&self.saved), + mods: mods_view(), acknowledged: self.saved.acknowledged.clone(), language: self.saved.language.clone(), }, diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 9fa1683..ad93aae 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -14,12 +14,12 @@ mod backgrounds; mod brand; mod build_activity; mod build_zip; -mod controller_keys; mod diagnose; mod fullscreen; mod job_log; mod known_problems; mod launcher; +mod mods; mod notify; mod patches; mod platform; diff --git a/src-tauri/src/mods.rs b/src-tauri/src/mods.rs new file mode 100644 index 0000000..3a80d9e --- /dev/null +++ b/src-tauri/src/mods.rs @@ -0,0 +1,286 @@ +//! The mods folder of VIctory-NVIDIA (PR #1892, release v2026.11.29.01 on). +//! +//! At every start, `victory` loads each `*.dll` in `\mods`, by name, before the title runs; +//! `` is `VICTORY_HOME`, else `%LOCALAPPDATA%\victory` (the same home as the F1 menu's +//! `victory-settings.txt`). The folder is the runtime's, so it is shared by every build of it. +//! Here the player can see what is in it, add a DLL, turn one off (renamed to `.dll.off`, +//! which the runtime does not load), turn it on again, or remove it. Mods load with +//! `LoadLibrary`, so the folder is a Windows one; elsewhere there is none. +//! +//! A mod is native code run inside the game with the player's rights. The launcher only moves +//! files: it never downloads a mod, and it never runs one itself. + +use std::path::{Path, PathBuf}; + +/// The suffix a turned-off mod gets after `.dll`. +const OFF: &str = ".off"; + +/// One mod in the folder. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub(crate) struct Mod { + /// The DLL's name as the runtime loads it (`example.dll`), also when it is off. + pub file: String, + /// Its name in the folder now (`example.dll`, or `example.dll.off` when off). The actions + /// take it, so a mod that is there both on and off is two rows, each acting on its own file. + pub entry: String, + pub on: bool, + pub bytes: u64, +} + +/// The runtime's home: `VICTORY_HOME`, else `%LOCALAPPDATA%\victory`. None off Windows, in +/// tests (they never touch the player's own), and with neither variable. +pub(crate) fn victory_home() -> Option { + if cfg!(test) || !cfg!(windows) { + return None; + } + std::env::var_os("VICTORY_HOME") + .filter(|home| !home.is_empty()) + .map(PathBuf::from) + .or_else(|| std::env::var_os("LOCALAPPDATA").map(|dir| PathBuf::from(dir).join("victory"))) +} + +/// The mods folder (it may not exist yet). +pub(crate) fn folder() -> Option { + victory_home().map(|home| home.join("mods")) +} + +/// The DLL name of a folder entry, and whether it is on: `x.dll` on, `x.dll.off` off. +fn parse_name(name: &str) -> Option<(String, bool)> { + let lower = name.to_ascii_lowercase(); + if lower.ends_with(".dll") && name.len() > 4 { + return Some((name.to_owned(), true)); + } + if lower.ends_with(".dll.off") && name.len() > 8 { + return Some((name[..name.len() - OFF.len()].to_owned(), false)); + } + None +} + +/// Every mod in `dir`, by name (the order the runtime loads them in), the one on first when a +/// name is there twice. A folder that does not exist has none. +pub(crate) fn list(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut mods: Vec = entries + .flatten() + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + let (file, on) = parse_name(&name)?; + let bytes = entry.metadata().map(|m| m.len()).unwrap_or(0); + Some(Mod { + file, + entry: name, + on, + bytes, + }) + }) + .collect(); + mods.sort_by(|a, b| a.file.cmp(&b.file).then(b.on.cmp(&a.on))); + mods +} + +/// A plain file name of a DLL: no folder, no `..`, ends in `.dll`. +fn checked_name(file: &str) -> Result<&str, String> { + let plain = !file.is_empty() + && !file.contains(['/', '\\', ':']) + && file != "." + && file != ".." + && Path::new(file).file_name().is_some_and(|name| name == file); + if !plain || !file.to_ascii_lowercase().ends_with(".dll") || file.len() <= 4 { + return Err(msg!("{file} is not the name of a mod DLL.")); + } + Ok(file) +} + +/// Whether a mod named `file` is in `dir`, on or off. +fn present(dir: &Path, file: &str) -> bool { + dir.join(file).is_file() || dir.join(format!("{file}{OFF}")).is_file() +} + +/// A folder entry the window names (`x.dll` or `x.dll.off`): its DLL name, whether it is on, +/// and its path. Err for a name with a folder in it, another kind of file, or one not there. +fn checked_entry(dir: &Path, entry: &str) -> Result<(String, bool, PathBuf), String> { + let parsed = parse_name(entry).filter(|(file, _)| checked_name(file).is_ok()); + let Some((file, on)) = parsed else { + return Err(msg!("{file} is not the name of a mod DLL.", file = entry)); + }; + let path = dir.join(entry); + if !path.is_file() { + return Err(msg!("The mod {file} is not in the mods folder.")); + } + Ok((file, on, path)) +} + +/// Turns the mod at folder entry `entry` on or off. Nothing changes when it already is. +pub(crate) fn set_on(dir: &Path, entry: &str, on: bool) -> Result<(), String> { + let (file, is_on, path) = checked_entry(dir, entry)?; + if is_on == on { + return Ok(()); + } + let to = if on { + dir.join(&file) + } else { + dir.join(format!("{file}{OFF}")) + }; + if to.exists() { + return Err(msg!( + "{file} is in the mods folder twice (on and off): remove one." + )); + } + std::fs::rename(&path, &to).map_err(|e| msg!("Could not rename {file}: {e}")) +} + +/// Copies the DLL at `source` into `dir`, on. Refuses another file kind, and a name already +/// there (on or off), so a mod is never overwritten. Returns the name it has there. +pub(crate) fn add(dir: &Path, source: &Path) -> Result { + let file = source + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + checked_name(&file)?; + if !source.is_file() { + return Err(msg!("{file} is not a file.")); + } + if present(dir, &file) { + return Err(msg!("A mod named {file} is already in the mods folder.")); + } + std::fs::create_dir_all(dir).map_err(|e| msg!("Could not make the mods folder: {e}"))?; + std::fs::copy(source, dir.join(&file)).map_err(|e| msg!("Could not copy {file}: {e}"))?; + Ok(file) +} + +/// Deletes the folder entry `entry` (a mod, on or off) from `dir`. +pub(crate) fn remove(dir: &Path, entry: &str) -> Result<(), String> { + let (file, _, path) = checked_entry(dir, entry)?; + std::fs::remove_file(&path).map_err(|e| msg!("Could not remove {file}: {e}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("vilauncher-mods-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn one(file: &str, entry: &str, on: bool, bytes: u64) -> Mod { + Mod { + file: file.into(), + entry: entry.into(), + on, + bytes, + } + } + + #[test] + fn lists_on_and_off_mods_by_name_and_nothing_else() { + let dir = temp("list"); + std::fs::write(dir.join("b.dll"), b"bb").unwrap(); + std::fs::write(dir.join("A.DLL.off"), b"a").unwrap(); + std::fs::write(dir.join("notes.txt"), b"").unwrap(); + std::fs::write(dir.join(".dll"), b"").unwrap(); + std::fs::create_dir(dir.join("folder.dll")).unwrap(); + assert_eq!( + list(&dir), + vec![ + one("A.DLL", "A.DLL.off", false, 1), + one("b.dll", "b.dll", true, 2) + ] + ); + assert!(list(&dir.join("missing")).is_empty()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn turning_off_renames_so_the_runtime_skips_it_and_on_brings_it_back() { + let dir = temp("toggle"); + std::fs::write(dir.join("x.dll"), b"x").unwrap(); + set_on(&dir, "x.dll", false).unwrap(); + assert!(!dir.join("x.dll").exists() && dir.join("x.dll.off").is_file()); + // The runtime loads files whose extension is dll: this one's is "off". + assert_eq!(Path::new("x.dll.off").extension().unwrap(), "off"); + set_on(&dir, "x.dll.off", false).unwrap(); + set_on(&dir, "x.dll.off", true).unwrap(); + assert!(dir.join("x.dll").is_file() && !dir.join("x.dll.off").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_mod_there_on_and_off_is_two_rows_each_acting_on_its_own_file() { + let dir = temp("twice"); + std::fs::write(dir.join("x.dll"), b"new").unwrap(); + std::fs::write(dir.join("x.dll.off"), b"old").unwrap(); + let rows = list(&dir); + assert_eq!( + rows, + vec![ + one("x.dll", "x.dll", true, 3), + one("x.dll", "x.dll.off", false, 3) + ] + ); + // Neither copy overwrites the other. + assert!(set_on(&dir, "x.dll.off", true).is_err()); + assert!(set_on(&dir, "x.dll", false).is_err()); + // Removing the off row removes the off copy, never the one that loads. + remove(&dir, "x.dll.off").unwrap(); + assert_eq!(std::fs::read(dir.join("x.dll")).unwrap(), b"new"); + assert!(!dir.join("x.dll.off").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn adds_a_dll_without_overwriting_and_removes_it() { + let dir = temp("add"); + let from = temp("add-source"); + std::fs::write(from.join("m.dll"), b"mod").unwrap(); + std::fs::write(from.join("m.exe"), b"no").unwrap(); + let mods = dir.join("mods"); + assert_eq!(add(&mods, &from.join("m.dll")).unwrap(), "m.dll"); + assert_eq!(std::fs::read(mods.join("m.dll")).unwrap(), b"mod"); + assert!(add(&mods, &from.join("m.dll")).is_err(), "already there"); + set_on(&mods, "m.dll", false).unwrap(); + assert!( + add(&mods, &from.join("m.dll")).is_err(), + "already there, off" + ); + assert!(add(&mods, &from.join("m.exe")).is_err(), "not a DLL"); + remove(&mods, "m.dll.off").unwrap(); + assert!(list(&mods).is_empty()); + assert!(remove(&mods, "m.dll").is_err()); + std::fs::remove_dir_all(dir).unwrap(); + std::fs::remove_dir_all(from).unwrap(); + } + + #[test] + fn names_with_folders_are_refused() { + let dir = temp("names"); + std::fs::create_dir(dir.join("sub")).unwrap(); + std::fs::write(dir.join("sub").join("x.dll"), b"x").unwrap(); + for bad in [ + "../x.dll", + "sub/x.dll", + "sub\\x.dll", + "C:x.dll", + "x.exe", + ".dll", + ".dll.off", + "", + ] { + assert!(set_on(&dir, bad, false).is_err(), "{bad}"); + assert!(remove(&dir, bad).is_err(), "{bad}"); + } + assert!(dir.join("sub").join("x.dll").is_file()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn tests_never_see_the_players_own_folder() { + assert!(folder().is_none()); + } +} diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 2316c64..69b3beb 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -6,22 +6,6 @@ import { isLocale, systemLocale } from "@/i18n/locales" import type { Action, AddonView, Graphics, LogView, MacRunner, MacRunnerChoice, Project, ResponsibilityId, Snapshot, StageKind, StorageView } from "@/lib/types" -// The controls VIctory reads from the keyboard, as src-tauri/src/controller_keys.rs lists them. -const CONTROLLER_CONTROLS: { id: string; label: string; default_key: number }[] = [ - { id: "menu", label: "Menu", default_key: 0x1b }, { id: "view", label: "View", default_key: 0x09 }, - { id: "a", label: "A", default_key: 0x0d }, { id: "b", label: "B", default_key: 0x08 }, - { id: "x", label: "X", default_key: 0x58 }, { id: "y", label: "Y", default_key: 0x59 }, - { id: "up", label: "D-pad up", default_key: 0x26 }, { id: "down", label: "D-pad down", default_key: 0x28 }, - { id: "left", label: "D-pad left", default_key: 0x25 }, { id: "right", label: "D-pad right", default_key: 0x27 }, - { id: "left_shoulder", label: "Left shoulder", default_key: 0x51 }, { id: "right_shoulder", label: "Right shoulder", default_key: 0x45 }, - { id: "left_stick_click", label: "Left stick click", default_key: 0x46 }, { id: "right_stick_click", label: "Right stick click", default_key: 0x48 }, - { id: "left_stick_up", label: "Left stick up", default_key: 0x57 }, { id: "left_stick_left", label: "Left stick left", default_key: 0x41 }, - { id: "left_stick_down", label: "Left stick down", default_key: 0x53 }, { id: "left_stick_right", label: "Left stick right", default_key: 0x44 }, - { id: "right_stick_up", label: "Right stick up", default_key: 0x49 }, { id: "right_stick_left", label: "Right stick left", default_key: 0x4a }, - { id: "right_stick_down", label: "Right stick down", default_key: 0x4b }, { id: "right_stick_right", label: "Right stick right", default_key: 0x4c }, - { id: "left_trigger", label: "Left trigger", default_key: 0x5a }, { id: "right_trigger", label: "Right trigger", default_key: 0x43 }, -] - const SAMPLE: { name: string; repo: string; gpu: string[]; fps: number | null; render: number | null; verified: boolean; summary: string }[] = [{"name":"Kelvaroq","repo":"stellarr-studio/kelvaroq","gpu":["NVIDIA"],"fps":10,"render":0.25,"verified":false,"summary":"Kelvaroq is a public Rust runtime built on VIctory and victory-fork. It adds rendering patches and measured submission improvements, and runs the game through the prologue and first mission."},{"name":"Belobug","repo":"Belobug/VIctory-Belobug-AMD","gpu":["AMD"],"fps":22,"render":0.8,"verified":true,"summary":"Belobug's VIctory fork runs on AMD Radeon and is now very playable: about 22 fps on average with no crashes, using about 30 GB of RAM and 12 GB of video memory. Its lit open world plays through missions, with story progress rated 80%, level with CGBJ, and its picture is rated just below DexNom's. Its README hasn't caught up yet: it still reports 5-7 fps."},{"name":"DexNom","repo":"DexNom/VIctory","gpu":["AMD"],"fps":3,"render":0.85,"verified":true,"summary":"DexNom Runtime, a fork of VIctory for AMD Radeon, tested on a Radeon RX 7900 XTX. It builds on ZSlayerHQ's victory-world-runtime with its own fixes for shaders, texture streaming and GPU memory. PortWatch has seen it running with ray-traced lighting working, the first AMD build on our board to get it. Its picture is the best-rated on our board, though lighting and materials still have problems, and it plays through missions at about 3-4 fps (about 1 fps with ray tracing on), rarely crashing."},{"name":"Uilian","repo":"uiliannn/VItoriaBr","gpu":["NVIDIA"],"fps":4,"render":0.2,"verified":false,"summary":"Uilian's VItoriaBr, built on hyphennn's victory-fork with his own NVIDIA work and streamed live on YouTube. On stream it reaches Jason's first mission, \"Gone Fishing\", with poor rendering, up to 4 fps and few crashes."},{"name":"AvatarManz","repo":"avatarmanz/VIctory-7900XTX","gpu":["AMD"],"fps":16,"render":0.7,"verified":true,"summary":"AvatarManz's fork of VIctory, tuned for speed on an AMD Radeon RX 7900 XTX. It brings victory-fork's, DexNom's and Belobug's work together on VIctory and adds its own speed-ups: the game's draw calls translated on eight threads of its own, frames prepared on a separate thread, and textures uploaded on their own queue. PortWatch has verified it: the game runs at about 16 fps on average in game, with sound, as far into the story as the leading builds. Its README measures 13-22 fps indoors and on the first boat mission, and a 41-minute session without a crash."},{"name":"hyphennn","repo":"fxceless/victory-fork","gpu":["NVIDIA"],"fps":3,"render":0.7,"verified":false,"summary":"hyphennn's fork of VIctory (formerly victory-gta6), with his own rendering and speed fixes. On his Rumble streams the prologue plays with ray-traced lighting, detailed textures and hair at about 3 fps; the README still lists shadows as black. Self-reported."},{"name":"VIctory","repo":"Marvisak/VIctory","gpu":["AMD"],"fps":1,"render":0,"verified":false,"summary":"Marvis's Rust layer runs the game natively. The owner reports controlled gameplay is now reachable, though the build remains unstable; the README still says it is not playable and reports about 1 fps in the world."},{"name":"xbox-emulator","repo":"omonkeyz/xbox-emulator","gpu":[],"fps":0,"render":0,"verified":false,"summary":"Rust runtime that runs dumped Xbox Series builds as normal Windows processes, continuing the TomBox project. It reports Trackmania races driving at about 60 fps and Terraria reaching its world, plus Fortnite's lobby. Self-reported."},{"name":"XCL","repo":"xcl-dev/xcl","gpu":["AMD","NVIDIA"],"fps":0,"render":0,"verified":false,"summary":"Wine-style layer running game code natively. On its main branch the game gets past its menus into the world for several testers, but the screen stays on a loading spinner and a GPU watchdog ends the run. Unverified."},{"name":"ScarlettX","repo":"Freminet/ScarlettX","gpu":[],"fps":0,"render":0,"verified":false,"summary":"Clean-room high-level emulator of the Scarlett OS and GDK runtime. It reports two retail Xbox Series games, Concept Destruction and Unicorn Overlord, playable on Windows."},{"name":"TuxBox","repo":"brcly/TuxBox","gpu":["NVIDIA"],"fps":0,"render":0,"verified":false,"summary":"Native-first layer for unpacked Xbox Series games, tested mostly on Linux through Proton. the game reported its own state as \"Game Running\" in the story intro before crashing after about ten minutes, but no picture past the player-selection prompt is shown. Self-reported."},{"name":"OpenScarlett","repo":"californiaAlmonds/OpenScarlett","gpu":["NVIDIA","Intel"],"fps":0,"render":0,"verified":false,"summary":"MIT-licensed C++20 translation layer targeting D3D12 and Vulkan. It now claims 17 boot stops cleared on a retail title it doesn't name, with no run record or frame shown, so no the game milestone yet."},{"name":"scarlett-layer","repo":"jadeowaowa/scarlett-layer","gpu":["NVIDIA"],"fps":0,"render":0,"verified":false,"summary":"Loader plus injected hook DLL that redirects console-only calls to Windows shims, with its own d3d12_xs wrapper and shader lifter. It reports Terraria's GDK build rendering its menus with audio; no gameplay yet."},{"name":"Xbox2Windows","repo":"R0Y00/Xbox2Windows","gpu":["NVIDIA","AMD","Intel"],"fps":0,"render":0,"verified":false,"summary":"Static recompilation research turning Xbox Series code and shaders into Windows C++ and DXIL, with over 50 contributors. Footage the project shared shows the game's menus, unstable. Its README now reports a modified diagnostic exe playing the intro and setup text; the original exe and the menus remain unverified."}] const params = new URLSearchParams(location.search) @@ -57,8 +41,13 @@ const state = { notice: params.get("notice") !== "0", skipUpdateWarning: false, agentAccess: false, - controllerKeysOn: false, - controllerBindings: {} as Record, + // VIctory-NVIDIA's mods folder, by name there: "x.dll" on, "x.dll.off" off (?mods=0: empty). + mods: (params.get("mods") === "0" + ? [] + : [ + { entry: "fps-overlay.dll", bytes: 412_160 }, + { entry: "photo-mode.dll.off", bytes: 1_284_096 }, + ]) as { entry: string; bytes: number }[], acknowledged: [] as ResponsibilityId[], macRunner: { kind: "none", bottle: "", wine: "", prefix: "", metalfx: false, streamline_dir: "" } as MacRunnerChoice, // ?lang=zh-TW starts in that language, as if the player had chosen it. @@ -173,10 +162,17 @@ function snapshot(): Snapshot { : "C:\\Users\\you\\AppData\\Local\\VILauncher\\backgrounds", skip_update_warning: state.skipUpdateWarning, agent_access: state.agentAccess, - controller_keys: { - on: state.controllerKeysOn, - controls: CONTROLLER_CONTROLS.map((c) => ({ ...c, key: state.controllerBindings[c.id] ?? c.default_key })), - }, + // As the launcher: the mods folder is a Windows one. + mods: + platform !== "windows" + ? null + : { + folder: "C:\\Users\\you\\AppData\\Local\\victory\\mods", + items: state.mods + .map((m) => ({ file: m.entry.replace(/\.off$/i, ""), entry: m.entry, on: !/\.off$/i.test(m.entry), bytes: m.bytes })) + .sort((a, b) => a.file.localeCompare(b.file) || Number(b.on) - Number(a.on)), + bindings: true, + }, acknowledged: state.acknowledged, language: state.language, }, @@ -382,22 +378,28 @@ async function act(a: Action): Promise { case "set_agent_access": state.agentAccess = a.enabled break - case "set_controller_keys": - state.controllerKeysOn = a.on - break - case "set_controller_key": { - const control = CONTROLLER_CONTROLS.find((c) => c.id === a.control) - if (!control) throw new Error(`There is no controller control ${a.control}.`) - if (a.key === null) { - delete state.controllerBindings[a.control] - break - } - if (a.key === 0 || a.key === 0xff) throw new Error("That key cannot be used for a controller control.") - const other = CONTROLLER_CONTROLS.find((c) => c.id !== a.control && (state.controllerBindings[c.id] ?? c.default_key) === a.key) - if (other) throw new Error(`${other.label} already uses that key.`) - state.controllerBindings[a.control] = a.key + case "mod_add": { + const file = a.path.split(/[\\/]/).pop() ?? "" + if (!/\.dll$/i.test(file) || file.length <= 4) throw new Error(`${file} is not the name of a mod DLL.`) + const taken = (name: string) => state.mods.some((m) => m.entry.toLowerCase() === name.toLowerCase()) + if (taken(file) || taken(`${file}.off`)) throw new Error(`A mod named ${file} is already in the mods folder.`) + state.mods = [...state.mods, { entry: file, bytes: 256_000 }] + return file + } + case "mod_set_on": { + const mod = state.mods.find((m) => m.entry === a.entry) + if (!mod) throw new Error(`The mod ${a.entry} is not in the mods folder.`) + const file = mod.entry.replace(/\.off$/i, "") + const to = a.on ? file : `${file}.off` + if (to === mod.entry) break + if (state.mods.some((m) => m.entry.toLowerCase() === to.toLowerCase())) throw new Error(`${file} is in the mods folder twice (on and off): remove one.`) + mod.entry = to break } + case "mod_remove": + if (!state.mods.some((m) => m.entry === a.entry)) throw new Error(`The mod ${a.entry} is not in the mods folder.`) + state.mods = state.mods.filter((m) => m.entry !== a.entry) + break case "acknowledge": if (!state.acknowledged.includes(a.id)) state.acknowledged = [...state.acknowledged, a.id] break diff --git a/src/features/settings/controller-keys.tsx b/src/features/settings/controller-keys.tsx deleted file mode 100644 index bfb7328..0000000 --- a/src/features/settings/controller-keys.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { useEffect, useState } from "react" -import { Button } from "@/components/ui/button" -import { Group, Row } from "@/components/ui/group" -import { Switch } from "@/components/ui/switch" -import { useT } from "@/i18n" -import { run, useStore } from "@/lib/store" -import type { ControllerControl } from "@/lib/types" - -/** The controls VIctory reads from the keyboard (src-tauri/src/controller_keys.rs), by id. */ -const CONTROL_IDS = [ - "menu", "view", "a", "b", "x", "y", "up", "down", "left", "right", - "left_shoulder", "right_shoulder", "left_stick_click", "right_stick_click", - "left_stick_up", "left_stick_left", "left_stick_down", "left_stick_right", - "right_stick_up", "right_stick_left", "right_stick_down", "right_stick_right", - "left_trigger", "right_trigger", -] as const -type ControlId = (typeof CONTROL_IDS)[number] - -const ESCAPE = 27 -/** Pressed alone, these do not choose a key. */ -const MODIFIERS = [16, 17, 18, 91, 92] -/** Keys whose names are printed on the keyboard, not translated. */ -const NAMED: Record = { 8: "Backspace", 9: "Tab", 13: "Enter", 32: "Space", 37: "←", 38: "↑", 39: "→", 40: "↓" } - -/** Virtual-key codes VIctory reads: letters and digits are their own character. */ -function isLetterOrDigit(code: number): boolean { - return (code >= 0x30 && code <= 0x39) || (code >= 0x41 && code <= 0x5a) -} - -export function ControllerKeysGroup() { - const t = useT() - const keys = useStore((s) => s.snap)!.settings.controller_keys - const [capturing, setCapturing] = useState(null) - - // While a control waits for its key, the next key press is the choice (Esc cancels). - useEffect(() => { - if (capturing === null) return - const onKey = (event: KeyboardEvent) => { - if (MODIFIERS.includes(event.keyCode)) return - event.preventDefault() - event.stopPropagation() - const id = capturing - setCapturing(null) - if (event.keyCode !== ESCAPE) void run({ type: "set_controller_key", control: id, key: event.keyCode }) - } - window.addEventListener("keydown", onKey, true) - return () => window.removeEventListener("keydown", onKey, true) - }, [capturing]) - - const keyLabel = (code: number) => { - if (NAMED[code]) return NAMED[code] - if (isLetterOrDigit(code)) return String.fromCharCode(code) - return t("settings.controllerKeys.unknownKey", { code: String(code) }) - } - const controlLabel = (control: ControllerControl) => { - const id = control.id as ControlId - return CONTROL_IDS.includes(id) ? t(`settings.controllerKeys.controls.${id}`) : control.label - } - const changed = keys.controls.filter((control) => control.key !== control.default_key) - - return ( - 0 ? ( - - ) : undefined - } - > - - void run({ type: "set_controller_keys", on })} - aria-label={t("settings.controllerKeys.on")} - /> - - {keys.controls.map((control) => ( - - {keyLabel(control.key)} - - {control.key !== control.default_key && ( - - )} - - ))} - - ) -} diff --git a/src/features/settings/mods.tsx b/src/features/settings/mods.tsx new file mode 100644 index 0000000..3adb9af --- /dev/null +++ b/src/features/settings/mods.tsx @@ -0,0 +1,94 @@ +import { useState } from "react" +import { toast } from "sonner" +import { FileText, FolderOpen, Plus, Trash2 } from "lucide-react" +import { Button } from "@/components/ui/button" +import { Group, Row } from "@/components/ui/group" +import { Switch } from "@/components/ui/switch" +import { formatBytes, useT } from "@/i18n" +import { pickFile } from "@/lib/api" +import { run, useStore } from "@/lib/store" + +/** + * VIctory-NVIDIA's mods folder (src-tauri/src/mods.rs): every DLL in it loads at each start. + * Off renames a mod so the game skips it; remove asks once in the row. Below, where the + * game's own mouse and keyboard controls are, which replaced the launcher's keyboard hook. + */ +export function ModsGroups() { + const t = useT() + const mods = useStore((s) => s.snap)!.settings.mods + const [removing, setRemoving] = useState(null) + if (!mods) return null + + const add = async () => { + const path = await pickFile(t("settings.mods.pickTitle"), [{ name: t("settings.mods.filterName"), extensions: ["dll"] }]) + if (!path) return + const file = await run({ type: "mod_add", path }) + if (file) toast.success(t("settings.mods.added", { file })) + } + + return ( + <> + void add()}> + {t("settings.mods.add")} + + } + > + {mods.folder}}> + + + {mods.items.length === 0 && {t("settings.mods.empty")}} />} + {mods.items.map((mod) => ( + {mod.file}} + hint={mod.on ? formatBytes(mod.bytes) : `${formatBytes(mod.bytes)} · ${t("settings.mods.offHint")}`} + > + {removing === mod.entry ? ( + <> + + + + ) : ( + <> + + void run({ type: "mod_set_on", entry: mod.entry, on })} + aria-label={t("settings.mods.load", { file: mod.file })} + /> + + )} + + ))} + +

{t("settings.mods.warning")}

+ + + + + + + + ) +} diff --git a/src/features/settings/settings-view.tsx b/src/features/settings/settings-view.tsx index 822df60..fa905e8 100644 --- a/src/features/settings/settings-view.tsx +++ b/src/features/settings/settings-view.tsx @@ -7,7 +7,7 @@ import { Input, Textarea } from "@/components/ui/input" import { Spinner } from "@/components/ui/spinner" import { Switch } from "@/components/ui/switch" import { GraphicsGroups } from "@/features/library/graphics-tab" -import { ControllerKeysGroup } from "@/features/settings/controller-keys" +import { ModsGroups } from "@/features/settings/mods" import { MacRunnerGroup, MetalfxRows } from "@/features/settings/mac-runner" import { LanguageSelect } from "@/features/shared/language-select" import { ResponsibilityDialog } from "@/features/shared/responsibility" @@ -191,7 +191,8 @@ export function SettingsView() { )} - + {/* VIctory-NVIDIA's mods folder and controls: a Windows folder, so none elsewhere. */} + diff --git a/src/i18n/messages/en/settings.ts b/src/i18n/messages/en/settings.ts index cb01238..d3451b5 100644 --- a/src/i18n/messages/en/settings.ts +++ b/src/i18n/messages/en/settings.ts @@ -134,26 +134,28 @@ export default { access: "Let AI agents help with builds", hint: "Off by default. Agents can read logs and, when you confirm, apply patches. See the README section 'Agent tools'.", }, - controllerKeys: { - title: "Controller keys", - description: "VIctory reads a controller from the keyboard when no controller is plugged in. Give any of its controls another key here.", - on: "Use the keyboard as a controller", - onHint: "Off by default. A keyboard hook runs only while victory.exe is in front, and sends the game's own key for the control whose key you press.", - change: "Change", - press: "Press a key, or Esc to cancel", - reset: "Reset", - resetAll: "Reset all", - keyDefault: "Default: {key}", - unknownKey: "Key {code}", - controls: { - menu: "Menu", view: "View", a: "A", b: "B", x: "X", y: "Y", - up: "D-pad up", down: "D-pad down", left: "D-pad left", right: "D-pad right", - left_shoulder: "Left shoulder", right_shoulder: "Right shoulder", - left_stick_click: "Left stick click", right_stick_click: "Right stick click", - left_stick_up: "Left stick up", left_stick_left: "Left stick left", left_stick_down: "Left stick down", left_stick_right: "Left stick right", - right_stick_up: "Right stick up", right_stick_left: "Right stick left", right_stick_down: "Right stick down", right_stick_right: "Right stick right", - left_trigger: "Left trigger", right_trigger: "Right trigger", - }, + mods: { + title: "Mods & controls", + description: "VIctory-NVIDIA (v2026.11.29.01 and later) loads every DLL in its mods folder at each start, before the game runs. Every build of it shares this folder.", + warning: "A mod is a program that runs inside the game with your rights. Only add DLLs from people you trust.", + folder: "Mods folder", + add: "Add a mod…", + pickTitle: "Choose a mod DLL", + filterName: "Mod DLL", + added: "{file} added. It loads at the next start.", + empty: "No mods yet. Add a DLL, or put one in the folder.", + load: "Load {file}", + offHint: "Off: kept in the folder, not loaded.", + remove: "Remove", + removeConfirm: "Remove {file}", + keep: "Keep", + removed: "{file} removed.", + controlsTitle: "Mouse, keyboard and controllers", + controlsDescription: "The game now reads controllers itself, generic USB pads too beside Xbox and PlayStation ones, and has its own mouse and keyboard controls, so the launcher's keyboard-as-controller keys are gone.", + mnk: "Mouse and keyboard", + mnkHint: "Turn it on in the game: press F1, then MOUSE AND KEYBOARD. Its keys are in bindings.ini, and KEY BINDINGS in the same menu changes them while you play.", + openBindings: "Show bindings.ini", + noBindings: "bindings.ini is written the first time mouse and keyboard is on.", }, updates: { title: "Updates", diff --git a/src/i18n/messages/es/settings.ts b/src/i18n/messages/es/settings.ts index df12b67..90b37ea 100644 --- a/src/i18n/messages/es/settings.ts +++ b/src/i18n/messages/es/settings.ts @@ -136,26 +136,28 @@ export default { access: "Permitir que agentes IA ayuden con las compilaciones", hint: "Desactivado por defecto. Los agentes pueden leer registros y, cuando confirmes, aplicar parches. Consulta la sección 'Agent tools' del README.", }, - controllerKeys: { - title: "Teclas de mando", - description: "VIctory lee un mando desde el teclado cuando no hay ningún mando conectado. Asigna aquí otra tecla a cualquiera de sus controles.", - on: "Usar el teclado como mando", - onHint: "Desactivado por defecto. Un hook de teclado solo se ejecuta mientras victory.exe esté en primer plano y envía la tecla propia del juego para el control cuya tecla pulses.", - change: "Cambiar", - press: "Pulsa una tecla, o Esc para cancelar", - reset: "Restablecer", - resetAll: "Restablecer todo", - keyDefault: "Predeterminada: {key}", - unknownKey: "Tecla {code}", - controls: { - menu: "Menú", view: "Vista", a: "A", b: "B", x: "X", y: "Y", - up: "Cruceta arriba", down: "Cruceta abajo", left: "Cruceta izquierda", right: "Cruceta derecha", - left_shoulder: "Botón superior izquierdo", right_shoulder: "Botón superior derecho", - left_stick_click: "Clic stick izquierdo", right_stick_click: "Clic stick derecho", - left_stick_up: "Stick izquierdo arriba", left_stick_left: "Stick izquierdo izquierda", left_stick_down: "Stick izquierdo abajo", left_stick_right: "Stick izquierdo derecha", - right_stick_up: "Stick derecho arriba", right_stick_left: "Stick derecho izquierda", right_stick_down: "Stick derecho abajo", right_stick_right: "Stick derecho derecha", - left_trigger: "Gatillo izquierdo", right_trigger: "Gatillo derecho", - }, + mods: { + title: "Mods y controles", + description: "VIctory-NVIDIA (v2026.11.29.01 y posteriores) carga cada DLL de su carpeta de mods en cada inicio, antes de que corra el juego. Todas sus compilaciones comparten esta carpeta.", + warning: "Un mod es un programa que corre dentro del juego con tus permisos. Añade solo DLL de personas en las que confíes.", + folder: "Carpeta de mods", + add: "Añadir un mod…", + pickTitle: "Elige una DLL de mod", + filterName: "DLL de mod", + added: "{file} añadido. Se carga en el próximo inicio.", + empty: "Aún no hay mods. Añade una DLL o pon una en la carpeta.", + load: "Cargar {file}", + offHint: "Desactivado: se guarda en la carpeta, no se carga.", + remove: "Quitar", + removeConfirm: "Quitar {file}", + keep: "Conservar", + removed: "{file} quitado.", + controlsTitle: "Ratón, teclado y mandos", + controlsDescription: "El juego ahora lee los mandos por sí mismo, también los mandos USB genéricos además de los de Xbox y PlayStation, y tiene sus propios controles de ratón y teclado, así que las teclas de teclado como mando del launcher ya no están.", + mnk: "Ratón y teclado", + mnkHint: "Actívalo en el juego: pulsa F1 y luego MOUSE AND KEYBOARD. Sus teclas están en bindings.ini, y KEY BINDINGS en el mismo menú las cambia mientras juegas.", + openBindings: "Mostrar bindings.ini", + noBindings: "bindings.ini se escribe la primera vez que se activan el ratón y el teclado.", }, updates: { title: "Actualizaciones", diff --git a/src/i18n/messages/fr/settings.ts b/src/i18n/messages/fr/settings.ts index f8608ea..71403c8 100644 --- a/src/i18n/messages/fr/settings.ts +++ b/src/i18n/messages/fr/settings.ts @@ -100,26 +100,28 @@ export default { access: "Laisser les agents IA aider pour les builds", hint: "Désactivé par défaut. Les agents peuvent lire les journaux et, avec votre confirmation, appliquer des correctifs. Voir la section « Agent tools » du README.", }, - controllerKeys: { - title: "Touches de manette", - description: "VIctory lit une manette depuis le clavier quand aucune manette n’est branchée. Donnez ici une autre touche à n’importe laquelle de ses commandes.", - on: "Utiliser le clavier comme manette", - onHint: "Désactivé par défaut. Un hook clavier ne s’exécute que lorsque victory.exe est au premier plan, et envoie la touche propre au jeu pour la commande dont vous appuyez sur la touche.", - change: "Modifier", - press: "Appuyez sur une touche, ou sur Échap pour annuler", - reset: "Réinitialiser", - resetAll: "Tout réinitialiser", - keyDefault: "Par défaut : {key}", - unknownKey: "Touche {code}", - controls: { - menu: "Menu", view: "Vue", a: "A", b: "B", x: "X", y: "Y", - up: "Croix directionnelle haut", down: "Croix directionnelle bas", left: "Croix directionnelle gauche", right: "Croix directionnelle droite", - left_shoulder: "Bumper gauche", right_shoulder: "Bumper droit", - left_stick_click: "Clic du stick gauche", right_stick_click: "Clic du stick droit", - left_stick_up: "Stick gauche haut", left_stick_left: "Stick gauche gauche", left_stick_down: "Stick gauche bas", left_stick_right: "Stick gauche droite", - right_stick_up: "Stick droit haut", right_stick_left: "Stick droit gauche", right_stick_down: "Stick droit bas", right_stick_right: "Stick droit droite", - left_trigger: "Gâchette gauche", right_trigger: "Gâchette droite", - }, + mods: { + title: "Mods et commandes", + description: "VIctory-NVIDIA (v2026.11.29.01 et suivantes) charge chaque DLL de son dossier de mods à chaque démarrage, avant que le jeu ne tourne. Toutes ses versions partagent ce dossier.", + warning: "Un mod est un programme qui tourne dans le jeu avec vos droits. N’ajoutez que des DLL de personnes en qui vous avez confiance.", + folder: "Dossier des mods", + add: "Ajouter un mod…", + pickTitle: "Choisir une DLL de mod", + filterName: "DLL de mod", + added: "{file} ajouté. Il se charge au prochain démarrage.", + empty: "Aucun mod pour l’instant. Ajoutez une DLL, ou placez-en une dans le dossier.", + load: "Charger {file}", + offHint: "Désactivé : gardé dans le dossier, non chargé.", + remove: "Supprimer", + removeConfirm: "Supprimer {file}", + keep: "Garder", + removed: "{file} supprimé.", + controlsTitle: "Souris, clavier et manettes", + controlsDescription: "Le jeu lit désormais les manettes lui-même, y compris les manettes USB génériques à côté des Xbox et PlayStation, et a ses propres commandes souris et clavier : les touches clavier-manette du lanceur ont donc disparu.", + mnk: "Souris et clavier", + mnkHint: "Activez-les dans le jeu : appuyez sur F1, puis MOUSE AND KEYBOARD. Les touches sont dans bindings.ini, et KEY BINDINGS dans le même menu les change pendant la partie.", + openBindings: "Afficher bindings.ini", + noBindings: "bindings.ini est écrit la première fois que la souris et le clavier sont activés.", }, updates: { title: "Mises à jour", diff --git a/src/i18n/messages/ru/settings.ts b/src/i18n/messages/ru/settings.ts index 80fb15b..f942b9e 100644 --- a/src/i18n/messages/ru/settings.ts +++ b/src/i18n/messages/ru/settings.ts @@ -134,26 +134,28 @@ export default { access: "Разрешить ИИ-агентам помогать со сборками", hint: "По умолчанию выключено. Агенты могут читать журналы и с вашего подтверждения применять патчи. См. раздел «Agent tools» в README.", }, - controllerKeys: { - title: "Клавиши контроллера", - description: "VIctory эмулирует контроллер с клавиатуры, когда геймпад не подключён. Здесь можно переназначить любую кнопку.", - on: "Использовать клавиатуру как контроллер", - onHint: "По умолчанию выключено. Перехват клавиш работает только когда окно victory.exe активно, и передаёт игре соответствующую кнопку контроллера.", - change: "Изменить", - press: "Нажмите клавишу или Esc для отмены", - reset: "Сбросить", - resetAll: "Сбросить все", - keyDefault: "По умолчанию: {key}", - unknownKey: "Клавиша {code}", - controls: { - menu: "Menu", view: "View", a: "A", b: "B", x: "X", y: "Y", - up: "Крестовина вверх", down: "Крестовина вниз", left: "Крестовина влево", right: "Крестовина вправо", - left_shoulder: "Левый бампер (LB)", right_shoulder: "Правый бампер (RB)", - left_stick_click: "Нажатие левого стика", right_stick_click: "Нажатие правого стика", - left_stick_up: "Левый стик вверх", left_stick_left: "Левый стик влево", left_stick_down: "Левый стик вниз", left_stick_right: "Левый стик вправо", - right_stick_up: "Правый стик вверх", right_stick_left: "Правый стик влево", right_stick_down: "Правый стик вниз", right_stick_right: "Правый стик вправо", - left_trigger: "Левый триггер (LT)", right_trigger: "Правый триггер (RT)", - }, + mods: { + title: "Моды и управление", + description: "VIctory-NVIDIA (v2026.11.29.01 и новее) при каждом запуске загружает все DLL из своей папки модов, до запуска игры. Эту папку используют все её сборки.", + warning: "Мод — это программа, которая работает внутри игры с вашими правами. Добавляйте только DLL от тех, кому доверяете.", + folder: "Папка модов", + add: "Добавить мод…", + pickTitle: "Выберите DLL мода", + filterName: "DLL мода", + added: "{file} добавлен. Он загрузится при следующем запуске.", + empty: "Модов пока нет. Добавьте DLL или положите её в папку.", + load: "Загружать {file}", + offHint: "Выключен: остаётся в папке, но не загружается.", + remove: "Удалить", + removeConfirm: "Удалить {file}", + keep: "Оставить", + removed: "{file} удалён.", + controlsTitle: "Мышь, клавиатура и геймпады", + controlsDescription: "Теперь игра сама читает геймпады, в том числе обычные USB-геймпады наряду с Xbox и PlayStation, и имеет собственное управление мышью и клавиатурой, поэтому клавиши «клавиатура как геймпад» из лаунчера убраны.", + mnk: "Мышь и клавиатура", + mnkHint: "Включите в игре: нажмите F1, затем MOUSE AND KEYBOARD. Клавиши хранятся в bindings.ini, а KEY BINDINGS в том же меню меняет их прямо во время игры.", + openBindings: "Показать bindings.ini", + noBindings: "bindings.ini создаётся при первом включении мыши и клавиатуры.", }, updates: { title: "Обновления", diff --git a/src/i18n/messages/zh-CN/settings.ts b/src/i18n/messages/zh-CN/settings.ts index fe22814..7aeb9e9 100644 --- a/src/i18n/messages/zh-CN/settings.ts +++ b/src/i18n/messages/zh-CN/settings.ts @@ -136,26 +136,28 @@ export default { access: "让 AI 代理协助构建", hint: "默认关闭。代理可以读取日志,并在你确认后应用补丁。请参阅 README 的“Agent tools”一节。", }, - controllerKeys: { - title: "控制器按键", - description: "没有接上控制器时,VIctory 会从键盘读取手柄。你可以在这里为任一控制项指定另一个按键。", - on: "用键盘代替控制器", - onHint: "默认关闭。键盘钩子只在 victory.exe 位于最前方时运行,会把你按下的按键换成游戏本身对应该控制项的按键。", - change: "更改", - press: "按下按键,或按 Esc 取消", - reset: "还原", - resetAll: "全部还原", - keyDefault: "默认:{key}", - unknownKey: "按键 {code}", - controls: { - menu: "菜单", view: "视图", a: "A", b: "B", x: "X", y: "Y", - up: "方向键上", down: "方向键下", left: "方向键左", right: "方向键右", - left_shoulder: "左肩键", right_shoulder: "右肩键", - left_stick_click: "左摇杆按下", right_stick_click: "右摇杆按下", - left_stick_up: "左摇杆上", left_stick_left: "左摇杆左", left_stick_down: "左摇杆下", left_stick_right: "左摇杆右", - right_stick_up: "右摇杆上", right_stick_left: "右摇杆左", right_stick_down: "右摇杆下", right_stick_right: "右摇杆右", - left_trigger: "左扳机", right_trigger: "右扳机", - }, + mods: { + title: "模组与操控", + description: "VIctory-NVIDIA(v2026.11.29.01 及以后)每次启动时、在游戏运行之前,都会加载其模组文件夹中的每个 DLL。它的所有构建共用这个文件夹。", + warning: "模组是以你的权限在游戏内运行的程序。只添加你信任的人提供的 DLL。", + folder: "模组文件夹", + add: "添加模组…", + pickTitle: "选择模组 DLL", + filterName: "模组 DLL", + added: "已添加 {file},下次启动时加载。", + empty: "还没有模组。添加一个 DLL,或把它放进文件夹。", + load: "加载 {file}", + offHint: "已停用:保留在文件夹中,但不加载。", + remove: "移除", + removeConfirm: "移除 {file}", + keep: "保留", + removed: "已移除 {file}。", + controlsTitle: "鼠标、键盘和手柄", + controlsDescription: "游戏现在会自己读取手柄,除了 Xbox 和 PlayStation 手柄,也支持通用 USB 手柄,并且有自己的鼠标和键盘操控,所以启动器的“键盘当手柄”按键已移除。", + mnk: "鼠标和键盘", + mnkHint: "在游戏中开启:按 F1,然后选择 MOUSE AND KEYBOARD。按键保存在 bindings.ini 中,同一菜单里的 KEY BINDINGS 可以在游戏中修改它们。", + openBindings: "显示 bindings.ini", + noBindings: "第一次开启鼠标和键盘时会写入 bindings.ini。", }, updates: { title: "更新", diff --git a/src/i18n/messages/zh-TW/settings.ts b/src/i18n/messages/zh-TW/settings.ts index 1f0359e..2d5fdcc 100644 --- a/src/i18n/messages/zh-TW/settings.ts +++ b/src/i18n/messages/zh-TW/settings.ts @@ -136,26 +136,28 @@ export default { access: "讓 AI 代理協助建置", hint: "預設關閉。代理可以讀取記錄,並在你確認後套用修補檔。請參閱 README 的「Agent tools」一節。", }, - controllerKeys: { - title: "控制器按鍵", - description: "沒有接上控制器時,VIctory 會從鍵盤讀取手把。你可以在這裡為任一控制項指定另一個按鍵。", - on: "以鍵盤代替控制器", - onHint: "預設關閉。鍵盤掛鉤只在 victory.exe 位於最前方時運作,會把你按下的按鍵送成遊戲本身對應該控制項的按鍵。", - change: "變更", - press: "按下按鍵,或按 Esc 取消", - reset: "還原", - resetAll: "全部還原", - keyDefault: "預設:{key}", - unknownKey: "按鍵 {code}", - controls: { - menu: "選單", view: "檢視", a: "A", b: "B", x: "X", y: "Y", - up: "十字鍵上", down: "十字鍵下", left: "十字鍵左", right: "十字鍵右", - left_shoulder: "左肩鍵", right_shoulder: "右肩鍵", - left_stick_click: "左搖桿按下", right_stick_click: "右搖桿按下", - left_stick_up: "左搖桿上", left_stick_left: "左搖桿左", left_stick_down: "左搖桿下", left_stick_right: "左搖桿右", - right_stick_up: "右搖桿上", right_stick_left: "右搖桿左", right_stick_down: "右搖桿下", right_stick_right: "右搖桿右", - left_trigger: "左扳機", right_trigger: "右扳機", - }, + mods: { + title: "模組與操控", + description: "VIctory-NVIDIA(v2026.11.29.01 及以後)每次啟動時、在遊戲執行之前,都會載入其模組資料夾中的每個 DLL。它的所有建置共用這個資料夾。", + warning: "模組是以你的權限在遊戲內執行的程式。只加入你信任的人提供的 DLL。", + folder: "模組資料夾", + add: "加入模組…", + pickTitle: "選擇模組 DLL", + filterName: "模組 DLL", + added: "已加入 {file},下次啟動時載入。", + empty: "還沒有模組。加入一個 DLL,或把它放進資料夾。", + load: "載入 {file}", + offHint: "已停用:保留在資料夾中,但不載入。", + remove: "移除", + removeConfirm: "移除 {file}", + keep: "保留", + removed: "已移除 {file}。", + controlsTitle: "滑鼠、鍵盤和手把", + controlsDescription: "遊戲現在會自己讀取手把,除了 Xbox 和 PlayStation 手把,也支援通用 USB 手把,並且有自己的滑鼠和鍵盤操控,所以啟動器的「鍵盤當手把」按鍵已移除。", + mnk: "滑鼠和鍵盤", + mnkHint: "在遊戲中開啟:按 F1,然後選擇 MOUSE AND KEYBOARD。按鍵儲存在 bindings.ini 中,同一選單裡的 KEY BINDINGS 可以在遊戲中修改它們。", + openBindings: "顯示 bindings.ini", + noBindings: "第一次開啟滑鼠和鍵盤時會寫入 bindings.ini。", }, updates: { title: "更新", diff --git a/src/lib/types.ts b/src/lib/types.ts index 2096ea3..e60b279 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -15,19 +15,22 @@ export interface Graphics { memory: MemorySaver } -/** One control VIctory reads from the keyboard (src-tauri/src/controller_keys.rs). */ -export interface ControllerControl { - id: string - label: string - /** The Windows virtual-key code VIctory reads for it. */ - default_key: number - /** The key the player chose, or the default. */ - key: number +/** One DLL in VIctory-NVIDIA's mods folder (src-tauri/src/mods.rs). */ +export interface ModEntry { + /** The name the game loads it by ("example.dll"), also while it is off. */ + file: string + /** Its name in the folder now ("example.dll", or "example.dll.off" when off): what the actions take. */ + entry: string + on: boolean + bytes: number } -export interface ControllerKeys { - on: boolean - controls: ControllerControl[] +/** VIctory-NVIDIA's mods folder: every DLL in it is loaded at each start. */ +export interface ModsView { + folder: string + items: ModEntry[] + /** The game's own mouse and keyboard keys file (bindings.ini) is there. */ + bindings: boolean } export interface ScriptOptions { @@ -210,8 +213,8 @@ export interface Snapshot { acknowledged: ResponsibilityId[] /** The player's language ("en", "zh-TW", "zh-CN"); null follows the system. */ language: string | null - /** Off by default: the keyboard drives the game's controller controls while victory.exe is in front. */ - controller_keys: ControllerKeys + /** VIctory-NVIDIA's mods folder; null where there is none (off Windows). */ + mods: ModsView | null } files: { chosen: boolean @@ -368,8 +371,6 @@ export type Action = | { type: "rollback"; repo: string } | { type: "set_update_warning"; show: boolean } | { type: "set_agent_access"; enabled: boolean } - | { type: "set_controller_keys"; on: boolean } - | { type: "set_controller_key"; control: string; key: number | null } | { type: "acknowledge"; id: ResponsibilityId } | { type: "uninstall"; repo: string } | { type: "stop" } @@ -410,7 +411,7 @@ export type Action = | { type: "choose_saves_dir"; path: string } | { type: "use_default_saves_dir" } | { type: "confirm_move"; answer: "move" | "keep" | "cancel" } - | { type: "open"; what: "project_folder" | "backgrounds" | "workspace" | "update" | "cache" | "saves"; repo?: string } + | { type: "open"; what: "project_folder" | "backgrounds" | "workspace" | "update" | "cache" | "saves" | "mods" | "bindings"; repo?: string } | { type: "export_log"; path: string; repo?: string } | { type: "check_update" } | { type: "download_update" } @@ -423,6 +424,9 @@ export type Action = | { type: "accept_notice" } | { type: "storage_scan" } | { type: "clear_cache"; repo: string } + | { type: "mod_add"; path: string } + | { type: "mod_set_on"; entry: string; on: boolean } + | { type: "mod_remove"; entry: string } | { type: "get_nvidia_files" } | { type: "set_fsr_dll"; path: string | null } | { type: "set_mac_runner"; runner: MacRunnerChoice } From b20356f247db6235ed3e4a67f809182f65366962 Mon Sep 17 00:00:00 2001 From: dazacode Date: Sun, 29 Nov 2026 02:32:02 -0800 Subject: [PATCH 2/3] Review fixes, and what upstream's issues show: keep the keys, F1, screens From the review of the first commit and research into the forks and VIctory-NVIDIA's open issues: - Keyboard keys for the controller come back, and skip builds with their own mouse and keyboard. Every other fork (the base, DexNom, fxceless, Kelvaroq, VItoriaBr) still reads only the fixed keyboard table, so removing the keys took remapping away from them. The hook tells a build with its own keyboard from the program (VICTORY_MNK_BINDINGS), read once per program file on a thread of its own, never in the hook. - On a `victory play` start the launcher no longer runs its F1 watcher: the build writes victory-settings.txt on every F1 change, also those applied at once, and the watcher closed the game each time. The build applies its choices and restarts itself. - A screen that is not 16:9 gets VICTORY_NATIVE_SIZE=2560x1440: the build sizes its picture after the screen's shape, and players on 21:9, 32:9 and 16:10 report it stopping at the start (upstream #2055, #2060, #2073). A value of the player's or the F1 menu's wins. - XMemVirtualAlloc refused ... (os error 8), then a stop, is named as the release's own reservation problem (#2081 and others, fix in PR #2133) with Restore previous build, not blamed on switches. - Short of Windows commit: its own fix, Series S and the memory saver, without the render scale and output cuts that are for the card; the text says what it changes. - Screenshot mode hides the mods folder's path (it has the user name). - The player's own switch wins over the memory saver's also when it equals the preset's default. - `victory --help` is asked once per program file, not before every check and start (seconds through Wine or CrossOver). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +- src-tauri/locales/es/launcher.json | 6 +- src-tauri/locales/fr/launcher.json | 6 +- src-tauri/locales/ru/launcher.json | 6 +- src-tauri/locales/zh-CN/launcher.json | 6 +- src-tauri/locales/zh-TW/launcher.json | 6 +- src-tauri/src/controller_keys.rs | 499 ++++++++++++++++++++++ src-tauri/src/diagnose.rs | 52 ++- src-tauri/src/launcher.rs | 191 ++++++++- src-tauri/src/launcher/actions.rs | 37 ++ src-tauri/src/launcher/view.rs | 32 ++ src-tauri/src/main.rs | 1 + src/dev/mock.ts | 38 ++ src/features/settings/controller-keys.tsx | 109 +++++ src/features/settings/mods.tsx | 4 +- src/features/settings/settings-view.tsx | 3 + src/i18n/messages/en/settings.ts | 24 +- src/i18n/messages/es/settings.ts | 24 +- src/i18n/messages/fr/settings.ts | 24 +- src/i18n/messages/ru/settings.ts | 24 +- src/i18n/messages/zh-CN/settings.ts | 24 +- src/i18n/messages/zh-TW/settings.ts | 24 +- src/lib/types.ts | 19 + 23 files changed, 1138 insertions(+), 33 deletions(-) create mode 100644 src-tauri/src/controller_keys.rs create mode 100644 src/features/settings/controller-keys.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 251d752..14619a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,14 +5,18 @@ The release notes for each tag are taken from the section for that version. ## Unreleased ### New -- **Mods for VIctory-NVIDIA** (*Settings → Mods & controls*, Windows): VIctory-NVIDIA v2026.11.29.01 loads every DLL in `%LOCALAPPDATA%\victory\mods` at each start (its PR #1892). The launcher lists them, adds a DLL, turns one off (renamed to `.dll.off`, which the game skips) or on again, removes one, and opens the folder. It never downloads or runs a mod itself, and never overwrites one. -- **Memory saver on VIctory-NVIDIA:** most of its switches are KLBF Lab's, which this build does not read. On a `victory play` start it now also sends the ones the build does read for the same need, from its docs/windows-memory.md: two pipeline workers (Light and up), and a smaller VRAM reserve for later render targets, given back once they settle (Very light). A value of your own wins. -- **Short of Windows memory, told apart:** when the game's memory guard reports the commit limit (RAM and page file) and the driver refuses pipelines with `0x8007000E`, Fix and verify now says the PC is short, not the card, and how to let Windows manage the page file. For VIctory-NVIDIA on 16 GB of RAM, two pipeline workers is offered as a possible setting. +- **Mods for VIctory-NVIDIA** (*Settings → Mods & controls*, Windows): VIctory-NVIDIA v2026.11.29.01 loads every DLL in `%LOCALAPPDATA% ictorymods` at each start (its PR #1892). The launcher lists them, adds a DLL, turns one off (renamed to `.dll.off`, which the game skips) or on again, removes one, and opens the folder. It never downloads or runs a mod itself, and never overwrites one. Screenshot mode hides the folder's path. +- **Memory saver on VIctory-NVIDIA:** most of its switches are KLBF Lab's, which this build does not read. On a `victory play` start it now also sends the ones the build does read for the same need, from its docs/windows-memory.md: two pipeline workers (Light and up), and a smaller VRAM reserve for later render targets, given back once they settle (Very light). A value of your own always wins. +- **Short of Windows memory, told apart:** when the game's memory guard reports the commit limit (RAM and page file) and the driver refuses pipelines with `0x8007000E`, Fix and verify says the PC is short, not the card, and how to let Windows manage the page file. Its fix turns on Series S and the memory saver, and leaves the render scale and output alone. For VIctory-NVIDIA on 16 GB of RAM, two pipeline workers is offered as a possible setting when a start does not already send it. +- **Start-up reservation crash of VIctory-NVIDIA v2026.11.29.01 named:** `XMemVirtualAlloc refused … (os error 8)` followed by a stop is a problem of that release on some PCs, not of RAM or switches. The launcher says so and points to *Restore previous build*. +- **Screens that are not 16:9:** VIctory-NVIDIA v2026.11.29.01 sizes its picture after the screen's shape, and players on 21:9, 32:9 and 16:10 screens report it stopping at the start. On such a screen the launcher asks for 2560x1440, the size before, unless you set `VICTORY_NATIVE_SIZE` yourself or in the F1 menu. ### Changed -- **Keyboard-as-controller keys removed:** VIctory-NVIDIA now reads generic USB pads beside Xbox and PlayStation ones, and has its own mouse and keyboard controls (F1, MOUSE AND KEYBOARD; keys in `bindings.ini`). The launcher's keyboard hook would have sent keys twice, so it is gone; *Mods & controls* shows where the game's own keys are. Saved settings from before still load. +- **Keyboard keys for the controller skip builds with their own mouse and keyboard:** VIctory-NVIDIA from v2026.11.29.01 has mouse and keyboard controls of its own (F1, MOUSE AND KEYBOARD; keys in `bindings.ini`), so the launcher's keys leave it alone and are never remapped twice. Every other fork still reads the fixed keyboard table, and keeps the launcher's keys. The launcher tells the builds apart from the program itself. ### Fixed +- **F1 menu on VIctory-NVIDIA:** the launcher no longer closes the game whenever the F1 menu saves a choice. That build applies its choices and restarts itself for those that need it; the launcher's own watcher closed it even for choices applied at once. +- **Fewer `--help` runs:** the launcher asks a build what it offers once per program file, not before every check and start (seconds each through Wine or CrossOver). - **Agent tool:** `status` said a VIctory-NVIDIA build was not installed. The project has a `diag` profile, and the tool looked for the program there; the launcher builds `release`, as the tool now does too. ## 1.2.2 diff --git a/src-tauri/locales/es/launcher.json b/src-tauri/locales/es/launcher.json index bf95aa5..ce8978a 100644 --- a/src-tauri/locales/es/launcher.json +++ b/src-tauri/locales/es/launcher.json @@ -178,6 +178,8 @@ "Could not copy {file}: {e}": "No se pudo copiar {file}: {e}", "Could not remove {file}: {e}": "No se pudo quitar {file}: {e}", "Windows ran short of memory for the game (RAM and page file).": "Windows se quedó sin memoria para el juego (RAM y archivo de paginación).", - "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "El juego pidió a Windows más memoria de la que dejaban la RAM y el archivo de paginación, así que se rechazaron pipelines de shaders y faltaron sus dibujados. Cierra otros programas y deja que Windows administre el tamaño del archivo de paginación (Sistema, Acerca de, Configuración avanzada del sistema, Rendimiento, Memoria virtual) y reinicia. Reparar y verificar también activa el ahorro de memoria, que en VIctory-NVIDIA prepara dos shaders a la vez en lugar de hasta ocho.", - "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Menos pipelines de shaders preparados a la vez (2 en lugar de hasta 8), para que el juego se mantenga por debajo del límite de memoria confirmada de Windows (RAM y archivo de paginación) en un PC con 16 GB de RAM. Los shaders tardan más en terminarse la primera vez." + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "El juego pidió a Windows más memoria de la que dejaban la RAM y el archivo de paginación, así que se rechazaron pipelines de shaders y faltaron sus dibujados. Cierra otros programas y deja que Windows administre el tamaño del archivo de paginación (Sistema, Acerca de, Configuración avanzada del sistema, Rendimiento, Memoria virtual) y reinicia. Reparar y verificar activa la Series S y el ahorro de memoria, que en VIctory-NVIDIA iniciado con su propio play prepara dos shaders a la vez en lugar de hasta ocho. La escala de renderizado y la salida se quedan como están: son para la memoria de la tarjeta.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Menos pipelines de shaders preparados a la vez (2 en lugar de hasta 8), para que el juego se mantenga por debajo del límite de memoria confirmada de Windows (RAM y archivo de paginación) en un PC con 16 GB de RAM. Los shaders tardan más en terminarse la primera vez.", + "This build could not reserve the game's memory at the start.": "Esta compilación no pudo reservar la memoria del juego al iniciar.", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "No es tu RAM ni tu archivo de paginación: esta versión de VIctory-NVIDIA reserva la memoria del juego en un rango de direcciones que se agota en algunos PC, y su próxima versión lo corrige. Hasta entonces, usa Restaurar compilación anterior en el proyecto (la versión anterior sí inicia), o actualiza cuando salga una más nueva." } diff --git a/src-tauri/locales/fr/launcher.json b/src-tauri/locales/fr/launcher.json index 298914b..779bd9a 100644 --- a/src-tauri/locales/fr/launcher.json +++ b/src-tauri/locales/fr/launcher.json @@ -178,6 +178,8 @@ "Could not copy {file}: {e}": "Impossible de copier {file} : {e}", "Could not remove {file}: {e}": "Impossible de supprimer {file} : {e}", "Windows ran short of memory for the game (RAM and page file).": "Windows a manqué de mémoire pour le jeu (RAM et fichier d'échange).", - "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "Le jeu a demandé à Windows plus de mémoire que la RAM et le fichier d'échange n'en laissaient : des pipelines de shaders ont été refusés et leurs rendus ont manqué. Fermez les autres programmes et laissez Windows gérer la taille du fichier d'échange (Système, Informations système, Paramètres système avancés, Performances, Mémoire virtuelle), puis redémarrez. Corriger et vérifier active aussi l'économiseur de mémoire qui, sur VIctory-NVIDIA, prépare deux shaders à la fois au lieu de huit au plus.", - "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Moins de pipelines de shaders préparés à la fois (2 au lieu de 8 au plus) : le jeu reste sous la limite de mémoire validée de Windows (RAM et fichier d’échange) sur un PC avec 16 Go de RAM. Les shaders mettent plus de temps à se terminer la première fois." + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "Le jeu a demandé à Windows plus de mémoire que la RAM et le fichier d'échange n'en laissaient : des pipelines de shaders ont été refusés et leurs rendus ont manqué. Fermez les autres programmes et laissez Windows gérer la taille du fichier d'échange (Système, Informations système, Paramètres système avancés, Performances, Mémoire virtuelle), puis redémarrez. Corriger et vérifier active la Series S et l'économiseur de mémoire qui, sur VIctory-NVIDIA lancé par son propre play, prépare deux shaders à la fois au lieu de huit au plus. L'échelle de rendu et la sortie restent telles quelles : elles concernent la mémoire de la carte.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Moins de pipelines de shaders préparés à la fois (2 au lieu de 8 au plus) : le jeu reste sous la limite de mémoire validée de Windows (RAM et fichier d’échange) sur un PC avec 16 Go de RAM. Les shaders mettent plus de temps à se terminer la première fois.", + "This build could not reserve the game's memory at the start.": "Cette version n'a pas pu réserver la mémoire du jeu au démarrage.", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "Ce n'est ni votre RAM ni votre fichier d'échange : cette version de VIctory-NVIDIA réserve la mémoire du jeu dans une plage d'adresses qui s'épuise sur certains PC, et sa prochaine version corrige cela. D'ici là, utilisez Restaurer le build précédent sur le projet (la version d'avant démarre), ou mettez à jour quand une plus récente sort." } diff --git a/src-tauri/locales/ru/launcher.json b/src-tauri/locales/ru/launcher.json index 33a9e00..8d08649 100644 --- a/src-tauri/locales/ru/launcher.json +++ b/src-tauri/locales/ru/launcher.json @@ -178,6 +178,8 @@ "Could not copy {file}: {e}": "Не удалось скопировать {file}: {e}", "Could not remove {file}: {e}": "Не удалось удалить {file}: {e}", "Windows ran short of memory for the game (RAM and page file).": "Windows не хватило памяти для игры (ОЗУ и файл подкачки).", - "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "Игра запросила у Windows больше памяти, чем оставалось в ОЗУ и файле подкачки, поэтому конвейеры шейдеров были отклонены, а их отрисовка пропала. Закройте другие программы и позвольте Windows автоматически выбирать размер файла подкачки (Система, О программе, Дополнительные параметры системы, Быстродействие, Виртуальная память), затем перезагрузите ПК. «Исправить и проверить» также включает экономию памяти: в VIctory-NVIDIA она готовит два шейдера одновременно вместо восьми.", - "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Меньше конвейеров шейдеров одновременно (2 вместо до 8), чтобы игра не выходила за предел выделенной памяти Windows (ОЗУ и файл подкачки) на ПК с 16 ГБ ОЗУ. В первый раз шейдеры готовятся дольше." + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "Игра запросила у Windows больше памяти, чем оставалось в ОЗУ и файле подкачки, поэтому конвейеры шейдеров были отклонены, а их отрисовка пропала. Закройте другие программы и позвольте Windows автоматически выбирать размер файла подкачки (Система, О программе, Дополнительные параметры системы, Быстродействие, Виртуальная память), затем перезагрузите ПК. «Исправить и проверить» включает Series S и экономию памяти: в VIctory-NVIDIA, запущенной через её собственный play, она готовит два шейдера одновременно вместо восьми. Масштаб рендеринга и выходное разрешение не меняются: они относятся к памяти видеокарты.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Меньше конвейеров шейдеров одновременно (2 вместо до 8), чтобы игра не выходила за предел выделенной памяти Windows (ОЗУ и файл подкачки) на ПК с 16 ГБ ОЗУ. В первый раз шейдеры готовятся дольше.", + "This build could not reserve the game's memory at the start.": "Этой сборке не удалось зарезервировать память игры при запуске.", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "Дело не в ОЗУ и не в файле подкачки: этот выпуск VIctory-NVIDIA резервирует память игры в диапазоне адресов, которого на некоторых ПК не хватает, и следующий выпуск это исправляет. До тех пор используйте «Восстановить предыдущую сборку» в проекте (предыдущий выпуск запускается) или обновитесь, когда выйдет новый." } diff --git a/src-tauri/locales/zh-CN/launcher.json b/src-tauri/locales/zh-CN/launcher.json index 00510ca..7de3afa 100644 --- a/src-tauri/locales/zh-CN/launcher.json +++ b/src-tauri/locales/zh-CN/launcher.json @@ -178,6 +178,8 @@ "Could not copy {file}: {e}": "无法复制 {file}:{e}", "Could not remove {file}: {e}": "无法移除 {file}:{e}", "Windows ran short of memory for the game (RAM and page file).": "Windows 给游戏的内存不足(内存和页面文件)。", - "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "游戏向 Windows 申请的内存超过了内存和页面文件剩余的量,因此着色器管线被拒绝,相应的绘制缺失。请关闭其他程序,并让 Windows 自动管理页面文件大小(系统、系统信息、高级系统设置、性能、虚拟内存),然后重启。“修复并验证”也会开启内存节省,在 VIctory-NVIDIA 上它每次只准备两个着色器,而不是最多八个。", - "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同时准备的着色器管线更少(2 个,而不是最多 8 个),这样在 16 GB 内存的电脑上,游戏不会超出 Windows 的提交内存上限(内存和页面文件)。第一次准备着色器会更久。" + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "游戏向 Windows 申请的内存超过了内存和页面文件剩余的量,因此着色器管线被拒绝,相应的绘制缺失。请关闭其他程序,并让 Windows 自动管理页面文件大小(系统、系统信息、高级系统设置、性能、虚拟内存),然后重启。“修复并验证”会开启 Series S 和内存节省;在通过自身 play 启动的 VIctory-NVIDIA 上,它每次只准备两个着色器,而不是最多八个。渲染比例和输出保持不变:它们针对的是显卡的显存。", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同时准备的着色器管线更少(2 个,而不是最多 8 个),这样在 16 GB 内存的电脑上,游戏不会超出 Windows 的提交内存上限(内存和页面文件)。第一次准备着色器会更久。", + "This build could not reserve the game's memory at the start.": "此构建在启动时无法预留游戏所需的内存。", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "这不是内存或页面文件的问题:这个版本的 VIctory-NVIDIA 会在一段地址范围内预留游戏内存,而这段范围在部分电脑上会不够用,下一个版本会修复。在此之前,请在项目上使用“还原上一个构建版本”(上一个版本可以启动),或等有新版本时更新。" } diff --git a/src-tauri/locales/zh-TW/launcher.json b/src-tauri/locales/zh-TW/launcher.json index bd95ef8..4269305 100644 --- a/src-tauri/locales/zh-TW/launcher.json +++ b/src-tauri/locales/zh-TW/launcher.json @@ -178,6 +178,8 @@ "Could not copy {file}: {e}": "無法複製 {file}:{e}", "Could not remove {file}: {e}": "無法移除 {file}:{e}", "Windows ran short of memory for the game (RAM and page file).": "Windows 給遊戲的記憶體不足(記憶體和分頁檔)。", - "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight.": "遊戲向 Windows 要求的記憶體超過了記憶體和分頁檔剩餘的量,因此著色器管線被拒絕,相應的繪製缺失。請關閉其他程式,並讓 Windows 自動管理分頁檔大小(系統、關於、進階系統設定、效能、虛擬記憶體),然後重新開機。「修復並驗證」也會開啟記憶體節省,在 VIctory-NVIDIA 上它一次只準備兩個著色器,而不是最多八個。", - "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同時準備的著色器管線更少(2 個,而不是最多 8 個),這樣在 16 GB 記憶體的電腦上,遊戲不會超出 Windows 的認可記憶體上限(記憶體和分頁檔)。第一次準備著色器會更久。" + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "遊戲向 Windows 要求的記憶體超過了記憶體和分頁檔剩餘的量,因此著色器管線被拒絕,相應的繪製缺失。請關閉其他程式,並讓 Windows 自動管理分頁檔大小(系統、關於、進階系統設定、效能、虛擬記憶體),然後重新開機。「修復並驗證」會開啟 Series S 和記憶體節省;在透過自身 play 啟動的 VIctory-NVIDIA 上,它一次只準備兩個著色器,而不是最多八個。渲染比例和輸出保持不變:它們針對的是顯示卡的記憶體。", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同時準備的著色器管線更少(2 個,而不是最多 8 個),這樣在 16 GB 記憶體的電腦上,遊戲不會超出 Windows 的認可記憶體上限(記憶體和分頁檔)。第一次準備著色器會更久。", + "This build could not reserve the game's memory at the start.": "此建置在啟動時無法預留遊戲所需的記憶體。", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "這不是記憶體或分頁檔的問題:這個版本的 VIctory-NVIDIA 會在一段位址範圍內預留遊戲記憶體,而這段範圍在部分電腦上會不夠用,下一個版本會修復。在此之前,請在專案上使用「還原上一個建置版本」(上一個版本可以啟動),或等有新版本時更新。" } diff --git a/src-tauri/src/controller_keys.rs b/src-tauri/src/controller_keys.rs new file mode 100644 index 0000000..fd88636 --- /dev/null +++ b/src-tauri/src/controller_keys.rs @@ -0,0 +1,499 @@ +//! Keyboard keys for the game's controller controls. +//! +//! VIctory's input layer reads a pad from the keyboard when no controller is connected: +//! a fixed table maps keys to pad buttons and sticks. Here the player can give each of +//! those controls another key. While the game window is in front, a low-level keyboard +//! hook sends the layer's own key for the control whose key was pressed. Off by default. +//! Only Windows has the hook; elsewhere the settings are kept and nothing is sent. +//! +//! A build with mouse and keyboard of its own (VIctory-NVIDIA from v2026.11.29.01: F1, +//! MOUSE AND KEYBOARD, keys in bindings.ini) is left alone, or the keys would be remapped +//! twice. Every other fork still reads the fixed table, so for them the keys stay. + +use std::collections::BTreeMap; + +/// Text only a build with its own mouse and keyboard bindings has in its program: the switch +/// naming VIctory-NVIDIA's bindings.ini (crates/victory-hle/src/modules/mnk.rs, play.rs). +const OWN_KEYBOARD_MARK: &[u8] = b"VICTORY_MNK_BINDINGS"; + +/// Whether a program's bytes are those of a build with its own mouse and keyboard. +pub fn has_own_keyboard(program: &[u8]) -> bool { + program + .windows(OWN_KEYBOARD_MARK.len()) + .any(|window| window == OWN_KEYBOARD_MARK) +} + +/// One control the layer reads from the keyboard, with the key the layer uses for it. +pub struct Control { + pub id: &'static str, + pub label: &'static str, + /// Windows virtual-key code the layer reads (the same as the browser's keyCode). + pub default_key: u16, +} + +pub const CONTROLS: &[Control] = &[ + Control { + id: "menu", + label: "Menu", + default_key: 0x1B, + }, + Control { + id: "view", + label: "View", + default_key: 0x09, + }, + Control { + id: "a", + label: "A", + default_key: 0x0D, + }, + Control { + id: "b", + label: "B", + default_key: 0x08, + }, + Control { + id: "x", + label: "X", + default_key: 0x58, + }, + Control { + id: "y", + label: "Y", + default_key: 0x59, + }, + Control { + id: "up", + label: "D-pad up", + default_key: 0x26, + }, + Control { + id: "down", + label: "D-pad down", + default_key: 0x28, + }, + Control { + id: "left", + label: "D-pad left", + default_key: 0x25, + }, + Control { + id: "right", + label: "D-pad right", + default_key: 0x27, + }, + Control { + id: "left_shoulder", + label: "Left shoulder", + default_key: 0x51, + }, + Control { + id: "right_shoulder", + label: "Right shoulder", + default_key: 0x45, + }, + Control { + id: "left_stick_click", + label: "Left stick click", + default_key: 0x46, + }, + Control { + id: "right_stick_click", + label: "Right stick click", + default_key: 0x48, + }, + Control { + id: "left_stick_up", + label: "Left stick up", + default_key: 0x57, + }, + Control { + id: "left_stick_left", + label: "Left stick left", + default_key: 0x41, + }, + Control { + id: "left_stick_down", + label: "Left stick down", + default_key: 0x53, + }, + Control { + id: "left_stick_right", + label: "Left stick right", + default_key: 0x44, + }, + Control { + id: "right_stick_up", + label: "Right stick up", + default_key: 0x49, + }, + Control { + id: "right_stick_left", + label: "Right stick left", + default_key: 0x4A, + }, + Control { + id: "right_stick_down", + label: "Right stick down", + default_key: 0x4B, + }, + Control { + id: "right_stick_right", + label: "Right stick right", + default_key: 0x4C, + }, + Control { + id: "left_trigger", + label: "Left trigger", + default_key: 0x5A, + }, + Control { + id: "right_trigger", + label: "Right trigger", + default_key: 0x43, + }, +]; + +pub fn control(id: &str) -> Option<&'static Control> { + CONTROLS.iter().find(|c| c.id == id) +} + +/// The key the player uses for a control: their own, else the layer's. +pub fn key_of(bindings: &BTreeMap, control: &Control) -> u16 { + bindings + .get(control.id) + .copied() + .unwrap_or(control.default_key) +} + +/// Whether `key` may be given to control `id`: a real key, and not one another control uses. +pub fn check_key(bindings: &BTreeMap, id: &str, key: u16) -> Result<(), String> { + // 0 and 0xFF are not keys; the rest stay with Windows or are modifiers the game needs. + const RESERVED: &[u16] = &[ + 0x03, 0x10, 0x11, 0x12, 0x14, 0x2C, 0x5B, 0x5C, 0x5D, 0x90, 0x91, 0xA0, 0xA1, 0xA2, 0xA3, + 0xA4, 0xA5, + ]; + if key == 0 || key == 0xFF || RESERVED.contains(&key) { + return Err("That key cannot be used for a controller control.".into()); + } + for other in CONTROLS.iter().filter(|c| c.id != id) { + if key_of(bindings, other) == key { + return Err(format!("{} already uses that key.", other.label)); + } + } + Ok(()) +} + +/// What the game should see for a key the player pressed. +#[cfg_attr(not(windows), allow(dead_code))] +#[derive(Debug, PartialEq, Eq)] +pub enum Step { + /// Unchanged: the key reaches the game as pressed. + Pass, + /// The layer's key for the control the player pressed. + Send(u16), + /// Nothing: the key is the layer's own key for a control the player moved elsewhere. + Swallow, +} + +#[cfg_attr(not(windows), allow(dead_code))] +pub fn translate(bindings: &BTreeMap, pressed: u16) -> Step { + if let Some(control) = CONTROLS.iter().find(|c| key_of(bindings, c) == pressed) { + return if control.default_key == pressed { + Step::Pass + } else { + Step::Send(control.default_key) + }; + } + if CONTROLS.iter().any(|c| c.default_key == pressed) { + Step::Swallow + } else { + Step::Pass + } +} + +#[cfg(windows)] +mod hook { + use super::{translate, Step}; + use std::collections::{BTreeMap, HashMap}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Mutex, Once}; + use windows_sys::Win32::Foundation::{CloseHandle, LPARAM, LRESULT, WPARAM}; + use windows_sys::Win32::System::Threading::{ + OpenProcess, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION, + }; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + MapVirtualKeyW, SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, + KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + CallNextHookEx, GetForegroundWindow, GetMessageW, GetWindowThreadProcessId, + SetWindowsHookExW, KBDLLHOOKSTRUCT, LLKHF_INJECTED, MSG, WH_KEYBOARD_LL, WM_KEYDOWN, + WM_KEYUP, WM_SYSKEYDOWN, WM_SYSKEYUP, + }; + + /// The game's program name: every VIctory build starts `victory.exe`. + const GAME_EXE: &str = "victory.exe"; + + static ENABLED: AtomicBool = AtomicBool::new(false); + static HOOK_STARTED: Once = Once::new(); + + struct State { + bindings: BTreeMap, + /// Keys held down whose presses were changed, and what each sent. Kept across + /// settings changes, so the release is always seen and nothing stays pressed. + held: HashMap, + } + + static STATE: Mutex> = Mutex::new(None); + + fn lock() -> std::sync::MutexGuard<'static, Option> { + STATE.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn configure(on: bool, bindings: BTreeMap) { + { + let mut state = lock(); + let held = state.take().map(|old| old.held).unwrap_or_default(); + *state = Some(State { bindings, held }); + } + ENABLED.store(on, Ordering::Relaxed); + if on { + HOOK_STARTED.call_once(|| { + std::thread::spawn(|| unsafe { + let hook = SetWindowsHookExW( + WH_KEYBOARD_LL, + Some(keyboard_hook), + std::ptr::null_mut(), + 0, + ); + if hook.is_null() { + return; + } + let mut message: MSG = std::mem::zeroed(); + // The hook runs on this thread, so it needs a message loop for as long as the launcher runs. + while GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) > 0 {} + }); + }); + } + } + + unsafe extern "system" fn keyboard_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + let info = &*(lparam as *const KBDLLHOOKSTRUCT); + let message = wparam as u32; + let down = message == WM_KEYDOWN || message == WM_SYSKEYDOWN; + let up = message == WM_KEYUP || message == WM_SYSKEYUP; + // Keys this hook sent are flagged injected: letting them through avoids a loop. + if (down || up) && info.flags & LLKHF_INJECTED == 0 { + let key = info.vkCode as u16; + // A release is always handled, so a key pressed in the game cannot stay down + // when the focus moves away or the setting changes. + let consumed = if up { + release(key) + } else { + ENABLED.load(Ordering::Relaxed) && game_without_own_keyboard() && press(key) + }; + if consumed { + return 1; + } + } + } + CallNextHookEx(std::ptr::null_mut(), code, wparam, lparam) + } + + /// A key went down in the game. Returns true when the key is consumed. + fn press(key: u16) -> bool { + let mut guard = lock(); + let Some(state) = guard.as_mut() else { + return false; + }; + if state.held.contains_key(&key) { + return true; + } + match translate(&state.bindings, key) { + Step::Pass => false, + Step::Send(sent) => { + state.held.insert(key, Step::Send(sent)); + drop(guard); + // SAFETY: SendInput with one well-formed input. + unsafe { send(sent, true) }; + true + } + Step::Swallow => { + state.held.insert(key, Step::Swallow); + true + } + } + } + + /// A key went up. Releases what its press sent. Returns true when the key is consumed. + fn release(key: u16) -> bool { + let mut guard = lock(); + let Some(state) = guard.as_mut() else { + return false; + }; + match state.held.remove(&key) { + None => false, + Some(Step::Send(sent)) => { + drop(guard); + // SAFETY: as above. + unsafe { send(sent, false) }; + true + } + Some(_) => true, + } + } + + /// What is known of each game program: whether it has its own mouse and keyboard; None + /// while it is being read. Read once per program file, on a thread of its own: never in + /// the hook, which Windows drops when it is slow. + static OWN_KEYBOARD: Mutex>>> = Mutex::new(None); + + /// Whether the window in front is the game, of a build known to have no mouse and keyboard + /// of its own. False while that is still being read: those keys pass unchanged. + unsafe fn game_without_own_keyboard() -> bool { + let Some(path) = game_in_front() else { + return false; + }; + let mut guard = OWN_KEYBOARD.lock().unwrap_or_else(|e| e.into_inner()); + let known = guard.get_or_insert_with(HashMap::new); + match known.get(&path) { + Some(Some(own)) => !own, + Some(None) => false, + None => { + known.insert(path.clone(), None); + std::thread::spawn(move || { + let own = + std::fs::read(&path).is_ok_and(|bytes| super::has_own_keyboard(&bytes)); + let mut guard = OWN_KEYBOARD.lock().unwrap_or_else(|e| e.into_inner()); + guard + .get_or_insert_with(HashMap::new) + .insert(path, Some(own)); + }); + false + } + } + } + + /// The program of the window in front, when it is the game. + unsafe fn game_in_front() -> Option { + let window = GetForegroundWindow(); + if window.is_null() { + return None; + } + let mut pid = 0u32; + GetWindowThreadProcessId(window, &mut pid); + let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if process.is_null() { + return None; + } + let mut buffer = [0u16; 1024]; + let mut length = buffer.len() as u32; + let named = QueryFullProcessImageNameW(process, 0, buffer.as_mut_ptr(), &mut length) != 0; + CloseHandle(process); + if !named { + return None; + } + let path = String::from_utf16_lossy(&buffer[..length as usize]); + std::path::Path::new(&path) + .file_name() + .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(GAME_EXE)) + .then_some(path) + } + + unsafe fn send(key: u16, down: bool) { + // Arrows, paging, insert and delete are extended keys. + let extended = matches!(key, 0x21..=0x28 | 0x2D | 0x2E); + let mut flags = 0; + if !down { + flags |= KEYEVENTF_KEYUP; + } + if extended { + flags |= KEYEVENTF_EXTENDEDKEY; + } + let input = INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: key, + wScan: MapVirtualKeyW(u32::from(key), MAPVK_VK_TO_VSC) as u16, + dwFlags: flags, + time: 0, + dwExtraInfo: 0, + }, + }, + }; + SendInput(1, &input, std::mem::size_of::() as i32); + } +} + +/// Applies the player's settings: whether the keys are on, and their key choices. +pub fn configure(on: bool, bindings: &BTreeMap) { + #[cfg(windows)] + hook::configure(on, bindings.clone()); + #[cfg(not(windows))] + let _ = (on, bindings); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bind(pairs: &[(&str, u16)]) -> BTreeMap { + pairs + .iter() + .map(|(id, key)| (id.to_string(), *key)) + .collect() + } + + #[test] + fn with_no_changes_every_key_passes() { + let none = BTreeMap::new(); + assert_eq!(translate(&none, 0x0D), Step::Pass); + assert_eq!(translate(&none, 0x46), Step::Pass); + assert_eq!(translate(&none, 0x20), Step::Pass); + } + + #[test] + fn a_moved_control_sends_the_layers_key_and_its_old_key_is_swallowed() { + // A (Enter in the layer) moved to F: F sends Enter, Enter itself is swallowed, + // and other keys are untouched. + let moved = bind(&[("a", 0x46)]); + assert_eq!(translate(&moved, 0x46), Step::Send(0x0D)); + assert_eq!(translate(&moved, 0x0D), Step::Swallow); + assert_eq!(translate(&moved, 0x58), Step::Pass); + } + + #[test] + fn a_key_already_in_use_is_refused_and_a_freed_key_is_allowed() { + let none = BTreeMap::new(); + // X is the layer's X key for control x: another control cannot take it. + assert!(check_key(&none, "a", 0x58).is_err()); + // Once X moves to K, X is free for another control. + let moved = bind(&[("x", 0x4B)]); + assert!(check_key(&moved, "a", 0x58).is_ok()); + // Keys the layer never reads for a control are not refused for that reason. + assert!(check_key(&none, "a", 0x20).is_ok()); + assert!(check_key(&none, "a", 0).is_err()); + // Modifiers, Windows and lock keys stay with the system. + assert!(check_key(&none, "a", 0x12).is_err()); + assert!(check_key(&none, "a", 0x5B).is_err()); + } + + #[test] + fn a_build_with_its_own_keyboard_is_told_from_its_program() { + assert!(has_own_keyboard(b"..VICTORY_MNK_BINDINGS..")); + assert!(!has_own_keyboard(b"..VICTORY_MNK.. VICTORY_KBM_PC..")); + assert!(!has_own_keyboard(b"")); + } + + #[test] + fn every_control_has_a_distinct_default_key() { + for (i, a) in CONTROLS.iter().enumerate() { + for b in &CONTROLS[i + 1..] { + assert_ne!(a.default_key, b.default_key, "{} and {}", a.id, b.id); + } + } + } +} diff --git a/src-tauri/src/diagnose.rs b/src-tauri/src/diagnose.rs index 6c7ff7e..eedb3bc 100644 --- a/src-tauri/src/diagnose.rs +++ b/src-tauri/src/diagnose.rs @@ -20,6 +20,9 @@ pub(crate) const FIX_CLEAR_SHADER_CACHE: &str = "clear-shader-cache"; pub(crate) const FIX_PERMISSIONS: &str = "permissions"; pub(crate) const FIX_DISK: &str = "disk-space"; pub(crate) const FIX_GRAPHICS_MEMORY: &str = "graphics-memory"; +/// Windows' commit (RAM and page file) ran out, not the card's memory: Series S and the memory +/// saver, without the render scale and output cuts that are for the card. +pub(crate) const FIX_COMMIT_MEMORY: &str = "commit-memory"; pub(crate) const FIX_GRAPHICS_DEVICE: &str = "graphics-device"; pub(crate) const FIX_DRIVER_PAGE: &str = "driver-page"; pub(crate) const FIX_REPO_SWITCH: &str = "repo-switch"; @@ -1157,9 +1160,29 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { advice: None, }); } + // VIctory-NVIDIA v2026.11.29.01 reserves the title's memory under a 2^37 cap + // (crates/victory-hle/src/modules/xmem.rs, TITLE_TOP_BITS) that runs out on some PCs: the + // reservation is refused with Windows error 8 and the title stops on 0x80000003 at the start + // (upstream issues #2081, #2112, #2141, #2150, #2167; PR #2133 fixes it). RAM and the page + // file are fine there, and the release before starts. The Windows text is in the player's + // language, so the English token and the error number are matched. + let xmem = lines + .iter() + .any(|line| line.contains("XMemVirtualAlloc refused") && line.contains("os error 8")); + if xmem { + found.push(Finding { + title: msg_str!("This build could not reserve the game's memory at the start.").to_string(), + detail: msg_str!("It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.").to_string(), + fix: None, + heavy: false, + data: None, + advice: None, + }); + } // The game's own crash reporter prints this when its code stops on an exception before - // or while the title starts. The usual cause is an experimental switch. - if has(&["VIctory: unhandled exception"]) { + // or while the title starts. The usual cause is an experimental switch (not when the + // reservation above is why). + if !xmem && has(&["VIctory: unhandled exception"]) { found.push(Finding { title: "The game stopped with an unhandled exception.".to_string(), detail: "The game's code hit an exception (for example 0x80000003, a breakpoint trap) and closed. Open Launch options and clear the extra switches, then Play again. If it still stops, send the report: it has the exception and the game's crash files.".to_string(), @@ -1203,21 +1226,23 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { let commit = has(&["left to commit"]) || refused && has(&["the commit left would fall under its floor"]); if commit || refused { - let (title, detail) = if commit { + let (title, detail, fix) = if commit { ( msg_str!("Windows ran short of memory for the game (RAM and page file)."), - msg_str!("The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify also turns on the memory saver, which on VIctory-NVIDIA makes two shaders at a time instead of up to eight."), + msg_str!("The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory."), + FIX_COMMIT_MEMORY, ) } else { ( "The game ran out of memory.", "Fix and verify lowers the render scale, turns on the texture fix and the memory saver, and lowers an output above 1080p to 1080p.", + FIX_GRAPHICS_MEMORY, ) }; found.push(Finding { title: title.to_string(), detail: detail.to_string(), - fix: Some(FIX_GRAPHICS_MEMORY), + fix: Some(fix), heavy: false, data: None, advice: None, @@ -1567,9 +1592,11 @@ mod tests { let found = from_log(&commit); let memory: Vec<_> = found .iter() - .filter(|f| f.fix == Some(FIX_GRAPHICS_MEMORY)) + .filter(|f| matches!(f.fix, Some(FIX_GRAPHICS_MEMORY | FIX_COMMIT_MEMORY))) .collect(); assert_eq!(memory.len(), 1, "one finding, so the fix runs once"); + // Windows' commit, not the card: the lighter fix. + assert_eq!(memory[0].fix, Some(FIX_COMMIT_MEMORY)); assert!(memory[0].title.contains("page file")); // The guard's line alone is a compile made later: no finding. assert!(from_log(&commit[..1]).is_empty()); @@ -1849,6 +1876,19 @@ mod tests { assert_eq!(hint.fix, None); } + #[test] + fn a_refused_title_reservation_is_named_and_not_blamed_on_switches_or_memory() { + // From upstream issue #2081 (v2026.11.29.01), the reservation then the stop. + let lines = vec![ + "WARN victory_hle::modules::xmem: XMemVirtualAlloc refused size=6538919936 kind=0x42000 flags=0x23 error=Not enough memory resources are available to process this command. (os error 8)".to_string(), + "VIctory: unhandled exception 0x80000003 at victory-image-0000+0x1e6c284 on thread 1234".to_string(), + ]; + let found = from_log(&lines); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].title.contains("reserve the game's memory")); + assert!(found[0].detail.contains("Restore previous build")); + } + #[test] fn an_unhandled_exception_is_named_with_the_switches_as_the_likely_cause() { let lines = vec!["VIctory: unhandled exception 0x80000003 at game_scarlett_master.exe+0x1ce6e13 on thread 3848".to_string()]; diff --git a/src-tauri/src/launcher.rs b/src-tauri/src/launcher.rs index 527dfe0..dad4f75 100644 --- a/src-tauri/src/launcher.rs +++ b/src-tauri/src/launcher.rs @@ -186,9 +186,10 @@ pub(crate) struct Saved { skip_update_warning: bool, /// Let AI agents read logs and, when the player confirms each step, apply patches. Off by default. agent_access: bool, - // The keyboard-as-controller hook (`controller_keys_on`, `controller_key_bindings`) is gone: - // VIctory-NVIDIA reads mouse and keyboard itself (F1, MOUSE AND KEYBOARD; bindings.ini) and - // pads of every kind. Settings files that still have those fields read as before. + /// Keyboard keys drive the game's controller controls (controller_keys.rs). Off by default. + controller_keys_on: bool, + /// The key the player chose for a controller control, by control id; absent: the layer's own. + controller_key_bindings: std::collections::BTreeMap, /// Ids of the responsibility warnings the player accepted ("import-repo", "agent-access", "agent-patch"). acknowledged: Vec, /// The window's language as a tag ("en", "zh-TW", "zh-CN"); none: the system's. @@ -1916,6 +1917,7 @@ impl App { } pub(crate) fn new(ctx: Ctx, mut saved: Saved) -> App { + crate::controller_keys::configure(saved.controller_keys_on, &saved.controller_key_bindings); if saved.render_scale <= 0.0 { saved.render_scale = 0.5; } @@ -3025,6 +3027,13 @@ fn extra_sets(extra: &str, name: &str, value: &str) -> bool { }) } +/// Whether the player's lines name the switch `name`, with any value. +fn extra_names(extra: &str, name: &str) -> bool { + extra + .lines() + .any(|line| line.split_once('=').is_some_and(|(k, _)| k.trim() == name)) +} + /// The DLSS and frame-generation switches for one run, set the way Neptune's own launcher sets them: /// the F1 menu's saved choice, only on NVIDIA RTX cards, with NVIDIA's files in `dir`. The player's own /// Launch options that name these switches win (nothing is set then). Returns the switches and, for the @@ -3291,6 +3300,28 @@ fn run_until_f1_restart( } fn victory_help(exe: &Path, subcommand: &str) -> Option { + // Asked again for every check and start (through Wine or CrossOver on a Mac, seconds each): + // one answer per program, subcommand and build of the file. + type Key = (PathBuf, String, Option, u64); + static ANSWERS: std::sync::OnceLock>>> = + std::sync::OnceLock::new(); + let meta = std::fs::metadata(exe).ok()?; + let key = ( + exe.to_path_buf(), + subcommand.to_owned(), + meta.modified().ok(), + meta.len(), + ); + let answers = ANSWERS.get_or_init(Default::default); + if let Some(answer) = answers.lock().unwrap().get(&key) { + return answer.clone(); + } + let answer = victory_help_uncached(exe, subcommand); + answers.lock().unwrap().insert(key, answer.clone()); + answer +} + +fn victory_help_uncached(exe: &Path, subcommand: &str) -> Option { let mut command = Command::new(exe); command.args([subcommand, "--help"]); crate::runner::adapt(&mut command); @@ -4113,6 +4144,56 @@ fn fix_graphics( )) } +/// Windows' commit (RAM and page file) ran out: Series S and the memory saver, which ask +/// Windows for less. The render scale, output and texture fix stay: they are for the card's +/// memory, which had room. The page file is the player's to change (the finding says how). +fn fix_commit(job: &Arc>, p: &Project, l: &mut Launch) -> Result { + let before = l.graphics; + let mut g = before; + g.series_s = true; + g.memory = g.memory.max(MemorySaver::Light); + if g == before { + return Ok(format!( + "The settings were already light (Series S, memory saver {:?}).", + g.memory + )); + } + l.graphics = g; + l.series_s = g.series_s; + if g.memory != before.memory { + // This run's switches were made from the old level: add the new one's (later lines win). + l.extra.push_str(&g.memory.lines()); + } + job.lock().unwrap().adjusted_graphics = Some((p.repo.clone(), g)); + Ok(format!( + "Series S, memory saver {:?}; render scale {:.2} and output {:?} kept; saved for the next Play.", + g.memory, g.render_scale, g.output + )) +} + +#[test] +fn the_commit_fix_keeps_the_picture_and_lightens_memory() { + let job = Arc::new(Mutex::new(Job::default())); + let mut launch = test_launch(std::env::temp_dir()); + launch.series_s = false; + launch.graphics.series_s = false; + launch.graphics.render_scale = 0.75; + launch.graphics.output = OutputResolution::P1440; + launch.graphics.memory = MemorySaver::Normal; + let done = fix_commit(&job, &test_project(), &mut launch).unwrap(); + assert!(done.contains("Series S"), "{done}"); + let g = launch.graphics; + assert!(g.series_s && launch.series_s); + assert_eq!(g.memory, MemorySaver::Light); + assert_eq!(g.render_scale, 0.75); + assert_eq!(g.output, OutputResolution::P1440); + assert!(job.lock().unwrap().adjusted_graphics.is_some()); + // Run again: nothing more to change. + assert!(fix_commit(&job, &test_project(), &mut launch) + .unwrap() + .contains("already")); +} + fn open_driver_page(vendor: Option<&str>) -> Result { let url = match vendor { Some("nvidia") => "https://www.nvidia.com/Download/index.aspx", @@ -4169,6 +4250,7 @@ fn apply_finding( diagnose::FIX_PERMISSIONS => fix_permissions(p), diagnose::FIX_DISK => fix_disk(p, job), diagnose::FIX_GRAPHICS_MEMORY => fix_graphics(job, p, l, true), + diagnose::FIX_COMMIT_MEMORY => fix_commit(job, p, l), diagnose::FIX_GRAPHICS_DEVICE => fix_graphics(job, p, l, false), diagnose::FIX_DRIVER_PAGE => open_driver_page(l.gpu_vendor), diagnose::FIX_REPO_SWITCH => fix_repo_switch(job, p, l, finding.data.as_deref()), @@ -4356,6 +4438,13 @@ fn native_nvidia_args(l: &Launch, help: &str) -> Result<(Vec, Vec) -> Option<&'static str> { + let (w, h) = screen?; + if w == 0 || h == 0 { + return None; + } + let off = (u64::from(w) * 9).abs_diff(u64::from(h) * 16) * 100 > u64::from(h) * 16; + off.then_some("2560x1440") +} + +#[test] +fn a_screen_that_is_not_16_9_gets_the_old_picture_size() { + for screen in [(2560, 1440), (1920, 1080), (3840, 2160), (1366, 768)] { + assert_eq!(native_size_for_screen(Some(screen)), None, "{screen:?}"); + } + for screen in [ + (3440, 1440), + (5120, 1440), + (2560, 1600), + (1920, 1200), + (1280, 800), + ] { + assert_eq!( + native_size_for_screen(Some(screen)), + Some("2560x1440"), + "{screen:?}" + ); + } + assert_eq!(native_size_for_screen(None), None); +} + /// The memory saver on VIctory-NVIDIA (`victory play`). That build sizes its own pools for a /// PC under 24 GB of RAM and a card of 8 GB or less, so the launcher only adds what its /// docs/windows-memory.md measured against the crashes the saver is for: @@ -4516,6 +4641,40 @@ fn advice_the_memory_saver_already_sends_is_not_offered() { )); } +#[test] +fn the_players_value_wins_over_the_memory_saver_also_when_it_is_the_presets() { + let root = + std::env::temp_dir().join(format!("vilauncher-nvidia-preset-{}", std::process::id())); + std::fs::create_dir_all(root.join("scripts")).unwrap(); + std::fs::write( + root.join("scripts/play-foxhound.ps1"), + "$settings = @{ +VICTORY_PIPELINE_WORKERS = '4' +}", + ) + .unwrap(); + let mut launch = test_launch(root.clone()); + launch.foxhound_preset = true; + launch.graphics.memory = MemorySaver::Light; + launch.extra = "VICTORY_PIPELINE_WORKERS=4".into(); + let command = native_nvidia_command( + &root.join("victory.exe"), + &root, + &test_project(), + &launch, + &[], + ); + let args: Vec<_> = command + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + assert!( + !args.iter().any(|a| a == "VICTORY_PIPELINE_WORKERS=2"), + "{args:?}" + ); + let _ = std::fs::remove_dir_all(root); +} + fn native_nvidia_command( exe: &Path, root: &Path, @@ -4543,6 +4702,8 @@ fn native_nvidia_command( .arg("play") .arg(l.game_dir.join(EXE_NAME)); let mut switches = std::collections::BTreeMap::new(); + // Every switch the player's lines name, also one left out below for equalling the preset's. + let mut named = std::collections::BTreeSet::new(); switches.insert("VICTORY_FULLSCREEN", if l.fullscreen { "1" } else { "0" }); for (key, value) in l.extra.lines().filter_map(|line| line.split_once('=')) { let (key, value) = (key.trim(), value.trim()); @@ -4553,6 +4714,7 @@ fn native_nvidia_command( ) && !key.starts_with("VICTORY_MENU_") { + named.insert(key); if defaults.get(key).copied() == Some(value) { switches.remove(key); } else { @@ -4563,7 +4725,14 @@ fn native_nvidia_command( // The memory saver's own switches are mostly KLBF Lab's, which this build does not read. // These are the ones it does read for the same need; a player's own value wins. for (key, value) in native_memory_switches(l.graphics.memory) { - switches.entry(key).or_insert(value); + if !named.contains(key) { + switches.insert(key, value); + } + } + if !named.contains("VICTORY_NATIVE_SIZE") { + if let Some(size) = native_size_for_screen(crate::platform::primary_screen()) { + switches.insert("VICTORY_NATIVE_SIZE", size); + } } // `victory play` puts `--set` over what the F1 menu saved, so a switch the player // chose in F1 would be undone at every start: those are left to the menu. @@ -4740,6 +4909,11 @@ fn play( } }, }; + // A build started through its own `play` applies the F1 menu's choices itself and restarts + // itself for those that need it; it also drops every switch given as an environment + // variable (play.rs's KEPT). The launcher's F1 watcher, which closes the game whenever the + // menu's file changes, would close it at every F1 change, even one applied at once. + let native_start = native.is_some(); let mut c = if let Some(command) = native { job.lock() .unwrap() @@ -4778,7 +4952,7 @@ fn play( job.lock().unwrap().stoppable = true; job.lock().unwrap().last_log.clear(); let _ = std::fs::remove_file(project_state(&p.repo).join("last-run.txt")); - let result = run_until_f1_restart(job, ctx, &mut c, l, |pid| { + let spawned = |pid| { record_play_spawn(job, p, pid); if p.local_exe.is_none() { if let Err(error) = build_activity::BuildActivity::record_run(&target_dir(&p.repo)) { @@ -4791,7 +4965,12 @@ fn play( if fullscreen { fullscreen::keep_borderless(pid); } - }); + }; + let result = if native_start { + run_with(job, ctx, &mut c, spawned) + } else { + run_until_f1_restart(job, ctx, &mut c, l, spawned) + }; // The player's Stop is not a crash: nothing is reported for it. let stopped = { let mut j = job.lock().unwrap(); diff --git a/src-tauri/src/launcher/actions.rs b/src-tauri/src/launcher/actions.rs index ab87999..e4b6f85 100644 --- a/src-tauri/src/launcher/actions.rs +++ b/src-tauri/src/launcher/actions.rs @@ -87,6 +87,15 @@ pub(crate) enum Action { SetUpdateWarning { show: bool, }, + /// Turns the keyboard-as-controller keys on or off (controller_keys.rs). + SetControllerKeys { + on: bool, + }, + /// Gives a controller control another key; `key` None goes back to the layer's own. + SetControllerKey { + control: String, + key: Option, + }, /// Let AI agents help with builds (off by default; turning it on needs the "agent-access" warning first). SetAgentAccess { enabled: bool, @@ -523,6 +532,34 @@ impl App { self.saved.skip_update_warning = !show; Value::Null } + Action::SetControllerKeys { on } => { + self.saved.controller_keys_on = on; + crate::controller_keys::configure(on, &self.saved.controller_key_bindings); + Value::Null + } + Action::SetControllerKey { control, key } => { + if crate::controller_keys::control(&control).is_none() { + return Err(format!("There is no controller control {control}.")); + } + match key { + Some(key) => { + crate::controller_keys::check_key( + &self.saved.controller_key_bindings, + &control, + key, + )?; + self.saved.controller_key_bindings.insert(control, key); + } + None => { + self.saved.controller_key_bindings.remove(&control); + } + } + crate::controller_keys::configure( + self.saved.controller_keys_on, + &self.saved.controller_key_bindings, + ); + Value::Null + } Action::SetAgentAccess { enabled } => { self.saved.agent_access = enabled; Value::Null diff --git a/src-tauri/src/launcher/view.rs b/src-tauri/src/launcher/view.rs index d36db69..2c6c75a 100644 --- a/src-tauri/src/launcher/view.rs +++ b/src-tauri/src/launcher/view.rs @@ -52,6 +52,36 @@ struct ListView { items: Vec, } +/// The keyboard-as-controller settings: on or off, and every control with its key. +#[derive(Serialize)] +pub(crate) struct ControllerKeysView { + on: bool, + controls: Vec, +} + +#[derive(Serialize)] +pub(crate) struct ControlView { + id: &'static str, + label: &'static str, + default_key: u16, + key: u16, +} + +fn controller_keys_view(saved: &super::Saved) -> ControllerKeysView { + ControllerKeysView { + on: saved.controller_keys_on, + controls: crate::controller_keys::CONTROLS + .iter() + .map(|control| ControlView { + id: control.id, + label: control.label, + default_key: control.default_key, + key: crate::controller_keys::key_of(&saved.controller_key_bindings, control), + }) + .collect(), + } +} + /// VIctory-NVIDIA's mods folder (mods.rs) and what is in it. None where there is none (off /// Windows). #[derive(Serialize)] @@ -226,6 +256,7 @@ struct SettingsView { backgrounds_dir: String, skip_update_warning: bool, agent_access: bool, + controller_keys: ControllerKeysView, mods: Option, acknowledged: Vec, /// The player's language choice; none: the system's. @@ -434,6 +465,7 @@ impl App { backgrounds_dir: crate::backgrounds::folder().display().to_string(), skip_update_warning: self.saved.skip_update_warning, agent_access: self.saved.agent_access, + controller_keys: controller_keys_view(&self.saved), mods: mods_view(), acknowledged: self.saved.acknowledged.clone(), language: self.saved.language.clone(), diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index ad93aae..227df84 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -14,6 +14,7 @@ mod backgrounds; mod brand; mod build_activity; mod build_zip; +mod controller_keys; mod diagnose; mod fullscreen; mod job_log; diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 69b3beb..e865262 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -6,6 +6,22 @@ import { isLocale, systemLocale } from "@/i18n/locales" import type { Action, AddonView, Graphics, LogView, MacRunner, MacRunnerChoice, Project, ResponsibilityId, Snapshot, StageKind, StorageView } from "@/lib/types" +// The controls VIctory reads from the keyboard, as src-tauri/src/controller_keys.rs lists them. +const CONTROLLER_CONTROLS: { id: string; label: string; default_key: number }[] = [ + { id: "menu", label: "Menu", default_key: 0x1b }, { id: "view", label: "View", default_key: 0x09 }, + { id: "a", label: "A", default_key: 0x0d }, { id: "b", label: "B", default_key: 0x08 }, + { id: "x", label: "X", default_key: 0x58 }, { id: "y", label: "Y", default_key: 0x59 }, + { id: "up", label: "D-pad up", default_key: 0x26 }, { id: "down", label: "D-pad down", default_key: 0x28 }, + { id: "left", label: "D-pad left", default_key: 0x25 }, { id: "right", label: "D-pad right", default_key: 0x27 }, + { id: "left_shoulder", label: "Left shoulder", default_key: 0x51 }, { id: "right_shoulder", label: "Right shoulder", default_key: 0x45 }, + { id: "left_stick_click", label: "Left stick click", default_key: 0x46 }, { id: "right_stick_click", label: "Right stick click", default_key: 0x48 }, + { id: "left_stick_up", label: "Left stick up", default_key: 0x57 }, { id: "left_stick_left", label: "Left stick left", default_key: 0x41 }, + { id: "left_stick_down", label: "Left stick down", default_key: 0x53 }, { id: "left_stick_right", label: "Left stick right", default_key: 0x44 }, + { id: "right_stick_up", label: "Right stick up", default_key: 0x49 }, { id: "right_stick_left", label: "Right stick left", default_key: 0x4a }, + { id: "right_stick_down", label: "Right stick down", default_key: 0x4b }, { id: "right_stick_right", label: "Right stick right", default_key: 0x4c }, + { id: "left_trigger", label: "Left trigger", default_key: 0x5a }, { id: "right_trigger", label: "Right trigger", default_key: 0x43 }, +] + const SAMPLE: { name: string; repo: string; gpu: string[]; fps: number | null; render: number | null; verified: boolean; summary: string }[] = [{"name":"Kelvaroq","repo":"stellarr-studio/kelvaroq","gpu":["NVIDIA"],"fps":10,"render":0.25,"verified":false,"summary":"Kelvaroq is a public Rust runtime built on VIctory and victory-fork. It adds rendering patches and measured submission improvements, and runs the game through the prologue and first mission."},{"name":"Belobug","repo":"Belobug/VIctory-Belobug-AMD","gpu":["AMD"],"fps":22,"render":0.8,"verified":true,"summary":"Belobug's VIctory fork runs on AMD Radeon and is now very playable: about 22 fps on average with no crashes, using about 30 GB of RAM and 12 GB of video memory. Its lit open world plays through missions, with story progress rated 80%, level with CGBJ, and its picture is rated just below DexNom's. Its README hasn't caught up yet: it still reports 5-7 fps."},{"name":"DexNom","repo":"DexNom/VIctory","gpu":["AMD"],"fps":3,"render":0.85,"verified":true,"summary":"DexNom Runtime, a fork of VIctory for AMD Radeon, tested on a Radeon RX 7900 XTX. It builds on ZSlayerHQ's victory-world-runtime with its own fixes for shaders, texture streaming and GPU memory. PortWatch has seen it running with ray-traced lighting working, the first AMD build on our board to get it. Its picture is the best-rated on our board, though lighting and materials still have problems, and it plays through missions at about 3-4 fps (about 1 fps with ray tracing on), rarely crashing."},{"name":"Uilian","repo":"uiliannn/VItoriaBr","gpu":["NVIDIA"],"fps":4,"render":0.2,"verified":false,"summary":"Uilian's VItoriaBr, built on hyphennn's victory-fork with his own NVIDIA work and streamed live on YouTube. On stream it reaches Jason's first mission, \"Gone Fishing\", with poor rendering, up to 4 fps and few crashes."},{"name":"AvatarManz","repo":"avatarmanz/VIctory-7900XTX","gpu":["AMD"],"fps":16,"render":0.7,"verified":true,"summary":"AvatarManz's fork of VIctory, tuned for speed on an AMD Radeon RX 7900 XTX. It brings victory-fork's, DexNom's and Belobug's work together on VIctory and adds its own speed-ups: the game's draw calls translated on eight threads of its own, frames prepared on a separate thread, and textures uploaded on their own queue. PortWatch has verified it: the game runs at about 16 fps on average in game, with sound, as far into the story as the leading builds. Its README measures 13-22 fps indoors and on the first boat mission, and a 41-minute session without a crash."},{"name":"hyphennn","repo":"fxceless/victory-fork","gpu":["NVIDIA"],"fps":3,"render":0.7,"verified":false,"summary":"hyphennn's fork of VIctory (formerly victory-gta6), with his own rendering and speed fixes. On his Rumble streams the prologue plays with ray-traced lighting, detailed textures and hair at about 3 fps; the README still lists shadows as black. Self-reported."},{"name":"VIctory","repo":"Marvisak/VIctory","gpu":["AMD"],"fps":1,"render":0,"verified":false,"summary":"Marvis's Rust layer runs the game natively. The owner reports controlled gameplay is now reachable, though the build remains unstable; the README still says it is not playable and reports about 1 fps in the world."},{"name":"xbox-emulator","repo":"omonkeyz/xbox-emulator","gpu":[],"fps":0,"render":0,"verified":false,"summary":"Rust runtime that runs dumped Xbox Series builds as normal Windows processes, continuing the TomBox project. It reports Trackmania races driving at about 60 fps and Terraria reaching its world, plus Fortnite's lobby. Self-reported."},{"name":"XCL","repo":"xcl-dev/xcl","gpu":["AMD","NVIDIA"],"fps":0,"render":0,"verified":false,"summary":"Wine-style layer running game code natively. On its main branch the game gets past its menus into the world for several testers, but the screen stays on a loading spinner and a GPU watchdog ends the run. Unverified."},{"name":"ScarlettX","repo":"Freminet/ScarlettX","gpu":[],"fps":0,"render":0,"verified":false,"summary":"Clean-room high-level emulator of the Scarlett OS and GDK runtime. It reports two retail Xbox Series games, Concept Destruction and Unicorn Overlord, playable on Windows."},{"name":"TuxBox","repo":"brcly/TuxBox","gpu":["NVIDIA"],"fps":0,"render":0,"verified":false,"summary":"Native-first layer for unpacked Xbox Series games, tested mostly on Linux through Proton. the game reported its own state as \"Game Running\" in the story intro before crashing after about ten minutes, but no picture past the player-selection prompt is shown. Self-reported."},{"name":"OpenScarlett","repo":"californiaAlmonds/OpenScarlett","gpu":["NVIDIA","Intel"],"fps":0,"render":0,"verified":false,"summary":"MIT-licensed C++20 translation layer targeting D3D12 and Vulkan. It now claims 17 boot stops cleared on a retail title it doesn't name, with no run record or frame shown, so no the game milestone yet."},{"name":"scarlett-layer","repo":"jadeowaowa/scarlett-layer","gpu":["NVIDIA"],"fps":0,"render":0,"verified":false,"summary":"Loader plus injected hook DLL that redirects console-only calls to Windows shims, with its own d3d12_xs wrapper and shader lifter. It reports Terraria's GDK build rendering its menus with audio; no gameplay yet."},{"name":"Xbox2Windows","repo":"R0Y00/Xbox2Windows","gpu":["NVIDIA","AMD","Intel"],"fps":0,"render":0,"verified":false,"summary":"Static recompilation research turning Xbox Series code and shaders into Windows C++ and DXIL, with over 50 contributors. Footage the project shared shows the game's menus, unstable. Its README now reports a modified diagnostic exe playing the intro and setup text; the original exe and the menus remain unverified."}] const params = new URLSearchParams(location.search) @@ -41,6 +57,8 @@ const state = { notice: params.get("notice") !== "0", skipUpdateWarning: false, agentAccess: false, + controllerKeysOn: false, + controllerBindings: {} as Record, // VIctory-NVIDIA's mods folder, by name there: "x.dll" on, "x.dll.off" off (?mods=0: empty). mods: (params.get("mods") === "0" ? [] @@ -162,6 +180,10 @@ function snapshot(): Snapshot { : "C:\\Users\\you\\AppData\\Local\\VILauncher\\backgrounds", skip_update_warning: state.skipUpdateWarning, agent_access: state.agentAccess, + controller_keys: { + on: state.controllerKeysOn, + controls: CONTROLLER_CONTROLS.map((c) => ({ ...c, key: state.controllerBindings[c.id] ?? c.default_key })), + }, // As the launcher: the mods folder is a Windows one. mods: platform !== "windows" @@ -378,6 +400,22 @@ async function act(a: Action): Promise { case "set_agent_access": state.agentAccess = a.enabled break + case "set_controller_keys": + state.controllerKeysOn = a.on + break + case "set_controller_key": { + const control = CONTROLLER_CONTROLS.find((c) => c.id === a.control) + if (!control) throw new Error(`There is no controller control ${a.control}.`) + if (a.key === null) { + delete state.controllerBindings[a.control] + break + } + if (a.key === 0 || a.key === 0xff) throw new Error("That key cannot be used for a controller control.") + const other = CONTROLLER_CONTROLS.find((c) => c.id !== a.control && (state.controllerBindings[c.id] ?? c.default_key) === a.key) + if (other) throw new Error(`${other.label} already uses that key.`) + state.controllerBindings[a.control] = a.key + break + } case "mod_add": { const file = a.path.split(/[\\/]/).pop() ?? "" if (!/\.dll$/i.test(file) || file.length <= 4) throw new Error(`${file} is not the name of a mod DLL.`) diff --git a/src/features/settings/controller-keys.tsx b/src/features/settings/controller-keys.tsx new file mode 100644 index 0000000..bae53c8 --- /dev/null +++ b/src/features/settings/controller-keys.tsx @@ -0,0 +1,109 @@ +import { useEffect, useState } from "react" +import { Button } from "@/components/ui/button" +import { Group, Row } from "@/components/ui/group" +import { Switch } from "@/components/ui/switch" +import { useT } from "@/i18n" +import { run, useStore } from "@/lib/store" +import type { ControllerControl } from "@/lib/types" + +/** The controls VIctory reads from the keyboard (src-tauri/src/controller_keys.rs), by id. */ +const CONTROL_IDS = [ + "menu", "view", "a", "b", "x", "y", "up", "down", "left", "right", + "left_shoulder", "right_shoulder", "left_stick_click", "right_stick_click", + "left_stick_up", "left_stick_left", "left_stick_down", "left_stick_right", + "right_stick_up", "right_stick_left", "right_stick_down", "right_stick_right", + "left_trigger", "right_trigger", +] as const +type ControlId = (typeof CONTROL_IDS)[number] + +const ESCAPE = 27 +/** Pressed alone, these do not choose a key. */ +const MODIFIERS = [16, 17, 18, 91, 92] +/** Keys whose names are printed on the keyboard, not translated. */ +const NAMED: Record = { 8: "Backspace", 9: "Tab", 13: "Enter", 32: "Space", 37: "←", 38: "↑", 39: "→", 40: "↓" } + +/** Virtual-key codes VIctory reads: letters and digits are their own character. */ +function isLetterOrDigit(code: number): boolean { + return (code >= 0x30 && code <= 0x39) || (code >= 0x41 && code <= 0x5a) +} + +export function ControllerKeysGroup() { + const t = useT() + const keys = useStore((s) => s.snap)!.settings.controller_keys + const [capturing, setCapturing] = useState(null) + + // While a control waits for its key, the next key press is the choice (Esc cancels). + useEffect(() => { + if (capturing === null) return + const onKey = (event: KeyboardEvent) => { + if (MODIFIERS.includes(event.keyCode)) return + event.preventDefault() + event.stopPropagation() + const id = capturing + setCapturing(null) + if (event.keyCode !== ESCAPE) void run({ type: "set_controller_key", control: id, key: event.keyCode }) + } + window.addEventListener("keydown", onKey, true) + return () => window.removeEventListener("keydown", onKey, true) + }, [capturing]) + + const keyLabel = (code: number) => { + if (NAMED[code]) return NAMED[code] + if (isLetterOrDigit(code)) return String.fromCharCode(code) + return t("settings.controllerKeys.unknownKey", { code: String(code) }) + } + const controlLabel = (control: ControllerControl) => { + const id = control.id as ControlId + return CONTROL_IDS.includes(id) ? t(`settings.controllerKeys.controls.${id}`) : control.label + } + const changed = keys.controls.filter((control) => control.key !== control.default_key) + + return ( + 0 ? ( + + ) : undefined + } + > + + void run({ type: "set_controller_keys", on })} + aria-label={t("settings.controllerKeys.on")} + /> + + {keys.controls.map((control) => ( + + {keyLabel(control.key)} + + {control.key !== control.default_key && ( + + )} + + ))} + + ) +} diff --git a/src/features/settings/mods.tsx b/src/features/settings/mods.tsx index 3adb9af..358e984 100644 --- a/src/features/settings/mods.tsx +++ b/src/features/settings/mods.tsx @@ -16,6 +16,8 @@ import { run, useStore } from "@/lib/store" export function ModsGroups() { const t = useT() const mods = useStore((s) => s.snap)!.settings.mods + // Screenshot mode hides paths: the folder's has the player's Windows user name. + const screenshot = useStore((s) => s.screenshot) const [removing, setRemoving] = useState(null) if (!mods) return null @@ -37,7 +39,7 @@ export function ModsGroups() { } > - {mods.folder}}> + {mods.folder}}> diff --git a/src/features/settings/settings-view.tsx b/src/features/settings/settings-view.tsx index fa905e8..e589a60 100644 --- a/src/features/settings/settings-view.tsx +++ b/src/features/settings/settings-view.tsx @@ -7,6 +7,7 @@ import { Input, Textarea } from "@/components/ui/input" import { Spinner } from "@/components/ui/spinner" import { Switch } from "@/components/ui/switch" import { GraphicsGroups } from "@/features/library/graphics-tab" +import { ControllerKeysGroup } from "@/features/settings/controller-keys" import { ModsGroups } from "@/features/settings/mods" import { MacRunnerGroup, MetalfxRows } from "@/features/settings/mac-runner" import { LanguageSelect } from "@/features/shared/language-select" @@ -194,6 +195,8 @@ export function SettingsView() { {/* VIctory-NVIDIA's mods folder and controls: a Windows folder, so none elsewhere. */} + + Date: Sun, 29 Nov 2026 02:49:30 -0800 Subject: [PATCH 3/3] Fix CI: tests never read the screen; the keyboard mark is Windows-only - The picture-size note for a screen that is not 16:9 read the real screen, so native_nvidia_play_keeps_f1_defaults_and_passes_profile_overrides failed on a runner whose screen is not 16:9. The screen is now looked up through screen_for_native_size, which gives none in tests. - has_own_keyboard and its mark are only read by the Windows hook: on macOS and Linux clippy -D warnings failed on them as dead code. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/controller_keys.rs | 3 +++ src-tauri/src/launcher.rs | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src-tauri/src/controller_keys.rs b/src-tauri/src/controller_keys.rs index fd88636..5d10022 100644 --- a/src-tauri/src/controller_keys.rs +++ b/src-tauri/src/controller_keys.rs @@ -14,9 +14,12 @@ use std::collections::BTreeMap; /// Text only a build with its own mouse and keyboard bindings has in its program: the switch /// naming VIctory-NVIDIA's bindings.ini (crates/victory-hle/src/modules/mnk.rs, play.rs). +// Only the Windows hook reads programs; elsewhere this is for the tests. +#[cfg_attr(not(windows), allow(dead_code))] const OWN_KEYBOARD_MARK: &[u8] = b"VICTORY_MNK_BINDINGS"; /// Whether a program's bytes are those of a build with its own mouse and keyboard. +#[cfg_attr(not(windows), allow(dead_code))] pub fn has_own_keyboard(program: &[u8]) -> bool { program .windows(OWN_KEYBOARD_MARK.len()) diff --git a/src-tauri/src/launcher.rs b/src-tauri/src/launcher.rs index dad4f75..697d4a2 100644 --- a/src-tauri/src/launcher.rs +++ b/src-tauri/src/launcher.rs @@ -4439,7 +4439,7 @@ fn native_nvidia_args(l: &Launch, help: &str) -> Result<(Vec, Vec Option<(u32, u32)> { + if cfg!(test) { + None + } else { + crate::platform::primary_screen() + } +} + fn native_size_for_screen(screen: Option<(u32, u32)>) -> Option<&'static str> { let (w, h) = screen?; if w == 0 || h == 0 { @@ -4730,7 +4740,7 @@ fn native_nvidia_command( } } if !named.contains("VICTORY_NATIVE_SIZE") { - if let Some(size) = native_size_for_screen(crate::platform::primary_screen()) { + if let Some(size) = native_size_for_screen(screen_for_native_size()) { switches.insert("VICTORY_NATIVE_SIZE", size); } }