diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index acb0f182d..0e160f135 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -21,6 +21,7 @@ mod remote;
mod render_control;
mod render_tick;
mod screens;
+mod shield;
mod sign_edit;
mod station_control;
mod stations;
@@ -472,6 +473,10 @@ struct Game<'a> {
title: Option
,
/// Armor slots: head, chest, legs, feet.
armor: [Option; 4],
+ /// The off hand (Inventory slot 40, saved as slot 150; menu slot 504 here).
+ offhand: Option,
+ /// The shield's item cooldown after an axe disabled it (ticks).
+ shield_cooldown: u32,
applied_modifiers: Vec<(String, String)>,
experience: Experience,
orbs: Vec,
@@ -1420,6 +1425,7 @@ impl Game<'_> {
}
}
let Some(stack) = self.held().cloned() else {
+ self.use_offhand();
return Ok(());
};
let Some(info) = self.res.items.get(&stack.item).cloned() else {
@@ -1428,6 +1434,9 @@ impl Game<'_> {
if self.use_potion_item(&stack)? || self.throw_item(&stack)? {
return Ok(());
}
+ if self.raise_shield(self.selected) {
+ return Ok(());
+ }
if &*stack.item == "minecraft:spyglass" {
self.use_spyglass();
return Ok(());
@@ -1461,6 +1470,7 @@ impl Game<'_> {
return Ok(());
};
if info.block.is_none() {
+ self.use_offhand();
return Ok(());
}
let face = match hit.face {
@@ -1527,14 +1537,18 @@ impl Game<'_> {
}
}
fn tick_using(&mut self) {
+ // ItemCooldowns.tick for the shield.
+ self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
let Some((slot, ticks)) = self.using else {
return;
};
- let Some(stack) = self.inventory[slot].clone() else {
+ let Some(stack) = self.stack_in(slot).cloned() else {
self.using = None;
return;
};
- if !self.right || slot != self.selected || self.screen != Screen::Playing {
+ // 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 {
self.release_bow(ticks);
}
@@ -1548,6 +1562,11 @@ impl Game<'_> {
self.using = None;
return;
};
+ if info.blocks_attacks.is_some() {
+ // ShieldItem: used for 72000 ticks, i.e. until released.
+ self.using = Some((slot, ticks + 1));
+ return;
+ }
if self.tick_drinking(slot, ticks, &stack) {
return;
}
@@ -1895,6 +1914,18 @@ impl Game<'_> {
};
self.previous_position = player.position;
player.yaw = self.yaw;
+ // LocalPlayer.modifyInput: walking while using an item.
+ player.item_use_speed = self
+ .using
+ .and_then(|(slot, _)| {
+ if slot == shield::OFFHAND_SLOT {
+ self.offhand.as_ref()
+ } else {
+ self.inventory.get(slot)?.as_ref()
+ }
+ })
+ .and_then(|s| self.res.items.get(&s.item))
+ .map(|i| i.use_speed);
MotionWorld {
player,
scene: &mut self.world,
@@ -1976,8 +2007,12 @@ impl Game<'_> {
];
self.death_message();
if !self.creative && !self.ui.rules.bool("keep_inventory") {
- let stacks: Vec =
+ // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40).
+ let mut stacks: Vec =
self.inventory.iter_mut().filter_map(Option::take).collect();
+ stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take));
+ stacks.extend(self.offhand.take());
+ self.apply_equipment();
for stack in stacks {
let r = &mut self.world.random;
let strength = f64::from(r.next_float()) * 0.5;
@@ -2339,6 +2374,16 @@ impl Game<'_> {
h - 23.0,
);
}
+ // Hud.extractItemHotbar: the off hand left of the hotbar (right-handed).
+ if let Some(stack) = self.offhand.clone() {
+ batch.sprite(
+ &self.res.atlas,
+ "gui/sprites/hud/hotbar_offhand_left",
+ w / 2.0 - 91.0 - 29.0,
+ h - 23.0,
+ );
+ self.draw_item(&mut batch, &stack, w / 2.0 - 91.0 - 26.0, h - 19.0);
+ }
for i in 0..9 {
if let Some(stack) = self.inventory[i].clone() {
self.draw_item(
@@ -2558,7 +2603,7 @@ impl Game<'_> {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
v.push(200);
if self.craft_size == 2 {
- v.extend(500..504);
+ v.extend(500..505);
}
}
}
@@ -2586,6 +2631,8 @@ impl Game<'_> {
84.0 + shift + ((i - 9) / 9) as f32 * 18.0,
),
500..504 => (8.0, 8.0 + (i - 500) as f32 * 18.0),
+ // InventoryMenu: the shield slot.
+ 504 => (77.0, 62.0),
300..500 => match self.container_kind() {
Some(BlockEntity::Furnace(_)) => {
[(56.0, 17.0), (56.0, 53.0), (116.0, 35.0)][(i - 300).min(2)]
@@ -2627,6 +2674,9 @@ impl Game<'_> {
if (500..504).contains(&i) {
return &mut self.armor[i - 500];
}
+ if i == 504 {
+ return &mut self.offhand;
+ }
if i >= 300 {
let key = self.container;
return match key.and_then(|k| self.world.block_entities.get_mut(&k)) {
@@ -2795,6 +2845,14 @@ impl Game<'_> {
}
for i in self.slots() {
let (sx, sy) = self.slot_position(i);
+ if i == 504 && self.offhand.is_none() {
+ batch.sprite(
+ &self.res.atlas,
+ "gui/sprites/container/slot/shield",
+ ox + sx,
+ oy + sy,
+ );
+ }
if (500..504).contains(&i) && self.armor[i - 500].is_none() {
let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500];
batch.sprite(
@@ -3988,6 +4046,7 @@ impl Game<'_> {
self.creative = level.creative;
let mut inventory = vec![None; 36];
self.armor = [None, None, None, None];
+ self.offhand = None;
for (slot, id, count, damage) in &level.inventory {
let stack = ItemStack {
item: Arc::from(id.as_str()),
@@ -3997,6 +4056,8 @@ impl Game<'_> {
};
if (100..104).contains(slot) {
self.armor[usize::from(103 - slot)] = Some(stack);
+ } else if *slot == 150 {
+ self.offhand = Some(stack);
} else if let Some(cell) = inventory.get_mut(usize::from(*slot)) {
*cell = Some(stack);
}
@@ -5915,6 +5976,14 @@ impl Game<'_> {
.enumerate()
.filter_map(|(i, s)| Some((i as u8, s.as_ref()?.extra.clone()?)))
.collect();
+ if let Some(s) = &self.offhand {
+ level
+ .inventory
+ .push((150, s.item.to_string(), s.count, s.damage));
+ if let Some(extra) = s.extra.clone() {
+ level.inventory_components.insert(150, extra);
+ }
+ }
// Vanilla stores armor in slots 100 (feet) to 103 (head).
for (i, s) in self.armor.iter().enumerate() {
if let Some(s) = s {
@@ -6155,6 +6224,11 @@ impl Game<'_> {
_ => {}
},
KeyCode::F3 => self.debug = !self.debug,
+ // key.swapOffhand: ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND.
+ KeyCode::KeyF if self.screen == Screen::Playing => {
+ std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]);
+ self.using = None;
+ }
KeyCode::KeyQ if self.screen == Screen::Playing => {
let all = self.keys.contains(&KeyCode::ControlLeft);
self.drop_held(all);
@@ -6870,6 +6944,8 @@ pub fn run() -> Result<()> {
frame_ticks: 0.0,
title: None,
armor: [None, None, None, None],
+ offhand: None,
+ shield_cooldown: 0,
applied_modifiers: Vec::new(),
experience: Experience::default(),
orbs: Vec::new(),
diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs
index 827c3caca..2ce9251e7 100644
--- a/crates/horizon-client/src/game/control.rs
+++ b/crates/horizon-client/src/game/control.rs
@@ -466,6 +466,7 @@ impl Game<'_> {
"target": target,
"selected": self.selected + 1,
"held": self.held().map(|s| json!({ "item": &*s.item, "count": s.count })),
+ "offhand": self.offhand.as_ref().map(|s| json!({ "item": &*s.item, "count": s.count, "damage": s.damage })),
"keys": self.keys.iter().map(|k| format!("{k:?}")).collect::>(),
"fps": self.fps,
"frames": self.frames,
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index 406e33611..5e091def3 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -815,11 +815,44 @@ impl Game<'_> {
if self.creative {
return;
}
+ let projectile = self
+ .res
+ .stations
+ .enchantments
+ .damage_tags
+ .get("minecraft:is_projectile")
+ .is_some_and(|t| t.contains(damage_type));
+ let blocking = self.player_blocking(Some(from), damage_type, false);
+ let raised = blocking.is_some();
+ // Melee: the attacker stands at `from`.
+ let attacker = (!projectile)
+ .then(|| {
+ self.mobs
+ .iter()
+ .filter(|m| m.alive())
+ .min_by(|a, b| {
+ let d = |m: &horizon_client::mobs::Mob| {
+ (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2)
+ };
+ d(a).total_cmp(&d(b))
+ })
+ .map(|m| m.id)
+ })
+ .flatten();
+ let mut outcome = horizon_client::health::BlockOutcome::default();
if let Some(player) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(damage_type)
- && player
- .hurt(&self.motion.health, self.world.health_rules, id, amount)
- .unwrap_or(false)
+ && let Ok(o) = player.hurt_blocking(
+ &self.motion.health,
+ self.world.health_rules,
+ id,
+ amount,
+ blocking,
+ )
+ && {
+ outcome = o;
+ o.hurt
+ }
{
let (dx, dz) = (player.position.x - from[0], player.position.z - from[2]);
let l = (dx * dx + dz * dz).sqrt().max(1e-4);
@@ -834,6 +867,9 @@ impl Game<'_> {
self.hurt_armor(amount);
self.thorns(from);
}
+ if raised {
+ self.after_block(outcome, amount, attacker, projectile);
+ }
}
/// Poison, wither, hunger and burning applied to the player by mobs.
fn tick_player_effects(&mut self) {
diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs
index 080ad41ff..a40be8a13 100644
--- a/crates/horizon-client/src/game/fov.rs
+++ b/crates/horizon-client/src/game/fov.rs
@@ -16,7 +16,7 @@ impl Game<'_> {
/// `Player.isScoping`: using a spyglass.
pub(super) fn scoping(&self) -> bool {
self.using
- .and_then(|(slot, _)| self.inventory[slot].as_ref())
+ .and_then(|(slot, _)| self.stack_in(slot))
.is_some_and(|s| &*s.item == "minecraft:spyglass")
}
/// `AbstractClientPlayer.getFieldOfViewModifier` (first person).
@@ -26,7 +26,7 @@ impl Game<'_> {
// Movement speed (sprinting, speed and slowness) relative to walking.
modifier *= (p.speed / WALKING_SPEED + 1.0) / 2.0;
if let Some((slot, ticks)) = self.using
- && let Some(stack) = &self.inventory[slot]
+ && let Some(stack) = self.stack_in(slot)
{
match &*stack.item {
"minecraft:bow" => {
diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs
new file mode 100644
index 000000000..d595c4b0b
--- /dev/null
+++ b/crates/horizon-client/src/game/shield.rs
@@ -0,0 +1,220 @@
+//! Shields and other `blocks_attacks` items: raising them (`ShieldItem.use`,
+//! from either hand), `LivingEntity.getItemBlockingWith` and
+//! `applyItemBlocking` inputs, and what follows a block: item damage,
+//! the block sound, attacker knockback (`blockedByItem`) and axes disabling
+//! the shield (`Player.blockUsingItem`, `BlocksAttacks.disable`).
+use super::Game;
+use horizon_client::{
+ health::{BlockOutcome, Blocking},
+ items::ItemStack,
+};
+use horizon_core::random::RandomSource;
+use horizon_world::blocking_rules::{BlockingRules, DamageReduction, ItemDamageFunction};
+
+/// `Inventory.SLOT_OFFHAND`: the `using` slot of an off-hand item.
+pub(super) const OFFHAND_SLOT: usize = 40;
+
+impl Game<'_> {
+ /// The stack in an inventory slot, the off hand at `OFFHAND_SLOT`.
+ pub(super) fn stack_in(&self, slot: usize) -> Option<&ItemStack> {
+ if slot == OFFHAND_SLOT {
+ self.offhand.as_ref()
+ } else {
+ self.inventory.get(slot)?.as_ref()
+ }
+ }
+ fn stack_in_mut(&mut self, slot: usize) -> &mut Option {
+ if slot == OFFHAND_SLOT {
+ &mut self.offhand
+ } else {
+ &mut self.inventory[slot]
+ }
+ }
+ fn blocks_attacks(&self, stack: &ItemStack) -> Option<&horizon_client::items::BlocksAttacks> {
+ self.res.items.get(&stack.item)?.blocks_attacks.as_ref()
+ }
+ /// `ShieldItem.use` (ItemUtils.startUsingInstantly) for the hand at `slot`;
+ /// false when that hand holds no blocking item or it is on cooldown.
+ pub(super) fn raise_shield(&mut self, slot: usize) -> bool {
+ let Some(stack) = self.stack_in(slot) else {
+ return false;
+ };
+ if self.blocks_attacks(stack).is_none() {
+ return false;
+ }
+ if self.shield_cooldown == 0 && self.using.is_none() {
+ self.using = Some((slot, 0));
+ }
+ 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(
+ &self,
+ from: Option<[f64; 3]>,
+ damage_type: &str,
+ pierce: bool,
+ ) -> Option {
+ let (slot, ticks) = self.using?;
+ let component = self.blocks_attacks(self.stack_in(slot)?)?;
+ // BlocksAttacks.blockDelayTicks: Math.round(seconds * 20).
+ if (ticks as i32) < (component.delay_seconds * 20.0).round() as i32 {
+ return None;
+ }
+ let tags = &self.res.stations.enchantments.damage_tags;
+ let matches = |spec: &str| match spec.strip_prefix('#') {
+ Some(tag) => tags.get(tag).is_some_and(|t| t.contains(damage_type)),
+ None => spec == damage_type,
+ };
+ let p = self.player.as_ref()?;
+ let angle = match from {
+ Some(src) => {
+ // calculateViewVector(0, yHeadRot) against the flattened direction.
+ let yaw = (-self.yaw).to_radians();
+ let view = [yaw.sin() as f64, yaw.cos() as f64];
+ let (dx, dz) = (src[0] - p.position.x, src[2] - p.position.z);
+ let len = (dx * dx + dz * dz).sqrt();
+ let to = if len < 1.0e-4 {
+ [0.0, 0.0]
+ } else {
+ [dx / len, dz / len]
+ };
+ (to[0] * view[0] + to[1] * view[1]).acos()
+ }
+ None => f64::from(std::f32::consts::PI),
+ };
+ let (threshold, base, factor) = component.item_damage;
+ Some(Blocking {
+ rules: BlockingRules {
+ delay_seconds: component.delay_seconds,
+ disable_scale: component.disable_scale,
+ reductions: component
+ .reductions
+ .iter()
+ .map(|r| DamageReduction {
+ horizontal_angle: r.horizontal_angle,
+ types: r.types.as_ref().map(|t| t.iter().any(|s| matches(s))),
+ base: r.base,
+ factor: r.factor,
+ })
+ .collect(),
+ item_damage: ItemDamageFunction {
+ threshold,
+ base,
+ factor,
+ },
+ },
+ bypassed: component.bypassed_by.as_deref().is_some_and(matches),
+ pierce,
+ angle,
+ })
+ }
+ /// After a hurt with the shield raised: `hurtBlockingItem`, `onBlocked`
+ /// and, for melee from a mob, `blockUsingItem`.
+ pub(super) fn after_block(
+ &mut self,
+ outcome: BlockOutcome,
+ damage: f32,
+ attacker: Option,
+ projectile: bool,
+ ) {
+ let Some((slot, _)) = self.using else { return };
+ let Some(stack) = self.stack_in(slot).cloned() else {
+ return;
+ };
+ let Some(component) = self.blocks_attacks(&stack).cloned() else {
+ return;
+ };
+ let at = self
+ .player
+ .as_ref()
+ .map(|p| [p.position.x, p.position.y, p.position.z]);
+ if outcome.sound
+ && let Some(sound) = &component.block_sound
+ {
+ let pitch = 0.8 + self.world.random.next_float() * 0.4;
+ self.audio.play(sound, at, 1.0, pitch);
+ }
+ if outcome.blocked <= 0.0 {
+ return;
+ }
+ // ItemDamageFunction.apply, then hurtAndBreak.
+ let (threshold, base, factor) = component.item_damage;
+ let item_damage = if outcome.blocked < threshold {
+ 0
+ } else {
+ (base + factor * outcome.blocked).floor() as i32
+ };
+ if item_damage > 0 && !self.creative {
+ let loss = self.durability_loss(&stack, item_damage as u32);
+ let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
+ let cell = self.stack_in_mut(slot);
+ if let Some(s) = cell.as_mut()
+ && max > 0
+ {
+ s.damage += loss;
+ if s.damage >= max {
+ *cell = None;
+ self.using = None;
+ self.audio.play(
+ "minecraft:item.shield.break",
+ at,
+ 0.8,
+ 0.8 + self.world.random.next_float() * 0.4,
+ );
+ return;
+ }
+ }
+ }
+ if projectile {
+ return;
+ }
+ let Some(id) = attacker else { return };
+ let fully = outcome.blocked >= damage;
+ let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
+ return;
+ };
+ let (mx, mz) = (m.position.x, m.position.z);
+ let disable = m
+ .extra
+ .main_hand
+ .as_deref()
+ .and_then(|item| self.res.items.get(item))
+ .map_or(0.0, |i| i.disable_blocking_seconds);
+ // LivingEntity.blockedByItem: defender.knockback(0.5, defender - attacker),
+ // which moves the defender along -(xd, zd).
+ if !fully && let Some(p) = self.player.as_mut() {
+ let (xd, zd) = (p.position.x - mx, p.position.z - mz);
+ let len = (xd * xd + zd * zd).sqrt();
+ if len >= 1.0e-5 {
+ let (dx, dz) = (xd / len * 0.5, zd / len * 0.5);
+ let v = p.velocity;
+ let y = if p.ground.on_ground {
+ (v.y / 2.0 + 0.5).min(0.4)
+ } else {
+ v.y
+ };
+ p.velocity = horizon_core::geometry::Vec3::new(v.x / 2.0 - dx, y, v.z / 2.0 - dz);
+ }
+ }
+ // BlocksAttacks.disable: item cooldown and stopUsingItem.
+ let ticks = disable * component.disable_scale;
+ let ticks = if ticks > 0.0 {
+ (ticks * 20.0).round() as u32
+ } else {
+ 0
+ };
+ if ticks > 0 {
+ self.shield_cooldown = ticks;
+ self.using = None;
+ if let Some(sound) = &component.disabled_sound {
+ let pitch = 0.8 + self.world.random.next_float() * 0.4;
+ self.audio.play(sound, at, 0.8, pitch);
+ }
+ }
+ }
+}
diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs
index 6941a9222..ec926aa60 100644
--- a/crates/horizon-client/src/health.rs
+++ b/crates/horizon-client/src/health.rs
@@ -217,6 +217,18 @@ impl PlayerMotion {
source: DamageTypeId,
amount: f32,
) -> Result {
+ Ok(self
+ .hurt_blocking(resources, rules, source, amount, None)?
+ .hurt)
+ }
+ pub fn hurt_blocking(
+ &mut self,
+ resources: &HealthResources,
+ rules: HealthRules,
+ source: DamageTypeId,
+ amount: f32,
+ blocking: Option,
+ ) -> Result {
let source = resources
.damage
.source::<()>(source, None, None, None)
@@ -230,15 +242,23 @@ impl PlayerMotion {
sync_velocity: &mut h.sync_velocity,
game_time: h.game_time,
status: self.status.clone(),
+ blocking,
+ blocked: 0.0,
+ block_sound: false,
};
- Ok(ServerPlayerCombat::new(
+ let hurt = ServerPlayerCombat::new(
&mut self.attributes,
&mut h.data,
&mut h.food,
h.ids,
&mut environment,
)?
- .hurt(&mut h.hurt, amount)?)
+ .hurt(&mut h.hurt, amount)?;
+ Ok(BlockOutcome {
+ hurt,
+ blocked: environment.blocked,
+ sound: environment.block_sound,
+ })
}
pub fn set_health(&mut self, value: f32, absorption: bool) -> Result<()> {
let h = &mut self.health;
@@ -267,6 +287,38 @@ pub(crate) struct Environment<'a> {
pub(crate) game_time: i64,
/// Resistance, fire resistance and armor protection (effects.rs).
pub(crate) status: crate::effects::StatusFlags,
+ /// The raised blocking item, if any, and what it blocked.
+ pub(crate) blocking: Option,
+ pub(crate) blocked: f32,
+ pub(crate) block_sound: bool,
+}
+/// `LivingEntity.applyItemBlocking` inputs for a raised `BlocksAttacks` item:
+/// reductions whose damage-type sets are already matched against the source.
+#[derive(Clone, Debug)]
+pub struct Blocking {
+ pub rules: horizon_world::blocking_rules::BlockingRules,
+ /// `bypassed_by` contains the source's damage type.
+ pub bypassed: bool,
+ /// The direct entity is an arrow with piercing.
+ pub pierce: bool,
+ /// Angle between the head's view and the source position (pi without one).
+ pub angle: f64,
+}
+/// The outcome of a hurt with a raised blocking item.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct BlockOutcome {
+ pub hurt: bool,
+ pub blocked: f32,
+ /// `BlocksAttacks.onBlocked` ran (the block sound plays).
+ pub sound: bool,
+}
+struct MatchedSets;
+impl horizon_world::blocking_rules::TypeMatchWorld for MatchedSets {
+ type Error = io::Error;
+ type Set = bool;
+ fn source_in_set(&mut self, set: bool) -> io::Result {
+ Ok(set)
+ }
}
impl Environment<'_> {
fn event(&mut self, event: HealthEvent) {
@@ -442,8 +494,15 @@ impl HurtWorld for Environment<'_> {
fn use_item(&mut self, _: &mut State) -> io::Result<()> {
Ok(())
}
- fn apply_blocking(&mut self, _: &mut State, _: f32) -> io::Result {
- Ok(0.0)
+ fn apply_blocking(&mut self, _: &mut State, damage: f32) -> io::Result {
+ let Some(b) = &self.blocking else {
+ return Ok(0.0);
+ };
+ if damage <= 0.0 || b.bypassed || b.pierce {
+ return Ok(0.0);
+ }
+ self.blocked = b.rules.resolve(&mut MatchedSets, damage, b.angle)?;
+ Ok(self.blocked)
}
fn freeze_hurts_extra(&mut self, _: &mut State) -> io::Result {
Ok(false)
@@ -464,9 +523,10 @@ impl HurtWorld for Environment<'_> {
Ok(())
}
fn blocking_component(&mut self, _: ()) -> Option<()> {
- None
+ self.blocking.as_ref().map(|_| ())
}
fn on_blocked(&mut self, _: &mut State, _: ()) -> io::Result<()> {
+ self.block_sound = true;
Ok(())
}
fn broadcast_damage(&mut self, _: &mut State) -> io::Result<()> {
diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs
index 531bc12b6..0a46c3f34 100644
--- a/crates/horizon-client/src/hunger.rs
+++ b/crates/horizon-client/src/hunger.rs
@@ -135,6 +135,9 @@ impl FoodWorld for TickWorld<'_> {
sync_velocity: self.sync_velocity,
game_time: self.game_time,
status: Default::default(),
+ blocking: None,
+ blocked: 0.0,
+ block_sound: false,
};
ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)?
.hurt(self.hurt, amount)?;
diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs
index 1f76fe295..d415ade86 100644
--- a/crates/horizon-client/src/items.rs
+++ b/crates/horizon-client/src/items.rs
@@ -41,6 +41,86 @@ pub struct ItemInfo {
pub equip_slot: Option,
/// All `attribute_modifiers`: (attribute, id, amount, operation, slot group).
pub modifiers: Vec<(String, String, f64, String, String)>,
+ /// `blocks_attacks` (shields).
+ pub blocks_attacks: Option,
+ /// `weapon.disable_blocking_for_seconds` (axes).
+ pub disable_blocking_seconds: f32,
+ /// `use_effects.speed_multiplier` (UseEffects.DEFAULT: 0.2).
+ pub use_speed: f32,
+}
+/// A reduction of `blocks_attacks.damage_reductions`.
+#[derive(Clone, Debug)]
+pub struct BlockReduction {
+ pub horizontal_angle: f32,
+ /// Damage type ids or `#tags`; None blocks every type.
+ pub types: Option>,
+ pub base: f32,
+ pub factor: f32,
+}
+/// The `blocks_attacks` component.
+#[derive(Clone, Debug)]
+pub struct BlocksAttacks {
+ pub delay_seconds: f32,
+ pub disable_scale: f32,
+ pub reductions: Vec,
+ /// item_damage: (threshold, base, factor)
+ pub item_damage: (f32, f32, f32),
+ pub bypassed_by: Option,
+ pub block_sound: Option,
+ pub disabled_sound: Option,
+}
+impl BlocksAttacks {
+ fn parse(v: &Value) -> Option {
+ if !v.is_object() {
+ return None;
+ }
+ let f = |v: &Value, d: f64| v.as_f64().unwrap_or(d) as f32;
+ let text = |v: &Value| v.as_str().map(str::to_owned);
+ let reductions = match v["damage_reductions"].as_array() {
+ Some(list) => list
+ .iter()
+ .map(|r| BlockReduction {
+ horizontal_angle: f(&r["horizontal_blocking_angle"], 90.0),
+ types: match &r["type"] {
+ Value::String(s) => Some(vec![s.clone()]),
+ Value::Array(a) => Some(
+ a.iter()
+ .filter_map(|t| t.as_str().map(str::to_owned))
+ .collect(),
+ ),
+ _ => None,
+ },
+ base: f(&r["base"], 0.0),
+ factor: f(&r["factor"], 0.0),
+ })
+ .collect(),
+ // BlocksAttacks.CODEC default: block everything within 90 degrees.
+ None => vec![BlockReduction {
+ horizontal_angle: 90.0,
+ types: None,
+ base: 0.0,
+ factor: 1.0,
+ }],
+ };
+ let d = &v["item_damage"];
+ Some(Self {
+ delay_seconds: f(&v["block_delay_seconds"], 0.0),
+ disable_scale: f(&v["disable_cooldown_scale"], 1.0),
+ reductions,
+ item_damage: if d.is_object() {
+ (
+ f(&d["threshold"], 1.0),
+ f(&d["base"], 0.0),
+ f(&d["factor"], 1.0),
+ )
+ } else {
+ (1.0, 0.0, 1.0)
+ },
+ bypassed_by: text(&v["bypassed_by"]),
+ block_sound: text(&v["block_sound"]),
+ disabled_sound: text(&v["disabled_sound"]),
+ })
+ }
}
#[derive(Clone, Debug, PartialEq)]
pub struct ItemStack {
@@ -183,6 +263,13 @@ impl Items {
.as_str()
.unwrap_or(name)
.to_owned(),
+ use_speed: c["minecraft:use_effects"]["speed_multiplier"]
+ .as_f64()
+ .unwrap_or(0.2) as f32,
+ blocks_attacks: BlocksAttacks::parse(&c["minecraft:blocks_attacks"]),
+ disable_blocking_seconds: c["minecraft:weapon"]["disable_blocking_for_seconds"]
+ .as_f64()
+ .unwrap_or(0.0) as f32,
equip_slot: c["minecraft:equippable"]["slot"]
.as_str()
.map(str::to_owned),
diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs
index a86772017..ce2840473 100644
--- a/crates/horizon-client/src/motion.rs
+++ b/crates/horizon-client/src/motion.rs
@@ -145,6 +145,8 @@ pub struct PlayerMotion {
pub pose: crate::pose::Pose,
pub dimensions: crate::pose::Dimensions,
pub speed: f32,
+ /// `LocalPlayer.itemUseSpeedMultiplier` while using an item (not riding).
+ pub item_use_speed: Option,
pub last_climbable: Option,
pub needs_sync: bool,
pub sync_position: bool,
@@ -212,6 +214,7 @@ impl PlayerMotion {
pose: crate::pose::Pose::Standing,
dimensions: crate::pose::Pose::Standing.dimensions(1.0),
speed: 0.0,
+ item_use_speed: None,
last_climbable: None,
needs_sync: false,
sync_position: false,
@@ -467,7 +470,7 @@ impl MotionWorld<'_, '_, '_> {
None
};
self.simulation_tick(
- crate::input::modify_input(direction, None, sneak),
+ crate::input::modify_input(direction, self.player.item_use_speed, sneak),
keys.jump,
)
}