From b39039e1a76b4b74faa83fb0ede87f87a8d58d91 Mon Sep 17 00:00:00 2001 From: dazacode Date: Sat, 28 Nov 2026 20:16:39 -0800 Subject: [PATCH 1/2] Port KLBF Lab's shader preparation, presets and memory saver - Before Play, translate the game's shaders once per shader translator (`victory shaders`, keyed on `victory shader-fingerprint`) and make the pipelines earlier runs recorded (`victory warm`), as KLBF Lab's play.ps1 does. - Pass KLBF_* switches from Launch options and launch scripts; never set or pass KLBF_LAUNCHER. Name KLBF Lab's own-launcher refusal in the log. - Read a project's play.ps1 along its default path only: no more both sides of if/else, and no variable values such as `VICTORY_GAME_DIR = $Game`. - Graphics presets set a whole setup (profile, scale, output, memory saver), with a recommendation for the PC, a "Fit screen (16:9)" output and a memory saver from VIctory-LITE (GPL-3.0). Fix and verify turns it on after an out-of-memory crash. - Log a frame-rate report after each session: average, median, 5 % and 1 % lows and time in each band, leaving out the first two minutes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + README.md | 5 +- src-tauri/locales/es/launcher.json | 2 + src-tauri/locales/fr/launcher.json | 2 + src-tauri/locales/ru/launcher.json | 2 + src-tauri/locales/zh-CN/launcher.json | 2 + src-tauri/locales/zh-TW/launcher.json | 2 + src-tauri/src/diagnose.rs | 28 +- src-tauri/src/launcher.rs | 365 ++++++++++++++++++++++++-- src-tauri/src/platform/mod.rs | 13 + src-tauri/src/platform/windows.rs | 8 + src-tauri/src/play_stats.rs | 105 +++++++- src-tauri/src/report.rs | 14 +- src-tauri/src/runner.rs | 4 +- src-tauri/src/script_preset.rs | 310 +++++++++++++++++++++- src/dev/mock.ts | 2 +- src/features/library/graphics-tab.tsx | 34 ++- src/i18n/messages/en/format.ts | 13 +- src/i18n/messages/en/library.ts | 4 + src/i18n/messages/es/format.ts | 13 +- src/i18n/messages/es/library.ts | 4 + src/i18n/messages/fr/format.ts | 13 +- src/i18n/messages/fr/library.ts | 4 + src/i18n/messages/ru/format.ts | 13 +- src/i18n/messages/ru/library.ts | 4 + src/i18n/messages/zh-CN/format.ts | 13 +- src/i18n/messages/zh-CN/library.ts | 4 + src/i18n/messages/zh-TW/format.ts | 13 +- src/i18n/messages/zh-TW/library.ts | 4 + src/lib/format.test.ts | 52 +++- src/lib/format.ts | 47 +++- src/lib/types.ts | 6 +- 32 files changed, 1029 insertions(+), 87 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef4b4ca..46ba0a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,18 @@ The release notes for each tag are taken from the section for that version. ## Unreleased +### New +- **Shaders prepared before Play:** on builds that offer it, Play first translates the game's shaders (`victory shaders`) once per build, keyed on the build's shader translator (`victory shader-fingerprint`) so a build with the same translator is not translated again. It then makes the pipelines earlier runs wrote down (`victory warm`), and only when runs wrote down new ones. The game no longer compiles them while it plays. A step that fails is logged and Play goes on; Stop stops it. The same preparation KLBF Lab's own launcher does. +- **KLBF Lab's own switches:** `KLBF_*` lines in Launch options (frame-rate cap, DirectStorage cache, memory stack and the rest of its LAUNCH-OPTIONS.md) now reach the game, and are read from a project's launch scripts and listed in problem reports. VILauncher never sets `KLBF_LAUNCHER`. + +- **Graphics presets are whole setups now** (after KLBF Lab's Console S, Console X and Low spec). Each one sets the console profile, render scale, output and memory saver together, and fits the output to the screen. **Fast** is Series S at half scale with the memory saver, for 8 GB cards or 16 GB of RAM. **Balanced** is Series S at three quarters. **Best quality** is Series X at full resolution. The Graphics tab says which one suits this PC. +- **Memory saver** (Graphics): Normal, Light (16 GB of RAM) or Very light (softer textures, for 8 GB cards). It gives idle memory back to the system sooner, against out-of-memory crashes, and doesn't raise the frame rate. Its switches come from vix0e0e's VIctory-LITE (GPL-3.0), as KLBF Lab carries them, and are set under both their `VICTORY_` and `KLBF_` names. After an out-of-memory crash, Fix and verify turns it on. +- **Fit screen (16:9) output:** the game's output at the main display's height, no wider than it (a 3440x1440 screen gets 2560x1440). Windows reads the display; elsewhere it is 1920x1080. +- **Frame-rate report after each session** (in the log), after KLBF Lab's shared measurement method: average, median, 5 % and 1 % lows, and the share of time spent at 60+, 30-60, 20-30, 10-20, 5-10 and under 5 fps. The first two minutes, while shaders compile, are left out. + ### Fixed +- **A project's play.ps1 defaults:** only what the script sets when run with no arguments is used. Before, both sides of an `if ($Safe) { ... } else { ... }` were applied together. A value the script fills from a variable (`VICTORY_GAME_DIR = $Game`) was passed on as that text, and replaced the game folder. +- **Builds that start only from their own launcher:** when a build refuses to start from another launcher (KLBF Lab since v26.11.9), the log now says so and names the launcher to use, instead of only showing the failure. - **Fix and verify after a rebuild:** when the build finishes but its program is missing, the launcher says where it expected it and suggests checking antivirus, instead of telling you to press Install. - **Linux builds of Windows-only games:** a build that fails because the project uses Windows-only libraries now says so in the log, instead of only showing the compiler's error. diff --git a/README.md b/README.md index 621977a..b701677 100644 --- a/README.md +++ b/README.md @@ -82,8 +82,9 @@ chmod +x VILauncher_*_amd64.AppImage - **Report a problem.** After a failed job, one click opens a GitHub issue with the log filled in. Names and folders are removed first. Nothing is sent until you press Submit on GitHub. - **Storage.** Settings shows how much disk each project uses (sources, builds, previous build, shader cache, saves). You can clear previous builds and shader caches. Saves are never cleared from here. - **Saves.** Continue a save, start fresh, copy from another build, or start from a named checkpoint. Import or export save ZIPs. -- **Launch presets and graphics.** Named argument and environment presets per project, and per-project graphics overrides. -- **Shader warm-up.** Builds the shader cache before the first launch where a project supports it. +- **Launch presets and graphics.** Named argument and environment presets per project, and per-project graphics overrides. The graphics presets (Fast, Balanced, Best quality) each set a whole setup: console profile, render scale, an output fitted to your screen, and a memory saver for 16 GB PCs and 8 GB cards. The Graphics tab says which one suits your PC. +- **Shader warm-up.** Builds the shader cache before the first launch where a project supports it. On builds that offer it, Play translates the game's shaders once per shader translator and makes the pipelines earlier runs recorded, so the game doesn't compile them while you play. +- **Session frame-rate report.** After each Play the log gives the average, median, 5 % and 1 % lows, and the time spent in each frame-rate band, leaving out the first two minutes. - **Activity log.** Full Git and Cargo output, copyable and exportable. Each job's log is also kept on disk. - **AI-agent access (off by default).** Lets an AI agent read logs and, after you confirm, apply a patch and run the project's build. See [Agent tools](#agent-tools). - **Screenshot mode.** Hides names, paths, notes and logs for sharing pictures. diff --git a/src-tauri/locales/es/launcher.json b/src-tauri/locales/es/launcher.json index 4adeee7..af78de4 100644 --- a/src-tauri/locales/es/launcher.json +++ b/src-tauri/locales/es/launcher.json @@ -32,6 +32,8 @@ "could not remove {path}: {error}": "no se pudo eliminar {path}: {error}", "Warming up shaders and pipelines (this can take hours)": "Precompilando shaders y pipelines (esto puede tardar horas)", "Warming up shaders (the first time takes minutes)": "Precompilando shaders (la primera vez tarda minutos)", + "Preparing the game's shaders for this build (once per build)": "Preparando los shaders del juego para esta compilación (una vez por compilación)", + "Preparing the pipelines of earlier runs (only new ones)": "Preparando los pipelines de partidas anteriores (solo los nuevos)", "Installing {what} (this can take a while)": "Instalando {what} (esto puede tardar un rato)", "Waiting for the Command Line Tools installer": "Esperando al instalador de las herramientas de línea de comandos", "the {what} installer was not finished (its window may still be open). Run Install missing tools again when it is.": "el instalador de {what} no terminó (su ventana puede seguir abierta). Vuelve a ejecutar Instalar herramientas faltantes cuando termine.", diff --git a/src-tauri/locales/fr/launcher.json b/src-tauri/locales/fr/launcher.json index 48a8f9c..ece9c99 100644 --- a/src-tauri/locales/fr/launcher.json +++ b/src-tauri/locales/fr/launcher.json @@ -32,6 +32,8 @@ "could not remove {path}: {error}": "impossible de supprimer {path} : {error}", "Warming up shaders and pipelines (this can take hours)": "Précompilation des shaders et des pipelines (cela peut prendre des heures)", "Warming up shaders (the first time takes minutes)": "Précompilation des shaders (la première fois, cela prend quelques minutes)", + "Preparing the game's shaders for this build (once per build)": "Préparation des shaders du jeu pour ce build (une fois par build)", + "Preparing the pipelines of earlier runs (only new ones)": "Préparation des pipelines des parties précédentes (seulement les nouveaux)", "Installing {what} (this can take a while)": "Installation en cours : {what} (cela peut prendre un certain temps)", "Waiting for the Command Line Tools installer": "En attente du programme d’installation des outils en ligne de commande", "the {what} installer was not finished (its window may still be open). Run Install missing tools again when it is.": "l’installation n’est pas terminée : {what} (sa fenêtre est peut-être encore ouverte). Relancez Installer les outils manquants une fois qu’elle l’est.", diff --git a/src-tauri/locales/ru/launcher.json b/src-tauri/locales/ru/launcher.json index a0c0a40..fbd258d 100644 --- a/src-tauri/locales/ru/launcher.json +++ b/src-tauri/locales/ru/launcher.json @@ -32,6 +32,8 @@ "could not remove {path}: {error}": "не удалось удалить {path}: {error}", "Warming up shaders and pipelines (this can take hours)": "Предкомпиляция шейдеров и конвейеров (может занять несколько часов)", "Warming up shaders (the first time takes minutes)": "Предкомпиляция шейдеров (в первый раз занимает несколько минут)", + "Preparing the game's shaders for this build (once per build)": "Подготовка шейдеров игры для этой сборки (один раз на сборку)", + "Preparing the pipelines of earlier runs (only new ones)": "Подготовка конвейеров из прошлых запусков (только новых)", "Installing {what} (this can take a while)": "Установка: {what} (может занять некоторое время)", "Waiting for the Command Line Tools installer": "Ожидание установщика инструментов командной строки", "the {what} installer was not finished (its window may still be open). Run Install missing tools again when it is.": "установка {what} не завершена (возможно, окно ещё открыто). Запустите «Установить недостающие инструменты» снова после завершения.", diff --git a/src-tauri/locales/zh-CN/launcher.json b/src-tauri/locales/zh-CN/launcher.json index 6d1bd12..1fc5088 100644 --- a/src-tauri/locales/zh-CN/launcher.json +++ b/src-tauri/locales/zh-CN/launcher.json @@ -32,6 +32,8 @@ "could not remove {path}: {error}": "无法删除 {path}:{error}", "Warming up shaders and pipelines (this can take hours)": "正在预编译着色器和管线(可能需要数小时)", "Warming up shaders (the first time takes minutes)": "正在预编译着色器(首次需要几分钟)", + "Preparing the game's shaders for this build (once per build)": "正在为此版本准备游戏着色器(每个版本一次)", + "Preparing the pipelines of earlier runs (only new ones)": "正在准备之前运行记录的管线(仅新的)", "Installing {what} (this can take a while)": "正在安装 {what}(可能需要一段时间)", "Waiting for the Command Line Tools installer": "正在等待命令行工具安装程序", "the {what} installer was not finished (its window may still be open). Run Install missing tools again when it is.": "{what} 安装程序尚未完成(它的窗口可能仍处于打开状态)。完成后请再次点击“安装缺少的工具”。", diff --git a/src-tauri/locales/zh-TW/launcher.json b/src-tauri/locales/zh-TW/launcher.json index 0bf24ea..f682141 100644 --- a/src-tauri/locales/zh-TW/launcher.json +++ b/src-tauri/locales/zh-TW/launcher.json @@ -32,6 +32,8 @@ "could not remove {path}: {error}": "無法刪除 {path}:{error}", "Warming up shaders and pipelines (this can take hours)": "正在預先編譯著色器和管線(可能需要數小時)", "Warming up shaders (the first time takes minutes)": "正在預先編譯著色器(第一次需要幾分鐘)", + "Preparing the game's shaders for this build (once per build)": "正在為此版本準備遊戲著色器(每個版本一次)", + "Preparing the pipelines of earlier runs (only new ones)": "正在準備先前執行記錄的管線(僅新的)", "Installing {what} (this can take a while)": "正在安裝 {what}(可能需要一段時間)", "Waiting for the Command Line Tools installer": "正在等待命令列工具安裝程式", "the {what} installer was not finished (its window may still be open). Run Install missing tools again when it is.": "{what} 安裝程式尚未完成(它的視窗可能還開著)。完成後請再按一次「安裝缺少的工具」。", diff --git a/src-tauri/src/diagnose.rs b/src-tauri/src/diagnose.rs index 627182d..8dcf590 100644 --- a/src-tauri/src/diagnose.rs +++ b/src-tauri/src/diagnose.rs @@ -1145,6 +1145,18 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { advice: None, }); } + // KLBF Lab (v26.11.9 on) refuses a `run` its own launcher did not start, by its author's + // choice. The launcher respects that and does not start it as its own launcher would. + if has(&["starts only from its own launcher"]) { + found.push(Finding { + title: "This build starts only from its own launcher.".to_string(), + detail: "Its author made it refuse other launchers, so VILauncher can build it and prepare its shaders but cannot start the game. Start it from the launcher that comes with it (for KLBF Lab: KLBF Lab.exe from its release, or play.ps1 in its folder).".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"]) { @@ -1184,7 +1196,7 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { if has(&["out of memory", "0x8007000E"]) { 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 lowers a 1440p or 4K output to 1080p.".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(), fix: Some(FIX_GRAPHICS_MEMORY), heavy: false, data: None, @@ -1779,6 +1791,20 @@ mod tests { .any(|f| f.title.contains("shader model 6.6"))); } + #[test] + fn a_build_that_refuses_other_launchers_is_named_without_a_fix() { + // KLBF Lab v26.11.9's text on stderr when `run` has no KLBF_LAUNCHER. + let lines = vec![ + "KLBF Lab starts only from its own launcher: it prepares the shaders and settings the game needs.".to_string(), + ]; + let found = from_log(&lines); + let hint = found + .iter() + .find(|f| f.title.contains("its own launcher")) + .expect("an own-launcher finding"); + assert_eq!(hint.fix, None); + } + #[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 bcc4a42..a4c91ea 100644 --- a/src-tauri/src/launcher.rs +++ b/src-tauri/src/launcher.rs @@ -139,6 +139,8 @@ pub(crate) struct Saved { fullscreen: bool, /// Default output resolution for projects without their own graphics settings. output: OutputResolution, + /// Default memory saver for projects without their own graphics settings. + memory: MemorySaver, /// Where projects are downloaded and built (empty: the default folder). install_dir: String, /// Where the shader and pipeline caches go, one folder per build (empty: `\cache`). @@ -258,6 +260,80 @@ pub(crate) struct GraphicsSettings { fullscreen: bool, #[serde(default)] output: OutputResolution, + #[serde(default)] + memory: MemorySaver, +} + +/// How hard the game is asked to give memory back (after VIctory-LITE's low-memory launcher by +/// vix0e0e, GPL-3.0, as KLBF Lab's "Memory Light" carries it). Each switch is set under both names +/// a fork may read it by: `VICTORY_` (VIctory-LITE and the forks with its code) and `KLBF_` +/// (KLBF Lab's port). A fork without them ignores them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub(crate) enum MemorySaver { + #[default] + Normal, + /// For 16 GB of RAM: idle memory given back sooner. Mostly against out-of-memory crashes. + Light, + /// For 8 GB of video memory too: also fewer slots and smaller texture uploads, and textures + /// capped at 512 pixels (a softer picture). + VeryLight, +} + +impl MemorySaver { + /// The switches, without a prefix ([`Self::lines`] adds both). + fn switches(self) -> &'static [(&'static str, &'static str)] { + // LITE's POOL_BLOCK_MB=4 is left out: KLBF Lab found Light crashing with it at the first + // uploads on an RX 9070 XT. + const LIGHT: &[(&str, &str)] = &[ + ("LIBRARY_IDLE_MS", "15000"), + ("SNAPSHOT_POOL_MB", "128"), + ("EXACT_TRIM", "1"), + ("DSTORAGE_RAM_ACCOUNTING", "1"), + ("SCRATCH_SPARE_MB", "32"), + ("POOL_IDLE_BLOCKS", "2"), + ("STAGING_SPARES", "2"), + ("STAGING_PACK", "1"), + ("TILE_IDLE_RELEASE", "1"), + ("WINDOW_IDLE_MS", "2500"), + ("SEND_SPARE_MB", "32"), + ]; + const VERY_LIGHT: &[(&str, &str)] = &[ + ("LIBRARY_IDLE_MS", "15000"), + ("SNAPSHOT_POOL_MB", "128"), + ("EXACT_TRIM", "1"), + ("DSTORAGE_RAM_ACCOUNTING", "1"), + ("SCRATCH_SPARE_MB", "32"), + ("POOL_IDLE_BLOCKS", "2"), + ("STAGING_SPARES", "2"), + ("STAGING_PACK", "1"), + ("TILE_IDLE_RELEASE", "1"), + ("WINDOW_IDLE_MS", "1500"), + ("SEND_SPARE_MB", "16"), + ("DYNAMIC_SLOTS", "262144"), + ("TEXTURE_STAGE_MB", "64"), + ("CARD_BUFFERS_MB", "128"), + ("TEXTURE_MAX_DIM", "512"), + ("TEXTURE_MAX_DIM_AUX", "256"), + ("TEXTURE_PRESSURE_CAP", "1"), + ]; + match self { + Self::Normal => &[], + Self::Light => LIGHT, + Self::VeryLight => VERY_LIGHT, + } + } + + /// The switches as Launch options lines, each under both prefixes. + fn lines(self) -> String { + self.switches() + .iter() + .flat_map(|(name, value)| { + crate::script_preset::SWITCH_PREFIXES + .iter() + .map(move |prefix| format!("\n{prefix}{name}={value}")) + }) + .collect() + } } #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -269,19 +345,73 @@ pub(crate) enum OutputResolution { P1080, P1440, P2160, + /// 16:9 at the main display's height, no wider than it: the whole height used, no stretching + /// (5120x1440 gives 2560x1440). 1920x1080 when the display is not known. + Screen, } impl OutputResolution { - fn dimensions(self) -> Option<&'static str> { + fn dimensions(self) -> Option { match self { Self::Default => None, - Self::P720 => Some("1280x720"), - Self::P936 => Some("1664x936"), - Self::P1080 => Some("1920x1080"), - Self::P1440 => Some("2560x1440"), - Self::P2160 => Some("3840x2160"), + Self::P720 => Some("1280x720".into()), + Self::P936 => Some("1664x936".into()), + Self::P1080 => Some("1920x1080".into()), + Self::P1440 => Some("2560x1440".into()), + Self::P2160 => Some("3840x2160".into()), + Self::Screen => { + let (width, height) = screen_16_9(crate::platform::primary_screen()); + Some(format!("{width}x{height}")) + } } } + + /// The output's height in pixels, `None` for the game's own. + fn height(self) -> Option { + let size = self.dimensions()?; + size.split_once('x')?.1.parse().ok() + } +} + +/// A 16:9 size at the screen's height, no wider than the screen (KLBF Lab's choice for its +/// presets): 2560x1080 gives 1920x1080, 1920x1200 gives 1920x1080. No screen: 1920x1080. +fn screen_16_9(screen: Option<(u32, u32)>) -> (u32, u32) { + let Some((width, height)) = screen.filter(|(w, h)| *w > 0 && *h > 0) else { + return (1920, 1080); + }; + let mut out = ((height as f64 * 16.0 / 9.0).round() as u32, height); + if out.0 > width { + out = (width, (width as f64 * 9.0 / 16.0).round() as u32); + } + // Even sizes: some upscalers refuse odd ones. + (out.0 & !1, out.1 & !1) +} + +#[cfg(test)] +#[test] +fn screen_output_fits_the_screen_height_at_16_9() { + assert_eq!(screen_16_9(Some((1920, 1080))), (1920, 1080)); + assert_eq!(screen_16_9(Some((5120, 1440))), (2560, 1440)); + assert_eq!(screen_16_9(Some((3440, 1440))), (2560, 1440)); + assert_eq!(screen_16_9(Some((1920, 1200))), (1920, 1080)); + assert_eq!(screen_16_9(Some((1366, 768))), (1364, 768)); + assert_eq!(screen_16_9(None), (1920, 1080)); +} + +#[cfg(test)] +#[test] +fn the_memory_saver_sets_each_switch_under_both_names() { + assert!(MemorySaver::Normal.lines().is_empty()); + let light = MemorySaver::Light.lines(); + assert!(light.contains("\nVICTORY_EXACT_TRIM=1") && light.contains("\nKLBF_EXACT_TRIM=1")); + assert!(!light.contains("POOL_BLOCK_MB")); + assert!(!light.contains("TEXTURE_MAX_DIM")); + let very = MemorySaver::VeryLight.lines(); + assert!( + very.contains("\nVICTORY_TEXTURE_MAX_DIM=512") + && very.contains("\nKLBF_WINDOW_IDLE_MS=1500") + ); + assert!(MemorySaver::Light < MemorySaver::VeryLight); } impl Saved { @@ -293,6 +423,7 @@ impl Saved { bright_shadows: self.bright_shadows, fullscreen: self.fullscreen, output: self.output, + memory: self.memory, } } @@ -303,6 +434,7 @@ impl Saved { self.bright_shadows = graphics.bright_shadows; self.fullscreen = graphics.fullscreen; self.output = graphics.output; + self.memory = graphics.memory; } fn graphics_for(&self, repo: &str) -> GraphicsSettings { @@ -326,6 +458,7 @@ impl Saved { if graphics.bright_shadows { extra.push_str("\nVICTORY_AMBIENT=0.6"); } + extra.push_str(&graphics.memory.lines()); if let Some(switches) = switches { extra.push('\n'); extra.push_str(switches); @@ -1107,24 +1240,9 @@ fn detect_launch_env(repo_dir: &Path) -> Vec<(String, String)> { let Ok(text) = std::fs::read_to_string(&script) else { return Vec::new(); }; - let mut vars = Vec::new(); - // Parse PowerShell hashtable lines like: VICTORY_FOO = '1'; VICTORY_BAR = '2' - // They appear inside $settings = @{ ... } and in conditional blocks. - for line in text.lines() { - let line = line.trim().trim_end_matches(';').trim(); - // Match lines containing VICTORY_ assignments with single-quoted values. - for part in line.split(';') { - let part = part.trim(); - if let Some((k, v)) = part.split_once('=') { - let k = k.trim().trim_start_matches("$settings."); - let v = v.trim().trim_matches('\'').trim_matches('"'); - if k.starts_with("VICTORY_") && !k.contains(' ') { - vars.push((k.to_string(), v.to_string())); - } - } - } - } - vars + // Only what the script sets when run with no arguments: not both sides of `if ($Safe)`, + // and never a value it fills from a variable (`VICTORY_GAME_DIR = $Game`). + script_preset::default_settings(&text) } /// The commit an installed build was made from, written after a build. fn built_file(repo: &str) -> PathBuf { @@ -2632,6 +2750,7 @@ fn test_launch(dir: PathBuf) -> Launch { bright_shadows: true, fullscreen: false, output: OutputResolution::Default, + memory: MemorySaver::Normal, }, gpu_vendor: Some("nvidia"), hardware: Default::default(), @@ -2836,7 +2955,8 @@ fn victory_env(c: &mut Command, p: &Project, l: &Launch) { for line in l.extra.lines() { if let Some((k, v)) = line.split_once('=') { let k = k.trim(); - if k.starts_with("VICTORY_") { + // KLBF Lab's own switches (KLBF_FPS_CAP, KLBF_DSTORAGE_CACHE_MB...) as well as VICTORY_ ones. + if script_preset::has_switch_prefix(k) && k != script_preset::OWN_STARTER_ONLY { c.env(k, v.trim()); } } @@ -3323,6 +3443,188 @@ fn warm(job: &Arc>, ctx: &Ctx, p: &Project, l: &Launch) -> Result<(), Ok(()) } +/// The mark of the last translation ahead, in the project's cache: the [`shader_stamp`] it was made for. +const SHADERS_AHEAD_MARK: &str = "shaders-ahead.txt"; +/// The pipelines runs wrote down (`VICTORY_PIPELINE_BOOK=1`), and the mark of the last `victory warm` +/// that made them, both in the cache's `pipelines` folder (where `victory warm` keeps its own files). +const PIPELINE_BOOK: &str = "known-pipelines.bin"; +const PIPELINES_WARMED_MARK: &str = "warmed.txt"; + +/// The preparation KLBF Lab's play.ps1 does before each start, for any build that offers its commands: +/// the game's shaders translated ahead once per translator (`victory shaders`), then the pipelines earlier +/// runs wrote down made ahead into the driver's cache (`victory warm`), only when runs wrote down new ones. +/// Without it the game translates and compiles while it plays: stutter, and on KLBF Lab black screens. +/// A step that fails or is missing is logged and Play goes on; the player's Stop stops Play. +fn prepare_ahead( + job: &Arc>, + ctx: &Ctx, + p: &Project, + l: &Launch, + exe: &Path, +) -> Result<(), String> { + let cache = project_cache(&p.repo); + let rpf = l.game_dir.join("shaders.rpf"); + // The player's own warm-up (Settings) translated them already for this Play. + if !l.warm_first && rpf.is_file() && victory_help(exe, "shaders").is_some() { + let mut command = Command::new(exe); + command.arg("shaders").arg(&rpf); + victory_env(&mut command, p, l); + let stamp = shader_stamp(exe, &command); + let mark = cache.join(SHADERS_AHEAD_MARK); + let have = std::fs::read_to_string(&mark).unwrap_or_default(); + if stamp.as_deref() != Some(have.trim()) { + stage( + job, + ctx, + msg_str!("Preparing the game's shaders for this build (once per build)"), + ); + match run_stoppable(job, ctx, &mut command)? { + Ok(()) => { + if let Some(stamp) = stamp { + let _ = std::fs::create_dir_all(&cache); + let _ = std::fs::write(&mark, stamp); + } + } + Err(error) => job.lock().unwrap().log.push(format!( + "Translating the shaders ahead failed ({error}); they are translated while playing instead." + )), + } + } + } + let pipelines = cache.join("pipelines"); + if warm_needed( + &pipelines.join(PIPELINE_BOOK), + &pipelines.join(PIPELINES_WARMED_MARK), + ) && victory_help(exe, "warm").is_some() + { + stage( + job, + ctx, + msg_str!("Preparing the pipelines of earlier runs (only new ones)"), + ); + let mut command = Command::new(exe); + command.arg("warm"); + victory_env(&mut command, p, l); + prepare_pipeline_cache(&command)?; + match run_stoppable(job, ctx, &mut command)? { + Ok(()) => { + // Only its time counts (warm_needed). + let _ = std::fs::write(pipelines.join(PIPELINES_WARMED_MARK), "warmed\n"); + } + Err(error) => job.lock().unwrap().log.push(format!( + "Making the pipelines ahead stopped early ({error}); the rest are made while playing." + )), + } + } + Ok(()) +} + +/// Runs `command` as a step the player may stop. The outer error is the player's Stop (Play ends +/// there); the inner one is the step's own failure. +fn run_stoppable( + job: &Arc>, + ctx: &Ctx, + command: &mut Command, +) -> Result, String> { + job.lock().unwrap().stoppable = true; + let result = run_with(job, ctx, command, |pid| job.lock().unwrap().pid = Some(pid)); + let stopped = { + let mut j = job.lock().unwrap(); + j.stoppable = false; + j.pid = None; + j.stopped + }; + if stopped { + return Err("stopped".into()); + } + Ok(result) +} + +/// What the translations ahead depend on, as KLBF Lab's play.ps1 keys them: the build's translator +/// (`victory shader-fingerprint` where the build has it, else the program's size and time), and the two +/// switches that change what is translated. `None` when the program cannot be read. +fn shader_stamp(exe: &Path, command: &Command) -> Option { + let translator = victory_output(exe, &["shader-fingerprint"]) + .map(|out| out.trim().to_owned()) + .filter(|id| { + (1..=64).contains(&id.len()) && id.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) + .map(|id| format!("translator|{id}")) + .or_else(|| { + let meta = std::fs::metadata(exe).ok()?; + let modified = meta + .modified() + .ok()? + .duration_since(std::time::UNIX_EPOCH) + .ok()?; + Some(format!("{}|{}", meta.len(), modified.as_nanos())) + })?; + let switch = |name: &str| { + command + .get_envs() + .find(|(key, _)| *key == name) + .and_then(|(_, value)| value) + .map(|value| value.to_string_lossy().into_owned()) + .unwrap_or_default() + }; + Some(format!( + "{translator}|probe={}|rays={}", + switch("VICTORY_PROBE_RAYS"), + switch("VICTORY_BVH_BUILDER") + )) +} + +/// Whether `victory warm` has work: runs wrote down pipelines (`book`) after the last warm (`mark`). +fn warm_needed(book: &Path, mark: &Path) -> bool { + let modified = |path: &Path| std::fs::metadata(path).and_then(|meta| meta.modified()); + match (modified(book), modified(mark)) { + (Err(_), _) => false, + (Ok(_), Err(_)) => true, + (Ok(book), Ok(mark)) => book > mark, + } +} + +/// The output of `exe args`, when it ran and succeeded. No window. +fn victory_output(exe: &Path, args: &[&str]) -> Option { + let mut command = Command::new(exe); + command.args(args).stdin(Stdio::null()); + crate::runner::adapt(&mut command); + hide_window(&mut command); + let output = command.output().ok()?; + output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +} + +#[cfg(test)] +#[test] +fn pipelines_are_made_ahead_only_after_runs_wrote_new_ones() { + let dir = std::env::temp_dir().join(format!("vilauncher-warm-needed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (book, mark) = (dir.join(PIPELINE_BOOK), dir.join(PIPELINES_WARMED_MARK)); + assert!(!warm_needed(&book, &mark), "no book: nothing to make"); + std::fs::write(&book, b"1").unwrap(); + assert!(warm_needed(&book, &mark), "a book never warmed"); + std::fs::write(&mark, b"1").unwrap(); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(60); + std::fs::File::options() + .write(true) + .open(&mark) + .unwrap() + .set_modified(later) + .unwrap(); + assert!(!warm_needed(&book, &mark), "warmed after the book"); + std::fs::File::options() + .write(true) + .open(&book) + .unwrap() + .set_modified(later + std::time::Duration::from_secs(60)) + .unwrap(); + assert!(warm_needed(&book, &mark), "runs wrote new pipelines since"); + std::fs::remove_dir_all(dir).unwrap(); +} + /// Every required game file is in `dir`. /// The game's program must be a Windows program, which starts with "MZ". A damaged copy, or /// another file under the game's name, does not; the game's loader then fails with @@ -3775,9 +4077,11 @@ fn fix_graphics( let mut g = before; if memory { g.render_scale = g.render_scale.min(0.25); - if matches!(g.output, OutputResolution::P1440 | OutputResolution::P2160) { + if g.output.height().is_some_and(|height| height > 1080) { g.output = OutputResolution::P1080; } + // The memory saver gives idle memory back sooner: what out-of-memory crashes need. + g.memory = g.memory.max(MemorySaver::Light); } else { g.render_scale = (g.render_scale - 0.15).max(0.25); } @@ -3800,10 +4104,14 @@ fn fix_graphics( l.extra .push_str("\nVICTORY_TEXTURE_DROP_MIPS=2\nVICTORY_NULL_COLOR=grey"); } + 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!( - "Render scale {:.2} -> {:.2}, Series S, texture fix on, output {:?}; saved for the next Play.", - before.render_scale, g.render_scale, g.output + "Render scale {:.2} -> {:.2}, Series S, texture fix on, output {:?}, memory saver {:?}; saved for the next Play.", + before.render_scale, g.render_scale, g.output, g.memory )) } @@ -4249,6 +4557,7 @@ fn play( .push(format!("Warm-up failed: {e}. Starting the game anyway.")); } } + prepare_ahead(job, ctx, p, l, &exe)?; if let Some(problem) = game_program_problem(&l.game_dir) { return Err(problem); } diff --git a/src-tauri/src/platform/mod.rs b/src-tauri/src/platform/mod.rs index 33bfc69..3b078ca 100644 --- a/src-tauri/src/platform/mod.rs +++ b/src-tauri/src/platform/mod.rs @@ -174,6 +174,19 @@ pub(crate) fn commit_charge() -> Option { } } +/// The main display's size in pixels, when the system says. Windows only for now; elsewhere +/// a "fit the screen" output falls back to 1080p. +pub(crate) fn primary_screen() -> Option<(u32, u32)> { + #[cfg(windows)] + { + windows::primary_screen() + } + #[cfg(not(windows))] + { + None + } +} + /// Commit pages of `page_bytes` each, as gigabytes to one decimal. None for an empty limit. #[cfg_attr(not(windows), allow(dead_code))] pub(crate) fn commit_from_pages( diff --git a/src-tauri/src/platform/windows.rs b/src-tauri/src/platform/windows.rs index 01bfdba..badb44d 100644 --- a/src-tauri/src/platform/windows.rs +++ b/src-tauri/src/platform/windows.rs @@ -22,6 +22,14 @@ pub(super) fn commit_charge() -> Option { super::commit_from_pages(info.CommitLimit, info.CommitTotal, info.PageSize) } +/// The main display's size in pixels (the launcher is DPI aware, so these are real pixels). +pub(super) fn primary_screen() -> Option<(u32, u32)> { + use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSCREEN, SM_CYSCREEN}; + // SAFETY: GetSystemMetrics only reads a system value. + let (width, height) = unsafe { (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)) }; + (width > 0 && height > 0).then_some((width as u32, height as u32)) +} + /// Free bytes on the volume holding `dir`, read with `fsutil`. pub(super) fn free_bytes(dir: &Path) -> Option { let drive: String = dir diff --git a/src-tauri/src/play_stats.rs b/src-tauri/src/play_stats.rs index 2222883..69082aa 100644 --- a/src-tauri/src/play_stats.rs +++ b/src-tauri/src/play_stats.rs @@ -22,6 +22,9 @@ struct Record { without_exact_60: FpsAverage, #[serde(skip)] started: Option, + /// This session's readings: seconds since it started, and the frame rate. + #[serde(skip)] + readings: Vec<(f64, f64)>, } impl Record { @@ -173,6 +176,10 @@ impl Session { record.samples += 1; record.mean_fps += (value - record.mean_fps) / record.samples as f64; record.latest_fps = Some(value); + let at = record + .started + .map_or(0.0, |started| started.elapsed().as_secs_f64()); + record.readings.push((at, value)); } } @@ -193,10 +200,80 @@ impl Session { record.mean_fps, record.samples ) }; - format!("Session playtime {} · {fps}", duration(record.session_ms)) + let mut summary = format!("Session playtime {} · {fps}", duration(record.session_ms)); + if let Some(report) = session_report(&record.readings) { + summary.push('\n'); + summary.push_str(&report); + } + summary } } +/// The readings taken while the first shaders compile, left out of the report (as KLBF Lab's +/// shared measurement method leaves out the start). +const WARM_UP_SECONDS: f64 = 120.0; + +/// The frame-rate bands of the report, highest first: (lowest fps in the band, its name). +const BANDS: &[(f64, &str)] = &[ + (60.0, "60+"), + (30.0, "30-60"), + (20.0, "20-30"), + (10.0, "10-20"), + (5.0, "5-10"), + (0.0, "under 5 (freezes)"), +]; + +/// A session's frame rate the way KLBF Lab's shared method reports it, so numbers from +/// different builds can be compared: the average, median, 5 % low and 1 % low, and the share +/// of readings in each band. The first two minutes are left out when later readings exist. +/// `None` without readings. +fn session_report(readings: &[(f64, f64)]) -> Option { + let after: Vec = readings + .iter() + .filter(|(at, _)| *at >= WARM_UP_SECONDS) + .map(|(_, fps)| *fps) + .collect(); + let (mut values, note) = if after.is_empty() { + ( + readings.iter().map(|(_, fps)| *fps).collect::>(), + "whole session, shorter than 2 min", + ) + } else { + (after, "after the first 2 min") + }; + if values.is_empty() { + return None; + } + values.sort_by(f64::total_cmp); + let count = values.len(); + // The value under which that share of the readings falls (nearest rank). + let low = |share: f64| values[((count as f64 * share).ceil() as usize).clamp(1, count) - 1]; + let median = if count % 2 == 1 { + values[count / 2] + } else { + (values[count / 2 - 1] + values[count / 2]) / 2.0 + }; + let average = values.iter().sum::() / count as f64; + let mut bands = Vec::new(); + let mut above = f64::INFINITY; + for (floor, name) in BANDS { + let inside = values + .iter() + .filter(|fps| **fps >= *floor && **fps < above) + .count(); + if inside > 0 { + bands.push(format!("{name} {}%", (inside * 100 + count / 2) / count)); + } + above = *floor; + } + Some(format!( + "Frame rate ({note}, {count} readings): average {average:.1}, median {median:.1}, 5% low {:.1}, 1% low {:.1} · time in each band: {}", + low(0.05), + low(0.01), + bands.join(", ") + )) +} + impl Drop for Session { fn drop(&mut self) { self.stop_clock(); @@ -303,6 +380,32 @@ mod tests { assert!(restored.averages(false).is_empty() && restored.averages(true).is_empty()); } + #[test] + fn the_session_report_leaves_out_the_warm_up_and_gives_lows_and_bands() { + assert_eq!(session_report(&[]), None); + // Warm-up readings (1 fps) are left out once later ones exist. + let mut readings: Vec<(f64, f64)> = (0..10).map(|i| (i as f64 * 5.0, 1.0)).collect(); + readings.extend((0..100).map(|i| (130.0 + i as f64 * 5.0, if i < 2 { 4.0 } else { 40.0 }))); + let report = session_report(&readings).unwrap(); + assert!( + report.starts_with("Frame rate (after the first 2 min, 100 readings):"), + "{report}" + ); + assert!(report.contains("average 39.3, median 40.0"), "{report}"); + assert!(report.contains("5% low 40.0, 1% low 4.0"), "{report}"); + assert!( + report.contains("30-60 98%, under 5 (freezes) 2%"), + "{report}" + ); + // A short session keeps all of its readings, and says so. + let short = session_report(&[(1.0, 10.0), (6.0, 20.0)]).unwrap(); + assert!( + short.contains("whole session, shorter than 2 min, 2 readings"), + "{short}" + ); + assert!(short.contains("median 15.0"), "{short}"); + } + #[test] fn only_finite_renderer_measurements_count() { assert_eq!(renderer_fps("target 60 fps, 16.7 ms/frame"), None); diff --git a/src-tauri/src/report.rs b/src-tauri/src/report.rs index 2b55069..22d92b5 100644 --- a/src-tauri/src/report.rs +++ b/src-tauri/src/report.rs @@ -187,22 +187,16 @@ pub(crate) struct SummaryFacts<'a> { pub private: Vec, } -/// The `VICTORY_NAME=value` lines of a launch, names and values only. A value that is not -/// a plain token (anything with a slash, a colon or a space) is replaced by a note, so a -/// path never reaches the summary. +/// The `VICTORY_NAME=value` and `KLBF_NAME=value` lines of a launch, names and values only. +/// A value that is not a plain token (anything with a slash, a colon or a space) is replaced +/// by a note, so a path never reaches the summary. fn switch_lines(extra: &str) -> Vec { extra .lines() .map(str::trim) - .filter(|line| line.starts_with("VICTORY_")) .filter_map(|line| { let (name, value) = line.split_once('=').unwrap_or((line, "")); - let rest = name.strip_prefix("VICTORY_")?; - let name_ok = !rest.is_empty() - && rest - .bytes() - .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_'); - if !name_ok { + if !crate::script_preset::is_switch_name(name) { return None; } if value.is_empty() { diff --git a/src-tauri/src/runner.rs b/src-tauri/src/runner.rs index cb60b98..56eacde 100644 --- a/src-tauri/src/runner.rs +++ b/src-tauri/src/runner.rs @@ -191,7 +191,9 @@ impl Runner { match value { Some(value) => { let text = value.to_string_lossy(); - if name.to_string_lossy().starts_with("VICTORY_") && text.starts_with('/') { + if crate::script_preset::has_switch_prefix(&name.to_string_lossy()) + && text.starts_with('/') + { out.env(name, windows_path(&text)); } else { out.env(name, value); diff --git a/src-tauri/src/script_preset.rs b/src-tauri/src/script_preset.rs index 76ead6d..d0b740a 100644 --- a/src-tauri/src/script_preset.rs +++ b/src-tauri/src/script_preset.rs @@ -13,6 +13,31 @@ pub const RAY_TRACING: &[&str] = &["VICTORY_BVH_BUILDER"]; pub const PROBE_RAYS: &[&str] = &["VICTORY_ACTIVATE_RAYS", "VICTORY_RT_RESOLVE"]; pub const HOOKS: &[&str] = &["VICTORY_GPU_ONLY", "VICTORY_KNOWN_WRITES"]; +/// The prefixes of the switches a build reads from its environment: `VICTORY_` for every +/// fork, `KLBF_` for KLBF Lab's own (its docs/klbf/LAUNCH-OPTIONS.md). +pub const SWITCH_PREFIXES: &[&str] = &["VICTORY_", "KLBF_"]; + +/// What KLBF Lab's own starters set so its `run` starts (`KLBF_LAUNCHER`). The launcher +/// never sets it or passes it on: that build starts only from its own launcher. +pub const OWN_STARTER_ONLY: &str = "KLBF_LAUNCHER"; + +/// Whether `name` is a switch the launcher passes to a build: a known prefix, then only +/// capitals, digits and `_`. Never [`OWN_STARTER_ONLY`]. +pub fn is_switch_name(name: &str) -> bool { + has_switch_prefix(name) + && name != OWN_STARTER_ONLY + && name + .bytes() + .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_') +} + +/// Whether `name` starts with one of [`SWITCH_PREFIXES`] and has more after it. +pub fn has_switch_prefix(name: &str) -> bool { + SWITCH_PREFIXES + .iter() + .any(|prefix| name.len() > prefix.len() && name.starts_with(prefix)) +} + /// Read a literal launch hashtable and recognize the supported Scarlett flag mappings. pub fn parse(script: &str) -> Result<(String, Options), String> { let lines: Vec<_> = script @@ -84,6 +109,201 @@ pub fn parse(script: &str) -> Result<(String, Options), String> { Ok((switches, options)) } +/// The literal switches a launch script sets when it is run with no arguments: the main +/// hashtable, and the `if` / `elseif` / `else` branches its default path takes. A `[switch]` +/// parameter is off unless the `param` block gives it `= $true`; a condition the launcher cannot +/// read is taken as false. Later assignments win. Folder switches, values that are not plain +/// quoted text, and `$env:` lines are left out. +pub fn default_settings(script: &str) -> Vec<(String, String)> { + #[derive(Clone, Copy)] + struct Block { + taken: bool, + /// Whether this is a branch of an if chain, and whether a branch of the chain was taken. + chain: Option, + } + let script = script.trim_start_matches('\u{feff}'); + let on_by_default = switches_on_by_default(script); + let mut stack: Vec = Vec::new(); + // The if chain that just closed at this level: whether one of its branches was taken. + let mut closed_chain: Option = None; + let mut found: Vec<(String, String)> = Vec::new(); + let take = |text: &str, stack: &[Block], found: &mut Vec<(String, String)>| { + if !stack.iter().all(|block| block.taken) { + return; + } + for part in assignments(text) { + let part = part.trim(); + // `$set.NAME = '1'` or `NAME = '1'` inside the hashtable; never `$env:NAME`. + let part = match part.strip_prefix('$') { + Some(rest) => match rest.split_once('.') { + Some((variable, rest)) + if variable + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') => + { + rest + } + _ => continue, + }, + None => part, + }; + if let Some((key, value)) = literal_assignment(part, None) { + if matches!( + key, + "VICTORY_GAME_DIR" + | "VICTORY_CACHE_DIR" + | "VICTORY_DATA_DIR" + | "VICTORY_CONFIG" + ) { + continue; + } + found.retain(|(name, _)| name != key); + found.push((key.to_owned(), value.to_owned())); + } + } + }; + for line in script.lines() { + let mut text = String::new(); + let mut quote = None; + for ch in line.chars() { + match (quote, ch) { + (Some(open), ch) => { + if open == ch { + quote = None; + } + text.push(ch); + } + (None, '\'' | '"') => { + quote = Some(ch); + text.push(ch); + } + (None, '#') => break, + (None, '{') => { + let head = text + .split_whitespace() + .collect::() + .to_ascii_lowercase(); + let (taken, chain) = if let Some(condition) = head.strip_prefix("elseif") { + let earlier = closed_chain.unwrap_or(true); + let now = !earlier && condition_holds(condition, &on_by_default); + (now, Some(earlier || now)) + } else if head == "else" { + let earlier = closed_chain.unwrap_or(true); + (!earlier, Some(true)) + } else if let Some(condition) = head.strip_prefix("if") { + let now = condition_holds(condition, &on_by_default); + (now, Some(now)) + } else { + // The hashtable (`$set = [ordered]@{`) is part of the default path; a + // loop, a script block or a function is not. + (head.ends_with("@"), None) + }; + if head.ends_with('@') { + // What came before `@{` is the variable it is assigned to, not a switch. + } else { + take(&text, &stack, &mut found); + } + stack.push(Block { taken, chain }); + closed_chain = None; + text.clear(); + } + (None, '}') => { + take(&text, &stack, &mut found); + text.clear(); + closed_chain = stack.pop().and_then(|block| block.chain); + } + (None, ch) => { + if !ch.is_whitespace() && closed_chain.is_some() { + // Something other than `else` after a closed chain ends it; `else` + // and `elseif` reach `{` with their head still in `text`. + let head = format!("{text}{ch}").trim_start().to_ascii_lowercase(); + if !"elseif".starts_with(head.as_str()) && !head.starts_with("elseif") { + closed_chain = None; + } + } + text.push(ch); + } + } + } + take(&text, &stack, &mut found); + } + found +} + +/// The `[switch]$Name = $true` parameters, in lower case. +fn switches_on_by_default(script: &str) -> Vec { + script + .lines() + .flat_map(|line| { + let compact = line + .split_whitespace() + .collect::() + .to_ascii_lowercase(); + // Several parameters may share a line: `[switch]$A, [switch]$B = $true)`. + compact + .split("[switch]$") + .skip(1) + .filter_map(|rest| { + let (name, value) = rest.split_once('=')?; + let name_ok = name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'); + (name_ok && value.starts_with("$true")).then(|| name.to_owned()) + }) + .collect::>() + }) + .collect() +} + +/// Whether a condition, as `($name -and -not $other)` without spaces and in lower case, holds +/// with every switch at its default. Only switches joined by `-and` / `-or` (left to right, as +/// PowerShell reads them) and `-not` / `!` are read; anything else is false. +fn condition_holds(condition: &str, on_by_default: &[String]) -> bool { + let Some(inner) = condition + .strip_prefix('(') + .and_then(|rest| rest.strip_suffix(')')) + else { + return false; + }; + let term = |term: &str| -> Option { + let (negated, name) = match term.strip_prefix("-not").or_else(|| term.strip_prefix('!')) { + Some(rest) => (true, rest), + None => (false, term), + }; + let name = name.strip_prefix('$')?; + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return None; + } + Some(on_by_default.iter().any(|on| on == name) != negated) + }; + let mut value = None; + let mut rest = inner; + let mut join: Option<&str> = None; + loop { + let next = [("-and", rest.find("-and")), ("-or", rest.find("-or"))] + .into_iter() + .filter_map(|(op, at)| at.map(|at| (op, at))) + .min_by_key(|(_, at)| *at); + let (piece, after) = match next { + Some((op, at)) => (&rest[..at], Some((op, &rest[at + op.len()..]))), + None => (rest, None), + }; + let Some(this) = term(piece) else { + return false; + }; + value = Some(match (value, join) { + (None, _) => this, + (Some(left), Some("-and")) => left && this, + (Some(left), _) => left || this, + }); + match after { + Some((op, tail)) => { + join = Some(op); + rest = tail; + } + None => return value.unwrap_or(false), + } + } +} + fn assignments(line: &str) -> Vec<&str> { let mut parts = Vec::new(); let mut quote = None; @@ -111,11 +331,7 @@ fn literal_assignment<'a>(assignment: &'a str, prefix: Option<&str>) -> Option<( let (key, value) = assignment.trim().split_once('=')?; let key = key.trim(); let key = prefix.map_or(Some(key), |prefix| key.strip_prefix(prefix))?; - if !key.starts_with("VICTORY_") - || !key - .bytes() - .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_') - { + if !is_switch_name(key) { return None; } let value = value.trim(); @@ -237,3 +453,87 @@ if ($AutoStart) { $set.VICTORY_AUTO_INPUT = '1' } ); assert!(parse("Write-Host 'No launch hashtable'").is_err()); } + +#[cfg(test)] +#[test] +fn reads_klbf_switches_but_never_the_own_starter_mark() { + // KLBF Lab's play.ps1: its own switches next to VICTORY_ ones, and the mark its `run` checks. + let script = r#" +$set = [ordered]@{ + VICTORY_GAME_DIR = $Game + KLBF_LAUNCHER = 'play.ps1' + VICTORY_PIPELINE_BOOK = '1' + KLBF_ALLOCATOR_TRIM = '1'; KLBF_SLOT_EVICT = '1'; KLBF_BUDGET_PACK = '1' + KLBF_lower = '1' +} +"#; + let (switches, _) = parse(script).unwrap(); + assert_eq!( + switches, + "KLBF_ALLOCATOR_TRIM=1\nKLBF_BUDGET_PACK=1\nKLBF_SLOT_EVICT=1\nVICTORY_PIPELINE_BOOK=1" + ); + assert!(is_switch_name("KLBF_FPS_CAP")); + assert!(is_switch_name("VICTORY_LOG")); + assert!(!is_switch_name(OWN_STARTER_ONLY)); + assert!(!is_switch_name("KLBF_")); + assert!(!is_switch_name("PATH")); + assert!(!is_switch_name("KLBF_FPS CAP")); +} + +#[cfg(test)] +#[test] +fn default_settings_follow_the_scripts_default_path_only() { + // KLBF Lab's scripts/play.ps1: -Safe off, so its else branch is the default. + let simple = r#" +param([switch]$Safe, [switch]$RayTracing, [hashtable]$More = @{}) +$settings = @{ + VICTORY_RELAY = '2'; VICTORY_CARD_AWAKE = '1' + VICTORY_GAME_DIR = $Game +} +if ($Safe) { + $settings.VICTORY_UNDER_WIDE = '0'; $settings.VICTORY_LAND_ECHO = '0' +} else { + $settings.VICTORY_THIN = '1'; $settings.VICTORY_JOIN_PARTS = '8' +} +if ($RayTracing) { $settings.VICTORY_BVH_BUILDER = '1' } +foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } +Get-ChildItem Env:VICTORY_* | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" } +$env:KLBF_LAUNCHER = 'scripts/play.ps1' +$env:VICTORY_LOG = 'trace' +"#; + let found = default_settings(simple); + let names: Vec<_> = found.iter().map(|(k, v)| format!("{k}={v}")).collect(); + assert_eq!( + names, + [ + "VICTORY_RELAY=2", + "VICTORY_CARD_AWAKE=1", + "VICTORY_THIN=1", + "VICTORY_JOIN_PARTS=8" + ] + ); + // play-scarlett.ps1's guards: `-not` of an off switch is on; a later value wins. + let guarded = r#" +param([switch]$Hooks, [switch]$NoHooks, [switch]$NoProbeRays, [switch]$RayTracing, [switch]$Fast = $true) +$set = [ordered]@{ + VICTORY_PIPELINE_WAIT_MS = '500' +} +if ($Hooks -and -not $NoHooks) { + $set.VICTORY_GPU_ONLY = '1' +} +if (-not $NoProbeRays -and -not $RayTracing) { $set.VICTORY_PROBE_RAYS = '1' } +if ($Fast) { $set.VICTORY_PIPELINE_WAIT_MS = '24' } +if ($RayTracing) { $set.VICTORY_A = '1' } elseif (-not $Hooks) { $set.VICTORY_B = '1' } else { $set.VICTORY_C = '1' } +if ($Build -eq 'release') { $set.VICTORY_D = '1' } +"#; + let found = default_settings(guarded); + let names: Vec<_> = found.iter().map(|(k, v)| format!("{k}={v}")).collect(); + assert_eq!( + names, + [ + "VICTORY_PROBE_RAYS=1", + "VICTORY_PIPELINE_WAIT_MS=24", + "VICTORY_B=1" + ] + ); +} diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 90c5581..2316c64 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -30,7 +30,7 @@ const listeners = new Set<() => void>() const changed = () => listeners.forEach((l) => l()) const platform = (params.get("platform") ?? (navigator.userAgent.includes("Mac") ? "macos" : "windows")) as "macos" | "windows" -const graphics: Graphics = { series_s: true, render_scale: 0.5, fix_8gb: true, bright_shadows: true, fullscreen: false, output: "Default" } +const graphics: Graphics = { series_s: true, render_scale: 0.5, fix_8gb: true, bright_shadows: true, fullscreen: false, output: "Default", memory: "Normal" } const state = { selected: (params.get("select") ?? SAMPLE[1]?.repo ?? null) as string | null, gpu: 0, diff --git a/src/features/library/graphics-tab.tsx b/src/features/library/graphics-tab.tsx index 173ae9f..ad0ba40 100644 --- a/src/features/library/graphics-tab.tsx +++ b/src/features/library/graphics-tab.tsx @@ -2,9 +2,22 @@ import { Group, Row } from "@/components/ui/group" import { Segmented } from "@/components/ui/segmented" import { Select } from "@/components/ui/select" import { Switch } from "@/components/ui/switch" +import { useMemo } from "react" import { useT } from "@/i18n" -import { graphicsMode, MODES, modeDetail, modeLabel, OUTPUTS, outputLabel, withMode } from "@/lib/format" -import { run } from "@/lib/store" +import { withSpec } from "@/lib/compat" +import { + graphicsMode, + MEMORY_SAVERS, + memoryLabel, + MODES, + modeDetail, + modeLabel, + OUTPUTS, + outputLabel, + recommendedMode, + withMode, +} from "@/lib/format" +import { run, useStore } from "@/lib/store" import type { Graphics, Project } from "@/lib/types" /** The console profiles: product names, the same in every language. */ @@ -47,10 +60,17 @@ export function GraphicsTab({ project: p }: { project: Project }) { export function GraphicsGroups({ graphics: g, onChange }: { graphics: Graphics; onChange(g: Graphics): void }) { const t = useT() const mode = graphicsMode(g) + const detected = useStore((s) => s.snap?.system ?? null) + const spec = useStore((s) => s.snap?.settings) + const recommended = useMemo(() => recommendedMode(withSpec(detected, spec)), [detected, spec]) + const presetHint = [ + mode ? modeDetail(mode) : t("library.graphics.renderScale", { percent: Math.round(g.render_scale * 100) }), + mode === recommended ? t("library.graphics.recommendedHere") : t("library.graphics.recommended", { preset: modeLabel(recommended) }), + ].join(" ") return ( <> - + onChange({ ...g, output })} /> + +