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..88a91ee97 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: # The C runtime linked in, so the game runs without the Visual C++ redistributable. env: RUSTFLAGS: -C target-feature=+crt-static - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare + run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare - name: Only system DLLs # Vulkan and the rest are loaded at run time; a linked non-system DLL is a # "DLL not found" dialog on some players' machines. @@ -29,8 +29,7 @@ jobs: python tools/check_imports.py target/release/horizon-ctl.exe python tools/check_imports.py target/release/horizon-prepare.exe - name: Package - shell: bash - run: packaging/package.sh target/release/horizon-client.exe dist/horizon-windows-x64 + run: cargo +stable run --locked -p xtask -- package target/release/horizon-client.exe dist/horizon-windows-x64 - uses: actions/upload-artifact@v4 with: name: horizon-windows-x64 @@ -41,17 +40,17 @@ 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 + run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare - name: Standard loader and libraries only run: | python3 tools/check_imports.py target/release/horizon-client python3 tools/check_imports.py target/release/horizon-ctl python3 tools/check_imports.py target/release/horizon-prepare - name: Package - run: packaging/package.sh target/release/horizon-client dist/horizon-linux-x86_64 + run: cargo +stable run --locked -p xtask -- package target/release/horizon-client dist/horizon-linux-x86_64 - uses: actions/upload-artifact@v4 with: name: horizon-linux-x86_64 diff --git a/.gitignore b/.gitignore index b8594a003..22e289788 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,12 @@ /saves/ /tools/logs/ .DS_Store +# What the client writes to its working directory when run from the repo root. +/options.txt +/horizon.txt +/horizon-graphics.txt +/horizon-controller.txt +/servers.dat +/screenshots/ +/crash-reports/ +/debug/ diff --git a/Cargo.lock b/Cargo.lock index 2a9d0cd47..1e3919458 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", @@ -848,6 +889,7 @@ dependencies = [ "horizon-world", "log", "miniz_oxide 0.8.9", + "naga", "png", "pollster", "serde_json", @@ -932,6 +974,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 +1135,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 +1302,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 +1570,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 +2520,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" @@ -3235,6 +3346,10 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +[[package]] +name = "xtask" +version = "0.1.0" + [[package]] name = "xxhash-rust" version = "0.8.19" diff --git a/Cargo.toml b/Cargo.toml index 46f2b68fe..2af3d37a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher"] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare"] +members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "xtask"] resolver = "2" [workspace.package] diff --git a/README.md b/README.md index cf56bd042..2ed714b7f 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`: @@ -141,7 +141,7 @@ Horizon contains no game files and never downloads them. It builds its resources git clone https://github.com/ludovic111/horizon.git cd horizon cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar # needs JDK 25 -python3 tools/fetch_sounds.py # optional: sounds from your launcher install +cargo run --release -p horizon-prepare -- sounds # optional: sounds from your launcher install cargo run --release -p horizon-client ``` diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index f602eac7b..b54424966 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). @@ -35,3 +37,7 @@ rng-trace = ["horizon-core/rng-trace"] [lints] workspace = true + +[dev-dependencies] +# Parses and validates the composed entity shader (already built for wgpu). +naga = { version = "30.0.1", features = ["wgsl-in"] } diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index b2f0a8900..af15b9fde 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -9,6 +9,10 @@ //! 1.0), foxes and axolotls from the third, sulfur cubes have size 2, salmon //! are small, slimes and magma cubes keep size 1, tropical fish school. //! +//! Spawner cases (`mode=spawner`, tools/test_spawner_parity.py) tick a +//! `mobs::spawner::Spawner` loaded from the case's SNBT on the same world and +//! print its events tick by tick. +//! //! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT use horizon_client::{ assets::Assets, @@ -25,6 +29,7 @@ use horizon_client::{ SpawnPlayer, SpawnRequest, SpawnState, Spawned, StructureAt, StructureSpawns, spawn_box, }, + spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn}, species::{self, Baby}, }, }; @@ -73,6 +78,8 @@ struct Shared<'a> { structures: &'a StructureSpawns, collision: &'a BlockCollisionRegistry<'a>, air: BlockStateId, + /// Every entity type id (`entity-types.json`). + entity_types: &'a HashSet, } struct World<'a> { s: &'a Shared<'a>, @@ -95,8 +102,10 @@ struct World<'a> { respawn: Option<[i32; 3]>, unloaded: HashSet<(i32, i32)>, spawn_mobs: bool, - /// Boxes of living entities (case entities, then spawned mobs). - entities: RefCell>, + /// The `spawner_blocks_work` game rule. + spawners_work: bool, + /// Types and boxes of living entities (case entities, then spawned mobs). + entities: RefCell>, } impl World<'_> { fn biome_at(&self, x: i32, y: i32, z: i32) -> &str { @@ -280,10 +289,21 @@ impl NaturalLevel for World<'_> { block: &lookup, binding: self.s.collision, }; + // getEntityCollisions(null, box): living shulkers are solid. + let grown = bounds.inflate(horizon_core::geometry::Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut world, bounds) + && !self + .entities + .borrow() + .iter() + .any(|(id, b)| id == "minecraft:shulker" && b.intersects(grown)) } fn unobstructed(&self, bounds: Aabb) -> bool { - !self.entities.borrow().iter().any(|b| b.intersects(bounds)) + !self + .entities + .borrow() + .iter() + .any(|(_, b)| b.intersects(bounds)) } fn spawn_mobs(&self) -> bool { self.spawn_mobs @@ -299,6 +319,28 @@ impl NaturalLevel for World<'_> { } } +impl SpawnerLevel for World<'_> { + fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool { + self.players.iter().any(|(p, mode)| { + let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2); + mode != "spectator" && (range < 0.0 || d < range * range) + }) + } + fn spawner_blocks_work(&self) -> bool { + self.spawners_work + } + fn entity_exists(&self, id: &str) -> bool { + self.s.types.types.contains_key(id) || self.s.entity_types.contains(id) + } + fn count_entities(&self, id: &str, bounds: Aabb) -> usize { + self.entities + .borrow() + .iter() + .filter(|(k, b)| k == id && b.intersects(bounds)) + .count() + } +} + /// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random. fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb { let t = &l.s.types.types[r.entity]; @@ -369,6 +411,17 @@ fn main() -> horizon_client::Result<()> { let biomes = Biomes::load(root)?; let structures = StructureSpawns::load(root); let collision = collisions::load(root, registry)?; + let entity_types: HashSet = fs::read(root.join("entity-types.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v.as_object().map(|o| { + o.keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect() + }) + }) + .unwrap_or_default(); let shared = Shared { facts: &facts, data: &data, @@ -378,6 +431,7 @@ fn main() -> horizon_client::Result<()> { structures: &structures, collision: &collision, air: facts.air, + entity_types: &entity_types, }; let mut adaptation: HashMap = HashMap::new(); let mut out = String::new(); @@ -538,12 +592,18 @@ fn main() -> horizon_client::Result<()> { respawn, unloaded, spawn_mobs: get("rules", "1") != "0", + spawners_work: get("spawners", "1") != "0", entities: RefCell::new( case_entities .iter() - .filter_map(|(t, p, _)| { - let t = types.types.get(t)?; - Some(spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32)) + .filter_map(|(id, p, _)| { + let t = types.types.get(id)?; + // Entity.setPos (a shulker sits at its block's centre). + let p = horizon_client::mobs::spawner::entity_position(t.species, *p); + Some(( + id.clone(), + spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32), + )) }) .collect(), ), @@ -560,14 +620,16 @@ fn main() -> horizon_client::Result<()> { let mut log: Vec = Vec::new(); let mut spawn = |l: &World, r: &SpawnRequest| -> Option { let bounds = neutral_box(l, r); - l.entities.borrow_mut().push(bounds); + l.entities.borrow_mut().push((r.entity.to_owned(), bounds)); Some(Spawned { bounds, school: true, }) }; let mode = get("mode", "chunk"); - if mode == "gen" { + if mode == "spawner" { + spawner_case(&world, &get, &mut random, &mut log)?; + } else if mode == "gen" { let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?); // The level random of the spawn predicates: no creature's predicate // draws from it (the oracle's answers fixed values). @@ -686,3 +748,86 @@ fn main() -> horizon_client::Result<()> { fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; Ok(()) } + +/// `SpawnerBlockEntity.serverTick` `ticks` times at `spos` for the spawner in +/// `snbt` (base64 SNBT), as the oracle logs it. +fn spawner_case( + world: &World, + get: &dyn Fn(&str, &'static str) -> String, + random: &mut LegacyRandom, + log: &mut Vec, +) -> horizon_client::Result<()> { + let v: Vec = get("spos", "0,0,0") + .split(',') + .map(|n| n.parse().unwrap_or(0)) + .collect(); + let pos = [v[0], v[1], v[2]]; + let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?; + let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0; + let mut spawner = Spawner::load(&tag); + let ticks: i32 = get("ticks", "1").parse()?; + for tick in 0..ticks { + let mut events = Vec::new(); + let mut spawned = std::collections::VecDeque::new(); + let mut spawn = |l: &World, r: &SpawnerSpawn| -> Option { + let t = l.s.types.types.get(r.id)?; + let [x, y, z] = r.position; + let bounds = spawn_box(x, y, z, t.width as f32, t.height as f32); + l.entities.borrow_mut().push((r.id.to_owned(), bounds)); + spawned.push_back(format!( + "{tick} spawn {} {} {} {} {}", + r.id, + bits(x), + bits(y), + bits(z), + // Shulker.finalizeSpawn faces it south. + yaw_text( + r.id, + if r.finalize && r.id == "minecraft:shulker" { + 0.0 + } else { + r.yaw + } + ) + )); + Some(SpawnerAdded { + id: spawned.len() as u32, + bounds, + mob: true, + }) + }; + spawner.server_tick(world, random, pos, &mut spawn, &mut events); + for e in events { + match e { + SpawnerEvent::BlockUpdated => log.push(format!("{tick} update")), + SpawnerEvent::BlockEvent(id) => log.push(format!("{tick} bevent {id} 0")), + // Each spawn's level event follows its tryAddFreshEntityWithPassengers. + SpawnerEvent::LevelEvent(id) => { + log.extend(spawned.pop_front()); + log.push(format!("{tick} levent {id} 0")); + } + SpawnerEvent::EntityPlace(_, p) => log.push(format!( + "{tick} gevent minecraft:entity_place {} {} {}", + p[0], p[1], p[2] + )), + SpawnerEvent::SpawnAnim(_) => log.push(format!("{tick} eevent 20")), + } + } + } + let next = spawner + .next_data() + .and_then(|d| d.id()) + .unwrap_or_else(|| "-".into()); + let pots: Vec = spawner + .potentials + .iter() + .map(|(d, w)| format!("{}*{w}", d.id().unwrap_or_else(|| "-".into()))) + .collect(); + log.push(format!( + "end delay={} next={next} pots={}", + spawner.spawn_delay as i16, + pots.join(",") + )); + log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); + Ok(()) +} diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index 5b9258aeb..b56da92fa 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -278,6 +278,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"]))?, @@ -457,7 +458,7 @@ fn main() -> Result<()> { "weaving" => world.player.status.weaving = op["value"].as_bool().unwrap(), "flying" => { let flying = op["value"].as_bool().unwrap(); - world.player.may_fly = flying; + world.player.may_fly = op["may_fly"].as_bool().unwrap_or(flying); world.player.flying = flying; } "trigger" => world.player.jump_trigger_time = op["value"].as_i64().unwrap() as i32, diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index d17c33466..7d4f5547d 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -7,7 +7,7 @@ use horizon_client::{ biome::{BiomeInfo, Biomes, GrassModifier}, blocks::BlockFacts, chunk::{Chunk, Light, MIN_Y, index}, - mesher::{MeshTables, Mesher, OPAQUE_LAYER, Vertex}, + mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex}, models, }; use horizon_core::biome::BiomeZoom; @@ -33,7 +33,8 @@ fn argb(color: u32) -> i32 { } /// Horizon keeps sky*16 in the low byte and block*16 above it; vanilla's light /// coords keep block in the low half-word and sky in the high one. -fn light_coords(light: u32) -> i32 { +fn light_coords(light: u16) -> i32 { + let light = u32::from(light); ((light & 0xFF) << 16 | (light >> 8 & 0xFF)) as i32 } /// Scenes cover the 3x3 chunk region around chunk (0, 0). @@ -146,9 +147,12 @@ fn scene( } for quad in vertices { let sprite = names - .get(&(quad[0].layer & !OPAQUE_LAYER)) + .get(&u32::from(quad[0].layer & !OPAQUE_LAYER)) .ok_or("unknown sprite layer")?; - if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) { + if quad + .iter() + .any(|v: &TerrainVertex| v.layer != quad[0].layer) + { return Err("quad mixes sprite layers".into()); } let vertices: Vec = quad 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/containers.rs b/crates/horizon-client/src/containers.rs index 9688af5eb..70c71d7fc 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -66,6 +66,8 @@ pub enum BlockEntity { Banner(Banner), /// `CrafterBlockEntity`. Crafter(Crafter), + /// `SpawnerBlockEntity` (`crate::mobs::spawner`). + Spawner(Box), } /// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag /// and the ticks left in the crafting animation. @@ -180,6 +182,9 @@ impl BlockEntity { if name == "minecraft:creaking_heart" { return Some(Self::CreakingHeart(Box::default())); } + if name == "minecraft:spawner" { + return Some(Self::Spawner(Box::default())); + } if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } @@ -255,6 +260,7 @@ impl BlockEntity { Self::Banner(_) => "minecraft:banner", Self::Crafter(_) => "minecraft:crafter", Self::CreakingHeart(_) => "minecraft:creaking_heart", + Self::Spawner(_) => "minecraft:mob_spawner", } } pub fn contents(&self) -> Vec { @@ -264,7 +270,7 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(), + Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -283,7 +289,7 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &[], Self::Crafter(c) => &c.items, - Self::CreakingHeart(_) => &[], + Self::CreakingHeart(_) | Self::Spawner(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -298,7 +304,7 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &mut [], Self::Crafter(c) => &mut c.items, - Self::CreakingHeart(_) => &mut [], + Self::CreakingHeart(_) | Self::Spawner(_) => &mut [], } } } diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index b696348f2..7f67aa7e2 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -67,6 +67,32 @@ impl Names { impl Creative { pub const WIDTH: f32 = 195.0; pub const HEIGHT: f32 = 136.0; + pub const TRASH_POSITION: (f32, f32) = (173.0, 112.0); + + /// Visible player slots in the creative inventory tab (game slot ids). + pub fn inventory_slots() -> impl Iterator { + (0..36).chain(500..505) + } + + /// CreativeModeInventoryScreen.selectTab positions its InventoryMenu wrappers. + pub fn inventory_slot_position(slot: usize) -> Option<(f32, f32)> { + match slot { + 0..9 => Some((9.0 + slot as f32 * 18.0, 112.0)), + 9..36 => Some(( + 9.0 + ((slot - 9) % 9) as f32 * 18.0, + 54.0 + ((slot - 9) / 9) as f32 * 18.0, + )), + 500..504 => { + let position = slot - 500; + Some(( + 54.0 + (position / 2) as f32 * 54.0, + 6.0 + (position % 2) as f32 * 27.0, + )) + } + 504 => Some((35.0, 20.0)), + _ => None, + } + } /// The scrollbar track (insideScrollbar), relative to the screen origin. pub const SCROLL_X: f32 = 175.0; pub const SCROLL_Y: f32 = 18.0; @@ -391,6 +417,52 @@ mod tests { Creative::from_json(&raw).unwrap() } + #[test] + fn inventory_tab_slot_layout_matches_vanilla() { + assert_eq!(Creative::inventory_slots().count(), 41); + for (slot, expected) in [ + (0, (9.0, 112.0)), + (8, (153.0, 112.0)), + (9, (9.0, 54.0)), + (35, (153.0, 90.0)), + (500, (54.0, 6.0)), + (501, (54.0, 33.0)), + (502, (108.0, 6.0)), + (503, (108.0, 33.0)), + (504, (35.0, 20.0)), + ] { + assert_eq!(Creative::inventory_slot_position(slot), Some(expected)); + } + assert_eq!(Creative::inventory_slot_position(100), None); + assert_eq!(Creative::TRASH_POSITION, (173.0, 112.0)); + let mut c = creative(90); + c.select(2); + assert!(c.tab().inventory); + assert!(!c.can_scroll(&Names { + map: HashMap::new() + })); + } + + #[test] + fn inventory_tab_can_return_to_category_and_search() { + let mut c = creative(90); + for (selected, inventory, search) in [ + (2, true, false), + (0, false, false), + (1, false, true), + (2, true, false), + ] { + c.search = "anvil".into(); + c.scroll = 0.5; + c.select(selected); + assert_eq!(c.selected, selected); + assert_eq!(c.tab().inventory, inventory); + assert_eq!(c.tab().search, search); + assert!(c.search.is_empty()); + assert_eq!(c.scroll, 0.0); + } + } + #[test] fn hidden_tabs_are_skipped() { let c = creative(0); diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 18cb01230..44ae40766 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -48,12 +48,14 @@ fn entity_light(normal: vec3, nether: bool) -> f32 { let l1 = normalize(vec3(-0.2, select(1.0, -1.0, nether), 0.7)); return min(1.0, (max(0.0, dot(l0, normal)) + max(0.0, dot(l1, normal))) * 0.6 + 0.4); } -// The OverlayTexture texel entity.vsh fetches: rows 0-7 hold the hurt red -// 0xB2FF0000; row 10 is white with alpha (1 - u / 15 * 0.75) * 255, u = 15 -// for the primed TNT flash (OverlayTexture.u(1.0)), so 63. Alpha 1 changes nothing. +// The OverlayTexture texel entity.vsh fetches (constants from overlay.rs): +// the hurt red for overlays 1 and 8, the white row at column 15 for the +// primed TNT flash (5) and at column overlay - 16 for 16..=31 (a creeper's +// swelling). Alpha 1 changes nothing. fn overlay_texel(overlay: u32) -> vec4 { - if overlay == 1u || overlay == 8u { return vec4(1.0, 0.0, 0.0, 178.0 / 255.0); } - if overlay == 5u { return vec4(1.0, 1.0, 1.0, 63.0 / 255.0); } + if overlay == 1u || overlay == 8u { return HURT_OVERLAY; } + if overlay == 5u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[15]); } + if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); } return vec4(1.0); } @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c47628a40..a196a1fca 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -73,6 +73,8 @@ mod net_harness; mod nether_portal; mod options; mod packs; +mod pad; +mod pad_menu; mod paintings; mod passengers; mod persist; @@ -93,6 +95,7 @@ mod sculk_fixture; mod shield; mod sign_edit; mod sniffers; +mod spawner; mod spill; mod station_control; mod stations; @@ -589,6 +592,22 @@ pub struct Resources { /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } +/// Ctrl+Q reads the physical keyboard, independently of sprint key mappings. +fn drop_whole_stack(physical_keys: &HashSet) -> bool { + physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight) +} + +fn select_creative_tab( + creative: &mut Creative, + clicks: &mut horizon_client::container_screen::Clicks, + tab: usize, +) { + creative.select(tab); + *clicks = Default::default(); + // Tabs are outside the panel; their release must not drop a carried stack. + clicks.skip_release(); +} + struct Game<'a> { res: &'a mut Resources, collision: &'a BlockCollisionRegistry<'a>, @@ -661,6 +680,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, @@ -829,6 +850,8 @@ struct Game<'a> { tridents: Vec, rockets: Vec, creaking: creaking::CreakingState, + /// Monster spawners' display mobs (`game/spawner.rs`). + spawners: spawner::SpawnerState, trident_model: Option, arrow_model: Option, tnts: Vec, @@ -876,6 +899,10 @@ struct Game<'a> { forced_hit: Option, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, + /// Block events (position, b0, b1, state) and entity events (id, event, + /// position) for the guests. + lan_block_events: Vec<([i32; 3], i32, i32, u16)>, + lan_entity_events: Vec<(i32, i8, [f64; 3])>, lan_acting: Option, /// Command feedback to forward to a guest. chat_capture: Option>, @@ -1624,6 +1651,9 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + LevelEvent::LevelEvent { id: 2004, pos, .. } => { + self.spawner_burst([pos.x, pos.y, pos.z]) + } LevelEvent::LevelEvent { id: id @ 3002..=3005, pos, @@ -2002,6 +2032,7 @@ impl Game<'_> { self.with_player_actor(|game| game.break_block_as_player(pos)) } fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { + self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); let facts = self.res.facts.get(state).clone(); @@ -2067,7 +2098,8 @@ impl Game<'_> { self.pop_resource(pos, d); } } - let xp = if silk { + // SpawnerBlock.spawnAfterBreak pops its experience whatever the tool. + let xp = if silk && &*facts.name != "minecraft:spawner" { 0 } else { self.block_experience(&facts.name) @@ -2673,6 +2705,7 @@ impl Game<'_> { } self.previous_position = feet; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.apply_equipment(); self.eye = 1.62; @@ -2708,6 +2741,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); @@ -2719,7 +2753,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(); @@ -2748,7 +2784,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; } @@ -3023,6 +3061,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) { @@ -3087,7 +3159,11 @@ impl Game<'_> { && self.title.is_none() && (matches!( self.screen, - Screen::Paused | Screen::Options | Screen::Stats | Screen::Advancements + Screen::Paused + | Screen::Options + | Screen::Stats + | Screen::Advancements + | Screen::WorldOptions ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { @@ -3143,6 +3219,7 @@ impl Game<'_> { let mut batch = self.hud_layers(size); self.frame_graph .draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas); + self.draw_pad_cursor(&mut batch); batch } fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch { @@ -3443,7 +3520,13 @@ impl Game<'_> { self.draw_book(&mut batch); batch } + fn creative_inventory_open(&self) -> bool { + self.screen == Screen::Creative && self.creative_screen.tab().inventory + } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { + if self.creative_inventory_open() { + return Self::creative_origin(batch); + } let (x, y) = batch.centered_origin(176.0, self.screen_height()); (x + self.recipe_book_shift(batch.width), y) } @@ -3454,6 +3537,9 @@ impl Game<'_> { } /// 300.. are the open container's slots. fn slots(&self) -> Vec { + if self.creative_inventory_open() { + return Creative::inventory_slots().collect(); + } if let Some(v) = self.station_slots().or_else(|| self.mount_slots()) { return v; } @@ -3470,7 +3556,8 @@ impl Game<'_> { | BlockEntity::Lectern(_) | BlockEntity::Sculk(_) | BlockEntity::Banner(_) - | BlockEntity::CreakingHeart(_), + | BlockEntity::CreakingHeart(_) + | BlockEntity::Spawner(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3484,6 +3571,11 @@ impl Game<'_> { } /// InventoryMenu / CraftingMenu slot layouts. fn slot_position(&self, i: usize) -> (f32, f32) { + if self.creative_inventory_open() + && let Some(position) = Creative::inventory_slot_position(i) + { + return position; + } if let Some(p) = self .station_slot_position(i) .or_else(|| self.machine_slot_position(i)) @@ -3593,6 +3685,32 @@ impl Game<'_> { .find_with(&grid, n, &scale) .map(|(name, result)| (name.to_owned(), result)) } + fn draw_inventory_slots(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) { + for i in self.slots() { + let (sx, sy) = self.slot_position(i); + if i == 504 && self.offhand.is_none() { + batch.sprite( + &self.res.atlas, + "gui/sprites/container/slot/shield", + ox + sx, + oy + sy, + ); + } + if (500..504).contains(&i) && self.armor[i - 500].is_none() { + let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; + batch.sprite( + &self.res.atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + sx, + oy + sy, + ); + } + let stack = self.slot_view(i); + if let Some(stack) = stack { + self.draw_item(batch, &stack, ox + sx, oy + sy); + } + } + } fn draw_inventory(&mut self, batch: &mut HudBatch) { if self.draw_station(batch) { return; @@ -3687,7 +3805,8 @@ impl Game<'_> { | BlockEntity::Lectern(_) | BlockEntity::Sculk(_) | BlockEntity::Banner(_) - | BlockEntity::CreakingHeart(_), + | BlockEntity::CreakingHeart(_) + | BlockEntity::Spawner(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -3719,30 +3838,7 @@ impl Game<'_> { if self.container.is_none() && self.craft_size != 3 && !self.mount_active() { self.draw_inventory_player(batch, ox, oy); } - for i in self.slots() { - let (sx, sy) = self.slot_position(i); - if i == 504 && self.offhand.is_none() { - batch.sprite( - &self.res.atlas, - "gui/sprites/container/slot/shield", - ox + sx, - oy + sy, - ); - } - if (500..504).contains(&i) && self.armor[i - 500].is_none() { - let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; - batch.sprite( - &self.res.atlas, - &format!("gui/sprites/container/slot/{icon}"), - ox + sx, - oy + sy, - ); - } - let stack = self.slot_view(i); - if let Some(stack) = stack { - self.draw_item(batch, &stack, ox + sx, oy + sy); - } - } + self.draw_inventory_slots(batch, ox, oy); self.draw_recipe_book(batch); if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); @@ -4204,7 +4300,7 @@ impl Game<'_> { (Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap), (None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap), (None, KeyCode::KeyQ) => { - let all = self.keys.contains(&KeyCode::ControlLeft); + let all = drop_whole_stack(&self.physical_keys); self.menu_click(Some(slot), i32::from(all), Input::Throw) } _ => false, @@ -4307,16 +4403,21 @@ impl Game<'_> { fn clicked_outside(&self, batch: &HudBatch) -> bool { use horizon_client::container_screen::{Book, Image, clicked_outside}; let (ox, oy) = self.inventory_origin(batch); - let (shift, width) = match self.station.as_ref().map(|s| s.kind) { - Some(stations::Kind::Merchant) => (-50.0, 276), - Some(stations::Kind::Beacon) => (beacon::SHIFT, 230), - _ => (0.0, 176), + let (shift, width, height) = if self.creative_inventory_open() { + (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32) + } else { + let (shift, width) = match self.station.as_ref().map(|s| s.kind) { + Some(stations::Kind::Merchant) => (-50.0, 276), + Some(stations::Kind::Beacon) => (beacon::SHIFT, 230), + _ => (0.0, 176), + }; + (shift, width, self.screen_height() as i32) }; let image = Image { left: (ox + shift) as i32, top: oy as i32, width, - height: self.screen_height() as i32, + height, }; let book = self .recipe_book_area(batch) @@ -5290,6 +5391,7 @@ impl Game<'_> { self.tick_jukeboxes(); self.tick_beacons(); self.tick_creaking_hearts()?; + self.tick_spawners()?; let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Furnace(f) = entity @@ -6672,7 +6774,12 @@ impl Game<'_> { "sculk_catalyst" | "sculk_sensor" | "calibrated_sculk_sensor" | "sculk_shrieker" => { (5, 5) } - "spawner" => (15, 43), + // SpawnerBlock.spawnAfterBreak: 15 + nextInt(15) + nextInt(15). + "spawner" => { + let r = &mut self.world.random; + let a = r.next_int_bound(15).unwrap_or(0); + return (15 + a + r.next_int_bound(15).unwrap_or(0)) as u32; + } _ => (0, 0), }; if max == 0 { @@ -7341,63 +7448,100 @@ impl Game<'_> { ); } let atlas = &self.res.atlas; - batch.text( - atlas, - &tab.title, - ox + 8.0, - oy + 6.0, - rgba(64, 64, 64, 255), - false, - ); + if !tab.inventory { + batch.text( + atlas, + &tab.title, + ox + 8.0, + oy + 6.0, + rgba(64, 64, 64, 255), + false, + ); + } if tab.search { let shown = format!("{}_", self.creative_screen.search); batch.text(atlas, &shown, ox + 82.0, oy + 6.0, u32::MAX, true); } - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); let mut hovered: Option = None; - for r in 0..5 { - for c in 0..9 { - let Some(stack) = items.get((first + r) * 9 + c) else { - continue; - }; - let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); - self.draw_item(batch, stack, x, y); - if self.cursor.0 >= x - && self.cursor.0 < x + 16.0 - && self.cursor.1 >= y - && self.cursor.1 < y + 16.0 - { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); - hovered = Some(stack.item.to_string()); - } + if tab.inventory { + self.draw_player_preview( + batch, + ox + 73.0, + oy + 6.0, + ox + 105.0, + oy + 49.0, + 20.0, + 0.0625, + ); + self.draw_inventory_slots(batch, ox, oy); + if Self::creative_trash_hovered(batch, self.cursor) { + let (x, y) = Creative::TRASH_POSITION; + batch.fill( + &self.res.atlas, + ox + x, + oy + y, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); } - } - for c in 0..9 { - let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0); - if let Some(stack) = self.inventory[c].clone() { - self.draw_item(batch, &stack, x, y); - if self.cursor.0 >= x - && self.cursor.0 < x + 16.0 - && self.cursor.1 >= y - && self.cursor.1 < y + 16.0 - { - hovered = Some(stack.item.to_string()); - } + if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { + let (x, y) = self.slot_position(slot); + batch.fill( + &self.res.atlas, + ox + x, + oy + y, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); } - } - let scrollable = self.creative_screen.rows(&self.res.names) > 5; - let scroller = if scrollable { - "gui/sprites/container/creative_inventory/scroller" } else { - "gui/sprites/container/creative_inventory/scroller_disabled" - }; - batch.sprite( - &self.res.atlas, - scroller, - ox + Creative::SCROLL_X, - oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), - ); + let items = self.creative_screen.items(&self.res.names); + let first = self.creative_screen.first_row(&self.res.names); + for r in 0..5 { + for c in 0..9 { + let Some(stack) = items.get((first + r) * 9 + c) else { + continue; + }; + let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); + self.draw_item(batch, stack, x, y); + if self.cursor.0 >= x + && self.cursor.0 < x + 16.0 + && self.cursor.1 >= y + && self.cursor.1 < y + 16.0 + { + batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + hovered = Some(stack.item.to_string()); + } + } + } + for c in 0..9 { + let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0); + if let Some(stack) = self.inventory[c].clone() { + self.draw_item(batch, &stack, x, y); + if self.cursor.0 >= x + && self.cursor.0 < x + 16.0 + && self.cursor.1 >= y + && self.cursor.1 < y + 16.0 + { + hovered = Some(stack.item.to_string()); + } + } + } + let scrollable = self.creative_screen.rows(&self.res.names) > 5; + let scroller = if scrollable { + "gui/sprites/container/creative_inventory/scroller" + } else { + "gui/sprites/container/creative_inventory/scroller_disabled" + }; + batch.sprite( + &self.res.atlas, + scroller, + ox + Creative::SCROLL_X, + oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), + ); + } for t in &tabs { let (tx, ty) = Creative::tab_position(t); if self.cursor.0 >= ox + tx @@ -7410,11 +7554,28 @@ impl Game<'_> { } if let Some(stack) = self.carried.clone() { self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); - } else if let Some(item) = hovered { + } + if tab.inventory { + if Self::creative_trash_hovered(batch, self.cursor) { + self.tooltip(batch, "Destroy Item", self.cursor.0, self.cursor.1); + } else { + self.draw_slot_tooltip(batch); + } + } else if self.carried.is_none() + && let Some(item) = hovered + { let name = self.res.names.item(&item); self.tooltip(batch, &name, self.cursor.0, self.cursor.1); } } + fn creative_trash_hovered(batch: &HudBatch, cursor: (f32, f32)) -> bool { + let (ox, oy) = Self::creative_origin(batch); + let (x, y) = Creative::TRASH_POSITION; + cursor.0 >= ox + x + && cursor.0 < ox + x + 16.0 + && cursor.1 >= oy + y + && cursor.1 < oy + y + 16.0 + } fn click_creative(&mut self, right: bool) { let Some(size) = self .renderer @@ -7430,14 +7591,30 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { let (tx, ty) = Creative::tab_position(t); if cx >= ox + tx && cx < ox + tx + 26.0 && cy >= oy + ty && cy < oy + ty + 32.0 { - if t.inventory { - self.screen = Screen::Inventory; - return; - } - self.creative_screen.select(i); + select_creative_tab(&mut self.creative_screen, &mut self.inv_clicks, i); + self.inv_drag = None; + self.last_inv_click = None; return; } } + if self.creative_inventory_open() { + if Self::creative_trash_hovered(&batch, self.cursor) { + if self.has_shift_down() { + self.inventory.fill(None); + self.armor.fill(None); + self.offhand = None; + self.craft_grid[..4].fill(None); + self.apply_equipment(); + } else { + self.carried = None; + } + self.inv_drag = None; + self.inv_clicks = Default::default(); + } else if self.slot_at(&batch, cx, cy).is_some() || self.clicked_outside(&batch) { + self.inventory_press(right); + } + return; + } // Holding the scrollbar scrolls as the mouse moves (mouseDragged). if !right && self @@ -7765,7 +7942,7 @@ impl Game<'_> { } else { Vec::new() }; - let hand = if title || self.screen == Screen::Inventory || self.scoping() { + let hand = if title || self.scoping() { Vec::new() } else { self.hand_geometry(alpha) @@ -7956,7 +8133,8 @@ impl Game<'_> { | KeyCode::Digit9 | KeyCode::KeyF | KeyCode::KeyQ - if self.screen == Screen::Inventory && self.inventory_hotkey(key) => {} + if (self.screen == Screen::Inventory || self.creative_inventory_open()) + && self.inventory_hotkey(key) => {} KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), // key.advancements. @@ -8002,7 +8180,7 @@ impl Game<'_> { self.using = None; } KeyCode::KeyQ if self.screen == Screen::Playing => { - let all = self.keys.contains(&KeyCode::ControlLeft); + let all = drop_whole_stack(&self.physical_keys); self.drop_held(all); } KeyCode::Digit1 @@ -8294,6 +8472,8 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory { self.loom_drag(); + } + if self.screen == Screen::Inventory || self.creative_inventory_open() { self.inventory_drag_move(); } if self.dragging && self.screen == Screen::Options { @@ -8449,6 +8629,9 @@ impl ApplicationHandler for Game<'_> { Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); } + Screen::Creative if self.creative_screen.tab().inventory => { + self.inventory_mouse_release(button == MouseButton::Right); + } Screen::Creative if button == MouseButton::Left => { self.creative_screen.release(); } @@ -8529,18 +8712,23 @@ impl ApplicationHandler for Game<'_> { WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => { self.remote_chat_key(&event) } - WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::WorldOptions => { + WindowEvent::KeyboardInput { event, .. } + if self.screen == Screen::WorldOptions + && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => + { self.world_options_key(&event) } - WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => { + // Options consumes presses; releases still reach the bound + // gameplay mapping below, including sneak/sprint toggles. + WindowEvent::KeyboardInput { event, .. } + if self.screen == Screen::Options && event.state == ElementState::Pressed => + { if let Some(shortcut) = self.edit_shortcut(&event) && self.options_shortcut(shortcut) { return Ok(()); } - if event.state == ElementState::Pressed - && let PhysicalKey::Code(key) = event.physical_key - { + if let PhysicalKey::Code(key) = event.physical_key { self.options_key(key, event.text.as_deref())?; } } @@ -8592,36 +8780,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(); @@ -8666,6 +8825,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()?; @@ -8771,6 +8931,7 @@ impl ApplicationHandler for Game<'_> { } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { self.poll_control(event_loop); + self.poll_pads(event_loop); if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout { self.error = Some("frame-limited run timed out".into()); event_loop.exit(); @@ -9029,6 +9190,7 @@ pub fn run() -> Result<()> { started: now, previous: now, last_input: now, + pad: Default::default(), frames: 0, fps: 0.0, fps_frames: 0, @@ -9152,6 +9314,7 @@ pub fn run() -> Result<()> { tridents: Vec::new(), rockets: Vec::new(), creaking: Default::default(), + spawners: Default::default(), trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), tnts: Vec::new(), @@ -9181,6 +9344,8 @@ pub fn run() -> Result<()> { saved_for_exit: false, forced_hit: None, lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), lan_acting: None, chat_capture: None, cmds: Default::default(), @@ -9208,9 +9373,7 @@ pub fn run() -> Result<()> { player_model: None, }; game.ui.vanilla_root = vanilla_root; - game.res.atlas.font.uniform = game.settings.force_unicode; - game.res.atlas.font.japanese = game.settings.japanese_glyphs; - game.ui.chat.options = game.settings.chat_options(); + game.apply_settings(); if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) .map_err(|e| format!("control socket {}: {e}", path.display()))?; @@ -9301,3 +9464,65 @@ mod runtime_reset_tests { assert!(stats.values.is_empty()); } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::container_screen::{Button, Clicks, Release, Target}; + use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys}; + + #[test] + fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() { + let mut creative = Creative::from_json(&serde_json::json!({ + "schema": 2, + "tabs": [{"type": "CATEGORY"}, {"type": "INVENTORY"}] + })) + .unwrap(); + for button in [Button::Left, Button::Right] { + let mut clicks = Clicks::default(); + for tab in [1, 1, 0, 1] { + select_creative_tab(&mut creative, &mut clicks, tab); + assert_eq!(creative.selected, tab); + assert_eq!(creative.tab().inventory, tab == 1); + assert_eq!( + clicks.release( + &Target::::Outside, + button, + false, + false, + false, + false + ), + Release::Nothing + ); + } + } + } + + #[test] + fn stack_drop_requires_physical_ctrl_even_with_sprint_latched() { + for sprint in [false, true] { + let mut toggles = ToggleKeys::default(); + if sprint { + toggles.key(SPRINT, KeyAction::Press, false, true); + toggles.key(SPRINT, KeyAction::Release, false, true); + } + assert_eq!(toggles.is_down(SPRINT), sprint); + + for held in 0..4 { + let mut physical_keys = HashSet::from([KeyCode::ShiftLeft, KeyCode::KeyQ]); + if held & 1 != 0 { + physical_keys.insert(KeyCode::ControlLeft); + } + if held & 2 != 0 { + physical_keys.insert(KeyCode::ControlRight); + } + assert_eq!(drop_whole_stack(&physical_keys), held != 0); + physical_keys.remove(&KeyCode::ControlLeft); + physical_keys.remove(&KeyCode::ControlRight); + assert!(!drop_whole_stack(&physical_keys)); + assert_eq!(toggles.is_down(SPRINT), sprint); + } + } + } +} diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 2de1f4c74..8b1b8071e 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -1232,14 +1232,7 @@ impl Game<'_> { self.playing()?; let all = a.pos.first() == Some(&"all"); let before = self.held().map(|s| self.stack_value(s)); - if all { - self.keys.insert(KeyCode::ControlLeft); - } - let result = self.key_pressed(KeyCode::KeyQ); - if all { - self.keys.remove(&KeyCode::ControlLeft); - } - result?; + self.drop_held(all); ok( json!({ "ok": true, "dropped_from": before, "held": self.held().map(|s| self.stack_value(s)) }), ) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index e0f908f43..dc5c7cdf1 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -88,7 +88,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..bc584990d 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()?; @@ -161,8 +163,9 @@ impl Game<'_> { self.debug_key(key, KeyAction::Release); } } - // Physical key presses follow the key binds like the keyboard does. - let key = if matches!(self.screen, Screen::Chat | Screen::Options) { + // Text screens consume raw presses; releases follow key binds. + let typing = matches!(self.screen, Screen::Chat | Screen::Options); + let key = if typing && arg(2)? != "up" { key } else { match self.settings.keys.translate(key) { @@ -391,6 +394,8 @@ impl Game<'_> { "sound" => Page::Sound, "controls" => Page::Controls, "keybinds" => Page::KeyBinds, + "controller" => Page::Controller, + "controller-binds" => Page::PadBinds, "mouse" => Page::Mouse, "chat" => Page::Chat, "accessibility" => Page::Accessibility, @@ -570,6 +575,9 @@ impl Game<'_> { json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name }) }); let renderer = self.renderer.as_ref().map(|r| { + let [arena_bytes, section_vertex_bytes] = r.section_vertex_bytes(); + // Device memory by the backend's allocator (Vulkan; absent elsewhere). + let memory = r.device.generate_allocator_report(); json!({ "gpu": r.info.name, "backend": format!("{:?}", r.info.backend), @@ -578,6 +586,10 @@ impl Game<'_> { "drawn_sections": r.drawn_sections, "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), + "arena_bytes": arena_bytes, + "section_vertex_bytes": section_vertex_bytes, + "gpu_allocated_bytes": memory.as_ref().map(|m| m.total_allocated_bytes), + "gpu_reserved_bytes": memory.as_ref().map(|m| m.total_reserved_bytes), }) }); json!({ diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 5126a8982..4789ea9e9 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -24,6 +24,17 @@ use horizon_core::{ }; use std::sync::Arc; +/// The world impact sound after successful arrow damage, including self-shots. +fn arrow_impact_sound( + random: &mut impl RandomSource, + hurt: bool, +) -> Option<(&'static str, f32, f32)> { + hurt.then(|| { + let pitch = 1.2 / (random.next_float() * 0.2 + 0.9); + ("minecraft:entity.arrow.hit", 1.0, pitch) + }) +} + /// Mob-system state owned by the game. #[derive(Default)] pub(super) struct Creatures { @@ -695,10 +706,10 @@ impl Game<'_> { // (`entity_motion_events`). MobEvent::GameEvent { .. } => {} MobEvent::AttackPlayer(amount, from) => { - self.mob_hits_player(amount, from, "minecraft:mob_attack") + self.mob_hits_player(amount, from, "minecraft:mob_attack"); } MobEvent::DamagePlayer { amount, from, kind } => { - self.mob_hits_player(amount, from, kind) + self.mob_hits_player(amount, from, kind); } MobEvent::ElderCurse { at } => self.elder_curse(at), MobEvent::Push { target, velocity } => { @@ -1266,9 +1277,9 @@ impl Game<'_> { pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { self.mob_hits_player(amount, from, kind); } - fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) { + fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) -> bool { if self.creative { - return; + return false; } let projectile = self .res @@ -1327,6 +1338,7 @@ impl Game<'_> { if raised { self.after_block(outcome, amount, attacker, projectile); } + outcome.hurt } /// A status effect from a mob, arrow or splash potion (`addEffect`). pub(super) fn give_player_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { @@ -1510,42 +1522,42 @@ impl Game<'_> { seconds: 5, }])?; } - match who { + let hurt = match who { Who::Player => { - if !self.creative { - self.mob_hits_player( - amount, - [p.previous.x, p.previous.y, p.previous.z], - "minecraft:arrow", - ); - if let Some((e, t)) = effect { - self.give_player_effect(e, *t, 0); - } - self.audio.play( - "minecraft:entity.arrow.hit_player", - Some(atp), - 1.0, - 1.0, - ); + let hurt = self.mob_hits_player( + amount, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:arrow", + ); + if hurt && let Some((e, t)) = effect { + self.give_player_effect(e, *t, 0); } + hurt } Who::Mob(id) => { - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - m.damage(amount, source); - } + let hurt = self + .mobs + .iter_mut() + .find(|m| m.id == id) + .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { self.last_hurt_by_player.insert(id); } - let pitch = 1.2 / (self.world.random.next_float() * 0.2 + 0.9); - self.audio - .play("minecraft:entity.arrow.hit", Some(atp), 1.0, pitch); + hurt } + }; + if let Some((sound, volume, pitch)) = + arrow_impact_sound(&mut self.world.random, hurt) + { + self.audio.play(sound, Some(atp), volume, pitch); } } (ProjectileKind::Arrow { .. }, Hit::Block { .. }) => { - let pitch = 1.2 / (self.world.random.next_float() * 0.2 + 0.9); - self.audio - .play("minecraft:entity.arrow.hit", Some(atp), 1.0, pitch); + if let Some((sound, volume, pitch)) = + arrow_impact_sound(&mut self.world.random, true) + { + self.audio.play(sound, Some(atp), volume, pitch); + } } (ProjectileKind::Snowball, hit) => { if let Hit::Entity { @@ -1652,11 +1664,13 @@ impl Game<'_> { (ProjectileKind::LargeFireball { power }, hit) => { if let Hit::Entity { who, .. } = hit { match who { - Who::Player => self.mob_hits_player( - 6.0, - [p.previous.x, p.previous.y, p.previous.z], - "minecraft:fireball", - ), + Who::Player => { + self.mob_hits_player( + 6.0, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:fireball", + ); + } Who::Mob(id) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.damage(6.0, source); @@ -1734,11 +1748,13 @@ impl Game<'_> { ); } (ProjectileKind::LlamaSpit, Hit::Entity { who, .. }) => match who { - Who::Player => self.mob_hits_player( - 1.0, - [p.previous.x, p.previous.y, p.previous.z], - "minecraft:spit", - ), + Who::Player => { + self.mob_hits_player( + 1.0, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:spit", + ); + } Who::Mob(id) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.damage(1.0, source); @@ -2328,6 +2344,23 @@ impl Game<'_> { return Ok(false); }; let kind = stack.item.trim_end_matches("_spawn_egg").to_owned(); + // EntityType.canSpawn: no monsters in peaceful (FAIL ends the click). + let id = format!("minecraft:{}", kind.trim_start_matches("minecraft:")); + if self.ui.difficulty == 0 + && let Some(t) = self.res.mob_types.get(&id) + && !horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species) + { + return Ok(true); + } + // SpawnEggItem.useOn on a spawner sets its mob. + if let Some(done) = self.use_spawn_egg_on_spawner(hit.pos, &id) { + if done { + self.swing_arm(); + self.stats.add("used", &stack.item, 1); + self.consume_held(); + } + return Ok(true); + } let p = [ hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], @@ -2444,6 +2477,7 @@ impl Game<'_> { } } self.elder_apparition_geometry(alpha, out); + self.spawner_geometry(camera, alpha, out); // Projectiles: the baked vanilla arrow model, the rest as item billboards. let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); let forward = glam::Vec3::new( @@ -2658,3 +2692,32 @@ impl Game<'_> { let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + #[test] + fn arrow_impact_uses_world_sound_volume_and_seeded_pitch() { + let mut random = LegacyRandom::new(0); + assert_eq!( + arrow_impact_sound(&mut random, true), + Some(( + "minecraft:entity.arrow.hit", + 1.0, + f32::from_bits(0x3f92d167) + )) + ); + let mut expected = LegacyRandom::new(0); + expected.next_float(); + assert_eq!(random.next_float(), expected.next_float()); + } + + #[test] + fn rejected_arrow_damage_is_silent_without_drawing_pitch() { + let mut random = LegacyRandom::new(0); + assert_eq!(arrow_impact_sound(&mut random, false), None); + assert_eq!(random.next_float(), LegacyRandom::new(0).next_float()); + } +} diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index e3fd0e896..ab6a79961 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -340,6 +340,34 @@ impl Game<'_> { disabled.join(",") )); } + // A spawner's next spawn data (its id and number of keys), potentials and delay. + let mut spawners: Vec<_> = self + .world + .block_entities + .iter() + .filter_map(|(p, e)| match e { + BlockEntity::Spawner(s) => Some((*p, s)), + _ => None, + }) + .collect(); + spawners.sort_unstable_by_key(|s| s.0); + for (p, s) in spawners { + let next = s.next_data().map_or("-".to_owned(), |d| { + format!( + "{}/{}", + d.id().unwrap_or_else(|| "?".into()), + d.entity.len() + ) + }); + out.push(format!( + "spawner {},{},{} next={next} potentials={} delay={}", + p.0, + p.1, + p.2, + s.potentials.len(), + s.spawn_delay as i16 + )); + } self.fixture_entities(&old_mobs, &old_stands, &mut out); for (i, t) in targets.iter().enumerate() { out.push(self.fixture_describe(i, t)); @@ -449,11 +477,19 @@ impl Game<'_> { f64::from(pos.z) + 0.5, ], }); + self.chat_capture = Some(Vec::new()); let used = self.use_item_as_player(); self.forced_hit = None; + let messages = self.chat_capture.take().unwrap_or_default(); used?; self.process_level_events()?; let mut out = Vec::new(); + for m in messages { + let key = m.component()["translate"] + .as_str() + .map_or_else(|| m.plain(), str::to_owned); + out.push(format!("msg {key}")); + } if let Some(s) = &stack { let used = self.stats.get("used", &s.item) - used_before; if used != 0 { diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index fa60228de..e6be63093 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -485,6 +485,7 @@ impl Game<'_> { player.fall_distance = 0.0; self.previous_position = player.position; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.apply_equipment(); let pitch = self.world.random.next_float() * 0.4 + 0.8; diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 9aaafd045..1332ad51d 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -335,6 +335,15 @@ impl Game<'_> { interaction: BlockInteraction, fire: bool, ) -> Result<()> { + if let Some(p) = &self.player { + let d = [ + p.position.x - center[0], + p.position.y - center[1], + p.position.z - center[2], + ]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius }); + } let mut targets = self.exploded_positions(center, radius); // Explosion.explode: the blast is heard. let ctx = horizon_client::sculk::Context::default(); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index a29ca085c..6fd7e4dd8 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -707,6 +707,19 @@ impl Game<'_> { } } + /// `Level.blockEvent` for the guests (`ClientboundBlockEventPacket`). + pub(super) fn lan_block_event(&mut self, pos: [i32; 3], b0: i32, b1: i32) { + if self.audio.capture.is_some() { + let state = self.world.block(pos[0], pos[1], pos[2]).0 as u16; + self.lan_block_events.push((pos, b0, b1, state)); + } + } + /// `Level.broadcastEntityEvent` for the guests. + pub(super) fn lan_entity_event(&mut self, id: i32, event: i8, at: [f64; 3]) { + if self.audio.capture.is_some() { + self.lan_entity_events.push((id, event, at)); + } + } /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { @@ -716,6 +729,12 @@ impl Game<'_> { } host.hub.level_event(kind, pos, data, acting); } + for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) { + host.hub.block_event(pos, b0, b1, state); + } + for (id, event, at) in std::mem::take(&mut self.lan_entity_events) { + host.hub.entity_event(id, event, at); + } self.lan_broadcast_effects(host); if host.hub.guests.is_empty() { host.mob_state.clear(); diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 4183596eb..8f2612472 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -304,8 +304,6 @@ impl Game<'_> { self.world_options = Some(o); self.apply_world_options(&before, &wanted); self.close_world_options(); - self.screen = Screen::Playing; - self.capture(true); return; } None => {} diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index fc37143b7..83d7ddfb3 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -28,7 +28,9 @@ pub(super) struct GameLevel<'g, 'a> { pub(super) game: &'g Game<'a>, w: MobWorld<'g>, /// Boxes of the mobs this pass created, not yet in the game's list. - pending: std::cell::RefCell>, + pub(super) pending: std::cell::RefCell>, + /// The types and boxes of what a spawner created this tick. + pub(super) pending_ids: std::cell::RefCell>, } impl GameLevel<'_, '_> { fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { @@ -165,7 +167,20 @@ impl NaturalLevel for GameLevel<'_, '_> { binding: self.w.collision, subject: None, }; + // getEntityCollisions(null, box): living shulkers are solid. + let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut scene, bounds) + && !self.game.mobs.iter().any(|m| { + m.species() == Species::Shulker + && m.alive() + && !m.removed + && m.bounds().intersects(grown) + }) + && !self + .pending_ids + .borrow() + .iter() + .any(|(id, b)| id == "minecraft:shulker" && b.intersects(grown)) } fn unobstructed(&self, bounds: Aabb) -> bool { let player = self @@ -194,12 +209,49 @@ impl NaturalLevel for GameLevel<'_, '_> { self.w.data.state(self.state(x, y, z)).flags & data::LAND != 0 } } +impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { + fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool { + let Some(p) = self.game.player_view() else { + return false; + }; + if !p.alive || p.spectator { + return false; + } + let at = self.game.player.as_ref().map(|p| p.position); + at.is_some_and(|a| { + let d = (a.x - x).powi(2) + (a.y - y).powi(2) + (a.z - z).powi(2); + range < 0.0 || d < range * range + }) + } + fn spawner_blocks_work(&self) -> bool { + self.game.ui.rules.bool("spawner_blocks_work") + } + fn entity_exists(&self, id: &str) -> bool { + self.game.res.mob_types.contains_key(id) || self.game.entity_type_exists(id) + } + fn count_entities(&self, id: &str, bounds: Aabb) -> usize { + let mobs = self + .game + .mobs + .iter() + .filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds)) + .count(); + let pending = self + .pending_ids + .borrow() + .iter() + .filter(|(k, b)| k == id && b.intersects(bounds)) + .count(); + mobs + pending + } +} impl<'a> Game<'a> { pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> { GameLevel { game: self, w: self.mob_world_base(&[]), pending: Default::default(), + pending_ids: Default::default(), } } /// Creates a mob the spawner accepted, finalized the game's way; the diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index a6296d09b..829f1e6ab 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -361,6 +361,7 @@ impl Game<'_> { player.velocity = rotate_y(player.velocity, -rotation); self.previous_position = player.position; self.player = Some(player); + self.pad.player_replaced(); self.sway = Default::default(); self.apply_equipment(); let pitch = self.world.random.next_float() * 0.4 + 0.8; diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index f9f7fc617..e4d44fe9d 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -26,6 +26,9 @@ impl Game<'_> { } /// Open the options screens (OptionsScreen) from the title or pause menu. pub(super) fn open_options(&mut self, from_title: bool) { + // Gameplay keys must not stay held behind the options screen, where + // bindings can also change before the physical key is released. + self.keys.clear(); self.screen = Screen::Options; self.options_from_title = from_title; let ui = &mut self.ui.options; @@ -91,7 +94,10 @@ impl Game<'_> { .shortcut(&self.res.atlas, shortcut, &mut self.clipboard) } pub(super) fn options_scroll(&mut self, amount: f32) { - self.ui.options.scroll_at(self.cursor, amount); + let size = self.gui_size(); + self.ui + .options + .scroll_at(&self.settings, size, self.cursor, amount); } /// Mouse buttons pressed while a key is being bound. pub(super) fn options_waiting_for_key(&self) -> bool { @@ -106,7 +112,7 @@ impl Game<'_> { } Ok(()) } - fn handle_option_events(&mut self, events: Vec) -> Result<()> { + pub(super) fn handle_option_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { Event::Changed => { diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs new file mode 100644 index 000000000..2f050fdec --- /dev/null +++ b/crates/horizon-client/src/game/pad.rs @@ -0,0 +1,532 @@ +//! 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, HealthWatch, PadState, Rumble}, + keybinds::{KeyBinds, key_code, mouse_button}, + mouse::Rotation, +}; +use serde_json::{Value, json}; +use std::time::{Duration, Instant}; +use winit::{event_loop::ActiveEventLoop, 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