LAN: players see each other use items (eating, bows, shields)

Neither side sent LivingEntity.DATA_LIVING_ENTITY_FLAGS for players, so
no one saw another player eat, draw a bow or raise a shield. The host now
sends the item in use and its hand for itself and every guest (always:
the trackers send only the entries that changed, and stopping is a change
back to 0), and draws its guests' bodies using their items. A guest's
client starts and stops the other players' item use from the flags and
drops their eating crumbs at their mouth (Consumable.onConsumeTick); the
eating sounds already come from the server.

lan_e2e.py eating: the host and the guest each see the other eat bread,
and stop.

Part of #803

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-18 14:19:40 +02:00
parent 2b6ae71fb7
commit 76e659c74b
8 changed files with 170 additions and 3 deletions
@@ -101,6 +101,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
sprinting: false,
equipment: Default::default(),
health: 20.0,
living_flags: 0,
};
loop {
world.game_time += 1;
+16 -1
View File
@@ -2,7 +2,7 @@
//! server threads and the play-state hub, feeds it the world's entities each
//! tick and turns what the guests do into gameplay. A world that is not open
//! costs one `Option` check per tick.
use super::Game;
use super::{Game, shield::OFFHAND_SLOT};
use horizon_client::{
Result,
items::ItemStack,
@@ -395,6 +395,8 @@ impl Game<'_> {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
// For how many ticks the host draws this guest using an item.
"model_using": h.models.get(&g.conn).map(|m| m.extra.using_item),
})).collect::<Vec<_>>(),
}),
_ => json!({ "open": false }),
@@ -722,6 +724,7 @@ impl Game<'_> {
sprinting: p.sprinting,
equipment,
health: p.health.health(),
living_flags: living_flags(self.using),
})
}
@@ -924,6 +927,7 @@ impl Game<'_> {
}
self.lan_flush_effects(&mut host);
self.tick_guests(&mut host);
self.lan_living_flags(&mut host);
self.tick_server_travel(&mut host);
self.lan_swings(&mut host);
self.lan_update_streaming(&host);
@@ -1158,6 +1162,11 @@ impl Game<'_> {
.each_ref()
.map(|s| s.as_ref().map(|s| s.item.clone()));
m.extra.crouching = g.sneaking;
// LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS): the
// item in use and its hand (the arm poses of a bow, a shield...).
let using = host.play.get(&g.conn).and_then(|p| p.using());
m.extra.using_item = using.map_or(0, |(_, ticks)| ticks as i32 + 1);
m.extra.using_off_hand = using.is_some_and(|(slot, _)| slot == OFFHAND_SLOT);
}
}
@@ -1226,3 +1235,9 @@ impl Game<'_> {
}
}
}
/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` for an item in use: 1, and 2 when
/// it is the off hand's.
pub(super) fn living_flags(using: Option<(usize, u32)>) -> i8 {
using.map_or(0, |(slot, _)| if slot == OFFHAND_SLOT { 3 } else { 1 })
}
@@ -60,6 +60,13 @@ pub(super) struct GuestPlay {
xp_delay: u32,
}
impl GuestPlay {
/// The item in use: its slot and for how many ticks.
pub(super) fn using(&self) -> Option<(usize, u32)> {
self.using
}
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
impl Rules for ItemRules<'_> {
fn max_stack(&self, item: &str) -> u32 {
@@ -1619,6 +1626,15 @@ impl Game<'_> {
}
}
/// The guests' items in use, for the players around (`LivingEntity.startUsingItem`
/// and `stopUsingItem` set DATA_LIVING_ENTITY_FLAGS).
pub(super) fn lan_living_flags(&mut self, host: &mut LanHost) {
for g in &mut host.hub.guests {
let using = host.play.get(&g.conn).and_then(GuestPlay::using);
g.living_flags = super::lan::living_flags(using);
}
}
/// Guests' arm swings for everyone else.
pub(super) fn lan_swings(&mut self, host: &mut LanHost) {
let conns: Vec<u32> = host.play.keys().copied().collect();
+84
View File
@@ -1478,6 +1478,25 @@ impl Game<'_> {
}
}
}
// LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS):
// another player starts using the item in a hand (eating, a
// bow drawn, a shield up), or stops.
let other = self
.remote
.as_ref()
.is_some_and(|r| r.level_players.contains_key(&p.id) && r.entity_id != p.id);
if other && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
for (index, _, value) in &p.values {
if let (8, Value::Byte(flags)) = (index, value) {
m.extra.using_off_hand = flags & 2 != 0;
if flags & 1 == 0 {
m.extra.using_item = 0;
} else if m.extra.using_item == 0 {
m.extra.using_item = 1;
}
}
}
}
// LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this
// player lies down in the bed, or gets up.
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
@@ -2597,6 +2616,7 @@ impl Game<'_> {
let mut lerps = std::mem::take(&mut r.lerps);
let head_lerps = &mut r.head_lerps;
let players = &r.level_players;
let mut using = Vec::new();
for m in &mut self.mobs {
let player = players.contains_key(&(m.id as i32));
if !running && !player {
@@ -2645,6 +2665,28 @@ impl Game<'_> {
m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32;
*steps -= 1;
}
// LivingEntity.updatingUsingItem for another player: the ticks the
// item has been used before this one.
if player && m.extra.using_item > 0 {
let item = if m.extra.using_off_hand {
m.extra.off_hand.clone()
} else {
m.extra.main_hand.clone()
};
if let Some(item) = item {
let eye = if m.extra.crouching { 1.27 } else { 1.62 };
let at = [m.position.x, m.position.y, m.position.z];
using.push((
item,
m.extra.using_item as u32 - 1,
at,
eye,
m.head_pitch,
m.yaw,
));
}
m.extra.using_item += 1;
}
// LivingEntity.tick's tickHeadTurn: a mob's BodyRotationControl,
// a player's body following its walk and look.
if player {
@@ -2692,6 +2734,9 @@ impl Game<'_> {
}
}
head_lerps.retain(|_, (_, steps)| *steps > 0);
for (item, ticks, at, eye, pitch, yaw) in using {
self.remote_player_eating(&item, ticks, at, eye, pitch, yaw);
}
if running {
// Boats, minecarts, armor stands, projectiles and the rest
// interpolate like mobs.
@@ -2717,6 +2762,44 @@ impl Game<'_> {
}
}
}
/// `Consumable.onConsumeTick` for another player eating: the crumbs at
/// their mouth every 4 ticks once 21.875% of the 32 ticks have passed
/// (`shouldEmitParticlesAndSounds`; the sounds come from the server).
fn remote_player_eating(
&mut self,
item: &str,
ticks: u32,
at: [f64; 3],
eye: f64,
pitch: f32,
yaw: f32,
) {
let food = self
.res
.items
.get(item)
.is_some_and(|i| i.consumable && i.food.is_some());
let duration = 32;
let remaining = duration - ticks.min(duration);
if !food || duration - remaining <= (duration as f32 * 0.21875) as u32 || remaining % 4 != 0
{
return;
}
let options = self.item_particle(&ItemStack::new(item, 1));
let mut spawned = Vec::new();
horizon_client::particles::item_use_particles(
&mut self.world.random,
pitch,
yaw,
at,
at[1] + eye,
5,
|p, v| spawned.push((p, v)),
);
for (p, v) in spawned {
self.particles.add(&options, p, v);
}
}
/// LocalPlayer.sendPosition plus input, sprint and held-slot updates.
fn remote_send_state(&mut self, input: u8) {
let Some(p) = self.player.as_ref() else {
@@ -3728,6 +3811,7 @@ impl Game<'_> {
let armor = [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref());
serde_json::json!({
"id": m.id,
"using": m.extra.using_item,
"armor": armor,
"main_hand": e.main_hand.as_deref(),
"off_hand": e.off_hand.as_deref(),
+4
View File
@@ -75,6 +75,9 @@ pub struct Guest {
pub fall_flying: bool,
pub flying: bool,
pub sleeping: bool,
/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS`: 1 while using an item, 2 if
/// it is in the off hand.
pub living_flags: i8,
/// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`),
/// `Player.sleepCounter`, and the bed last told to the player itself.
pub bed: Option<[i32; 3]>,
@@ -222,6 +225,7 @@ impl Guest {
fall_flying: false,
flying: false,
sleeping: false,
living_flags: 0,
bed: None,
sleep_timer: 0,
sent_bed: None,
+8
View File
@@ -80,6 +80,8 @@ pub struct HostState {
pub sprinting: bool,
pub equipment: [Option<ItemStack>; 6],
pub health: f32,
/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` (the item in use).
pub living_flags: i8,
}
/// Everything the hub needs from the game for one tick.
@@ -1375,6 +1377,7 @@ impl Hub {
rot: (f32, f32, f32),
on_ground: bool,
flags: (bool, bool, bool, bool),
living_flags: i8,
skin: u8,
health: f32,
equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>,
@@ -1406,6 +1409,9 @@ impl Hub {
if pose != 0 {
meta.push((6, serializer::POSE, Value::Id(pose)));
}
// Always there: the trackers send the entries that changed, and an
// item no longer in use is a change back to 0.
meta.push((8, serializer::BYTE, Value::Byte(living_flags)));
if (health - 1.0).abs() > f32::EPSILON && health != 20.0 {
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
@@ -1469,6 +1475,7 @@ impl Hub {
(h.yaw, h.pitch, h.head_yaw),
h.on_ground,
(h.sneaking, h.sprinting, false, false),
h.living_flags,
0x7F,
h.health,
equipment,
@@ -1498,6 +1505,7 @@ impl Hub {
(g.yaw, g.pitch, g.head_yaw),
g.on_ground,
(g.sneaking, g.sprinting, g.fall_flying, g.sleeping),
g.living_flags,
g.info.model_customisation,
g.health,
equipment,
+1
View File
@@ -181,6 +181,7 @@ impl Server {
sprinting: false,
equipment: Default::default(),
health: 20.0,
living_flags: 0,
};
let mut ctx = TickCtx {
world: &mut self.world,
+40 -2
View File
@@ -43,6 +43,8 @@ address. The script then checks, from both sides, what a guest's game used to ge
pushes it, as in vanilla), not ever faster across the ground.
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
counts up) and the server eats one loaf and feeds the guest.
- eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the
player it draws, and no longer once the bread is eaten (#803);
- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the
guest their points (not the host).
- objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the
@@ -84,7 +86,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', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance']
class Game:
@@ -1095,6 +1097,42 @@ def check_eat(host, guest, out):
return detail
def check_eating(host, guest, out):
for g in (host, guest):
g('command', command='gamemode survival')
g('command', command='clear @s')
# Hungry: Player.canEat.
g('command', command='effect give @s minecraft:hunger 3 255')
host.wait(70)
for g in (host, guest):
g('command', command='effect clear @s')
g('command', command='give @s minecraft:bread 2')
host.wait(5)
face_each_other(host, guest)
def using(game):
# On its server thread the host's window is a client of its server too.
if game is host and not SERVER_THREAD:
return lan_guest(host).get('model_using') or 0
return max((e.get('using') or 0 for e in remote(game).get('player_equipment', [])), default=0)
seen = {}
for name, eater, watcher in (('host eats', host, guest), ('guest eats', guest, host)):
eater.raw('select', 'minecraft:bread')
hold = threading.Thread(target=eater.raw, args=('use-item', '--hold', 2.2))
hold.start()
samples = []
for _ in range(4):
time.sleep(0.3)
samples.append(using(watcher))
watcher.shot(out, 'eating-' + name.replace(' ', '-'))
hold.join()
eater.wait(10)
seen[name] = {'during': samples, 'after': using(watcher)}
for name, s in seen.items():
assert sum(1 for u in s['during'] if u > 0) >= 3 and s['after'] == 0, f'{name}: {seen}'
return seen
def check_xp(host, guest, out):
for g in (host, guest):
g('command', command='gamemode survival')
@@ -1276,7 +1314,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'commands': check_commands,
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks,
'sleep': check_sleep, 'push': check_push, 'eat': check_eat,
'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating,
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles,
'light': check_light}