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.

A number key and an attack in one tick swing the new item at the old one's target

Evrim Cicekd073e1dc7e21
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 3721e78f3..015e04e38 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -2814,6 +2814,13 @@ struct Game<'a> {
/// `remote_handle_input`): picked once, so a creative break does not
/// move the use that follows it past the broken block.
tick_hit: Option<Option<Hit>>,
+ /// The mob of that `hitResult`, picked with the item held at the pick
+ /// (`LocalPlayer.raycastHitResult`: a spear's `attack_range`), before the
+ /// tick's number keys change it.
+ tick_mob: Option<Option<(usize, f64)>>,
+ /// Number keys since the last tick (`keyHotbarSlots[i].consumeClick`):
+ /// `Minecraft.handleKeybinds` selects them after the tick's pick.
+ hotbar_presses: Vec<usize>,
/// `Player.entityInteractionRange` and `blockInteractionRange`, refreshed
/// each tick from the attribute (a server's reach modifier, creative's
/// +2): the pick helpers' `&self` reach.
@@ -11111,6 +11118,9 @@ impl Game<'_> {
darken
}
fn mob_hit(&self) -> Option<(usize, f64)> {
+ if let Some(hit) = self.tick_mob {
+ return hit;
+ }
let (eye, dir) = self.aim()?;
let reach: f64 = self.entity_reach;
let mut best: Option<(usize, f64)> = None;
@@ -15969,7 +15979,7 @@ impl Game<'_> {
{
self.hotbar_load_or_save(slot, load);
} else {
- self.selected = slot;
+ self.hotbar_presses.push(slot);
}
}
_ if self.screen == Screen::Paused && self.pause_menu => {
@@ -18443,6 +18453,8 @@ impl<'a> Game<'a> {
world_icon: None,
forced_hit: None,
tick_hit: None,
+ tick_mob: None,
+ hotbar_presses: Vec::new(),
entity_reach: 3.0,
block_reach: 4.5,
guest_use: None,
diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs
index c949e84a0..e8063fdf7 100644
--- a/crates/horizon-client/src/game/hand.rs
+++ b/crates/horizon-client/src/game/hand.rs
@@ -205,6 +205,67 @@ impl Game<'_> {
self.attack_ticks = 0;
self.hand_strength.reset();
}
+ /// `Minecraft.tick`'s `pick`, then `handleKeybinds`' number keys: the
+ /// tick's clicks act on what the item held before the keys picked (a
+ /// spear's 4.5 blocks), with the item the keys select (attribute
+ /// swapping a spear's reach onto a mace).
+ 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);
+ for slot in std::mem::take(&mut self.hotbar_presses) {
+ self.selected = slot;
+ }
+ }
+ /// The tick's clicks are done: later picks follow the crosshair again.
+ pub(super) fn release_tick_targets(&mut self) {
+ self.tick_hit = None;
+ self.tick_mob = None;
+ }
+ /// `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> {
+ let active = self
+ .using
+ .and_then(|(slot, _)| self.inventory.get(slot).and_then(Option::as_ref))
+ .or_else(|| self.held())?;
+ self.pack
+ .item_renderer
+ .models
+ .components(&horizon_client::item_render::stack_view(active))
+ .get("minecraft:attack_range")
+ .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)> {
+ let eye = v3(self.eye_position()?);
+ let look = v3(super::view_vector(self.yaw, self.pitch));
+ let reach = attack_reach(range, self.creative);
+ let camera = self.remote_camera_id();
+ let boxes: Vec<(usize, Aabb)> = (self.mobs.iter().enumerate())
+ .filter(|(_, m)| !m.removed && Some(m.id) != self.riding && Some(m.id) != camera)
+ .map(|(i, m)| (i, m.bounds()))
+ .collect();
+ let clip = |from: Vec3, to: Vec3| {
+ let length = from.distance_squared(to).sqrt();
+ let d = to.subtract(from).scale(1.0 / length);
+ (length > 0.0)
+ .then(|| self.clip_ray([from.x, from.y, from.z], [d.x, d.y, d.z], length))
+ .flatten()
+ .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)
+ .into_iter()
+ .map(|(i, at)| (i, eye.distance_squared(at).sqrt()))
+ .reduce(|a, b| if b.1 < a.1 { b } else { a })
+ }
/// The attack and use part of `Minecraft.tick` for the local player:
/// attack clicks since the last tick and the held attack button.
pub(super) fn tick_local_hand(&mut self) -> Result<()> {
@@ -216,11 +277,10 @@ impl Game<'_> {
// (scripts under --control hold buttons without grabbing it).
let down = self.left;
let ticks = self.clicks.destroying.ticks;
- // Minecraft.hitResult is picked once per frame: a creative break
- // does not move the use that follows it past the broken block.
- if use_clicks > 0 && attack_clicks > 0 {
- self.tick_hit = Some(self.pick());
- }
+ // Minecraft.hitResult is picked once per tick, before the number
+ // keys: a creative break does not move the use that follows it
+ // past the broken block.
+ self.pick_tick_targets();
let mut world = GameHands {
game: self,
error: None,
@@ -229,7 +289,7 @@ impl Game<'_> {
let error = world.error.take();
self.clicks = clicks;
if let Some(e) = error {
- self.tick_hit = None;
+ self.release_tick_targets();
return Err(e);
}
// Use clicks follow the attack clicks within the tick, against
@@ -245,7 +305,7 @@ impl Game<'_> {
break;
}
}
- self.tick_hit = None;
+ self.release_tick_targets();
used?;
// A tick of breaking: the hit sound every fourth tick and the
// cracking particles.
@@ -267,8 +327,10 @@ impl Game<'_> {
}
}
} else {
- // Minecraft.tick: a screen keeps the attack from starting.
+ // Minecraft.tick: a screen keeps the attack from starting, and
+ // opening it released the keys (`KeyMapping.releaseAll`).
self.clicks.miss_time = 10000;
+ self.hotbar_presses.clear();
}
let d = &self.clicks.destroying;
self.mining = d.active.then_some(Mining {
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index dbb00525b..cc6471710 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -8181,9 +8181,23 @@ impl Game<'_> {
self.stop_remote_mining();
}
if !ready {
+ // A screen's opening released the keys (`KeyMapping.releaseAll`).
+ self.hotbar_presses.clear();
return;
}
// 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);
+ self.remote_queued_keys();
+ if let Some(r) = self.remote.as_mut() {
+ r.input = input;
+ }
+ }
+
+ /// `MultiPlayerGameMode.ensureHasSentCarriedItem`: the server hears of a
+ /// new selected slot before anything the slot acts with.
+ fn remote_send_carried(&mut self) {
let carried_changed = self.remote.as_mut().is_some_and(|r| {
if r.carried == Some(self.selected) {
false
@@ -8197,8 +8211,9 @@ impl Game<'_> {
slot: self.selected as i16,
}));
}
- let (attack, use_item) = (self.left, self.right);
- input.tick(&mut RemoteInputWorld(self), attack, use_item);
+ }
+
+ fn remote_queued_keys(&mut self) {
// handleKeybinds' keybind polls: the queued presses act now, in tick
// order, so no packet goes out between CLIENT_TICK_END and a pong.
let pending = self
@@ -8229,9 +8244,6 @@ impl Game<'_> {
if self.clicks.miss_time > 0 {
self.clicks.miss_time -= 1;
}
- if let Some(r) = self.remote.as_mut() {
- r.input = input;
- }
}
fn remote_start_attack(&mut self) -> bool {
@@ -9836,10 +9848,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.tick_hit = Some(self.0.pick());
+ self.0.pick_tick_targets();
+ // The attack or use a number key's slot makes sends the slot first.
+ self.0.remote_send_carried();
}
fn release_hit_result(&mut self) {
- self.0.tick_hit = None;
+ self.0.release_tick_targets();
}
fn using_item(&self) -> bool {
self.0.using.is_some()
diff --git a/tools/attack_swap_e2e.py b/tools/attack_swap_e2e.py
new file mode 100644
index 000000000..782a52eb8
--- /dev/null
+++ b/tools/attack_swap_e2e.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python3
+"""Attribute swapping from a spear to a mace against an actual vanilla 26.3 server.
+
+`Minecraft.tick` picks the crosshair target (`pick`, with the held item's
+`attack_range`: a spear reaches 4.5 blocks) before `handleKeybinds` takes a
+number key and then the attack click. A number key and a click in the same
+tick therefore swing the new item at the target the spear picked, and the
+server's `handleAttack` checks that item's range with a 3 block buffer. The
+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).
+Requires prepared resources and built horizon-client/horizon-ctl binaries.
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import time
+
+import lab
+import test_rust_parity as base
+from integration_env import game_environment
+from test_dedicated_server_parity import Server, game_time
+from test_locator_bar_parity import server_dir
+
+ROOT = Path(__file__).resolve().parents[1]
+EXE = '.exe' if os.name == 'nt' else ''
+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.
+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),
+]
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--game', type=Path, default=ROOT / f'target/fast/horizon-client{EXE}')
+ parser.add_argument('--ctl', type=Path, default=ROOT / f'target/fast/horizon-ctl{EXE}')
+ parser.add_argument('--resources', type=Path, default=ROOT / '.local/horizon-client/26.3')
+ parser.add_argument('--output', type=Path)
+ args = parser.parse_args()
+ output = (args.output or Path(tempfile.mkdtemp(prefix='attack-swap-'))).resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ _, jars, libraries = base.verify_artifacts()
+ dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
+ command = ['java', '-Xmx2G', '-Duser.timezone=UTC', '-cp', dependencies,
+ 'net.minecraft.server.Main', 'nogui']
+ port = server_dir(output / 'server')
+ server = Server(command, output / 'server', 'vanilla')
+ env = game_environment(os.environ, output)
+ results = []
+ # Keep AF_UNIX paths short even in nested worktrees.
+ with tempfile.TemporaryDirectory(prefix='aswap-', dir=None if os.name == 'nt' else '/tmp') as socket_home:
+ socket = Path(socket_home) / 'ctl.sock'
+
+ def ctl(*commands, timeout=500):
+ r = subprocess.run([str(args.ctl.resolve()), '--socket', str(socket), *map(str, commands)],
+ cwd=output, env=env, capture_output=True, text=True, timeout=timeout)
+ data = json.loads(r.stdout)
+ if r.returncode or data.get('error'):
+ raise RuntimeError(f'{commands}: {data}; {r.stderr}')
+ return data
+
+ def pig_health():
+ start = len(server.lines)
+ server.console(f'data get entity {PIG} Health')
+ game_time(server)
+ values = [float(m.group(1)) for line in server.lines[start:]
+ if (m := re.search(r'entity data: (-?\d+(?:\.\d+)?)f', line))]
+ assert len(values) == 1, server.lines[start:]
+ return values[0]
+
+ try:
+ server.wait_for(r'Done \(')
+ ctl('launch', '--game', args.game.resolve(), '--offscreen', '--no-pause', '--name', NAME,
+ '--resources', args.resources.resolve(), '--render-distance', 2, '--width', 960, '--height', 720)
+ ctl('connect', f'127.0.0.1:{port}', NAME)
+ ctl('wait-ready', 400)
+ for line in (f'op {NAME}', 'gamerule spawn_mobs false', f'gamemode survival {NAME}',
+ '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'):
+ server.console(line)
+ game_time(server)
+ ctl('wait', 20)
+ for label, distance, inputs, expected in CASES:
+ server.console(f'kill {PIG}')
+ 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)
+ before = pig_health()
+ server.console('tick rate 1')
+ game_time(server)
+ ctl('wait', 2)
+ ctl('wait', 1)
+ for action in inputs:
+ ctl(*action.split())
+ server.console('tick rate 20')
+ game_time(server)
+ ctl('wait', 10)
+ after = pig_health()
+ hit = after < before
+ result = dict(label=label, distance=distance, health_before=before, health_after=after,
+ hit=hit, expected=expected, pass_=hit == expected)
+ results.append(result)
+ (output / 'results.json').write_text(json.dumps(results, indent=2))
+ print(json.dumps(result), flush=True)
+ finally:
+ try:
+ ctl('quit')
+ except (RuntimeError, subprocess.TimeoutExpired, json.JSONDecodeError):
+ pass
+ server.stop()
+ passed = sum(r['pass_'] for r in results)
+ print(f'{passed}/{len(results)} attack swaps match vanilla: {output}')
+ assert len(results) == len(CASES) and passed == len(results), results
+
+
+if __name__ == '__main__':
+ main()