diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9d68cb0c6..2299df12e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -136,6 +136,7 @@ use horizon_client::{ creative::{Creative, Names}, entities::{Experience, ExperienceOrb, ItemEntity}, environment::Environment, + first_person::Hand, gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, hud_layout, hud_overlays, @@ -796,6 +797,9 @@ struct Game<'a> { armor: [Option; 4], /// The off hand (Inventory slot 40, saved as slot 150; menu slot 504 here). offhand: Option, + /// The hand an item use acts with (`InteractionHand`): the off hand only + /// for its turn in `use_item` and while its item is being used. + hand: Hand, /// The shield's item cooldown after an axe disabled it (ticks). shield_cooldown: u32, /// The source of a command run through /execute (the player otherwise). @@ -1194,8 +1198,26 @@ impl Game<'_> { } None } + /// The stack in the hand that acts (`getItemInHand(hand)`). fn held(&self) -> Option<&ItemStack> { - self.inventory[self.selected].as_ref() + self.stack_in(self.held_slot()) + } + fn held_mut(&mut self) -> &mut Option { + self.stack_in_mut(self.held_slot()) + } + /// The slot of the hand that acts: the selected one, or `OFFHAND_SLOT`. + fn held_slot(&self) -> usize { + match self.hand { + Hand::Main => self.selected, + Hand::Off => shield::OFFHAND_SLOT, + } + } + /// Run `f` with `hand` acting (`held`, `consume_held`, `swing_arm`). + fn with_hand(&mut self, hand: Hand, f: impl FnOnce(&mut Self) -> T) -> T { + let prior = std::mem::replace(&mut self.hand, hand); + let out = f(self); + self.hand = prior; + out } /// Inventory.add: returns the stack that did not fit. fn give(&mut self, mut stack: ItemStack) -> Option { @@ -2234,20 +2256,22 @@ impl Game<'_> { self.process_level_events()?; Ok(()) } - fn use_item(&mut self) -> Result<()> { + /// The hand whose use ended the click, if any. + fn use_item(&mut self) -> Result> { self.with_player_actor(|game| game.use_item_as_player()) } - fn use_item_as_player(&mut self) -> Result<()> { + /// `Minecraft.startUseItem`: the main hand, then the off hand. + fn use_item_as_player(&mut self) -> Result> { // Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass). if self.spectator() { - return Ok(()); + return Ok(None); } // A carrot or warped fungus on a stick boosts the ridden pig or strider. if self.riding.is_some() && let Some(item) = self.held().map(|s| s.item.clone()) && self.use_steering_stick(&item) { - return Ok(()); + return Ok(Some(Hand::Main)); } if self.interact_frame() || self.interact_armor_stand() @@ -2256,7 +2280,7 @@ impl Game<'_> { || self.interact_mob()? || self.interact_knot() { - return Ok(()); + return Ok(Some(Hand::Main)); } // An EntityHitResult may fall through to Item.use, never to useItemOn. let block_hit = if self.entity_targeted() { @@ -2264,59 +2288,72 @@ impl Game<'_> { } else { self.pick() }; + for hand in Hand::BOTH { + if self.with_hand(hand, |game| game.use_hand(block_hit.as_ref()))? { + return Ok(Some(hand)); + } + } + Ok(None) + } + /// One hand's turn in `startUseItem`: `useItemOn` the block aimed at, + /// then `useItem`. Whether the click ends here (it acted or failed). + fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result { + // isSecondaryUseActive with something in either hand keeps blocks + // from reacting. let sneaking = self.keys.contains(&KeyCode::ShiftLeft); - let mut anchor_passed = None; - // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. - if !(sneaking && self.held().is_some()) - && let Some(hit) = block_hit.as_ref() + let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); + let mut anchor_passed = false; + // MultiPlayerGameMode.useItemOn: blocks react first. + if !(sneaking && hands_full) + && let Some(hit) = block_hit { let held = self.held().cloned(); if self.use_lectern(hit.pos, held.as_ref()) { self.swing_arm(); - return Ok(()); + return Ok(true); } if self.use_jukebox(hit.pos, held.as_ref()) { self.swing_arm(); - return Ok(()); + return Ok(true); } if self.use_composter(hit.pos, held.as_ref()) { self.swing_arm(); - return Ok(()); + return Ok(true); } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); - return Ok(()); + return Ok(true); } // The main hand passes; its item is used, then the off hand's glowstone. - respawn_anchor::AnchorUse::Pass => anchor_passed = Some(hit.pos), + respawn_anchor::AnchorUse::Pass => anchor_passed = true, respawn_anchor::AnchorUse::Other => {} } - let face = match hit.face { - [0, 1, 0] => Direction::Up, - [0, -1, 0] => Direction::Down, - [0, 0, -1] => Direction::North, - [0, 0, 1] => Direction::South, - [-1, 0, 0] => Direction::West, - _ => Direction::East, - }; - let player = PlayerContext { - yaw: self.yaw, - pitch: self.pitch, - may_build: self.may_build(), - can_eat: self.creative - || self - .player - .as_ref() - .is_some_and(|p| p.health.food.food < 20), - game_master: false, - }; - let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); - let item = held.as_ref().map(|s| s.item.to_string()); - let result = if anchor_passed.is_some() { - horizon_world::level::InteractionResult::Pass - } else { - self.with_level(|b, level, ticks| { + // TRY_WITH_EMPTY_HAND: only the main hand's turn uses the block + // itself (useWithoutItem). + if !anchor_passed && self.hand == Hand::Main { + let face = match hit.face { + [0, 1, 0] => Direction::Up, + [0, -1, 0] => Direction::Down, + [0, 0, -1] => Direction::North, + [0, 0, 1] => Direction::South, + [-1, 0, 0] => Direction::West, + _ => Direction::East, + }; + let player = PlayerContext { + yaw: self.yaw, + pitch: self.pitch, + may_build: self.may_build(), + can_eat: self.creative + || self + .player + .as_ref() + .is_some_and(|p| p.health.food.food < 20), + game_master: false, + }; + let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let item = held.as_ref().map(|s| s.item.to_string()); + let result = self.with_level(|b, level, ticks| { b.use_item_on( level, ticks, @@ -2326,29 +2363,22 @@ impl Game<'_> { player, item.as_deref(), ) - }) - }; - self.process_level_events()?; - if result.consumes_action() { - self.swing_arm(); - return Ok(()); + }); + self.process_level_events()?; + if result.consumes_action() { + self.swing_arm(); + return Ok(true); + } } } let Some(stack) = self.held().cloned() else { - // Minecraft.startUseItem goes on to the off hand. - if let Some(pos) = anchor_passed - && self.charge_anchor_from_offhand(pos)? - { - return Ok(()); - } - self.use_offhand(); - return Ok(()); + return Ok(false); }; let Some(info) = self.res.items.get(&stack.item).cloned() else { - return Ok(()); + return Ok(false); }; if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) { - return Ok(()); + return Ok(true); } use horizon_client::first_person::UseResult; let swings = self.swings_started; @@ -2357,18 +2387,18 @@ impl Game<'_> { if (UseResult::Success { swing }).should_swing(swings, self.swings_started) { self.swing_arm(); } - return Ok(()); + return Ok(true); } - UseResult::Fail => return Ok(()), + UseResult::Fail => return Ok(true), UseResult::Pass => {} } if self.use_potion_item(&stack)? || ((block_hit.is_some() || !stack.item.ends_with("_spawn_egg")) && self.throw_item(&stack)?) { - return Ok(()); + return Ok(true); } - if self.raise_shield(self.selected) + if self.raise_shield(self.held_slot()) || self.use_fishing_rod(&stack) || self.use_crossbow(&stack) || self.use_trident(&stack) @@ -2379,29 +2409,29 @@ impl Game<'_> { // placed first (useItemOn before useItem). || (!(info.block.is_some() && block_hit.is_some()) && self.equip_from_hand(&stack)) { - return Ok(()); + return Ok(true); } if &*stack.item == "minecraft:spyglass" { self.use_spyglass(); - return Ok(()); + return Ok(true); } if &*stack.item == "minecraft:bow" { if self.using.is_none() && (self.creative || self.projectile_slot("minecraft:bow").is_some()) { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } - return Ok(()); + return Ok(true); } // Block foods attempt placement before starting consumption. if !(info.block.is_some() && block_hit.is_some()) && self.start_eating(&info) { - return Ok(()); + return Ok(true); } // BoatItem.use also performs its own fluid/block raycast. if self.place_boat(&stack) { - return Ok(()); + return Ok(true); } - if let Some(hit) = block_hit.as_ref() + if let Some(hit) = block_hit && (self.launch_firework(hit, &stack) || self.place_minecart(hit, &stack) || self.place_painting(hit, &stack) @@ -2409,28 +2439,20 @@ impl Game<'_> { || self.place_armor_stand(hit, &stack) || self.place_end_crystal(hit, &stack)) { - return Ok(()); + return Ok(true); } if self.use_ender_eye(&stack, block_hit.is_some())? { - return Ok(()); + return Ok(true); } let Some(hit) = block_hit else { - self.use_offhand(); - return Ok(()); + return Ok(false); }; if info.block.is_none() { - if let Some(pos) = anchor_passed - && self.charge_anchor_from_offhand(pos)? - { - return Ok(()); - } - self.use_offhand(); - return Ok(()); + return Ok(false); } if !self.may_build() { // ItemStack.useOn passes in adventure mode; useItem eats. - self.start_eating(&info); - return Ok(()); + return Ok(self.start_eating(&info)); } let face = match hit.face { [0, 1, 0] => Direction::Up, @@ -2460,7 +2482,7 @@ impl Game<'_> { if self.start_eating(&info) { self.stats.add("used", &stack.item, 1); } - return Ok(()); + return Ok(true); }; let target = [pos.x, pos.y, pos.z]; if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { @@ -2497,9 +2519,9 @@ impl Game<'_> { self.consume_held(); // SolidBucketItem.useOn: BucketItem.getEmptySuccessItem in hand. if solid_bucket && !self.creative { - self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1)); + *self.held_mut() = Some(ItemStack::new("minecraft:bucket", 1)); } - Ok(()) + Ok(true) } /// `Consumable.startConsuming` for held food the player can eat /// (`Player.canEat`): the right click is held for `consume_seconds`. @@ -2514,7 +2536,7 @@ impl Game<'_> { return false; } if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } true } @@ -2522,16 +2544,29 @@ impl Game<'_> { if self.creative { return; } - if let Some(s) = self.inventory[self.selected].as_mut() { + let cell = self.held_mut(); + if let Some(s) = cell.as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *cell = None; } } } fn tick_using(&mut self) { // ItemCooldowns.tick for the shield. self.shield_cooldown = self.shield_cooldown.saturating_sub(1); + let Some((slot, _)) = self.using else { + return; + }; + let hand = if slot == shield::OFFHAND_SLOT { + Hand::Off + } else { + Hand::Main + }; + self.with_hand(hand, Self::tick_used_item); + } + /// `LivingEntity.updatingUsingItem` for the item in use, its hand acting. + fn tick_used_item(&mut self) { let Some((slot, ticks)) = self.using else { return; }; @@ -2542,13 +2577,13 @@ impl Game<'_> { // Switching hotbar slots only ends a main-hand use. let hand_changed = slot != self.selected && slot != shield::OFFHAND_SLOT; if !self.right || hand_changed || self.screen != Screen::Playing { - if &*stack.item == "minecraft:bow" && slot == self.selected { + if &*stack.item == "minecraft:bow" && !hand_changed { self.release_bow(ticks); } if &*stack.item == "minecraft:spyglass" { self.stop_spyglass(); } - if &*stack.item == "minecraft:trident" && slot == self.selected { + if &*stack.item == "minecraft:trident" && !hand_changed { self.release_trident(ticks); } self.using = None; @@ -6479,8 +6514,7 @@ impl Game<'_> { self.0.creative } fn hand(&mut self) -> &mut Option { - let selected = self.0.selected; - &mut self.0.inventory[selected] + self.0.held_mut() } fn add(&mut self, stack: &mut ItemStack) -> bool { let before = stack.count; @@ -6512,7 +6546,7 @@ impl Game<'_> { else { return Ok(false); }; - let Some(held) = self.inventory[self.selected].as_ref() else { + let Some(held) = self.held() else { return Ok(false); }; let removes_dye = cauldron::removes_dye(&self.res.items, &held.item); @@ -6659,19 +6693,23 @@ impl Game<'_> { if self.creative { return; } - let amount = match self.inventory[self.selected].clone() { + let amount = match self.held().cloned() { Some(held) => self.durability_loss(&held, amount), None => amount, }; - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 + let max = self + .held() + .and_then(|s| self.res.items.get(&s.item)) + .map_or(0, |i| i.max_damage); + let cell = self.held_mut(); + if let Some(stack) = cell.as_mut() + && max > 0 { stack.damage += amount; - if stack.damage >= info.max_damage { + if stack.damage >= max { let broken = stack.item.clone(); + *cell = None; self.stats.add("broken", &broken, 1); - self.inventory[self.selected] = None; if let Some(eye) = self.eye_position() { self.audio.play( "minecraft:entity.item.break", @@ -6751,8 +6789,8 @@ impl Game<'_> { damage: 0, extra: None, }; - if self.inventory[self.selected].is_none() { - self.inventory[self.selected] = Some(filled); + if self.held().is_none() { + *self.held_mut() = Some(filled); } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { @@ -6806,7 +6844,7 @@ impl Game<'_> { } self.trigger_block("minecraft:placed_block", target, stack); if !self.creative { - self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1)); + *self.held_mut() = Some(ItemStack::new("minecraft:bucket", 1)); } return Ok(UseResult::Success { swing: true }); } @@ -7140,7 +7178,7 @@ impl Game<'_> { // FirstPersonHandsAndItemsRenderer: the swing of the hand that // swings, and its inverse arm height (the swap scale is 1 for every // item but spears). - let attack = if self.swing.attack_hand() == horizon_client::first_person::Hand::Main { + let attack = if self.swing.attack_hand() == Hand::Main { self.swing.animation(a) } else { 0.0 @@ -9597,6 +9635,7 @@ pub fn run() -> Result<()> { title: None, armor: [None, None, None, None], offhand: None, + hand: Hand::Main, shield_cooldown: 0, command_source: None, titles: Default::default(), diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 94e9422ed..78eb22330 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -565,9 +565,9 @@ impl Game<'_> { held.count -= 1; if held.count == 0 { // The worn piece comes back to the hand. - self.inventory[self.selected] = current; + *self.held_mut() = current; } else { - self.inventory[self.selected] = Some(held); + *self.held_mut() = Some(held); if let Some(old) = current && let Some(rest) = self.give(old) && let Some(eye) = self.eye_position() diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 7bf687899..3904ab465 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -59,7 +59,7 @@ impl Game<'_> { pages.push(String::new()); } BookScreen::Edit { - slot: self.selected, + slot: self.held_slot(), pages, page: 0, signing: false, @@ -104,7 +104,7 @@ impl Game<'_> { while pages.len() > 1 && pages.last().is_some_and(String::is_empty) { pages.pop(); } - if let Some(stack) = self.inventory.get_mut(slot).and_then(Option::as_mut) + if let Some(stack) = self.stack_in_mut(slot).as_mut() && &*stack.item == "minecraft:writable_book" { if sign { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f9f102e93..a10afba96 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2569,11 +2569,11 @@ impl Game<'_> { self.audio.play(sound, Some(eye), 0.5, pitch); self.swing_arm(); if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } Ok(true) @@ -2615,11 +2615,11 @@ impl Game<'_> { } self.swing_arm(); if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } Ok(true) diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index 4a62aa194..70ccba8d3 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -88,7 +88,7 @@ impl Game<'_> { } else if (self.projectile_slot(CROSSBOW).is_some() || self.creative) && self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } true } @@ -135,7 +135,7 @@ impl Game<'_> { let drawn = (0..shots) .map(|i| horizon_client::arrows::drawn_ammo(&ammo, self.creative || i > 0)) .collect(); - if let Some(bow) = self.inventory[slot].as_mut() { + if let Some(bow) = self.stack_in_mut(slot).as_mut() { bow.data_mut().charged = drawn; } let pitch = 1.0 / (self.world.random.next_float() * 0.5 + 1.0) + 0.2; @@ -147,7 +147,7 @@ impl Game<'_> { let Some(eye) = self.eye_position() else { return; }; - let Some(bow) = self.inventory[self.selected].as_mut() else { + let Some(bow) = self.held_mut().as_mut() else { return; }; let charged = std::mem::take(&mut bow.data_mut().charged); diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index f8440f06e..0d8043ecc 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -514,9 +514,15 @@ impl Game<'_> { } self.using = None; self.inventory[self.selected] = stack.clone(); - let used_before = stack - .as_ref() - .map_or(0, |s| self.stats.get("used", &s.item)); + self.offhand = parse_stack(op["offhand"].as_str().unwrap_or("-"))?; + // The used statistic of each item held, once. + let mut items: Vec<_> = [stack.as_ref(), self.offhand.as_ref()] + .into_iter() + .flatten() + .map(|s| s.item.clone()) + .collect(); + items.dedup(); + let used_before: Vec<_> = items.iter().map(|i| self.stats.get("used", i)).collect(); self.forced_hit = Some(super::Hit { pos: [pos.x, pos.y, pos.z], face: [0, 1, 0], @@ -542,10 +548,10 @@ impl Game<'_> { out.push(format!("msg {key}")); } } - if let Some(s) = &stack { - let used = self.stats.get("used", &s.item) - used_before; + for (item, before) in items.iter().zip(used_before) { + let used = self.stats.get("used", item) - before; if used != 0 { - out.push(format!("stat {} minecraft:used {used}", s.item)); + out.push(format!("stat {item} minecraft:used {used}")); } } let using = self @@ -553,8 +559,9 @@ impl Game<'_> { .and_then(|(slot, _)| self.stack_in(slot)) .map_or("-".to_owned(), |s| s.item.to_string()); out.push(format!( - "held {} using {using}", - canon_stack(self.inventory[self.selected].as_ref()) + "held {} offhand {} using {using}", + canon_stack(self.inventory[self.selected].as_ref()), + canon_stack(self.offhand.as_ref()) )); out.push(match self.respawn_config { Some(c) => format!( @@ -568,6 +575,7 @@ impl Game<'_> { }); self.player = None; self.using = None; + self.offhand = None; Ok(out) } diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 102248861..778c0f0a2 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -146,7 +146,7 @@ impl Game<'_> { /// `SpyglassItem.use`: start scoping. pub(super) fn use_spyglass(&mut self) { if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); let at = self.eye_position(); self.audio.play("minecraft:item.spyglass.use", at, 1.0, 1.0); } diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index ec5123424..1c657d36e 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -42,9 +42,9 @@ impl Game<'_> { self.swings_started += 1; } } - /// `swing(InteractionHand.MAIN_HAND)` with the default animation. + /// `swing(hand)` for the hand that acts, with the default animation. pub(super) fn swing_arm(&mut self) { - self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + self.swing_hand(self.hand, SwingAnimation::DEFAULT); } /// `Player.resetAttackStrengthTicker`. pub(super) fn reset_attack_strength(&mut self) { @@ -166,18 +166,23 @@ impl Game<'_> { if self.clicks.destroying.active || self.hands_busy() { return Ok(()); } - let before = self.held().cloned(); + let before = [self.stack_in(self.selected).cloned(), self.offhand.clone()]; let swings = self.swings_started; let using = self.using.is_some(); - self.use_item()?; + let Some(hand) = self.use_item()? else { + return Ok(()); + }; + let (before, after) = match hand { + Hand::Main => (&before[0], self.stack_in(self.selected).cloned()), + Hand::Off => (&before[1], self.offhand.clone()), + }; let swung = self.swings_started != swings; - let after = self.held().cloned(); - let spent = match (&before, &after) { + let spent = match (before, &after) { (Some(a), Some(b)) => a.count != b.count || a.item != b.item || self.creative, _ => false, }; if (swung && spent) || (!using && self.using.is_some() && after.is_some()) { - self.heights.item_used(Hand::Main); + self.heights.item_used(hand); } Ok(()) } diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 3da532a31..e2d4617fc 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -482,7 +482,7 @@ impl Game<'_> { if self.creative { self.give_or_drop_stack(filled); } else if stack.count == 1 { - self.inventory[self.selected] = Some(filled); + *self.held_mut() = Some(filled); } else { self.consume_held(); self.give_or_drop_stack(filled); diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 683e57c9e..826480bd6 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -89,7 +89,7 @@ impl Game<'_> { match &*stack.item { "minecraft:potion" | "minecraft:ominous_bottle" => { if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } Ok(true) } @@ -177,8 +177,8 @@ impl Game<'_> { return; } self.consume_held(); - if self.inventory[self.selected].is_none() { - self.inventory[self.selected] = Some(filled); + if self.held().is_none() { + *self.held_mut() = Some(filled); } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { @@ -218,15 +218,15 @@ impl Game<'_> { self.apply_effect_action(a); } if !self.creative { - if let Some(s) = self.inventory[slot].as_mut() { + if let Some(s) = self.stack_in_mut(slot).as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[slot] = None; + *self.stack_in_mut(slot) = None; } } let bottle = ItemStack::new("minecraft:glass_bottle", 1); - if self.inventory[slot].is_none() { - self.inventory[slot] = Some(bottle); + if self.stack_in(slot).is_none() { + *self.stack_in_mut(slot) = Some(bottle); } else if let Some(rest) = self.give(bottle) { self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); } diff --git a/crates/horizon-client/src/game/powder_snow.rs b/crates/horizon-client/src/game/powder_snow.rs index 091114131..7d0a7770d 100644 --- a/crates/horizon-client/src/game/powder_snow.rs +++ b/crates/horizon-client/src/game/powder_snow.rs @@ -119,7 +119,7 @@ impl Game<'_> { } return; } - let held = &mut self.inventory[self.selected]; + let held = self.held_mut(); let last = held.as_ref().is_none_or(|s| s.count <= 1); if last { *held = Some(filled); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 1f1fa3507..9e73d790c 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -1224,11 +1224,11 @@ impl Game<'_> { self.audio .play("minecraft:item.ominous_bottle.dispose", Some(eye), 1.0, 1.0); if !self.creative - && let Some(s) = self.inventory[slot].as_mut() + && let Some(s) = self.stack_in_mut(slot).as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[slot] = None; + *self.stack_in_mut(slot) = None; } } } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index f2f21469f..834d1ad44 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -4,6 +4,7 @@ //! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`), //! using a charge. use super::{Dim, Game}; +use horizon_client::first_person::Hand; use horizon_client::{ Result, blocks::Fluid, @@ -104,7 +105,7 @@ impl Game<'_> { .play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0); Ok(()) } - /// `RespawnAnchorBlock.useItemOn` with `held` in the main hand. + /// `RespawnAnchorBlock.useItemOn` with `held` in the hand that acts. pub(super) fn use_respawn_anchor( &mut self, pos: [i32; 3], @@ -126,37 +127,11 @@ impl Game<'_> { } return Ok(AnchorUse::Charged); } - if fuel(self.offhand.as_ref()) && chargeable { + if self.hand == Hand::Main && fuel(self.offhand.as_ref()) && chargeable { return Ok(AnchorUse::Pass); } Ok(AnchorUse::Other) } - /// The off hand's glowstone on an anchor the main hand passed on. - pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result { - let state = self.world.block(pos[0], pos[1], pos[2]); - let fuel = self - .offhand - .as_ref() - .is_some_and(|s| &*s.item == "minecraft:glowstone"); - if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 { - return Ok(false); - } - let used = self.offhand.clone(); - self.charge_anchor(pos, state, Some(Who::Player))?; - if !self.creative - && let Some(s) = self.offhand.as_mut() - { - s.count -= 1; - if s.count == 0 { - self.offhand = None; - } - } - if let Some(stack) = used { - self.trigger_block("minecraft:item_used_on_block", pos, &stack); - } - self.swing_arm(); - Ok(true) - } /// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the /// Nether it explodes; inside, it becomes the respawn point. pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> { diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index 331257407..733dae55f 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -47,10 +47,6 @@ impl Game<'_> { } true } - /// Main-hand use fell through: try the off hand (Minecraft.startUseItem). - pub(super) fn use_offhand(&mut self) -> bool { - self.raise_shield(OFFHAND_SLOT) - } /// `LivingEntity.getItemBlockingWith` and the inputs of `applyItemBlocking` /// for an attack from `from` (`DamageSource.getSourcePosition`). pub(super) fn player_blocking( diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index aef884601..179ade374 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -78,7 +78,7 @@ impl Game<'_> { return true; } if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } true } @@ -99,7 +99,7 @@ impl Game<'_> { if ticks < 10 { return; } - let Some(stack) = self.inventory[self.selected].clone() else { + let Some(stack) = self.held().cloned() else { return; }; let Some(eye) = self.eye_position() else { @@ -134,13 +134,13 @@ impl Game<'_> { } // hurtWithoutBreaking, then the thrown copy. if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.damage += 1; } - let thrown = self.inventory[self.selected].clone().unwrap_or(stack); + let thrown = self.held().cloned().unwrap_or(stack); if !self.creative { - self.inventory[self.selected] = None; + *self.held_mut() = None; } let start = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); let mut projectile = horizon_client::projectiles::Projectile::new( diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 105e27984..9dae29564 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -71,11 +71,11 @@ impl Game<'_> { self.stats.add("used", "minecraft:wind_charge", 1); self.swing_arm(); if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } Ok(true) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 4115c9063..19779739b 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -470,7 +470,7 @@ public final class VanillaDispenserOracle { static final class Clicker extends net.minecraft.server.level.ServerPlayer { VanillaBlockUpdateOracle.World world; boolean creative, sneaking; - ItemStack hand; + ItemStack hand, offhand; List stats; String using; Clicker() { @@ -485,12 +485,14 @@ public final class VanillaDispenserOracle { @Override public boolean isDescending() { return sneaking; } @Override public EntityType getType() { return EntityTypes.PLAYER; } @Override public net.minecraft.core.Holder> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); } - @Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; } + @Override public ItemStack getItemBySlot(EquipmentSlot slot) { + return slot == EquipmentSlot.MAINHAND ? hand : slot == EquipmentSlot.OFFHAND ? offhand : ItemStack.EMPTY; + } @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) { - return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY; + return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : offhand; } @Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) { - if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack; + if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack; else offhand = stack; } @Override public void startUsingItem(net.minecraft.world.InteractionHand h) { using = BuiltInRegistries.ITEM.getKey(getItemInHand(h).getItem()).toString(); @@ -515,9 +517,9 @@ public final class VanillaDispenserOracle { * A right click on the top of the block at `pos` (`ServerPlayerGameMode.useItemOn` * of the real game mode, survival or creative): the block's `useItemOn` and * `useWithoutItem`, then the item's `useOn` (`BlockItem.place`, falling back - * to eating a consumable), and `useItem` when that passes, as - * `Minecraft.startUseItem` goes on to. The statistics, the held stack and - * the item the player started using follow. + * to eating a consumable), and `useItem` when that passes, for the main + * hand and then the off hand, as `Minecraft.startUseItem` goes on to. The + * statistics, the held stacks and the item the player started using follow. */ static List useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception { if (VanillaBlockUpdateOracle.Server.players == null) { @@ -528,6 +530,7 @@ public final class VanillaDispenserOracle { player.creative = use.get("creative").getAsBoolean(); player.sneaking = use.get("sneaking").getAsBoolean(); player.hand = stack(use.get("item").getAsString()); + player.offhand = use.has("offhand") ? stack(use.get("offhand").getAsString()) : ItemStack.EMPTY; player.stats = new ArrayList<>(); var abilities = new net.minecraft.world.entity.player.Abilities(); abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative; @@ -556,16 +559,18 @@ public final class VanillaDispenserOracle { player.creative ? net.minecraft.world.level.GameType.CREATIVE : net.minecraft.world.level.GameType.SURVIVAL); var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0), net.minecraft.core.Direction.UP, pos, false); - var hand = net.minecraft.world.InteractionHand.MAIN_HAND; - var result = gameMode.useItemOn(player, w, player.getItemInHand(hand), hand, hit); - // Minecraft.startUseItem: a click on a block that neither succeeded nor - // failed goes on to use the item in the same hand. - if (!(result instanceof net.minecraft.world.InteractionResult.Success) - && !(result instanceof net.minecraft.world.InteractionResult.Fail) && !player.hand.isEmpty()) { - gameMode.useItem(player, w, player.getItemInHand(hand), hand); + // Minecraft.startUseItem: each hand in turn clicks the block, then uses + // its item unless the click succeeded or failed; a success ends it. + for (var hand : net.minecraft.world.InteractionHand.values()) { + ItemStack held = player.getItemInHand(hand); + var result = gameMode.useItemOn(player, w, held, hand, hit); + if (result instanceof net.minecraft.world.InteractionResult.Success + || result instanceof net.minecraft.world.InteractionResult.Fail) break; + if (!held.isEmpty() && gameMode.useItem(player, w, held, hand) instanceof net.minecraft.world.InteractionResult.Success) break; } List out = new ArrayList<>(player.stats); - out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using)); + out.add("held " + ParityData.canon(player.hand) + " offhand " + ParityData.canon(player.offhand) + + " using " + (player.using == null ? "-" : player.using)); var respawn = player.getRespawnConfig(); out.add("respawn " + (respawn == null ? "-" : respawn.respawnData().dimension().identifier() + " " + VanillaBlockUpdateOracle.pos(respawn.respawnData().pos()))); return out; diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index 5b3c40971..0fd360e76 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -6,7 +6,9 @@ for beds in the Nether and the End. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who -right-clicks the top face of the origin holding an item. Vanilla runs the real +right-clicks the top face of the origin holding an item, sometimes with +another (or nothing) in the main hand and the item in the off hand, the +main hand trying first. Vanilla runs the real `ServerPlayerGameMode.useItemOn` over the headless level of the dispenser harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and `useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` @@ -26,6 +28,7 @@ or fall apart (`AbstractBedBlock.useWithoutItem` under the dimension's (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level events, sounds, game events, the used statistic, the held stack, the item the player started using, spawners' next spawn data, potentials and delay, the +off hand's stack, player's respawn point, system messages and the level random afterwards. """ import json @@ -144,6 +147,9 @@ def anchor_case(rng, states, case): 'distance': 3 if nether else 12} if rng.random() < 0.3: use['respawn'] = rng.choice([[0, 0, 0], [5, 0, 5]]) + if rng.random() < 0.4: + # Glowstone in the off hand: the main hand passes it on (PASS). + use['offhand'] = d_plain(rng.choice(['glowstone', 'glowstone', 'apple']), rng.choice([1, 16])) if rng.random() < 0.2: case['rules'] = {'block_explosion_drop_decay': False} case['use_item'] = use @@ -206,6 +212,10 @@ def cases(facts, count, seed): held = '-' if item == '-' else d.plain(item, rng.choice([1, 1, 2, 16, 64])) case['use_item'] = {'item': held, 'creative': rng.random() < 0.2, 'sneaking': rng.random() < 0.2, 'food': rng.choice([20, 20, 19, 10, 0])} + if rng.random() < 0.3: + # The item in the off hand, something else or nothing in the main hand. + main = rng.choice(['-', '-', 'stick', 'apple', 'stone', 'bone_meal', 'shield']) + case['use_item'].update(offhand=held, item='-' if main == '-' else d.plain(main, rng.choice([1, 16]))) case['cells'] = cells case['items'] = [] case['mode'] = 'dispense'