Merge pull request #2564 from Louistuis/fix/eat-held-after-full
🤖 Agent: verified by Ludovic's AI agent (contrib gate 20): USE_ITEM_COMPLETE finishes the use; eating on the client (lan_e2e eat_full, eating, helduse, consume-release pass). It passed in this wave's union with main on the Mac mini: the selected parity harnesses (332/332, then 122/122 on the final union), clippy -D warnings and the tests, and lan_e2e with the host on its server thread and in-frame (18/18 each). Thanks @Louistuis!
This commit is contained in:
@@ -1706,6 +1706,9 @@ struct Game<'a> {
|
||||
/// The acting guest's cooldowns, as (item, ticks): their packet needs the
|
||||
/// hub's item registry, which the guest's turn does not hold.
|
||||
guest_cooldowns: Vec<(Arc<str>, i32)>,
|
||||
/// The acting guest's own entity events (`ServerPlayer.connection.send`),
|
||||
/// sent with their entity id, which the guest's turn does not hold.
|
||||
guest_entity_events: Vec<i8>,
|
||||
/// `broadcastToAdmins` lines a guest's command queued, sent once it
|
||||
/// returns: the line, whether operators get it and whether the console
|
||||
/// logs it.
|
||||
@@ -4222,6 +4225,7 @@ impl Game<'_> {
|
||||
if &*stack.item == "minecraft:spyglass" {
|
||||
// SpyglassItem.USE_DURATION, then finishUsingItem.
|
||||
if ticks + 1 >= 1200 {
|
||||
self.send_use_item_complete();
|
||||
self.stop_spyglass();
|
||||
self.using = None;
|
||||
} else {
|
||||
@@ -4243,6 +4247,7 @@ impl Game<'_> {
|
||||
}
|
||||
if ticks >= duration {
|
||||
self.using = None;
|
||||
self.send_use_item_complete();
|
||||
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
|
||||
self.apply_use_cooldown(&stack);
|
||||
self.finish_consuming(&info, consumable, &stack);
|
||||
@@ -13149,6 +13154,7 @@ impl<'a> Game<'a> {
|
||||
lan_acting: None,
|
||||
guest_packets: Vec::new(),
|
||||
guest_cooldowns: Vec::new(),
|
||||
guest_entity_events: Vec::new(),
|
||||
lan_acting_name: None,
|
||||
lan_acting_uuid: None,
|
||||
chat_capture: None,
|
||||
|
||||
@@ -19,7 +19,17 @@ use std::convert::Infallible;
|
||||
|
||||
type ItemConsumable = Consumable<String, ConsumeEffect>;
|
||||
|
||||
/// `EntityEvent.USE_ITEM_COMPLETE`: the server finished the player's use.
|
||||
pub(super) const USE_ITEM_COMPLETE_EVENT: i8 = 9;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `ServerPlayer.completeUsingItem`: the player's own client is told
|
||||
/// first, and completes the use itself (eating the food there too).
|
||||
pub(super) fn send_use_item_complete(&mut self) {
|
||||
if self.lan_acting.is_some() {
|
||||
self.guest_entity_events.push(USE_ITEM_COMPLETE_EVENT);
|
||||
}
|
||||
}
|
||||
/// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`.
|
||||
pub(super) fn emit_consume(
|
||||
&mut self,
|
||||
|
||||
@@ -165,6 +165,8 @@ pub(super) struct GuestSwap {
|
||||
acting: (Option<u32>, Option<String>, Option<u128>),
|
||||
/// The packets queued for that guest.
|
||||
packets: Vec<play::Clientbound>,
|
||||
/// The entity events queued for that guest.
|
||||
entity_events: Vec<i8>,
|
||||
/// The host's count of swings started, kept while the guest acts.
|
||||
swings: u32,
|
||||
/// How many projectiles there were: those added since are the guest's.
|
||||
@@ -389,6 +391,7 @@ impl Game<'_> {
|
||||
self.lan_acting_uuid.replace(g.uuid),
|
||||
);
|
||||
let packets = std::mem::take(&mut self.guest_packets);
|
||||
let entity_events = std::mem::take(&mut self.guest_entity_events);
|
||||
let swings = self.swings_started;
|
||||
let projectiles = self.creatures.projectiles.len();
|
||||
let modifiers = std::mem::replace(
|
||||
@@ -449,6 +452,7 @@ impl Game<'_> {
|
||||
death_cause,
|
||||
acting,
|
||||
packets,
|
||||
entity_events,
|
||||
swings,
|
||||
projectiles,
|
||||
modifiers,
|
||||
@@ -508,6 +512,7 @@ impl Game<'_> {
|
||||
combat,
|
||||
acting,
|
||||
packets,
|
||||
entity_events,
|
||||
swings,
|
||||
projectiles,
|
||||
modifiers,
|
||||
@@ -529,6 +534,17 @@ impl Game<'_> {
|
||||
for packet in std::mem::replace(&mut self.guest_packets, packets) {
|
||||
host.hub.send_to(conn, &packet);
|
||||
}
|
||||
// ServerPlayer.connection.send: the guest's own entity events.
|
||||
let entity_id = host.hub.guests[i].entity_id;
|
||||
for event in std::mem::replace(&mut self.guest_entity_events, entity_events) {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::EntityEvent(play::EntityEvent {
|
||||
id: entity_id,
|
||||
event,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// ServerItemCooldowns.onCooldownStarted: the guest's own cooldown.
|
||||
for (group, duration) in std::mem::take(&mut self.guest_cooldowns) {
|
||||
host.hub.send_to(
|
||||
@@ -1916,21 +1932,8 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
let play = host.play.entry(conn).or_default();
|
||||
// Player.tick's ItemCooldowns.tick, once a tick for each player
|
||||
// (the shield an axe disabled, a thrown pearl).
|
||||
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
|
||||
// ServerGamePacketListenerImpl.tick's dropSpamThrottler.
|
||||
play.creative_drops = play.creative_drops.saturating_sub(1);
|
||||
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
|
||||
// the guest (a duration of 0 removes it).
|
||||
for group in play.cooldowns.tick() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::Cooldown(play::Cooldown {
|
||||
group: group.to_string(),
|
||||
duration: 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
let digging = play.digging;
|
||||
let using = play.using.is_some();
|
||||
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
||||
@@ -1967,6 +1970,24 @@ impl Game<'_> {
|
||||
play.digging = None;
|
||||
}
|
||||
}
|
||||
// Player.tick's ItemCooldowns.tick, once a tick for each player
|
||||
// (the shield an axe disabled, a thrown pearl), after
|
||||
// LivingEntity.tick's use: an entry a finished use starts has 20
|
||||
// ticks left when the next tick's packets are handled, as the
|
||||
// guest's own client counts.
|
||||
let play = host.play.entry(conn).or_default();
|
||||
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
|
||||
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
|
||||
// the guest (a duration of 0 removes it).
|
||||
for group in play.cooldowns.tick() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::Cooldown(play::Cooldown {
|
||||
group: group.to_string(),
|
||||
duration: 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Player.tick: a different main-hand item resets the attack
|
||||
// strength, and detectEquipmentUpdates gives the guest its modifiers.
|
||||
let g = &host.hub.guests[gi];
|
||||
|
||||
@@ -313,6 +313,7 @@ impl Game<'_> {
|
||||
return true;
|
||||
}
|
||||
self.using = None;
|
||||
self.send_use_item_complete();
|
||||
self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player);
|
||||
if ominous {
|
||||
self.drink_ominous_bottle(slot, stack);
|
||||
|
||||
@@ -117,6 +117,8 @@ pub(super) struct Remote {
|
||||
joined: bool,
|
||||
status: String,
|
||||
pub(super) entity_id: i32,
|
||||
/// The item the player's use began with (`LivingEntity.useItem`).
|
||||
pub(super) use_item: Option<Arc<str>>,
|
||||
dimension: DimensionType,
|
||||
/// What chunk packets decode with (the dimension's height and sky, the
|
||||
/// biome registry); replaced whenever one of them changes.
|
||||
@@ -433,6 +435,7 @@ impl Game<'_> {
|
||||
joined: false,
|
||||
status: "Connecting to the server...".into(),
|
||||
entity_id: 0,
|
||||
use_item: None,
|
||||
dimension: DimensionType::vanilla("minecraft:overworld"),
|
||||
chunk_format: Arc::new(ChunkFormat::new(
|
||||
&DimensionType::vanilla("minecraft:overworld"),
|
||||
@@ -1650,8 +1653,10 @@ impl Game<'_> {
|
||||
self.send(S::ClientInformation(info));
|
||||
}
|
||||
C::Respawn(p) => {
|
||||
// A new player, without effects: the server sends them again.
|
||||
// A new player, without effects (the server sends them
|
||||
// again) and with no item in use.
|
||||
self.potions.effects.clear();
|
||||
self.using = None;
|
||||
self.enter_remote_dimension(&p.spawn, true);
|
||||
self.screen = Screen::Playing;
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
@@ -2185,6 +2190,11 @@ impl Game<'_> {
|
||||
self.honey_slide_particles(at);
|
||||
}
|
||||
}
|
||||
if p.event == super::consume::USE_ITEM_COMPLETE_EVENT
|
||||
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
|
||||
{
|
||||
self.remote_complete_using();
|
||||
}
|
||||
}
|
||||
C::Animate(p) => self.remote_animate(p.id, p.action),
|
||||
// ClientPacketListener.handleSwingAnimation: the entity swings
|
||||
@@ -3182,12 +3192,6 @@ impl Game<'_> {
|
||||
fn tick_remote_level(&mut self) -> Result<()> {
|
||||
self.ticks += 1;
|
||||
self.track_experience_display();
|
||||
// Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s
|
||||
// for a server's client (multiplayer and the default single player),
|
||||
// so the entries advance here or the slot stays shaded until the
|
||||
// server says the entry ended. `onCooldownEnded` is the plain
|
||||
// ItemCooldowns' no-op on a client.
|
||||
self.cooldowns.tick();
|
||||
// Leaving a slot clears its bundle's selection here and on the server.
|
||||
self.tick_bundle_hover();
|
||||
// Options.broadcastOptions: a changed render distance or Chat option
|
||||
@@ -3223,6 +3227,14 @@ impl Game<'_> {
|
||||
// Window callbacks only queue clicks, so an interaction cannot leak
|
||||
// between CLIENT_TICK_END and a later pong.
|
||||
self.remote_handle_input();
|
||||
// Player.tick's ItemCooldowns.tick, in ClientLevel.tickEntities after
|
||||
// handleKeybinds: this path replaces `tick_world`'s for a server's
|
||||
// client (multiplayer and the default single player), so the entries
|
||||
// advance here or the slot stays shaded until the server says the
|
||||
// entry ended. `onCooldownEnded` is the plain ItemCooldowns' no-op on
|
||||
// a client. Ticking it after the keybinds keeps a held use from
|
||||
// trying again a tick before the server's entry ends.
|
||||
self.cooldowns.tick();
|
||||
// ClientLevel.tick: the border's size change.
|
||||
self.border.tick();
|
||||
self.player_border();
|
||||
@@ -4359,10 +4371,19 @@ impl Game<'_> {
|
||||
let Some(info) = self.res.items().get(&held.item).cloned() else {
|
||||
return false;
|
||||
};
|
||||
// MultiPlayerGameMode.useItem runs the use here too (inside
|
||||
// startPrediction): the `use_cooldown` component starts its entry, and
|
||||
// the server's ClientboundCooldownPacket confirms it.
|
||||
self.apply_use_cooldown(&held);
|
||||
// MultiPlayerGameMode.useItem's prediction: an item cooling down
|
||||
// passes (its packet still goes).
|
||||
let group = horizon_client::cooldowns::group(&held, info.use_cooldown.as_ref());
|
||||
if self.cooldowns.is_on_cooldown(&group) {
|
||||
return false;
|
||||
}
|
||||
// It runs the use here too: ItemStack.use starts the `use_cooldown`
|
||||
// of an item with no use time, and the server's
|
||||
// ClientboundCooldownPacket confirms it; one held in use starts it at
|
||||
// finishUsingItem (remote_complete_using).
|
||||
if !info.consumable.as_ref().is_some_and(|c| c.ticks() > 0) {
|
||||
self.apply_use_cooldown(&held);
|
||||
}
|
||||
// Food starts being eaten (Consumable.startConsuming), a book and
|
||||
// quill opens.
|
||||
self.with_hand(hand, |g| g.start_eating(&info));
|
||||
@@ -4437,14 +4458,25 @@ impl Game<'_> {
|
||||
self.remote_use_item(Hand::Off);
|
||||
}
|
||||
/// `LivingEntity.updatingUsingItem` on a server client: an item held in
|
||||
/// use (`held_until_released`), and a
|
||||
/// consumable's eating animation and its crumbs. The server eats it and
|
||||
/// sends the stack, the hunger and the sounds.
|
||||
/// use (`held_until_released`), and a consumable's eating animation and
|
||||
/// its crumbs until the server's USE_ITEM_COMPLETE. The server sends the
|
||||
/// stack, its hunger and the sounds.
|
||||
fn remote_tick_using(&mut self) {
|
||||
let Some((slot, ticks)) = self.using else {
|
||||
return;
|
||||
};
|
||||
let stack = self.stack_in(slot).cloned();
|
||||
// The use stops when the hand no longer holds the item it began with
|
||||
// (ItemStack.isSameItem).
|
||||
let item = stack.as_ref().map(|s| Arc::clone(&s.item));
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
if ticks == 0 {
|
||||
r.use_item = item;
|
||||
} else if r.use_item != item {
|
||||
self.using = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Another hotbar slot picked: LivingEntity.updatingUsingItem sees a
|
||||
// different stack in the hand. The off hand keeps its item.
|
||||
let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT;
|
||||
@@ -4469,20 +4501,51 @@ impl Game<'_> {
|
||||
self.using = None;
|
||||
return;
|
||||
}
|
||||
// Consumable.shouldEmitParticlesAndSounds, as in tick_used_item.
|
||||
let duration = consumable.ticks().max(0) as u32;
|
||||
let remaining = duration - ticks.min(duration);
|
||||
if consumable.particles && consumable.should_emit(remaining as i32) {
|
||||
// Consumable.startConsuming eats one with no use time at once, without
|
||||
// a use (nor a USE_ITEM_COMPLETE).
|
||||
if consumable.ticks() <= 0 {
|
||||
self.using = None;
|
||||
return;
|
||||
}
|
||||
// Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. The
|
||||
// countdown goes on past zero (LivingEntity.updateUsingItem completes
|
||||
// only on the server) until the server's USE_ITEM_COMPLETE.
|
||||
let remaining = consumable.ticks() - ticks as i32;
|
||||
if consumable.particles && consumable.should_emit(remaining) {
|
||||
self.eat_particles(&stack, 5);
|
||||
}
|
||||
if ticks + 1 >= duration {
|
||||
self.using = None;
|
||||
if consumable.particles {
|
||||
self.eat_particles(&stack, 16);
|
||||
}
|
||||
} else {
|
||||
self.using = Some((slot, ticks + 1));
|
||||
self.using = Some((slot, ticks + 1));
|
||||
}
|
||||
/// `Player.handleEntityEvent(9)`: `completeUsingItem` on the client. A consumable's last crumbs, and FoodProperties.onConsume,
|
||||
/// which runs on the client too (Consumable.onConsume calls its
|
||||
/// ConsumableListeners on both sides): the client's FoodData eats at once,
|
||||
/// so a held right click finds `Player.canEat` false instead of starting
|
||||
/// another bite before the server's ClientboundSetHealth arrives.
|
||||
fn remote_complete_using(&mut self) {
|
||||
let Some((slot, _)) = self.using.take() else {
|
||||
return;
|
||||
};
|
||||
let Some(stack) = self.stack_in(slot).cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(info) = self.res.items().get(&stack.item).cloned() else {
|
||||
return;
|
||||
};
|
||||
if info.consumable.as_ref().is_some_and(|c| c.particles) {
|
||||
self.eat_particles(&stack, 16);
|
||||
}
|
||||
if let Some((nutrition, saturation)) = info.food
|
||||
&& let Some(r) = self.remote.as_mut()
|
||||
{
|
||||
// FoodData.eat(nutrition, saturation), as finish_consuming does;
|
||||
// the next ClientboundSetHealth replaces it.
|
||||
let (_, food, sat) = &mut r.health;
|
||||
*food = (*food + nutrition as i32).clamp(0, 20);
|
||||
*sat = (*sat + saturation).clamp(0.0, *food as f32);
|
||||
self.apply_remote_health();
|
||||
}
|
||||
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
|
||||
self.apply_use_cooldown(&stack);
|
||||
}
|
||||
/// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick.
|
||||
pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
|
||||
|
||||
+65
-1
@@ -114,6 +114,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
use to completion still consumes the item (#1293).
|
||||
- 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);
|
||||
- eat_full: holding right click with melon slices until the food bar is full: the guest's own
|
||||
client eats each slice when the server says it is done (entity event 9,
|
||||
USE_ITEM_COMPLETE), so no other bite starts; held on chorus fruit, both fruits are
|
||||
eaten across its cooldown (#2471).
|
||||
- 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
|
||||
@@ -5218,6 +5222,64 @@ CHECKS += ['helduse']
|
||||
CHECK_FNS.update(helduse=check_held_use)
|
||||
|
||||
|
||||
def check_eat_full(host, guest, out):
|
||||
"""Holding right click past a full food bar starts no other bite; chorus fruit's cooldown
|
||||
doesn't leave the use stuck (#2471)."""
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
# Full health: natural regeneration at 18 food or more would eat into the bar.
|
||||
guest('command', command='effect give @s minecraft:instant_health 1 10')
|
||||
guest('command', command='effect give @s minecraft:hunger 60 127')
|
||||
for _ in range(400):
|
||||
if remote(guest)['food'] <= 17:
|
||||
break
|
||||
guest.wait(1)
|
||||
guest('command', command='effect clear @s')
|
||||
guest('command', command='give @s minecraft:melon_slice 16')
|
||||
guest.wait(5)
|
||||
guest.raw('select', 'minecraft:melon_slice')
|
||||
hungry = remote(guest)['food']
|
||||
# A slice (2 food) takes 32 ticks (1.6 s): the button stays down well past the slices that fill
|
||||
# the bar, with room for a slow server.
|
||||
slices = -(-(20 - hungry) // 2)
|
||||
hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', slices * 4.0 + 6.0))
|
||||
hold.start()
|
||||
deadline = time.monotonic() + slices * 4.0 + 2.0
|
||||
while remote(guest)['food'] < 20 and time.monotonic() < deadline:
|
||||
time.sleep(0.1)
|
||||
# The bar is full and the button is still down: nothing is in use over the next 20 ticks
|
||||
# (sleeps, as `wait` is refused while the held use-item runs).
|
||||
using = []
|
||||
for _ in range(4):
|
||||
time.sleep(0.25)
|
||||
using.append(guest('state').get('using'))
|
||||
guest.shot(out, 'eat-full')
|
||||
hold.join()
|
||||
guest.wait(10)
|
||||
full = {'hungry': hungry, 'fed': remote(guest)['food'], 'using': using,
|
||||
'eaten': 16 - guest('inventory')['counts'].get('minecraft:melon_slice', 0), 'needed': slices}
|
||||
assert hungry < 20, f'the guest is not hungry: {full}'
|
||||
assert full['fed'] == 20 and full['eaten'] == slices, f'the bar did not fill: {full}'
|
||||
assert using == [None] * 4, f'another bite started with a full food bar: {full}'
|
||||
|
||||
# Chorus fruit can always be eaten, then its group cools down for 20 ticks: the client waits
|
||||
# it out (MultiPlayerGameMode.useItem) and eats the second fruit with the button still held.
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:chorus_fruit 2')
|
||||
guest.wait(5)
|
||||
guest.raw('select', 'minecraft:chorus_fruit')
|
||||
guest.raw('use-item', '--hold', 7.0)
|
||||
guest.wait(10)
|
||||
chorus = {'left': guest('inventory')['counts'].get('minecraft:chorus_fruit', 0),
|
||||
'using': guest('state').get('using')}
|
||||
assert chorus == {'left': 0, 'using': None}, f'the held use did not eat both chorus fruits: {chorus}'
|
||||
return {'full': full, 'chorus': chorus}
|
||||
|
||||
|
||||
CHECKS += ['eat_full']
|
||||
CHECK_FNS.update(eat_full=check_eat_full)
|
||||
|
||||
|
||||
def check_consume_release(host, guest, out):
|
||||
"""#1293: releasing a consumable in either hand cancels it on client and server, while
|
||||
holding it to completion applies its effects and remainder (Consumable.onConsume)."""
|
||||
@@ -5262,8 +5324,10 @@ def check_consume_release(host, guest, out):
|
||||
assert effects == before, f'{case} applied consumption effects after release: {cancelled}'
|
||||
game.shot(out, f'consume-release-{hand}-{item}')
|
||||
# A sustained press must still consume normally, including the milk's empty bucket.
|
||||
# The use ends with the server's USE_ITEM_COMPLETE, 32 server ticks after its
|
||||
# UseItem: room for a busy server before letting go.
|
||||
game.raw('mouse', 'right', 'down')
|
||||
game.wait(40)
|
||||
game.wait(50)
|
||||
game.raw('mouse', 'right', 'up')
|
||||
game.wait(10)
|
||||
inventory = game('inventory')
|
||||
|
||||
Reference in New Issue
Block a user