From 337d7d7a7a518e425d3f6dc9676f0b41b716a085 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:39:45 +0200 Subject: [PATCH 01/19] Entity use with either hand: bows and food past a mob, off-hand items on mobs, emptied frames - The remote client sends Interact for a targeted mob only for a hand vanilla's client-side Mob.interact would accept with it (leads, name tags, food, buckets, shears, saddled mounts, tamed pets, ...), so a bow drawn or food eaten while aiming at a cow goes on to useItem (#1350). - Both hands: the main hand's item, then the off hand's entity, block and item (Minecraft.startUseItem). The server runs Interact with the packet's hand (GuestUse::Entity), and mobs, armour stands, leads and mounts use the held hand's stack, so an off-hand bucket milks a cow and off-hand wheat feeds it (#1362). - The entity tracker sends an item frame's item and rotation when they go back to empty and 0, so a punched frame shows empty on clients (#1355). - lan_e2e `hands`: the bow, the golden apple, the off-hand bucket and wheat and the emptied frame, for the host and the guest. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 35 +++++-- .../horizon-client/src/game/armor_stands.rs | 4 +- crates/horizon-client/src/game/creatures.rs | 31 ++++--- crates/horizon-client/src/game/lan_actions.rs | 5 + crates/horizon-client/src/game/leads.rs | 4 +- crates/horizon-client/src/game/mounts.rs | 2 +- crates/horizon-client/src/game/remote.rs | 29 ++++-- .../horizon-client/src/game/remote_mob_use.rs | 91 +++++++++++++++++++ crates/horizon-client/src/lan/entity.rs | 39 +++++++- tools/lan_e2e.py | 86 +++++++++++++++++- 10 files changed, 288 insertions(+), 38 deletions(-) create mode 100644 crates/horizon-client/src/game/remote_mob_use.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0faca0ab4..2d185b40e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -121,6 +121,7 @@ mod pumpkin; mod raids; mod recipe_book; mod remote; +mod remote_mob_use; mod remote_objects; mod remote_projectiles; mod remote_stations; @@ -495,6 +496,9 @@ enum FallStep { enum GuestUse { OnBlock(Hand), Item(Hand), + /// `handleInteract`: `Player.interactOn` with the hand, nothing else (the + /// client sends UseItem itself when the entity passed). + Entity(Hand), } /// The client world as seen by the vanilla block-behaviour library. @@ -3210,6 +3214,9 @@ impl Game<'_> { // A guest's use packets name one hand and touch no entity: the client // sends one per hand and part of its click, and Interact for entities. let guest = self.guest_use; + if let Some(GuestUse::Entity(hand)) = guest { + return Ok(self.with_hand(hand, Game::interact_entity)?.then_some(hand)); + } let on_block = matches!(guest, Some(GuestUse::OnBlock(_))); if !on_block && self.riding.is_some() @@ -3218,14 +3225,7 @@ impl Game<'_> { { return Ok(Some(Hand::Main)); } - if guest.is_none() - && (self.interact_frame() - || self.interact_armor_stand() - || self.interact_boat() - || self.interact_cart() - || self.interact_mob()? - || self.interact_knot()) - { + if guest.is_none() && self.interact_entity()? { return Ok(Some(Hand::Main)); } // An EntityHitResult may fall through to Item.use, never to useItemOn. @@ -3235,16 +3235,33 @@ impl Game<'_> { self.pick() }; let hands = match guest { - Some(GuestUse::OnBlock(hand) | GuestUse::Item(hand)) => vec![hand], + Some(GuestUse::OnBlock(hand) | GuestUse::Item(hand) | GuestUse::Entity(hand)) => { + vec![hand] + } None => Hand::BOTH.to_vec(), }; + let entity = guest.is_none() && self.entity_targeted(); for hand in hands { + // The off hand's turn starts on the entity too (Minecraft.startUseItem). + if entity && hand == Hand::Off && self.with_hand(hand, Game::interact_entity)? { + return Ok(Some(hand)); + } if self.with_hand(hand, |game| game.use_hand(block_hit.as_ref()))? { return Ok(Some(hand)); } } Ok(None) } + /// `Player.interactOn` for the entity under the crosshair with the + /// acting hand: whether it took the click. + fn interact_entity(&mut self) -> Result { + Ok(self.interact_frame() + || self.interact_armor_stand() + || self.interact_boat() + || self.interact_cart() + || self.interact_mob()? + || self.interact_knot()) + } /// One hand's turn in `startUseItem`: `useItemOn` the block aimed at, /// then `useItem`. Whether the click ends here (it acted or failed). fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 6e06f21b0..f175af401 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -461,14 +461,14 @@ impl Game<'_> { count: 1, ..h.clone() }); - self.inventory[self.selected] = Some(ItemStack { + *self.held_mut() = Some(ItemStack { count: h.count - 1, ..h }); } h => { self.armor_stands[i].equipment[slot] = h; - self.inventory[self.selected] = current; + *self.held_mut() = current; } } let p = self.armor_stands[i].position; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 969543601..06b96be2b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2409,13 +2409,14 @@ impl Game<'_> { self.spawn_item(rest, self.eye_position().unwrap_or([0.0; 3]), [0.0; 3], 40); } } else { - self.inventory[self.selected] = Some(filled); + *self.held_mut() = Some(filled); } self.swing_arm(); return Ok(true); } let creative = self.creative; - let selected = self.selected; + // The hand's slot (Player.interactOn passes the hand). + let selected = self.held_slot(); if self.interact_zombie_villager(index, &item) { return Ok(true); } @@ -2447,10 +2448,10 @@ impl Game<'_> { // PiglinAi.mobInteract: hand over something gold to admire. if self.mobs[index].alive() && self.give_piglin(index, &item) { self.swing_arm(); - if !creative && let Some(stack) = self.inventory[selected].as_mut() { + if !creative && let Some(stack) = self.stack_in_mut(selected).as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[selected] = None; + *self.stack_in_mut(selected) = None; } } return Ok(true); @@ -2761,11 +2762,11 @@ impl Game<'_> { } if consume && !creative - && let Some(stack) = self.inventory[selected].as_mut() + && let Some(stack) = self.stack_in_mut(selected).as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[selected] = None; + *self.stack_in_mut(selected) = None; } } if let Some(g) = give { @@ -2775,8 +2776,8 @@ impl Game<'_> { damage: 0, extra: None, }; - if self.inventory[selected].is_none() { - self.inventory[selected] = Some(stack); + if self.stack_in(selected).is_none() { + *self.stack_in_mut(selected) = Some(stack); } else if let Some(rest) = self.give(stack) { let at = self.eye_position().unwrap_or(center); self.spawn_item(rest, at, [0.0, 0.0, 0.0], 40); @@ -2808,13 +2809,17 @@ impl Game<'_> { if self.creative { return; } - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items().get(&stack.item) - && info.max_damage > 0 + let slot = self.held_slot(); + let max_damage = self + .held() + .and_then(|s| self.res.items().get(&s.item)) + .map_or(0, |i| i.max_damage); + if max_damage > 0 + && let Some(stack) = self.stack_in_mut(slot).as_mut() { stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + if stack.damage >= max_damage { + *self.stack_in_mut(slot) = None; } } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 67764c090..e3b94a87b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -942,9 +942,14 @@ impl Game<'_> { .look_at_entity(host, gi, p.id, Some(p.location)) .is_some() { + // handleInteract: the entity and that hand only; a click the + // entity passes comes back as UseItem. + let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; let swung = self.as_guest(host, conn, |g| { + g.guest_use = Some(GuestUse::Entity(hand)); let swings = g.swings_started; let _ = g.use_item(); + g.guest_use = None; g.swings_started != swings }); self.lan_swing_back(host, conn, swung); diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index ae5d87fff..3a5112967 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -202,10 +202,10 @@ impl Game<'_> { self.mobs[index].extra.leash = Some(Holder::Player); self.lead_sound("tied", at); // The lead is always used up. - if let Some(stack) = self.inventory[self.selected].as_mut() { + if let Some(stack) = self.held_mut().as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } return true; diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index c10d7a458..fa4bbc209 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -104,7 +104,7 @@ impl Game<'_> { } /// `AbstractHorse.mobInteract`. Returns whether the click was used. pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool { - let held = self.inventory[self.selected].clone(); + let held = self.held().cloned(); let m = &self.mobs[index]; let species = m.species(); // A server player rides it already (`isVehicle`: no seat, no feeding). diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f969cbeb9..76851364a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3624,7 +3624,10 @@ impl Game<'_> { horizon_client::interaction_input::use_on_target(&mut RemoteUseWorld(self), entity); } - fn remote_use_entity(&mut self) -> bool { + /// `Minecraft.startUseItem`'s entity turn for `hand`: Interact goes to + /// the server, and whether the click ends there is what this client's + /// copy of the entity answers (`MultiPlayerGameMode.interact`). + fn remote_use_entity(&mut self, hand: Hand) -> bool { let sneaking = self.keys.contains(&KeyCode::ShiftLeft); // A boat, minecart, item frame, armor stand or painting nearer than // any mob: the server uses it (AbstractBoat.interact boards it). @@ -3632,6 +3635,10 @@ impl Game<'_> { && self.mob_hit().is_none_or(|(_, d)| hit.distance < d) && self.before_block(hit.distance) { + // The main hand's turn takes it; there is no off hand turn. + if hand == Hand::Off { + return false; + } self.send(S::Interact(play::Interact { id: hit.id, hand: 0, @@ -3647,18 +3654,18 @@ impl Game<'_> { let id = self.mobs[i].id as i32; self.send(S::Interact(play::Interact { id, - hand: 0, + hand: hand_id(hand), location: [0.0, 1.0, 0.0], secondary: sneaking, })); - // Player.interactOn: another player passes, and the held item is - // used instead (Minecraft.startUseItem). + // Player.interactOn: another player passes, and so does a mob + // the held item means nothing to: the item is used instead. let player = self .remote .as_ref() .is_some_and(|r| r.level_players.contains_key(&id)); - if !player { - self.swing_arm(); + if !player && self.remote_mob_takes(i, hand) { + self.with_hand(hand, Game::swing_arm); return true; } } @@ -3881,7 +3888,13 @@ impl Game<'_> { if self.remote_use_item(Hand::Main) { return; } - if !self.entity_targeted() && self.remote_use_block(Hand::Off) { + // The off hand's turn: the entity again, or the block. + let off_target = if self.entity_targeted() { + self.remote_use_entity(Hand::Off) + } else { + self.remote_use_block(Hand::Off) + }; + if off_target { return; } self.remote_use_item(Hand::Off); @@ -4986,7 +4999,7 @@ struct RemoteUseWorld<'g, 'a>(&'g mut Game<'a>); impl horizon_client::interaction_input::TargetUseWorld for RemoteUseWorld<'_, '_> { fn use_entity(&mut self) -> bool { - self.0.remote_use_entity() + self.0.remote_use_entity(Hand::Main) } fn use_block(&mut self) -> bool { self.0.remote_use_block(Hand::Main) diff --git a/crates/horizon-client/src/game/remote_mob_use.rs b/crates/horizon-client/src/game/remote_mob_use.rs new file mode 100644 index 000000000..9575cf925 --- /dev/null +++ b/crates/horizon-client/src/game/remote_mob_use.rs @@ -0,0 +1,91 @@ +//! A server's client right-clicking a mob: vanilla's client runs +//! `Player.interactOn` on its own level (`MultiPlayerGameMode.interact`) to +//! learn whether the click ends on the mob or goes on to the held item +//! (`Minecraft.startUseItem` then sends UseItem). The server does the real +//! interaction; this is what the client's copy of the mob answers. +use super::Game; +use horizon_client::{ + first_person::Hand, + mobs::{Species, equine, llama}, +}; + +impl Game<'_> { + /// Whether mob `i` takes a right click with `hand`'s item on this + /// client (`Mob.interact`'s result consumes the action). + pub(super) fn remote_mob_takes(&self, i: usize, hand: Hand) -> bool { + let Some(m) = self.mobs.get(i).filter(|m| m.alive()) else { + return false; + }; + let stack = match hand { + Hand::Main => self.stack_in(self.selected), + Hand::Off => self.offhand.as_ref(), + }; + let item = stack.map_or("", |s| &*s.item); + let baby = m.is_baby(); + // Mob.checkAndHandleImportantInteractions: a lead, a named name tag, + // a spawn egg of the mob's own kind. + if item == "minecraft:lead" + || item == "minecraft:name_tag" && stack.is_some_and(|s| s.custom_name().is_some()) + || item.strip_suffix("_spawn_egg") == Some(m.kind.id.as_str()) + { + return true; + } + // Animal.mobInteract: its food is CONSUME on a client. + if m.kind.flags.animal && m.kind.food.iter().any(|f| f.as_str() == item) { + return true; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + match m.species() { + // Villager / WanderingTrader.mobInteract: trading, or a baby's head shake. + Species::Villager | Species::WanderingTrader => item != "minecraft:villager_spawn_egg", + // AbstractHorse, Camel: ridden (or their inventory opened); a baby only eats. + s if equine::is_equine(s) + || llama::is_llama(s) + || matches!(s, Species::Camel | Species::CamelHusk) => + { + !baby + } + // Pig / Strider.mobInteract: a saddled one is ridden. + Species::Pig | Species::Strider => m.extra.saddled && !sneaking, + // HappyGhast.mobInteract: a harnessed adult is ridden. + Species::HappyGhast => !baby && m.extra.head.is_some(), + // TamableAnimal (wolf, cat, parrot) on a client: CONSUME once tame. + Species::Wolf | Species::Cat | Species::Parrot => m.extra.tame, + // Allay.mobInteract: gives an item or takes it back. + Species::Allay => !item.is_empty() || m.extra.main_hand.is_some(), + Species::Cow | Species::Goat => item == "minecraft:bucket" && !baby, + Species::Mooshroom => { + matches!( + item, + "minecraft:bucket" | "minecraft:bowl" | "minecraft:shears" + ) && !baby + } + Species::Sheep => item == "minecraft:shears" || item.ends_with("_dye"), + // Bucketable.bucketMobPickup. + Species::Cod + | Species::Salmon + | Species::TropicalFish + | Species::Pufferfish + | Species::Axolotl + | Species::Tadpole => item == "minecraft:water_bucket", + Species::Armadillo => item == "minecraft:brush", + // ZombieVillager.mobInteract: CONSUME for a golden apple. + Species::ZombieVillager => item == "minecraft:golden_apple", + // Creeper.mobInteract: CREEPER_IGNITERS. + Species::Creeper => { + matches!(item, "minecraft:flint_and_steel" | "minecraft:fire_charge") + } + // PiglinAi.mobInteract: an adult admires what it loves. + Species::Piglin => { + !baby + && self + .res + .items() + .item_tags + .get("minecraft:piglin_loved") + .is_some_and(|tag| tag.contains(item)) + } + _ => false, + } + } +} diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index c4e8052c0..b7484a7be 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -460,12 +460,16 @@ impl ServerEntity { // A value back at its default is left out of the state, but the // clients still hold the old one: Entity's shared flags and pose go // back to 0 (a player standing up again, a mob no longer on fire), - // a sleeper's bed to none. + // a sleeper's bed to none, an item frame's item to empty and its + // rotation to 0 (ItemFrame.DATA_ITEM and DATA_ROTATION). + let frame = e.kind.ends_with("item_frame"); for (index, kind, _) in &self.meta { let default = match (*index, *kind) { (0, serializer::BYTE) => Value::Byte(0), (6, serializer::POSE) => Value::Id(0), (14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None), + (9, serializer::ITEM_STACK) if frame => Value::Item(None), + (10, serializer::INT) if frame => Value::Int(0), _ => continue, }; if !e.meta.iter().any(|m| m.0 == *index) { @@ -1040,6 +1044,39 @@ mod tests { assert!(changes(&mut s, &e).is_empty()); } + #[test] + fn an_emptied_item_frame_sends_its_empty_item_and_rotation() { + let mut e = state(0.0); + e.kind = "minecraft:item_frame".into(); + let mut s = added(&e); + changes(&mut s, &e); + e.meta = vec![ + ( + 9, + serializer::ITEM_STACK, + Value::Item(Some(Stack::new(5, 1))), + ), + (10, serializer::INT, Value::Int(3)), + ]; + changes(&mut s, &e); + // Punched out (ItemFrame.removeFramedMap, setItem(EMPTY)): both back to the default. + e.meta.clear(); + let data = changes(&mut s, &e) + .into_iter() + .find_map(|p| match p { + play::Clientbound::SetEntityData(d) => Some(d), + _ => None, + }) + .expect("the empty frame is sent"); + assert_eq!( + data.values, + vec![ + (9, serializer::ITEM_STACK, Value::Item(None)), + (10, serializer::INT, Value::Int(0)), + ] + ); + } + #[test] fn metadata_and_equipment_send_only_the_changes() { let mut e = state(0.0); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 79250678e..d659c3811 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -130,6 +130,11 @@ address. The script then checks, from both sides, what a guest's game used to ge it (#1222). - frames: the host and the guest each put a diamond in an item frame and turn it, and put a helmet on an armor stand and take it back (#1222). +- hands: the host and the guest each, at a cow that cares for none of it: draw a bow and shoot, and + let go of a golden apple at once without eating it (the click goes on to the item); + milk the cow with a bucket in the off hand and feed it wheat from the off hand; and + punch the diamond out of an item frame, which then shows empty on both sides (#1350, + #1355, #1362). - mounts: the host and the guest each open a tamed horse's, donkey's and llama's inventory (shift + right click, then the inventory key while riding), put on a saddle, armour or a carpet and fill the chest by shift-clicking. @@ -179,7 +184,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'levels'] class Game: @@ -2809,6 +2814,83 @@ def check_frames(host, guest, out): return result +def check_hands(host, guest, out): + """#1350, #1355, #1362: right clicks a cow passes go on to the item, the off hand gets its + turn on the cow, and a frame punched empty is empty for everyone.""" + result = {} + spots = apart(host, guest) + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + player('command', command='gamemode survival') + player('command', command='clear @s') + player('command', command='effect clear @s') + # A cow two blocks ahead that stays put, and a framed diamond on a wall behind the player. + player('command', command=f'summon minecraft:cow {x + 0.5} {y} {z + 3.5} {{NoAI:1b}}') + player('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z - 2} minecraft:stone') + player('command', command=f'summon minecraft:item_frame {x + 0.5} {y + 1.5} {z - 0.97} ' + f'{{block_pos:[I;{x},{y + 1},{z - 1}],Facing:3b,Item:{{id:"minecraft:diamond",count:1}}}}') + player.wait(20) + counts = lambda: player('inventory')['counts'] + aim_cow = lambda: player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 0.8:.2f}', f'{z + 3.5:.2f}') + try: + player('command', command='give @s minecraft:bow') + player('command', command='give @s minecraft:arrow 6') + player.wait(5) + player.raw('select', 'minecraft:bow') + aim_cow() + assert player('looking_at')['kind'] == 'entity', f'the {label} does not aim at the cow' + player.raw('mouse', 'right', 'down') + player.wait(25) + drawn = player('state')['using'] + player.raw('mouse', 'right', 'up') + player.wait(20) + assert drawn, f'the {label}\'s bow is not drawn at the cow' + assert counts().get('minecraft:arrow') == 5, f'the {label} shot no arrow: {counts()}' + player('command', command='clear @s') + player('command', command='give @s minecraft:golden_apple') + player.wait(5) + player.raw('select', 'minecraft:golden_apple') + aim_cow() + player.raw('mouse', 'right', 'down') + player.wait(5) + player.raw('mouse', 'right', 'up') + player.wait(40) + assert counts().get('minecraft:golden_apple') == 1, f'the {label} ate the apple let go of: {counts()}' + # The main hand empty, a bucket and then wheat in the off hand. + player('command', command='clear @s') + player('command', command='item replace entity @s weapon.offhand with minecraft:bucket') + player.wait(5) + aim_cow() + player.raw('mouse', 'right', 'click') + player.wait(15) + offhand = player('inventory')['offhand'] + assert offhand and offhand['item'] == 'minecraft:milk_bucket', f'the {label}\'s off hand holds {offhand}' + player('command', command='item replace entity @s weapon.offhand with minecraft:wheat 3') + player.wait(5) + aim_cow() + player.raw('mouse', 'right', 'click') + player.wait(15) + offhand = player('inventory')['offhand'] + assert offhand and offhand['count'] == 2, f'the {label}\'s cow ate no off hand wheat: {offhand}' + # The framed diamond, punched out. + frame = [o for o in player('status')['objects'] if o['kind'].endswith('item_frame') + and o['position'] == [x, y + 1, z - 1]] + assert frame and frame[0]['item'] == 'minecraft:diamond', f'the {label} sees the frame as {frame}' + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z - 0.95:.2f}') + player.raw('mouse', 'left', 'click') + player.wait(20) + for side, game in ((label, player), ('other side', other)): + seen = [o for o in game('status')['objects'] if o['kind'].endswith('item_frame') + and o['position'] == [x, y + 1, z - 1]] + assert seen and seen[0].get('item') is None, f'the {side} sees the punched frame as {seen}' + result[label] = {'bow': 'shot', 'apple': 'kept', 'off hand': 'milked, fed', 'frame': 'emptied'} + finally: + player('command', command=f'kill @e[type=!minecraft:player,x={x - 3},y={y - 1},z={z - 3},dx=6,dy=4,dz=8]') + player('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z - 2} minecraft:air') + player('command', command='clear @s') + return result + + # Animals a player rides: (kind, summon NBT, what readies it, what is held to ride, the test # while riding). `move` walks forward, `jump` charges the horse's jump bar, `rise` holds jump on # a happy ghast, `sit` only rides (a llama goes where it likes). @@ -3369,7 +3451,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, 'levels': check_levels} From c7abc8c718d6fd78bc5ed8f7766a3ab8491cb846 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:39:46 +0200 Subject: [PATCH 02/19] Chat: styled server components, click and hover events, legacy codes, message order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A connection's chat keeps the server's component: SystemChat goes through the same translation and styles as the action bar, and player and disguised chat are decorated from their chat type's translation, parameters and style (ChatType.Bound.decorate), so colours, bold, hex colours, and the client's language are kept (#1372, #1389). - Components parse `click_event` (suggest_command, copy_to_clipboard; never open_file from a server) and `hover_event` show_text (#1377), and the chat screen draws the hovered part's tooltip (#1381). - `§` codes in chat colour the text with Chat Colors on and are stripped with it off (ComponentRenderUtils.wrapComponents) (#1379). - A command's operator broadcast skips the player whose command it was on the integrated server too (#1373), and /give fires InventoryChangeTrigger before its message, whose announcement is sent first (#1375). - The control socket's `messages` gives the chat lines as components; lan_e2e `styles` checks a styled tellraw, the advancement order and the missing echo for the host and the guest. Co-Authored-By: Claude Opus 5.5 --- .../examples/hud_fixture/kinds.rs | 1 + crates/horizon-client/src/chat.rs | 42 +++++++- crates/horizon-client/src/chat_tests.rs | 42 ++++++++ crates/horizon-client/src/component.rs | 19 ++++ crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/chat.rs | 35 ++++++- crates/horizon-client/src/game/commands.rs | 5 + crates/horizon-client/src/game/integrated.rs | 4 +- crates/horizon-client/src/game/lan_actions.rs | 11 ++- crates/horizon-client/src/game/remote.rs | 95 +++++++++---------- crates/horizon-client/src/settings.rs | 1 + crates/horizon-client/src/text.rs | 28 ++++++ tools/lan_e2e.py | 74 ++++++++++++++- 13 files changed, 297 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index 850db5218..d1450f2e1 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -306,6 +306,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { height_focused: option("chatHeightFocused"), height_unfocused: option("chatHeightUnfocused"), line_spacing: option("chatLineSpacing"), + colors: c["chatColors"].as_bool().unwrap_or(true), }; for m in c["messages"].as_array().into_iter().flatten() { // GuiMessageTag indicator colours: systemSinglePlayer and chatError. diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 7c51a40f1..273b87153 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -29,10 +29,14 @@ pub struct ChatOptions { pub height_focused: f64, pub height_unfocused: f64, pub line_spacing: f64, + /// Chat Colors (`chatColors`): legacy `§` codes format the text, or are + /// left out. + pub colors: bool, } impl Default for ChatOptions { fn default() -> Self { Self { + colors: true, opacity: 1.0, background_opacity: 0.5, scale: 1.0, @@ -136,7 +140,8 @@ impl Chat { } fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { let width = self.max_width(); - for line in atlas.font.wrap_components(&message.content, width) { + let content = self.displayed(&message.content); + for line in atlas.font.wrap_components(&content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); @@ -152,6 +157,16 @@ impl Chat { } self.lines.truncate(100); } + /// What a message's lines wrap (ComponentRenderUtils.wrapComponents): + /// without Chat Colors its `§` codes are stripped (stripColor); with + /// them the font draws them as formatting. + fn displayed(&self, content: &Text) -> Text { + if self.options.colors { + content.resolve_legacy() + } else { + content.strip_legacy() + } + } /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). pub fn rescale(&mut self, atlas: &HudAtlas) { self.scroll = 0; @@ -308,6 +323,21 @@ impl Chat { x: f64, y: f64, ) -> Option { + self.style_at(font, height, x, y)?.click + } + /// The hover text under a GUI-space cursor while chat is focused + /// (ChatScreen.render's `renderComponentHoverEffect`). + pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option { + self.style_at(font, height, x, y)?.hover.map(|h| *h) + } + /// ChatComponent.getClickedComponentStyleAt. + fn style_at( + &self, + font: &crate::font::Font, + height: i32, + x: f64, + y: f64, + ) -> Option { let scale = self.options.scale as f32; let mut x = x / f64::from(scale) - 4.0; let bottom = hud_layout::floor((height - 40) as f32 / scale); @@ -324,7 +354,7 @@ impl Chat { for (c, style) in content.chars() { x -= f64::from(font.advance(c, style)); if x < 0.0 { - return style.click.clone(); + return Some(style.clone()); } } None @@ -337,6 +367,14 @@ impl Chat { .map(|m| m.content.plain()) .collect() } + /// The newest messages as components, styles included (control socket). + pub fn recent_components(&self, n: usize) -> Vec { + self.messages + .iter() + .take(n) + .map(|m| m.content.component()) + .collect() + } } /// `CommandSuggestions.SuggestionsList`. diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index e1bf2feda..d0ce3f458 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -285,3 +285,45 @@ fn ask_server_nodes_wait_for_the_servers_completions() { screen.type_text(&m, &c, "/bossbar get pt"); assert_eq!(screen.take_request(), None); } + +#[test] +fn legacy_codes_colour_the_line_or_vanish_without_chat_colours() { + let mut chat = Chat::default(); + let red = Text::literal("\u{a7}cRED"); + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color == Some(0xFF5555))); + chat.options.colors = false; + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color.is_none())); + // A lone section sign or an unknown code stays as written. + assert_eq!( + chat.displayed(&Text::literal("a\u{a7}zb")).plain(), + "a\u{a7}zb" + ); +} + +#[test] +fn a_server_component_keeps_its_click_and_hover_events() { + let font = font(); + let json = serde_json::json!({ + "text": "CLICK", "color": "green", "bold": true, + "click_event": {"action": "suggest_command", "command": "/say clicked"}, + "hover_event": {"action": "show_text", "value": {"text": "Tip", "color": "aqua"}}, + }); + let line = crate::component::to_text(&json, &mut |s| Text::literal(s)); + let mut chat = Chat::default(); + add(&mut chat, &font, line); + let x = 4.0 + f64::from(font.width("CL")); + let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else { + panic!("the line must suggest its command"); + }; + assert_eq!(command, "/say clicked"); + let hover = chat.hover_at(&font, 360, x, 315.0).expect("a hover text"); + assert_eq!(hover.plain(), "Tip"); + assert_eq!(hover.spans[0].style.color, Some(text::AQUA)); + // Past the (bold, so wider) text, nothing. + let past = 4.0 + f64::from(font.width("CLICK")) + 20.0; + assert!(chat.hover_at(&font, 360, past, 315.0).is_none()); +} diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 68460054b..fced49898 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -168,6 +168,25 @@ fn object_style(o: &serde_json::Map) -> Style { style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); style.font = o.get("font").and_then(crate::text::font_id); + // ClickEvent.CODEC: the actions a chat line acts on here. A component + // from a server never opens a file. + if let Some(e) = o.get("click_event").and_then(Value::as_object) { + let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); + style.click = match e.get("action").and_then(Value::as_str) { + Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), + Some("copy_to_clipboard") => { + text("value").map(crate::text::ClickEvent::CopyToClipboard) + } + _ => None, + }; + } + // HoverEvent.ShowText. + if let Some(e) = o.get("hover_event").and_then(Value::as_object) + && e.get("action").and_then(Value::as_str) == Some("show_text") + && let Some(value) = e.get("value") + { + style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s)))); + } style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 3d957efe0..3ee069778 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -673,6 +673,8 @@ impl Game<'_> { json!({ "chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)), "order": "newest first", + // The chat lines as drawn: colours, click and hover events. + "styled": self.ui.chat.recent_components(n), "title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(), "subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(), "actionbar": (titles.overlay_time > 0).then(|| titles.overlay.as_ref().map(|t| t.plain())).flatten(), diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..be73607ae 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -450,7 +450,7 @@ impl Game<'_> { // Connected to a server (single player's own included), the chat on // screen is the connection's: the game's own messages join it. if self.remote.is_some() { - self.chat_line(text.plain()); + self.chat_line(text); return; } let focused = self.screen == Screen::Chat; @@ -681,6 +681,16 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); + // The hovered message part's tooltip, one row per line of its text. + if let Some(hover) = self.ui.chat.hover_at( + &self.gui.atlas.font, + batch.height as i32, + f64::from(self.cursor.0), + f64::from(self.cursor.1), + ) { + let lines = hover_rows(&hover); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } } /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. @@ -953,3 +963,26 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: fn owner_permission(allow_commands: bool) -> u8 { if allow_commands { 4 } else { 0 } } + +/// A hover text's rows for the tooltip: split at line breaks, each in the +/// colour of its first styled character (white without one). +fn hover_rows(hover: &horizon_client::text::Text) -> Vec<(String, u32)> { + let mut rows = vec![(String::new(), None)]; + for (c, style) in hover.resolve_legacy().chars() { + if c == '\n' { + rows.push((String::new(), None)); + continue; + } + let row = rows.last_mut().expect("one row"); + if row.0.is_empty() { + row.1 = style.color; + } + row.0.push(c); + } + rows.into_iter() + .map(|(text, color)| { + let [_, r, g, b] = color.unwrap_or(0xFF_FFFF).to_be_bytes(); + (text, horizon_client::hud::rgba(r, g, b, 255)) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index c6877a839..0a51f6119 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1039,6 +1039,11 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); } } + // containerMenu.broadcastChanges: InventoryChangeTrigger + // (and its announcement) comes before the command's message. + if g.player.is_some() { + g.check_inventory_trigger(); + } }); } // The prototype stack: one item. diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ef5775174..bdb6fe892 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -465,8 +465,10 @@ impl Game<'_> { host = self.lan.take().expect("a command puts the hub back"); self.leave_guest(&mut host, swap); host.hub.sync_all_effects(); - // A teleport into another level happens before its feedback is sent. + // A teleport into another level happens before its feedback is + // sent, and what the command earned is announced before it too. self.run_level_teleports(&mut host); + self.announce_guest_advancements(&mut host); for line in lines { out.push(line.plain()); host.hub.send_to( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 67764c090..a34eb417c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -85,7 +85,7 @@ pub(super) struct GuestCommand { conn: u32, command: String, permission: u8, - /// An integrated server's: no admin feedback or level teleports (yet). + /// An integrated server's: no level teleports (yet). integrated: bool, } @@ -1382,6 +1382,8 @@ impl Game<'_> { // A teleport into another level happens before its feedback is sent. self.run_level_teleports(&mut host); } + // What the command earned is announced before its feedback. + self.announce_guest_advancements(&mut host); for line in lines { host.hub.send_to( c.conn, @@ -1391,9 +1393,8 @@ impl Game<'_> { }), ); } - if !c.integrated { - self.send_admin_feedback(&mut host, Some(c.conn)); - } + // The other operators hear of it; never the player whose command it was. + self.send_admin_feedback(&mut host, Some(c.conn)); self.lan = Some(host); } } @@ -1745,7 +1746,7 @@ impl Game<'_> { /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). - fn announce_guest_advancements(&mut self, host: &mut LanHost) { + pub(super) fn announce_guest_advancements(&mut self, host: &mut LanHost) { for text in std::mem::take(&mut self.adv.announced) { host.hub .system_message(horizon_client::lan::data::component_nbt(&text.component())); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f969cbeb9..8dff41c6f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -38,7 +38,7 @@ use horizon_protocol::{ play::{self, Clientbound as C, Serverbound as S}, }, registry::{Builtin, DimensionType, Dynamic, ceil_log2}, - text::{Language, format_java, plain}, + text::{Language, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; use std::{ @@ -675,11 +675,14 @@ impl Game<'_> { } Some(stack) } - pub(super) fn chat_line(&mut self, text: String) { + /// A line in the connection's chat, with its styles, click and hover + /// events (ChatComponent.addMessage). + pub(super) fn chat_line(&mut self, content: horizon_client::text::Text) { + let text = content.plain(); log::info!("[chat] {text}"); self.ui.chat.add( &self.gui.atlas, - horizon_client::text::Text::literal(text.clone()), + content, None, self.ticks, self.screen == Screen::Chat, @@ -2256,42 +2259,27 @@ impl Game<'_> { } } C::SystemChat(p) => { - let text = plain( - &p.content, - &self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(), - ); - // ChatListener.handleOverlay. + // The component as sent, translated in the client's own + // language. ChatListener.handleOverlay for the action bar. + let text = remote_text(&p.content); if p.overlay { - self.titles.set_overlay(remote_text(&p.content), false); + self.titles.set_overlay(text, false); } else { self.chat_line(text); } } C::PlayerChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); + use horizon_client::scoreboard::tag_to_json; let content = p .unsigned_content .as_ref() - .map_or_else(|| p.content.clone(), |t| plain(t, &lang)); - let line = self.format_chat(&p.chat_type, &content); + .map_or_else(|| serde_json::Value::from(p.content.as_str()), tag_to_json); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::DisguisedChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - let content = plain(&p.message, &lang); - let line = self.format_chat(&p.chat_type, &content); + let content = horizon_client::scoreboard::tag_to_json(&p.message); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::PlayerInfoUpdate(p) => { @@ -2723,11 +2711,17 @@ impl Game<'_> { true } /// ChatType decoration: `chat.translation_key` with sender/content parameters. - fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { + /// ChatType.Bound.decorate: the chat type's translation, with the + /// sender, the target and the message as its parameters, in its style. + fn format_chat( + &self, + bound: &play::ChatTypeBound, + content: serde_json::Value, + ) -> horizon_client::text::Text { + use horizon_client::scoreboard::{comp_text, tag_to_json}; let Some(r) = self.remote.as_ref() else { - return content.to_owned(); + return comp_text(&content); }; - let sender = plain(&bound.name, &r.lang); let decoration = r .registries .data("minecraft:chat_type", bound.chat_type) @@ -2736,30 +2730,31 @@ impl Game<'_> { Some(Tag::String(s)) => s.to_string_lossy(), _ => "chat.type.text".into(), }; - let params: Vec = match decoration.and_then(|d| d.get("parameters")) { + let parameter = |name: &str| match name { + "sender" => tag_to_json(&bound.name), + "target" => bound + .target + .as_ref() + .map_or_else(|| serde_json::Value::from(""), tag_to_json), + _ => content.clone(), + }; + let with: Vec = match decoration.and_then(|d| d.get("parameters")) { Some(Tag::List(list)) => list .iter() .map(|p| match p { - Tag::String(s) => match s.to_string_lossy().as_str() { - "sender" => sender.clone(), - "target" => bound - .target - .as_ref() - .map(|t| plain(t, &r.lang)) - .unwrap_or_default(), - _ => content.to_owned(), - }, - _ => String::new(), + Tag::String(s) => parameter(&s.to_string_lossy()), + _ => serde_json::Value::from(""), }) .collect(), - _ => vec![sender, content.to_owned()], + _ => vec![parameter("sender"), parameter("content")], }; - let pattern = r - .lang - .get(&key) - .cloned() - .unwrap_or_else(|| "<%s> %s".into()); - format_java(&pattern, ¶ms) + let mut component = match decoration.and_then(|d| d.get("style")) { + Some(style @ Tag::Compound(_)) => tag_to_json(style), + _ => serde_json::json!({}), + }; + component["translate"] = key.into(); + component["with"] = with.into(); + comp_text(&component) } fn remote_item_data(&mut self, id: i32, stack: &Option) { let Some(stack) = self.to_stack(stack) else { @@ -4530,7 +4525,9 @@ impl Game<'_> { self.send(S::ContainerClose(play::ContainerClose { container: p.container, })); - self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); + self.chat_line(horizon_client::text::Text::literal(format!( + "(Horizon cannot show {menu} screens yet)" + ))); return; } }; diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 1fadacf57..20f3ade23 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -593,6 +593,7 @@ impl Settings { height_focused: f64::from(self.chat_height_focused), height_unfocused: f64::from(self.chat_height_unfocused), line_spacing: f64::from(self.chat_line_spacing), + colors: self.chat_colors, } } } diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 9f39155d1..41a21d285 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -428,6 +428,34 @@ impl Text { } out } + /// The text without its legacy `§` codes (ChatFormatting.stripFormatting: + /// a `§` and a code character, `0`-`9`, `a`-`f`, `k`-`o` or `r`). + pub fn strip_legacy(&self) -> Text { + if !self.spans.iter().any(|s| s.text.contains('§')) { + return self.clone(); + } + let code = + |c: char| matches!(c.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r'); + let mut out = Text::default(); + for span in &self.spans { + let mut text = String::with_capacity(span.text.len()); + let mut chars = span.text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '§' && chars.peek().is_some_and(|&n| code(n)) { + chars.next(); + } else { + text.push(c); + } + } + if !text.is_empty() { + out.spans.push(Span { + text, + style: span.style.clone(), + }); + } + } + out + } /// Characters with their effective styles. pub fn chars(&self) -> impl Iterator { self.spans diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 79250678e..00727d61d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -61,6 +61,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - feedback: the guest's command feedback names the guest and shows the numbers; - chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the server thread the host window's too; +- styles: a styled tellraw reaches the host and the guest (each its own) with its colour, bold, click and hover + events; each player's /give tells them of the Diamonds! advancement before the give's + own message, and never echoes their command back to them as `[Name: ...]`; - effects: a beacon's power reaches every player in range, the host and the guest; - distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) @@ -179,7 +182,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] class Game: @@ -1310,8 +1313,8 @@ def check_loom(host, guest, out): def own_reply(event): """A chat event that answers the guest's own command. On the server thread the guest also gets - its own command's `[Guest: ...]` operator broadcast, a moment later, which an answer to the next - command must not be taken for.""" + its own command's `[Guest: ...]` operator broadcast before #1373, a moment later, which an answer + to the next command must not be taken for.""" return event.get('event') == 'chat' and not event.get('text', '').startswith(f'[{GUEST_NAME}: ') @@ -1876,6 +1879,69 @@ def check_chat(host, guest, out): return seen +def styled_parts(component): + """Every component in a chat line's tree (the line, its `extra` and `with` parts).""" + if isinstance(component, dict): + yield component + for key in ('extra', 'with'): + for part in component.get(key) or []: + yield from styled_parts(part) + elif isinstance(component, list): + for part in component: + yield from styled_parts(part) + + +def check_styles(host, guest, out): + # ChatComponent keeps what the server sent: the style, the click and the hover event. + stamp = f'STYLE {int(time.time())}' + line = {'text': stamp, 'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': {'action': 'show_text', 'value': 'Tip'}} + seen = {} + for g in (host, guest): + # Each to itself: tellraw reaches only the player whose command it is here. + since = g.raw('events')['last'] + g('command', command='tellraw @s ' + json.dumps(line)) + g.raw('wait-for', 'chat', stamp, '--timeout', 10, '--since', since) + part = next((p for c in g.raw('messages', 10)['styled'] for p in styled_parts(c) + if stamp in str(p.get('text', ''))), None) or {} + seen[g.name] = {k: part.get(k) for k in ('color', 'bold', 'click_event', 'hover_event')} + hover = seen[g.name]['hover_event'] or {} + seen[g.name]['hover_event'] = [hover.get('action'), 'Tip' in str(hover.get('value'))] + # InventoryChangeTrigger fires inside /give, before its message; the operator echo + # (broadcastToAdmins) skips the player whose command it was. + order = {} + for g in (host, guest): + for command in ('advancement revoke @s everything', 'clear @s'): + g('command', command=command) + g.wait(5) + since = g.raw('events')['last'] + g('command', command='give @s minecraft:diamond') + g.raw('wait-for', 'chat', 'Diamonds!', '--timeout', 10, '--since', since) + g.wait(20) + chat = g.raw('messages', 8)['chat'] + name = GUEST_NAME if g is guest else host.player + gave = next((i for i, l in enumerate(chat) if l.startswith('Gave 1 [Diamond]')), None) + made = next((i for i, l in enumerate(chat) if '[Diamonds!]' in l), None) + echo = [l for l in chat if l.startswith(f'[{name}: ')] + # Newest first: the give's message is newer than the advancement's. + order[g.name] = {'gave': gave, 'advancement': made, 'echo': echo} + guest.raw('key', 't', 'tap') + guest.wait(5) + guest.shot(out, 'styles') + guest.raw('key', 'esc', 'tap') + want = {'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': ['show_text', True]} + for name, got in seen.items(): + assert got == want, f'{name} styled line: {got}' + for name, o in order.items(): + assert o['gave'] is not None and o['advancement'] is not None, f'{name} chat: {o}' + assert o['gave'] < o['advancement'], f'{name}: the give came before the advancement: {o}' + assert not o['echo'], f'{name} heard its own command: {o}' + return {'styles': seen, 'order': order} + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -3348,7 +3414,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn, - 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, + 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, 'styles': check_styles, 'machines': check_machines, 'brewing': check_brewing, 'loom': check_loom, From b15e5e893ed96733ebcdb1e8a1e7e41969251f59 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:58:39 +0200 Subject: [PATCH 03/19] Code mods are the client's mods feature: tests and probes skip wasmtime horizon-mods' runtime is no longer a default feature, and its sandbox test requires runtime and pack instead of a dev-dependency on itself (that dev-dependency turned the runtime on in every workspace build with examples, the parity probe build included). The client gets a mods feature that turns the runtime on; without it game/mods.rs keeps content mods and logs why code mods don't start, and every hook does nothing. Release builds (client and server) pass the feature, CI's clippy and tests pass it (and pack, for the sandbox test), and pr_ready does where horizon-mods is checked. horizon_mods::find moves to manifest.rs: content mods use it without the runtime. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 8 ++- Cargo.lock | 1 - crates/horizon-client/Cargo.toml | 6 +- crates/horizon-client/src/game/chat.rs | 4 +- crates/horizon-client/src/game/extras.rs | 2 +- crates/horizon-client/src/game/mods.rs | 83 ++++++++++++++++++++---- crates/horizon-mods/Cargo.toml | 11 ++-- crates/horizon-mods/src/lib.rs | 2 +- crates/horizon-mods/src/manifest.rs | 20 +++++- crates/horizon-mods/src/runtime.rs | 17 ----- docs/mods.md | 12 +++- tests/test_pr_ready.py | 5 +- tools/pr_ready.py | 14 +++- 14 files changed, 138 insertions(+), 52 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8966854c2..32ad79497 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,12 +61,13 @@ jobs: if: steps.rust.outputs.required != 'false' run: | cargo +stable fmt --all -- --check - cargo +stable clippy --workspace --all-targets -- -D warnings + # With the game's code mods (on in every release build, off by default). + cargo +stable clippy --workspace --all-targets --features horizon-client/mods -- -D warnings # The server build (released as horizon-engine): the game without sound or controllers. cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' - run: cargo +stable test --workspace + run: cargo +stable test --workspace --features horizon-client/mods,horizon-mods/pack parity: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository uses: ./.github/workflows/parity.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b19ba9ce5..bb3be5480 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -128,7 +128,8 @@ jobs: if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev - name: Build the client, horizon-ctl, horizon-prepare and horizon-server - run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server + # `horizon-client/mods`: every released game runs code mods (the feature is off in dev builds). + run: cargo build --release --locked --features horizon-client/mods -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server - name: Every program the release folder takes was built run: | for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do @@ -250,8 +251,9 @@ jobs: run: | set -euo pipefail # After the client is packaged: target/release/horizon-client is rebuilt without the audio and - # controllers features, so it needs neither libasound nor libudev (minimal server images lack them). - cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client + # controllers features, so it needs neither libasound nor libudev (minimal server images lack them), + # and with code mods like the client. + cargo build --release --locked -p horizon-client --no-default-features --features mods --bin horizon-client cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" folder="dist/${{ matrix.server_dir }}" python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" diff --git a/Cargo.lock b/Cargo.lock index 2f832e248..1a1b288c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1493,7 +1493,6 @@ dependencies = [ name = "horizon-mods" version = "0.1.0" dependencies = [ - "horizon-mods", "log", "serde", "serde_json", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index cd5d86fe7..94ba949d0 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -18,7 +18,8 @@ horizon-protocol = { path = "../horizon-protocol" } horizon-server-files = { path = "../horizon-server-files" } horizon-friends = { path = "../horizon-friends" } # Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). -horizon-mods = { path = "../horizon-mods" } +# Their runtime is the `mods` feature. +horizon-mods = { path = "../horizon-mods", default-features = false } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" @@ -78,6 +79,9 @@ default = ["audio", "controllers"] audio = ["dep:cpal"] # Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad. controllers = ["dep:gilrs", "dep:horizon-dualsense"] +# Runs code mods (wasmtime and cranelift: a quarter of a clean build). On in every release build +# (release.yml); the tests and probes don't need it. Content mods load without it. +mods = ["horizon-mods/runtime"] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..3d10d57b6 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -454,7 +454,7 @@ impl Game<'_> { return; } let focused = self.screen == Screen::Chat; - let heard = self.mods.mods.is_running().then(|| text.plain()); + let heard = self.mods.running().then(|| text.plain()); self.ui.chat.add( &self.gui.atlas, text, @@ -583,7 +583,7 @@ impl Game<'_> { &[Text::literal(PLAYER_NAME), Text::literal(message)], ); let focused = self.screen == Screen::Chat; - let heard = self.mods.mods.is_running().then(|| line.plain()); + let heard = self.mods.running().then(|| line.plain()); self.ui .chat .add(&self.gui.atlas, line, None, self.ticks, focused); diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index c16c54447..cee173fda 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -237,7 +237,7 @@ impl Game<'_> { /// the caller). The top left corner gives way to the debug screen. pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { let e = &self.settings.extras; - let mod_panels = self.mods.mods.panels().next().is_some(); + let mod_panels = self.mods.has_panels(); if !e.fps && !e.keystrokes && !e.minimap && !mod_panels { return; } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 01787ec02..572f9fe2b 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -2,43 +2,76 @@ //! their tick, frame, chat and command hooks, their HUD panels and what //! they print. With no mod on, `horizon_mods::Mods` holds no engine and //! every hook here returns after one check. -use super::{Game, Screen}; +//! +//! Code mods run only in builds with the `mods` feature (release builds): +//! without it the game links no wasmtime, and every hook does nothing. +//! Content mods (`content_root`) load in every build. +use super::Game; use horizon_client::{ command::{Dispatcher, vanilla}, - extras::Corner, - extras_hud::{self, Corners}, + extras_hud::Corners, hud::HudBatch, - mod_list::{self, Installed}, - text::{self, Text}, + mod_list, }; -use horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}; -use std::{ - path::PathBuf, - time::{Duration, Instant}, +use std::{path::PathBuf, time::Duration}; +#[cfg(feature = "mods")] +use { + super::Screen, + horizon_client::{ + extras::Corner, + extras_hud, + mod_list::Installed, + text::{self, Text}, + }, + horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}, + std::time::Instant, }; #[derive(Default)] pub(super) struct ModsState { - pub(super) mods: Mods, + #[cfg(feature = "mods")] + mods: Mods, /// `--dev-mod PATH`: always on, reloaded when rebuilt. pub(super) dev: Vec, /// When dev mods were last checked for a rebuild. + #[cfg(feature = "mods")] checked: Option, /// The chat's command tree while a running mod owns commands. + #[cfg(feature = "mods")] tree: Option, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. pub(super) fn dispatcher(&self) -> &Dispatcher { - self.tree - .as_ref() - .unwrap_or_else(|| vanilla::game_dispatcher()) + #[cfg(feature = "mods")] + if let Some(tree) = &self.tree { + return tree; + } + vanilla::game_dispatcher() + } + /// Whether a mod runs: the chat keeps its lines for them. + pub(super) fn running(&self) -> bool { + #[cfg(feature = "mods")] + if self.mods.is_running() { + return true; + } + false + } + /// Whether a mod draws a HUD panel. + pub(super) fn has_panels(&self) -> bool { + #[cfg(feature = "mods")] + if self.mods.panels().next().is_some() { + return true; + } + false } } /// How often dev mods are checked for a rebuild. +#[cfg(feature = "mods")] const RELOAD_CHECK: Duration = Duration::from_secs(1); /// A vanilla command name: mods may not take it. +#[cfg(feature = "mods")] fn vanilla_command(name: &str) -> bool { let d = vanilla::game_dispatcher(); d.nodes[0] @@ -112,6 +145,30 @@ pub(super) fn content_root( } } +/// A build without the `mods` feature: no mod runs. +#[cfg(not(feature = "mods"))] +impl Game<'_> { + /// Says why the installed and dev mods don't run. + pub(super) fn start_mods(&mut self) { + let dir = Self::options_path().with_file_name(mod_list::DIR); + let found = horizon_mods::find(&dir).len() + self.mods.dev.len(); + if found > 0 { + log::warn!( + "Horizon: {found} mod(s) not started: this build has no mod runtime (build with --features mods)" + ); + } + } + pub(super) fn sync_mods(&mut self) {} + pub(super) fn tick_mods(&mut self) {} + pub(super) fn mods_frame(&mut self, _elapsed: Duration) {} + pub(super) fn mod_command(&mut self, _command: &str) -> bool { + false + } + pub(super) fn mods_chat(&mut self, _line: &str) {} + pub(super) fn draw_mod_panels(&self, _batch: &mut HudBatch, _corners: &mut Corners) {} +} + +#[cfg(feature = "mods")] impl Game<'_> { /// Reads `horizon-mods/` and the dev mods, and starts the ones turned on. pub(super) fn start_mods(&mut self) { diff --git a/crates/horizon-mods/Cargo.toml b/crates/horizon-mods/Cargo.toml index 8db24ac35..013d38a99 100644 --- a/crates/horizon-mods/Cargo.toml +++ b/crates/horizon-mods/Cargo.toml @@ -19,13 +19,16 @@ wit-component = { version = "0.239", optional = true } wit-parser = { version = "0.239", optional = true } [features] -default = ["runtime"] -# Loads and runs mods; without it only manifests and packaging (cargo horizon-mod). +# Loads and runs mods (the game's `mods` feature); without it only manifests, +# content and packaging. Off by default so builds that don't run mods (the +# game's tests and probes) skip wasmtime and cranelift. runtime = ["dep:wasmtime"] pack = ["dep:wit-component", "dep:wit-parser"] -[dev-dependencies] -horizon-mods = { path = ".", features = ["pack"] } +# Runs real mods: `cargo test -p horizon-mods --features runtime,pack`. +[[test]] +name = "sandbox" +required-features = ["runtime", "pack"] [lints] workspace = true diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index ec9ebe67d..5060bf747 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -11,6 +11,6 @@ pub mod manifest; mod runtime; pub use content::Content; -pub use manifest::{Capability, Manifest, Package, Side}; +pub use manifest::{Capability, Manifest, Package, Side, find}; #[cfg(feature = "runtime")] pub use runtime::*; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 44cdbd418..a71210883 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -1,6 +1,10 @@ //! `horizon-mod.toml`, a mod's manifest, and the `.hmod` file around it. use serde::Deserialize; -use std::{fmt, io::Read, path::Path}; +use std::{ + fmt, + io::Read, + path::{Path, PathBuf}, +}; /// The manifest's file name, beside `mod.wasm`. pub const MANIFEST: &str = "horizon-mod.toml"; @@ -282,6 +286,20 @@ impl Package { } } +/// The `.hmod` files and mod folders in `dir`, by name. +pub fn find(dir: &Path) -> Vec { + let Ok(read) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec = read + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "hmod") || p.join(MANIFEST).is_file()) + .collect(); + found.sort(); + found +} + /// Turns a `wasm32-unknown-unknown` cdylib built with the SDK into the /// component the game loads. #[cfg(feature = "pack")] diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 975cd1461..9dd2eb54e 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -131,23 +131,6 @@ pub struct Mods { out: Vec, } -/// The `.hmod` files and mod folders in `dir`, by name. -pub fn find(dir: &Path) -> Vec { - let Ok(read) = std::fs::read_dir(dir) else { - return Vec::new(); - }; - let mut found: Vec = read - .flatten() - .map(|e| e.path()) - .filter(|p| { - p.extension().is_some_and(|e| e == "hmod") - || p.join(crate::manifest::MANIFEST).is_file() - }) - .collect(); - found.sort(); - found -} - impl Mods { /// Reads every mod at `paths` and starts those `enabled` says are on. /// A command that `reserved` (vanilla's commands) or an earlier mod diff --git a/docs/mods.md b/docs/mods.md index 4b356d336..4521d312d 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -137,10 +137,17 @@ proposal, no profiling. Its cranelift backend generates native code for x86-64 and ARM64 on Windows, macOS and Linux, which is why one `.hmod` serves them all. +The game links it only with its `mods` feature: every release build turns it +on (`release.yml`), and a build from source needs +`cargo build --release -p horizon-client --features mods` to run code mods. +Without it (the tests and probes) wasmtime and cranelift aren't built, a +quarter of a clean build; content mods still load, and the game logs why the +code mods don't start. + ### Performance Measured on the Mac mini (M4 Pro), release build, `cargo test -p -horizon-mods --release --test sandbox -- --ignored --nocapture`: +horizon-mods --features runtime,pack --release --test sandbox -- --ignored --nocapture`: | | per call | |---|---| @@ -180,7 +187,8 @@ chat (`Mod Test Guest stopped: it took too long (an endless loop?)`), marks it on the Mods page and carries on; the other mods keep running. Host functions clip what a mod hands back (chat lines per call, HUD lines and lengths). Tests: `crates/horizon-mods/tests/sandbox.rs` (an endless loop, a panic and a 1 GiB -allocation, next to a healthy mod). +allocation, next to a healthy mod; `cargo test -p horizon-mods --features +runtime,pack`). ## Playing with mods diff --git a/tests/test_pr_ready.py b/tests/test_pr_ready.py index c10e7b2ac..8268d5ab7 100644 --- a/tests/test_pr_ready.py +++ b/tests/test_pr_ready.py @@ -9,6 +9,7 @@ PACKAGES = {"horizon-core": "crates/horizon-core", "horizon-client": "crates/hor "horizon-theme": "crates/horizon-theme", "xtask": "xtask"} LIBRARIES = set(PACKAGES) - {"xtask"} DEPENDENCIES = {"horizon-client": {"horizon-core"}} +MODS = " --features horizon-mods/runtime,horizon-mods/pack,horizon-client/mods" def args(host="local", quick=False): @@ -58,9 +59,9 @@ class PrReadyTests(unittest.TestCase): steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES) by_name = {step.name: step for step in steps} self.assertEqual(by_name["clippy"].command, - "cargo clippy --workspace --all-targets --locked -- -D warnings") + "cargo clippy --workspace" + MODS + " --all-targets --locked -- -D warnings") self.assertEqual(by_name["tests: workspace"].command, - "cargo test --locked --workspace --tests") + "cargo test --locked --workspace" + MODS + " --tests") self.assertEqual(by_name["doc tests"].command, "cargo test --locked --workspace --doc") def test_non_rust_changes_skip_workspace_checks(self): diff --git a/tools/pr_ready.py b/tools/pr_ready.py index e3e317ef8..a944e2116 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -274,6 +274,16 @@ def parity_summary(output): return text +def mod_features(crates): + """Code mods are off by default (docs/mods.md): on wherever horizon-mods is checked, as in CI.""" + if crates is not None and "horizon-mods" not in crates: + return "" + features = ["horizon-mods/runtime", "horizon-mods/pack"] + if crates is None or "horizon-client" in crates: + features.append("horizon-client/mods") + return f" --features {','.join(features)}" + + def plan(args, base, changed, crates_of, libraries, dependencies): """The checks for these changed files, in the order they run.""" rust = any(workspace_rust(path) for path in changed) @@ -297,10 +307,10 @@ def plan(args, base, changed, crates_of, libraries, dependencies): Step("Python tests", "python3 -m unittest discover -s tests", where="here", skip=None if python else "no Python change", summary=unittest_passed), Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust), - Step("clippy", f"cargo clippy {clippy_selection} --all-targets --locked -- -D warnings", + Step("clippy", f"cargo clippy {clippy_selection}{mod_features(clippy_crates)} --all-targets --locked -- -D warnings", skip=None if rust else no_rust), Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""), - f"cargo test --locked {selection} --tests", + f"cargo test --locked {selection}{mod_features(crates)} --tests", skip=test_skip, summary=tests_passed), Step("doc tests", f"cargo test --locked {doc_selection} --doc", skip=test_skip or (None if doc_crates else "no library touched"), summary=tests_passed), From ac811d470883ef930f1041ccd34f8b857c8841d5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:37:34 +0200 Subject: [PATCH 04/19] One side_mask for the two datafixes, one test MobType for two mobs.rs tests datafix: LeavesFix's getSideMask is ChunkPalettedStorageFix's, line for line; chunk_leaves uses chunk_flatten's. mobs.rs: push_tests takes sensor_scan_tests' 46-line cow MobType instead of its own copy. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs.rs | 51 +------------------ .../src/datafix/chunk_flatten.rs | 4 +- .../horizon-world/src/datafix/chunk_leaves.rs | 27 +--------- 3 files changed, 5 insertions(+), 77 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 76f622d9c..a61ea2a11 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -2277,7 +2277,7 @@ mod sensor_scan_tests { use horizon_core::geometry::Vec3; use serde_json::json; - fn kind() -> Arc { + pub(super) fn kind() -> Arc { Arc::new(MobType { id: "minecraft:cow".into(), species: Species::Cow, @@ -2481,56 +2481,9 @@ mod sensor_scan_tests { } #[cfg(test)] mod push_tests { + use super::sensor_scan_tests::kind; use super::*; use horizon_core::geometry::Vec3; - use serde_json::json; - - fn kind() -> Arc { - Arc::new(MobType { - id: "minecraft:cow".into(), - species: Species::Cow, - width: 0.9, - height: 1.4, - eye_height: 1.3, - category: "creature".into(), - max_health: 10.0, - speed: 0.2, - flying_speed: 0.4, - attack_damage: 0.0, - attack_knockback: 0.0, - follow_range: 16.0, - step_height: 0.6, - armor: 0.0, - armor_toughness: 0.0, - knockback_resistance: 0.0, - jump_strength: 0.42, - attributes: Arc::default(), - gravity: 0.08, - safe_fall_distance: 3.0, - fall_damage_multiplier: 1.0, - water_efficiency: 0.0, - water_slowdown: 0.8, - air_speed: 0.02, - baby_scale: 0.5, - head_rot_speed: 10.0, - max_head_x_rot: 40.0, - max_head_y_rot: 75.0, - ambient_interval: 120, - flags: Flags { - animal: true, - ..Default::default() - }, - model: Arc::new(Part::parse("root", &json!({}))), - layers: HashMap::new(), - texture: String::new(), - brain: Brain::Passive, - anim: Anim::Rabbit, - sounds: [""; 3], - step_sound: None, - food: Arc::default(), - tempt: Arc::default(), - }) - } /// The pending pushes as one list, scanned for each mob, as before. fn take_old(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { diff --git a/crates/horizon-world/src/datafix/chunk_flatten.rs b/crates/horizon-world/src/datafix/chunk_flatten.rs index e3c116d93..671fc9f73 100644 --- a/crates/horizon-world/src/datafix/chunk_flatten.rs +++ b/crates/horizon-world/src/datafix/chunk_flatten.rs @@ -266,8 +266,8 @@ fn is_virtual(block: usize) -> bool { VIRTUAL.contains(&block) } -/// `getSideMask`. -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { +/// `getSideMask` (LeavesFix has the same copy). +pub(super) fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { let mut s = 0; if north { if east { diff --git a/crates/horizon-world/src/datafix/chunk_leaves.rs b/crates/horizon-world/src/datafix/chunk_leaves.rs index 9cd2fd3d9..07d59cbdf 100644 --- a/crates/horizon-world/src/datafix/chunk_leaves.rs +++ b/crates/horizon-world/src/datafix/chunk_leaves.rs @@ -6,6 +6,7 @@ //! emulated here (`IntOpenHashSet` and the key order of an `Int2ObjectOpenHashMap`). use std::collections::{HashMap, HashSet}; +use super::chunk_flatten::side_mask; use super::dynamic::{as_int, as_long_stream, as_str, ceillog2, set}; use crate::nbt::Tag; @@ -355,32 +356,6 @@ fn get_index(x: i32, y: i32, z: i32) -> i32 { y << 8 | z << 4 | x } -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { - let mut s = 0; - if north { - if east { - s |= 2; - } else if west { - s |= 128; - } else { - s |= 1; - } - } else if south { - if west { - s |= 32; - } else if east { - s |= 8; - } else { - s |= 16; - } - } else if east { - s |= 4; - } else if west { - s |= 64; - } - s -} - /// `LeavesFix` over a chunk (`{Level: ...}`). pub(super) fn leaves_fix(chunk: &mut Tag) { let Some(level) = chunk.get_mut("Level") else { From a79077b30e1fb734615b83c762f6a13defda3b28 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:42:20 +0200 Subject: [PATCH 05/19] Mob brains share Timed, compute_path, reached and the living-entity scan Behavior's Timed was copied into the villager, animal, monster and warden brains: one copy now, in brain.rs, drawing its duration in Java's int arithmetic (two copies used plain +, the same for every duration they have). MoveToTargetSink's tryComputePath and reachedTarget, copied into the villager, monster and warden brains on the same WalkTarget and Slot types, are the villager brain's, given each brain's CANT_REACH_WALK_TARGET_SINCE. NearestLivingEntitySensor's scan, copied into the villager, animal and monster brains, is brain.rs's living_near. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/mobs/animal_brain.rs | 89 ++++--------- crates/horizon-client/src/mobs/brain.rs | 58 ++++++++- .../horizon-client/src/mobs/monster_brain.rs | 116 +++-------------- .../horizon-client/src/mobs/villager_brain.rs | 118 +++++++----------- .../horizon-client/src/mobs/warden_brain.rs | 108 +++------------- 5 files changed, 156 insertions(+), 333 deletions(-) diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 331870b4a..bd0eb9c90 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -9,7 +9,12 @@ //! own random drives positions, sounds and jumps. `RunOne` shuffles with a //! random of its own, seeded with the brain's `shuffle_seed` when it is //! built. -use super::{Mob, MobEvent, MobWorld, Species, Who, path::Path, sniffer}; +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, + path::Path, + sniffer, +}; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource}, @@ -603,22 +608,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -794,37 +784,6 @@ fn followable_friendly(s: Species) -> bool { // ---- Behaviours ------------------------------------------------------------ -/// `Behavior`'s running state and end time. -#[derive(Clone, Copy, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } - fn timed_out(&self, now: i64) -> bool { - now > self.end - } -} - /// `RunOne`: shuffles its children by weight and starts the first that can. #[derive(Clone, Debug)] struct Gate { @@ -1076,7 +1035,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).walk_target.clear(); mem(m).look_target.clear(); m.add_effect("minecraft:regeneration", 200, 0); @@ -1086,7 +1045,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AnimalPanic { t, .. } => { @@ -1094,7 +1053,7 @@ impl B { if !(mm.hurt_by.get() == Some(&true) || mm.is_panicking.present()) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1123,7 +1082,7 @@ impl B { let reached = reached(m, cx.w, &walk); if !reached && compute_path(m, cx, &walk, path, speed) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); return true; @@ -1139,21 +1098,21 @@ impl B { if !mem(m).temptation_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownGaze(t) => { if !mem(m).gaze_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownTransport(t) => { if !mem(m).transport_items_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::Transport(x) => x.try_start(m, cx), @@ -1171,7 +1130,7 @@ impl B { let Some(partner) = breed_partner(m, cx.w) else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1200,7 +1159,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1210,14 +1169,14 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::FeelingHappy(t) => { if !mem(m).sniffer_happy.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::FEELING_HAPPY); true } @@ -1233,7 +1192,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::DIGGING); true } @@ -1246,7 +1205,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::RISING); true } @@ -1261,7 +1220,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SEARCHING); true } @@ -1278,7 +1237,7 @@ impl B { if is_tempted(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SCENTING); true } @@ -1293,12 +1252,12 @@ impl B { if m.is_baby() || !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SNIFFING); true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AxolotlAction { .. } diff --git a/crates/horizon-client/src/mobs/brain.rs b/crates/horizon-client/src/mobs/brain.rs index da83ee93d..67bb6a2a6 100644 --- a/crates/horizon-client/src/mobs/brain.rs +++ b/crates/horizon-client/src/mobs/brain.rs @@ -1,8 +1,11 @@ //! Pieces of vanilla's `Brain` that species implemented as brains share: //! memories that expire, behaviour durations, walk targets and //! `MoveToTargetSink`. -use super::{Mob, goals::Cx}; -use horizon_core::random::RandomSource; +use super::{Mob, MobWorld, Who, goals::Cx}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; /// A memory with an expiry (`Brain.setMemoryWithExpiry`): present for the /// tick it was set and `ttl` more ticks. `Ttl::default()` is absent. @@ -25,6 +28,57 @@ impl Ttl { } } } +/// `Behavior`'s bookkeeping in the brains ported behaviour for behaviour +/// (villager, animal, monster, warden): running, and until when. +#[derive(Clone, Copy, Debug)] +pub struct Timed { + pub running: bool, + pub end: i64, + pub min: i32, + pub max: i32, +} +impl Timed { + pub fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw from the level random, in Java's + /// int arithmetic (made even when it cannot vary). + pub fn begin(&mut self, lr: &mut LegacyRandom, now: i64) { + self.running = true; + let bound = self.max.wrapping_add(1).wrapping_sub(self.min); + let d = self.min.wrapping_add(lr.next_int_bound(bound).unwrap_or(0)); + self.end = now + i64::from(d); + } + /// `Behavior.timedOut`. + pub fn timed_out(&self, now: i64) -> bool { + now > self.end + } +} +/// `NearestLivingEntitySensor`'s scan: the living entities (the player +/// among them) whose boxes meet the follow range around `m`, nearest first. +pub fn living_near(m: &Mob, w: &MobWorld) -> Vec { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others_near(area) { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + found.into_iter().map(|(w, _)| w).collect() +} /// A random duration in `min..=max` (`Behavior`'s end time). pub fn duration(m: &mut Mob, min: i32, max: i32) -> i32 { if max <= min { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index eeb2c42f2..be310cdd7 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -11,9 +11,10 @@ //! seeded when the brain is built. use super::{ Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, goals::Cx, path::Path, - villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget}, + villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget, compute_path, reached}, }; use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{ @@ -129,6 +130,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> &Memories { &brain(m).expect("brain").mem } @@ -296,22 +301,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -460,31 +450,6 @@ fn sense_breeze_attack(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw from the level random. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `StartAttacking`'s target finders. #[derive(Clone, Copy, Debug)] enum Finder { @@ -611,14 +576,14 @@ impl B { if *creaking && !super::creaking::can_move(m) || !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -640,9 +605,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -723,7 +688,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::RandomStroll(running, speed) => { @@ -852,7 +817,7 @@ impl B { mem(m).breeze_shoot.clear(); return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start super::breeze::set_pose(m, super::breeze::SHOOTING); mem(m).breeze_shoot_charging.set_ttl((), 15); @@ -871,7 +836,7 @@ impl B { if !long_jump_can_run(m, cx) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if !mem(m).breeze_jump_inhaling.present() { mem(m).breeze_jump_inhaling.set_ttl((), 10); @@ -909,7 +874,7 @@ impl B { if !stuck { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).breeze_shoot.set_ttl((), 60); true } @@ -928,7 +893,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); slide_start(m, cx); true } @@ -993,7 +958,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1126,53 +1091,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target.block(w).is_some_and(|p| { - let h = block_of(m.position); - (p[0] - h[0]).abs() + (p[1] - h[1]).abs() + (p[2] - h[2]).abs() <= walk.close - }) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - *path = m.create_path_to(cx.w, block_of(Vec3::new(step[0], step[1], step[2])), 0); - return path.is_some(); - } - } - false -} /// `BehaviorUtils.isWithinAttackRange(body, target, 1)` for a mob without a /// ranged weapon: `Mob.isWithinMeleeAttackRange`. fn within_attack_range(m: &Mob, w: &MobWorld, target: Who) -> bool { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index e02cfa176..cdfd49e39 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -11,6 +11,7 @@ //! `Brain::shuffle_seed` when the brain is built. use super::{ Mob, MobEvent, MobWorld, Seen, Species, Who, + brain::{Timed, living_near}, path::{Path, PathNode}, }; use horizon_core::{ @@ -341,6 +342,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -565,22 +570,7 @@ const FOLLOW_RANGE: f64 = 16.0; /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -791,34 +781,6 @@ fn sense_golem(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } -} - /// The POI types villagers use. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Poi { @@ -1498,18 +1460,18 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::PanicTrigger(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); // VillagerPanicTrigger.start if panic_condition(m) { if !brain_mut(m).is_active(Act::Panic) { @@ -1542,9 +1504,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1561,7 +1523,7 @@ impl B { if !follow_trading_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); follow_trading_player(m); true } @@ -1573,7 +1535,7 @@ impl B { if !matches!(a, Act::Idle | Act::Work | Act::Play) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::JumpOnBed { @@ -1590,7 +1552,7 @@ impl B { if mm.walk_target.present() || !m.is_baby() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *bed = Some(nearest); *time_left = 100; *jumps = 3 + cx.lr.next_int_bound(4).unwrap_or(0); @@ -1599,7 +1561,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GiveGiftToHero { @@ -1618,7 +1580,7 @@ impl B { *until_next -= 1; return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *given = false; *started = now; let mm = mem(m); @@ -1630,7 +1592,7 @@ impl B { if !mem(m).interaction_target.present() || !show_trades_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if let Some(target) = mem(m).interaction_target.value() { mem(m).look_target.set(Tracker::Entity(target, true)); @@ -1646,7 +1608,7 @@ impl B { if !villager_target_valid(m, cx.w, Mem::InteractionTarget) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).interaction_target.value().unwrap(); lock_gaze(m, target, cx); true @@ -1659,7 +1621,7 @@ impl B { if !breeding_possible(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).breed_target.value().unwrap(); lock_gaze(m, target, cx); *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); @@ -1680,7 +1642,7 @@ impl B { if !closer_to_center(site, m.position, 1.73) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start let mm = mem(m); mm.last_worked_at_poi.set(now); @@ -1709,7 +1671,7 @@ impl B { *valid = farmland_around(m, cx.w); *target = pick_farmland(valid, cx); let Some(p) = *target else { return false }; - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { let mm = mem(m); mm.look_target.set(Tracker::Block(p)); @@ -2288,7 +2250,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { if super::villager::start_sleeping(m, home, w) { mem(m).last_slept.set(now); @@ -2609,7 +2571,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LocateHidingPlace { @@ -2769,7 +2731,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -3141,33 +3103,37 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { } } /// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { +pub(super) fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { walk.target .block(w) .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) } -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( +/// `MoveToTargetSink.tryComputePath`, for the brains on these memories +/// (villager, monster, warden): `cant_reach` is the brain's +/// `CANT_REACH_WALK_TARGET_SINCE`. +pub(super) fn compute_path( m: &mut Mob, - cx: &mut Bx, + w: &MobWorld, + now: i64, walk: &WalkTarget, path: &mut Option, speed: &mut f32, + cant_reach: fn(&mut Mob) -> &mut Slot, ) -> bool { - let Some(target) = walk.target.block(cx.w) else { + let Some(target) = walk.target.block(w) else { return false; }; - *path = m.create_path_to(cx.w, target, 0); + *path = m.create_path_to(w, target, 0); *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); + if reached(m, w, walk) { + cant_reach(m).clear(); } else { let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); + let since = cant_reach(m); if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); + since.clear(); + } else if !since.present() { + since.set(now); } if path.is_some() { return true; @@ -3178,14 +3144,14 @@ fn compute_path( f64::from(target[2]) + 0.5, ]; if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + m.default_random_pos_towards(w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) { let p = [ step[0].floor() as i32, step[1].floor() as i32, step[2].floor() as i32, ]; - *path = m.create_path_to(cx.w, p, 0); + *path = m.create_path_to(w, p, 0); return path.is_some(); } } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 518347e77..8caafefc9 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -14,9 +14,10 @@ //! shuffle seed. use super::{ Mob, MobEvent, MobWorld, Who, + brain::Timed, goals::Cx, path::Path, - villager_brain::{Slot, Tracker, Visible, WalkTarget}, + villager_brain::{Slot, Tracker, Visible, WalkTarget, compute_path, reached}, warden::{self, Pose}, }; use horizon_core::{ @@ -145,31 +146,6 @@ impl Memories { } } -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw (made even when it cannot vary). - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `RunOne`'s `ShufflingList` over a stroll (weight 2) and `DoNothing` (1). #[derive(Clone, Debug)] struct Gate { @@ -383,6 +359,10 @@ fn brain(m: &Mob) -> Option<&Brain> { pub(super) fn mem(m: &mut Mob) -> &mut Memories { &mut m.extra.warden.as_mut().expect("a warden").brain.mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -558,9 +538,6 @@ fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) - fn block_of(p: Vec3) -> [i32; 3] { [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] } -fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { - (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() -} fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum() } @@ -607,57 +584,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target - .block(w) - .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - let p = [ - step[0].floor() as i32, - step[1].floor() as i32, - step[2].floor() as i32, - ]; - *path = m.create_path_to(cx.w, p, 0); - return path.is_some(); - } - } - false -} fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { match (a, b) { (None, None) => true, @@ -710,7 +636,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::SetWardenLookTarget(r) => one(r, || { @@ -732,7 +658,7 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -755,9 +681,9 @@ impl B { return false; }; let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -775,7 +701,7 @@ impl B { if !mm.is_emerging.present() || mm.walk_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); warden::set_pose(m, Pose::Emerging); sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); true @@ -791,7 +717,7 @@ impl B { if !(m.on_ground || liquid) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if m.on_ground { warden::set_pose(m, Pose::Digging); sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); @@ -872,7 +798,7 @@ impl B { true }), B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GoToDisturbance(r) => one(r, || { @@ -907,7 +833,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); true } @@ -919,7 +845,7 @@ impl B { let Some(target) = mm.roar_target.value() else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.roar_sound_delay.set_ttl((), ROAR_SOUND_DELAY); mm.walk_target.clear(); @@ -1004,7 +930,7 @@ impl B { if !close { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.attack_cooling_down .set_ttl(true, i64::from(SONIC_DURATION)); @@ -1092,7 +1018,7 @@ impl B { && let Some(walk) = mem(m).walk_target.value() && let Some(now_target) = walk.target.block(cx.w) && dist_sqr(now_target, last) > 4 - && compute_path(m, cx, &walk, path, speed) + && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); From de358cd72127156cd9c27ecd662ee73b86adb113 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:39:09 +0200 Subject: [PATCH 06/19] A server's players drop their inventory on death unless keep_inventory is on The guest death path (LAN guests, dedicated players and single player's window on its server thread) gave the experience reward but never ran Player.dropEquipment, so a player died with keep_inventory off and kept everything (#1284). Both paths now share one drop_inventory: destroyVanishingCursedItems, then Inventory.dropAll from the eyes less 0.3. ServerPlayer.die skips the loot for spectators only; the window's own death skipped it in creative too, which vanilla doesn't. lan_e2e keepinv: host and guest, keep_inventory off and on, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 38 ++++++++----- crates/horizon-client/src/game/lan_actions.rs | 6 ++ tools/lan_e2e.py | 56 ++++++++++++++++++- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 95aca4ecb..486f042a9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1989,6 +1989,28 @@ impl Game<'_> { particle.scale(0.6); self.particles.push(particle); } + /// `Player.dropEquipment` for the player who died: unless keep_inventory + /// is on, `destroyVanishingCursedItems`, then `Inventory.dropAll` from + /// `at` (the eyes less 0.3): slots 0..36, armor feet to head (36..39), + /// the off hand (40), each thrown in a random direction. + fn drop_inventory(&mut self, at: [f64; 3]) { + if self.ui.rules.bool("keep_inventory") { + return; + } + let mut stacks: Vec = + self.inventory.iter_mut().filter_map(Option::take).collect(); + stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take)); + stacks.extend(self.offhand.take()); + stacks.retain(|s| s.enchantment_level("minecraft:vanishing_curse") == 0); + self.apply_equipment(); + for stack in stacks { + let r = &mut self.world.random; + let strength = f64::from(r.next_float()) * 0.5; + let angle = f64::from(r.next_float()) * std::f64::consts::TAU; + let v = [-angle.sin() * strength, 0.2, angle.cos() * strength]; + self.spawn_item(stack, at, v, 40); + } + } fn spawn_item( &mut self, stack: ItemStack, @@ -4278,20 +4300,8 @@ impl Game<'_> { .experience .death_reward(self.ui.rules.bool("keep_inventory") || self.spectator()); self.spawn_orbs(feet, reward); - if !self.creative && !self.ui.rules.bool("keep_inventory") { - // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). - let mut stacks: Vec = - self.inventory.iter_mut().filter_map(Option::take).collect(); - stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take)); - stacks.extend(self.offhand.take()); - self.apply_equipment(); - for stack in stacks { - let r = &mut self.world.random; - let strength = f64::from(r.next_float()) * 0.5; - let angle = f64::from(r.next_float()) * std::f64::consts::TAU; - let v = [-angle.sin() * strength, 0.2, angle.cos() * strength]; - self.spawn_item(stack, at, v, 40); - } + if !self.spectator() { + self.drop_inventory(at); } self.audio .play("minecraft:entity.player.death", Some(at), 1.0, 1.0); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index d3cfd3766..8e07dfb05 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1717,6 +1717,9 @@ impl Game<'_> { } .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); let (name, uuid) = (g.name.clone(), g.uuid); + // ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3. + let drops = (g.game_mode != SPECTATOR) + .then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]); let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); let message = match cause { // ServerPlayer.die: the death message, to everyone unless @@ -1750,6 +1753,9 @@ impl Game<'_> { ); // LivingEntity.die: the death animation, the dying player included. host.hub.entity_event(id, 3, at); + if let Some(eyes) = drops { + self.as_guest(host, conn, |game| game.drop_inventory(eyes)); + } self.spawn_orbs(at, reward); } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 12be44657..479feaf4e 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -176,6 +176,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - totem: the host and the guest each take a lethal hit holding a totem of undying in the off hand, then the main hand: the server uses it up and keeps them alive at 1 health with its effects, and each side hears the totem once (entity event 35) (#1292). +- keepinv: the host and the guest each die holding diamonds and wearing a helmet: with keep_inventory + off both drop where they died and the player respawns without them; with it on nothing + drops and the player keeps them (#1284). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4068,8 +4071,57 @@ def check_totem(host, guest, out): return seen -CHECKS += ['totem'] -CHECK_FNS.update(totem=check_totem) +def check_keep_inventory(host, guest, out): + """ServerPlayer.die's dropAllDeathLoot for each player (Player.dropEquipment): with keep_inventory + off, the diamonds and the helmet a player dies with lie where it died and it respawns with + neither; with it on, nothing drops and it respawns with both (#1284).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + host('command', command=f'setworldspawn {hx} {hy} {hz}') + host('command', command='gamerule respawn_radius 0') + try: + for keep in ('false', 'true'): + host('command', command=f'gamerule keep_inventory {keep}') + for game, dz in ((host, -3), (guest, 3)): + # 14 blocks from the world spawn: nothing dropped is picked up on respawning. + x, z = hx + 14, hz + dz + host('command', command=f'fill {x - 2} {hy - 1} {z - 1} {x + 2} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 1} {x + 2} {hy + 2} {z + 1} minecraft:air') + host('command', command='kill @e[type=minecraft:item]') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='give @s minecraft:diamond 7') + game('command', command='item replace entity @s armor.head with minecraft:iron_helmet') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5}') + game.wait(20) + game('command', command='kill @s') + game.wait(30) + dropped = sorted((e['item']['item'], e['item']['count']) + for e in game.raw('entities', 8, 'minecraft:item')['entities']) + game.shot(out, f'keepinv-{keep}') + respawn_when_ready(game) + game.wait(40) + back_to_game(game) + seen[f'{game.name}-keep-{keep}'] = { + 'dropped': dropped, + 'kept': {item: server_count(game, item) for item in ('diamond', 'iron_helmet')}} + finally: + host('command', command='gamerule keep_inventory false') + host('command', command='gamerule respawn_radius 10') + host('command', command='kill @e[type=minecraft:item]') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for case, s in seen.items(): + want = ({'dropped': [], 'kept': {'diamond': 7, 'iron_helmet': 1}} if case.endswith('true') else + {'dropped': [('minecraft:diamond', 7), ('minecraft:iron_helmet', 1)], + 'kept': {'diamond': 0, 'iron_helmet': 0}}) + assert s == want, f'{case}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory) if __name__ == '__main__': From 52d8ed6721be9b7db334284f14b0fb271ba13f86 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:57:34 +0200 Subject: [PATCH 07/19] Signs open their editor on a server's players, and what they write reaches the server A sign a server's player placed (a LAN guest, or single player's window on its server thread) opened no editor: its turn's editor was dropped with the rest of the guest's screens (#1380). The server now does as ServerPlayer.openTextEdit: the block, then ClientboundOpenSignEditorPacket, and the player may write on that sign. The client opens its editor on the sign it has and sends ServerboundSignUpdatePacket when it closes; the server takes the lines (formatting codes stripped) unless the sign is waxed, the player was not the one allowed or went out of reach, and sends the sign to everyone. The window's own sign now reaches its guests too (sendBlockUpdated, not only a save). horizon-protocol: OpenSignEditor and SignUpdate, with SignTextSlot as a VarInt and the lines as a fixed list of four (26.3's stream codecs). horizon-ctl: type and key reach an open sign editor; block shows a sign's lines. lan_e2e signs: host and guest each place, write and see, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/agent.rs | 6 ++ crates/horizon-client/src/game/control.rs | 13 ++- crates/horizon-client/src/game/lan_actions.rs | 9 +- .../horizon-client/src/game/lan_stations.rs | 27 +++--- crates/horizon-client/src/game/remote.rs | 1 + crates/horizon-client/src/game/sign_edit.rs | 90 ++++++++++++++++++- crates/horizon-protocol/src/packets/play.rs | 63 +++++++++++++ tools/lan_e2e.py | 44 ++++++++- 8 files changed, 234 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 868a8d046..0c1954891 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -335,6 +335,12 @@ impl Game<'_> { Some(Ticker::Shulker { .. }) => v["lid"] = json!(self.block_anim(pos, 1.0).shulker.0), _ => {} } + // The lines of a sign, as this client has them. + if let Some(horizon_client::containers::BlockEntity::Sign(sign)) = + self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + { + v["sign"] = json!({ "front": sign.front.lines, "back": sign.back.lines }); + } v } pub(super) fn stack_value(&self, s: &ItemStack) -> Value { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9132c7723..271f9b116 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -232,6 +232,13 @@ impl Game<'_> { "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; self.require_world()?; + // The sign editor takes raw presses (Enter, arrows, Backspace, Escape). + if self.sign_edit.is_some() { + if arg(2)? != "up" { + self.sign_input(Some(key), None); + } + return ok(); + } // A held edit modifier (`key super down`) and A/C/V/X: the // open book's Select All, Copy, Paste or Cut. if self.book.is_some() && arg(2)? != "up" { @@ -524,6 +531,10 @@ impl Game<'_> { self.book_type(text); return ok(); } + if self.sign_edit.is_some() { + self.sign_input(None, Some(text)); + return ok(); + } match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), @@ -549,7 +560,7 @@ impl Game<'_> { } _ => { return Err( - "type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(), + "type needs the chat screen (key t tap), a sign or book, the language search, the creative search, the anvil or World Options".into(), ); } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8e07dfb05..ac557e2dd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -30,6 +30,8 @@ use winit::keyboard::KeyCode; /// Per-guest state of the gameplay code that lives outside `Guest`. #[derive(Default)] pub(super) struct GuestPlay { + /// The sign this guest may write on (`SignBlockEntity.playerWhoMayEdit`). + pub(super) sign_editing: Option<[i32; 3]>, mining: Option, destroy_delay: u32, using: Option<(usize, u32)>, @@ -510,7 +512,8 @@ impl Game<'_> { std::mem::swap(&mut self.mount, &mut play.mount); self.container = container; self.screen = screen; - self.sign_edit = host_sign; + // A sign the guest's placement opened (SignBlock.openTextEdit). + let guest_sign = std::mem::replace(&mut self.sign_edit, host_sign); // A lectern the guest's use opened (LecternBlock.openScreen). let guest_lectern = match std::mem::replace(&mut self.book, host_book) { Some(super::books::BookScreen::View { @@ -649,6 +652,9 @@ impl Game<'_> { if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if let Some(edit) = guest_sign { + self.lan_open_sign_editor(host, conn, edit); + } if let Some(key) = guest_lectern { self.lan_open_lectern(host, conn, key); } @@ -1025,6 +1031,7 @@ impl Game<'_> { self.lan_station_button(host, conn, p.container, p.button); } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::SignUpdate(p) => self.lan_sign_update(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); } diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 25921f936..2efcfc705 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -588,17 +588,7 @@ impl Game<'_> { let [x, y, z] = gs.pos; let name = &self.res.facts().get(self.world.block(x, y, z)).name; let block = StationKind::from_block(name) == Some(gs.kind); - let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; - // The block interaction range (4.5, creative 5) and the buffer. - let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; - let near = (0..3) - .map(|k| { - let lo = f64::from(gs.pos[k]); - (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) - }) - .sum::() - < reach * reach; - if !(block && near) { + if !(block && within_reach(g, gs.pos)) { let window = gs.window; self.lan_station_closed(host, conn, Some(window)); host.hub.send_to( @@ -670,3 +660,18 @@ pub(super) fn station_inputs(gs: &GuestStation) -> Vec { .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) .unwrap_or_default() } + +/// `Player.isWithinBlockInteractionRange(pos, 4)`: the guest's eyes within +/// its block interaction range (4.5, creative 5) and a 4-block buffer of the +/// block's box. +pub(super) fn within_reach(g: &horizon_client::lan::guest::Guest, pos: [i32; 3]) -> bool { + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 156fbe13b..67e30d7c1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2573,6 +2573,7 @@ impl Game<'_> { self.drop_remote_chunks_out_of_range(); } C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag), + C::OpenSignEditor(p) => self.remote_open_sign_editor(p), // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. C::SetDefaultSpawnPosition(p) => { let [x, y, z] = p.pos.pos; diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index c679bad69..5a26e3e69 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -1,12 +1,13 @@ //! The sign editing screen (`SignEditScreen` / `HangingSignEditScreen`): //! opened when a sign is placed, four lines limited to the sign's line //! width, Up/Down/Enter move between lines, Escape or Done closes. -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, signs::wood_type, }; +use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use std::time::Instant; use winit::{ event::{ElementState, KeyEvent}, @@ -33,14 +34,95 @@ impl Game<'_> { self.right = false; self.capture(false); } + /// `AbstractSignEditScreen.removed`: a server's client sends what it + /// wrote (ServerboundSignUpdatePacket); the window's own world keeps it + /// and sends it to its guests (`sendBlockUpdated`). pub(super) fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { - self.world - .modified - .insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); + if self.remote.is_some() { + if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) { + let side = if edit.front { &sign.front } else { &sign.back }; + self.send(S::SignUpdate(play::SignUpdate { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + lines: side.lines.clone(), + front: edit.front, + })); + } + } else { + self.mark_block_entity_updated(edit.pos); + } } self.capture(true); } + /// `ServerPlayer.openTextEdit` for the guest whose action opened a sign: + /// the block, then the editor, on its client, and the guest may write on it. + pub(super) fn lan_open_sign_editor(&mut self, host: &mut LanHost, conn: u32, edit: SignEditor) { + let pos = [edit.pos.0, edit.pos.1, edit.pos.2]; + let state = self.world.block(pos[0], pos[1], pos[2]).0 as i32; + host.hub + .send_to(conn, &C::BlockUpdate(play::BlockUpdate { pos, state })); + host.hub.send_to( + conn, + &C::OpenSignEditor(play::OpenSignEditor { + pos, + front: edit.front, + }), + ); + host.play.entry(conn).or_default().sign_editing = Some(pos); + } + /// `ServerGamePacketListenerImpl.handleSignUpdate`: the lines, formatting + /// codes stripped, go on the sign the guest may write on unless it is + /// waxed (`SignBlockEntity.updateSignText`); a guest gone out of reach + /// may no longer write (`playerIsTooFarAwayToEdit`). + pub(super) fn lan_sign_update(&mut self, host: &mut LanHost, conn: u32, p: play::SignUpdate) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let near = super::lan_stations::within_reach(g, p.pos); + let Some(play) = host.play.get_mut(&conn) else { + return; + }; + if !near { + play.sign_editing = None; + } + if play.sign_editing != Some(p.pos) { + log::warn!("{} just tried to change non-editable sign", g.name); + return; + } + let key = (p.pos[0], p.pos[1], p.pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + return; + }; + if sign.waxed { + return; + } + let side = if p.front { + &mut sign.front + } else { + &mut sign.back + }; + for (line, new) in side.lines.iter_mut().zip(&p.lines) { + *line = horizon_client::clipboard::strip_formatting(new); + } + play.sign_editing = None; + self.mark_block_entity_updated(key); + } + /// `ClientPacketListener.handleOpenSignEditor`: the editor on a sign this + /// client has. + pub(super) fn remote_open_sign_editor(&mut self, p: play::OpenSignEditor) { + let key = (p.pos[0], p.pos[1], p.pos[2]); + if matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sign(_)) + ) { + self.open_sign_editor(key, p.front); + } else { + log::warn!( + "ignoring openTextEdit on a block that is no sign at {:?}", + p.pos + ); + } + } pub(super) fn sign_edit_key(&mut self, event: &KeyEvent) { if event.state != ElementState::Pressed { return; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 23ba00699..cfbc3d78b 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -461,6 +461,10 @@ packet!(OpenScreen { container: i32 => VarInt, menu: i32 => VarInt, title: Tag = // ClientboundMountScreenOpenPacket: a horse's or llama's inventory, with its // chest's columns (`getInventoryColumns`). packet!(MountScreenOpen { container: i32 => VarInt, columns: i32 => VarInt, entity: i32 => Int }); +packet!( + /// ClientboundOpenSignEditorPacket: the sign whose side the player edits. + OpenSignEditor { pos: [i32; 3] => Pos, front: bool => SignSide } +); packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); /// MessageSignature.Packed: an index into the last-seen cache or a full signature. pub struct PackedSignature; @@ -1507,6 +1511,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN, OpenScreen(OpenScreen) = OPEN_SCREEN, + OpenSignEditor(OpenSignEditor) = OPEN_SIGN_EDITOR, Ping(Ping) = PING, PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, @@ -1805,6 +1810,38 @@ packet!( /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. RenameItem { name: String => Str } ); +packet!( + /// ServerboundSignUpdatePacket: the four lines the player wrote on a side. + SignUpdate { pos: [i32; 3] => Pos, lines: [String; 4] => SignLines, front: bool => SignSide } +); +/// SignTextSlot.STREAM_CODEC: VarInt 0 for the back, 1 for the front (any +/// other id reads as the back, ByIdMap's ZERO strategy). +pub struct SignSide; +impl Codec for SignSide { + fn read(r: &mut Reader) -> Result { + Ok(r.varint()? == 1) + } + fn write(v: &bool, w: &mut Writer) { + w.varint(i32::from(*v)); + } +} +/// `stringUtf8(384)` in `fixedSizeList(4)`: four lines, no count. +pub struct SignLines; +impl Codec<[String; 4]> for SignLines { + fn read(r: &mut Reader) -> Result<[String; 4]> { + Ok([ + r.string(384)?, + r.string(384)?, + r.string(384)?, + r.string(384)?, + ]) + } + fn write(v: &[String; 4], w: &mut Writer) { + for line in v { + w.string(line); + } + } +} packet!( /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an /// optional `mob_effect` id. @@ -1912,6 +1949,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, + SignUpdate(SignUpdate) = SIGN_UPDATE, UseItem(UseItem) = USE_ITEM, UseItemOn(UseItemOn) = USE_ITEM_ON, }); @@ -2608,4 +2646,29 @@ mod tests { }); round_trip(p, Clientbound::encode, Clientbound::decode); } + + #[test] + fn sign_packets_match_vanilla_stream_codecs() { + // ClientboundOpenSignEditorPacket: BlockPos, then SignTextSlot as a VarInt (FRONT is 1). + let open = Clientbound::OpenSignEditor(OpenSignEditor { + pos: [1, 2, 3], + front: true, + }); + let body = open.encode(); + assert_eq!( + body[1..9], + crate::buf::pack_block_pos([1, 2, 3]).to_be_bytes() + ); + assert_eq!(body[9..], [1]); + round_trip(open, Clientbound::encode, Clientbound::decode); + // ServerboundSignUpdatePacket: BlockPos, four strings with no count, then the slot. + let update = Serverbound::SignUpdate(SignUpdate { + pos: [-4, 70, 9], + lines: ["Hi".into(), String::new(), "x".into(), String::new()], + front: false, + }); + let body = update.encode(); + assert_eq!(body[9..], [2, b'H', b'i', 0, 1, b'x', 0, 0]); + round_trip(update, Serverbound::encode, Serverbound::decode); + } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 479feaf4e..f5127fa0c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -179,6 +179,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - keepinv: the host and the guest each die holding diamonds and wearing a helmet: with keep_inventory off both drop where they died and the player respawns without them; with it on nothing drops and the player keeps them (#1284). +- signs: the host and the guest each place an oak sign: the editor opens on their own screen + (ClientboundOpenSignEditorPacket), the two lines they write reach the server + (ServerboundSignUpdatePacket) and both sides show them (#1380). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4120,8 +4123,45 @@ def check_keep_inventory(host, guest, out): return seen -CHECKS += ['totem', 'keepinv'] -CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory) +def check_signs(host, guest, out): + """SignBlock.openTextEdit on the placing player's client, for the host and the guest: placing + an oak sign opens its editor there and nowhere else, the lines typed into it go to the server + when it closes, and both sides then show them (#1380).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, other, dz in ((host, guest, -2), (guest, host, 2)): + spot = (hx + 2, hy, hz + dz) + game('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone') + game('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='give @s minecraft:oak_sign 1') + game.wait(10) + game.raw('place', *spot, '--item', 'minecraft:oak_sign') + game.wait(10) + opened = {g.name: g('state').get('screen') for g in (game, other)} + game.shot(out, 'signs-editor') + lines = [f'{game.name} wrote', 'line two'] + game.raw('type', lines[0]) + game.raw('key', 'enter', 'tap') + game.raw('type', lines[1]) + game.raw('key', 'esc', 'tap') + game.wait(20) + back_to_game(other) + seen[game.name] = {'opened': opened, + 'shown': {g.name: (g.raw('block', *spot).get('sign') or {}).get('front') + for g in (game, other)}} + other.shot(out, 'signs-shown') + for name, s in seen.items(): + other = 'guest' if name == 'host' else 'host' + want = [f'{name} wrote', 'line two', '', ''] + assert s['opened'] == {name: 'sign', other: 'playing'}, f'{name}: {seen}' + assert s['shown'] == {name: want, other: want}, f'{name}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv', 'signs'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs) if __name__ == '__main__': From 5617d702cc62e676de8c24c4506ad055a62617b8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:09:55 +0200 Subject: [PATCH 08/19] Books open on a server's players, and what they write and sign reaches the server A server's player (a LAN guest, or single player's window on its server thread) could neither write in a book and quill nor read a written book: the server opened the screens in the guest's turn and dropped them (#1366). As in vanilla, the client opens a book and quill's editor itself when it uses one (LocalPlayer.openItemGui) and sends ServerboundEditBookPacket when it saves or signs; the server writes the pages or makes the written book, signed with the player's name, in that hotbar slot or the off hand. A written book opens on the client when the server sends ClientboundOpenBookPacket for its hand (ServerPlayer.openItemGui). horizon-protocol: OpenBook and EditBook (pages a list of at most 100). horizon-ctl: book sign presses Sign, then Sign and Close; book done on a book and quill saves it, as its Done button does. lan_e2e books: host and guest each write, sign, read and drop a book, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/books.rs | 153 ++++++++++++++---- crates/horizon-client/src/game/lan_actions.rs | 1 + crates/horizon-client/src/game/remote.rs | 6 +- .../src/game/station_control.rs | 2 +- crates/horizon-protocol/src/packets/play.rs | 49 ++++++ tools/lan_e2e.py | 59 ++++++- 6 files changed, 237 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index ccc1c6e19..9af1da70c 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -3,9 +3,10 @@ //! pixels, 1024 characters, 100 pages), signing it into a written book, //! reading written books, and lecterns (placing a book, turning its pages //! with a redstone pulse, the comparator output and taking the book). -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ containers::{BlockEntity, Lectern}, + first_person::Hand, hud::{HudBatch, rgba}, item_data::WrittenBook, items::ItemStack, @@ -14,6 +15,7 @@ use horizon_client::{ ui, }; use horizon_core::position::BlockPos; +use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use horizon_world::level::flags as level_flags; use std::time::Instant; use winit::{ @@ -48,9 +50,32 @@ impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { self.gui.atlas.font.split(&Text::literal(page), 114.0) } - /// `WritableBookItem.use` / `WrittenBookItem.use`. + /// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`). + /// A server's player writes in its own client's editor + /// (`LocalPlayer.openItemGui`), and reads on its own client once told to + /// (`ServerPlayer.openItemGui`'s ClientboundOpenBookPacket). pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { - let screen = match &*stack.item { + let written = match &*stack.item { + "minecraft:writable_book" => false, + "minecraft:written_book" => true, + _ => return false, + }; + if self.lan_acting.is_some() { + if written { + let hand = i32::from(self.hand == Hand::Off); + self.guest_packets + .push(C::OpenBook(play::OpenBook { hand })); + } + } else if let Some(screen) = self.book_screen(stack) { + self.open_book(screen); + } + self.swing_arm(); + true + } + /// The screen a book in hand opens: `BookEditScreen` for a book and + /// quill, `BookViewScreen` for a written book. + fn book_screen(&self, stack: &ItemStack) -> Option { + Some(match &*stack.item { "minecraft:writable_book" => { let mut pages = stack .data() @@ -77,12 +102,31 @@ impl Game<'_> { page: 0, lectern: None, }, - _ => return false, - }; - self.open_book(screen); - self.swing_arm(); + _ => return None, + }) + } + /// `MultiPlayerGameMode.useItem`'s own use of a book and quill on a + /// server's client: its editor opens here at once. + pub(super) fn remote_use_book(&mut self, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:writable_book" { + return false; + } + if let Some(screen) = self.book_screen(stack) { + self.open_book(screen); + } true } + /// `ClientPacketListener.handleOpenBook`: the written book in that hand. + pub(super) fn remote_open_book(&mut self, hand: i32) { + let hand = if hand == 1 { Hand::Off } else { Hand::Main }; + let screen = self.with_hand(hand, |g| { + let stack = g.held().filter(|s| &*s.item == "minecraft:written_book")?; + g.book_screen(&stack.clone()) + }); + if let Some(screen) = screen { + self.open_book(screen); + } + } fn open_book(&mut self, screen: BookScreen) { self.book = Some(screen); self.keys.clear(); @@ -104,7 +148,9 @@ impl Game<'_> { self.book = None; self.capture(true); } - /// `BookEditScreen.saveChanges`: trailing empty pages dropped. + /// `BookEditScreen.saveChanges` and `BookSignScreen`'s Sign and Close: + /// trailing empty pages dropped, the book in hand updated here and, on a + /// server's client, sent (ServerboundEditBookPacket). fn save_book(&mut self, sign: bool) { let Some(BookScreen::Edit { slot, pages, title, .. @@ -116,29 +162,59 @@ impl Game<'_> { while pages.len() > 1 && pages.last().is_some_and(String::is_empty) { pages.pop(); } - if let Some(stack) = self.stack_in_mut(slot).as_mut() - && &*stack.item == "minecraft:writable_book" - { - if sign { - let mut written = ItemStack::new("minecraft:written_book", 1); - written.data_mut().written = Some(WrittenBook { - title: title.trim().to_owned(), - author: super::chat::PLAYER_NAME.to_owned(), - generation: 0, - pages, - }); - *stack = written; - } else { - stack.data_mut().writable_pages = if pages.iter().all(String::is_empty) { - Vec::new() - } else { - pages - }; - stack.tidy(); - } + let title = sign.then(|| title.trim().to_owned()); + if self.remote.is_some() { + self.send(S::EditBook(play::EditBook { + slot: slot as i32, + pages: pages.clone(), + title: title.clone(), + })); } + self.write_book(slot, pages, title); self.capture(true); } + /// The book and quill at `slot` takes the pages, or with a title becomes + /// the written book its writer signed. + fn write_book(&mut self, slot: usize, pages: Vec, title: Option) { + let author = self + .lan_acting_name + .clone() + .unwrap_or_else(|| super::chat::PLAYER_NAME.to_owned()); + let Some(stack) = self + .stack_in_mut(slot) + .as_mut() + .filter(|s| &*s.item == "minecraft:writable_book") + else { + return; + }; + if let Some(title) = title { + let mut written = ItemStack::new("minecraft:written_book", 1); + written.data_mut().written = Some(WrittenBook { + title, + author, + generation: 0, + pages, + }); + *stack = written; + } else { + stack.data_mut().writable_pages = if pages.iter().all(String::is_empty) { + Vec::new() + } else { + pages + }; + stack.tidy(); + } + } + /// `ServerGamePacketListenerImpl.handleEditBook`: a guest's book in a + /// hotbar slot or its off hand (`updateBookContents`, `signBook`). + pub(super) fn lan_edit_book(&mut self, host: &mut LanHost, conn: u32, p: play::EditBook) { + if !((0..9).contains(&p.slot) || p.slot == super::shield::OFFHAND_SLOT as i32) { + return; + } + self.as_guest(host, conn, |g| { + g.write_book(p.slot as usize, p.pages, p.title) + }); + } pub(super) fn book_key(&mut self, event: &KeyEvent) { if event.state != ElementState::Pressed { return; @@ -519,7 +595,26 @@ impl Game<'_> { Some(key) => self.lectern_button(key, 3), None => return Err("not a lectern".into()), }, - Some("done") => self.close_book(), + // The book and quill's buttons: Sign, then Sign and Close; Done + // (which saves), then Cancel. + Some("sign") => match self.book.as_mut() { + Some(BookScreen::Edit { + signing: true, + title, + .. + }) if !title.trim().is_empty() => self.save_book(true), + Some(BookScreen::Edit { signing, .. }) => *signing = true, + _ => return Err("not a book and quill".into()), + }, + Some("done") => match self.book.as_mut() { + Some(BookScreen::Edit { signing: true, .. }) => { + if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() { + *signing = false; + } + } + Some(BookScreen::Edit { .. }) => self.save_book(false), + _ => self.close_book(), + }, Some(other) => return Err(format!("unknown book button {other}").into()), } Ok(match &self.book { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ac557e2dd..73fa67ba9 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1032,6 +1032,7 @@ impl Game<'_> { } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), S::SignUpdate(p) => self.lan_sign_update(host, conn, p), + S::EditBook(p) => self.lan_edit_book(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 67e30d7c1..bb4a3d9c1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2574,6 +2574,7 @@ impl Game<'_> { } C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag), C::OpenSignEditor(p) => self.remote_open_sign_editor(p), + C::OpenBook(p) => self.remote_open_book(p.hand), // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. C::SetDefaultSpawnPosition(p) => { let [x, y, z] = p.pos.pos; @@ -3978,8 +3979,11 @@ impl Game<'_> { return false; }; // MultiPlayerGameMode.useItem runs the use here too: food starts - // being eaten (Consumable.startConsuming). + // being eaten (Consumable.startConsuming), a book and quill opens. self.with_hand(hand, |g| g.start_eating(&info)); + if self.with_hand(hand, |g| g.remote_use_book(&held)) { + return true; + } // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. if &*held.item == "minecraft:bow" { diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index ecbbad0b8..7530b4278 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -10,7 +10,7 @@ pub(super) const HELP: &[&str] = &[ "use X Y Z open the block's menu as if right-clicked", "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", - "book [next|back|take|done] the open book or lectern: its page, or press one of its buttons", + "book [next|back|take|sign|done] the open book or lectern: its page, or press one of its buttons", "type TEXT | type-back type into the anvil name box / delete one character", "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index cfbc3d78b..fe3d19b85 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -465,6 +465,11 @@ packet!( /// ClientboundOpenSignEditorPacket: the sign whose side the player edits. OpenSignEditor { pos: [i32; 3] => Pos, front: bool => SignSide } ); +packet!( + /// ClientboundOpenBookPacket: the hand (InteractionHand, 0 main, 1 off) + /// whose written book the player reads. + OpenBook { hand: i32 => VarInt } +); packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); /// MessageSignature.Packed: an index into the last-seen cache or a full signature. pub struct PackedSignature; @@ -1511,6 +1516,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN, OpenScreen(OpenScreen) = OPEN_SCREEN, + OpenBook(OpenBook) = OPEN_BOOK, OpenSignEditor(OpenSignEditor) = OPEN_SIGN_EDITOR, Ping(Ping) = PING, PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, @@ -1814,6 +1820,29 @@ packet!( /// ServerboundSignUpdatePacket: the four lines the player wrote on a side. SignUpdate { pos: [i32; 3] => Pos, lines: [String; 4] => SignLines, front: bool => SignSide } ); +packet!( + /// ServerboundEditBookPacket: the book's slot (a hotbar slot, or 40 for + /// the off hand), its pages and, to sign it, its title. + EditBook { + slot: i32 => VarInt, + pages: Vec => BookPages, + title: Option => Opt>, + } +); +/// `stringUtf8(1024)` in `list(100)`: a book's pages. +pub struct BookPages; +impl Codec> for BookPages { + fn read(r: &mut Reader) -> Result> { + let n = r.varint()?; + if !(0..=100).contains(&n) { + return Err(Error::new(format!("{n} book pages, at most 100"))); + } + (0..n).map(|_| r.string(1024)).collect() + } + fn write(v: &Vec, w: &mut Writer) { + List::>::write(v, w); + } +} /// SignTextSlot.STREAM_CODEC: VarInt 0 for the back, 1 for the front (any /// other id reads as the back, ByIdMap's ZERO strategy). pub struct SignSide; @@ -1925,6 +1954,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + EditBook(EditBook) = EDIT_BOOK, Interact(Interact) = INTERACT, KeepAlive(KeepAlive) = KEEP_ALIVE, MovePlayerPos(MovePlayerPos) = MOVE_PLAYER_POS, @@ -2671,4 +2701,23 @@ mod tests { assert_eq!(body[9..], [2, b'H', b'i', 0, 1, b'x', 0, 0]); round_trip(update, Serverbound::encode, Serverbound::decode); } + + #[test] + fn book_packets_match_vanilla_stream_codecs() { + // ClientboundOpenBookPacket: InteractionHand as a VarInt. + let open = Clientbound::OpenBook(OpenBook { hand: 1 }); + assert_eq!(open.encode()[1..], [1]); + round_trip(open, Clientbound::encode, Clientbound::decode); + // ServerboundEditBookPacket: the slot, the pages (a counted list), then an optional title. + let sign = Serverbound::EditBook(EditBook { + slot: 40, + pages: vec!["a".into(), String::new()], + title: Some("T".into()), + }); + assert_eq!(sign.encode()[1..], [40, 2, 1, b'a', 0, 1, 1, b'T']); + round_trip(sign, Serverbound::encode, Serverbound::decode); + let mut w = Writer::new(); + w.varint(101); + assert!(BookPages::read(&mut Reader::new(&w.data)).is_err()); + } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f5127fa0c..3b369564f 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -182,6 +182,10 @@ address. The script then checks, from both sides, what a guest's game used to ge - signs: the host and the guest each place an oak sign: the editor opens on their own screen (ClientboundOpenSignEditorPacket), the two lines they write reach the server (ServerboundSignUpdatePacket) and both sides show them (#1380). +- books: the host and the guest each write in a book and quill on their own screen, sign it + (ServerboundEditBookPacket), read the written book the server gave them + (ClientboundOpenBookPacket), then drop it: the other side sees its title, author and + page (#1366). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4160,8 +4164,59 @@ def check_signs(host, guest, out): return seen -CHECKS += ['totem', 'keepinv', 'signs'] -CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs) +def book_screen(game): + """The open book (`book`'s page and page count), once `game` shows it.""" + game.raw('wait-for', 'screen', 'book', '--timeout', 10) + return game.raw('book') + + +def check_books(host, guest, out): + """Books in hand for the host and the guest: a book and quill opens its editor on the player's + own client (LocalPlayer.openItemGui), what it writes and signs reaches the server + (ServerboundEditBookPacket), and the written book opens on the player's client when the server + says so (ServerPlayer.openItemGui's ClientboundOpenBookPacket); dropped, the other side sees the + server's book (#1366).""" + seen = {} + for game, other in ((host, guest), (guest, host)): + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:writable_book') + x, y, z = pos_of(game) + game.raw('look-at', f'{x + 0.5:.2f}', f'{y + 30:.2f}', f'{z:.2f}') + game.wait(10) + case = seen[game.name] = {} + game.raw('use-item') + case['edit'] = book_screen(game) + case['other_screen'] = other('state').get('screen') + game.raw('type', f'{game.name} page one') + game.shot(out, 'books-edit') + game.raw('book', 'sign') + game.raw('type', f'{game.name} book') + game.raw('book', 'sign') + game.wait(20) + case['signed'] = {item: server_count(game, item) for item in ('writable_book', 'written_book')} + game.raw('use-item') + case['view'] = book_screen(game) + game.shot(out, 'books-view') + game.raw('book', 'done') + game.wait(5) + game.raw('key', 'q', 'tap') + game.wait(30) + books = [e['item'].get('components', '') for e in other.raw('entities', 16, 'minecraft:item')['entities'] + if e['item']['item'] == 'minecraft:written_book'] + case['dropped'] = [all(f'{game.name} {t}' in c for t in ('page one', 'book')) for c in books] + host('command', command='kill @e[type=minecraft:item]') + for name, case in seen.items(): + assert case['edit'] == {'page': 0, 'pages': 1, 'lectern': None}, f'{name}: {seen}' + assert case['other_screen'] == 'playing', f'{name}: {seen}' + assert case['signed'] == {'writable_book': 0, 'written_book': 1}, f'{name}: {seen}' + assert case['view'] == {'page': 0, 'pages': 1, 'lectern': None}, f'{name}: {seen}' + assert case['dropped'] == [True], f'{name}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv', 'signs', 'books'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs, books=check_books) if __name__ == '__main__': From 5ed8181adca456aae7ca081bc8b0acd6e1d5b47b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:12:44 +0200 Subject: [PATCH 09/19] Elytra glides on a server's players: the client sends START_FALL_FLYING and the server checks it A server's client never took the chest slot's Elytra into its own movement (player.glider) and never told the server it started gliding, so on the server thread and as a LAN guest the player just fell. The client now sets the glider as the window's own tick does and sends ServerboundPlayerCommandPacket START_FALL_FLYING when a glide starts. The hub used to accept that command blindly and never clear it. The game now answers it as handlePlayerCommand does (Player.tryToStartFallFlying, else stopFallFlying), and each tick runs LivingEntity.updateFallFlying for a gliding guest: the glide ends once canGlide fails (landed, riding, flying, levitation, a glider about to break), every 20th tick wears the Elytra, every 10th is an elytra_glide game event, and a glide that isn't diving keeps the fall distance at 1 (checkFallDistanceAccumulation). lan_e2e gets an elytra check, for the host and the guest, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 27 +++--- crates/horizon-client/src/game/agent.rs | 1 + crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 89 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 17 ++++ crates/horizon-client/src/lan/hub.rs | 7 +- tools/lan_e2e.py | 55 ++++++++++++ 7 files changed, 181 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 486f042a9..c62994dec 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1812,6 +1812,16 @@ impl Game<'_> { self.stack_in_mut(self.held_slot()) } /// The slot of the hand that acts: the selected one, or `OFFHAND_SLOT`. + /// `LivingEntity.canGlideUsing`: a glider in the chest slot that will + /// not break with its next point of wear. + fn glider_worn(&self) -> bool { + self.armor[1].as_ref().is_some_and(|s| { + self.res + .items() + .get(&s.item) + .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) + }) + } fn held_slot(&self) -> usize { match self.hand { Hand::Main => self.selected, @@ -3931,13 +3941,7 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; - // LivingEntity.canGlideUsing: a glider in its slot that will not break next. - player.glider = self.armor[1].as_ref().is_some_and(|s| { - self.res - .items() - .get(&s.item) - .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) - }); + player.glider = self.glider_worn(); // A saved death already dropped inventory/XP and counted the death. if player.health.dead_or_dying() { self.screen = Screen::Dead; @@ -4015,6 +4019,7 @@ impl Game<'_> { let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); let spin_targets = self.spin_targets(); + let glider = self.glider_worn(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -4057,13 +4062,7 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; - // LivingEntity.canGlideUsing: a glider in its slot that will not break next. - player.glider = self.armor[1].as_ref().is_some_and(|s| { - self.res - .items() - .get(&s.item) - .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) - }); + player.glider = glider; // LocalPlayer.modifyInput: walking while using an item. player.item_use_speed = self .using diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0c1954891..89fec4254 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -463,6 +463,7 @@ impl Game<'_> { "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], "on_ground": p.ground.on_ground, "flying": p.flying, + "fall_flying": p.fall_flying, "sneaking": self.keys.contains(&KeyCode::ShiftLeft), "sprinting": self.keys.contains(&KeyCode::ControlLeft), "health": p.health.health(), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8467b6d3a..9db544421 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -410,6 +410,8 @@ impl Game<'_> { // ItemCooldowns: the ticks the shield an axe disabled stays down. "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), "sneaking": g.sneaking, + // The server's Elytra glide (shared flag 7). + "fall_flying": g.fall_flying, "sleeping": g.bed, "health": g.health, // The server's body: its air supply and golden hearts. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 73fa67ba9..81ee2860b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1027,6 +1027,7 @@ impl Game<'_> { g.open_ridden_mount_menu(); }); } + S::PlayerCommand(p) if p.action == 6 => self.lan_start_gliding(host, conn), S::ContainerButtonClick(p) => { self.lan_station_button(host, conn, p.container, p.button); } @@ -1850,6 +1851,13 @@ impl Game<'_> { /// sounds are heard at the guest. fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) { self.guest_vehicle_tick(host, conn); + // The last move's fall stands in for the server's delta movement. + let fell = host + .hub + .guest_mut(conn) + .and_then(|g| g.moves.last().map(|m| m.0[1])) + .unwrap_or(0.0); + self.guest_glide_tick(host, conn, fell); let Some(g) = host.hub.guest_mut(conn) else { return; }; @@ -1966,6 +1974,87 @@ impl Game<'_> { } } + /// ServerGamePacketListenerImpl.handlePlayerCommand START_FALL_FLYING: + /// `Player.tryToStartFallFlying`, or else `stopFallFlying` (a second + /// start while gliding ends the glide, as in vanilla). + fn lan_start_gliding(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + let start = !g.fall_flying && self.guest_can_glide(host, conn) == Some(true); + let in_liquid = self + .as_guest(host, conn, |game| { + game.player + .as_ref() + .is_some_and(|p| p.fluids.was_touching_water || p.is_in_lava()) + }) + .unwrap_or(true); + if let Some(g) = host.hub.guest_mut(conn) { + g.fall_flying = start && !in_liquid; + } + } + + /// `Player.canGlide`: not flying, airborne, not riding, no levitation, and + /// a glider that its next point of wear won't break. + fn guest_can_glide(&mut self, host: &mut LanHost, conn: u32) -> Option { + let g = host.hub.guest_mut(conn)?; + if g.flying || g.on_ground || g.vehicle.is_some() { + return Some(false); + } + self.as_guest(host, conn, |game| { + game.glider_worn() && game.potions.effects.get("levitation").is_none() + }) + } + + /// `LivingEntity.updateFallFlying` on the server, once a tick for a + /// gliding guest: the glide ends once `canGlide` fails; otherwise every + /// 20th tick wears the glider by one, and every 10th is an + /// `elytra_glide` game event. Entity.checkFallDistanceAccumulation runs + /// first: a glide that isn't diving keeps the fall distance at 1. + fn guest_glide_tick(&mut self, host: &mut LanHost, conn: u32, fell: f64) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + if !g.fall_flying { + if let Some(m) = g.motion.as_mut() { + m.fall_fly_ticks = 0; + } + return; + } + let creative = g.creative(); + if let Some(m) = g.motion.as_mut() + && fell > -0.5 + && m.fall_distance > 1.0 + { + m.fall_distance = 1.0; + } + if self.guest_can_glide(host, conn) != Some(true) { + if let Some(g) = host.hub.guest_mut(conn) { + g.fall_flying = false; + } + return; + } + self.as_guest(host, conn, |game| { + let Some(p) = game.player.as_mut() else { + return; + }; + p.fall_fly_ticks += 1; + let next = p.fall_fly_ticks + 1; + let at = [p.position.x, p.position.y, p.position.z]; + if next % 10 != 0 { + return; + } + if (next / 10) % 2 == 0 + && !creative + && let Some(elytra) = game.armor[1].as_mut() + { + elytra.damage += 1; + } + let ctx = game.player_context(None); + game.post_game_event("minecraft:elytra_glide", at, ctx); + }); + } + /// `Player.isInWall`: a suffocating block in the 0.48-wide box at the /// eyes. Suffocating is a full collision box that is also a full render /// cube (`BlockBehaviour.isSuffocating`'s default; glass and the like diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index bb4a3d9c1..362dc3cf2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3139,6 +3139,12 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.fluids.fast_lava = self.dim == Dim::Nether; + let glider = self.glider_worn(); + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; + player.glider = glider; + let was_gliding = player.fall_flying; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. if let Some(head) = self.sleeping { @@ -3163,6 +3169,9 @@ impl Game<'_> { // LocalPlayer.onUpdateAbilities: flight turned on or off (a double // jump, a spectator, landing) is sent to the server. let flying = player.flying; + // LocalPlayer.aiStep: a glide this client started is sent to the + // server (ServerboundPlayerCommandPacket START_FALL_FLYING). + let started_gliding = player.fall_flying && !was_gliding; let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; @@ -3202,6 +3211,14 @@ impl Game<'_> { flags: if flying { 2 } else { 0 }, })); } + if started_gliding { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 6, + data: 0, + })); + } self.remote_send_state(input); Ok(()) } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c8f2e980d..0b2ce442a 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2011,14 +2011,15 @@ impl Hub { self.guests[i].sneaking = p.flags & 32 != 0; self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0; } - // OPEN_INVENTORY is the game's: the ridden mount's inventory. - S::PlayerCommand(p) if p.action == 5 => { + // OPEN_INVENTORY (the ridden mount's inventory) and + // START_FALL_FLYING (checked against the guest's chest slot + // and effects) are the game's. + S::PlayerCommand(p) if matches!(p.action, 5 | 6) => { events.push(HostEvent::Packet(conn, Box::new(S::PlayerCommand(p)))); } S::PlayerCommand(p) => match p.action { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, - 6 => self.guests[i].fall_flying = true, // STOP_SLEEPING. 0 => self.wake(i), _ => {} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 3b369564f..d93a142f1 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -186,6 +186,10 @@ address. The script then checks, from both sides, what a guest's game used to ge (ServerboundEditBookPacket), read the written book the server gave them (ClientboundOpenBookPacket), then drop it: the other side sees its title, author and page (#1366). +- elytra: the host and the guest, high up with an Elytra on, jump in the air and glide + (ServerboundPlayerCommandPacket START_FALL_FLYING): both their client and the server + have them gliding, they go forward far more than down, and the glide ends on both once + they land (#1288). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4219,5 +4223,56 @@ CHECKS += ['totem', 'keepinv', 'signs', 'books'] CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs, books=check_books) +def check_elytra(host, guest, out): + """LivingEntity.updateFallFlying for each player: a jump while falling with an Elytra on starts a + glide that the server takes too (Player.tryToStartFallFlying), the glide carries the player + forward rather than down, and landing ends it on both sides (canGlide fails on the ground).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dx in ((host, -2), (guest, 2)): + x, z = hx + dx, hz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 1} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 1} {hy + 3} {z + 1} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect give @s minecraft:resistance 60 4 true') + game('command', command='item replace entity @s armor.chest with minecraft:elytra') + game('command', command=f'tp @s {x + 0.5} {hy + 60} {z + 0.5} 0 0') + game.wait(6) + start = pos_of(game) + game.raw('key', 'space', 'down') + game.wait(1) + game.raw('key', 'space', 'up') + game.wait(30) + end = pos_of(game) + glide = {'client': own(game).get('fall_flying'), + 'server': server_player(host, game).get('fall_flying'), + 'forward': round(math.hypot(end[0] - start[0], end[2] - start[2]), 1), + 'down': round(start[1] - end[1], 1)} + game.shot(out, 'elytra') + game('command', command=f'tp @s {x + 0.5} {hy + 1} {z + 0.5}') + game.wait(30) + landed = {'on_ground': own(game).get('on_ground'), + 'client': own(game).get('fall_flying'), + 'server': server_player(host, game).get('fall_flying')} + seen[game.name] = {'glide': glide, 'landed': landed} + finally: + for game in (host, guest): + game('command', command='clear @s') + game('command', command='effect clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + g, l = s['glide'], s['landed'] + # Falling alone covers about 25 blocks in those 30 ticks and goes nowhere. + assert g['client'] and g['server'] and g['forward'] > 8 and g['down'] < 20, f'{name} glide: {seen}' + assert l['on_ground'] and not l['client'] and not l['server'], f'{name} landed: {seen}' + return seen + + +CHECKS += ['elytra'] +CHECK_FNS.update(elytra=check_elytra) + + if __name__ == '__main__': main() From ad76f911bdeff02d524acc0cad0916fc59b23167 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:50:41 +0200 Subject: [PATCH 10/19] Shields, tridents, crossbows and spyglasses end their use on a server: the client starts it too Item.use runs on the client as well (MultiPlayerGameMode.useItem), and only a use the client started sends RELEASE_USE_ITEM when the button lets go. A server's client started one for bows and food only, so a shield kept blocking after release, a charged trident never left the hand, a loaded crossbow stayed "in use" on the server and never fired, and a spyglass never scoped. The client now starts what the window's own Item.use does: a bow or crossbow with ammunition, a trident, a spyglass, a shield off cooldown, and keeps it until the button lets go. The server's RELEASE_USE_ITEM let go of a main-hand bow only. It now runs ServerPlayer.releaseUsingItem with the used item's hand, through the release the window's own tick shares (bow, trident, spyglass). A loaded crossbow reached its client without its ammunition: the network stack gets minecraft:charged_projectiles (registry id 51, ItemStackTemplate list), and a server's client decodes it. lan_e2e gets a helduse check, for the host and the guest, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 21 ++-- crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 18 ++- crates/horizon-client/src/game/remote.rs | 80 +++++++++++--- crates/horizon-client/src/lan/guest.rs | 19 ++++ crates/horizon-protocol/src/item.rs | 26 +++++ tools/lan_e2e.py | 103 ++++++++++++++++++ 7 files changed, 242 insertions(+), 28 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c62994dec..11f5dded2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3653,16 +3653,8 @@ impl Game<'_> { // Switching hotbar slots only ends a main-hand use. let hand_changed = slot != self.selected && slot != shield::OFFHAND_SLOT; if !self.right || hand_changed || self.screen != Screen::Playing { - if &*stack.item == "minecraft:bow" && !hand_changed { - self.release_bow(ticks); - } - if &*stack.item == "minecraft:spyglass" { - self.stop_spyglass(); - } - if &*stack.item == "minecraft:trident" && !hand_changed { - self.release_trident(ticks); - } self.using = None; + self.release_used_item(&stack, ticks, hand_changed); return; } let Some(info) = self.res.items().get(&stack.item).cloned() else { @@ -3718,6 +3710,17 @@ impl Game<'_> { self.using = Some((slot, ticks)); } } + /// `LivingEntity.releaseUsingItem` (`Item.releaseUsing`) for `stack`, + /// used for `ticks`, its hand acting: a bow or a trident lets go (not + /// when its hand changed), a spyglass stops scoping. + pub(super) fn release_used_item(&mut self, stack: &ItemStack, ticks: u32, hand_changed: bool) { + match &*stack.item { + "minecraft:bow" if !hand_changed => self.release_bow(ticks), + "minecraft:trident" if !hand_changed => self.release_trident(ticks), + "minecraft:spyglass" => self.stop_spyglass(), + _ => {} + } + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9db544421..e0db6d725 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -409,6 +409,9 @@ impl Game<'_> { "game_mode": g.game_mode, // ItemCooldowns: the ticks the shield an axe disabled stays down. "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), + // The item the server has this guest using: its slot and ticks. + "using": h.play.get(&g.conn).and_then(|p| p.using()) + .map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), "sneaking": g.sneaking, // The server's Elytra glide (shared flag 7). "fall_flying": g.fall_flying, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 81ee2860b..91e4e15e5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -868,14 +868,20 @@ impl Game<'_> { self.as_guest(host, conn, |g| g.drop_held(a.action == 4)); } } + // RELEASE_USE_ITEM: ServerPlayer.releaseUsingItem, with the + // hand of the item in use acting. 6 => { self.as_guest(host, conn, |g| { - if let Some((slot, ticks)) = g.using.take() - && g.stack_in(slot) - .is_some_and(|s| &*s.item == "minecraft:bow") - { - g.release_bow(ticks); - } + let Some(hand) = g.used_hand() else { + return; + }; + g.with_hand(hand, |g| { + if let Some((slot, ticks)) = g.using.take() + && let Some(stack) = g.stack_in(slot).cloned() + { + g.release_used_item(&stack, ticks, false); + } + }); }); } // SWAP_ITEM_WITH_OFFHAND: the hands swap and the item in use stops diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 362dc3cf2..21c3ff963 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -638,6 +638,22 @@ impl Game<'_> { ("mob_factor", Tag::Float(v[5].to_bits())), ]), Component::Profile(p) => profile_tag(p), + // ItemStackTemplate.CODEC: id, count and components. + Component::Stacks(stacks) => Tag::List( + stacks + .iter() + .map(|t| { + let mut entries = vec![ + ("id", Tag::String(self.item_name(t.item).as_ref().into())), + ("count", Tag::Int(t.count)), + ]; + if let Some(c) = self.protocol_components(t) { + entries.push(("components", c)); + } + Tag::compound(entries) + }) + .collect(), + ), Component::CustomModelData { floats, flags, @@ -4001,19 +4017,55 @@ impl Game<'_> { if self.with_hand(hand, |g| g.remote_use_book(&held)) { return true; } - // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting - // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. - if &*held.item == "minecraft:bow" { - self.with_hand(hand, |g| { - if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) - { - g.using = Some((g.held_slot(), 0)); - } - }); - } + self.with_hand(hand, |g| g.remote_start_held_use(&held)); item_has_use(&info) } + /// `Item.use` runs on the client too (MultiPlayerGameMode.useItem): an + /// item held in use until the button lets go starts being used here, so + /// that letting go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and + /// the server ends the use: a bow or a trident is let go, a crossbow's + /// charge ends, a shield is lowered, a spyglass stops scoping. Their + /// sounds, loaded arrows and thrown tridents come from the server. + fn remote_start_held_use(&mut self, held: &ItemStack) { + if self.using.is_some() { + return; + } + let start = match &*held.item { + // BowItem.use: with an arrow, or in creative. + "minecraft:bow" => self.creative || self.projectile_slot("minecraft:bow").is_some(), + // CrossbowItem.use: charging when not charged and with ammunition; + // a charged one shoots on the server. + "minecraft:crossbow" => { + held.data().is_none_or(|d| d.charged.is_empty()) + && (self.creative || self.projectile_slot("minecraft:crossbow").is_some()) + } + // TridentItem.use: not about to break, Riptide only in water or rain. + "minecraft:trident" => { + self.use_trident(held); + return; + } + // SpyglassItem.use (its sound is the server's). + "minecraft:spyglass" => true, + // ShieldItem.use: anything that blocks attacks, off cooldown. + _ => { + self.raise_shield(self.held_slot()); + return; + } + }; + if start { + self.using = Some((self.held_slot(), 0)); + } + } + /// Whether `stack` stays in use until the button lets go (bows, + /// crossbows, tridents, spyglasses, shields): its use only counts ticks here. + fn held_until_released(&self, stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass" + ) || self.blocks_attacks(stack).is_some() + } + /// The rest of Minecraft.startUseItem once the main hand's target passed: /// the main hand's item, then the off hand's turn (its block, its item). /// The server does each packet's part with that packet's hand only. @@ -4026,7 +4078,8 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// `LivingEntity.updatingUsingItem` on a server client: an item held in + /// use (`held_until_released`), and a /// consumable's eating animation and its crumbs. The server eats it and /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { @@ -4034,8 +4087,9 @@ impl Game<'_> { return; }; let stack = self.stack_in(slot).cloned(); - // A drawn bow: held until the button lets go (or another slot is picked). - if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + // A drawn bow, a charging crossbow, a raised shield...: held until + // the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| self.held_until_released(s)) { self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) .then_some((slot, ticks + 1)); return; diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 6ed7a2925..fd2b197e0 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -430,6 +430,13 @@ pub fn stack_to_network( item_id: impl Fn(&str) -> i32, enchantment_id: impl Fn(&str) -> Option, s: &Option, +) -> Option { + network_stack(&item_id, &enchantment_id, s) +} +fn network_stack( + item_id: &dyn Fn(&str) -> i32, + enchantment_id: &dyn Fn(&str) -> Option, + s: &Option, ) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(item_id(&s.item), s.count as i32); @@ -486,6 +493,18 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(i32::from(mode)), )); } + // A loaded crossbow's ammunition. + if !d.charged.is_empty() { + let charged = d + .charged + .iter() + .filter_map(|c| network_stack(item_id, enchantment_id, &Some(c.clone()))) + .collect(); + stack.added.push(( + horizon_protocol::item::component::CHARGED_PROJECTILES, + horizon_protocol::item::Component::Stacks(charged), + )); + } // The books a lectern shows and a guest reads. if !d.writable_pages.is_empty() { stack.added.push(( diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 6f59228b5..650fa4baa 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -32,6 +32,7 @@ pub mod component { pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; + pub const CHARGED_PROJECTILES: i32 = 51; pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; } @@ -75,6 +76,8 @@ pub enum Component { /// `WritableBookContent`: the pages (raw text). WritableBook(Vec), WrittenBook(WrittenBook), + /// `ChargedProjectiles`: a loaded crossbow's ammunition, as templates. + Stacks(Vec), } /// `Filterable.streamCodec`: the raw value, then an optional filtered one @@ -125,6 +128,10 @@ impl Component { resolved: r.bool()?, }) } + CHARGED_PROJECTILES => { + let n = r.count(1024)?; + Self::Stacks((0..n).map(|_| Template::read(r)).collect::>()?) + } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, ENCHANTMENT_GLINT_OVERRIDE => Self::Bool(r.bool()?), @@ -283,6 +290,10 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::Stacks(stacks) => { + w.varint(stacks.len() as i32); + stacks.iter().for_each(|s| Template::write(s, w)); + } Self::WritableBook(pages) => { w.varint(pages.len() as i32); for page in pages { @@ -533,6 +544,21 @@ mod tests { round::, HashedSlot>(None); } + #[test] + fn charged_projectiles_are_item_stack_templates() { + // A crossbow (id 7) loaded with one arrow (id 9): ChargedProjectiles + // is a list of ItemStackTemplate, the item before the count. + let bytes = [1, 7, 1, 0, 51, 1, 9, 1, 0, 0]; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::CHARGED_PROJECTILES), + Some(&Component::Stacks(vec![Stack::new(9, 1)])) + ); + let mut w = Writer::new(); + Slot::write(&Some(stack), &mut w); + assert_eq!(w.data, bytes); + } + #[test] fn filtered_book_pages_are_read_and_dropped() { // A writable book with one page "hi" and its filtered "**". diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index d93a142f1..b13c3cade 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -190,6 +190,10 @@ address. The script then checks, from both sides, what a guest's game used to ge (ServerboundPlayerCommandPacket START_FALL_FLYING): both their client and the server have them gliding, they go forward far more than down, and the glide ends on both once they land (#1288). +- helduse: the host and the guest raise a shield, charge and fire a crossbow, throw a trident + and scope with a spyglass: each use starts on their own client and on the server, and + letting go ends it on both (RELEASE_USE_ITEM), so the shield lowers, the trident flies + and the loaded crossbow fires on the next use (#1300, #1281, #1282, #1301). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4274,5 +4278,104 @@ CHECKS += ['elytra'] CHECK_FNS.update(elytra=check_elytra) +def server_using(host, game): + """The item the server has the player using ({slot, ticks}), or None.""" + if game is host and not SERVER_THREAD: + return host('state').get('using') + return server_player(host, game).get('using') + + +def flying(game, kind): + """How many of the projectiles this side draws are of `kind` (a trident, an arrow).""" + return sum(kind in q['kind'].lower() for q in game('status')['projectiles']) + + +def check_held_use(host, guest, out): + """Items used until the button lets go, for each player: the client starts the use too + (Item.use runs on both sides), so letting go sends RELEASE_USE_ITEM and the server ends it.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dz in ((host, -3), (guest, 3)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 12} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:air') + host('command', command=f'fill {x + 12} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:stone') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + s = {} + # ShieldItem: raised while held, lowered once let go. + game('command', command='item replace entity @s weapon.offhand with minecraft:shield') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['shield'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['shield']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + game('command', command='item replace entity @s weapon.offhand with minecraft:air') + # SpyglassItem: scoping while held. + game('command', command='item replace entity @s weapon.mainhand with minecraft:spyglass') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['spyglass'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['spyglass']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + # TridentItem.releaseUsing after 10 ticks: thrown. + host('command', command='kill @e[type=minecraft:trident]') + game('command', command='item replace entity @s weapon.mainhand with minecraft:trident') + game.wait(5) + # /kill finds no thrown trident (Horizon's selectors miss them): count what's new. + before = flying(game, 'trident') + game.raw('use-item', '--hold', 1.2) + game.wait(10) + s['trident'] = {'kept': server_count(game, 'trident'), + 'thrown': flying(game, 'trident') - before} + host('command', command='kill @e[type=minecraft:trident]') + # CrossbowItem: charged by holding (25 ticks), fired by the next use. + host('command', command='kill @e[type=minecraft:arrow]') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:crossbow') + game('command', command='give @s minecraft:arrow 16') + game.wait(5) + before = flying(game, 'arrow') + game.raw('use-item', '--hold', 1.6) + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'] = {'loaded': 'charged_projectiles' in str(held.get('components', '')), + 'arrows': server_count(game, 'arrow')} + game.raw('use-item') + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'].update( + fired=flying(game, 'arrow') - before, + emptied='charged_projectiles' not in str(held.get('components', ''))) + game.shot(out, 'helduse') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:arrow]') + host('command', command='kill @e[type=minecraft:trident]') + for game in (host, guest): + back_to_game(game) + game.raw('mouse', 'right', 'up') + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + for item in ('shield', 'spyglass'): + assert s[item] == {'held': (True, True), 'let_go': (False, False)}, f'{name} {item}: {seen}' + assert s['trident'] == {'kept': 0, 'thrown': 1}, f'{name} trident: {seen}' + assert s['crossbow'] == {'loaded': True, 'arrows': 15, 'fired': 1, 'emptied': True}, \ + f'{name} crossbow: {seen}' + return seen + + +CHECKS += ['helduse'] +CHECK_FNS.update(helduse=check_held_use) + + if __name__ == '__main__': main() From 8ef418e223eed07d4ca2215e6f0d3016890bb76c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:34:27 +0200 Subject: [PATCH 11/19] Maps in one hand: the off hand, or the main hand beside an item, draws the map FirstPersonHandsAndItemsRenderer.submitArmWithItem draws a stack with a map_id two-handed only from the main hand with an empty off hand; any other map is renderOneHandedMap in its own hand. Horizon only had the two-handed case and drew every other held map as its item model (#1459). MapHold picks the case from the hand renderer's visible items, and one_handed_map_pose is renderOneHandedMap's transform, checked against vanilla's PoseStack. renderMap (background, map, decorations) is shared by both cases. The arms under held maps are still not drawn, as before. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/first_person.rs | 120 ++++++++++++++++++++++ crates/horizon-client/src/game.rs | 31 ++++-- crates/horizon-client/src/game/maps.rs | 25 ++--- 3 files changed, 156 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 02132d942..0735ce2ba 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -137,6 +137,48 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - m } +/// How `submitArmWithItem` holds a stack with a `minecraft:map_id`: in both +/// hands when it is the main hand's and the off hand is empty +/// (`renderTwoHandedMap`), else in its own hand (`renderOneHandedMap`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MapHold { + TwoHanded, + OneHanded, +} +impl MapHold { + pub fn of(hand: Hand, off_hand_empty: bool) -> Self { + if hand == Hand::Main && off_hand_empty { + Self::TwoHanded + } else { + Self::OneHanded + } + } +} + +/// `renderOneHandedMap` up to `renderMap`: the pose of a map in the hand on +/// the `left` or right arm (the arm under it is not drawn). +pub fn one_handed_map_pose(left: bool, inverse_height: f32, attack: f32) -> glam::Mat4 { + use glam::{Mat4, Vec3}; + use horizon_core::geometry::trig::Mth; + let invert = if left { -1.0 } else { 1.0 }; + let pi = std::f32::consts::PI; + let root = attack.sqrt(); + let x_swing = (root * pi).msin(); + Mat4::from_translation(Vec3::new(invert * 0.125, -0.125, 0.0)) + * Mat4::from_translation(Vec3::new( + invert * 0.51, + -0.08 + inverse_height * -1.2, + -0.75, + )) + * Mat4::from_translation(Vec3::new( + invert * -0.5 * x_swing, + 0.4 * (root * std::f32::consts::TAU).msin() - 0.3 * x_swing, + -0.3 * (attack * pi).msin(), + )) + * Mat4::from_rotation_x((x_swing * -45.0).to_radians()) + * Mat4::from_rotation_y((invert * x_swing * -30.0).to_radians()) +} + /// `FirstPersonHandsAndItems.evaluateWhichHandsToRender`: whether the main /// and the off hand show, from what each holds (item and whether it is a /// charged crossbow) and the item in use with its hand. A bow or crossbow @@ -819,6 +861,84 @@ mod tests { mod item_pose_tests { use super::*; #[test] + fn a_map_is_two_handed_only_in_the_main_hand_with_an_empty_off_hand() { + assert_eq!(MapHold::of(Hand::Main, true), MapHold::TwoHanded); + assert_eq!(MapHold::of(Hand::Main, false), MapHold::OneHanded); + assert_eq!(MapHold::of(Hand::Off, true), MapHold::OneHanded); + assert_eq!(MapHold::of(Hand::Off, false), MapHold::OneHanded); + } + #[test] + fn one_handed_maps_follow_render_one_handed_map() { + // PoseStack.last().pose() from vanilla's renderOneHandedMap + // transforms (column-major), for (left, inverse height, attack). + let cases: [(bool, f32, f32, [f32; 16]); 3] = [ + ( + false, + 0.0, + 0.0, + [ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.635, -0.205, + -0.75, 1.0, + ], + ), + ( + true, + 0.25, + 0.3, + [ + 0.86894435, + -0.34686038, + -0.35302067, + 0.0, + 0.0, + 0.713303, + -0.70085573, + 0.0, + 0.4949098, + 0.6090046, + 0.61982065, + 0.0, + -0.1406033, + -0.9197687, + -0.9926984, + 1.0, + ], + ), + ( + false, + 0.6, + 0.85, + [ + 0.9919303, + 0.024030307, + 0.12448644, + 0.0, + 0.0, + 0.9818737, + -0.18953651, + 0.0, + -0.12678458, + 0.18800701, + 0.97395027, + 0.0, + 0.5136029, + -1.1862278, + -0.88621765, + 1.0, + ], + ), + ]; + for (left, inverse_height, attack, want) in cases { + let got = one_handed_map_pose(left, inverse_height, attack).to_cols_array(); + for (g, w) in got.iter().zip(want) { + assert!( + (g - w).abs() < 1e-5, + "{left} {inverse_height} {attack}: {got:?}" + ); + } + } + } + #[test] fn ranged_draw_uses_native_charge_curves_and_caps() { for (ticks, stretch) in [ (0.0, 1.0), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 03854e9f8..14fdc8192 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8798,20 +8798,15 @@ impl Game<'_> { ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let deg = |d: f32| d.to_radians(); - if self.held_map_geometry(to_world, attacks[0], inverse_heights[0], packed, &mut out) { - return out; - } let shown = self.hands_to_render(); let used_hand = self.used_hand(); let spinning = self .player .as_ref() .is_some_and(|p| p.auto_spin_attack_ticks > 0); - for (i, (hand, item)) in Hand::BOTH - .into_iter() - .zip(self.visible_hand_items()) - .enumerate() - { + let items = self.visible_hand_items(); + let off_hand_empty = items[1].is_none(); + for (i, (hand, item)) in Hand::BOTH.into_iter().zip(items).enumerate() { if !shown[i] { continue; } @@ -8874,6 +8869,26 @@ impl Game<'_> { ); continue; }; + if let Some(id) = maps::map_id(&stack) { + use horizon_client::first_person::{MapHold, one_handed_map_pose}; + match MapHold::of(hand, off_hand_empty) { + MapHold::TwoHanded => self.two_handed_map_geometry( + to_world, + attack, + inverse_height, + id, + packed, + &mut out, + ), + MapHold::OneHanded => self.held_map( + to_world * one_handed_map_pose(left, inverse_height, attack), + id, + packed, + &mut out, + ), + } + continue; + } let mut owner = self.player_owner(Some(&stack)); // The other hand may hold an equal stack: only the used // hand's item is in use, only the main hand's selected. diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index bc2534659..5809cf3b6 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -918,21 +918,17 @@ impl Game<'_> { ); } } - /// `renderTwoHandedMap`: the held map (main hand, empty off hand) in view space. - pub(super) fn held_map_geometry( + /// `renderTwoHandedMap`: map `id` held in both hands, in view space (the + /// arms under it are not drawn). + pub(super) fn two_handed_map_geometry( &mut self, to_world: glam::Mat4, attack: f32, inverse_height: f32, + id: i32, light: u32, out: &mut Vec, - ) -> bool { - let Some(id) = self.inventory[self.selected].as_ref().and_then(map_id) else { - return false; - }; - if self.offhand.is_some() { - return false; - } + ) { let deg = |d: f32| d.to_radians(); let sqrt_attack = attack.sqrt(); let y_swing = -0.2 * (attack * std::f32::consts::PI).sin(); @@ -949,10 +945,16 @@ impl Game<'_> { )) * glam::Mat4::from_rotation_x(deg(tilt * -85.0)); let swing = (sqrt_attack * std::f32::consts::PI).sin(); - // renderMap: background (with 7-pixel border) then the map. let m = base * glam::Mat4::from_rotation_x(deg(swing * 20.0)) - * glam::Mat4::from_scale(glam::Vec3::splat(2.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(2.0)); + self.held_map(m, id, light, out); + } + /// `renderMap`: map `id` at pose `m`, its background (with a 7-pixel + /// border) then the map. + pub(super) fn held_map(&mut self, m: glam::Mat4, id: i32, light: u32, out: &mut Vec) { + let deg = |d: f32| d.to_radians(); + let m = m * glam::Mat4::from_rotation_y(deg(180.0)) * glam::Mat4::from_rotation_z(deg(180.0)) * glam::Mat4::from_scale(glam::Vec3::splat(0.38)) @@ -984,7 +986,6 @@ impl Game<'_> { if has_data { self.map_vertices(id, m, light, out); } - true } } From 7dac46ec3cc74eda07797572e84c7434065db3c8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:58:35 +0200 Subject: [PATCH 12/19] Bundles take and give items in inventories and containers A carried bundle clicked on a stack took its place instead of taking it in (#1456): Horizon's menus had no BundleItem click overrides. The PICKUP click now runs them first, as AbstractContainerMenu.tryItemClickBehaviourOverride: - a carried bundle takes as much of a clicked stack as its weight allows (tryTransfer), and a right click on an empty slot puts its first stack there (removeOne, the rest going back in); - a stack clicked onto a bundle in a slot goes in as far as it fits, and a right click with an empty hand takes the bundle's first stack out. BundleContents.Mutable is in horizon_client::bundle (exact Fraction weights: 1/max stack, 1 for a beehive with bees, a nested bundle's contents plus 1/16; shulker boxes don't fit), used by the menu engine and the LAN/server-thread container engine. The insert, insert-fail and remove-one sounds play at the player. In single player the inventory screen's empty-hand press went to an older click path instead of the menu engine; it now goes to the engine, as on a server, so the right click on a bundle works there too. The menu click harness now has bundles (empty, loaded, nested; often in hand) and compares the player's sounds: 3000/3000 bundle-heavy cases match, 2796/3000 without the overrides. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/menu_fixture.rs | 6 +- crates/horizon-client/src/bundle.rs | 192 +++++++++++++++++ crates/horizon-client/src/game.rs | 30 +++ crates/horizon-client/src/game/lan_actions.rs | 3 + crates/horizon-client/src/items.rs | 3 + crates/horizon-client/src/lan/menu.rs | 201 +++++++++++++++++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu.rs | 13 +- crates/horizon-client/src/menu/bundle.rs | 95 +++++++++ .../horizonlab/parity/VanillaMenuOracle.java | 14 +- tools/test_menu_click_parity.py | 49 ++++- 11 files changed, 594 insertions(+), 13 deletions(-) create mode 100644 crates/horizon-client/src/bundle.rs create mode 100644 crates/horizon-client/src/menu/bundle.rs diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 1da4a0278..898c95383 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -58,11 +58,12 @@ fn state(menu: &Menu) -> String { .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); let line = format!( - "{} | {} |{data} | {} | {}", + "{} | {} |{data} | {} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), - equipped.join(";") + equipped.join(";"), + menu.player_sounds.join(";") ); if menu.kind() != Kind::Lectern { return line; @@ -171,6 +172,7 @@ fn main() -> horizon_client::Result<()> { }); menu.drops.clear(); menu.equipped.clear(); + menu.player_sounds.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { let slot = op[0].as_i64().unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs new file mode 100644 index 000000000..8658b5815 --- /dev/null +++ b/crates/horizon-client/src/bundle.rs @@ -0,0 +1,192 @@ +//! `BundleContents.Mutable`: what a bundle takes in and gives back, by +//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click +//! overrides on it. +use crate::items::{ItemStack, Items}; +use horizon_world::nbt::Tag; + +/// A bundle weight: vanilla's `Fraction`, exact and kept reduced. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Weight { + n: i128, + d: i128, +} + +fn gcd(a: i128, b: i128) -> i128 { + let (mut a, mut b) = (a.abs(), b.abs()); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +impl Weight { + const ZERO: Self = Self { n: 0, d: 1 }; + const ONE: Self = Self { n: 1, d: 1 }; + + fn new(n: i128, d: i128) -> Self { + let g = gcd(n, d); + Self { n: n / g, d: d / g } + } + + fn add(self, o: Self) -> Self { + Self::new(self.n * o.d + o.n * self.d, self.d * o.d) + } + + fn sub(self, o: Self) -> Self { + self.add(Self { n: -o.n, d: o.d }) + } + + fn times(self, count: u32) -> Self { + Self::new(self.n * i128::from(count), self.d) + } + + /// `this.divideBy(item).intValue()` (truncated), at least 0. + fn how_many(self, item: Self) -> u32 { + let q = (self.n * item.d) / (self.d * item.n); + u32::try_from(q.max(0)).unwrap_or(u32::MAX) + } +} + +/// The sounds of `BundleItem` (`Entity.playSound` at the player): insert +/// and remove one at volume 0.8 and pitch `0.8 + random * 0.4`, a failed +/// insert at 1, 1. +pub const INSERT: &str = "minecraft:item.bundle.insert"; +pub const INSERT_FAIL: &str = "minecraft:item.bundle.insert_fail"; +pub const REMOVE_ONE: &str = "minecraft:item.bundle.remove_one"; + +fn max_stack(items: &Items, stack: &ItemStack) -> u32 { + items.get(&stack.item).map_or(64, |i| i.max_stack).max(1) +} + +/// The stack's `bundle_contents`, when it has the component. +fn contents_of<'a>(items: &Items, stack: &'a ItemStack) -> Option<&'a [ItemStack]> { + let inside = stack.data().map_or(&[][..], |d| &d.bundle_contents[..]); + let bundle = items.get(&stack.item).is_some_and(|i| i.bundle); + (bundle || !inside.is_empty()).then_some(inside) +} + +/// `BundleContents.getWeight`: a nested bundle weighs its contents plus +/// 1/16, a beehive with bees 1, the rest 1 / max stack size. +fn item_weight(items: &Items, stack: &ItemStack) -> Weight { + if let Some(inside) = contents_of(items, stack) { + return contents_weight(items, inside).add(Weight::new(1, 16)); + } + let bees = stack + .data() + .and_then(|d| d.other("minecraft:bees")) + .is_some_and(|b| matches!(b, Tag::List(l) if !l.is_empty())); + if bees { + Weight::ONE + } else { + Weight::new(1, i128::from(max_stack(items, stack))) + } +} + +fn contents_weight(items: &Items, inside: &[ItemStack]) -> Weight { + inside.iter().fold(Weight::ZERO, |w, s| { + w.add(item_weight(items, s).times(s.count)) + }) +} + +/// `BundleContents.canItemBeInBundle`: shulker boxes don't fit. +pub fn can_be_in_bundle(stack: &ItemStack) -> bool { + stack.count > 0 && !stack.item.ends_with("shulker_box") +} + +/// `BundleContents.Mutable`. +pub struct Contents { + items: Vec, + weight: Weight, +} + +impl Contents { + /// The bundle's contents; None when the stack is no bundle. + pub fn of(items: &Items, stack: &ItemStack) -> Option { + let inside = contents_of(items, stack)?.to_vec(); + let weight = contents_weight(items, &inside); + Some(Self { + items: inside, + weight, + }) + } + + /// `getMaxAmountToAdd` for `stack`'s kind of item. + pub fn room_for(&self, items: &Items, stack: &ItemStack) -> u32 { + Weight::ONE + .sub(self.weight) + .how_many(item_weight(items, stack)) + } + + /// `tryInsert`: what fits moves to the front, merged with its kind. + pub fn try_insert(&mut self, items: &Items, stack: &mut ItemStack) -> u32 { + if !can_be_in_bundle(stack) { + return 0; + } + let weight = item_weight(items, stack); + let amount = stack + .count + .min(Weight::ONE.sub(self.weight).how_many(weight)); + if amount == 0 { + return 0; + } + self.weight = self.weight.add(weight.times(amount)); + // ItemStack.isStackable: a damaged stack is damageable. + let stackable = max_stack(items, stack) > 1 && stack.damage == 0; + let same = self + .items + .iter() + .position(|s| stackable && s.same_item_same_components(stack)); + let added = match same { + Some(i) => { + let mut merged = self.items.remove(i); + merged.count += amount; + stack.count -= amount; + merged + } + None => { + let mut part = stack.clone(); + part.count = amount; + stack.count -= amount; + part + } + }; + self.items.insert(0, added); + amount + } + + /// `removeOne`: the first stack (Horizon keeps no selected item). + pub fn remove_one(&mut self, items: &Items) -> Option { + if self.items.is_empty() { + return None; + } + let stack = self.items.remove(0); + self.weight = self + .weight + .sub(item_weight(items, &stack).times(stack.count)); + Some(stack) + } + + /// `toImmutable`, written back into the bundle's component. + pub fn store(self, bundle: &mut ItemStack) { + bundle.data_mut().bundle_contents = self.items; + bundle.tidy(); + } +} + +#[cfg(test)] +mod tests { + use super::Weight; + + #[test] + fn weights_add_up_exactly() { + let w = Weight::new(1, 64) + .times(32) + .add(Weight::new(1, 16).times(4)); + assert_eq!(w, Weight::new(3, 4)); + assert_eq!(Weight::ONE.sub(w).how_many(Weight::new(1, 64)), 16); + assert_eq!(Weight::ONE.sub(Weight::ONE).how_many(Weight::ONE), 0); + // An over-full bundle (made by a command) has no room. + let over = Weight::ONE.sub(Weight::new(5, 4)); + assert_eq!(over.how_many(Weight::new(1, 64)), 0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 03854e9f8..b311f6d9d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5481,6 +5481,20 @@ impl Game<'_> { Some(true) }) } + /// A sound a menu click made the player play (a bundle's insert or + /// remove): `Entity.playSound` at the player. + pub(super) fn player_menu_sound(&mut self, sound: &str) { + let Some(p) = self.player.as_ref() else { + return; + }; + let at = [p.position.x, p.position.y, p.position.z]; + let (volume, pitch) = if sound == horizon_client::bundle::INSERT_FAIL { + (1.0, 1.0) + } else { + (0.8, 0.8 + self.world.random.next_float() * 0.4) + }; + self.audio.play(sound, Some(at), volume, pitch); + } /// The open menu as the verified engine (`horizon_client::menu`): the /// game's slots are copied in, `run` acts on it, and the slots, carried /// stack, menu data and drops are copied back when it returns Some(true) @@ -5870,6 +5884,11 @@ impl Game<'_> { let carried = menu.carried.take(); let dropped = std::mem::take(&mut menu.dropped); let sounds = std::mem::take(&mut menu.sounds); + // A bundle's sounds are the player's own (`Entity.playSound`): the + // client plays them as it clicks, predicting or not. + for sound in std::mem::take(&mut menu.player_sounds) { + self.player_menu_sound(sound); + } let crafted = std::mem::take(&mut menu.crafted); let equipped = std::mem::take(&mut menu.equipped); for (i, stack) in after.into_iter().enumerate() { @@ -6114,6 +6133,17 @@ impl Game<'_> { } return; } + // mouseClicked: an empty hand's PICKUP is the menu's click at once + // (a right click on a bundle takes its first stack out). + if let (Some(input), Some(_)) = (input, slot) + && self.remote.is_none() + && self.menu_click(slot, i32::from(right), input) + { + if let Some(key) = self.container { + self.container_changed(key); + } + return; + } self.click_inventory(right); } /// Mouse movement while a quick craft drag is running. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 19c3a9a6c..5d80d4767 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -160,6 +160,9 @@ impl GuestPlay { struct ItemRules<'a>(&'a horizon_client::items::Items); impl Rules for ItemRules<'_> { + fn items(&self) -> &horizon_client::items::Items { + self.0 + } fn max_stack(&self, item: &str) -> u32 { self.0.get(item).map_or(64, |i| i.max_stack) } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index ab9c98804..abbc1241f 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -120,6 +120,8 @@ pub struct ItemInfo { pub dye: Option, /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. pub block_transformer: Option, + /// Has a default `bundle_contents` (the bundles, `BundleItem`). + pub bundle: bool, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -593,6 +595,7 @@ impl Items { jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), + bundle: c.get("minecraft:bundle_contents").is_some(), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index d37874bc8..de9fb9608 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -4,10 +4,15 @@ //! clone, throw, quick craft (drag) and pickup all; items thrown out of a //! menu are returned for the game to drop. use super::guest::Guest; -use crate::{items::ItemStack, world::World}; +use crate::{ + bundle::{Contents, can_be_in_bundle}, + items::{ItemStack, Items}, + world::World, +}; /// What the menus need to know about items. pub trait Rules { + fn items(&self) -> &Items; fn max_stack(&self, item: &str) -> u32; /// The armor slot (0 head .. 3 feet) an item can be worn in. fn armor_index(&self, item: &str) -> Option; @@ -364,6 +369,9 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { return; } let right = button == 1; + if bundle_click(view, i, right, rules) { + return; + } let (slot_item, carried) = (view.get(i), view.guest.carried.clone()); match (slot_item, carried) { (None, None) => {} @@ -410,6 +418,84 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { } } +/// `tryItemClickBehaviourOverride`: the carried stack's +/// `BundleItem.overrideStackedOnOther`, then the clicked one's +/// `overrideOtherStackedOnMe`. True when a bundle took the click. +fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bool { + let items = rules.items(); + let other = view.get(i); + if let Some(mut carried) = view.guest.carried.clone() + && let Some(mut contents) = Contents::of(items, &carried) + && other.is_some() != right + { + match other { + // tryTransfer: as much as fits, through `safeTake`. + Some(mut other) => { + if can_be_in_bundle(&other) { + let amount = other.count.min(contents.room_for(items, &other)); + if amount > 0 { + let mut taken = other.clone(); + taken.count = amount; + other.count -= amount; + view.set(i, (other.count > 0).then_some(other)); + contents.try_insert(items, &mut taken); + } + } + } + // removeOne into the empty slot (`safeInsert`); the rest goes back. + None => { + if let Some(mut stack) = contents.remove_one(items) { + if view.may_place(i, &stack, rules) { + let amount = stack.count.min(view.slot_max(i, &stack, rules)); + view.set( + i, + Some(ItemStack { + count: amount, + ..stack.clone() + }), + ); + stack.count -= amount; + } + if stack.count > 0 { + contents.try_insert(items, &mut stack); + } + } + } + } + contents.store(&mut carried); + view.guest.carried = Some(carried); + return true; + } + let Some(mut bundle) = other else { + return false; + }; + let Some(mut contents) = Contents::of(items, &bundle) else { + return false; + }; + // Slot.allowModification: mayPickup and mayPlace of its item. + let allowed = view.may_place(i, &bundle, rules); + match (view.guest.carried.take(), right) { + (Some(mut carried), false) => { + if allowed { + contents.try_insert(items, &mut carried); + } + view.guest.carried = (carried.count > 0).then_some(carried); + } + (None, true) => { + if allowed { + view.guest.carried = contents.remove_one(items); + } + } + (carried, _) => { + view.guest.carried = carried; + return false; + } + } + contents.store(&mut bundle); + view.set(i, Some(bundle)); + true +} + fn swap(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { let Ok(i) = usize::try_from(slot) else { return; @@ -538,3 +624,116 @@ fn quick_craft( } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::lan::{Joined, PlayerSender}; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{Arc, atomic::AtomicI32, mpsc}; + + struct ItemRules(Items); + impl Rules for ItemRules { + fn items(&self) -> &Items { + &self.0 + } + fn max_stack(&self, item: &str) -> u32 { + self.0.get(item).map_or(64, |i| i.max_stack) + } + fn armor_index(&self, _: &str) -> Option { + None + } + } + + fn guest() -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: 2, + uuid: 2, + name: "Alex".into(), + properties: Vec::new(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender::new(tx, Arc::default()), + latency: Arc::new(AtomicI32::new(0)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + 2, + [0.0, 64.0, 0.0], + 8, + ) + } + + fn contents(stack: &Option) -> Vec<(String, u32)> { + let inside = stack.as_ref().and_then(|s| s.data()); + inside.map_or(Vec::new(), |d| { + d.bundle_contents + .iter() + .map(|s| (s.item.to_string(), s.count)) + .collect() + }) + } + + /// A guest's chest clicks run `BundleItem`'s overrides: a carried + /// bundle takes a slot's stack and drops its first one into an empty + /// slot; a stack clicked onto a bundle goes in, as far as it fits. + #[test] + fn guest_chest_clicks_fill_and_empty_bundles() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION) + }); + if !root.join("items.json").exists() { + eprintln!("skipping resource-backed bundle check: {}", root.display()); + return; + } + let registry = horizon_world::level::data::load_registry(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, ®istry).unwrap(); + let rules = ItemRules(Items::load(&root, ®istry, &facts).unwrap()); + let mut g = guest(); + let mut chest = vec![ + Some(ItemStack::new("minecraft:stone", 48)), + None, + Some(ItemStack::new("minecraft:bundle", 1)), + ]; + let mut drag = None; + let mut view = View { + guest: &mut g, + container: Some(&mut chest), + }; + view.guest.carried = Some(ItemStack::new("minecraft:bundle", 1)); + // Left click with the bundle: the stone goes in. + click(&mut view, &mut drag, 0, 0, input::PICKUP, &rules); + assert_eq!(view.get(0), None); + assert_eq!( + contents(&view.guest.carried), + [("minecraft:stone".into(), 48)] + ); + // Right click on an empty slot: the stone comes back out. + click(&mut view, &mut drag, 1, 1, input::PICKUP, &rules); + assert_eq!(view.get(1).map(|s| s.count), Some(48)); + assert_eq!(contents(&view.guest.carried), []); + // Ender pearls (1/16 each) onto the bundle in the chest: 16 fit. + view.guest.carried = Some(ItemStack::new("minecraft:ender_pearl", 16)); + click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules); + assert_eq!(view.guest.carried, None); + let bundle = view.get(2); + assert_eq!(contents(&bundle), [("minecraft:ender_pearl".into(), 16)]); + // Full: more stone stays in hand. + view.guest.carried = Some(ItemStack::new("minecraft:stone", 5)); + click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules); + assert_eq!(view.guest.carried.as_ref().map(|s| s.count), Some(5)); + // Right click on it with an empty hand takes the pearls out. + view.guest.carried = None; + click(&mut view, &mut drag, 2, 1, input::PICKUP, &rules); + assert_eq!( + view.guest.carried.as_ref().map(|s| (&*s.item, s.count)), + Some(("minecraft:ender_pearl", 16)) + ); + assert_eq!(contents(&view.get(2)), []); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1f04a89f0..dddf87c0d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -27,6 +27,7 @@ pub mod border_render; pub mod bossbar; pub mod breaking; pub mod brewing; +pub mod bundle; pub mod camera; pub mod cauldron; pub mod chat; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index cdaf73eed..be35c9bae 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -16,6 +16,7 @@ use crate::{ }; use std::sync::Arc; +mod bundle; pub mod place; /// What a menu needs to know about items and recipes. @@ -276,6 +277,9 @@ pub struct Menu { pub loom_patterns: Vec>, /// Sounds the menu plays (`ui.loom.take_result`), for the caller. pub sounds: Vec<&'static str>, + /// Sounds the player makes (a bundle's insert and remove), for the + /// caller to play at the player as `Entity.playSound`. + pub player_sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, /// `LivingEntity.onEquipItem` calls that change the item: the @@ -671,6 +675,7 @@ impl Menu { quick_slots: Vec::new(), loom_patterns: Vec::new(), sounds: Vec::new(), + player_sounds: Vec::new(), crafted: Vec::new(), equipped: Vec::new(), merchant: None, @@ -2536,10 +2541,12 @@ impl Menu { Ok(()) } - /// The PICKUP branch of `doClick` (without the bundle overrides), ending - /// with `slot.setChanged()`. + /// The PICKUP branch of `doClick`: a bundle's override, else the + /// plain click, ending with `slot.setChanged()`. fn pickup(&mut self, env: &Env, s: usize, primary: bool) { - self.pickup_inner(env, s, primary); + if !self.bundle_click(env, s, primary) { + self.pickup_inner(env, s, primary); + } self.slot_changed(env, s); } diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs new file mode 100644 index 000000000..3bbcfe9cd --- /dev/null +++ b/crates/horizon-client/src/menu/bundle.rs @@ -0,0 +1,95 @@ +//! `BundleItem`'s click overrides in a PICKUP click +//! (`tryItemClickBehaviourOverride`). +use super::{Env, Menu, tidy}; +use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle}; + +impl Menu { + /// The carried stack's `overrideStackedOnOther`, then the clicked + /// one's `overrideOtherStackedOnMe`. True when a bundle took the click. + pub(super) fn bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + self.carried_bundle_click(env, s, primary) || self.clicked_bundle_click(env, s, primary) + } + + /// `BundleItem.overrideStackedOnOther`: the carried bundle on a slot. + fn carried_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let Some(mut contents) = self + .carried + .as_ref() + .and_then(|c| Contents::of(env.items, c)) + else { + return false; + }; + match (self.slot(s).cloned(), primary) { + (Some(other), true) => { + // tryTransfer: what fits, taken by the slot's rules. + let mut moved = 0; + if can_be_in_bundle(&other) { + let room = contents.room_for(env.items, &other); + if let Some(mut taken) = self.safe_take(env, s, other.count, room) { + moved = contents.try_insert(env.items, &mut taken); + } + } + self.player_sounds + .push(if moved > 0 { INSERT } else { INSERT_FAIL }); + } + (None, false) => { + if let Some(stack) = contents.remove_one(env.items) { + let count = stack.count; + let mut remainder = Some(stack); + self.safe_insert(env, s, &mut remainder, count); + match remainder { + Some(mut rest) => { + contents.try_insert(env.items, &mut rest); + } + None => self.player_sounds.push(REMOVE_ONE), + } + } + } + _ => return false, + } + if let Some(carried) = self.carried.as_mut() { + contents.store(carried); + } + true + } + + /// `BundleItem.overrideOtherStackedOnMe`: a click on a bundle in a slot. + fn clicked_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let Some(mut bundle) = self.slot(s).cloned() else { + return false; + }; + let Some(mut contents) = Contents::of(env.items, &bundle) else { + return false; + }; + let allowed = self.allow_modification(env, s); + match (self.carried.take(), primary) { + (Some(mut other), true) => { + let moved = if allowed { + contents.try_insert(env.items, &mut other) + } else { + 0 + }; + self.player_sounds + .push(if moved > 0 { INSERT } else { INSERT_FAIL }); + self.carried = Some(other); + tidy(&mut self.carried); + } + (None, false) => { + if allowed && let Some(removed) = contents.remove_one(env.items) { + self.player_sounds.push(REMOVE_ONE); + self.carried = Some(removed); + } + } + (carried, _) => { + // toggleSelectedItem(-1): Horizon keeps no selected item. + self.carried = carried; + return false; + } + } + // `self.set(BUNDLE_CONTENTS, ...)` changes the slot's stack in place. + contents.store(&mut bundle); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = Some(bundle); + true + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 9b4e6e8f5..3c7de61ef 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -37,6 +37,9 @@ public final class VanillaMenuOracle { static final List drops = new ArrayList<>(); /** onEquipItem calls that change the item (its sound and game event): slot and new stack. */ static final List equips = new ArrayList<>(); + /** The sounds the player played ({@code Entity.playSound}: a bundle's insert and remove). */ + static final List sounds = new ArrayList<>(); + static final net.minecraft.util.RandomSource soundRandom = net.minecraft.util.RandomSource.create(0L); /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; /** The block entity behind a "lectern" menu. */ @@ -99,6 +102,8 @@ public final class VanillaMenuOracle { @Override public void scheduleTick(BlockPos pos, net.minecraft.world.level.block.Block block, int delay) { } @Override public void updateNeighborsAt(BlockPos pos, net.minecraft.world.level.block.Block block, net.minecraft.world.level.redstone.Orientation o) { } @Override public void playSound(net.minecraft.world.entity.Entity e, BlockPos pos, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { } + // A bundle sound's pitch: 0.8 + level.getRandom().nextFloat() * 0.4. + @Override public net.minecraft.util.RandomSource getRandom() { return soundRandom; } } /** The maps of the case's level, by id, and the next free id. */ @@ -127,6 +132,9 @@ public final class VanillaMenuOracle { if (!ItemStack.isSameItemSameComponents(old, now)) equips.add(slot.getName() + ":" + ParityData.canon(now)); } @Override public boolean hasDisconnected() { return false; } + @Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { + sounds.add(sound.location().toString()); + } @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); return null; @@ -251,9 +259,9 @@ public final class VanillaMenuOracle { // No inventory slots: the inventory Take Book fills. StringBuilder items = new StringBuilder(); for (int i = 0; i < 36; i++) items.append(' ').append(ParityData.canon(inv.getItem(i))); - return state(menu, inv) + " | " + String.join(";", equips) + " | inv" + items; + return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds) + " | inv" + items; } - return state(menu, inv) + " | " + String.join(";", equips); + return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds); } public static void main(String[] args) throws Exception { @@ -271,6 +279,7 @@ public final class VanillaMenuOracle { try { drops.clear(); equips.clear(); + sounds.clear(); var world = make(World.class); world.server = make(Server.class); var player = make(FakePlayer.class); @@ -325,6 +334,7 @@ public final class VanillaMenuOracle { for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); equips.clear(); + sounds.clear(); out.println("init " + clickState(menu, inv)); for (var opJson : f.getAsJsonArray("ops")) { var op = opJson.getAsJsonArray(); diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 4e34b39cc..e1998e579 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -22,8 +22,10 @@ results, and the scaled and locked copies a take makes), the lectern (over the block entity: its page buttons, clamped to the book's pages, and Take Book, with the inventory compared too) and the server's furnace menus over their block entities (`*_be`: a new input restarts -cooking, other clicks keep its progress). After -every click the slots, carried stack, data slots and drops are compared. +cooking, other clicks keep its progress). Bundles (empty, partly and fully +loaded, nested) are among the stacks and often in hand, for BundleItem's click +overrides. After every click the slots, carried stack, data slots, drops and +the player's sounds are compared. """ import argparse import json @@ -37,6 +39,8 @@ except ImportError: MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, 'cartography': 39, 'lectern': 1, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} +# Where a carried bundle is common: the containers that hold anything. +BUNDLE_MENUS = {'inventory', 'chest1', 'chest3', 'shulker', 'hopper', 'dispenser'} DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, 'stonecutter': 1, 'enchanting': 10, 'beacon': 3, 'lectern': 1, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} @@ -91,8 +95,10 @@ def snbt(item, count, damage=0, curse=False, potion=None): class Gen: - def __init__(self, rng, items): + def __init__(self, rng, items, bundles=None): self.rng = rng + # Bundles come from their own generator, so the other stacks stay as they were. + self.bundles = bundles or random.Random(0) self.items = items self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items] self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k @@ -108,7 +114,37 @@ class Gen: damage = rng.randrange(1, info['minecraft:max_damage']) count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None - return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) + stack = snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) + return self.bundle() if self.bundles.random() < 0.06 else stack + + def bundle(self, room=64): + """A bundle, empty or holding up to its weight (in 64ths: 1 per item of a + 64-stack, 4 of a 16-stack, 64 of a tool), now and then another bundle.""" + return self.loaded_bundle(room)[0] + + def loaded_bundle(self, room): + rng = self.bundles + color = rng.choice(['', '', 'red_', 'light_blue_']) + inside, used = [], 0 + for _ in range(rng.choice([0, 0, 1, 1, 2, 3, 5])): + if room == 64 and rng.random() < 0.1: + # A nested bundle weighs its contents plus 1/16. + if room - used > 4: + nested, weight = self.loaded_bundle(min(room - used - 4, 16)) + inside.append(nested) + used += weight + 4 + continue + item = rng.choice(self.pool) + top = self.items[item].get('minecraft:max_stack_size', 64) + unit = 64 // top + if unit > room - used or 'shulker_box' in item: + continue + most = min(top, (room - used) // unit) + count = min(most, rng.choice([1, 1, 2, rng.randrange(1, most + 1)])) + used += count * unit + inside.append(snbt(item, count)) + body = ',components:{"minecraft:bundle_contents":[%s]}' % ','.join(inside) if inside else '' + return '{id:"minecraft:%sbundle",count:1%s}' % (color, body), used def slots(self, size, density): return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] @@ -333,7 +369,7 @@ def main(): vanilla.compile('ParityData', 'VanillaMenuOracle') items = json.loads((lib.RESOURCES / 'items.json').read_text()) rng = random.Random(args.seed) - g = Gen(rng, items) + g = Gen(rng, items, random.Random(args.seed + 1)) cases = [] chosen = args.menus.split(',') if args.menus else list(MENUS) for n in range(args.cases): @@ -442,6 +478,9 @@ def main(): 'anvil': g.anvil_stack, 'smithing': g.smith_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' if carried_food is not None: carried = carried_food + elif menu in BUNDLE_MENUS and g.bundles.random() < 0.3: + # A bundle in hand, emptied into slots and filled from them. + carried = g.bundle() if menu == 'lectern': carried = '-' extra = {} From 8acb46756bca113619cc50b106b2f5012383b632 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:41 +0200 Subject: [PATCH 13/19] Bundle clicks: the open menu's slotsChanged for the player's inventory BundleItem.broadcastChangesOnContainerMenu calls slotsChanged(player inventory) after a bundle click. The menus that don't check which container changed recompute from their inputs (crafting grids, loom, stonecutter, cartography, merchant, smithing's hasRecipeError). The menu click harness found it on a loom with a fixture result: 8000/8000 cases now match (seeds 7 and 11). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/menu.rs | 17 +++++++++++++++++ crates/horizon-client/src/menu/bundle.rs | 9 ++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index be35c9bae..07e4ba2b9 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -936,6 +936,23 @@ impl Menu { } } + /// `slotsChanged(player.getInventory())`, which a bundle click calls + /// (`BundleItem.broadcastChangesOnContainerMenu`): the menus that don't + /// check which container changed recompute from their inputs. + fn inventory_slots_changed(&mut self, env: &Env) { + match self.kind { + Kind::Inventory | Kind::Crafting => self.recompute(env), + Kind::Loom => self.loom_changed(env), + Kind::Stonecutter => self.stone_changed(env), + Kind::Cartography => self.carto_changed(env), + Kind::Merchant => self.merchant_update(env), + // ItemCombinerMenu.slotsChanged only for its inputs; the + // smithing table's hasRecipeError always. + Kind::Smithing => self.smith_error(), + _ => {} + } + } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and /// the levels (creative pays nothing). The enchanting itself needs a /// level and is the caller's (`enchant_button`). diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs index 3bbcfe9cd..fba4a488e 100644 --- a/crates/horizon-client/src/menu/bundle.rs +++ b/crates/horizon-client/src/menu/bundle.rs @@ -7,7 +7,14 @@ impl Menu { /// The carried stack's `overrideStackedOnOther`, then the clicked /// one's `overrideOtherStackedOnMe`. True when a bundle took the click. pub(super) fn bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { - self.carried_bundle_click(env, s, primary) || self.clicked_bundle_click(env, s, primary) + let took = self.carried_bundle_click(env, s, primary) + || self.clicked_bundle_click(env, s, primary); + if took { + // broadcastChangesOnContainerMenu: the open menu's + // slotsChanged for the player's inventory. + self.inventory_slots_changed(env); + } + took } /// `BundleItem.overrideStackedOnOther`: the carried bundle on a slot. From c89695dd93207ad855cd8e5ca07368ecbb17bd95 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:01:32 +0200 Subject: [PATCH 14/19] lan_e2e hands: shoot the cow with a half drawn bow so it lives A fully drawn bow fires a crit arrow: AbstractArrow.onHitEntity adds random.nextInt(damage / 2 + 2) to the 6 damage, so one shot in five does 10 and kills the 10 health cow. The off hand bucket then had nothing to milk ("the host's off hand holds minecraft:bucket"), on either side, in any mode. Under 20 ticks of draw the arrow is no crit and does at most 6. The check now also asserts the cow is still there after the shot. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 61ffe1f8e..73b93a159 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -3703,13 +3703,18 @@ def check_hands(host, guest, out): player.raw('select', 'minecraft:bow') aim_cow() assert player('looking_at')['kind'] == 'entity', f'the {label} does not aim at the cow' + # Half drawn: a full draw is a crit, up to 10 damage (AbstractArrow.onHitEntity), which + # kills the 10 health cow one shot in five. Under 20 ticks the arrow does at most 6. player.raw('mouse', 'right', 'down') - player.wait(25) + player.wait(10) drawn = player('state')['using'] player.raw('mouse', 'right', 'up') player.wait(20) assert drawn, f'the {label}\'s bow is not drawn at the cow' assert counts().get('minecraft:arrow') == 5, f'the {label} shot no arrow: {counts()}' + aim_cow() + cow = player('looking_at').get('entity') or {} + assert cow.get('health', 0) > 0, f'the {label}\'s arrow killed the cow: {cow}' player('command', command='clear @s') player('command', command='give @s minecraft:golden_apple') player.wait(5) From 4daa91cf520156ccf3dd4051a17da44a966e8fed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:15:06 +0200 Subject: [PATCH 15/19] Wind charges push a server's players: the burst's packet carries each one's push A wind charge's burst (ServerExplosion with TRIGGER_BLOCK) pushed only the game's own player, so a LAN guest, and single player's window on its server thread, never rose (#1386). The burst now pushes every player in reach, each swapped in as the player, and sends ClientboundExplodePacket to the players within 64 blocks with the push it gave them (hitPlayers), which their client adds (Entity.pushFromExplosion); onExplosionHit's fall-damage grace goes on the server's body. A burst from a guest's own turn (their charge landing, their mace's wind burst) waits for the turn to end, so that it reaches the host and the other guests too. The packet's centre particle is the gust emitter and it throws no block particles, as WindCharge.explode asks; the client now draws the packet's own particle. Explosion knockback resistance lowers the player's push as in vanilla, and a guest's body knows whether it flies (no push while flying in creative). lan_e2e wind: host and guest each throw a charge at their feet, rise about six blocks and land unhurt, in both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 4 +- crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 1 + .../horizon-client/src/game/lan_particles.rs | 144 +++++++++++++---- crates/horizon-client/src/game/wind.rs | 153 +++++++++++++----- crates/horizon-client/src/particles.rs | 10 ++ tools/lan_e2e.py | 53 ++++++ 7 files changed, 297 insertions(+), 70 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 442c37237..70a4009b8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -47,6 +47,8 @@ pub(super) struct Creatures { pub pearl_cooldown: u32, /// The wind charge's use cooldown (ticks). pub wind_cooldown: u32, + /// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs). + pub wind_bursts: Vec, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. @@ -1778,7 +1780,7 @@ impl Game<'_> { _ => self.projectile_hit(&p, hit)?, } } - Ok(()) + self.flush_wind_bursts() } /// `projectile_hit` for a projectile the guest `conn` shot, run as them; /// as the host's when they have left. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 00c5c3433..bab304569 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1011,6 +1011,8 @@ impl Game<'_> { drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); + // A mace's wind burst from a guest's attack. + let _ = self.flush_wind_bursts(); } fn lan_guest_joined( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index cabddcf39..2c2c25e93 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -258,6 +258,7 @@ impl Game<'_> { motion.pitch = g.pitch; motion.sprinting = g.sprinting; motion.may_fly = g.creative() || g.game_mode == SPECTATOR; + motion.flying = g.flying; motion.invulnerable = motion.may_fly; let _ = motion.set_health(g.health, false); motion.health.food.food = g.food; diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 2cacfabdb..1efb4ac58 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -3,7 +3,7 @@ //! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). use super::Game; use horizon_client::particles::{ParticleOptions, ParticleType}; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ entity_data::{Particle, ParticleData}, packets::play::{self, Clientbound as C}, @@ -154,7 +154,7 @@ impl Game<'_> { } /// `ClientPacketListener.handleExplosion`: the blast's particles (and its - /// sound, when the packet carries it). + /// sound, when the packet carries it), then the player's push. pub(super) fn remote_explode(&mut self, p: &play::Explode) { if p.play_sound { let pitch = (1.0 @@ -168,37 +168,88 @@ impl Game<'_> { pitch, ); } - let (world, facts) = (&self.world, self.res.facts()); - self.particles - .explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| { - facts.is_air(world.block(b[0], b[1], b[2])) - }); + if let Some(options) = self.received_particle(&p.particle, p.center) { + self.particles.add(&options, p.center, [1.0, 0.0, 0.0]); + } + // A wind charge's burst throws none. + if !p.block_particles.is_empty() { + let (world, facts) = (&self.world, self.res.facts()); + self.particles.explosion_blocks( + p.center, + p.radius, + p.block_count.max(0) as usize, + &|b| facts.is_air(world.block(b[0], b[1], b[2])), + ); + } + // Entity.pushFromExplosion. + if let (Some(push), Some(player)) = (p.knockback, self.player.as_mut()) { + player.velocity = Vec3::new( + player.velocity.x + push[0], + player.velocity.y + push[1], + player.velocity.z + push[2], + ); + } } /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the - /// players' motion), so the packet carries neither. + /// motion a hurt player is sent), so the packet carries neither. pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { - let Some(host) = self.lan.as_ref() else { - return; - }; - let particle = |name: &str| { - Some(Particle { - id: host.hub.registry_id("minecraft:particle_type", name)?, - data: None, - }) - }; let emitter = if radius < 2.0 { "minecraft:explosion" } else { "minecraft:explosion_emitter" }; - let (Some(at_center), Some(poof), Some(smoke)) = ( - particle(emitter), - particle("minecraft:poof"), - particle("minecraft:smoke"), - ) else { - return; + let sound = "minecraft:entity.generic.explode"; + if let Some(packet) = + self.explosion_packet(center, radius, block_count, emitter, sound, true) + { + self.send_explosion(packet, &[]); + } + } + + /// A wind charge's burst (`AbstractWindCharge.explode`): gust emitters, + /// no block particles, and for each player it pushed the push + /// (`ServerExplosion.hitPlayers`), which only that client applies, as + /// nothing hurt them. + pub(super) fn lan_wind_burst( + &self, + center: [f64; 3], + radius: f32, + sound: &str, + block_count: usize, + pushed: &[(u32, [f64; 3])], + ) { + let emitter = if radius < 2.0 { + "minecraft:gust_emitter_small" + } else { + "minecraft:gust_emitter_large" + }; + if let Some(packet) = + self.explosion_packet(center, radius, block_count, emitter, sound, false) + { + self.send_explosion(packet, pushed); + } + } + + /// `ClientboundExplodePacket` without a push, or None while not serving. + /// The sound is the level's, which the players hear already, so it isn't + /// played from the packet. + fn explosion_packet( + &self, + center: [f64; 3], + radius: f32, + block_count: usize, + emitter: &str, + sound: &str, + block_particles: bool, + ) -> Option { + let hub = &self.lan.as_ref()?.hub; + let particle = |name: &str| { + Some(Particle { + id: hub.registry_id("minecraft:particle_type", name)?, + data: None, + }) }; // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES. let info = |particle, scaling| play::ExplosionParticle { @@ -207,22 +258,49 @@ impl Game<'_> { speed: 1.0, weight: 1, }; - let packet = C::Explode(play::Explode { + let block_particles = if block_particles { + vec![ + info(particle("minecraft:poof")?, 0.5), + info(particle("minecraft:smoke")?, 1.0), + ] + } else { + Vec::new() + }; + Some(play::Explode { center, radius, block_count: block_count as i32, knockback: None, - particle: at_center, - sound: match host - .hub - .registry_id("minecraft:sound_event", "minecraft:entity.generic.explode") - { + particle: particle(emitter)?, + sound: match hub.registry_id("minecraft:sound_event", sound) { Some(id) => (id, None), - None => (-1, Some(("minecraft:entity.generic.explode".into(), None))), + None => (-1, Some((sound.into(), None))), }, - block_particles: vec![info(poof, 0.5), info(smoke, 1.0)], + block_particles, play_sound: false, - }); - host.hub.broadcast_near(center, 64.0, &packet, None); + }) + } + + /// `packet` to each player within 64 blocks of its centre, with the push + /// `pushed` holds for them. + fn send_explosion(&self, mut packet: play::Explode, pushed: &[(u32, [f64; 3])]) { + let Some(host) = self.lan.as_ref() else { + return; + }; + let center = packet.center; + let plain = C::Explode(packet.clone()).encode(); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + let d: f64 = (0..3).map(|k| (g.position[k] - center[k]).powi(2)).sum(); + if d >= 4096.0 { + continue; + } + match pushed.iter().find(|(conn, _)| *conn == g.conn) { + Some((_, push)) => { + packet.knockback = Some(*push); + g.send(&C::Explode(packet.clone())); + } + None => g.sender.send(plain.clone()), + } + } } } diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 72e6ee0e8..0754bca8b 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -22,6 +22,14 @@ const PLAYER_KNOCKBACK: f32 = 1.22; /// `BreezeWindCharge.RADIUS`. const BREEZE_RADIUS: f32 = 3.0; +/// A burst `wind_burst` puts off until a guest's turn is over. +pub(super) struct Burst { + center: [f64; 3], + radius: f32, + multiplier: f32, + breeze: bool, + wind_charge: bool, +} /// `Projectile.deflect` with `ProjectileDeflection.REVERSE`. pub(super) fn reverse(p: &mut Projectile, jitter: f32) { p.velocity = Vec3::new( @@ -196,7 +204,9 @@ impl Game<'_> { set.into_iter().collect() } /// `ServerExplosion.hurtEntities` for a calculator that damages nothing: - /// knockback scaled by distance, exposure and the multiplier. + /// knockback scaled by distance, exposure and the multiplier. Returns the + /// guests it pushed and by how much (`hitPlayers`), which their clients + /// apply from the burst's packet. fn wind_knockback( &mut self, center: [f64; 3], @@ -204,7 +214,7 @@ impl Game<'_> { multiplier: f32, wind_charge: bool, blocklike: bool, - ) { + ) -> Vec<(u32, [f64; 3])> { let diameter = f64::from(radius * 2.0); let distance = |p: [f64; 3]| { ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)) @@ -223,42 +233,30 @@ impl Game<'_> { [d[0] / l, d[1] / l, d[2] / l] } }; - let multiplier = f64::from(multiplier); - // The player (not a spectator; a flying creative player takes none). - if let Some(p) = self.player.as_ref() - && !self.spectator() - { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - let flying = self.creative && p.flying; - if dist <= 1.0 && !flying { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - let eye = [ - feet[0], - feet[1] + f64::from(p.dimensions.eye_height), - feet[2], - ]; - let exposure = self.seen_percent( - center, - [feet[0] - w, feet[1], feet[2] - w], - [feet[0] + w, feet[1] + h, feet[2] + w], - ); - let power = (1.0 - dist) * f64::from(exposure) * multiplier; - let dir = direction(eye); - if let Some(p) = self.player.as_mut() { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - // ServerPlayer.onExplosionHit: a wind charge's burst cancels the - // fall; any other burst ends the grace of the last impulse. - let at = p.position; - p.impulse.set_ignore_fall_damage(wind_charge, Some(at)); + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. In a guest's turn (a mace's wind + // burst) the player is that guest. + let own = self.wind_push_player(center, radius, multiplier, wind_charge); + let mut pushed: Vec<_> = self.lan_acting.zip(own).into_iter().collect(); + if let Some(mut host) = self.lan.take() { + let guests: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in guests { + let push = self.as_guest(&mut host, conn, |g| { + g.wind_push_player(center, radius, multiplier, wind_charge) + }); + if let Some(Some(push)) = push { + pushed.push((conn, push)); } } + self.lan = Some(host); } + let multiplier = f64::from(multiplier); let mut mobs = std::mem::take(&mut self.mobs); for m in mobs.iter_mut().filter(|m| m.alive()) { let feet = [m.position.x, m.position.y, m.position.z]; @@ -351,6 +349,67 @@ impl Game<'_> { push(t.position, &mut t.velocity, self); } self.tnts = tnts; + pushed + } + /// `ServerExplosion.hurtEntities` for the player (not a spectator, nor a + /// creative player flying): the push, less with explosion knockback + /// resistance, and `ServerPlayer.onExplosionHit`. Returns the push. + fn wind_push_player( + &mut self, + center: [f64; 3], + radius: f32, + multiplier: f32, + wind_charge: bool, + ) -> Option<[f64; 3]> { + if self.spectator() { + return None; + } + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let creative = self.creative; + let p = self.player.as_ref()?; + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = ((feet[0] - center[0]).powi(2) + + (feet[1] - center[1]).powi(2) + + (feet[2] - center[2]).powi(2)) + .sqrt() + / f64::from(radius * 2.0); + if dist > 1.0 || creative && p.flying { + return None; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0] - center[0], + feet[1] + f64::from(p.dimensions.eye_height) - center[1], + feet[2] - center[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let power = (1.0 - dist) * f64::from(exposure) * f64::from(multiplier) * (1.0 - resistance); + let l = (eye[0] * eye[0] + eye[1] * eye[1] + eye[2] * eye[2]).sqrt(); + let push = if l < 1.0e-5 { + [0.0; 3] + } else { + eye.map(|d| d / l * power) + }; + let p = self.player.as_mut()?; + p.velocity = Vec3::new( + p.velocity.x + push[0], + p.velocity.y + push[1], + p.velocity.z + push[2], + ); + // ServerPlayer.onExplosionHit: a wind charge's burst cancels the + // fall; any other burst ends the grace of the last impulse. + let at = p.position; + p.impulse.set_ignore_fall_damage(wind_charge, Some(at)); + Some(push) } /// The burst: knockback, the blocks that react, the gust and the sound. pub(super) fn wind_burst( @@ -361,13 +420,27 @@ impl Game<'_> { breeze: bool, wind_charge: bool, ) -> Result<()> { + // In a guest's turn (their charge landing, their mace's burst) the + // host holds the other players (`as_guest`): the burst waits for the + // turn to end so that it reaches every player, the guest too. + if self.lan_acting.is_some() && self.lan.is_none() { + self.creatures.wind_bursts.push(Burst { + center, + radius, + multiplier, + breeze, + wind_charge, + }); + return Ok(()); + } // ServerExplosion.explode: the blast is heard first. let ctx = horizon_client::sculk::Context::default(); self.post_game_event("minecraft:explode", center, ctx); let mut targets = self.wind_positions(center, radius); // ServerExplosion.shouldAffectBlocklikeEntities let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing"); - self.wind_knockback(center, radius, multiplier, wind_charge, blocklike); + let pushed = self.wind_knockback(center, radius, multiplier, wind_charge, blocklike); + let block_count = targets.len(); // Explosion.canTriggerBlocks: a breeze's charge needs mob griefing. if !breeze || self.ui.rules.bool("mob_griefing") { // Util.shuffle(list, level.random) @@ -396,6 +469,14 @@ impl Game<'_> { }; self.particles .add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + self.lan_wind_burst(center, radius, sound, block_count, &pushed); + Ok(()) + } + /// The bursts guests' turns put off. + pub(super) fn flush_wind_bursts(&mut self) -> Result<()> { + for b in std::mem::take(&mut self.creatures.wind_bursts) { + self.wind_burst(b.center, b.radius, b.multiplier, b.breeze, b.wind_charge)?; + } Ok(()) } /// `BlockBehaviour.onExplosionHit` for `TRIGGER_BLOCK`: doors, gates, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index a5df97258..c4df7d147 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1336,6 +1336,16 @@ impl ParticleEngine { ParticleType::ExplosionEmitter }; self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + self.explosion_blocks(center, radius, block_count, is_air); + } + /// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`. + pub fn explosion_blocks( + &mut self, + center: [f64; 3], + radius: f32, + block_count: usize, + is_air: &dyn Fn([i32; 3]) -> bool, + ) { for _ in 0..block_count.min(512) { let r = &mut self.random; let d = Vec3::new( diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 9b86a4934..41d39f37b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -199,6 +199,9 @@ address. The script then checks, from both sides, what a guest's game used to ge and scope with a spyglass: each use starts on their own client and on the server, and letting go ends it on both (RELEASE_USE_ITEM), so the shield lowers, the trident flies and the loaded crossbow fires on the next use (#1300, #1281, #1282, #1301). +- wind: the host and the guest each throw a wind charge at their feet: the server's burst + launches them about six blocks up (the push in ClientboundExplodePacket) and they land + unhurt (#1386). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4673,5 +4676,55 @@ CHECKS += ['helduse'] CHECK_FNS.update(helduse=check_held_use) +def check_wind(host, guest, out): + """A wind charge each player throws at its own feet (ServerExplosion with TRIGGER_BLOCK): the + server's burst pushes the thrower through its ClientboundExplodePacket (hitPlayers), which + launches it about six blocks up, and onExplosionHit spares it the fall damage where it lands + (#1386).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='gamerule natural_health_regeneration false') + seen = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 2} {hy - 1} {z - 2} {x + 2} {hy - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 2} {x + 2} {hy + 10} {z + 2} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command='give @s minecraft:wind_charge 2') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} 0 90') + game.wait(20) + start = pos_of(game)[1] + game.raw('use-item') + peak = start + for _ in range(30): + game.wait(2) + peak = max(peak, pos_of(game)[1]) + game.wait(40) + game.shot(out, 'wind') + me = own(game) + seen[game.name] = {'rose': round(peak - start, 1), + 'landed': round(me['position'][1] - start, 1), + 'health': me['health'], + 'server_health': server_player(host, game)['health'], + 'charges': server_count(game, 'wind_charge')} + finally: + host('command', command='gamerule natural_health_regeneration true') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + # Vanilla rises about 6 blocks from a charge at the feet. + assert 4 < s['rose'] < 8 and s['landed'] == 0, f'{name}: {seen}' + assert s['health'] == 20 and s['server_health'] == 20 and s['charges'] == 1, f'{name}: {seen}' + return seen + + +CHECKS += ['wind'] +CHECK_FNS.update(wind=check_wind) + + if __name__ == '__main__': main() From e1fff77a484a57e4d34947215768660a1f2dcb7b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:38:13 +0200 Subject: [PATCH 16/19] Prepare: Netty's native transports are optional, as in the game Prism Launcher never downloads io.netty:netty-transport-native-kqueue (or the epoll one on Linux), so preparing from a Prism install stopped on a jar the game runs without: vanilla's EventLoopGroupHolder.remote takes KQueue/Epoll only when isAvailable(), else Netty NIO. Preparing now imports a native transport when the launcher has it (checked against the version JSON's sha1, as before) and goes on without it otherwise; every other library stays required. Fixes #1487. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-prepare/src/artifacts.rs | 163 +++++++++++++++++++++++- 1 file changed, 159 insertions(+), 4 deletions(-) diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index b29bffb28..805dd80d4 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -372,6 +372,19 @@ fn client_library_artifacts(manifest: &Value) -> Result, Str Ok(artifacts) } +/// Netty's native transports (`io.netty:netty-transport-native-kqueue:4.2.16.Final:osx-aarch_64`, +/// the epoll ones on Linux): the game uses one when it loads and Netty NIO otherwise +/// (`EventLoopGroupHolder.remote` asks `KQueue.isAvailable()`, then `Epoll.isAvailable()`), and +/// Prism Launcher never downloads them (#1487). Preparing imports one when the launcher has it. +fn runs_without(name: &str) -> bool { + let mut parts = name.split(':'); + parts.next() == Some("io.netty") + && parts + .next() + .is_some_and(|artifact| artifact.starts_with("netty-transport-native-")) + && parts.nth(1).is_some() +} + /// A relative path with only normal components and forward slashes, from a manifest or bundle. pub(crate) fn safe_relative(path: &str) -> Option { if path.contains('\\') || path.starts_with('/') { @@ -547,9 +560,18 @@ pub fn import( for (name, artifact) in client_library_artifacts(&manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe library path")?; + let source = launcher_library(&minecraft, name, &relative); + let destination = lock.directory.join("libraries/client").join(&relative); + if runs_without(name) && !source.is_file() && !destination.exists() { + log(&format!( + "No {name} in {}: the game runs without it", + minecraft.display() + )); + continue; + } client_libraries.push(import_copy( - &launcher_library(&minecraft, name, &relative), - &lock.directory.join("libraries/client").join(&relative), + &source, + &destination, sha1, "sha1", &hint(LAUNCHER_HINT, version), @@ -783,13 +805,17 @@ pub fn verify(lock: &Lock) -> Result { } /// The client libraries, checked against the version JSON (tools/test_model_baking_parity.py's -/// `client_libraries`); the client-side exporters compile against them. +/// `client_libraries`); the client-side exporters compile against them. A native transport the +/// player's launcher did not have is left out. pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result, String> { let mut libraries = Vec::new(); - for (_, artifact) in client_library_artifacts(manifest)? { + for (name, artifact) in client_library_artifacts(manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe client library path")?; let library = lock.directory.join("libraries/client").join(&relative); + if runs_without(name) && !library.exists() { + continue; + } if !library.exists() || digest(&library, "sha1")? != sha1 { return Err(format!("Client dependency checksum changed: {path}")); } @@ -1071,6 +1097,135 @@ mod tests { } } + /// scanfee's Prism Launcher 26.3 install on a Mac (#1487): Prism keeps natives under its own + /// names and never downloads Netty's native transport, which the game runs without. Preparing + /// still checks every other library, and the transport whenever the launcher has it. + #[test] + fn a_prism_install_without_netty_natives_prepares() { + let fixture = Imports::new(); + let old = fixture.imported(&fixture.source); + let prism = fixture.directory.join("PrismLauncher"); + let put = |path: &str, data: &[u8]| { + let path = prism.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + put( + "versions/9.9/9.9.jar", + &fs::read(old.join("jars/client.jar")).unwrap(), + ); + put("libraries/org/lib/lib/1/lib-1.jar", b"lib"); + put( + "libraries/com/mojang/jtracy-natives-test/1/jtracy-natives-test-1.jar", + b"jtracy natives", + ); + let sha1 = |data: &[u8]| { + let file = fixture.directory.join("sha1"); + fs::write(&file, data).unwrap(); + digest(&file, "sha1").unwrap() + }; + let library = |name: &str, path: &str, sha1: &str, rules: &str| { + format!( + r#"{{"name":"{name}","downloads":{{"artifact":{{"path":"{path}","sha1":"{sha1}"}}}}{rules}}}"# + ) + }; + let netty = |arch: &str| { + library( + &format!("io.netty:netty-transport-native-kqueue:1:osx-{arch}"), + &format!("io/netty/netty-transport-native-kqueue/1/netty-transport-native-kqueue-1-osx-{arch}.jar"), + &sha1(b"kqueue"), + &format!(r#","rules":[{{"action":"allow","os":{{"name":"{}"}}}}]"#, rule_system()), + ) + }; + let client_sha1 = digest(&old.join("jars/client.jar"), "sha1").unwrap(); + let server_sha1 = digest(&old.join("jars/server.jar"), "sha1").unwrap(); + let libraries = [ + library( + "org.lib:lib:1", + "org/lib/lib/1/lib-1.jar", + &sha1(b"lib"), + "", + ), + library( + "com.mojang:jtracy:1:natives-test", + "com/mojang/jtracy/1/jtracy-1-natives-test.jar", + &sha1(b"jtracy natives"), + "", + ), + netty("aarch_64"), + netty("x86_64"), + ]; + put( + "versions/9.9/9.9.json", + format!( + r#"{{"id":"9.9","javaVersion":{{"majorVersion":25}},"downloads":{{"client":{{"sha1":"{client_sha1}"}},"server":{{"sha1":"{server_sha1}"}}}},"libraries":[{}]}}"#, + libraries.join(",") + ) + .as_bytes(), + ); + let manifest_sha1 = digest(&prism.join("versions/9.9/9.9.json"), "sha1").unwrap(); + fs::write( + fixture.target.join("research-lock.json"), + format!( + r#"{{"minecraft":{{"version":"9.9","java_major":25,"manifest_sha1":"{manifest_sha1}","client_sha1":"{client_sha1}","server_sha1":"{server_sha1}"}}}}"# + ), + ) + .unwrap(); + let lock = Lock::read(&fixture.target).unwrap(); + let server = old.join("jars/server.jar"); + let prepare = || import(&fixture.target, &lock, Some(&prism), Some(&server), &|_| {}); + let imported = || { + let manifest = verify(&lock).unwrap().manifest; + client_libraries(&lock, &manifest).unwrap().len() + }; + + prepare().unwrap(); + assert_eq!(imported(), 2); + let prepared = read_json(&lock.directory.join("prepared.json")).unwrap(); + let listed = prepared.get("libraries").and_then(|l| l.get("client")); + assert_eq!( + listed.and_then(Value::as_array).map(<[Value]>::len), + Some(2) + ); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + + // The launcher's copy is used, and checked, when it has one. + let manifest = read_json(&prism.join("versions/9.9/9.9.json")).unwrap(); + let (_, transport) = client_library_artifacts(&manifest) + .unwrap() + .into_iter() + .find(|(name, _)| runs_without(name)) + .unwrap(); + let path = transport.get("path").and_then(Value::as_str).unwrap(); + put(&format!("libraries/{path}"), b"not kqueue"); + assert!(prepare().unwrap_err().contains("is not the pinned file")); + put(&format!("libraries/{path}"), b"kqueue"); + prepare().unwrap(); + assert_eq!(imported(), 3); + // Other libraries stay required. + fs::remove_dir_all(lock.directory.join("libraries/client/org")).unwrap(); + fs::remove_file(prism.join("libraries/org/lib/lib/1/lib-1.jar")).unwrap(); + assert!(prepare().unwrap_err().starts_with("Missing ")); + } + + #[test] + fn runs_without_only_netty_native_transports() { + assert!(runs_without( + "io.netty:netty-transport-native-kqueue:4.2.16.Final:osx-aarch_64" + )); + assert!(runs_without( + "io.netty:netty-transport-native-epoll:4.2.16.Final:linux-x86_64" + )); + for required in [ + "io.netty:netty-transport-native-unix-common:4.2.16.Final", + "io.netty:netty-transport-classes-kqueue:4.2.16.Final", + "org.lwjgl:lwjgl:3.3.3:natives-macos-arm64", + "com.mojang:jtracy:1.14.38:natives-windows", + ] { + assert!(!runs_without(required), "{required}"); + } + } + #[test] fn natives_follow_the_architecture() { let names = ["a:b:1:natives-macos", "a:b:1:natives-macos-arm64"]; From 52bc81ca5b1fe78fe98b63685c0fc0a1c1c6a0ae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:48:08 +0200 Subject: [PATCH 17/19] Launcher: the command reference is the same on Windows launcher.yml's Windows build has failed since the reference test landed: Git for Windows checks text out with CRLF (core.autocrlf), so docs/launcher-commands.md never equalled what markdown() generates. .gitattributes now pins LF for the generated files tests compare byte for byte, and the launcher's check reads the file whatever line endings a clone gave it, with a test of a CRLF checkout. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 5 +++++ launcher/src/cli_tools.rs | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..13584e4d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Generated files that tests compare byte for byte with what they generate: LF on every OS, also +# where Git for Windows' core.autocrlf would check them out with CRLF. +docs/launcher-commands.md text eol=lf +docs/horizon-ctl-commands.md text eol=lf +website/src/tokens.css text eol=lf diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index 7653311ac..a851adcbd 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -419,6 +419,20 @@ mod tests { ); } + /// Whether the reference on disk says `want`, whatever line endings the checkout gave it: Git + /// for Windows checks text out with CRLF (core.autocrlf) where .gitattributes does not pin LF. + fn up_to_date(have: &str, want: &str) -> bool { + have.replace("\r\n", "\n") == want + } + + #[test] + fn a_windows_checkout_of_the_reference_is_up_to_date() { + let want = markdown(); + assert!(up_to_date(&want, &want)); + assert!(up_to_date(&want.replace('\n', "\r\n"), &want)); + assert!(!up_to_date(&want.replacen("## ", "### ", 1), &want)); + } + #[test] fn the_launcher_reference_is_up_to_date() { let path = @@ -429,7 +443,7 @@ mod tests { } let have = std::fs::read_to_string(&path).unwrap_or_default(); assert!( - have == want, + up_to_date(&have, &want), "docs/launcher-commands.md is out of date: HORIZON_WRITE_DOCS=1 cargo test --manifest-path launcher/Cargo.toml the_launcher_reference" ); for tool in all() { From 574e3ca567fcdbef23818e767ba1357345a0e199 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:23:52 +0200 Subject: [PATCH 18/19] dedicated_server parity: the client re-sends its position as vanilla's does The harness failed about 1 run in 3 on CI with "play-trade villager false" on Horizon's side: the protocol client never saw the villager it trades with. A server pairs a player with an entity only while the entity's chunk has been sent to it, and checks again when either moves (ChunkMap.move / updatePlayers). VanillaProtocolClient sent its position once, at the spawn teleport, and never again. Horizon's first chunk batch goes out two ticks after the player is placed (after the first tick's packets, as vanilla orders them); when a busy machine held the tick thread back long enough for the client's move to be handled one tick after placement, the villager's chunk wasn't sent yet, and with no later move the villager was never paired. The 26.3 client re-sends its position every 20 ticks standing still (LocalPlayer.sendPosition, after a ServerboundClientTickEnd each tick). The parity client now does the same from the time it is loaded until its death, so an entity whose chunk comes late is paired at the next reminder, on either server. On failure the harness now adds the servers' and clients' warnings and errors to its message and the client log's tail when the client fails, and parity.py's summary prints the end of the first failing harnesses' logs, so CI shows why. Co-Authored-By: Claude Opus 5.5 --- .../parity/VanillaProtocolClient.java | 15 +++++++++ tools/parity.py | 14 ++++++-- tools/test_dedicated_server_parity.py | 32 ++++++++++++++++--- 3 files changed, 54 insertions(+), 7 deletions(-) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index d5e9c86fa..e37e898a3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -65,6 +65,7 @@ import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; import net.minecraft.network.protocol.game.ServerboundChatPacket; import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket; import net.minecraft.network.protocol.handshake.ClientIntent; @@ -484,6 +485,8 @@ public final class VanillaProtocolClient { // When the dead player sent a command (ServerGamePacketListenerImpl.handleChatCommand runs it // whether the player is alive or not); it respawns once the reply came, or 3 s later. long deadCommandAt = 0; + // When the client last sent where it is. + long positionAt = 0; while (System.currentTimeMillis() < deadline) { Received r; try { @@ -536,6 +539,7 @@ public final class VanillaProtocolClient { // acceptance alone, as the 26.3 client sends. if (!respawning && step < ENTITIES) { send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); + positionAt = now; } if (!loaded) { send(new ServerboundPlayerLoadedPacket()); @@ -635,6 +639,17 @@ public final class VanillaProtocolClient { commandTree(p); } } + if (entities == null && loaded && deadCommandAt == 0 && now - positionAt >= 1000) { + // LocalPlayer.sendPosition: once its level is loaded the 26.3 client sends where it is + // every 20 ticks even standing still, and the server then checks again which entities the + // player sees (ChunkMap.move). An entity whose chunk was sent after the player's last move, + // such as the villager when the first chunks come late, is paired at the next one. The tick + // end first (Minecraft.tick sends one every tick): a server takes one position per client tick. + // Until the death: from then on the steps wait only on entities spawned for the player. + send(ServerboundClientTickEndPacket.INSTANCE); + send(new ServerboundMovePlayerPacket.Pos(position.position(), false, false)); + positionAt = now; + } if (entities != null && loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) { // Entity mode: the harness's console summons the scene once it reads this // line; everything tracked from then on is recorded until the client leaves. diff --git a/tools/parity.py b/tools/parity.py index 68ff16e73..a1a9f4133 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -65,6 +65,7 @@ SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve() MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2)) HOST = socket.gethostname().split(".")[0] DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here +FAILURE_TAILS, FAILURE_TAIL_LINES = 10, 30 # the summary prints the end of the first failures' logs def harness_settings(path): @@ -1361,8 +1362,17 @@ def main(): failed = sorted(name for name, record in results.items() if record["status"] != "pass") finished_run(failed) print(f"\n{len(results) - len(failed)} passed, {len(failed)} failed in {elapsed / 60:.1f} min.") - for name in failed: - print(f" {name}: {STATE_DIR / 'logs' / (name + '.log')}") + for index, name in enumerate(failed): + log = STATE_DIR / 'logs' / (name + '.log') + print(f" {name}: {log}") + # The end of a harness's output says why it failed, and CI shows only this output. + if index < FAILURE_TAILS: + try: + lines = log.read_text(encoding='utf-8', errors='replace').splitlines()[-FAILURE_TAIL_LINES:] + except OSError: + lines = [] + for line in lines: + print(f" {line[:300]}") return 1 if failed else 0 diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 07d61f3d5..f45df9822 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -7,7 +7,9 @@ respawn_radius 0) and stops; a vanilla dedicated server and Horizon's server.properties, server-icon.png and lists. VanillaProtocolClient, a headless client made of vanilla's own codecs (any byte vanilla would not read is an error), pings each server, joins it in offline mode through -login, configuration and play, accepts the spawn teleport, receives the +login, configuration and play, accepts the spawn teleport (then, standing +still until its death, sends its position every 20 ticks as LocalPlayer +does: the server checks then which entities it sees), receives the chunks around the spawn (their bytes are compared: the world is loaded from the same files), chats, runs /list and commands that fail (`/random value 7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by @@ -244,6 +246,20 @@ def console_lines(lines): return out +# What a failure's diff doesn't say: warnings, errors, panics and why a player left. +NOTABLE = re.compile(r'/(WARN|ERROR)\]|Exception|panicked|lost connection') + + +def notable_lines(path, limit=20): + """A server's notable lines from its `Done (` on (the startup warnings are every run's), or a client's.""" + try: + lines = path.read_text(encoding='utf-8', errors='replace').splitlines() + except OSError: + return [] + start = next((i for i, l in enumerate(lines) if 'Done (' in l), 0) + return [f'{path.name}: {l[:300]}' for l in lines[start:] if NOTABLE.search(l)][-limit:] + + def server_files(directory): out = [] for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json', @@ -420,9 +436,13 @@ def main(): (world / 'playerdata').mkdir(exist_ok=True) def client(port, out): - oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build, - out.stem, timeout=300) + try: + oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build, + out.stem, timeout=300) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: + log = (build / f'{out.stem}.log').read_text(encoding='utf-8', errors='replace').splitlines() + raise AssertionError(f'{out.stem}: {error}:\n' + '\n'.join(log[-30:])) from None results = {} for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: @@ -448,8 +468,10 @@ def main(): if a != b: differences.append(f'chunk {key}: vanilla {a} horizon {b}') if differences or errors: + notes = [line for name in ('vanilla', 'vanilla-client', 'horizon', 'horizon-client') + for line in notable_lines(build / f'{name}.log')] raise AssertionError(f'{len([d for d in differences if d[:1] in "+-" and d[:3] not in ("+++", "---")])} differing lines ' - f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80])) + f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80] + notes)) lab.write_json(report, dict( schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], From ea424ebd52dd500173c70c18b6ad5aeecee561d3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:26:56 +0200 Subject: [PATCH 19/19] LAN and dedicated servers wait for the player's client to finish breaking a block ServerPlayerGameMode breaks a digging player's block only when the player's client says it is done (STOP_DESTROY_BLOCK, or the delayed destroy), or at once when it is instant. The host ran the guest's tick_mining with its own count and broke the block when that reached 1. A guest whose client ran even a tick behind lost the block before it predicted the break: no destroy particles, no break sound, and the dropped item could appear before the block vanished. lan_e2e's new digging check holds attack across six oak logs and hears six breaks, then stalls the guest for a second halfway through stone: the stone is still there on both sides when it resumes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 7 +++- tools/lan_e2e.py | 68 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6184f1626..b1777eba8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3803,7 +3803,12 @@ impl Game<'_> { } self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; - if m.progress >= 1.0 { + // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's + // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK + // (`guest_stop_digging`), never breaking it on its own count. Breaking it here would + // take the block from under the player's crack before the player's client predicts the + // break, so it gets neither particles nor sound. + if m.progress >= 1.0 && (self.lan_acting.is_none() || m.ticks == 1) { let pos = m.pos; self.mining = None; self.break_block(pos)?; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 994636066..f69081945 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4521,5 +4521,73 @@ CHECKS += ['totem'] CHECK_FNS.update(totem=check_totem) +def check_digging(host, guest, out): + """The server breaks a block a player digs only once that player's client is done + (ServerPlayerGameMode: STOP_DESTROY_BLOCK, or the delayed destroy), never on its own count, so + the player's client always breaks it first, with its particles and sound. The guest holds + attack across a wall of six oak logs with a copper axe and hears each one break; then it digs + stone with a wooden pickaxe and its game stalls for a second halfway: the stone is still there + on both sides when it resumes, and the guest's own crack finishes it.""" + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + x, y, z = gx + 3, gy, gz + 4 + heard = lambda sound: guest('status')['heard'].get(sound, 0) + at = lambda b: (f'{b[0] + 0.02:.2f}', f'{b[1] + 0.5:.2f}', f'{b[2] + 0.5:.2f}') + guest('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:copper_axe') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y + 3} {z + 2} minecraft:air') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x + 2} {y} {z - 1} {x + 2} {y + 1} {z + 1} minecraft:oak_log') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + guest.wait(30) + logs = [(x + 2, y + dy, z + dz) for dz in (-1, 0, 1) for dy in (0, 1)] + before = heard('minecraft:block.wood.break') + guest.raw('look-at', *at(logs[0])) + guest.raw('mouse', 'left', 'down') + left = list(logs) + deadline = time.time() + 20 + while left and time.time() < deadline: + if guest.raw('block', *left[0]).get('block') != 'minecraft:oak_log': + left.pop(0) + if left: + guest.raw('look-at', *at(left[0])) + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen = {'logs_left': left, 'log_breaks_heard': heard('minecraft:block.wood.break') - before} + + # Stone with a wooden pickaxe: 23 ticks. The guest stalls for a second after about 8. + stone = (x + 2, y, z) + guest('command', command='item replace entity @s weapon.mainhand with minecraft:wooden_pickaxe') + host('command', command=f'setblock {stone[0]} {stone[1]} {stone[2]} minecraft:stone') + guest.wait(10) + before = heard('minecraft:block.stone.break') + guest.raw('look-at', *at(stone)) + guest.raw('mouse', 'left', 'down') + time.sleep(0.4) + os.kill(guest.pid, signal.SIGSTOP) + try: + time.sleep(1.0) + finally: + os.kill(guest.pid, signal.SIGCONT) + resumed = {'guest': guest.raw('block', *stone).get('block'), 'server': host.raw('block', *stone).get('block'), + 'mining': guest('state').get('mining')} + # Let go once it breaks: past it the crosshair reaches the floor. + deadline = time.time() + 5 + while guest.raw('block', *stone).get('block') == 'minecraft:stone' and time.time() < deadline: + pass + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen.update(resumed=resumed, stone_after=host.raw('block', *stone).get('block'), + stone_breaks_heard=heard('minecraft:block.stone.break') - before) + guest.shot(out, 'digging') + assert not left and seen['log_breaks_heard'] == 6, f'the server broke logs before the guest did: {seen}' + assert resumed['guest'] == resumed['server'] == 'minecraft:stone', f'the server broke the stone while the guest stalled: {seen}' + assert seen['stone_after'] == 'minecraft:air' and seen['stone_breaks_heard'] == 1, f'the guest did not break the stone: {seen}' + return seen + + +CHECKS += ['digging'] +CHECK_FNS.update(digging=check_digging) + + if __name__ == '__main__': main()