Skip to content

Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.

Attack swap: the item's pick stops on a block, and its range holds the hit

Evrim Cicekcbed0c07bd49
diff --git a/crates/horizon-client-input/src/interaction_input.rs b/crates/horizon-client-input/src/interaction_input.rs
index 06d1c8c3b..945772643 100644
--- a/crates/horizon-client-input/src/interaction_input.rs
+++ b/crates/horizon-client-input/src/interaction_input.rs
@@ -51,6 +51,10 @@ impl InteractionInput {
pub fn press(&mut self, button: Button) {
self.clicks[button as usize] += 1;
}
+ /// Whether a click waits for the next tick.
+ pub fn has_clicks(&self) -> bool {
+ self.clicks.iter().any(|&c| c > 0)
+ }
pub fn tick(&mut self, world: &mut impl InteractionWorld, attack_down: bool, use_down: bool) {
let [attack, use_item, pick] = std::mem::take(&mut self.clicks);
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 015e04e38..4cadb56c4 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -11344,7 +11344,7 @@ impl Game<'_> {
let Some((index, distance)) = self.mob_hit() else {
return false;
};
- if !self.before_block(distance) {
+ if !self.before_block(distance) || !self.held_range_allows(distance) {
return false;
}
self.attack_mob(index);
@@ -15891,6 +15891,8 @@ impl Game<'_> {
KeyCode::KeyE => match self.screen {
Screen::Playing if self.spectator() => {}
Screen::Playing => {
+ // handleKeybinds: the number keys select before key.inventory.
+ self.select_queued_hotbar();
// key.inventory while riding a tamed mount opens its inventory.
if !self.open_ridden_mount_menu() {
if self.tutorial.open_inventory() {
@@ -15931,6 +15933,8 @@ impl Game<'_> {
}
}
KeyCode::KeyF if self.screen == Screen::Playing => {
+ // handleKeybinds: the number keys select before key.swapOffhand.
+ self.select_queued_hotbar();
// handlePlayerAction SWAP_ITEM_WITH_OFFHAND: setItemInHand for
// the off hand, then the main hand.
std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]);
@@ -15942,6 +15946,8 @@ impl Game<'_> {
self.using = None;
}
KeyCode::KeyQ if self.screen == Screen::Playing => {
+ // handleKeybinds: the number keys select before key.drop.
+ self.select_queued_hotbar();
let all = drop_whole_stack(self.modifiers);
self.drop_held(all);
}
@@ -16030,6 +16036,8 @@ impl Game<'_> {
}
}
MouseButton::Middle if pressed => {
+ // handleKeybinds: the number keys select before key.pickItem.
+ self.select_queued_hotbar();
// Minecraft.pickBlockOrEntity -> the server's handlePickItemFromBlock:
// the block's clone item, with its block entity's data on Ctrl in
// creative, picked from the inventory (`pick_item`).
diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs
index a972146bf..c3604e5e4 100644
--- a/crates/horizon-client/src/game/chat.rs
+++ b/crates/horizon-client/src/game/chat.rs
@@ -574,6 +574,8 @@ impl Game<'_> {
/// last time, when this method can restore it (a command draft only for
/// /), else with its prefix.
pub(super) fn open_chat_method(&mut self, prefix: &str) {
+ // handleKeybinds: the number keys select before key.chat and key.command.
+ self.select_queued_hotbar();
let command = prefix == "/";
let draft = self
.ui
diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs
index e8063fdf7..d8d08c405 100644
--- a/crates/horizon-client/src/game/hand.rs
+++ b/crates/horizon-client/src/game/hand.rs
@@ -212,11 +212,15 @@ impl Game<'_> {
pub(super) fn pick_tick_targets(&mut self) {
self.tick_hit = Some(self.pick());
self.tick_mob = None;
- let mob = self
- .active_attack_range()
- .and_then(|range| self.attack_range_mob_hit(&range))
- .or_else(|| self.mob_hit());
- self.tick_mob = Some(mob);
+ let mob = match self.active_attack_range() {
+ Some(range) => self.attack_range_pick(&range),
+ None => None,
+ };
+ self.tick_mob = Some(mob.unwrap_or_else(|| self.mob_hit()));
+ self.select_queued_hotbar();
+ }
+ /// `handleKeybinds`' number keys (`keyHotbarSlots[i].consumeClick`).
+ pub(super) fn select_queued_hotbar(&mut self) {
for slot in std::mem::take(&mut self.hotbar_presses) {
self.selected = slot;
}
@@ -226,6 +230,19 @@ impl Game<'_> {
self.tick_hit = None;
self.tick_mob = None;
}
+ /// `Minecraft.startAttack` on an entity: a main-hand item with an
+ /// `attack_range` attacks only a hit inside it.
+ pub(super) fn held_range_allows(&self, distance: f64) -> bool {
+ let range = self.held().and_then(|stack| {
+ self.pack
+ .item_renderer
+ .models
+ .components(&horizon_client::item_render::stack_view(stack))
+ .get("minecraft:attack_range")
+ .cloned()
+ });
+ range.is_none_or(|r| attack_range_contains(&r, distance, self.creative))
+ }
/// `LocalPlayer.raycastHitResult`'s item (`getActiveItem`: the one in
/// use, else the main hand's) `attack_range` component.
fn active_attack_range(&self) -> Option<serde_json::Value> {
@@ -241,9 +258,12 @@ impl Game<'_> {
.cloned()
}
/// `AttackRange.getClosesetHit` against the mobs `mob_hit` can pick
- /// (`EntitySelector.CAN_BE_PICKED`): the nearest one hit within the
- /// item's reach, none on a miss or a block first.
- fn attack_range_mob_hit(&self, range: &serde_json::Value) -> Option<(usize, f64)> {
+ /// (`EntitySelector.CAN_BE_PICKED`), as `raycastHitResult` reads it: the
+ /// nearest mob hit within the item's reach; no mob when the clip met a
+ /// block within the block reach (`getHitEntitiesAlong`'s block result,
+ /// kept by `filterHitResult`); `None` on a miss, where the plain pick
+ /// decides.
+ fn attack_range_pick(&self, range: &serde_json::Value) -> Option<Option<(usize, f64)>> {
let eye = v3(self.eye_position()?);
let look = v3(super::view_vector(self.yaw, self.pitch));
let reach = attack_reach(range, self.creative);
@@ -261,10 +281,17 @@ impl Game<'_> {
.map(|hit| Vec3::new(hit.point[0], hit.point[1], hit.point[2]))
};
let movement = self.known_player_movement();
- super::spear::hits_in_reach(&boxes, eye, look, movement, reach, clip)
+ let nearest = super::spear::hits_in_reach(&boxes, eye, look, movement, reach, &clip)
.into_iter()
.map(|(i, at)| (i, eye.distance_squared(at).sqrt()))
- .reduce(|a, b| if b.1 < a.1 { b } else { a })
+ .reduce(|a, b| if b.1 < a.1 { b } else { a });
+ if nearest.is_some() {
+ return Some(nearest);
+ }
+ let to = eye.add_vector(look.scale(f64::from(reach.1) + movement.dot(look).max(0.0)));
+ clip(eye, to)
+ .is_some_and(|block| eye.distance_squared(block) <= self.block_reach.powi(2))
+ .then_some(None)
}
/// The attack and use part of `Minecraft.tick` for the local player:
/// attack clicks since the last tick and the held attack button.
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index cc6471710..dc430ed02 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -8188,7 +8188,10 @@ impl Game<'_> {
// MultiPlayerGameMode.tick syncs the carried slot before keybinds.
self.remote_send_carried();
let (attack, use_item) = (self.left, self.right);
- input.tick(&mut RemoteInputWorld(self), attack, use_item);
+ // A tick that clicks, attacks or uses acts with the slot its number
+ // keys select (`ensureHasSentCarriedItem` before the packets).
+ let acts = input.has_clicks() || attack || use_item;
+ input.tick(&mut RemoteInputWorld(self, acts), attack, use_item);
self.remote_queued_keys();
if let Some(r) = self.remote.as_mut() {
r.input = input;
@@ -8312,11 +8315,14 @@ impl Game<'_> {
} else if let Some((i, distance)) = self.mob_hit()
&& self.before_block(distance)
{
- self.send(S::Attack(play::Attack {
- id: self.mobs[i].id as i32,
- }));
- self.remote_player_attack(i);
- self.reset_attack_strength();
+ // Minecraft.startAttack: an item's attack_range must hold the hit.
+ if self.held_range_allows(distance) {
+ self.send(S::Attack(play::Attack {
+ id: self.mobs[i].id as i32,
+ }));
+ self.remote_player_attack(i);
+ self.reset_attack_strength();
+ }
} else if !self.entity_targeted()
&& let Some(hit) = self.pick()
{
@@ -8531,7 +8537,9 @@ impl Game<'_> {
// `KeyMapping.releaseAll` clears key.use; without this the button still
// reads held and a use would start again on the first tick back.
self.right = false;
- horizon_client::interaction_input::release_on_screen_open(&mut RemoteInputWorld(self));
+ horizon_client::interaction_input::release_on_screen_open(&mut RemoteInputWorld(
+ self, false,
+ ));
}
/// `MultiPlayerGameMode.releaseUsingItem`: sends `RELEASE_USE_ITEM` and
/// runs the client half of `Item.releaseUsing` (a Riptide launch moves the
@@ -9830,7 +9838,8 @@ fn synced_local_use(
}
}
-struct RemoteInputWorld<'g, 'a>(&'g mut Game<'a>);
+/// The game as the tick's input sees it, and whether the tick acts.
+struct RemoteInputWorld<'g, 'a>(&'g mut Game<'a>, bool);
struct RemoteUseWorld<'g, 'a>(&'g mut Game<'a>);
@@ -9849,8 +9858,12 @@ impl horizon_client::interaction_input::TargetUseWorld for RemoteUseWorld<'_, '_
impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_, '_> {
fn pick_hit_result(&mut self) {
self.0.pick_tick_targets();
- // The attack or use a number key's slot makes sends the slot first.
- self.0.remote_send_carried();
+ // MultiPlayerGameMode.ensureHasSentCarriedItem: an action this tick
+ // sends the slot the number keys chose first; otherwise the next
+ // tick's MultiPlayerGameMode.tick does.
+ if self.1 {
+ self.0.remote_send_carried();
+ }
}
fn release_hit_result(&mut self) {
self.0.release_tick_targets();
diff --git a/tools/attack_swap_e2e.py b/tools/attack_swap_e2e.py
index 782a52eb8..e0afae584 100644
--- a/tools/attack_swap_e2e.py
+++ b/tools/attack_swap_e2e.py
@@ -10,7 +10,12 @@ server is slowed to one tick a second so both inputs land in one client tick.
Cases: the swap and the click in one tick hit a pig 3.75 blocks away; the
swap a tick before the click misses it (the mace's own pick reaches 3); a
-mace click at 2.25 blocks hits (the setup lands attacks at all).
+mace click at 2.25 blocks hits (the setup lands attacks at all). A pig inside
+the spear's 2 block minimum: with the floor behind it, the spear's pick ends
+on the floor (`getHitEntitiesAlong`'s block result), so the mace misses the
+pig; over a pit the spear's pick misses and the plain pick finds the pig. A
+stick given an `attack_range` does not attack a pig inside its minimum
+(`startAttack`).
Requires prepared resources and built horizon-client/horizon-ctl binaries.
"""
import argparse
@@ -34,11 +39,19 @@ NAME = 'SwapTester'
PIG = '@e[type=minecraft:pig,limit=1]'
# Player at 0.5 80 0.5 looking east; the pig's near face is `distance` - 0.45
# from the eyes' column.
+FLOOR = ['fill -3 70 -3 8 79 3 minecraft:stone']
+# Stone under the player and the pig only, air past 2 down to 70.
+PIT = ['fill -3 70 -3 8 79 3 minecraft:air', 'fill -3 79 -3 1 79 3 minecraft:stone']
+SWAP = ['key 2 tap', 'mouse left click']
+APART = ['key 2 tap', 'wait 1', 'mouse left click']
CASES = [
- # (label, pig distance, inputs, expected hit)
- ('same-tick', 4.2, ['key 2 tap', 'mouse left click'], True),
- ('tick-apart', 4.2, ['key 2 tap', 'wait 1', 'mouse left click'], False),
- ('mace-near', 2.7, ['key 2 tap', 'wait 1', 'mouse left click'], True),
+ # (label, terrain, pig distance, look height, inputs, expected hit)
+ ('same-tick', FLOOR, 4.2, 80.45, SWAP, True),
+ ('tick-apart', FLOOR, 4.2, 80.45, APART, False),
+ ('mace-near', FLOOR, 2.7, 80.45, APART, True),
+ ('min-reach-floor', FLOOR, 1.0, 80.6, SWAP, False),
+ ('min-reach-pit', PIT, 1.0, 80.6, SWAP, True),
+ ('ranged-stick', PIT, 1.0, 80.6, ['key 3 tap', 'wait 1', 'mouse left click'], False),
]
@@ -90,19 +103,23 @@ def main():
'fill -3 79 -3 8 79 3 minecraft:stone', 'fill -3 80 -3 8 84 3 minecraft:air',
f'tp {NAME} 0.5 80 0.5 -90 0',
f'item replace entity {NAME} hotbar.0 with minecraft:iron_spear',
- f'item replace entity {NAME} hotbar.1 with minecraft:mace'):
+ f'item replace entity {NAME} hotbar.1 with minecraft:mace',
+ f'item replace entity {NAME} hotbar.2 with minecraft:stick'
+ '[minecraft:attack_range={min_reach:2.0f,max_reach:4.5f}]'):
server.console(line)
game_time(server)
ctl('wait', 20)
- for label, distance, inputs, expected in CASES:
+ for label, terrain, distance, look, inputs, expected in CASES:
server.console(f'kill {PIG}')
+ for line in terrain:
+ server.console(line)
server.console(f'summon minecraft:pig {0.5 + distance} 80 0.5 {{NoAI:1b,Silent:1b}}')
server.console(f'tp {NAME} 0.5 80 0.5 -90 0')
game_time(server)
ctl('key', '1', 'tap')
# A full attack charge with the spear in hand.
ctl('wait', 40)
- ctl('look-at', 0.5 + distance, 80.45, 0.5)
+ ctl('look-at', 0.5 + distance, look, 0.5)
before = pig_health()
server.console('tick rate 1')
game_time(server)