From 1a067b3d9ef1e02fcd300720eeb219cdfc133fc9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:26:05 +0200 Subject: [PATCH] Agent control: read and set every option by key options-get [KEY...] gives every options.txt option by its vanilla key with its value and what it accepts (type, range, step or choices; enums by name, key bindings as key.keyboard.w). options-set KEY VALUE sets one, applies it at once and saves options.txt as the options screen does (language and resource packs reload too); a value the option refuses is an error naming what it accepts, and the option keeps its value. After a set, ui reads the redrawn screen. horizon-ctl and its MCP gain both; tools/agent_control_e2e.py gains an options scenario. Co-Authored-By: Claude Opus 5.5 --- .../src/bin/horizon-ctl/commands.rs | 7 + crates/horizon-client/src/game/control.rs | 4 + crates/horizon-client/src/game/options.rs | 58 +++++++ crates/horizon-client/src/game/ui_control.rs | 3 +- crates/horizon-client/src/options_file.rs | 157 ++++++++++++++++++ docs/native-client.md | 6 + tools/agent_control_e2e.py | 35 +++- 7 files changed, 266 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index f85105859..4ff24d5c8 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -278,6 +278,13 @@ pub const COMMANDS: &[Cmd] = &[ "The option behind it rounds to its own steps; read the new label with ui.", ["horizon-ctl set fov 0.5", "horizon-ctl set render-distance 0"], &[p("id", Ty::Str, "slider id from ui"), p("value", Ty::Num, "0..1 along the track")], mcp: true, local: false), + cmd!("options-get", Screens, "options-get [KEY...]", "the game's options (options.txt) by key, with their type and range or choices", + "Keys are vanilla's: fov, renderDistance, guiScale, gamma, maxFps, lang, resourcePacks, soundCategory_music, key_key.jump... Enums are given and set by name, key bindings by key name (key.keyboard.w).", + ["horizon-ctl options-get", "horizon-ctl options-get fov renderDistance"], &[opt("keys", Ty::Rest, "option keys (default: all)")], mcp: true, local: false), + cmd!("options-set", Screens, "options-set KEY VALUE", "set one option, apply it at once and save options.txt, as the options screen does", + "A value the option refuses is an error saying what it accepts. Lists are JSON: options-set resourcePacks [\"vanilla\"].", + ["horizon-ctl options-set fov 90", "horizon-ctl options-set renderClouds fast", "horizon-ctl options-set key_key.jump key.keyboard.j"], + &[p("key", Ty::Str, "option key from options-get"), p("value", Ty::Rest, "the new value")], mcp: true, local: false), cmd!("click-button", Screens, "click-button LABEL", "click a button of the open screen or title menu by its label", "Case-insensitive; a unique part of the label is enough. screen lists the buttons.", ["horizon-ctl click-button Singleplayer", "horizon-ctl click-button \"Create New World\"", "horizon-ctl click-button respawn"], diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 726b095b9..17890ab27 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -137,6 +137,9 @@ impl Game<'_> { super::agent::Handled::Deferred => return Ok(None), super::agent::Handled::No => {} } + if let Some(value) = self.options_control(&words, line)? { + return Ok(Some(value)); + } if let Some(value) = self.lan_control(&words)? { return Ok(Some(value)); } @@ -159,6 +162,7 @@ impl Game<'_> { .chain(super::sculk::HELP) .chain(super::agent::HELP) .chain(super::ui_control::HELP) + .chain(super::options::CONTROL_HELP) .chain(super::pad::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index cdeb68d0a..374da7c29 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -8,9 +8,67 @@ use horizon_client::{ options_ui::{Event, Page}, window::{FrameContext, InactivityFpsLimit, framerate_limit}, }; +use serde_json::{Value, json}; use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen}; +pub(super) const CONTROL_HELP: &[&str] = &[ + "options-get [KEY...] options.txt values by key, with their type, range or choices", + "options-set KEY VALUE set an option (enums by name, keys as key.keyboard.w, lists as JSON), apply and save it", +]; + impl Game<'_> { + /// `options-get` and `options-set`; None for other commands. + pub(super) fn options_control(&mut self, words: &[&str], line: &str) -> Result> { + match words[0] { + "options-get" => { + let file = self.settings.to_file(); + let wanted: Vec<&str> = if words.len() > 1 { + words[1..].to_vec() + } else { + horizon_client::options_file::keys() + }; + let mut options = serde_json::Map::new(); + for key in wanted { + let described = file.describe(key).ok_or_else(|| { + format!("unknown option {key}; options-get lists them all") + })?; + options.insert(key.to_owned(), described); + } + Ok(Some(json!({ "options": options }))) + } + "options-set" => { + let key = words.get(1).ok_or("options-set KEY VALUE")?; + // The value runs to the end of the line (lists, server names). + let value = line + .trim_start() + .strip_prefix("options-set") + .and_then(|rest| rest.trim_start().strip_prefix(key)) + .map(str::trim) + .filter(|v| !v.is_empty()) + .ok_or("options-set KEY VALUE: missing the value")?; + let mut file = self.settings.to_file(); + file.set_text(key, value)?; + let mut settings = horizon_client::settings::Settings::from_file(file); + // Horizon's own files are not in options.txt. + std::mem::swap(&mut settings.horizon, &mut self.settings.horizon); + std::mem::swap(&mut settings.controller, &mut self.settings.controller); + std::mem::swap(&mut settings.extras, &mut self.settings.extras); + self.settings = settings; + // As the options screen applies a change. + self.handle_option_events(vec![Event::Changed])?; + match *key { + "lang" => self.load_language(&self.settings.language.clone()), + "resourcePacks" | "incompatibleResourcePacks" => self.reload_packs(), + _ => {} + } + // Labels change (a language, a value): `ui` reads the redrawn screen. + self.ui_wait.clicked(); + let now = self.settings.to_file().describe(key); + Ok(Some(json!({ "ok": true, "key": key, "option": now }))) + } + _ => Ok(None), + } + } pub(super) fn options_path() -> std::path::PathBuf { std::env::current_dir() .unwrap_or_default() diff --git a/crates/horizon-client/src/game/ui_control.rs b/crates/horizon-client/src/game/ui_control.rs index a20598a60..94ca8a7b9 100644 --- a/crates/horizon-client/src/game/ui_control.rs +++ b/crates/horizon-client/src/game/ui_control.rs @@ -43,7 +43,8 @@ impl UiWait { self.after = None; std::mem::take(&mut self.waiting) } - fn clicked(&mut self) { + /// The screen changed: widget commands wait for it to be drawn again. + pub(super) fn clicked(&mut self) { self.after = Some((widgets::generation(), Instant::now())); } } diff --git a/crates/horizon-client/src/options_file.rs b/crates/horizon-client/src/options_file.rs index 5c14450ec..339bb0fdf 100644 --- a/crates/horizon-client/src/options_file.rs +++ b/crates/horizon-client/src/options_file.rs @@ -717,3 +717,160 @@ fn split_lines(text: &str) -> Vec<&str> { pub fn keys() -> Vec<&'static str> { TABLE.iter().map(|d| d.key.as_str()).collect() } + +/// What an option accepts, for the control socket (`options-get`). +fn accepts(kind: Kind) -> serde_json::Value { + use serde_json::json; + match kind { + Kind::Option(Spec::Bool) | Kind::PlainBool => json!({ "type": "bool" }), + Kind::Option(Spec::Int(lo, hi)) => json!({ "type": "int", "min": lo, "max": hi }), + Kind::Option(Spec::LazyInt(lo)) => json!({ "type": "int", "min": lo }), + Kind::Option(Spec::Scaled(imin, imax, k, ..)) => json!({ + "type": "double", + "min": f64::from(imin) / k, + "max": f64::from(imax) / k, + "step": 1.0 / k, + }), + Kind::Option(Spec::FrameLimit) => { + json!({ "type": "int", "min": 10, "max": 260, "step": 10 }) + } + Kind::Option(Spec::Fov) => json!({ "type": "int", "min": 30, "max": 110 }), + Kind::Option(Spec::WheelSensitivity) => { + json!({ "type": "double", "min": log_mouse(-200), "max": log_mouse(100) }) + } + Kind::Option(Spec::Unit | Spec::UnitSquare | Spec::UnitSquareImplicit) => { + json!({ "type": "double", "min": 0.0, "max": 1.0 }) + } + Kind::Option(Spec::Named(names)) => json!({ "type": "enum", "choices": names }), + Kind::Option(Spec::Id(count)) => json!({ "type": "int", "min": 0, "max": count - 1 }), + Kind::Option(Spec::Clouds) => json!({ "type": "enum", "choices": CLOUDS }), + Kind::Option(Spec::AnyStr) | Kind::PlainStr => json!({ "type": "string" }), + Kind::PlainInt => json!({ "type": "int" }), + Kind::List => json!({ "type": "list" }), + Kind::Tutorial => json!({ "type": "enum", "choices": TUTORIAL_STEPS }), + Kind::Key => json!({ "type": "key", "example": "key.keyboard.w" }), + } +} + +/// The names of an enum-valued option. +fn choices(kind: Kind) -> Option<&'static [&'static str]> { + match kind { + Kind::Option(Spec::Named(names)) => Some(names), + Kind::Option(Spec::Clouds) => Some(CLOUDS), + Kind::Tutorial => Some(&TUTORIAL_STEPS), + _ => None, + } +} + +impl OptionsFile { + /// An option for the control socket: `{"value", "type", ...}` with what + /// it accepts (range, choices); enum values by name. None when unknown. + pub fn describe(&self, key: &str) -> Option { + let i = Self::index(key)?; + let kind = TABLE[i].kind; + let value = match (choices(kind), &self.values[i]) { + (Some(names), V::Int(x)) => usize::try_from(*x) + .ok() + .and_then(|x| names.get(x)) + .map_or(serde_json::Value::Null, |n| (*n).into()), + (_, V::Bool(b)) => (*b).into(), + (_, V::Int(x)) => (*x).into(), + (_, V::Double(d)) => (*d).into(), + (_, V::Str(s)) => s.as_str().into(), + (_, V::List(l)) => l.clone().into(), + }; + let mut out = accepts(kind); + out["value"] = value; + Some(out) + } + + /// Set an option from text, as the control socket's `options-set` does: + /// enums by name, key bindings by key name (`key.keyboard.w`), lists as + /// JSON. Unlike loading `options.txt`, a value the option refuses is an + /// error naming what it accepts, and the option keeps its value. + pub fn set_text(&mut self, key: &str, text: &str) -> Result<(), String> { + let i = Self::index(key).ok_or_else(|| format!("unknown option {key}"))?; + let d = &TABLE[i]; + let refused = || format!("{key} refuses {text:?}; it accepts {}", accepts(d.kind)); + let candidate = if let Some(names) = choices(d.kind) { + let x = names.iter().position(|n| *n == text).ok_or_else(refused)?; + V::Int(x as i32) + } else if matches!(d.kind, Kind::Key) { + let name = canonical_key(text).map_err(|_| refused())?; + if name == "key.keyboard.unknown" && text != name { + return Err(refused()); + } + V::Str(name) + } else { + match &d.default { + V::Bool(_) => V::Bool(text.parse().map_err(|_| refused())?), + V::Int(_) => V::Int(text.parse().map_err(|_| refused())?), + V::Double(_) => V::Double(text.parse().map_err(|_| refused())?), + V::Str(_) => V::Str(text.to_owned()), + V::List(_) => V::List(serde_json::from_str(text).map_err(|_| refused())?), + } + }; + self.values[i] = match d.kind { + Kind::Option(spec) => spec.validate(&candidate).ok_or_else(refused)?, + _ => candidate, + }; + Ok(()) + } +} + +#[cfg(test)] +mod control_tests { + use super::*; + + #[test] + fn describes_values_with_what_they_accept() { + let f = OptionsFile::default(); + let fov = f.describe("fov").unwrap(); + assert_eq!(fov["value"], 70); + assert_eq!( + (fov["type"].as_str(), fov["min"].as_i64()), + (Some("int"), Some(30)) + ); + assert_eq!(f.describe("renderClouds").unwrap()["value"], "true"); + assert_eq!( + f.describe("key_key.forward").unwrap()["value"], + "key.keyboard.w" + ); + assert_eq!(f.describe("resourcePacks").unwrap()["type"], "list"); + assert!(f.describe("nope").is_none()); + for key in keys() { + assert!(f.describe(key).is_some(), "{key}"); + } + } + + #[test] + fn sets_valid_values_and_refuses_others() { + let mut f = OptionsFile::default(); + f.set_text("fov", "90").unwrap(); + assert_eq!(f.get("fov"), Some(&V::Int(90))); + let e = f.set_text("fov", "200").unwrap_err(); + assert!(e.contains("\"max\":110"), "{e}"); + assert_eq!( + f.get("fov"), + Some(&V::Int(90)), + "a refused value changes nothing" + ); + f.set_text("renderClouds", "fast").unwrap(); + assert_eq!(f.name("renderClouds"), "fast"); + assert!(f.set_text("renderClouds", "fancy").is_err()); + f.set_text("maxFps", "125").unwrap(); + assert_eq!(f.get("maxFps"), Some(&V::Int(120)), "IntRange steps of 10"); + f.set_text("key_key.jump", "key.keyboard.j").unwrap(); + assert_eq!(f.key_binding("key.jump"), "key.keyboard.j"); + assert!(f.set_text("key_key.jump", "jump").is_err()); + f.set_text("resourcePacks", r#"["vanilla","file/x.zip"]"#) + .unwrap(); + assert_eq!(f.list("resourcePacks"), ["vanilla", "file/x.zip"]); + assert!(f.set_text("gamma", "1.5").is_err()); + assert!( + f.set_text("nope", "1") + .unwrap_err() + .contains("unknown option") + ); + } +} diff --git a/docs/native-client.md b/docs/native-client.md index 7f0b3239a..ddd927826 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -128,6 +128,12 @@ game accepts, test hooks included. would and `set ID VALUE` moves a slider to 0..1; after a click, the next `ui`, `click` or `set` waits for the screen to be redrawn. Design and plans: [agent-control.md](agent-control.md). +- **Options:** `options-get [KEY...]` gives every `options.txt` option by its + vanilla key with its value and what it accepts (`{"type": "int", "min": 30, + "max": 110, "value": 70}`; enums with `choices`, key bindings as + `key.keyboard.w`); `options-set KEY VALUE` sets one, applies it at once and + saves `options.txt` as the options screen does. A value the option refuses + is an error saying what it accepts, not vanilla's silent reset. - **Screens:** `open-inventory`, `click-slot SLOT [right] [shift]` (0-8 hotbar, 9-35 inventory, 100+ crafting grid, 200 result, 300+ containers, 500-503 armor, 504 offhand, 600+ stations), `close`, `click-button LABEL` (any diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 0294863c8..05f15b445 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -5,7 +5,8 @@ A script creates a world through the title menus, finds a tree it can walk to, b checks the inventory, crafts planks in the inventory screen, places one and reads it back. It runs through the CLI (one horizon-ctl process per command) and through `horizon-ctl mcp` with a small JSON-RPC client, and saves a screenshot of each run. The ui scenario drives the menus by -widget id instead: the title screen, the options (a slider set by id) and the inventory's slots. +widget id instead: the title screen, the options (a slider set by id) and the inventory's slots; +the options scenario reads and sets options.txt values by key. python3 tools/agent_control_e2e.py # both modes python3 tools/agent_control_e2e.py --mode mcp # one of them @@ -39,7 +40,7 @@ POSITIONAL = { 'find_block': ['block', 'radius'], 'entities': ['radius', 'type'], 'click_slot': ['slot'], 'click_button': ['label'], 'type': ['text'], 'wait': ['ticks'], 'wait_ready': ['seconds'], 'command': ['command'], 'look_at_block': ['x', 'y', 'z'], 'click': ['id'], 'set': ['id', 'value'], - 'give': ['item', 'count'], + 'give': ['item', 'count'], 'options_get': ['keys'], 'options_set': ['key', 'value'], } # Booleans the game takes as bare words. BARE = {'click_slot': ['right', 'shift'], 'click': ['right', 'shift']} @@ -308,7 +309,35 @@ def ui_scenario(d, out): return {'widgets': len(tree)} -SCENARIOS = {'survival': scenario, 'ui': ui_scenario} +def options_scenario(d, out): + # Every option, typed, from the title screen; then set, refused, applied and saved. + options = d('options_get')['options'] + assert len(options) > 100, len(options) + assert options['fov'] == {'type': 'int', 'min': 30, 'max': 110, 'value': 70}, options['fov'] + assert options['renderClouds']['choices'] == ['false', 'fast', 'true'], options['renderClouds'] + assert d('options_set', key='fov', value='90')['option']['value'] == 90 + try: + d('options_set', key='fov', value='200') + raise AssertionError('fov 200 was accepted') + except Failed as e: + assert '"max":110' in str(e), e + d('options_set', key='renderClouds', value='fast') + d('options_set', key='key_key.jump', value='key.keyboard.j') + got = d('options_get', keys='fov renderClouds key_key.jump')['options'] + assert [got[k]['value'] for k in ('fov', 'renderClouds', 'key_key.jump')] == [90, 'fast', 'key.keyboard.j'], got + saved = (d.cwd / 'options.txt').read_text() + assert 'fov:0.5' in saved and 'renderClouds:"fast"' in saved and 'key_key.jump:key.keyboard.j' in saved, saved + # The options screen shows it: FOV 90 sits at (90 - 30) / 80 of its slider. + d('click', id='options') + assert abs(widgets(d)['fov']['value'] - 0.75) < 0.01 + # Applied at once: a GUI scale of 2 on the 1280x720 window makes the GUI 640x360. + d('options_set', key='guiScale', value='2') + assert d('ui')['gui_size'] == [640, 360], 'the GUI scale did not apply' + d('options_set', key='guiScale', value='0') + return {'options': len(options)} + + +SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario} def run(mode, ctl, out, resources, which='survival'):