From e2bf2a6cd342ad192d4ba61e30f447e1048deb77 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 26 Nov 2026 04:12:35 +0000 Subject: [PATCH] Core: the engine's settings registry, presets, session summaries, an [engine] table in profiles and --compare - registry.rs reads what python -m framegen.settings prints (leniently: unknown sections, fields and settings without choices still read) and the engine's settings.json, key by key - presets.rs: Quality, Balanced, Performance, Lowest delay as one table - sessions.rs: session summary JSON files, read as they are - profiles get an [engine] table (any engine setting by key), passed as --set KEY=VALUE - no multiplier in a profile: no --hz, so the engine's saved Frame multiplier counts - summit run --compare, behind an Option in engine::Live --- crates/summit-cli/src/main.rs | 11 +- crates/summit-core/src/engine.rs | 82 +++++- crates/summit-core/src/launch.rs | 17 ++ crates/summit-core/src/lib.rs | 3 + crates/summit-core/src/presets.rs | 100 +++++++ crates/summit-core/src/profile.rs | 37 ++- crates/summit-core/src/registry.rs | 457 +++++++++++++++++++++++++++++ crates/summit-core/src/sessions.rs | 212 +++++++++++++ 8 files changed, 905 insertions(+), 14 deletions(-) create mode 100644 crates/summit-core/src/presets.rs create mode 100644 crates/summit-core/src/registry.rs create mode 100644 crates/summit-core/src/sessions.rs diff --git a/crates/summit-cli/src/main.rs b/crates/summit-cli/src/main.rs index d11ae5f..8c952d3 100644 --- a/crates/summit-cli/src/main.rs +++ b/crates/summit-cli/src/main.rs @@ -32,6 +32,9 @@ enum Cmd { #[arg(long, default_value_t = 60)] wait: u32, /// With --enhance: hide the "summit - git.molberg.cloud/alex/summit" line in the corner #[arg(long)] no_watermark: bool, + /// With --enhance: the engine's live comparison, `:,,...` (e.g. scaler:off,fsr). + /// Experimental: needs an engine that has --compare. + #[arg(long)] compare: Option, /// The command hands the game to another program and returns at once (`steam steam://rungameid/N`). /// With --enhance, Summit then waits for the engine (the game's window) instead of the command. #[arg(long)] detached: bool, @@ -341,7 +344,9 @@ fn main() -> Result<()> { let missing = checks.iter().filter(|c| c.status == doctor::Status::Missing).count(); if missing == 0 { println!("all set"); } else { println!("{missing} missing: see the lines marked MISS"); } } - Cmd::Run { id, enhance, window, wait, no_watermark, detached, focus, title, mut cmd } => { + Cmd::Run { id, enhance, window, wait, no_watermark, compare, detached, focus, title, mut cmd } => { + let compare = compare.map(|c| engine::parse_compare(&c).map_err(|e| anyhow::anyhow!("--compare: {e}"))).transpose()?; + anyhow::ensure!(compare.is_none() || enhance, "--compare needs --enhance: the comparison is drawn by the engine"); // From here on a signal to summit stops the game and the engine and puts the display mode back. signals::install(); let st = state::load(); @@ -402,7 +407,7 @@ fn main() -> Result<()> { let status = if let (Some(eng), true) = (&eng, remote_play) { // The engine first: it has to see the stream start (the codec header comes once, as the stream's // first packet), so chiaki-ng is started once the engine says it is waiting on the frame tap. - let live = engine::Live { wait_secs: 0, watermark: if no_watermark { Some(false) } else { None } }; + let live = engine::Live { wait_secs: 0, watermark: if no_watermark { Some(false) } else { None }, compare: compare.clone() }; let mut args = engine::plan(eng, &engine::Source::Ps5, &p, true, None, None); args.extend(engine::live_args(&live)); if summit_core::ui::path().is_ok_and(|p| p.exists()) { @@ -441,7 +446,7 @@ fn main() -> Result<()> { } else if let Some(eng) = eng { let mut game = child.spawn().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))?; placer = start_placer(s, d, &p, true, place_target(&id, window.as_deref(), game.id()), wait); - let live = engine::Live { wait_secs: wait, watermark: if no_watermark { Some(false) } else { None } }; + let live = engine::Live { wait_secs: wait, watermark: if no_watermark { Some(false) } else { None }, compare: compare.clone() }; let mut args = engine::run_enhance_plan(&eng, game.id(), window.as_deref(), &p, &live); if summit_core::ui::path().is_ok_and(|p| p.exists()) { let ui = summit_core::ui::load(); diff --git a/crates/summit-core/src/engine.rs b/crates/summit-core/src/engine.rs index 983c7c0..d402ca5 100644 --- a/crates/summit-core/src/engine.rs +++ b/crates/summit-core/src/engine.rs @@ -86,9 +86,9 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option } if display { a.push("--display".into()); - // the frame multiplier N: the engine shows N frames for each real one of a 30 fps game, 30 x N fps - let hz = 30 * u32::from(p.multiplier().unwrap_or(2)); - a.push("--hz".into()); a.push(hz.to_string()); + // the frame multiplier N: the engine shows N frames for each real one of a 30 fps game, 30 x N fps. + // Not set in the profile: no flag, so the engine's own saved Frame multiplier is used (2x unless changed). + if let Some(m) = p.multiplier() { a.push("--hz".into()); a.push((30 * u32::from(m)).to_string()); } if let Some(g) = p.game_fps.as_deref().filter(|g| crate::profile::GAME_FPS.contains(g)) { a.push(opt("game-fps", g)); } if let Some((w, h)) = p.output_res.as_deref().and_then(crate::profile::parse_res) { a.push(format!("--output-res={w}x{h}")); } match p.window_mode.as_str() { @@ -100,6 +100,11 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option if let Some(f) = &p.fill { a.push(opt("fill", f)); } if let Some(v) = p.vsync { a.push(if v { "--vsync" } else { "--no-vsync" }.into()); } } else if let Some(o) = out { a.push(opt("out", &o.to_string_lossy())); } + // Engine settings by key (the profile's `engine` table): `--set=KEY=`, read after the flags above, so + // these win. One the engine does not know (an older engine) is said in its log and left out. + for (k, v) in &p.engine { + if k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !k.is_empty() { a.push(format!("--set={k}={}", crate::registry::from_toml(v))); } + } if let Some(t) = max_ticks { a.push("--max-ticks".into()); a.push(t.to_string()); } a } @@ -179,14 +184,35 @@ pub struct Live { pub wait_secs: u32, /// The "summit - git.molberg.cloud/alex/summit" line in a corner. None leaves the engine's saved setting (on by default). pub watermark: Option, + /// The engine's live comparison: `:,,...` ([`parse_compare`]), passed on as `--compare`. + /// None: no comparison. Experimental: the engine's side of this is on another branch. + pub compare: Option, +} +impl Default for Live { fn default() -> Self { Self { wait_secs: 60, watermark: None, compare: None } } } + +/// Check a comparison as the engine's `--compare` takes it: `:,,...`, a setting's key (letters, +/// digits, `_`, `-`) and at least two values. Returns it trimmed, with no spaces around the values. +pub fn parse_compare(s: &str) -> Result { + let how = "a comparison is :,,... (e.g. scaler:off,fsr)"; + let (dim, values) = s.split_once(':').ok_or(how)?; + let dim = dim.trim(); + if !dim.starts_with(|c: char| c.is_ascii_alphanumeric()) || !dim.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') { return Err(how.into()); } + let v: Vec<&str> = values.split(',').map(str::trim).collect(); + if v.len() < 2 || v.iter().any(|x| x.is_empty()) { return Err(format!("{how}: at least two values")); } + Ok(format!("{dim}:{}", v.join(","))) +} + +/// Whether this engine has the live comparison (its run.py knows `--compare`): the launcher only offers it then. +pub fn has_compare(engine: &Path) -> bool { + std::fs::read_to_string(engine.join("run.py")).is_ok_and(|t| t.contains("\"--compare\"")) } -impl Default for Live { fn default() -> Self { Self { wait_secs: 60, watermark: None } } } /// Extra engine flags for a live window, after `plan()`'s. pub fn live_args(l: &Live) -> Vec { let mut a = vec![]; if l.wait_secs > 0 { a.push("--window-wait".to_string()); a.push(l.wait_secs.to_string()); } if let Some(w) = l.watermark { a.push("--watermark".into()); a.push(if w { "on" } else { "off" }.into()); } + if let Some(c) = l.compare.as_deref().and_then(|c| parse_compare(c).ok()) { a.push(format!("--compare={c}")); } a } @@ -398,6 +424,9 @@ mod tests { #[test] fn ps5_display_plan() { let a = plan(Path::new("/e"), &Source::Ps5, &p(), true, None, None); assert_eq!(a[1..].join(" "), "--chiaki --model=4.25 --scaler vsr --display --hz 120 --fullscreen --monitor=HDMI-A-1"); + // no multiplier in the profile: no --hz, so the engine's saved Frame multiplier counts + let a = plan(Path::new("/e"), &Source::Ps5, &Profile::default(), true, None, None); + assert_eq!(a[1..].join(" "), "--chiaki --display"); } #[test] fn file_to_out_plan() { // upscaler "none" (the editor's Off): the engine shows the picture at its own size @@ -417,7 +446,7 @@ mod tests { #[test] fn window_plan_names_the_source() { let pr = Profile { framegen: "rife".into(), upscaler: "fsr".into(), ..Default::default() }; let a = plan(Path::new("/e"), &Source::Window("Voidrunner".into()), &pr, true, None, None); - assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --display --hz 60"); + assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --display"); } #[test] fn parse_source_kinds() { assert_eq!(parse_source("ps5"), Ok(Source::Ps5)); @@ -437,12 +466,12 @@ mod tests { } #[test] fn run_enhance_window_override_and_watermark_off() { let pr = Profile { framegen: "none".into(), upscaler: "fsr".into(), ..Default::default() }; - let a = run_enhance_plan(Path::new("/e"), 1, Some("class:steam_app_620"), &pr, &Live { wait_secs: 0, watermark: Some(false) }); - assert_eq!(a[1..].join(" "), "--source window --window=class:steam_app_620 --off --scaler fsr --display --hz 60 --watermark off"); + let a = run_enhance_plan(Path::new("/e"), 1, Some("class:steam_app_620"), &pr, &Live { wait_secs: 0, watermark: Some(false), compare: None }); + assert_eq!(a[1..].join(" "), "--source window --window=class:steam_app_620 --off --scaler fsr --display --watermark off"); } #[test] fn live_args_leave_the_saved_watermark_alone_by_default() { assert_eq!(live_args(&Live::default()).join(" "), "--window-wait 60"); - assert_eq!(live_args(&Live { wait_secs: 5, watermark: Some(true) }).join(" "), "--window-wait 5 --watermark on"); + assert_eq!(live_args(&Live { wait_secs: 5, watermark: Some(true), compare: None }).join(" "), "--window-wait 5 --watermark on"); } #[test] fn extra_args_split_on_spaces() { assert_eq!(extra_args(Some(" --no-graph --fp32 ")), vec!["--no-graph", "--fp32"]); @@ -565,7 +594,7 @@ mod tests { let pr = Profile { framegen: "rife".into(), model: Some("vfg".into()), vfg_quality: Some("high".into()), motion: Some("half".into()), ai_engine: Some("trt".into()), steady_hud: Some(true), upscaler: "fsr".into(), fsr_sharpness: Some(0.25), vsr_quality: Some(4), window_mode: "windowed".into(), fill: Some("zoom".into()), vsync: Some(false), ..Default::default() }; let a = plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None); - assert_eq!(a[1..].join(" "), "--chiaki --model=vfg --vfg-quality=high --scale=0.5 --engine=trt --steady-hud --scaler fsr --fsr-sharpness=0.25 --display --hz 60 --no-fullscreen --fill=zoom --no-vsync"); + assert_eq!(a[1..].join(" "), "--chiaki --model=vfg --vfg-quality=high --scale=0.5 --engine=trt --steady-hud --scaler fsr --fsr-sharpness=0.25 --display --no-fullscreen --fill=zoom --no-vsync"); // VSR quality only with VSR, VFG quality only with VFG let a = plan(Path::new("/e"), &Source::Ps5, &Profile { upscaler: "rtx-vsr".into(), vsr_quality: Some(3), vfg_quality: Some("low".into()), ..Default::default() }, true, None, None); assert!(a.contains(&"--vsr-quality=3".to_string()) && !a.iter().any(|x| x.starts_with("--vfg-quality")), "{a:?}"); @@ -577,6 +606,39 @@ mod tests { assert!(run_enhance_plan(Path::new("/e"), 1, None, &w, &Live { watermark: Some(true), ..Live::default() }).ends_with(&["--watermark".to_string(), "on".to_string()])); } #[test] fn dlss_is_not_an_engine_scaler() { assert_eq!(scaler_arg("dlss"), None); } + #[test] fn the_engine_table_goes_as_set_flags_after_the_named_ones() { + let mut pr = Profile { upscaler: "fsr".into(), ..Default::default() }; + pr.engine.insert("overlay_style".into(), toml::Value::String("graphs".into())); + pr.engine.insert("hz".into(), toml::Value::Integer(120)); + pr.engine.insert("interp".into(), toml::Value::Boolean(false)); + pr.engine.insert("fsr_sharpness".into(), toml::Value::Float(0.25)); + pr.engine.insert("bad key --x".into(), toml::Value::Integer(1)); + let a = plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None); + assert_eq!(a[1..].join(" "), "--chiaki --scaler fsr --display --set=fsr_sharpness=0.25 --set=hz=120 --set=interp=false --set=overlay_style=\"graphs\""); + // a value can never become another option: it stays inside its --set= + pr.engine.clear(); + pr.engine.insert("look".into(), toml::Value::String("--out /etc/x".into())); + let a = plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None); + assert_eq!(a.last().unwrap(), "--set=look=\"--out /etc/x\""); + } + #[test] fn compare_is_passed_through_only_when_asked_and_well_formed() { + assert_eq!(live_args(&Live::default()).join(" "), "--window-wait 60"); // None: nothing + let l = Live { compare: Some(" scaler : off, fsr ,vsr ".into()), ..Live::default() }; + assert_eq!(live_args(&l).join(" "), "--window-wait 60 --compare=scaler:off,fsr,vsr"); + let a = run_enhance_plan(Path::new("/e"), 7, None, &Profile::default(), &Live { compare: Some("hz:60,120".into()), ..Live::default() }); + assert_eq!(a[1..].join(" "), "--source window --window=pid:7 --display --window-wait 60 --compare=hz:60,120"); + assert_eq!(parse_compare("fsr_sharpness:0,0.5,2").as_deref(), Ok("fsr_sharpness:0,0.5,2")); + for bad in ["scaler", "scaler:fsr", ":a,b", "scaler:a,,b", "sc aler:a,b", "--x:a,b", ""] { assert!(parse_compare(bad).is_err(), "{bad}"); } + // one that is not well formed is never passed on + assert_eq!(live_args(&Live { compare: Some("nonsense".into()), ..Live::default() }).join(" "), "--window-wait 60"); + let d = std::env::temp_dir().join(format!("summit-has-compare-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("run.py"), "ap.add_argument(\"--hz\")\n").unwrap(); + assert!(!has_compare(&d)); + std::fs::write(d.join("run.py"), "ap.add_argument(\"--compare\", metavar=\"SPEC\")\n").unwrap(); + assert!(has_compare(&d)); + let _ = std::fs::remove_dir_all(&d); + } #[test] fn framegen_none_turns_interp_off() { let pr = Profile { framegen: "none".into(), ..Default::default() }; assert!(plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None).contains(&"--off".to_string())); @@ -612,7 +674,7 @@ mod tests { } #[test] fn game_frame_rate_and_output_resolution_reach_the_engine() { - let p = Profile { framegen: "rife".into(), game_fps: Some("60".into()), output_res: Some("2560 x 1440".into()), ..Default::default() }; + let p = Profile { framegen: "rife".into(), framegen_multiplier: 2, game_fps: Some("60".into()), output_res: Some("2560 x 1440".into()), ..Default::default() }; let a = plan(Path::new("/e"), &Source::Window("pid:1".into()), &p, true, None, None).join(" "); assert!(a.contains("--hz 60 --game-fps=60 --output-res=2560x1440"), "{a}"); let p = Profile { game_fps: Some("120".into()), output_res: Some("huge".into()), ..Default::default() }; diff --git a/crates/summit-core/src/launch.rs b/crates/summit-core/src/launch.rs index fac9adb..647724a 100644 --- a/crates/summit-core/src/launch.rs +++ b/crates/summit-core/src/launch.rs @@ -179,6 +179,15 @@ pub fn with_focus(mut argv: Vec) -> Vec { argv } +/// `summit run ... --enhance` with the engine's live comparison on (`:,,...`). Only a plan that goes +/// through `summit run` with Enhance can carry it; any other is returned as it is. +pub fn with_compare(mut argv: Vec, compare: &str) -> Vec { + let head = |a: &str| argv.iter().take_while(|x| x.as_str() != "--").any(|x| x == a); + let ours = argv.len() >= 3 && argv[1] == "run" && head("--enhance") && !argv.iter().take_while(|x| x.as_str() != "--").any(|x| x.starts_with("--compare")); + if ours { argv.insert(3, format!("--compare={compare}")); } + argv +} + /// True when Play would install rather than start (owned Steam game that is not on disk). pub fn is_install(e: &Entry) -> bool { e.source == Source::Steam && !e.installed && e.steam_app_id.is_some() } @@ -204,6 +213,14 @@ mod tests { // a game whose own arguments say --focus still gets ours let own = vec!["/s".to_string(), "run".into(), "custom:x".into(), "--".into(), "/g".into(), "--focus".into()]; assert_eq!(with_focus(own)[3], "--focus"); + // the comparison: only on a plan that runs the engine, once, and before the game's command + let enh: Vec = ["/b/summit", "run", "steam:1", "--enhance", "--", "steam", "--compare=x"].iter().map(|s| s.to_string()).collect(); + let c = with_compare(enh.clone(), "scaler:off,fsr"); + assert_eq!(c[3], "--compare=scaler:off,fsr"); + assert_eq!(with_compare(c.clone(), "hz:60,120"), c); + let no_enh: Vec = ["/b/summit", "run", "steam:1", "--", "steam"].iter().map(|s| s.to_string()).collect(); + assert_eq!(with_compare(no_enh.clone(), "scaler:off,fsr"), no_enh); + assert_eq!(with_compare(plain.clone(), "scaler:off,fsr"), plain); } #[test] fn steam_installed_goes_through_summit_run() { diff --git a/crates/summit-core/src/lib.rs b/crates/summit-core/src/lib.rs index 9c22670..3096129 100644 --- a/crates/summit-core/src/lib.rs +++ b/crates/summit-core/src/lib.rs @@ -10,9 +10,12 @@ pub mod launch; pub mod lutris; pub mod model; pub mod names; +pub mod presets; pub mod profile; +pub mod registry; pub mod running; pub mod scan; +pub mod sessions; pub mod sgdb; pub mod shortcuts; pub mod signals; diff --git a/crates/summit-core/src/presets.rs b/crates/summit-core/src/presets.rs new file mode 100644 index 0000000..dd2d7d0 --- /dev/null +++ b/crates/summit-core/src/presets.rs @@ -0,0 +1,100 @@ +//! Engine presets: a few named sets of engine settings. This table is the only place they are defined; the +//! launcher's Settings page, a game's profile and `summit preset` all read it. +//! +//! A preset only sets the keys listed here and leaves everything else alone. Every preset sets the same keys, so +//! exactly one of them (or none: "Custom") matches at any time. The descriptions say what changes; the numbers in +//! them are the engine's own notes (framegen/settings.py `impact`, measured on the engine author's PC), not +//! something measured for these presets. +use serde_json::Value; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum V { B(bool), I(i64), S(&'static str) } +impl V { pub fn json(self) -> Value { match self { V::B(b) => Value::Bool(b), V::I(i) => Value::from(i), V::S(s) => Value::String(s.into()) } } } + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Preset { + pub id: &'static str, + pub name: &'static str, + /// One line: who it is for. + pub summary: &'static str, + /// What it changes and what that costs, in plain words. + pub detail: &'static str, + /// Registry key -> value. The same keys in every preset, in the same order. + pub set: &'static [(&'static str, V)], +} + +impl Preset { + pub fn values(&self) -> Vec<(&'static str, Value)> { self.set.iter().map(|(k, v)| (*k, v.json())).collect() } +} + +pub const PRESETS: &[Preset] = &[ + Preset { + id: "quality", name: "Quality", + summary: "The best picture the engine makes, for a card with headroom.", + detail: "Frame generation on at 2x with motion detail Full (sharpest on fast detail, the slowest), FSR 1 upscaling straight to the screen's size, VSync on (no tear lines; up to one refresh more delay).", + set: &[("interp", V::B(true)), ("hz", V::I(60)), ("motion", V::S("full")), ("scaler", V::S("fsr")), ("output_res", V::S("screen")), ("vsync", V::B(true))], + }, + Preset { + id: "balanced", name: "Balanced", + summary: "The engine's own defaults.", + detail: "Frame generation on at 2x with motion detail Auto (Full, dropping to Half only at high frame rates or big captures), FSR 1 upscaling to the screen's size, VSync off (lowest delay; fast turns can tear without G-Sync or FreeSync).", + set: &[("interp", V::B(true)), ("hz", V::I(60)), ("motion", V::S("auto")), ("scaler", V::S("fsr")), ("output_res", V::S("screen")), ("vsync", V::B(false))], + }, + Preset { + id: "performance", name: "Performance", + summary: "The lightest for the graphics card, for when frames get left out.", + detail: "Frame generation on at 2x with motion detail Half (about 40% less time per AI frame, a little softer on small fast details), upscaling to 1080p and stretching that to the screen (softer on a 1440p or 4K screen), VSync off.", + set: &[("interp", V::B(true)), ("hz", V::I(60)), ("motion", V::S("half")), ("scaler", V::S("fsr")), ("output_res", V::S("1920x1080")), ("vsync", V::B(false))], + }, + Preset { + id: "lowest-delay", name: "Lowest delay", + summary: "Upscaling only: nothing that waits for the next frame.", + detail: "Frame generation off, so the game's frames are shown as they come (generation is what adds about 20 to 40 ms), FSR 1 upscaling to the screen's size, VSync off. Motion is only as smooth as the game itself.", + set: &[("interp", V::B(false)), ("hz", V::I(60)), ("motion", V::S("auto")), ("scaler", V::S("fsr")), ("output_res", V::S("screen")), ("vsync", V::B(false))], + }, +]; + +/// The keys presets set (the same for each). +pub fn keys() -> Vec<&'static str> { PRESETS[0].set.iter().map(|(k, _)| *k).collect() } + +pub fn by_id(id: &str) -> Option<&'static Preset> { PRESETS.iter().find(|p| p.id.eq_ignore_ascii_case(id) || p.name.eq_ignore_ascii_case(id)) } + +/// The preset the current values are, or None ("Custom"). `value_of` gives the value in use for a key. +pub fn current(value_of: &dyn Fn(&str) -> Value) -> Option<&'static Preset> { + PRESETS.iter().find(|p| p.set.iter().all(|(k, v)| crate::registry::same(&value_of(k), &v.json()))) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + #[test] + fn every_preset_sets_the_same_keys_and_no_two_are_alike() { + let k = keys(); + for p in PRESETS { + assert_eq!(p.set.iter().map(|(k, _)| *k).collect::>(), k, "{}", p.id); + assert!(!p.summary.is_empty() && !p.detail.is_empty()); + } + for (i, a) in PRESETS.iter().enumerate() { for b in &PRESETS[i + 1..] { assert_ne!(a.set, b.set, "{} and {}", a.id, b.id); } } + assert_eq!(by_id("Lowest delay").map(|p| p.id), Some("lowest-delay")); + assert_eq!(by_id("PERFORMANCE").map(|p| p.id), Some("performance")); + assert!(by_id("ultra").is_none()); + } + + #[test] + fn the_current_preset_is_custom_once_a_value_differs() { + let mut v: BTreeMap<&str, Value> = by_id("quality").unwrap().values().into_iter().collect(); + let look = |v: &BTreeMap<&str, Value>| current(&|k| v.get(k).cloned().unwrap_or(Value::Null)).map(|p| p.id); + assert_eq!(look(&v), Some("quality")); + v.insert("vsync", Value::Bool(false)); + assert_eq!(look(&v), None); + v.insert("motion", Value::String("auto".into())); + assert_eq!(look(&v), Some("balanced")); + v.insert("hz", Value::from(120)); + assert_eq!(look(&v), None); + // the settings file may hold 60.0 for 60 + v.insert("hz", serde_json::json!(60.0)); + assert_eq!(look(&v), Some("balanced")); + } +} diff --git a/crates/summit-core/src/profile.rs b/crates/summit-core/src/profile.rs index 8f36f5b..7a4f7f3 100644 --- a/crates/summit-core/src/profile.rs +++ b/crates/summit-core/src/profile.rs @@ -97,6 +97,9 @@ pub struct Profile { /// Which window Enhance takes, in the engine's `--window` form (`class:NAME`, part of the title, `dir:FOLDER`, /// alternatives split by "|"). None: Summit works it out (launch::window_query), and asks when it can't. pub window: Option, + /// Engine settings by the engine's own key (engine/framegen/settings.py), for anything the fields above do not + /// name: passed as `--set KEY=VALUE`, and winning over them. Empty: the engine's saved settings. + pub engine: BTreeMap, } impl Profile { @@ -142,6 +145,8 @@ pub struct Layer { #[serde(skip_serializing_if = "Option::is_none")] pub window: Option, #[serde(skip_serializing_if = "Option::is_none")] pub game_fps: Option, #[serde(skip_serializing_if = "Option::is_none")] pub output_res: Option, + /// `[engine]`: engine settings by the engine's key (the launcher's settings rows write here). See [`Profile::engine`]. + #[serde(skip_serializing_if = "Option::is_none")] pub engine: Option>, /// Files from before layers: `fullscreen = true` is `window_mode = "borderless"` (the engine's picture over the /// whole monitor, which is what it did). Read, never written. #[serde(skip_serializing)] pub fullscreen: Option, @@ -151,8 +156,11 @@ pub struct Layer { pub const KEYS: &[&str] = &[ "monitor", "width", "height", "refresh_hz", "window_mode", "focus", "enhance", "upscaler", "fsr_sharpness", "vsr_quality", "framegen", "framegen_multiplier", "target_hz", "model", "vfg_quality", "motion", "ai_engine", - "steady_hud", "fill", "vsync", "watermark", "launch_args", "env", "window", "game_fps", "output_res", + "steady_hud", "fill", "vsync", "watermark", "launch_args", "env", "window", "game_fps", "output_res", "engine", ]; +/// The engine's setting keys that a named profile setting also decides (crate::registry::named_for). +const NAMED_ENGINE_KEYS: &[&str] = &["interp", "hz", "game_fps", "output_res", "model", "vfg_quality", "motion", "engine", "steady_hud", + "scaler", "fsr_sharpness", "vsr_quality", "fill", "vsync", "watermark"]; impl Layer { /// A file from before layers stored every field, so "false", "" and 0 there only meant "nothing chosen": they @@ -207,6 +215,10 @@ impl Layer { if let Some(v) = &self.window { p.window = Some(v.trim().to_string()).filter(|v| !v.is_empty()); } if let Some(v) = &self.game_fps { p.game_fps = text(v); } if let Some(v) = &self.output_res { p.output_res = text(v).filter(|r| r != "screen"); } + // A later layer wins whichever way it says it: a named setting here replaces the same engine key from the + // layer below, and this layer's own engine table goes on top. + for k in NAMED_ENGINE_KEYS { if crate::registry::named_for(k).iter().any(|n| self.has(n)) { p.engine.remove(*k); } } + if let Some(v) = &self.engine { for (k, val) in v { p.engine.insert(k.clone(), val.clone()); } } } /// Whether this layer sets `key` (one of [`KEYS`]). @@ -222,6 +234,7 @@ impl Layer { "vsync" => self.vsync.is_some(), "watermark" => self.watermark.is_some(), "launch_args" => self.launch_args.is_some(), "env" => self.env.is_some(), "window" => self.window.is_some(), "game_fps" => self.game_fps.is_some(), "output_res" => self.output_res.is_some(), + "engine" => self.engine.as_ref().is_some_and(|m| !m.is_empty()), _ => false, } } @@ -240,6 +253,7 @@ impl Layer { "fill" => self.fill = None, "vsync" => self.vsync = None, "watermark" => self.watermark = None, "launch_args" => self.launch_args = None, "env" => self.env = None, "window" => self.window = None, "game_fps" => self.game_fps = None, "output_res" => self.output_res = None, + "engine" => self.engine = None, _ => return false, } true @@ -445,4 +459,25 @@ mod tests { let old = Layer { framegen_multiplier: Some(2), target_hz: Some(120), ..Default::default() }; assert_eq!(resolve(&[&old]).multiplier(), Some(4)); } + #[test] + fn the_engine_table_layers_like_everything_else() { + let t = |s: &str| toml::Value::String(s.into()); + let d = parse_layer("version = 2\nupscaler = \"fsr\"\n\n[engine]\noverlay_style = \"graphs\"\nscaler = \"vsr\"\nhz = 90\n").unwrap(); + assert_eq!(d.engine.as_ref().unwrap().get("hz"), Some(&toml::Value::Integer(90))); + let g = Layer { engine: Some([("overlay_style".to_string(), t("minimal")), ("vsync".to_string(), toml::Value::Boolean(true))].into()), ..Default::default() }; + let p = resolve(&[&d, &g]); + assert_eq!(p.engine.get("overlay_style"), Some(&t("minimal"))); // the game's own + assert_eq!(p.engine.get("scaler"), Some(&t("vsr"))); // the defaults' + assert_eq!(p.engine.get("vsync"), Some(&toml::Value::Boolean(true))); + // a game that still names the upscaler the older way wins over the defaults' engine table + let old = Layer { upscaler: Some("bilinear".into()), ..Default::default() }; + let p = resolve(&[&d, &old]); + assert!(!p.engine.contains_key("scaler") && p.upscaler == "bilinear"); + assert!(g.has("engine") && !Layer::default().has("engine")); + let mut g2 = g.clone(); + assert!(g2.unset("engine") && g2.is_empty()); + // written and read back + let text = toml::to_string_pretty(&Layer { version: Some(LAYER_VERSION), monitor: Some("DP-1".into()), ..g.clone() }).unwrap(); + assert_eq!(parse_layer(&text).unwrap().engine, g.engine, "{text}"); + } } diff --git a/crates/summit-core/src/registry.rs b/crates/summit-core/src/registry.rs new file mode 100644 index 0000000..d637052 --- /dev/null +++ b/crates/summit-core/src/registry.rs @@ -0,0 +1,457 @@ +//! The engine's settings registry, as the launcher reads it: `python -m framegen.settings` prints every setting +//! (engine/framegen/settings.py SPECS) as JSON, so the launcher keeps no copy of the labels, choices or help. +//! Parsed leniently: a field that is missing or of another type than expected is left empty, a setting without a key +//! is skipped, and a setting this version has never heard of is shown like any other. +//! +//! Also here: the saved values (the engine's settings.json, read and written key by key so anything else in the +//! file is kept) and how a launch profile's settings map onto the registry's keys ([`forced`]). +use crate::profile::{Layer, Profile}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Choice { pub value: Value, pub name: String, pub hint: String } + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Spec { + pub key: String, + pub label: String, + /// Section ("" in the JSON becomes "Other"). + pub group: String, + /// Heading inside the section ("" for none). + pub sub: String, + pub help: String, + pub default: Value, + /// Applies at once; false: at the next start. + pub live: bool, + /// Written to the settings file; false: one session only, so the launcher cannot set it. + pub saved: bool, + pub later: String, + pub quick: bool, + /// "picture" and "speed" lines (any other name the engine adds is kept and shown too). + pub impact: Vec<(String, String)>, + pub experimental: bool, + /// Only used with these sources (empty: all). + pub sources: Vec, + /// Source kind -> why it is not used there ("" for any other source). + pub elsewhere: BTreeMap, + /// Only used while setting `.0` has one of the values `.1`. + pub applies: Option<(String, Vec)>, + pub choices: Vec, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Registry { + /// The engine's settings file. + pub path: PathBuf, + /// The PC the numbers in the impact lines were measured on. + pub impact_pc: String, + pub specs: Vec, +} + +/// Two JSON values that mean the same choice: numbers by value (1 and 1.0), everything else exactly. +pub fn same(a: &Value, b: &Value) -> bool { + match (a.as_f64(), b.as_f64()) { (Some(x), Some(y)) => (x - y).abs() < 1e-9, _ => a == b } +} + +/// A value as text, for a choice the registry gives no name for. +pub fn plain(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + Value::Bool(true) => "On".into(), Value::Bool(false) => "Off".into(), + Value::Null => "Not set".into(), + other => other.to_string(), + } +} + +fn text(v: Option<&Value>) -> String { v.and_then(Value::as_str).unwrap_or_default().to_string() } +fn flag(v: Option<&Value>, default: bool) -> bool { v.and_then(Value::as_bool).unwrap_or(default) } + +impl Spec { + fn parse(v: &Value) -> Option { + let o = v.as_object()?; + let key = text(o.get("key")); + if key.is_empty() { return None; } + let label = match text(o.get("label")) { l if l.is_empty() => key.clone(), l => l }; + let group = match text(o.get("group")) { g if g.trim().is_empty() => "Other".to_string(), g => g }; + // choices: [{value, name, hint}], or bare values + let choices: Vec = o.get("choices").and_then(Value::as_array).map(|a| a.iter().map(|c| match c.as_object() { + Some(c) if c.contains_key("value") => { + let value = c.get("value").cloned().unwrap_or(Value::Null); + let name = match text(c.get("name")) { n if n.is_empty() => plain(&value), n => n }; + Choice { name, hint: text(c.get("hint")), value } + } + _ => Choice { name: plain(c), hint: String::new(), value: c.clone() }, + }).collect()).unwrap_or_default(); + let mut impact: Vec<(String, String)> = o.get("impact").and_then(Value::as_object) + .map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).filter(|(_, v)| !v.is_empty()).collect()).unwrap_or_default(); + impact.sort_by_key(|(k, _)| match k.as_str() { "picture" => 0, "speed" => 1, _ => 2 }); + let applies = o.get("applies").and_then(Value::as_object).and_then(|a| { + let k = text(a.get("key")); + let vals = a.get("values").and_then(Value::as_array).cloned().unwrap_or_default(); + (!k.is_empty()).then_some((k, vals)) + }); + Some(Spec { + key, label, group, sub: text(o.get("sub")), help: text(o.get("help")), default: o.get("default").cloned().unwrap_or(Value::Null), + live: flag(o.get("live"), true), saved: flag(o.get("saved"), true), later: text(o.get("later")), quick: flag(o.get("quick"), false), + impact, experimental: flag(o.get("experimental"), false), + sources: o.get("sources").and_then(Value::as_array).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default(), + elsewhere: o.get("elsewhere").and_then(Value::as_object).map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default(), + applies, choices, + }) + } + + /// The index of `v` among the choices. + pub fn position(&self, v: &Value) -> Option { self.choices.iter().position(|c| same(&c.value, v)) } + + /// What a value is called: the choice's name, else what the engine's own naming gives for a custom value (a + /// frame multiplier, an output size), else the value as text. + pub fn name_of(&self, v: &Value) -> String { + if let Some(i) = self.position(v) { return self.choices[i].name.clone(); } + match (self.key.as_str(), v) { + ("hz", Value::Number(n)) if n.as_u64().is_some_and(|hz| hz % 30 == 0 && hz > 0) => format!("{}x", n.as_u64().unwrap_or(0) / 30), + ("output_res", Value::String(s)) => crate::profile::parse_res(s).map(|(w, h)| format!("{w} x {h}")).unwrap_or_else(|| s.clone()), + _ => plain(v), + } + } + + /// Why the setting is not used with these values (the setting it depends on has another value), or None. + pub fn unused_now(&self, reg: &Registry, value_of: &dyn Fn(&str) -> Value) -> Option { + let (key, values) = self.applies.as_ref()?; + let cur = value_of(key); + if values.iter().any(|v| same(v, &cur)) { return None; } + let (label, names) = match reg.get(key) { + Some(dep) => (dep.label.clone(), values.iter().map(|v| dep.name_of(v)).collect::>()), + None => (key.clone(), values.iter().map(plain).collect()), + }; + let now = reg.get(key).map(|d| d.name_of(&cur)).unwrap_or_else(|| plain(&cur)); + let want = match names.as_slice() { + [] => "set".to_string(), + [one] => one.clone(), + many if many.len() > 3 => format!("{}, {} or another of {}", many[0], many[1], many.len()), + many => format!("{} or {}", many[..many.len() - 1].join(", "), many[many.len() - 1]), + }; + Some(format!("Only used while {label} is {want} (now {now}).")) + } + + /// Why the setting is not used with frames from `source` (the engine's kinds: "window", "chiaki", "capture", + /// "tap", "file"), or None if it is. + pub fn unused_with(&self, source: &str) -> Option { + if self.sources.is_empty() || self.sources.iter().any(|s| s == source) { return None; } + Some(self.elsewhere.get(source).or_else(|| self.elsewhere.get("")).cloned().filter(|s| !s.is_empty()) + .unwrap_or_else(|| format!("Only used with these sources: {}.", self.sources.join(", ")))) + } + + /// The note for a setting that only some sources use, where no source is known (the Settings page). + pub fn source_note(&self) -> Option { + if self.sources.is_empty() { return None; } + Some(self.elsewhere.get("").cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Only used with these sources: {}.", self.sources.join(", ")))) + } +} + +impl Registry { + /// Parse what `python -m framegen.settings` printed. + pub fn parse(json: &str) -> Result { + let v: Value = serde_json::from_str(json.trim()).map_err(|e| format!("not JSON: {e}"))?; + let o = v.as_object().ok_or("not a JSON object")?; + let mut specs: Vec = o.get("specs").and_then(Value::as_array).ok_or("no \"specs\" list")?.iter().filter_map(Spec::parse).collect(); + let mut seen = std::collections::HashSet::new(); + specs.retain(|s| seen.insert(s.key.clone())); + Ok(Registry { path: PathBuf::from(text(o.get("path"))), impact_pc: text(o.get("impact_pc")), specs }) + } + + /// Ask the engine (a few hundredths of a second: it loads no GPU library). + pub fn load(engine: &Path) -> Result { + let out = std::process::Command::new(crate::engine::python(engine)).current_dir(engine).args(["-m", "framegen.settings"]) + .stdin(std::process::Stdio::null()).output().map_err(|e| format!("could not run the engine's Python: {e}"))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + return Err(format!("the engine could not list its settings: {}", err.lines().last().unwrap_or("no output").trim())); + } + let mut reg = Self::parse(&String::from_utf8_lossy(&out.stdout))?; + if reg.path.as_os_str().is_empty() { return Err("the engine did not say where its settings file is".into()); } + if let Some(p) = std::env::var_os("SUMMIT_ENGINE_SETTINGS").filter(|p| !p.is_empty()) { reg.path = p.into(); } + Ok(reg) + } + + pub fn get(&self, key: &str) -> Option<&Spec> { self.specs.iter().find(|s| s.key == key) } + + /// The sections in the order the registry first names them, each with its settings in registry order. + pub fn groups(&self) -> Vec<(String, Vec<&Spec>)> { + let mut out: Vec<(String, Vec<&Spec>)> = vec![]; + for s in &self.specs { + match out.iter_mut().find(|(g, _)| *g == s.group) { Some((_, v)) => v.push(s), None => out.push((s.group.clone(), vec![s])) } + } + out + } +} + +/// The values saved in the engine's settings file. A missing or damaged file is no values (the engine then uses its +/// defaults, and so does the launcher). +pub fn read_values(path: &Path) -> BTreeMap { + std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| v.as_object().map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())).unwrap_or_default() +} + +/// Set (or with None remove, which is the engine's default) values in the settings file, keeping everything else +/// in it. Written whole and renamed into place, as the engine's own save is one write. +pub fn write_values(path: &Path, changes: &[(&str, Option)]) -> anyhow::Result<()> { + let mut all = read_values(path); + for (k, v) in changes { + match v { Some(v) => { all.insert(k.to_string(), v.clone()); } None => { all.remove(*k); } } + } + let obj: serde_json::Map = all.into_iter().collect(); + crate::state::write_atomic(path, serde_json::to_string_pretty(&Value::Object(obj))?.as_bytes())?; + Ok(()) +} + +pub fn to_toml(v: &Value) -> Option { + Some(match v { + Value::Bool(b) => toml::Value::Boolean(*b), + Value::Number(n) => match n.as_i64() { Some(i) => toml::Value::Integer(i), None => toml::Value::Float(n.as_f64()?) }, + Value::String(s) => toml::Value::String(s.clone()), + _ => return None, + }) +} +pub fn from_toml(v: &toml::Value) -> Value { + match v { + toml::Value::Boolean(b) => Value::Bool(*b), + toml::Value::Integer(i) => Value::from(*i), + toml::Value::Float(f) => serde_json::Number::from_f64(*f).map(Value::Number).unwrap_or(Value::Null), + toml::Value::String(s) => Value::String(s.clone()), + other => Value::String(other.to_string()), + } +} + +/// What a resolved profile makes the engine use, by registry key: exactly what [`crate::engine::plan`] passes on +/// the command line (the older named settings first, then the profile's `engine` table, which wins). A key that is +/// not here is left to the engine's saved setting. +pub fn forced(p: &Profile) -> BTreeMap { + let mut m: BTreeMap = BTreeMap::new(); + let s = |v: &str| Value::String(v.to_string()); + if p.framegen == "none" { m.insert("interp".into(), Value::Bool(false)); } + if let Some(x) = p.multiplier() { m.insert("hz".into(), Value::from(30 * u32::from(x))); } + if let Some(g) = p.game_fps.as_deref().filter(|g| crate::profile::GAME_FPS.contains(g)) { m.insert("game_fps".into(), s(g)); } + if let Some((w, h)) = p.output_res.as_deref().and_then(crate::profile::parse_res) { m.insert("output_res".into(), s(&format!("{w}x{h}"))); } + if let Some(x) = &p.model { m.insert("model".into(), s(x)); } + if let (Some("vfg"), Some(q)) = (p.model.as_deref(), &p.vfg_quality) { m.insert("vfg_quality".into(), s(q)); } + if let Some(x @ ("full" | "half")) = p.motion.as_deref() { m.insert("motion".into(), s(x)); } + if let Some(x) = &p.ai_engine { m.insert("engine".into(), s(x)); } + if let Some(x) = p.steady_hud { m.insert("steady_hud".into(), Value::Bool(x)); } + if let Some(sc) = crate::engine::scaler_arg(&p.upscaler) { + m.insert("scaler".into(), s(sc)); + if let (Some(v), "fsr") = (p.fsr_sharpness, sc) { m.insert("fsr_sharpness".into(), Value::from(v as f64)); } + if let (Some(q), "vsr") = (p.vsr_quality, sc) { m.insert("vsr_quality".into(), Value::from(q)); } + } + match p.window_mode.as_str() { + "windowed" => { m.insert("fullscreen".into(), Value::Bool(false)); } + _ if p.fullscreen() => { m.insert("fullscreen".into(), Value::Bool(true)); } + _ => {} + } + if let Some(x) = &p.fill { m.insert("fill".into(), s(x)); } + if let Some(x) = p.vsync { m.insert("vsync".into(), Value::Bool(x)); } + if let Some(x) = p.watermark { m.insert("watermark".into(), Value::Bool(x)); } + for (k, v) in &p.engine { m.insert(k.clone(), from_toml(v)); } + m +} + +/// The older named profile settings that say the same as registry key `key` (cleared when the key is set through +/// the `engine` table, so two places never disagree). "fullscreen" has none: that is the window mode, a launch setting. +pub fn named_for(key: &str) -> &'static [&'static str] { + match key { + "interp" => &["framegen"], "hz" => &["framegen_multiplier", "target_hz"], "game_fps" => &["game_fps"], + "output_res" => &["output_res"], "model" => &["model"], "vfg_quality" => &["vfg_quality"], "motion" => &["motion"], + "engine" => &["ai_engine"], "steady_hud" => &["steady_hud"], "scaler" => &["upscaler"], "fsr_sharpness" => &["fsr_sharpness"], + "vsr_quality" => &["vsr_quality"], "fill" => &["fill"], "vsync" => &["vsync"], "watermark" => &["watermark"], + _ => &[], + } +} + +impl Layer { + /// Set registry key `key` in this layer (None: stop setting it, so the layer below or the engine's saved + /// setting decides). The older named setting for the same thing is dropped. + pub fn set_engine(&mut self, key: &str, value: Option<&Value>) { + for k in named_for(key) { self.unset(k); } + let mut map = self.engine.take().unwrap_or_default(); + match value.and_then(to_toml) { Some(v) => { map.insert(key.to_string(), v); } None => { map.remove(key); } } + self.engine = (!map.is_empty()).then_some(map); + } + + /// Whether this layer by itself decides registry key `key` (through the `engine` table or an older named setting). + pub fn sets_engine(&self, key: &str) -> bool { + self.engine.as_ref().is_some_and(|m| m.contains_key(key)) || forced(&crate::profile::resolve(&[self])).contains_key(key) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const SAMPLE: &str = r#"{"path": "/tmp/x/settings.json", "impact_pc": "a PC", "specs": [ + {"key": "interp", "label": "Frame generation", "group": "Frame generation", "sub": "Basics", "help": "h", "default": true, "live": true, "saved": true, + "later": "", "quick": true, "impact": {"speed": "Adds delay.", "picture": "Smoother."}, "experimental": false, "sources": null, "elsewhere": null, "applies": null, + "choices": [{"value": true, "name": "On", "hint": ""}, {"value": false, "name": "Off", "hint": "No new frames."}]}, + {"key": "hz", "label": "Frame multiplier", "group": "Frame generation", "sub": "Basics", "default": 60, "quick": true, + "applies": {"key": "interp", "values": [true]}, "choices": [{"value": 60, "name": "2x", "hint": ""}, {"value": 90, "name": "3x", "hint": ""}]}, + {"key": "capture_size", "label": "Capture card resolution", "group": "Sources", "default": "1080p", "experimental": true, "live": false, + "sources": ["capture"], "elsewhere": {"chiaki": "Remote Play is 1080p.", "": "Only used with a capture card."}, + "choices": [{"value": "1080p", "name": "1080p", "hint": ""}, {"value": "2160p", "name": "4K", "hint": ""}]}, + {"key": "fsr_sharpness", "label": "FSR sharpening", "group": "Upscaling", "default": 0.5, + "choices": [{"value": 0.0, "name": "Max"}, {"value": 0.5, "name": "Medium"}, {"value": 1.0, "name": "Low"}]} + ]}"#; + + #[test] + fn parses_what_the_engine_prints() { + let r = Registry::parse(SAMPLE).unwrap(); + assert_eq!(r.path, PathBuf::from("/tmp/x/settings.json")); + assert_eq!(r.specs.len(), 4); + let i = r.get("interp").unwrap(); + assert_eq!((i.label.as_str(), i.group.as_str(), i.sub.as_str(), i.quick, i.saved, i.live), ("Frame generation", "Frame generation", "Basics", true, true, true)); + assert_eq!(i.impact, vec![("picture".to_string(), "Smoother.".to_string()), ("speed".to_string(), "Adds delay.".to_string())]); + assert_eq!(i.choices[1], Choice { value: json!(false), name: "Off".into(), hint: "No new frames.".into() }); + assert_eq!(r.get("hz").unwrap().applies, Some(("interp".to_string(), vec![json!(true)]))); + let c = r.get("capture_size").unwrap(); + assert!(c.experimental && !c.live && c.sources == vec!["capture"]); + assert_eq!(r.groups().iter().map(|(g, v)| (g.as_str(), v.len())).collect::>(), vec![("Frame generation", 2), ("Sources", 1), ("Upscaling", 1)]); + } + + #[test] + fn a_registry_from_a_newer_engine_still_reads() { + // an unknown section, fields this version has never seen, a new kind of setting without choices, choices as + // bare values, wrong types, a spec without a key, the same key twice + let r = Registry::parse(r#"{"path": "/s.json", "new_top_level": 1, "specs": [ + {"key": "aa", "label": "Anti-aliasing", "group": "Anti-aliasing", "sub": 7, "default": "off", "kind": "enum", "min": 1, + "impact": {"picture": "Smoother edges.", "memory": "More VRAM.", "bad": 3}, "choices": ["off", "fxaa", 2, true]}, + {"key": "strength", "label": "Strength", "group": "", "default": 0.4, "type": "range", "range": [0, 1], "choices": null}, + {"label": "no key"}, 17, {"key": "aa", "label": "again"}, + {"key": "odd", "impact": "fast", "applies": {"key": "", "values": 3}, "sources": "all", "quick": "yes", "default": {"a": 1}} + ]}"#).unwrap(); + assert_eq!(r.specs.iter().map(|s| s.key.as_str()).collect::>(), vec!["aa", "strength", "odd"]); + let aa = r.get("aa").unwrap(); + assert_eq!(aa.choices.iter().map(|c| c.name.as_str()).collect::>(), vec!["off", "fxaa", "2", "On"]); + assert_eq!(aa.impact, vec![("picture".to_string(), "Smoother edges.".to_string()), ("memory".to_string(), "More VRAM.".to_string())]); + assert_eq!(aa.sub, ""); + let s = r.get("strength").unwrap(); + assert!(s.choices.is_empty() && s.group == "Other"); + assert_eq!(s.name_of(&json!(0.4)), "0.4"); + let odd = r.get("odd").unwrap(); + assert!(odd.label == "odd" && odd.applies.is_none() && odd.sources.is_empty() && !odd.quick && odd.impact.is_empty()); + assert_eq!(r.groups().iter().map(|(g, _)| g.as_str()).collect::>(), vec!["Anti-aliasing", "Other"]); + assert!(Registry::parse("[]").is_err() && Registry::parse("{}").is_err() && Registry::parse("nope").is_err()); + } + + #[test] + fn values_compare_by_meaning_and_custom_ones_get_a_name() { + let r = Registry::parse(SAMPLE).unwrap(); + assert!(same(&json!(1), &json!(1.0)) && !same(&json!(true), &json!(1)) && !same(&json!("1"), &json!(1))); + assert_eq!(r.get("fsr_sharpness").unwrap().position(&json!(1)), Some(2)); + let hz = r.get("hz").unwrap(); + assert_eq!((hz.name_of(&json!(90)).as_str(), hz.name_of(&json!(210)).as_str()), ("3x", "7x")); + } + + #[test] + fn says_why_a_setting_is_not_used() { + let r = Registry::parse(SAMPLE).unwrap(); + let off = |k: &str| if k == "interp" { json!(false) } else { Value::Null }; + let on = |k: &str| if k == "interp" { json!(true) } else { Value::Null }; + let hz = r.get("hz").unwrap(); + assert_eq!(hz.unused_now(&r, &off).as_deref(), Some("Only used while Frame generation is On (now Off).")); + assert_eq!(hz.unused_now(&r, &on), None); + let c = r.get("capture_size").unwrap(); + assert_eq!(c.unused_with("capture"), None); + assert_eq!(c.unused_with("chiaki").as_deref(), Some("Remote Play is 1080p.")); + assert_eq!(c.unused_with("window").as_deref(), Some("Only used with a capture card.")); + assert_eq!(c.source_note().as_deref(), Some("Only used with a capture card.")); + assert_eq!(hz.source_note(), None); + } + + #[test] + fn the_settings_file_is_changed_key_by_key() { + let d = std::env::temp_dir().join(format!("summit-registry-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + let f = d.join("deep/settings.json"); + assert!(read_values(&f).is_empty()); + write_values(&f, &[("scaler", Some(json!("vsr"))), ("hz", Some(json!(120)))]).unwrap(); + // something the launcher does not know stays in the file + let mut v = read_values(&f); + v.insert("from_a_newer_engine".into(), json!([1, 2])); + std::fs::write(&f, serde_json::to_string(&v).unwrap()).unwrap(); + write_values(&f, &[("hz", None), ("vsync", Some(json!(true)))]).unwrap(); + let v = read_values(&f); + assert_eq!(v.get("scaler"), Some(&json!("vsr"))); + assert_eq!(v.get("vsync"), Some(&json!(true))); + assert_eq!(v.get("from_a_newer_engine"), Some(&json!([1, 2]))); + assert!(!v.contains_key("hz")); + std::fs::write(&f, "not json").unwrap(); + assert!(read_values(&f).is_empty()); + write_values(&f, &[("hz", Some(json!(90)))]).unwrap(); // a damaged file is replaced, not a reason to fail + assert_eq!(read_values(&f).get("hz"), Some(&json!(90))); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_profile_forces_what_the_planner_passes() { + let p = Profile { framegen: "none".into(), upscaler: "rtx-vsr".into(), vsr_quality: Some(3), fsr_sharpness: Some(0.25), framegen_multiplier: 4, + window_mode: "borderless".into(), watermark: Some(false), motion: Some("half".into()), ..Default::default() }; + let f = forced(&p); + assert_eq!(f.get("interp"), Some(&json!(false))); + assert_eq!(f.get("hz"), Some(&json!(120))); + assert_eq!(f.get("scaler"), Some(&json!("vsr"))); + assert_eq!(f.get("vsr_quality"), Some(&json!(3))); + assert!(!f.contains_key("fsr_sharpness")); // only with FSR, as the planner + assert_eq!(f.get("fullscreen"), Some(&json!(true))); + assert_eq!(f.get("watermark"), Some(&json!(false))); + assert_eq!(f.get("motion"), Some(&json!("half"))); + assert!(forced(&Profile::default()).is_empty()); + // the engine table wins over the older named setting + let mut p = Profile { upscaler: "fsr".into(), ..Default::default() }; + p.engine.insert("scaler".into(), toml::Value::String("bilinear".into())); + p.engine.insert("overlay_style".into(), toml::Value::String("graphs".into())); + let f = forced(&p); + assert_eq!((f.get("scaler"), f.get("overlay_style")), (Some(&json!("bilinear")), Some(&json!("graphs")))); + } + + #[test] + fn setting_a_key_in_a_layer_drops_the_older_named_setting() { + let mut l = Layer { upscaler: Some("rtx-vsr".into()), framegen_multiplier: Some(4), target_hz: Some(120), ..Default::default() }; + assert!(l.sets_engine("scaler") && l.sets_engine("hz") && !l.sets_engine("vsync")); + l.set_engine("scaler", Some(&json!("fsr"))); + assert_eq!(l.upscaler, None); + assert_eq!(l.engine.as_ref().unwrap().get("scaler"), Some(&toml::Value::String("fsr".into()))); + l.set_engine("hz", None); + assert_eq!((l.framegen_multiplier, l.target_hz), (None, None)); + assert!(!l.sets_engine("hz")); + l.set_engine("fsr_sharpness", Some(&json!(0.25))); + l.set_engine("vsr_quality", Some(&json!(4))); + l.set_engine("overlay", Some(&json!(false))); + let text = toml::to_string_pretty(&l).unwrap(); + let back: Layer = toml::from_str(&text).unwrap(); + assert_eq!(back, l, "{text}"); + let f = forced(&crate::profile::resolve(&[&back])); + assert_eq!((f.get("fsr_sharpness"), f.get("vsr_quality"), f.get("overlay")), (Some(&json!(0.25)), Some(&json!(4)), Some(&json!(false)))); + l.set_engine("scaler", None); l.set_engine("fsr_sharpness", None); l.set_engine("vsr_quality", None); l.set_engine("overlay", None); + assert!(l.is_empty(), "{l:?}"); + } + + #[test] + fn the_real_engine_registry_reads_when_python_is_here() { + let engine = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../engine"); + let Ok(r) = Registry::load(&engine) else { eprintln!("skipped: no python3 to ask the engine"); return }; + assert!(r.specs.len() > 30 && r.get("scaler").is_some() && r.get("hz").is_some()); + assert!(r.specs.iter().all(|s| !s.label.is_empty() && !s.group.is_empty())); + assert!(r.specs.iter().filter(|s| s.quick).count() >= 4); + // every preset names a real setting and one of its choices + for p in crate::presets::PRESETS { + for (k, v) in p.values() { + let s = r.get(k).unwrap_or_else(|| panic!("preset {}: no setting {k}", p.id)); + assert!(s.position(&v).is_some(), "preset {}: {k} has no choice {v}", p.id); + } + } + // every key the launch profile can force is a real setting, of the registry's type + for k in ["interp", "hz", "game_fps", "output_res", "model", "vfg_quality", "motion", "engine", "steady_hud", "scaler", "fsr_sharpness", "vsr_quality", "fullscreen", "fill", "vsync", "watermark", "replay", "replay_clip"] { + assert!(r.get(k).is_some(), "the engine has no setting {k}"); + } + } +} diff --git a/crates/summit-core/src/sessions.rs b/crates/summit-core/src/sessions.rs new file mode 100644 index 0000000..d1d1f69 --- /dev/null +++ b/crates/summit-core/src/sessions.rs @@ -0,0 +1,212 @@ +//! Session summaries the engine writes after a run (JSON files), for a game's Statistics view. +//! +//! The format belongs to the engine and is not fixed here: every `*.json` in the sessions folders is read as it +//! is, and what is shown is what the file holds (its fields, flattened). Only the names of a few fields are +//! guessed, to pick a headline: a duration, an average frame rate, the lows, which game it was. A file that is +//! not a JSON object is skipped; a missing folder is no sessions. +use serde_json::Value; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Summary { + pub file: PathBuf, + /// When it ended, as far as the file says (a "ended"/"end"/"time"/"timestamp" field in seconds), else the + /// file's modification time. Seconds since 1970; 0 if unknown. + pub when: u64, + /// The game it says it was for ("game", "title", "game_title", "name", "game_id", "id"), if it says. + pub game: Option, + /// Every scalar in the file as (dotted name, text), sorted by name; lists of scalars joined, other lists + /// counted. + pub fields: Vec<(String, String)>, + pub duration_s: Option, + pub fps_avg: Option, + /// (the field's own name, value): "1% low", "0.1% low", "min"... + pub lows: Vec<(String, f64)>, + /// The fields under a "settings" object (or any name ending in "settings"), as (key, text). + pub settings: Vec<(String, String)>, +} + +/// Where summaries are looked for: $SUMMIT_SESSIONS_DIR, then `sessions` and `stats` folders under the engine's +/// and Summit's data, state, cache and config folders. Folders that do not exist are fine. +pub fn dirs() -> Vec { + let mut v: Vec = vec![]; + if let Some(d) = std::env::var_os("SUMMIT_SESSIONS_DIR").filter(|d| !d.is_empty()) { v.push(d.into()); } + let roots = [::dirs::data_dir(), ::dirs::state_dir(), ::dirs::cache_dir(), ::dirs::config_dir()]; + for root in roots.into_iter().flatten() { + for app in ["smoovplay", "summit"] { for sub in ["sessions", "stats"] { v.push(root.join(app).join(sub)); } } + } + v.dedup(); + v +} + +fn scalar(v: &Value) -> Option { + match v { + Value::String(s) => Some(s.clone()), + Value::Bool(b) => Some(if *b { "yes" } else { "no" }.into()), + Value::Number(n) => Some(match n.as_f64() { Some(f) if n.is_f64() => trim_num(f), _ => n.to_string() }), + Value::Null => None, + _ => None, + } +} +fn trim_num(f: f64) -> String { + let s = format!("{f:.2}"); + s.trim_end_matches('0').trim_end_matches('.').to_string() +} + +fn flatten(prefix: &str, v: &Value, depth: u8, out: &mut Vec<(String, String)>) { + match v { + Value::Object(o) if depth < 4 => for (k, v) in o { flatten(&if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") }, v, depth + 1, out); }, + Value::Object(o) => out.push((prefix.to_string(), format!("{} fields", o.len()))), + Value::Array(a) => { + let parts: Vec = a.iter().filter_map(scalar).collect(); + if parts.len() == a.len() && a.len() <= 12 { out.push((prefix.to_string(), parts.join(", "))); } + else { out.push((prefix.to_string(), format!("{} values", a.len()))); } + } + other => if let Some(s) = scalar(other) { out.push((prefix.to_string(), s)); }, + } +} + +fn last(name: &str) -> String { name.rsplit('.').next().unwrap_or(name).to_lowercase() } + +/// Read one summary from JSON text. None if it is not a JSON object. +pub fn parse(text: &str, file: &Path, mtime: u64) -> Option { + let v: Value = serde_json::from_str(text).ok()?; + let o = v.as_object()?; + let mut fields = vec![]; + flatten("", &v, 0, &mut fields); + let num = |name: &str| -> Option { fields.iter().find(|(k, _)| k == name).and_then(|(_, v)| v.parse::().ok()) }; + let pick = |test: &dyn Fn(&str) -> bool| -> Option<(String, f64)> { + fields.iter().find(|(k, v)| test(&k.to_lowercase()) && v.parse::().is_ok()).map(|(k, v)| (k.clone(), v.parse().unwrap_or(0.0))) + }; + let game = ["game", "title", "game_title", "name", "game_id", "id"].iter() + .find_map(|k| o.get(*k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from)); + let when = ["ended", "ended_at", "end", "end_time", "time", "timestamp", "started", "start"].iter() + .find_map(|k| num(k)).filter(|t| *t > 1.0e9 && *t < 1.0e11).map(|t| t as u64).unwrap_or(mtime); + // seconds unless the name says otherwise + let duration_s = pick(&|k| { let l = last(k); l.contains("duration") || l.contains("elapsed") || l == "seconds" || l == "length_s" || l == "playtime" }) + .map(|(k, v)| { let l = last(&k); if l.ends_with("_ms") { v / 1000.0 } else if l.ends_with("_min") || l.ends_with("minutes") { v * 60.0 } else { v } }); + let is_fps = |k: &str| k.contains("fps") || k.contains("frame_rate") || k.contains("framerate"); + let fps_avg = pick(&|k| is_fps(k) && (k.contains("avg") || k.contains("average") || k.contains("mean"))) + .or_else(|| pick(&|k| { let l = last(k); l == "fps" || l == "output_fps" || l == "fps_out" })).map(|(_, v)| v); + let lows: Vec<(String, f64)> = fields.iter().filter(|(k, _)| { let k = k.to_lowercase(); (k.contains("low") || k.contains("p1") || k.contains("p01") || k.contains("min_fps") || k.contains("fps_min")) && !k.contains("settings") }) + .filter_map(|(k, v)| Some((last(k).replace('_', " "), v.parse::().ok()?))).take(4).collect(); + let settings: Vec<(String, String)> = fields.iter().filter_map(|(k, v)| { + let (head, rest) = k.split_once('.')?; + head.to_lowercase().ends_with("settings").then(|| (rest.to_string(), v.clone())) + }).collect(); + Some(Summary { file: file.to_path_buf(), when, game, fields, duration_s, fps_avg, lows, settings }) +} + +/// Every summary in `dirs` (and one folder level below, for a folder per game), newest first. At most `max` files +/// are read, and none bigger than 1 MB. +pub fn read(dirs: &[PathBuf], max: usize) -> Vec { + let mut files: Vec<(PathBuf, u64, Option)> = vec![]; + let scan = |dir: &Path, folder: Option, files: &mut Vec<(PathBuf, u64, Option)>| -> Vec { + let mut subs = vec![]; + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let p = e.path(); + let Ok(meta) = e.metadata() else { continue }; + if meta.is_dir() { subs.push(p); continue; } + if p.extension().and_then(|x| x.to_str()) != Some("json") || meta.len() > 1_000_000 { continue; } + let mtime = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0); + files.push((p, mtime, folder.clone())); + } + subs + }; + for d in dirs { + for sub in scan(d, None, &mut files) { + let name = sub.file_name().map(|n| n.to_string_lossy().into_owned()); + scan(&sub, name, &mut files); + } + } + files.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + files.dedup_by(|a, b| a.0 == b.0); + files.truncate(max); + let mut out: Vec = files.into_iter().filter_map(|(p, mtime, folder)| { + let mut s = parse(&std::fs::read_to_string(&p).ok()?, &p, mtime)?; + if s.game.is_none() { s.game = folder; } // a folder per game names it + Some(s) + }).collect(); + out.sort_by(|a, b| b.when.cmp(&a.when)); + out +} + +fn norm(s: &str) -> String { s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() } + +/// Whether a summary is for the game with this id and title: it names one of them (letters and digits compared, +/// so "Void Runner" is "voidrunner"). A summary that names no game belongs to none. +pub fn is_for(s: &Summary, id: &str, title: &str) -> bool { + let Some(g) = s.game.as_deref().map(norm).filter(|g| !g.is_empty()) else { return false }; + g == norm(title) || g == norm(id) || id.rsplit(':').next().is_some_and(|tail| g == norm(tail)) +} + +/// "1 h 12 min", "4 min 5 s", "42 s". +pub fn duration_label(s: f64) -> String { + let t = s.max(0.0).round() as u64; + match (t / 3600, (t % 3600) / 60, t % 60) { + (0, 0, s) => format!("{s} s"), + (0, m, s) => format!("{m} min {s} s"), + (h, m, _) => format!("{h} h {m} min"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shows_what_is_in_the_file_whatever_its_shape() { + let s = parse(r#"{"game": "Voidrunner", "ended": 1795000000, "duration_s": 754.4, "fps": {"avg": 118.26, "low_1": 96.5, "low_01": 71}, + "settings": {"scaler": "fsr", "hz": 120, "interp": true}, "dropped": [1, 2, 3], "notes": null}"#, Path::new("a.json"), 5).unwrap(); + assert_eq!(s.game.as_deref(), Some("Voidrunner")); + assert_eq!(s.when, 1795000000); + assert_eq!(s.duration_s, Some(754.4)); + assert_eq!(s.fps_avg, Some(118.26)); + assert_eq!(s.lows, vec![("low 01".to_string(), 71.0), ("low 1".to_string(), 96.5)]); + assert_eq!(s.settings, vec![("hz".to_string(), "120".to_string()), ("interp".to_string(), "yes".to_string()), ("scaler".to_string(), "fsr".to_string())]); + assert!(s.fields.contains(&("dropped".to_string(), "1, 2, 3".to_string()))); + assert!(s.fields.contains(&("fps.avg".to_string(), "118.26".to_string()))); + assert!(!s.fields.iter().any(|(k, _)| k == "notes")); + } + + #[test] + fn other_names_and_nothing_at_all() { + let s = parse(r#"{"title": "X", "elapsed_ms": 90000, "average_fps": 59.9, "one_percent_low_fps": 48}"#, Path::new("b.json"), 77).unwrap(); + assert_eq!((s.duration_s, s.fps_avg, s.when), (Some(90.0), Some(59.9), 77)); + assert_eq!(s.lows, vec![("one percent low fps".to_string(), 48.0)]); + // nothing recognisable: still a summary, with its fields, and no made-up numbers + let s = parse(r#"{"a": 1, "b": {"c": "d"}}"#, Path::new("c.json"), 3).unwrap(); + assert_eq!((s.duration_s, s.fps_avg, s.game.clone(), s.lows.len(), s.settings.len()), (None, None, None, 0, 0)); + assert_eq!(s.fields, vec![("a".to_string(), "1".to_string()), ("b.c".to_string(), "d".to_string())]); + assert!(parse("[1, 2]", Path::new("d.json"), 0).is_none()); + assert!(parse("{broken", Path::new("e.json"), 0).is_none()); + assert!(parse("", Path::new("f.json"), 0).is_none()); + } + + #[test] + fn reads_folders_defensively_and_matches_games() { + let d = std::env::temp_dir().join(format!("summit-sessions-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + assert!(read(&[d.clone(), d.join("nope")], 50).is_empty()); + std::fs::create_dir_all(d.join("Voidrunner")).unwrap(); + std::fs::write(d.join("one.json"), r#"{"game": "Void Runner", "ended": 1795000100, "duration": 60}"#).unwrap(); + std::fs::write(d.join("Voidrunner/two.json"), r#"{"ended": 1795000200, "fps_avg": 90}"#).unwrap(); + std::fs::write(d.join("other.json"), r#"{"game": "Else", "ended": 1795000300}"#).unwrap(); + std::fs::write(d.join("junk.json"), "not json").unwrap(); + std::fs::write(d.join("list.json"), "[]").unwrap(); + std::fs::write(d.join("readme.txt"), "{}").unwrap(); + let all = read(&[d.clone()], 50); + assert_eq!(all.iter().map(|s| s.when).collect::>(), vec![1795000300, 1795000200, 1795000100]); + let mine: Vec<&Summary> = all.iter().filter(|s| is_for(s, "custom:voidrunner", "Voidrunner")).collect(); + assert_eq!(mine.len(), 2); + assert_eq!(mine[0].game.as_deref(), Some("Voidrunner")); // from its folder + assert!(!is_for(&Summary::default(), "x", "X")); + assert_eq!(read(&[d.clone()], 1).len(), 1); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn durations_read_naturally() { + assert_eq!((duration_label(42.4).as_str(), duration_label(245.0).as_str(), duration_label(4330.0).as_str()), ("42 s", "4 min 5 s", "1 h 12 min")); + } +}