From 0818190ee4b23f93857d65e9f4dd39f35ea8e7d0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:06:50 +0200 Subject: [PATCH 1/3] docs: controller support design note Vanilla 26.3 has no gamepad code; Horizon's own design follows Bedrock's default controller layout. Mapping, menus, glyphs, options file, rumble, Steam Deck and the PR plan. Co-Authored-By: Claude Opus 5.5 --- docs/controllers.md | 174 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 docs/controllers.md diff --git a/docs/controllers.md b/docs/controllers.md new file mode 100644 index 000000000..74aea46da --- /dev/null +++ b/docs/controllers.md @@ -0,0 +1,174 @@ +# Controllers + +Horizon plays with PlayStation (DualShock 4, DualSense), Xbox (360, One, +Series) and Nintendo Switch Pro controllers, and on the Steam Deck with its +built-in controls. Keyboard and mouse keep working exactly as before: with no +controller connected, or with controllers turned off, nothing changes. + +## What vanilla has + +Nothing. Minecraft Java 26.3 never calls GLFW's gamepad or joystick API, has +no controller options and ships no button glyphs. Its only non-mouse UI input +is keyboard focus navigation (`InputType.KEYBOARD_ARROW` / `KEYBOARD_TAB`: +arrows and Tab move a focus ring between widgets). So controller support is +Horizon's own feature. It follows what players already know from Minecraft on +consoles (Bedrock Edition's default controller layout) and Horizon's menu +design for any new screen. + +## Input layer + +[gilrs](https://crates.io/crates/gilrs) reads the pads: evdev on Linux (with +libudev for hot-plugging), IOKit on macOS, Windows.Gaming.Input on Windows. +Its SDL mapping database normalizes every pad to one positional layout +(South/East/West/North face buttons, bumpers, triggers, sticks, D-pad, +Select/Start). No second windowing or event stack: gilrs is polled once per +loop iteration next to winit's events. + +- The pure logic (mapping table, deadzones and curves, button edges, the + settings file, glyph choice) lives in `crates/horizon-client/src/gamepad.rs` + and is unit-tested. The game owns a thin gilrs backend and applies actions. +- Controller actions go through the same path a keyboard key takes after + rebinding: an action names a vanilla key mapping (`key.jump`, `key.attack`, + ...), and the game handles it as that mapping's default key or mouse button. + Toggle sneak/sprint/attack/use, screens releasing held keys, and the + multiplayer client all behave as they do on the keyboard. +- Movement is analog: the left stick's direction and tilt feed the player's + move vector directly (a half-tilted stick walks slowly, like Bedrock), + instead of being rounded to WASD. The forward/back/left/right flags other + code reads (sprint start, boats, minecarts, the server's input packet) are + set when the stick passes a threshold. +- The pad last touched is the active one. Several pads are not merged. +- `horizon-ctl pad ...` injects a virtual pad (buttons, sticks, triggers) into + a running game, for tests without hardware. + +## Default mapping + +| Action | Xbox | PlayStation | Mapping | +|---|---|---|---| +| Move | Left stick | Left stick | analog `key.forward/back/left/right` | +| Look | Right stick | Right stick | camera | +| Jump / fly up | A | ✕ | `key.jump` | +| Drop item | B | ○ | `key.drop` | +| Swap offhand | X | □ | `key.swapOffhand` | +| Inventory | Y | △ | `key.inventory` | +| Hotbar left / right | LB / RB | L1 / R1 | Horizon `pad.hotbarPrevious/Next` | +| Use / place | LT | L2 | `key.use` | +| Attack / break | RT | R2 | `key.attack` | +| Sprint | Left stick click | L3 | `key.sprint` | +| Sneak (toggles) | Right stick click | R3 | `key.sneak` | +| Change camera | D-pad up | D-pad up | `key.togglePerspective` | +| Pick block | D-pad left | D-pad left | `key.pickItem` | +| Chat | D-pad right | D-pad right | `key.chat` | +| Advancements | D-pad down | D-pad down | `key.advancements` | +| Player list (hold) | View | Create / Share | `key.playerlist` | +| Pause / back | Menu | Options | Escape (fixed) | + +The Guide / PS / Steam button is left to the system. Sneak on a stick click +toggles by default (holding a stick in while steering the camera is +awkward, which is why Bedrock does the same); the controls options can make it +hold-to-sneak. + +## Menus and inventories + +Vanilla's screens are all mouse-driven, and Horizon draws them 1:1, so a pad +drives them through a **virtual cursor** (as Bedrock's classic inventory UI +and Java's controller mods do), not focus navigation: + +- Left stick moves the cursor with acceleration; in container screens the + cursor is gently pulled toward the nearest slot centre. +- D-pad steps one slot (18 GUI pixels in containers) or one widget row in + menus and snaps to it. +- A = left click (take / place stack, press a button), X = right click + (half stack / place one), Y = quick move (shift-click), B = back / close. +- LB / RB switch creative tabs and recipe book pages; right stick scrolls + (creative grid, lists, chat). +- Sliders: A grabs, the stick or D-pad left/right moves, A releases. +- Text fields: the Steam Deck's keyboard (Steam + X) types into them like a + real keyboard. Other platforms have no on-screen keyboard yet; text input + needs a keyboard. + +The cursor is drawn only while the pad is the last-used input; moving the +mouse hands control back immediately. + +## Glyphs + +Horizon draws its own button glyphs in the HUD and screens (no Mojang +assets, nothing new from the player's jar): a small round or pill shape with +the label in the game font, sized to the GUI scale, with two styles: + +- **Xbox / Steam Deck / generic**: A B X Y in their usual colours, LB RB LT + RT, View, Menu, stick icons. +- **PlayStation**: ✕ ○ □ △ drawn as shapes in their colours, L1 R1 L2 R2, + Create/Share, Options. +- **Nintendo**: B A Y X by position. + +The style comes from the pad's USB vendor (Sony 054c, Microsoft 045e, +Nintendo 057e, Valve 28de) unless the controls options force one. Glyphs +replace key names where a prompt names a key (the controls list, tutorial +hints, "Press X to dismount") only while the pad is the last-used input. + +## Options and remapping + +Controller settings are Horizon's own and live in `horizon-controller.txt` +next to `options.txt`, like `horizon-graphics.txt`: `options.txt` stays +exactly vanilla's, so a vanilla client can share the game folder. + +``` +enabled:true +vibration:true +lookSensitivity:0.5 +invertX:false +invertY:false +moveDeadzone:0.15 +lookDeadzone:0.12 +triggerThreshold:0.4 +toggleSneak:true +glyphs:auto +bind_key.jump:south +bind_pad.hotbarNext:rb +``` + +Only bindings that differ from the defaults are written. The controls +options get a Controller page: on/off, vibration, look sensitivity, invert +X/Y, deadzones, glyph style, sneak toggle, and a binding list like the key +binds screen (pick an action, press a button; conflicts marked as vanilla +does; reset). + +Deadzones are radial (the stick's length, so diagonals aren't clipped) and the +remaining range is rescaled to 0..1. Look uses a squared curve for precise +aim near the centre, up to 200°/s yaw and 140°/s pitch at the default +sensitivity, slower while scoping with a spyglass. + +## Rumble + +Vibration (on by default, off in the options) through gilrs force feedback: +taking damage (stronger with the damage), a block broken, an explosion nearby +(scaled by distance), a totem of undying, an elytra boost, a fish biting. +Short, low-intensity pulses, as on Bedrock. Linux (evdev force feedback, +including Steam Input's virtual pad) and Windows support it; macOS gilrs has +no force feedback, so it is silently skipped there. + +## Steam Deck + +- In Game Mode, or any game launched through Steam, Steam Input presents the + Deck's controls as a virtual Xbox pad: Horizon sees it like any Xbox pad + and uses Xbox-letter glyphs (the Deck's face buttons are A B X Y). Steam's + default "Gamepad" layout works with no setup; the trackpads stay mouse. +- Started outside Steam on the Deck, the kernel's `hid-steam` driver exposes + the controls as a gamepad too (while Steam isn't holding them), so it also + works out of the box. +- Text entry uses Steam's keyboard (Steam + X). + +## PR plan + +1. **Input layer and gameplay** (this note, gilrs, defaults, movement, + camera, actions, hotbar, B/Start to leave screens, `horizon-ctl pad`, + `horizon-controller.txt` with the look/deadzone settings). +2. **Menus and inventories**: virtual cursor, slot snapping, clicks, quick + move, tabs, scrolling, sliders. +3. **Glyphs and the Controller options page**: glyph drawing per pad type, + the options page, remapping UI. +4. **Rumble**. + +Each is shippable alone. Testing is with unit tests, the injected pad and +vscreen screenshots; each PR says what still needs a real controller. From b7330ac0cc7f627bf32b8e058a6164946d8c23e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:15:40 +0200 Subject: [PATCH 2/3] Controllers: gilrs input layer, in-game movement, camera, actions and hotbar Vanilla 26.3 has no gamepad input, so this is Horizon's own, on Bedrock's default layout (docs/controllers.md). gilrs reads the pads; the pure part (bindings, radial deadzones, the look curve, button edges, the horizon-controller.txt settings file) is in gamepad.rs with unit tests. Buttons act as the vanilla key mapping they're bound to, through the same path a rebound keyboard key takes (the keyboard's post-rebinding handling moves into Game::mapped_key). The left stick is an analog move vector, the right stick turns the view per frame, LB/RB step the hotbar, B and Start leave screens and A respawns. horizon-ctl pad injects a virtual pad. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +- .github/workflows/release.yml | 4 +- Cargo.lock | 110 ++++ README.md | 2 +- crates/horizon-client/Cargo.toml | 2 + .../examples/scene_motion_probe.rs | 1 + .../horizon-client/examples/sprint_probe.rs | 1 + .../src/bin/horizon-ctl/commands.rs | 4 + crates/horizon-client/src/game.rs | 80 ++- crates/horizon-client/src/game/books.rs | 2 +- crates/horizon-client/src/game/control.rs | 2 + crates/horizon-client/src/game/pad.rs | 435 +++++++++++++ crates/horizon-client/src/game/remote.rs | 5 +- crates/horizon-client/src/game/screens.rs | 2 +- crates/horizon-client/src/game/sign_edit.rs | 2 +- crates/horizon-client/src/gamepad.rs | 596 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/settings.rs | 11 + crates/horizon-client/src/sprint.rs | 21 +- tools/check_imports.py | 2 +- 20 files changed, 1244 insertions(+), 43 deletions(-) create mode 100644 crates/horizon-client/src/game/pad.rs create mode 100644 crates/horizon-client/src/gamepad.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0048a14e0..7b1a63710 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,9 +22,9 @@ jobs: python tools/check_public_tree.py --history - name: Test offline research tooling run: python -m unittest discover -s tests -v - - name: Install Rust toolchain and the ALSA headers the client's audio links against + - name: Install Rust toolchain and the ALSA and udev headers the client links against run: | - sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev + sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev rustup toolchain install stable --profile minimal --component rustfmt --component clippy - name: Check formatting and lint run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ea634cb6..3476c4fc2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -41,8 +41,8 @@ jobs: - uses: actions/checkout@v4 - name: Install Rust toolchain run: rustup toolchain install stable --profile minimal - - name: ALSA headers - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev + - name: ALSA and udev headers + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev - name: Build the client run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare - name: Standard loader and libraries only diff --git a/Cargo.lock b/Cargo.lock index 2a9d0cd47..393e942cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -648,6 +648,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" @@ -754,6 +760,40 @@ dependencies = [ "r-efi 6.0.0", ] +[[package]] +name = "gilrs" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "902fb00d3f6398e635be22e5c837b303c501835cca7ac11a47bba138f7aafdd8" +dependencies = [ + "fnv", + "gilrs-core", + "log", + "uuid", + "vec_map", +] + +[[package]] +name = "gilrs-core" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc7f0ce6237abcc0523f2a5502b1e3fe5802daaae47ac14e166fe49551301ea9" +dependencies = [ + "inotify", + "js-sys", + "libc", + "libudev-sys", + "log", + "nix", + "objc2-core-foundation", + "objc2-io-kit", + "uuid", + "vec_map", + "wasm-bindgen", + "web-sys", + "windows 0.62.2", +] + [[package]] name = "glam" version = "0.30.10" @@ -840,6 +880,7 @@ dependencies = [ "chrono", "cpal", "flate2", + "gilrs", "glam", "horizon-assets", "horizon-core", @@ -932,6 +973,26 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1073,6 +1134,16 @@ dependencies = [ "redox_syscall 0.9.4", ] +[[package]] +name = "libudev-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -1230,6 +1301,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "8.0.0" @@ -1486,6 +1569,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "bitflags 2.13.2", + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -2425,6 +2519,22 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + [[package]] name = "version_check" version = "0.9.5" diff --git a/README.md b/README.md index cf56bd042..db9482a25 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ Commands block until the action is done and reply with what happened; errors are ## Build from source -For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA development headers (`libasound2-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux. +For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA and udev development headers (`libasound2-dev libudev-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux. Horizon contains no game files and never downloads them. It builds its resources from **your own copy** of Minecraft: Java Edition 26.3, verified against the checksums in `research-lock.json`: diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index f602eac7b..984768c9d 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -28,6 +28,8 @@ chrono = { version = "0.4.42", default-features = false, features = ["clock", "s flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } horizon-theme = { path = "../horizon-theme" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } +# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). +gilrs = "0.11" [features] # Records the call sites of mob random draws (`mob_ai_probe` traces). diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index a5c61c065..b2f16a277 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -274,6 +274,7 @@ fn main() -> Result<()> { jump: mask & 16 != 0, shift: mask & 32 != 0, sprint: mask & 64 != 0, + analog: None, })?; } "movement_statistics" => world.check_movement_statistics(vector(&op["value"]))?, diff --git a/crates/horizon-client/examples/sprint_probe.rs b/crates/horizon-client/examples/sprint_probe.rs index 18d4b8fce..ab538ffe1 100644 --- a/crates/horizon-client/examples/sprint_probe.rs +++ b/crates/horizon-client/examples/sprint_probe.rs @@ -17,6 +17,7 @@ fn keys(mask: u64) -> Keys { jump: mask & 16 != 0, shift: mask & 32 != 0, sprint: mask & 64 != 0, + analog: None, } } fn main() -> Result<()> { diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index 8683402a2..655609d5c 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -252,6 +252,10 @@ pub const COMMANDS: &[Cmd] = &[ ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false), cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "", ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false), + cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them", + "Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.", + ["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"], + &[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false), cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false), cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false), // Screens diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a0d350a6b..e9a12e282 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -72,6 +72,7 @@ mod nautili; mod net_harness; mod options; mod packs; +mod pad; mod paintings; mod passengers; mod persist; @@ -660,6 +661,8 @@ struct Game<'a> { previous: Instant, /// FramerateLimitTracker.latestInputTime. last_input: Instant, + /// Controllers (Horizon's own). + pad: pad::Pads, frames: u64, fps: f32, fps_frames: u64, @@ -2666,6 +2669,7 @@ impl Game<'_> { self.update_totem_ready(); self.tick_command_extras(); let camera_eye = self.camera_eye_height(); + let stick = self.pad_move(); if self.riding.is_some() && self.player.is_some() { let playing = self.screen == Screen::Playing; let held = |k| playing && self.keys.contains(&k); @@ -2677,7 +2681,9 @@ impl Game<'_> { jump: held(KeyCode::Space), shift: held(KeyCode::ShiftLeft), sprint: false, - }; + analog: None, + } + .with_stick(stick.filter(|_| playing)); self.tick_riding(keys)?; } let riding = self.riding.is_some(); @@ -2706,7 +2712,9 @@ impl Game<'_> { jump: held(KeyCode::Space), shift: held(KeyCode::ShiftLeft), sprint: held(KeyCode::ControlLeft), - }; + analog: None, + } + .with_stick(stick.filter(|_| playing)); if !riding { self.previous_position = player.position; } @@ -2971,6 +2979,40 @@ impl Game<'_> { self.keys.remove(&key); } } + /// A key event after rebinding, as the default key of its mapping (the + /// keyboard and controllers both end here). + fn mapped_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) -> Result<()> { + // Sneak and sprint are ToggleKeyMappings: a press (or a key + // repeat) flips them when toggling; only releases reach them + // behind a screen (KeyboardHandler.keyPress). + let toggle = match key { + KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)), + KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)), + _ => None, + }; + if let Some((slot, option)) = toggle { + let action = match (pressed, repeat) { + (false, _) => KeyAction::Release, + (_, false) => KeyAction::Press, + (_, true) => KeyAction::Repeat, + }; + let screen_open = self.screen != Screen::Playing || self.title.is_some(); + self.toggles.key(slot, action, screen_open, option); + self.sync_toggle(slot); + if !pressed { + return Ok(()); + } + } else if !pressed { + self.keys.remove(&key); + return Ok(()); + } else { + self.keys.insert(key); + } + if repeat { + return Ok(()); + } + self.key_pressed(key) + } /// `KeyMapping.releaseAll` when a screen opens and /// `restoreToggleStatesOnScreenClosed` when it closes. fn track_toggle_screens(&mut self) { @@ -8497,36 +8539,7 @@ impl ApplicationHandler for Game<'_> { } None => return Ok(()), }; - // Sneak and sprint are ToggleKeyMappings: a press (or a key - // repeat) flips them when toggling; only releases reach them - // behind a screen (KeyboardHandler.keyPress). - let toggle = match key { - KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)), - KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)), - _ => None, - }; - if let Some((slot, option)) = toggle { - let action = match (event.state, event.repeat) { - (ElementState::Released, _) => KeyAction::Release, - (_, false) => KeyAction::Press, - (_, true) => KeyAction::Repeat, - }; - let screen_open = self.screen != Screen::Playing || self.title.is_some(); - self.toggles.key(slot, action, screen_open, option); - self.sync_toggle(slot); - if event.state != ElementState::Pressed { - return Ok(()); - } - } else if event.state != ElementState::Pressed { - self.keys.remove(&key); - return Ok(()); - } else { - self.keys.insert(key); - } - if event.repeat { - return Ok(()); - } - self.key_pressed(key)?; + self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?; } WindowEvent::RedrawRequested => { self.observe_fullscreen(); @@ -8571,6 +8584,7 @@ impl ApplicationHandler for Game<'_> { } } self.apply_mouse_look(); + self.pad_look(elapsed.as_secs_f32()); self.advance_flight(); let ticked = Instant::now(); let rendered = self.render()?; @@ -8675,6 +8689,7 @@ impl ApplicationHandler for Game<'_> { } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { self.poll_control(event_loop); + self.poll_pads(); if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout { self.error = Some("frame-limited run timed out".into()); event_loop.exit(); @@ -8933,6 +8948,7 @@ pub fn run() -> Result<()> { started: now, previous: now, last_input: now, + pad: Default::default(), frames: 0, fps: 0.0, fps_frames: 0, diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index b276b9a88..bebbbfc88 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -87,7 +87,7 @@ impl Game<'_> { self.right = false; self.capture(false); } - fn close_book(&mut self) { + pub(super) fn close_book(&mut self) { self.book = None; self.capture(true); } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 38a93c56b..2ab1245cf 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -134,10 +134,12 @@ impl Game<'_> { .chain(super::render_control::HELP) .chain(super::sculk::HELP) .chain(super::agent::HELP) + .chain(super::pad::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), + "pad" => Ok(Some(self.pad_command(&words)?)), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; self.require_world()?; diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs new file mode 100644 index 000000000..d59e60e01 --- /dev/null +++ b/crates/horizon-client/src/game/pad.rs @@ -0,0 +1,435 @@ +//! Controllers through gilrs (Horizon's own; docs/controllers.md): the +//! active pad's state each loop iteration, its button edges dispatched as +//! the vanilla key mappings they are bound to, the left stick as an analog +//! move vector and the right stick turning the view. `horizon-ctl pad` +//! injects a virtual pad on top of the real one. +use super::{Game, Screen}; +use horizon_client::{ + Result, + gamepad::{self, Button, Edges, GlyphStyle, PadState}, + keybinds::{KeyBinds, key_code, mouse_button}, + mouse::Rotation, +}; +use serde_json::{Value, json}; +use std::time::Instant; +use winit::keyboard::KeyCode; + +pub(super) const HELP: &[&str] = &[ + "pad BUTTON down|up|tap a virtual controller button (south east west north lb rb lt rt select start ls rs up down left right)", + "pad stick left|right X Y tilt a virtual stick (-1..1, up positive); 0 0 centres it", + "pad trigger left|right VALUE pull a virtual trigger (0..1)", + "pad release centre and release the virtual controller", + "pad status connected controllers, the active one and its state", +]; + +/// The controllers and the state the game last acted on. +#[derive(Default)] +pub(super) struct Pads { + gilrs: Option, + started: bool, + /// The pad last touched; only its input counts. + active: Option, + /// The virtual pad of `horizon-ctl pad`. + injected: PadState, + /// The virtual pad was in use at the last poll. + virtual_input: bool, + /// Buttons a `pad ... tap` releases at the next poll. + taps: Vec