Merge pull request #912 from rdbtCVS/t3/fix-grimac-false-flags
🤖 Agent: thanks rdbt! Verify passes. Checked locally merged with current main: fmt and clippy clean, cargo test -p horizon-client (885 passed), 14 harnesses including your two new oracles (player_sync, interaction_input, local_input, sprint_input, item_use, item_use_start, item_use_lifecycle, use_item_on, teleport_consume, lan, dedicated_server, server_player_combat, server_player_targets, server_entities), and lan_e2e pvp, hurt, eat, eating, clicks, chat, respawn in both modes: all pass. Fixes #903.
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
use horizon_client::interaction_input::{
|
||||
Button, InteractionInput, InteractionWorld, TargetUseWorld, use_on_target,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
struct World {
|
||||
using: bool,
|
||||
destroying: bool,
|
||||
entity: bool,
|
||||
dig_on_attack: bool,
|
||||
begin_using: bool,
|
||||
delay: u32,
|
||||
events: Vec<String>,
|
||||
passing: bool,
|
||||
}
|
||||
impl InteractionWorld for World {
|
||||
fn using_item(&self) -> bool {
|
||||
self.using
|
||||
}
|
||||
fn release_using(&mut self) {
|
||||
self.events.push("release".into());
|
||||
self.using = false;
|
||||
}
|
||||
fn start_attack(&mut self) -> bool {
|
||||
self.events.push("attack".into());
|
||||
if !self.entity {
|
||||
self.destroying = self.dig_on_attack;
|
||||
}
|
||||
false
|
||||
}
|
||||
fn start_use(&mut self) {
|
||||
if self.destroying {
|
||||
return;
|
||||
}
|
||||
self.delay = 4;
|
||||
let entity = self.entity;
|
||||
use_on_target(self, entity);
|
||||
}
|
||||
fn pick(&mut self) {
|
||||
self.events.push("pick".into());
|
||||
}
|
||||
fn use_delay(&self) -> u32 {
|
||||
self.delay
|
||||
}
|
||||
fn continue_attack(&mut self, down: bool) {
|
||||
if self.using {
|
||||
return;
|
||||
}
|
||||
let down = down && !self.entity;
|
||||
self.events.push(format!("continue {down}"));
|
||||
if !down {
|
||||
self.destroying = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TargetUseWorld for World {
|
||||
fn use_entity(&mut self) -> bool {
|
||||
self.events
|
||||
.push(if self.passing { "entity" } else { "use" }.into());
|
||||
if self.passing {
|
||||
false
|
||||
} else {
|
||||
self.using = self.begin_using;
|
||||
true
|
||||
}
|
||||
}
|
||||
fn use_block(&mut self) -> bool {
|
||||
self.events
|
||||
.push(if self.passing { "block" } else { "use" }.into());
|
||||
if self.passing {
|
||||
false
|
||||
} else {
|
||||
self.using = self.begin_using;
|
||||
true
|
||||
}
|
||||
}
|
||||
fn use_item(&mut self) {
|
||||
self.events.push("item".into());
|
||||
self.using = self.begin_using;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
let input = std::io::BufReader::new(std::fs::File::open(&args[1])?);
|
||||
let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?);
|
||||
for (i, line) in input.lines().enumerate() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let flag = |key: &str| row[key].as_bool().unwrap();
|
||||
let mut world = World {
|
||||
using: flag("using"),
|
||||
destroying: flag("destroying"),
|
||||
entity: flag("entity"),
|
||||
dig_on_attack: flag("dig_on_attack"),
|
||||
begin_using: flag("begin_using"),
|
||||
delay: row["delay"].as_u64().unwrap() as u32,
|
||||
events: vec![],
|
||||
passing: row["passing"].as_bool().unwrap_or(false),
|
||||
};
|
||||
let mut input = InteractionInput::default();
|
||||
for button in row["clicks"].as_array().unwrap() {
|
||||
input.press(match button.as_u64().unwrap() {
|
||||
0 => Button::Attack,
|
||||
1 => Button::Use,
|
||||
_ => Button::Pick,
|
||||
});
|
||||
}
|
||||
input.tick(&mut world, flag("attack_down"), flag("use_down"));
|
||||
writeln!(out, "== {i}")?;
|
||||
for event in world.events {
|
||||
writeln!(out, "{event}")?;
|
||||
}
|
||||
writeln!(
|
||||
out,
|
||||
"state {} {} {}",
|
||||
world.using, world.destroying, world.delay
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use horizon_client::player_sync::{PositionSender, teleport_velocity};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use horizon_protocol::packets::play::{PlayerPosition, Serverbound as S};
|
||||
use serde_json::Value;
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
fn number(value: &Value) -> f64 {
|
||||
f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap())
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
let input = std::io::BufReader::new(std::fs::File::open(&args[1])?);
|
||||
let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?);
|
||||
for line in input.lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
if row["kind"] == "movement" {
|
||||
let mut sender = PositionSender::default();
|
||||
for op in row["ops"].as_array().unwrap() {
|
||||
let pos = std::array::from_fn(|i| number(&op[i]));
|
||||
let rot = (number(&op[3]) as f32, number(&op[4]) as f32);
|
||||
if let Some(packet) =
|
||||
sender.update(pos, rot, op[5].as_bool().unwrap(), op[6].as_bool().unwrap())
|
||||
{
|
||||
let name = match packet {
|
||||
S::MovePlayerPos(_) => "pos",
|
||||
S::MovePlayerPosRot(_) => "posrot",
|
||||
S::MovePlayerRot(_) => "rot",
|
||||
S::MovePlayerStatus(_) => "status",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
write!(out, "{name} ")?;
|
||||
for byte in &packet.encode()[1..] {
|
||||
write!(out, "{byte:02x}")?;
|
||||
}
|
||||
writeln!(out)?;
|
||||
} else {
|
||||
writeln!(out, "-")?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let vector = |key: &str| {
|
||||
Vec3::new(
|
||||
number(&row[key][0]),
|
||||
number(&row[key][1]),
|
||||
number(&row[key][2]),
|
||||
)
|
||||
};
|
||||
let rotation = |key: &str| (number(&row[key][0]) as f32, number(&row[key][1]) as f32);
|
||||
let old = rotation("old");
|
||||
let new = rotation("new");
|
||||
let delta = vector("delta");
|
||||
let packet = PlayerPosition {
|
||||
teleport: 0,
|
||||
position: [0.0; 3],
|
||||
delta: [delta.x, delta.y, delta.z],
|
||||
yaw: new.0,
|
||||
pitch: new.1,
|
||||
relatives: row["flags"].as_i64().unwrap() as i32,
|
||||
};
|
||||
let v = teleport_velocity(vector("velocity"), old, new, &packet);
|
||||
writeln!(
|
||||
out,
|
||||
"{:016x} {:016x} {:016x}",
|
||||
v.x.to_bits(),
|
||||
v.y.to_bits(),
|
||||
v.z.to_bits()
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl Game<'_> {
|
||||
});
|
||||
self.clicks.destroying = destroying;
|
||||
self.attack_clicks = 0;
|
||||
self.stop_remote_mining();
|
||||
self.request_remote_mining_stop();
|
||||
self.mining = None;
|
||||
}
|
||||
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
|
||||
|
||||
@@ -94,11 +94,7 @@ pub(super) struct Remote {
|
||||
biome_bits: u8,
|
||||
view_distance: i32,
|
||||
sequence: i32,
|
||||
last_pos: [f64; 3],
|
||||
last_rot: (f32, f32),
|
||||
last_on_ground: bool,
|
||||
last_collision: bool,
|
||||
reminder: u32,
|
||||
position_sender: horizon_client::player_sync::PositionSender,
|
||||
last_input: u8,
|
||||
was_sprinting: bool,
|
||||
carried: Option<usize>,
|
||||
@@ -144,6 +140,8 @@ pub(super) struct Remote {
|
||||
profile: u128,
|
||||
destroying: Option<([i32; 3], u8, f32)>,
|
||||
destroy_delay: u32,
|
||||
input: horizon_client::interaction_input::InteractionInput,
|
||||
stop_mining: bool,
|
||||
placing: Option<([i32; 3], u64)>,
|
||||
death_message: Option<String>,
|
||||
player_type: Option<Arc<MobType>>,
|
||||
@@ -278,6 +276,7 @@ impl Game<'_> {
|
||||
self.container = None;
|
||||
self.carried = None;
|
||||
self.using = None;
|
||||
self.clicks.miss_time = 0;
|
||||
self.set_mode_id(0);
|
||||
self.experience = Experience {
|
||||
level: 0,
|
||||
@@ -306,11 +305,7 @@ impl Game<'_> {
|
||||
biome_bits: 7,
|
||||
view_distance: self.settings.render_distance,
|
||||
sequence: 0,
|
||||
last_pos: [0.0; 3],
|
||||
last_rot: (0.0, 0.0),
|
||||
last_on_ground: false,
|
||||
last_collision: false,
|
||||
reminder: 0,
|
||||
position_sender: Default::default(),
|
||||
last_input: 0,
|
||||
was_sprinting: false,
|
||||
carried: None,
|
||||
@@ -339,6 +334,8 @@ impl Game<'_> {
|
||||
profile: 0,
|
||||
destroying: None,
|
||||
destroy_delay: 0,
|
||||
input: Default::default(),
|
||||
stop_mining: false,
|
||||
placing: None,
|
||||
death_message: None,
|
||||
player_type,
|
||||
@@ -664,6 +661,8 @@ impl Game<'_> {
|
||||
r.dimension = dimension;
|
||||
r.game_mode = spawn.game_type;
|
||||
r.loaded_sent = false;
|
||||
// A replacement LocalPlayer has a fresh sendPosition baseline.
|
||||
r.position_sender = Default::default();
|
||||
r.predictions.clear();
|
||||
self.set_mode_id(spawn.game_type);
|
||||
self.dim = Dim::from_id(&spawn.dimension);
|
||||
@@ -1224,6 +1223,9 @@ impl Game<'_> {
|
||||
|
||||
fn handle_packet(&mut self, packet: C) -> Result<()> {
|
||||
match packet {
|
||||
// ClientCommonPacketListenerImpl.handlePing runs on the game
|
||||
// thread, after all preceding packets (especially teleports).
|
||||
C::Ping(p) => self.send(S::Pong(p)),
|
||||
// PingDebugMonitor.onPongReceived.
|
||||
C::PongResponse(p) => {
|
||||
let delay = self.debug_millis() - p.time;
|
||||
@@ -2423,10 +2425,11 @@ impl Game<'_> {
|
||||
p.pitch
|
||||
})
|
||||
.clamp(-90.0, 90.0);
|
||||
let delta = Vec3::new(
|
||||
pick(rel::DELTA_X, velocity.x, p.delta[0]),
|
||||
pick(rel::DELTA_Y, velocity.y, p.delta[1]),
|
||||
pick(rel::DELTA_Z, velocity.z, p.delta[2]),
|
||||
let delta = horizon_client::player_sync::teleport_velocity(
|
||||
velocity,
|
||||
(self.yaw, self.pitch),
|
||||
(yaw, pitch),
|
||||
p,
|
||||
);
|
||||
match self.player.as_mut() {
|
||||
Some(player) => {
|
||||
@@ -2449,8 +2452,8 @@ impl Game<'_> {
|
||||
self.yaw = yaw;
|
||||
self.pitch = pitch;
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.last_pos = [position.x, position.y, position.z];
|
||||
r.last_rot = (yaw, pitch);
|
||||
// handleMovePlayer does not change LocalPlayer.sendPosition's
|
||||
// baseline: the next tick must still report the corrected state.
|
||||
r.destroying = None;
|
||||
}
|
||||
self.mining = None;
|
||||
@@ -2467,6 +2470,16 @@ impl Game<'_> {
|
||||
|
||||
/// One client tick while connected (Minecraft.tick with a ClientLevel).
|
||||
pub(super) fn tick_remote(&mut self) -> Result<()> {
|
||||
self.tick_remote_level()?;
|
||||
// Minecraft.tick sends this even when the player cannot tick yet,
|
||||
// including while waiting for chunks. Keep it outside early returns.
|
||||
if self.remote.as_ref().is_some_and(|r| r.joined) {
|
||||
self.send(S::ClientTickEnd(Empty));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tick_remote_level(&mut self) -> Result<()> {
|
||||
self.ticks += 1;
|
||||
// Options.broadcastOptions: a changed render distance is sent again.
|
||||
let view = client_view_distance(self.settings.render_distance);
|
||||
@@ -2493,6 +2506,10 @@ impl Game<'_> {
|
||||
if self.use_delay > 0 {
|
||||
self.use_delay -= 1;
|
||||
}
|
||||
// Minecraft.handleKeybinds precedes entity ticking and sendChanges.
|
||||
// Window callbacks only queue clicks, so an interaction cannot leak
|
||||
// between CLIENT_TICK_END and a later pong.
|
||||
self.remote_handle_input();
|
||||
// ClientLevel.tick: the border's size change.
|
||||
self.border.tick();
|
||||
self.tick_remote_entities(running);
|
||||
@@ -2515,13 +2532,11 @@ impl Game<'_> {
|
||||
(player.position.z.floor() as i32) >> 4,
|
||||
);
|
||||
if !self.streaming.is_lit(cx, cz) {
|
||||
// Moved where nothing is loaded by horizon-ctl (`tp`, `fly`):
|
||||
// the server hears of it, and sends the chunks there. A player
|
||||
// who walked there has already sent that move.
|
||||
let pos = [player.position.x, player.position.y, player.position.z];
|
||||
// LocalPlayer.tick can wait for chunks, but Minecraft.tick still
|
||||
// calls sendChanges: rotations and the 20-tick position reminder
|
||||
// must continue, as well as moves into the unloaded area.
|
||||
if let Some(r) = self.remote.as_ref()
|
||||
&& r.loaded_sent
|
||||
&& r.last_pos != pos
|
||||
{
|
||||
let input = r.last_input;
|
||||
self.remote_send_state(input);
|
||||
@@ -2620,16 +2635,9 @@ impl Game<'_> {
|
||||
// The player's own model (third person, the inventory's preview).
|
||||
self.tick_player_model();
|
||||
if !dead {
|
||||
self.remote_mining();
|
||||
// Minecraft.handleKeybinds: no new use while an item is in use.
|
||||
if self.right && self.use_delay == 0 && playing && self.using.is_none() {
|
||||
self.remote_use();
|
||||
self.use_delay = 4;
|
||||
}
|
||||
self.remote_tick_using();
|
||||
}
|
||||
self.remote_send_state(input);
|
||||
self.send(S::ClientTickEnd(Empty));
|
||||
Ok(())
|
||||
}
|
||||
/// The local player's share of every touching entity's
|
||||
@@ -2929,41 +2937,12 @@ impl Game<'_> {
|
||||
data: 0,
|
||||
}));
|
||||
}
|
||||
r.reminder += 1;
|
||||
let d = [
|
||||
pos[0] - r.last_pos[0],
|
||||
pos[1] - r.last_pos[1],
|
||||
pos[2] - r.last_pos[2],
|
||||
];
|
||||
let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || r.reminder >= 20;
|
||||
let rotated = yaw != r.last_rot.0 || pitch != r.last_rot.1;
|
||||
let flags = u8::from(on_ground) | u8::from(collision) << 1;
|
||||
let [x, y, z] = pos;
|
||||
if moved && rotated {
|
||||
out.push(S::MovePlayerPosRot(play::MovePlayerPosRot {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
yaw,
|
||||
pitch,
|
||||
flags,
|
||||
}));
|
||||
} else if moved {
|
||||
out.push(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags }));
|
||||
} else if rotated {
|
||||
out.push(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags }));
|
||||
} else if r.last_on_ground != on_ground || r.last_collision != collision {
|
||||
out.push(S::MovePlayerStatus(play::MovePlayerStatus { flags }));
|
||||
if let Some(packet) = r
|
||||
.position_sender
|
||||
.update(pos, (yaw, pitch), on_ground, collision)
|
||||
{
|
||||
out.push(packet);
|
||||
}
|
||||
if moved {
|
||||
r.last_pos = pos;
|
||||
r.reminder = 0;
|
||||
}
|
||||
if rotated {
|
||||
r.last_rot = (yaw, pitch);
|
||||
}
|
||||
r.last_on_ground = on_ground;
|
||||
r.last_collision = collision;
|
||||
// Creative inventory edits are sent slot by slot (SetCreativeModeSlot).
|
||||
let mut creative_slots = Vec::new();
|
||||
if self.creative {
|
||||
@@ -3006,16 +2985,12 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock.
|
||||
fn remote_mining(&mut self) {
|
||||
fn remote_mining(&mut self, start: bool) {
|
||||
let Some(r) = self.remote.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if r.destroy_delay > 0 {
|
||||
if !start && r.destroy_delay > 0 {
|
||||
r.destroy_delay -= 1;
|
||||
}
|
||||
if !self.left || self.screen != Screen::Playing {
|
||||
self.stop_remote_mining();
|
||||
self.mining = None;
|
||||
return;
|
||||
}
|
||||
let Some(hit) = self.pick() else {
|
||||
@@ -3027,11 +3002,6 @@ impl Game<'_> {
|
||||
if self.res.facts().is_air(state) {
|
||||
return;
|
||||
}
|
||||
if self.remote.as_ref().is_some_and(|r| r.destroy_delay > 0) {
|
||||
return;
|
||||
}
|
||||
self.swing_arm();
|
||||
self.send(S::Punch(Empty));
|
||||
if self.creative {
|
||||
let seq = self.next_sequence();
|
||||
self.predict_break(hit.pos, state, seq);
|
||||
@@ -3069,6 +3039,9 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.and_then(|r| r.destroying)
|
||||
.is_some_and(|(p, _, _)| p == hit.pos);
|
||||
if start && same {
|
||||
return;
|
||||
}
|
||||
if !same {
|
||||
if let Some((old, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) {
|
||||
self.send(S::PlayerAction(play::PlayerAction {
|
||||
@@ -3183,15 +3156,25 @@ impl Game<'_> {
|
||||
}
|
||||
self.mining = None;
|
||||
}
|
||||
/// Minecraft.startUseItem: use on the targeted block, then the item itself.
|
||||
/// Minecraft.startUseItem: use one crosshair target, then the item itself.
|
||||
fn remote_use(&mut self) {
|
||||
let held_block = self
|
||||
.held()
|
||||
.and_then(|h| self.res.items().get(&h.item))
|
||||
.is_some_and(|i| i.block.is_some());
|
||||
// Minecraft.startUseItem returns before resetting rightClickDelay
|
||||
// while a survival block break is active.
|
||||
if self.remote.as_ref().is_some_and(|r| r.destroying.is_some()) {
|
||||
return;
|
||||
}
|
||||
self.use_delay = 4;
|
||||
// Resolve the crosshair once. A passing entity interaction keeps
|
||||
// that target and may only fall back to using the item itself.
|
||||
let entity = self.entity_targeted();
|
||||
horizon_client::interaction_input::use_on_target(&mut RemoteUseWorld(self), entity);
|
||||
}
|
||||
|
||||
fn remote_use_entity(&mut self) -> bool {
|
||||
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
|
||||
// Entities first (interact), like the hit result order.
|
||||
if let Some((i, _)) = self.mob_hit() {
|
||||
if let Some((i, distance)) = self.mob_hit()
|
||||
&& self.before_block(distance)
|
||||
{
|
||||
let id = self.mobs[i].id as i32;
|
||||
self.send(S::Interact(play::Interact {
|
||||
id,
|
||||
@@ -3207,9 +3190,17 @@ impl Game<'_> {
|
||||
.is_some_and(|r| r.level_players.contains_key(&id));
|
||||
if !player {
|
||||
self.swing_arm();
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn remote_use_block(&mut self) -> bool {
|
||||
let held_block = self
|
||||
.held()
|
||||
.and_then(|h| self.res.items().get(&h.item))
|
||||
.is_some_and(|i| i.block.is_some());
|
||||
if let Some(hit) = self.pick() {
|
||||
let seq = self.next_sequence();
|
||||
let cursor = [
|
||||
@@ -3238,9 +3229,13 @@ impl Game<'_> {
|
||||
}
|
||||
if held_block {
|
||||
self.swing_arm();
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn remote_use_item(&mut self) {
|
||||
if let Some(held) = self.held().cloned() {
|
||||
let seq = self.next_sequence();
|
||||
self.send(S::UseItem(play::UseItem {
|
||||
@@ -3272,7 +3267,10 @@ impl Game<'_> {
|
||||
self.using = None;
|
||||
return;
|
||||
};
|
||||
if !self.right || slot != self.selected || self.screen != Screen::Playing {
|
||||
// Button release belongs to the next handleKeybinds phase, which
|
||||
// sends RELEASE_USE_ITEM. Do not silently clear a use begun by a
|
||||
// quick press/release between ticks.
|
||||
if slot != self.selected {
|
||||
self.using = None;
|
||||
return;
|
||||
}
|
||||
@@ -3291,52 +3289,139 @@ impl Game<'_> {
|
||||
self.using = Some((slot, ticks + 1));
|
||||
}
|
||||
}
|
||||
/// Left click: attack the targeted entity (MultiPlayerGameMode.attack).
|
||||
/// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick.
|
||||
pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
|
||||
if self.screen == Screen::Chat {
|
||||
return Ok(());
|
||||
}
|
||||
match button {
|
||||
use horizon_client::interaction_input::Button;
|
||||
let input = match button {
|
||||
MouseButton::Left => {
|
||||
if pressed && let Some((i, _)) = self.mob_hit() {
|
||||
let id = self.mobs[i].id as i32;
|
||||
self.send(S::Attack(play::Attack { id }));
|
||||
self.send(S::Punch(Empty));
|
||||
self.swing_arm();
|
||||
return Ok(());
|
||||
}
|
||||
if pressed && self.pick().is_none() {
|
||||
self.send(S::Punch(Empty));
|
||||
self.swing_arm();
|
||||
}
|
||||
self.left = pressed;
|
||||
self.toggles
|
||||
.button(2, pressed, false, self.settings.toggle_attack);
|
||||
self.left = self.toggles.is_down(2);
|
||||
Some(Button::Attack)
|
||||
}
|
||||
MouseButton::Right => {
|
||||
self.right = pressed;
|
||||
if pressed {
|
||||
self.remote_use();
|
||||
self.use_delay = 4;
|
||||
} else {
|
||||
self.send(S::PlayerAction(play::PlayerAction {
|
||||
action: 6,
|
||||
pos: [0; 3],
|
||||
direction: 0,
|
||||
sequence: 0,
|
||||
}));
|
||||
}
|
||||
self.toggles
|
||||
.button(3, pressed, false, self.settings.toggle_use);
|
||||
self.right = self.toggles.is_down(3);
|
||||
Some(Button::Use)
|
||||
}
|
||||
MouseButton::Middle if pressed => {
|
||||
if let Some(hit) = self.pick() {
|
||||
self.send(S::PickItemFromBlock(play::PickItemFromBlock {
|
||||
pos: hit.pos,
|
||||
include_data: self.has_control_down(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
MouseButton::Middle => Some(Button::Pick),
|
||||
_ => None,
|
||||
};
|
||||
if pressed
|
||||
&& let Some(button) = input
|
||||
&& let Some(remote) = self.remote.as_mut()
|
||||
{
|
||||
remote.input.press(button);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn request_remote_mining_stop(&mut self) {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.stop_mining = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_handle_input(&mut self) {
|
||||
let Some(r) = self.remote.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let mut input = std::mem::take(&mut r.input);
|
||||
let stop = std::mem::take(&mut r.stop_mining);
|
||||
let ready = r.loaded_sent && self.screen == Screen::Playing && self.sleeping.is_none();
|
||||
if stop || !ready {
|
||||
self.stop_remote_mining();
|
||||
}
|
||||
if !ready {
|
||||
return;
|
||||
}
|
||||
// MultiPlayerGameMode.tick syncs the carried slot before keybinds.
|
||||
let carried_changed = self.remote.as_mut().is_some_and(|r| {
|
||||
if r.carried == Some(self.selected) {
|
||||
false
|
||||
} else {
|
||||
r.carried = Some(self.selected);
|
||||
true
|
||||
}
|
||||
});
|
||||
if carried_changed {
|
||||
self.send(S::SetCarriedItem(play::SetCarriedItem {
|
||||
slot: self.selected as i16,
|
||||
}));
|
||||
}
|
||||
let (attack, use_item) = (self.left, self.right);
|
||||
input.tick(&mut RemoteInputWorld(self), attack, use_item);
|
||||
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 {
|
||||
if self.clicks.miss_time > 0 {
|
||||
return false;
|
||||
}
|
||||
if self.spectator() {
|
||||
return true;
|
||||
}
|
||||
let mut instant = false;
|
||||
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.reset_attack_strength();
|
||||
} else if !self.entity_targeted()
|
||||
&& let Some(hit) = self.pick()
|
||||
{
|
||||
self.remote_mining(true);
|
||||
instant = self
|
||||
.res
|
||||
.facts()
|
||||
.is_air(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
|
||||
} else {
|
||||
if !self.creative {
|
||||
self.clicks.miss_time = 10;
|
||||
}
|
||||
self.reset_attack_strength();
|
||||
}
|
||||
self.swing_arm();
|
||||
self.send(S::Punch(Empty));
|
||||
instant
|
||||
}
|
||||
|
||||
fn remote_continue_attack(&mut self, down: bool) {
|
||||
if !down {
|
||||
self.clicks.miss_time = 0;
|
||||
}
|
||||
if self.clicks.miss_time > 0 || self.using.is_some() {
|
||||
return;
|
||||
}
|
||||
let entity = self.entity_targeted();
|
||||
if down
|
||||
&& !entity
|
||||
&& let Some(hit) = self.pick()
|
||||
{
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
if !self.res.facts().is_air(state) {
|
||||
self.remote_mining(false);
|
||||
self.swing_arm();
|
||||
self.send(S::Punch(Empty));
|
||||
} else {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.destroying = None;
|
||||
}
|
||||
self.mining = None;
|
||||
}
|
||||
} else {
|
||||
self.stop_remote_mining();
|
||||
self.mining = None;
|
||||
}
|
||||
}
|
||||
/// Keys with a multiplayer meaning; returns true when consumed.
|
||||
pub(super) fn remote_key(&mut self, key: KeyCode) -> Result<bool> {
|
||||
if self.screen != Screen::Playing {
|
||||
@@ -4056,6 +4141,57 @@ fn client_view_distance(render_distance: i32) -> i8 {
|
||||
render_distance.clamp(2, i32::from(i8::MAX)) as i8
|
||||
}
|
||||
|
||||
struct RemoteInputWorld<'g, 'a>(&'g mut Game<'a>);
|
||||
|
||||
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()
|
||||
}
|
||||
fn use_block(&mut self) -> bool {
|
||||
self.0.remote_use_block()
|
||||
}
|
||||
fn use_item(&mut self) {
|
||||
self.0.remote_use_item();
|
||||
}
|
||||
}
|
||||
|
||||
impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_, '_> {
|
||||
fn using_item(&self) -> bool {
|
||||
self.0.using.is_some()
|
||||
}
|
||||
fn release_using(&mut self) {
|
||||
self.0.send(S::PlayerAction(play::PlayerAction {
|
||||
action: 6,
|
||||
pos: [0; 3],
|
||||
direction: 0,
|
||||
sequence: 0,
|
||||
}));
|
||||
self.0.using = None;
|
||||
}
|
||||
fn start_attack(&mut self) -> bool {
|
||||
self.0.remote_start_attack()
|
||||
}
|
||||
fn start_use(&mut self) {
|
||||
self.0.remote_use();
|
||||
}
|
||||
fn pick(&mut self) {
|
||||
if let Some(hit) = self.0.pick() {
|
||||
self.0.send(S::PickItemFromBlock(play::PickItemFromBlock {
|
||||
pos: hit.pos,
|
||||
include_data: self.0.has_control_down(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
fn use_delay(&self) -> u32 {
|
||||
self.0.use_delay
|
||||
}
|
||||
fn continue_attack(&mut self, down: bool) {
|
||||
self.0.remote_continue_attack(down);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Game;
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
//! The mouse-key portion of Minecraft.handleKeybinds. Events only count clicks;
|
||||
//! the client tick consumes them before player movement and CLIENT_TICK_END.
|
||||
#[derive(Default)]
|
||||
pub struct InteractionInput {
|
||||
clicks: [u32; 3],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Button {
|
||||
Attack,
|
||||
Use,
|
||||
Pick,
|
||||
}
|
||||
|
||||
pub trait InteractionWorld {
|
||||
fn using_item(&self) -> bool;
|
||||
fn release_using(&mut self);
|
||||
fn start_attack(&mut self) -> bool;
|
||||
fn start_use(&mut self);
|
||||
fn pick(&mut self);
|
||||
fn use_delay(&self) -> u32;
|
||||
fn continue_attack(&mut self, down: bool);
|
||||
}
|
||||
|
||||
/// Minecraft.startUseItem dispatches one hit result per hand. A passing
|
||||
/// entity interaction falls back to the item, without trying a block behind it.
|
||||
pub trait TargetUseWorld {
|
||||
fn use_entity(&mut self) -> bool;
|
||||
fn use_block(&mut self) -> bool;
|
||||
fn use_item(&mut self);
|
||||
}
|
||||
|
||||
pub fn use_on_target(world: &mut impl TargetUseWorld, entity: bool) {
|
||||
let consumed = if entity {
|
||||
world.use_entity()
|
||||
} else {
|
||||
world.use_block()
|
||||
};
|
||||
if !consumed {
|
||||
world.use_item();
|
||||
}
|
||||
}
|
||||
|
||||
impl InteractionInput {
|
||||
pub fn press(&mut self, button: Button) {
|
||||
self.clicks[button as usize] += 1;
|
||||
}
|
||||
|
||||
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);
|
||||
let mut instant = false;
|
||||
if world.using_item() {
|
||||
if !use_down {
|
||||
world.release_using();
|
||||
}
|
||||
// Vanilla drains all three click queues while using an item,
|
||||
// including the tick that releases it.
|
||||
} else {
|
||||
for _ in 0..attack {
|
||||
instant |= world.start_attack();
|
||||
}
|
||||
for _ in 0..use_item {
|
||||
world.start_use();
|
||||
}
|
||||
for _ in 0..pick {
|
||||
world.pick();
|
||||
}
|
||||
}
|
||||
if use_down && world.use_delay() == 0 && !world.using_item() {
|
||||
world.start_use();
|
||||
}
|
||||
world.continue_attack(!instant && attack_down);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct World {
|
||||
using: bool,
|
||||
destroying: bool,
|
||||
delay: u32,
|
||||
begin_using: bool,
|
||||
events: Vec<&'static str>,
|
||||
}
|
||||
impl InteractionWorld for World {
|
||||
fn using_item(&self) -> bool {
|
||||
self.using
|
||||
}
|
||||
fn release_using(&mut self) {
|
||||
self.events.push("release");
|
||||
self.using = false;
|
||||
}
|
||||
fn start_attack(&mut self) -> bool {
|
||||
self.events.push("attack");
|
||||
false
|
||||
}
|
||||
fn start_use(&mut self) {
|
||||
if !self.destroying {
|
||||
self.events.push("use");
|
||||
self.delay = 4;
|
||||
self.using = self.begin_using;
|
||||
}
|
||||
}
|
||||
fn pick(&mut self) {
|
||||
self.events.push("pick");
|
||||
}
|
||||
fn use_delay(&self) -> u32 {
|
||||
self.delay
|
||||
}
|
||||
fn continue_attack(&mut self, _: bool) {
|
||||
self.events.push("continue");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_clicks_wait_for_a_tick_and_follow_keybind_order() {
|
||||
let mut input = InteractionInput::default();
|
||||
let mut world = World::default();
|
||||
input.press(Button::Use);
|
||||
input.press(Button::Pick);
|
||||
input.press(Button::Attack);
|
||||
assert!(world.events.is_empty());
|
||||
// Both edges can arrive between ticks; the press still acts once.
|
||||
input.tick(&mut world, false, false);
|
||||
assert_eq!(world.events, ["attack", "use", "pick", "continue"]);
|
||||
world.events.clear();
|
||||
input.tick(&mut world, false, false);
|
||||
assert_eq!(
|
||||
world.events,
|
||||
["continue"],
|
||||
"no spurious release or repeated click"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releasing_actual_item_use_discards_clicks_for_that_tick() {
|
||||
let mut input = InteractionInput::default();
|
||||
let mut world = World {
|
||||
using: true,
|
||||
..Default::default()
|
||||
};
|
||||
for button in [Button::Attack, Button::Use, Button::Pick] {
|
||||
input.press(button);
|
||||
}
|
||||
input.tick(&mut world, true, false);
|
||||
assert_eq!(world.events, ["release", "continue"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holding_use_respects_the_delay_and_active_digging() {
|
||||
let mut input = InteractionInput::default();
|
||||
let mut world = World {
|
||||
destroying: true,
|
||||
..Default::default()
|
||||
};
|
||||
input.press(Button::Use);
|
||||
input.tick(&mut world, true, true);
|
||||
assert_eq!(world.events, ["continue"]);
|
||||
world.destroying = false;
|
||||
world.events.clear();
|
||||
input.tick(&mut world, false, true);
|
||||
assert_eq!(world.events, ["use", "continue"]);
|
||||
world.events.clear();
|
||||
input.tick(&mut world, false, true);
|
||||
assert_eq!(world.events, ["continue"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quick_use_click_releases_on_the_following_tick() {
|
||||
let mut input = InteractionInput::default();
|
||||
let mut world = World {
|
||||
begin_using: true,
|
||||
..Default::default()
|
||||
};
|
||||
input.press(Button::Use);
|
||||
input.tick(&mut world, false, false);
|
||||
assert_eq!(world.events, ["use", "continue"]);
|
||||
assert!(world.using);
|
||||
world.events.clear();
|
||||
input.tick(&mut world, false, false);
|
||||
assert_eq!(world.events, ["release", "continue"]);
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,7 @@ pub mod hud_layout;
|
||||
pub mod hud_overlays;
|
||||
pub mod hunger;
|
||||
pub mod input;
|
||||
pub mod interaction_input;
|
||||
pub mod inv_sort;
|
||||
pub mod inventory_effects;
|
||||
pub mod item_data;
|
||||
@@ -133,6 +134,7 @@ pub mod particles;
|
||||
pub mod patrol;
|
||||
pub mod perf_overlay;
|
||||
pub mod pick_item;
|
||||
pub mod player_sync;
|
||||
pub mod poi_sections;
|
||||
pub mod portal_sections;
|
||||
pub mod pose;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Multiplayer session: a network thread that connects to a server, logs in,
|
||||
//! runs the configuration phase and then forwards decoded play packets to the
|
||||
//! game thread. Keep-alives and pings are answered on the network thread like
|
||||
//! vanilla's connection handlers so a busy frame never times the client out.
|
||||
//! game thread. Keep-alives are answered on the network thread; pings wait for
|
||||
//! the game thread, like ClientCommonPacketListenerImpl.handlePing, so a pong
|
||||
//! cannot overtake an earlier world update or teleport acknowledgement.
|
||||
//! Online-mode servers need the Microsoft account the launcher signed in
|
||||
//! (crate::auth): the login joins the server through the session service and
|
||||
//! encrypts the connection (ClientHandshakePacketListenerImpl.handleHello).
|
||||
@@ -382,8 +383,17 @@ fn run(
|
||||
uuid: profile.uuid,
|
||||
name: profile.name,
|
||||
});
|
||||
receive_play(&mut reader, shared_writer, lang, send)
|
||||
}
|
||||
|
||||
fn receive_play(
|
||||
reader: &mut ConnReader,
|
||||
shared_writer: &Mutex<Option<ConnWriter>>,
|
||||
lang: &Language,
|
||||
send: &Sender<Event>,
|
||||
) -> Result<String, String> {
|
||||
loop {
|
||||
let (id, payload) = reader.recv().map_err(e)?;
|
||||
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
|
||||
let packet = match play::Clientbound::decode(id, &payload) {
|
||||
Ok(p) => p,
|
||||
Err(err) => {
|
||||
@@ -404,7 +414,6 @@ fn run(
|
||||
};
|
||||
match packet {
|
||||
play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)),
|
||||
play::Clientbound::Ping(p) => reply(play::Serverbound::Pong(p)),
|
||||
play::Clientbound::BundleDelimiter(_) => {}
|
||||
play::Clientbound::ResourcePackPush(p) => {
|
||||
// Declined: Horizon has no server resource packs.
|
||||
@@ -415,7 +424,7 @@ fn run(
|
||||
}
|
||||
play::Clientbound::StartConfiguration(_) => {
|
||||
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
|
||||
let registries = configure(&mut reader, shared_writer, lang, send)?;
|
||||
let registries = configure(reader, shared_writer, lang, send)?;
|
||||
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
|
||||
}
|
||||
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
|
||||
@@ -585,6 +594,50 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pings_wait_behind_teleports_but_keepalives_do_not_wait_for_the_game() {
|
||||
let (client, server) = horizon_protocol::connection::Pipe::pair();
|
||||
let (mut reader, writer) = Connection::local(client).split();
|
||||
let writer = Arc::new(Mutex::new(Some(writer)));
|
||||
let (send, events) = channel();
|
||||
let thread_writer = writer.clone();
|
||||
let thread = std::thread::spawn(move || {
|
||||
receive_play(&mut reader, &thread_writer, &Language::new(), &send)
|
||||
});
|
||||
let mut server = Connection::local(server);
|
||||
let teleport = play::Clientbound::PlayerPosition(play::PlayerPosition {
|
||||
teleport: 42,
|
||||
position: [10.0, 64.0, 10.0],
|
||||
delta: [0.0; 3],
|
||||
yaw: 90.0,
|
||||
pitch: 0.0,
|
||||
relatives: 0,
|
||||
});
|
||||
server.send(&teleport.encode()).unwrap();
|
||||
server
|
||||
.send(&play::Clientbound::Ping(cfg::Ping { id: 7 }).encode())
|
||||
.unwrap();
|
||||
// A reply to this proves the receive loop has passed the ping. The
|
||||
// old implementation instead replies with Pong before this keepalive.
|
||||
server
|
||||
.send(&play::Clientbound::KeepAlive(cfg::KeepAlive { id: 9 }).encode())
|
||||
.unwrap();
|
||||
let (id, body) = server.recv().unwrap();
|
||||
assert_eq!(
|
||||
play::Serverbound::decode(id, &body).unwrap(),
|
||||
play::Serverbound::KeepAlive(cfg::KeepAlive { id: 9 })
|
||||
);
|
||||
let timeout = Duration::from_secs(5);
|
||||
assert!(
|
||||
matches!(events.recv_timeout(timeout).unwrap(), Event::Packet(p) if *p == teleport)
|
||||
);
|
||||
assert!(
|
||||
matches!(events.recv_timeout(timeout).unwrap(), Event::Packet(p) if *p == play::Clientbound::Ping(cfg::Ping { id: 7 }))
|
||||
);
|
||||
writer.lock().unwrap().take().unwrap().shutdown();
|
||||
assert!(thread.join().unwrap().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() {
|
||||
let (send, events) = channel();
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! LocalPlayer.sendPosition and PositionMoveRotation.calculateAbsolute.
|
||||
use horizon_core::geometry::Vec3;
|
||||
use horizon_protocol::packets::play::{self, PlayerPosition, Serverbound as S, relative};
|
||||
|
||||
/// Only movement updates advance this baseline. A teleport acknowledgement is
|
||||
/// separate and must not suppress the next tick's corrected position or look.
|
||||
#[derive(Default)]
|
||||
pub struct PositionSender {
|
||||
position: [f64; 3],
|
||||
rotation: (f32, f32),
|
||||
on_ground: bool,
|
||||
collision: bool,
|
||||
reminder: u32,
|
||||
}
|
||||
|
||||
impl PositionSender {
|
||||
pub fn update(
|
||||
&mut self,
|
||||
position: [f64; 3],
|
||||
rotation: (f32, f32),
|
||||
on_ground: bool,
|
||||
collision: bool,
|
||||
) -> Option<S> {
|
||||
self.reminder += 1;
|
||||
let d: [f64; 3] = std::array::from_fn(|i| position[i] - self.position[i]);
|
||||
let moved =
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || self.reminder >= 20;
|
||||
let rotated = rotation.0 - self.rotation.0 != 0.0 || rotation.1 - self.rotation.1 != 0.0;
|
||||
let flags = u8::from(on_ground) | u8::from(collision) << 1;
|
||||
let [x, y, z] = position;
|
||||
let (yaw, pitch) = rotation;
|
||||
let packet = if moved && rotated {
|
||||
Some(S::MovePlayerPosRot(play::MovePlayerPosRot {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
yaw,
|
||||
pitch,
|
||||
flags,
|
||||
}))
|
||||
} else if moved {
|
||||
Some(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags }))
|
||||
} else if rotated {
|
||||
Some(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags }))
|
||||
} else if self.on_ground != on_ground || self.collision != collision {
|
||||
Some(S::MovePlayerStatus(play::MovePlayerStatus { flags }))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if moved {
|
||||
self.position = position;
|
||||
self.reminder = 0;
|
||||
}
|
||||
if rotated {
|
||||
self.rotation = rotation;
|
||||
}
|
||||
self.on_ground = on_ground;
|
||||
self.collision = collision;
|
||||
packet
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotate the old velocity before adding the relative delta components.
|
||||
/// Angles deliberately use Java's double toRadians followed by a float cast.
|
||||
pub fn teleport_velocity(
|
||||
mut velocity: Vec3,
|
||||
old_rotation: (f32, f32),
|
||||
new_rotation: (f32, f32),
|
||||
packet: &PlayerPosition,
|
||||
) -> Vec3 {
|
||||
if packet.relatives & relative::ROTATE_DELTA != 0 {
|
||||
let pitch = f64::from(old_rotation.1 - new_rotation.1).to_radians() as f32;
|
||||
let yaw = f64::from(old_rotation.0 - new_rotation.0).to_radians() as f32;
|
||||
velocity = velocity.rotate_x(pitch).rotate_y(yaw);
|
||||
}
|
||||
let old = [velocity.x, velocity.y, velocity.z];
|
||||
let flags = [relative::DELTA_X, relative::DELTA_Y, relative::DELTA_Z];
|
||||
let result: [f64; 3] = std::array::from_fn(|i| {
|
||||
if packet.relatives & flags[i] != 0 {
|
||||
old[i] + packet.delta[i]
|
||||
} else {
|
||||
packet.delta[i]
|
||||
}
|
||||
});
|
||||
Vec3::new(result[0], result[1], result[2])
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.multiplayer.*;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.world.*;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.player.*;
|
||||
import net.minecraft.world.flag.*;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.SwingAnimation;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.WorldBorder;
|
||||
import net.minecraft.world.phys.*;
|
||||
|
||||
/** Runs the shipped handleKeybinds; only game-mode effects and UI are shells. */
|
||||
public final class VanillaInteractionInputOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
static List<String> events = new ArrayList<>();
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name); f.setAccessible(true); return f;
|
||||
}
|
||||
static <T> T make(Class<T> type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); }
|
||||
public static class MC extends Minecraft {
|
||||
public MC() { super(null); }
|
||||
@Override public boolean hasControlDown() { return false; }
|
||||
}
|
||||
public static class UI extends Gui {
|
||||
public UI() { super(null, null, null); }
|
||||
@Override public void handleKeybinds() {}
|
||||
}
|
||||
public static class Mouse extends MouseHandler {
|
||||
public Mouse() { super(null); }
|
||||
@Override public boolean isMouseGrabbed() { return true; }
|
||||
}
|
||||
public static class Level extends ClientLevel {
|
||||
public Level() { super(null, null, null, null, 0, 0, null, false, 0L, 0); }
|
||||
@Override public BlockState getBlockState(BlockPos pos) { return Blocks.STONE.defaultBlockState(); }
|
||||
@Override public FeatureFlagSet enabledFeatures() { return FeatureFlags.REGISTRY.allFlags(); }
|
||||
}
|
||||
public static class Connection extends ClientPacketListener {
|
||||
public Connection() { super(null, null, null); }
|
||||
@Override public void send(Packet<?> packet) {}
|
||||
}
|
||||
public static class Human extends LocalPlayer {
|
||||
boolean using;
|
||||
ItemStack held = ItemStack.EMPTY;
|
||||
public Human() { super(null, null, null, null, null, null, false, null, null); }
|
||||
@Override public boolean isUsingItem() { return using; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
@Override public boolean isCreative() { return false; }
|
||||
@Override public boolean isHandsBusy() { return false; }
|
||||
@Override public ItemStack getItemInHand(InteractionHand hand) {
|
||||
return hand == InteractionHand.MAIN_HAND ? held : ItemStack.EMPTY;
|
||||
}
|
||||
@Override public void itemUsed(InteractionHand hand) {}
|
||||
@Override public boolean cannotAttackWithItem(ItemStack item, int slot) { return false; }
|
||||
@Override public boolean isWithinEntityInteractionRange(Entity e, double buffer) { return true; }
|
||||
@Override public boolean swing(InteractionHand hand, SwingAnimation animation, boolean send) { return false; }
|
||||
}
|
||||
public static class Mode extends MultiPlayerGameMode {
|
||||
boolean destroying, digOnAttack, beginUsing, passing;
|
||||
Human player;
|
||||
public Mode() { super(null, null); }
|
||||
@Override public boolean isDestroying() { return destroying; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
@Override public boolean startDestroyBlock(BlockPos pos, Direction face) {
|
||||
events.add("attack"); destroying = digOnAttack; return true;
|
||||
}
|
||||
@Override public boolean continueDestroyBlock(BlockPos pos, Direction face) {
|
||||
events.add("continue true"); return true;
|
||||
}
|
||||
@Override public void stopDestroyBlock() { events.add("continue false"); destroying = false; }
|
||||
@Override public void attack(Player p, Entity e) { events.add("attack"); }
|
||||
@Override public void releaseUsingItem(Player p) { events.add("release"); player.using = false; }
|
||||
InteractionResult use() { events.add("use"); player.using = beginUsing; return InteractionResult.SUCCESS_SERVER; }
|
||||
@Override public InteractionResult useItemOn(LocalPlayer p, InteractionHand h, BlockHitResult hit) {
|
||||
if (passing) { events.add("block"); return InteractionResult.PASS; }
|
||||
return use();
|
||||
}
|
||||
@Override public InteractionResult interact(Player p, Entity e, EntityHitResult hit, InteractionHand h) {
|
||||
if (passing) { events.add("entity"); return InteractionResult.PASS; }
|
||||
return use();
|
||||
}
|
||||
@Override public InteractionResult useItem(Player p, InteractionHand h) {
|
||||
events.add("item"); player.using = beginUsing; return InteractionResult.SUCCESS_SERVER;
|
||||
}
|
||||
@Override public void handlePickItemFromBlock(BlockPos pos, boolean data) { events.add("pick"); }
|
||||
@Override public void handlePickItemFromEntity(Entity entity, boolean data) { events.add("pick"); }
|
||||
}
|
||||
static boolean flag(JsonObject row, String name) { return row.get(name).getAsBoolean(); }
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var u = Class.forName("sun.misc.Unsafe"); unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
var handle = Minecraft.class.getDeclaredMethod("handleKeybinds"); handle.setAccessible(true);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
int i = 0;
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
var mc = make(MC.class); var options = make(Options.class);
|
||||
for (var f : Options.class.getDeclaredFields()) {
|
||||
if (Modifier.isStatic(f.getModifiers())) continue;
|
||||
f.setAccessible(true);
|
||||
if (f.getType() == KeyMapping.class) f.set(options, make(KeyMapping.class));
|
||||
if (f.getType() == KeyMapping[].class) {
|
||||
var keys = new KeyMapping[9];
|
||||
for (int n = 0; n < keys.length; n++) keys[n] = make(KeyMapping.class);
|
||||
f.set(options, keys);
|
||||
}
|
||||
}
|
||||
var player = make(Human.class); player.using = flag(row, "using");
|
||||
boolean passing = row.has("passing") && flag(row, "passing");
|
||||
player.held = passing ? new ItemStack(Blocks.STONE.asItem()) : ItemStack.EMPTY;
|
||||
var level = make(Level.class);
|
||||
field(ClientLevel.class, "worldBorder").set(level, new WorldBorder());
|
||||
field(Player.class, "abilities").set(player, new Abilities());
|
||||
field(LocalPlayer.class, "connection").set(player, make(Connection.class));
|
||||
var mode = make(Mode.class); mode.player = player;
|
||||
mode.destroying = flag(row, "destroying"); mode.digOnAttack = flag(row, "dig_on_attack");
|
||||
mode.beginUsing = flag(row, "begin_using");
|
||||
mode.passing = passing;
|
||||
field(Minecraft.class, "options").set(mc, options);
|
||||
field(Minecraft.class, "gui").set(mc, make(UI.class));
|
||||
field(Minecraft.class, "mouseHandler").set(mc, make(Mouse.class));
|
||||
field(Minecraft.class, "player").set(mc, player);
|
||||
field(Minecraft.class, "level").set(mc, level);
|
||||
field(Minecraft.class, "gameMode").set(mc, mode);
|
||||
var entity = make(net.minecraft.world.entity.item.ItemEntity.class);
|
||||
field(Entity.class, "blockPosition").set(entity, BlockPos.ZERO);
|
||||
field(Minecraft.class, "hitResult").set(mc, flag(row, "entity")
|
||||
? new EntityHitResult(entity, Vec3.ZERO)
|
||||
: new BlockHitResult(Vec3.ZERO, Direction.UP, BlockPos.ZERO, false));
|
||||
String[] names = {"keyAttack", "keyUse", "keyPickItem"};
|
||||
for (var click : row.getAsJsonArray("clicks")) {
|
||||
var key = (KeyMapping)field(Options.class, names[click.getAsInt()]).get(options);
|
||||
var count = field(KeyMapping.class, "clickCount");
|
||||
count.setInt(key, count.getInt(key) + 1);
|
||||
}
|
||||
field(KeyMapping.class, "isDown").setBoolean(options.keyAttack, flag(row, "attack_down"));
|
||||
field(KeyMapping.class, "isDown").setBoolean(options.keyUse, flag(row, "use_down"));
|
||||
field(Minecraft.class, "rightClickDelay").setInt(mc, row.get("delay").getAsInt());
|
||||
events.clear(); handle.invoke(mc);
|
||||
out.println("== " + i++);
|
||||
for (String event : events) out.println(event);
|
||||
out.println("state " + player.using + " " + mode.destroying + " " + field(Minecraft.class, "rightClickDelay").getInt(mc));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.HexFormat;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/** Runs shipped methods; only the world lifecycle and packet sink are fixtures. */
|
||||
public final class VanillaPlayerSyncOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
static PrintWriter out;
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name); f.setAccessible(true); return f;
|
||||
}
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
return type.cast(allocate.invoke(unsafe, type));
|
||||
}
|
||||
public static final class Player extends LocalPlayer {
|
||||
boolean ground;
|
||||
public Player() { super(null, null, null, null, null, null, false, null, null); }
|
||||
@Override protected boolean isControlledCamera() { return true; }
|
||||
@Override public boolean isSprinting() { return false; }
|
||||
@Override public boolean onGround() { return ground; }
|
||||
}
|
||||
public static final class Sink extends ClientPacketListener {
|
||||
boolean sent;
|
||||
public Sink() { super(null, null, null); }
|
||||
@Override public void send(Packet<?> packet) {
|
||||
sent = true;
|
||||
var buf = new FriendlyByteBuf(Unpooled.buffer());
|
||||
String name;
|
||||
try {
|
||||
if (packet instanceof ServerboundMovePlayerPacket.PosRot p) {
|
||||
name = "posrot"; ServerboundMovePlayerPacket.PosRot.STREAM_CODEC.encode(buf, p);
|
||||
} else if (packet instanceof ServerboundMovePlayerPacket.Pos p) {
|
||||
name = "pos"; ServerboundMovePlayerPacket.Pos.STREAM_CODEC.encode(buf, p);
|
||||
} else if (packet instanceof ServerboundMovePlayerPacket.Rot p) {
|
||||
name = "rot"; ServerboundMovePlayerPacket.Rot.STREAM_CODEC.encode(buf, p);
|
||||
} else if (packet instanceof ServerboundMovePlayerPacket.StatusOnly p) {
|
||||
name = "status"; ServerboundMovePlayerPacket.StatusOnly.STREAM_CODEC.encode(buf, p);
|
||||
} else { throw new AssertionError(packet); }
|
||||
byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes);
|
||||
out.println(name + " " + HexFormat.of().formatHex(bytes));
|
||||
} finally { buf.release(); }
|
||||
}
|
||||
}
|
||||
static double number(JsonElement value) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(value.getAsString(), 16));
|
||||
}
|
||||
static Vec3 vector(JsonObject row, String key) {
|
||||
var a = row.getAsJsonArray(key);
|
||||
return new Vec3(number(a.get(0)), number(a.get(1)), number(a.get(2)));
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
var sendPosition = LocalPlayer.class.getDeclaredMethod("sendPosition");
|
||||
sendPosition.setAccessible(true);
|
||||
var minecraft = make(Minecraft.class);
|
||||
var options = make(Options.class);
|
||||
field(Options.class, "autoJump").set(options, OptionInstance.createBoolean("test", false));
|
||||
field(Minecraft.class, "options").set(minecraft, options);
|
||||
try (var output = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
out = output;
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
if (row.get("kind").getAsString().equals("movement")) {
|
||||
var p = make(Player.class);
|
||||
var sink = make(Sink.class);
|
||||
field(LocalPlayer.class, "connection").set(p, sink);
|
||||
field(LocalPlayer.class, "minecraft").set(p, minecraft);
|
||||
for (var value : row.getAsJsonArray("ops")) {
|
||||
var op = value.getAsJsonArray();
|
||||
field(Entity.class, "position").set(p, new Vec3(number(op.get(0)), number(op.get(1)), number(op.get(2))));
|
||||
field(Entity.class, "yRot").setFloat(p, (float)number(op.get(3)));
|
||||
field(Entity.class, "xRot").setFloat(p, (float)number(op.get(4)));
|
||||
p.ground = op.get(5).getAsBoolean();
|
||||
p.horizontalCollision = op.get(6).getAsBoolean();
|
||||
sink.sent = false;
|
||||
sendPosition.invoke(p);
|
||||
if (!sink.sent) out.println("-");
|
||||
}
|
||||
} else {
|
||||
var old = row.getAsJsonArray("old");
|
||||
var next = row.getAsJsonArray("new");
|
||||
var base = new PositionMoveRotation(Vec3.ZERO, vector(row, "velocity"), (float)number(old.get(0)), (float)number(old.get(1)));
|
||||
var change = new PositionMoveRotation(Vec3.ZERO, vector(row, "delta"), (float)number(next.get(0)), (float)number(next.get(1)));
|
||||
var v = PositionMoveRotation.calculateAbsolute(base, change, Relative.unpack(row.get("flags").getAsInt())).deltaMovement();
|
||||
out.printf("%016x %016x %016x%n", Double.doubleToRawLongBits(v.x), Double.doubleToRawLongBits(v.y), Double.doubleToRawLongBits(v.z));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare queued interaction ordering with the real Minecraft.handleKeybinds."""
|
||||
import itertools
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def corpus():
|
||||
rng = random.Random(0x434C49434B)
|
||||
for using, destroying, attack_down, use_down, entity in itertools.product([False, True], repeat=5):
|
||||
for clicks in [[], [1], [0, 1], [1, 0], [2, 1, 0], [0, 0, 1, 1, 2]]:
|
||||
for delay in [0, 3]:
|
||||
yield dict(using=using, destroying=destroying, attack_down=attack_down,
|
||||
use_down=use_down, entity=entity, clicks=clicks, delay=delay,
|
||||
dig_on_attack=rng.choice([False, True]),
|
||||
begin_using=rng.choice([False, True]))
|
||||
# A player interaction returning PASS must go directly to the held item.
|
||||
# The level still reports a solid block underneath the entity hit.
|
||||
for entity in [False, True]:
|
||||
for clicks in [[1], [1, 1], [0, 1], [1, 2]]:
|
||||
yield dict(using=False, destroying=False, attack_down=False, use_down=False,
|
||||
entity=entity, clicks=clicks, delay=0, dig_on_attack=False,
|
||||
begin_using=False, passing=True)
|
||||
|
||||
|
||||
def main():
|
||||
def inputs(build):
|
||||
rows = list(corpus())
|
||||
path = build / "inputs.jsonl"
|
||||
path.write_text("".join(json.dumps(row) + "\n" for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
harness.differential(
|
||||
"interaction-input-parity", "VanillaInteractionInputOracle", "interaction_input_fixture", inputs,
|
||||
"Invokes Minecraft.handleKeybinds itself with real KeyMapping click counters. "
|
||||
"Compares attack/use/pick ordering, release gating, drained clicks during use, "
|
||||
"held-button repetition and use cooldowns for block/entity targets. "
|
||||
"Includes passing entity interactions over solid blocks: only the held "
|
||||
"item may be tried afterward. "
|
||||
"Game-mode side effects and world simulation are controlled fixtures.",
|
||||
sources=[lab.ROOT / "crates/horizon-client/src/interaction_input.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/game/remote.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/game/hand.rs",
|
||||
lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare movement packet selection and teleport velocity with the pinned client."""
|
||||
import json
|
||||
import random
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def corpus():
|
||||
# Stationary heartbeats, rotation-only updates, status changes and corrected
|
||||
# positions followed by unchanged looks must retain vanilla's packet types.
|
||||
yield dict(kind="movement", ops=[[0, 0, 0, 0, 0, False, False]] * 61)
|
||||
yield dict(kind="movement", ops=[
|
||||
[0, 64, 0, 90, 0, True, False],
|
||||
[0, 64, 0, 90, 0, True, False],
|
||||
[0, 64, 0, 91, 0, True, False],
|
||||
[100, 80, -20, 180, 20, False, False],
|
||||
[100, 80, -20, 180, 20, True, False],
|
||||
[100, 80, -20, 180, 20, True, True],
|
||||
])
|
||||
rng = random.Random(0x53594E43)
|
||||
for _ in range(300):
|
||||
state = [0, 0, 0, 0, 0, False, False]
|
||||
ops = []
|
||||
for _ in range(80):
|
||||
if rng.random() < 0.5:
|
||||
axis = rng.randrange(3)
|
||||
state[axis] += rng.choice([0, 0.0001, 0.0002, 0.0002000001, 0.1, 10])
|
||||
if rng.random() < 0.3:
|
||||
state[3] += rng.choice([-360, -1, 0, 0.001, 1, 360])
|
||||
state[4] = rng.choice([-90, 0, 30, 90])
|
||||
if rng.random() < 0.2:
|
||||
state[rng.randrange(5, 7)] = rng.choice([False, True])
|
||||
ops.append(state.copy())
|
||||
yield dict(kind="movement", ops=ops)
|
||||
for flags in range(16):
|
||||
for _ in range(40):
|
||||
yield dict(kind="velocity", flags=flags << 5,
|
||||
velocity=[rng.uniform(-4, 4) for _ in range(3)],
|
||||
delta=[rng.uniform(-4, 4) for _ in range(3)],
|
||||
old=[rng.uniform(-720, 720), rng.uniform(-90, 90)],
|
||||
new=[rng.uniform(-720, 720), rng.uniform(-90, 90)])
|
||||
|
||||
|
||||
def main():
|
||||
def inputs(build):
|
||||
rows = list(corpus())
|
||||
def bits(v):
|
||||
return struct.pack(">d", v).hex()
|
||||
for row in rows:
|
||||
if row["kind"] == "movement":
|
||||
row["ops"] = [[*map(bits, op[:5]), *op[5:]] for op in row["ops"]]
|
||||
else:
|
||||
for key in ["velocity", "delta", "old", "new"]:
|
||||
row[key] = list(map(bits, row[key]))
|
||||
path = build / "inputs.jsonl"
|
||||
path.write_text("".join(json.dumps(row) + "\n" for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
harness.differential(
|
||||
"player-sync-parity", "VanillaPlayerSyncOracle", "player_sync_fixture", inputs,
|
||||
"Actual LocalPlayer.sendPosition packet payloads over persistent movement "
|
||||
"sequences; PositionMoveRotation.calculateAbsolute velocity with every "
|
||||
"relative-delta/rotate-delta combination. World simulation, connection "
|
||||
"scheduling and live anticheat behaviour are outside this harness.",
|
||||
sources=[lab.ROOT / "crates/horizon-client/src/player_sync.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/game/remote.rs",
|
||||
lab.ROOT / "crates/horizon-client/src/net.rs"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user